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.

281507 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 <signal.h>
  634. /* Got a build error here? You'll need to install the freetype library...
  635. The name of the package to install is "libfreetype6-dev".
  636. */
  637. #include <ft2build.h>
  638. #include FT_FREETYPE_H
  639. #include <X11/Xlib.h>
  640. #include <X11/Xatom.h>
  641. #include <X11/Xresource.h>
  642. #include <X11/Xutil.h>
  643. #include <X11/Xmd.h>
  644. #include <X11/keysym.h>
  645. #include <X11/cursorfont.h>
  646. #if JUCE_USE_XINERAMA
  647. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  648. #include <X11/extensions/Xinerama.h>
  649. #endif
  650. #if JUCE_USE_XSHM
  651. #include <X11/extensions/XShm.h>
  652. #include <sys/shm.h>
  653. #include <sys/ipc.h>
  654. #endif
  655. #if JUCE_USE_XRENDER
  656. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  657. #include <X11/extensions/Xrender.h>
  658. #include <X11/extensions/Xcomposite.h>
  659. #endif
  660. #if JUCE_USE_XCURSOR
  661. // If you're missing this header, try installing the libxcursor-dev package
  662. #include <X11/Xcursor/Xcursor.h>
  663. #endif
  664. #if JUCE_OPENGL
  665. /* Got an include error here?
  666. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  667. and "freeglut3-dev".
  668. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  669. want to disable it.
  670. */
  671. #include <GL/glx.h>
  672. #endif
  673. #undef KeyPress
  674. #if JUCE_ALSA
  675. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  676. not got your paths set up correctly to find its header files.
  677. The package you need to install to get ASLA support is "libasound2-dev".
  678. If you don't have the ALSA library and don't want to build Juce with audio support,
  679. just disable the JUCE_ALSA flag in juce_Config.h
  680. */
  681. #include <alsa/asoundlib.h>
  682. #endif
  683. #if JUCE_JACK
  684. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  685. installed, or you've not got your paths set up correctly to find its header files.
  686. The package you need to install to get JACK support is "libjack-dev".
  687. If you don't have the jack-audio-connection-kit library and don't want to build
  688. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  689. */
  690. #include <jack/jack.h>
  691. //#include <jack/transport.h>
  692. #endif
  693. #undef SIZEOF
  694. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  695. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  696. #elif JUCE_MAC || JUCE_IOS
  697. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  698. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  699. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  700. #define USE_COREGRAPHICS_RENDERING 1
  701. #if JUCE_IOS
  702. #import <Foundation/Foundation.h>
  703. #import <UIKit/UIKit.h>
  704. #import <AudioToolbox/AudioToolbox.h>
  705. #import <AVFoundation/AVFoundation.h>
  706. #import <CoreData/CoreData.h>
  707. #import <MobileCoreServices/MobileCoreServices.h>
  708. #import <QuartzCore/QuartzCore.h>
  709. #include <sys/fcntl.h>
  710. #if JUCE_OPENGL
  711. #include <OpenGLES/ES1/gl.h>
  712. #include <OpenGLES/ES1/glext.h>
  713. #endif
  714. #else
  715. #import <Cocoa/Cocoa.h>
  716. #import <CoreAudio/HostTime.h>
  717. #if JUCE_BUILD_NATIVE
  718. #import <CoreAudio/AudioHardware.h>
  719. #import <CoreMIDI/MIDIServices.h>
  720. #import <QTKit/QTKit.h>
  721. #import <WebKit/WebKit.h>
  722. #import <DiscRecording/DiscRecording.h>
  723. #import <IOKit/IOKitLib.h>
  724. #import <IOKit/IOCFPlugIn.h>
  725. #import <IOKit/hid/IOHIDLib.h>
  726. #import <IOKit/hid/IOHIDKeys.h>
  727. #import <IOKit/pwr_mgt/IOPMLib.h>
  728. #endif
  729. #if (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU)) \
  730. || ! (defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  731. #include <Carbon/Carbon.h>
  732. #endif
  733. #include <sys/dir.h>
  734. #endif
  735. #include <sys/socket.h>
  736. #include <sys/sysctl.h>
  737. #include <sys/stat.h>
  738. #include <sys/param.h>
  739. #include <sys/mount.h>
  740. #include <fnmatch.h>
  741. #include <utime.h>
  742. #include <dlfcn.h>
  743. #include <ifaddrs.h>
  744. #include <net/if_dl.h>
  745. #include <mach/mach_time.h>
  746. #include <mach-o/dyld.h>
  747. #if MACOS_10_4_OR_EARLIER
  748. #include <GLUT/glut.h>
  749. #endif
  750. #if ! CGFLOAT_DEFINED
  751. #define CGFloat float
  752. #endif
  753. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  754. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  755. #elif JUCE_ANDROID
  756. /*** Start of inlined file: juce_android_NativeIncludes.h ***/
  757. #ifndef __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  758. #define __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  759. #include <jni.h>
  760. #include <pthread.h>
  761. #include <sched.h>
  762. #include <sys/time.h>
  763. #include <utime.h>
  764. #include <errno.h>
  765. #include <fcntl.h>
  766. #include <dlfcn.h>
  767. #include <sys/stat.h>
  768. #include <sys/statfs.h>
  769. #include <sys/ptrace.h>
  770. #include <sys/sysinfo.h>
  771. #include <pwd.h>
  772. #include <dirent.h>
  773. #include <fnmatch.h>
  774. #if JUCE_OPENGL
  775. #include <GLES/gl.h>
  776. #endif
  777. #endif // __JUCE_ANDROID_NATIVEINCLUDES_JUCEHEADER__
  778. /*** End of inlined file: juce_android_NativeIncludes.h ***/
  779. #else
  780. #error "Unknown platform!"
  781. #endif
  782. #endif
  783. //==============================================================================
  784. #define DONT_SET_USING_JUCE_NAMESPACE 1
  785. #undef max
  786. #undef min
  787. #define NO_DUMMY_DECL
  788. #define JUCE_AMALGAMATED_TEMPLATE 1
  789. #if JUCE_BUILD_NATIVE
  790. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  791. #endif
  792. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  793. #pragma warning (disable: 4309 4305)
  794. #endif
  795. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  796. BEGIN_JUCE_NAMESPACE
  797. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  798. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  799. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  800. /**
  801. Creates a floating carbon window that can be used to hold a carbon UI.
  802. This is a handy class that's designed to be inlined where needed, e.g.
  803. in the audio plugin hosting code.
  804. */
  805. class CarbonViewWrapperComponent : public Component,
  806. public ComponentMovementWatcher,
  807. public Timer
  808. {
  809. public:
  810. CarbonViewWrapperComponent()
  811. : ComponentMovementWatcher (this),
  812. wrapperWindow (0),
  813. carbonWindow (0),
  814. embeddedView (0),
  815. recursiveResize (false)
  816. {
  817. }
  818. virtual ~CarbonViewWrapperComponent()
  819. {
  820. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  821. }
  822. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  823. virtual void removeView (HIViewRef embeddedView) = 0;
  824. virtual void mouseDown (int, int) {}
  825. virtual void paint() {}
  826. virtual bool getEmbeddedViewSize (int& w, int& h)
  827. {
  828. if (embeddedView == 0)
  829. return false;
  830. HIRect bounds;
  831. HIViewGetBounds (embeddedView, &bounds);
  832. w = jmax (1, roundToInt (bounds.size.width));
  833. h = jmax (1, roundToInt (bounds.size.height));
  834. return true;
  835. }
  836. void createWindow()
  837. {
  838. if (wrapperWindow == 0)
  839. {
  840. Rect r;
  841. r.left = getScreenX();
  842. r.top = getScreenY();
  843. r.right = r.left + getWidth();
  844. r.bottom = r.top + getHeight();
  845. CreateNewWindow (kDocumentWindowClass,
  846. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  847. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  848. &r, &wrapperWindow);
  849. jassert (wrapperWindow != 0);
  850. if (wrapperWindow == 0)
  851. return;
  852. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  853. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  854. [ownerWindow addChildWindow: carbonWindow
  855. ordered: NSWindowAbove];
  856. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  857. EventTypeSpec windowEventTypes[] =
  858. {
  859. { kEventClassWindow, kEventWindowGetClickActivation },
  860. { kEventClassWindow, kEventWindowHandleDeactivate },
  861. { kEventClassWindow, kEventWindowBoundsChanging },
  862. { kEventClassMouse, kEventMouseDown },
  863. { kEventClassMouse, kEventMouseMoved },
  864. { kEventClassMouse, kEventMouseDragged },
  865. { kEventClassMouse, kEventMouseUp},
  866. { kEventClassWindow, kEventWindowDrawContent },
  867. { kEventClassWindow, kEventWindowShown },
  868. { kEventClassWindow, kEventWindowHidden }
  869. };
  870. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  871. InstallWindowEventHandler (wrapperWindow, upp,
  872. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  873. windowEventTypes, this, &eventHandlerRef);
  874. setOurSizeToEmbeddedViewSize();
  875. setEmbeddedWindowToOurSize();
  876. creationTime = Time::getCurrentTime();
  877. }
  878. }
  879. void deleteWindow()
  880. {
  881. removeView (embeddedView);
  882. embeddedView = 0;
  883. if (wrapperWindow != 0)
  884. {
  885. RemoveEventHandler (eventHandlerRef);
  886. DisposeWindow (wrapperWindow);
  887. wrapperWindow = 0;
  888. }
  889. }
  890. void setOurSizeToEmbeddedViewSize()
  891. {
  892. int w, h;
  893. if (getEmbeddedViewSize (w, h))
  894. {
  895. if (w != getWidth() || h != getHeight())
  896. {
  897. startTimer (50);
  898. setSize (w, h);
  899. if (getParentComponent() != 0)
  900. getParentComponent()->setSize (w, h);
  901. }
  902. else
  903. {
  904. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  905. }
  906. }
  907. else
  908. {
  909. stopTimer();
  910. }
  911. }
  912. void setEmbeddedWindowToOurSize()
  913. {
  914. if (! recursiveResize)
  915. {
  916. recursiveResize = true;
  917. if (embeddedView != 0)
  918. {
  919. HIRect r;
  920. r.origin.x = 0;
  921. r.origin.y = 0;
  922. r.size.width = (float) getWidth();
  923. r.size.height = (float) getHeight();
  924. HIViewSetFrame (embeddedView, &r);
  925. }
  926. if (wrapperWindow != 0)
  927. {
  928. Rect wr;
  929. wr.left = getScreenX();
  930. wr.top = getScreenY();
  931. wr.right = wr.left + getWidth();
  932. wr.bottom = wr.top + getHeight();
  933. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  934. ShowWindow (wrapperWindow);
  935. }
  936. recursiveResize = false;
  937. }
  938. }
  939. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  940. {
  941. setEmbeddedWindowToOurSize();
  942. }
  943. void componentPeerChanged()
  944. {
  945. deleteWindow();
  946. createWindow();
  947. }
  948. void componentVisibilityChanged()
  949. {
  950. if (isShowing())
  951. createWindow();
  952. else
  953. deleteWindow();
  954. setEmbeddedWindowToOurSize();
  955. }
  956. static void recursiveHIViewRepaint (HIViewRef view)
  957. {
  958. HIViewSetNeedsDisplay (view, true);
  959. HIViewRef child = HIViewGetFirstSubview (view);
  960. while (child != 0)
  961. {
  962. recursiveHIViewRepaint (child);
  963. child = HIViewGetNextView (child);
  964. }
  965. }
  966. void timerCallback()
  967. {
  968. setOurSizeToEmbeddedViewSize();
  969. // To avoid strange overpainting problems when the UI is first opened, we'll
  970. // repaint it a few times during the first second that it's on-screen..
  971. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  972. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  973. }
  974. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  975. {
  976. switch (GetEventKind (event))
  977. {
  978. case kEventWindowHandleDeactivate:
  979. ActivateWindow (wrapperWindow, TRUE);
  980. return noErr;
  981. case kEventWindowGetClickActivation:
  982. {
  983. getTopLevelComponent()->toFront (false);
  984. [carbonWindow makeKeyAndOrderFront: nil];
  985. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  986. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  987. sizeof (ClickActivationResult), &howToHandleClick);
  988. HIViewSetNeedsDisplay (embeddedView, true);
  989. return noErr;
  990. }
  991. }
  992. return eventNotHandledErr;
  993. }
  994. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  995. {
  996. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  997. }
  998. protected:
  999. WindowRef wrapperWindow;
  1000. NSWindow* carbonWindow;
  1001. HIViewRef embeddedView;
  1002. bool recursiveResize;
  1003. Time creationTime;
  1004. EventHandlerRef eventHandlerRef;
  1005. };
  1006. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  1007. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  1008. END_JUCE_NAMESPACE
  1009. #endif
  1010. //==============================================================================
  1011. #if JUCE_BUILD_CORE
  1012. /*** Start of inlined file: juce_FileLogger.cpp ***/
  1013. BEGIN_JUCE_NAMESPACE
  1014. FileLogger::FileLogger (const File& logFile_,
  1015. const String& welcomeMessage,
  1016. const int maxInitialFileSizeBytes)
  1017. : logFile (logFile_)
  1018. {
  1019. if (maxInitialFileSizeBytes >= 0)
  1020. trimFileSize (maxInitialFileSizeBytes);
  1021. if (! logFile_.exists())
  1022. {
  1023. // do this so that the parent directories get created..
  1024. logFile_.create();
  1025. }
  1026. String welcome;
  1027. welcome << newLine
  1028. << "**********************************************************" << newLine
  1029. << welcomeMessage << newLine
  1030. << "Log started: " << Time::getCurrentTime().toString (true, true) << newLine;
  1031. logMessage (welcome);
  1032. }
  1033. FileLogger::~FileLogger()
  1034. {
  1035. }
  1036. void FileLogger::logMessage (const String& message)
  1037. {
  1038. DBG (message);
  1039. const ScopedLock sl (logLock);
  1040. FileOutputStream out (logFile, 256);
  1041. out << message << newLine;
  1042. }
  1043. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1044. {
  1045. if (maxFileSizeBytes <= 0)
  1046. {
  1047. logFile.deleteFile();
  1048. }
  1049. else
  1050. {
  1051. const int64 fileSize = logFile.getSize();
  1052. if (fileSize > maxFileSizeBytes)
  1053. {
  1054. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1055. jassert (in != 0);
  1056. if (in != 0)
  1057. {
  1058. in->setPosition (fileSize - maxFileSizeBytes);
  1059. String content;
  1060. {
  1061. MemoryBlock contentToSave;
  1062. contentToSave.setSize (maxFileSizeBytes + 4);
  1063. contentToSave.fillWith (0);
  1064. in->read (contentToSave.getData(), maxFileSizeBytes);
  1065. in = 0;
  1066. content = contentToSave.toString();
  1067. }
  1068. int newStart = 0;
  1069. while (newStart < fileSize
  1070. && content[newStart] != '\n'
  1071. && content[newStart] != '\r')
  1072. ++newStart;
  1073. logFile.deleteFile();
  1074. logFile.appendText (content.substring (newStart), false, false);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1080. const String& logFileName,
  1081. const String& welcomeMessage,
  1082. const int maxInitialFileSizeBytes)
  1083. {
  1084. #if JUCE_MAC
  1085. File logFile ("~/Library/Logs");
  1086. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1087. .getChildFile (logFileName);
  1088. #else
  1089. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1090. if (logFile.isDirectory())
  1091. {
  1092. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1093. .getChildFile (logFileName);
  1094. }
  1095. #endif
  1096. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1097. }
  1098. END_JUCE_NAMESPACE
  1099. /*** End of inlined file: juce_FileLogger.cpp ***/
  1100. /*** Start of inlined file: juce_Logger.cpp ***/
  1101. BEGIN_JUCE_NAMESPACE
  1102. Logger::Logger()
  1103. {
  1104. }
  1105. Logger::~Logger()
  1106. {
  1107. }
  1108. Logger* Logger::currentLogger = 0;
  1109. void Logger::setCurrentLogger (Logger* const newLogger,
  1110. const bool deleteOldLogger)
  1111. {
  1112. Logger* const oldLogger = currentLogger;
  1113. currentLogger = newLogger;
  1114. if (deleteOldLogger)
  1115. delete oldLogger;
  1116. }
  1117. void Logger::writeToLog (const String& message)
  1118. {
  1119. if (currentLogger != 0)
  1120. currentLogger->logMessage (message);
  1121. else
  1122. outputDebugString (message);
  1123. }
  1124. #if JUCE_LOG_ASSERTIONS
  1125. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1126. {
  1127. String m ("JUCE Assertion failure in ");
  1128. m << filename << ", line " << lineNum;
  1129. Logger::writeToLog (m);
  1130. }
  1131. #endif
  1132. END_JUCE_NAMESPACE
  1133. /*** End of inlined file: juce_Logger.cpp ***/
  1134. /*** Start of inlined file: juce_Random.cpp ***/
  1135. BEGIN_JUCE_NAMESPACE
  1136. Random::Random (const int64 seedValue) throw()
  1137. : seed (seedValue)
  1138. {
  1139. }
  1140. Random::~Random() throw()
  1141. {
  1142. }
  1143. void Random::setSeed (const int64 newSeed) throw()
  1144. {
  1145. seed = newSeed;
  1146. }
  1147. void Random::combineSeed (const int64 seedValue) throw()
  1148. {
  1149. seed ^= nextInt64() ^ seedValue;
  1150. }
  1151. void Random::setSeedRandomly()
  1152. {
  1153. combineSeed ((int64) (pointer_sized_int) this);
  1154. combineSeed (Time::getMillisecondCounter());
  1155. combineSeed (Time::getHighResolutionTicks());
  1156. combineSeed (Time::getHighResolutionTicksPerSecond());
  1157. combineSeed (Time::currentTimeMillis());
  1158. }
  1159. int Random::nextInt() throw()
  1160. {
  1161. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1162. return (int) (seed >> 16);
  1163. }
  1164. int Random::nextInt (const int maxValue) throw()
  1165. {
  1166. jassert (maxValue > 0);
  1167. return (nextInt() & 0x7fffffff) % maxValue;
  1168. }
  1169. int64 Random::nextInt64() throw()
  1170. {
  1171. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1172. }
  1173. bool Random::nextBool() throw()
  1174. {
  1175. return (nextInt() & 0x80000000) != 0;
  1176. }
  1177. float Random::nextFloat() throw()
  1178. {
  1179. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1180. }
  1181. double Random::nextDouble() throw()
  1182. {
  1183. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1184. }
  1185. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1186. {
  1187. BigInteger n;
  1188. do
  1189. {
  1190. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1191. }
  1192. while (n >= maximumValue);
  1193. return n;
  1194. }
  1195. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1196. {
  1197. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1198. while ((startBit & 31) != 0 && numBits > 0)
  1199. {
  1200. arrayToChange.setBit (startBit++, nextBool());
  1201. --numBits;
  1202. }
  1203. while (numBits >= 32)
  1204. {
  1205. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1206. startBit += 32;
  1207. numBits -= 32;
  1208. }
  1209. while (--numBits >= 0)
  1210. arrayToChange.setBit (startBit + numBits, nextBool());
  1211. }
  1212. Random& Random::getSystemRandom() throw()
  1213. {
  1214. static Random sysRand (1);
  1215. return sysRand;
  1216. }
  1217. END_JUCE_NAMESPACE
  1218. /*** End of inlined file: juce_Random.cpp ***/
  1219. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1220. BEGIN_JUCE_NAMESPACE
  1221. RelativeTime::RelativeTime (const double seconds_) throw()
  1222. : seconds (seconds_)
  1223. {
  1224. }
  1225. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1226. : seconds (other.seconds)
  1227. {
  1228. }
  1229. RelativeTime::~RelativeTime() throw()
  1230. {
  1231. }
  1232. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1233. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw() { return RelativeTime (milliseconds * 0.001); }
  1234. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw() { return RelativeTime (numberOfMinutes * 60.0); }
  1235. const RelativeTime RelativeTime::hours (const double numberOfHours) throw() { return RelativeTime (numberOfHours * (60.0 * 60.0)); }
  1236. const RelativeTime RelativeTime::days (const double numberOfDays) throw() { return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0)); }
  1237. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw() { return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0)); }
  1238. int64 RelativeTime::inMilliseconds() const throw() { return (int64) (seconds * 1000.0); }
  1239. double RelativeTime::inMinutes() const throw() { return seconds / 60.0; }
  1240. double RelativeTime::inHours() const throw() { return seconds / (60.0 * 60.0); }
  1241. double RelativeTime::inDays() const throw() { return seconds / (60.0 * 60.0 * 24.0); }
  1242. double RelativeTime::inWeeks() const throw() { return seconds / (60.0 * 60.0 * 24.0 * 7.0); }
  1243. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1244. {
  1245. if (seconds < 0.001 && seconds > -0.001)
  1246. return returnValueForZeroTime;
  1247. String result;
  1248. result.preallocateStorage (16);
  1249. if (seconds < 0)
  1250. result << '-';
  1251. int fieldsShown = 0;
  1252. int n = std::abs ((int) inWeeks());
  1253. if (n > 0)
  1254. {
  1255. result << n << (n == 1 ? TRANS(" week ")
  1256. : TRANS(" weeks "));
  1257. ++fieldsShown;
  1258. }
  1259. n = std::abs ((int) inDays()) % 7;
  1260. if (n > 0)
  1261. {
  1262. result << n << (n == 1 ? TRANS(" day ")
  1263. : TRANS(" days "));
  1264. ++fieldsShown;
  1265. }
  1266. if (fieldsShown < 2)
  1267. {
  1268. n = std::abs ((int) inHours()) % 24;
  1269. if (n > 0)
  1270. {
  1271. result << n << (n == 1 ? TRANS(" hr ")
  1272. : TRANS(" hrs "));
  1273. ++fieldsShown;
  1274. }
  1275. if (fieldsShown < 2)
  1276. {
  1277. n = std::abs ((int) inMinutes()) % 60;
  1278. if (n > 0)
  1279. {
  1280. result << n << (n == 1 ? TRANS(" min ")
  1281. : TRANS(" mins "));
  1282. ++fieldsShown;
  1283. }
  1284. if (fieldsShown < 2)
  1285. {
  1286. n = std::abs ((int) inSeconds()) % 60;
  1287. if (n > 0)
  1288. {
  1289. result << n << (n == 1 ? TRANS(" sec ")
  1290. : TRANS(" secs "));
  1291. ++fieldsShown;
  1292. }
  1293. if (fieldsShown == 0)
  1294. {
  1295. n = std::abs ((int) inMilliseconds()) % 1000;
  1296. if (n > 0)
  1297. result << n << TRANS(" ms");
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return result.trimEnd();
  1303. }
  1304. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1305. {
  1306. seconds = other.seconds;
  1307. return *this;
  1308. }
  1309. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1310. {
  1311. seconds += timeToAdd.seconds;
  1312. return *this;
  1313. }
  1314. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1315. {
  1316. seconds -= timeToSubtract.seconds;
  1317. return *this;
  1318. }
  1319. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1320. {
  1321. seconds += secondsToAdd;
  1322. return *this;
  1323. }
  1324. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1325. {
  1326. seconds -= secondsToSubtract;
  1327. return *this;
  1328. }
  1329. bool operator== (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() == t2.inSeconds(); }
  1330. bool operator!= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() != t2.inSeconds(); }
  1331. bool operator> (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() > t2.inSeconds(); }
  1332. bool operator< (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() < t2.inSeconds(); }
  1333. bool operator>= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() >= t2.inSeconds(); }
  1334. bool operator<= (const RelativeTime& t1, const RelativeTime& t2) throw() { return t1.inSeconds() <= t2.inSeconds(); }
  1335. const RelativeTime operator+ (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t += t2; }
  1336. const RelativeTime operator- (const RelativeTime& t1, const RelativeTime& t2) throw() { RelativeTime t (t1); return t -= t2; }
  1337. END_JUCE_NAMESPACE
  1338. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1339. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1340. BEGIN_JUCE_NAMESPACE
  1341. SystemStats::CPUFlags SystemStats::cpuFlags;
  1342. const String SystemStats::getJUCEVersion()
  1343. {
  1344. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1345. + "." + String (JUCE_MINOR_VERSION)
  1346. + "." + String (JUCE_BUILDNUMBER);
  1347. }
  1348. #ifdef JUCE_DLL
  1349. void* juce_Malloc (int size) { return malloc (size); }
  1350. void* juce_Calloc (int size) { return calloc (1, size); }
  1351. void* juce_Realloc (void* block, int size) { return realloc (block, size); }
  1352. void juce_Free (void* block) { free (block); }
  1353. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1354. void* juce_DebugMalloc (int size, const char* file, int line) { return _malloc_dbg (size, _NORMAL_BLOCK, file, line); }
  1355. void* juce_DebugCalloc (int size, const char* file, int line) { return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line); }
  1356. void* juce_DebugRealloc (void* block, int size, const char* file, int line) { return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line); }
  1357. void juce_DebugFree (void* block) { _free_dbg (block, _NORMAL_BLOCK); }
  1358. #endif
  1359. #endif
  1360. END_JUCE_NAMESPACE
  1361. /*** End of inlined file: juce_SystemStats.cpp ***/
  1362. /*** Start of inlined file: juce_Time.cpp ***/
  1363. #if JUCE_MSVC
  1364. #pragma warning (push)
  1365. #pragma warning (disable: 4514)
  1366. #endif
  1367. #ifndef JUCE_WINDOWS
  1368. #include <sys/time.h>
  1369. #else
  1370. #include <ctime>
  1371. #endif
  1372. #include <sys/timeb.h>
  1373. #if JUCE_MSVC
  1374. #pragma warning (pop)
  1375. #ifdef _INC_TIME_INL
  1376. #define USE_NEW_SECURE_TIME_FNS
  1377. #endif
  1378. #endif
  1379. BEGIN_JUCE_NAMESPACE
  1380. namespace TimeHelpers
  1381. {
  1382. static struct tm millisToLocal (const int64 millis) throw()
  1383. {
  1384. struct tm result;
  1385. const int64 seconds = millis / 1000;
  1386. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1387. {
  1388. // use extended maths for dates beyond 1970 to 2037..
  1389. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1390. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1391. const int days = (int) (jdm / literal64bit (86400));
  1392. const int a = 32044 + days;
  1393. const int b = (4 * a + 3) / 146097;
  1394. const int c = a - (b * 146097) / 4;
  1395. const int d = (4 * c + 3) / 1461;
  1396. const int e = c - (d * 1461) / 4;
  1397. const int m = (5 * e + 2) / 153;
  1398. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1399. result.tm_mon = m + 2 - 12 * (m / 10);
  1400. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1401. result.tm_wday = (days + 1) % 7;
  1402. result.tm_yday = -1;
  1403. int t = (int) (jdm % literal64bit (86400));
  1404. result.tm_hour = t / 3600;
  1405. t %= 3600;
  1406. result.tm_min = t / 60;
  1407. result.tm_sec = t % 60;
  1408. result.tm_isdst = -1;
  1409. }
  1410. else
  1411. {
  1412. time_t now = static_cast <time_t> (seconds);
  1413. #if JUCE_WINDOWS
  1414. #ifdef USE_NEW_SECURE_TIME_FNS
  1415. if (now >= 0 && now <= 0x793406fff)
  1416. localtime_s (&result, &now);
  1417. else
  1418. zeromem (&result, sizeof (result));
  1419. #else
  1420. result = *localtime (&now);
  1421. #endif
  1422. #else
  1423. // more thread-safe
  1424. localtime_r (&now, &result);
  1425. #endif
  1426. }
  1427. return result;
  1428. }
  1429. static int extendedModulo (const int64 value, const int modulo) throw()
  1430. {
  1431. return (int) (value >= 0 ? (value % modulo)
  1432. : (value - ((value / modulo) + 1) * modulo));
  1433. }
  1434. static uint32 lastMSCounterValue = 0;
  1435. }
  1436. Time::Time() throw()
  1437. : millisSinceEpoch (0)
  1438. {
  1439. }
  1440. Time::Time (const Time& other) throw()
  1441. : millisSinceEpoch (other.millisSinceEpoch)
  1442. {
  1443. }
  1444. Time::Time (const int64 ms) throw()
  1445. : millisSinceEpoch (ms)
  1446. {
  1447. }
  1448. Time::Time (const int year,
  1449. const int month,
  1450. const int day,
  1451. const int hours,
  1452. const int minutes,
  1453. const int seconds,
  1454. const int milliseconds,
  1455. const bool useLocalTime) throw()
  1456. {
  1457. jassert (year > 100); // year must be a 4-digit version
  1458. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1459. {
  1460. // use extended maths for dates beyond 1970 to 2037..
  1461. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1462. : 0;
  1463. const int a = (13 - month) / 12;
  1464. const int y = year + 4800 - a;
  1465. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1466. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1467. - 32045;
  1468. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1469. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1470. + milliseconds;
  1471. }
  1472. else
  1473. {
  1474. struct tm t;
  1475. t.tm_year = year - 1900;
  1476. t.tm_mon = month;
  1477. t.tm_mday = day;
  1478. t.tm_hour = hours;
  1479. t.tm_min = minutes;
  1480. t.tm_sec = seconds;
  1481. t.tm_isdst = -1;
  1482. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1483. if (millisSinceEpoch < 0)
  1484. millisSinceEpoch = 0;
  1485. else
  1486. millisSinceEpoch += milliseconds;
  1487. }
  1488. }
  1489. Time::~Time() throw()
  1490. {
  1491. }
  1492. Time& Time::operator= (const Time& other) throw()
  1493. {
  1494. millisSinceEpoch = other.millisSinceEpoch;
  1495. return *this;
  1496. }
  1497. int64 Time::currentTimeMillis() throw()
  1498. {
  1499. static uint32 lastCounterResult = 0xffffffff;
  1500. static int64 correction = 0;
  1501. const uint32 now = getMillisecondCounter();
  1502. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1503. if (now < lastCounterResult)
  1504. {
  1505. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1506. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1507. {
  1508. // get the time once using normal library calls, and store the difference needed to
  1509. // turn the millisecond counter into a real time.
  1510. #if JUCE_WINDOWS
  1511. struct _timeb t;
  1512. #ifdef USE_NEW_SECURE_TIME_FNS
  1513. _ftime_s (&t);
  1514. #else
  1515. _ftime (&t);
  1516. #endif
  1517. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1518. #else
  1519. struct timeval tv;
  1520. struct timezone tz;
  1521. gettimeofday (&tv, &tz);
  1522. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1523. #endif
  1524. }
  1525. }
  1526. lastCounterResult = now;
  1527. return correction + now;
  1528. }
  1529. uint32 juce_millisecondsSinceStartup() throw();
  1530. uint32 Time::getMillisecondCounter() throw()
  1531. {
  1532. const uint32 now = juce_millisecondsSinceStartup();
  1533. if (now < TimeHelpers::lastMSCounterValue)
  1534. {
  1535. // in multi-threaded apps this might be called concurrently, so
  1536. // make sure that our last counter value only increases and doesn't
  1537. // go backwards..
  1538. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1539. TimeHelpers::lastMSCounterValue = now;
  1540. }
  1541. else
  1542. {
  1543. TimeHelpers::lastMSCounterValue = now;
  1544. }
  1545. return now;
  1546. }
  1547. uint32 Time::getApproximateMillisecondCounter() throw()
  1548. {
  1549. jassert (TimeHelpers::lastMSCounterValue != 0);
  1550. return TimeHelpers::lastMSCounterValue;
  1551. }
  1552. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1553. {
  1554. for (;;)
  1555. {
  1556. const uint32 now = getMillisecondCounter();
  1557. if (now >= targetTime)
  1558. break;
  1559. const int toWait = targetTime - now;
  1560. if (toWait > 2)
  1561. {
  1562. Thread::sleep (jmin (20, toWait >> 1));
  1563. }
  1564. else
  1565. {
  1566. // xxx should consider using mutex_pause on the mac as it apparently
  1567. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1568. for (int i = 10; --i >= 0;)
  1569. Thread::yield();
  1570. }
  1571. }
  1572. }
  1573. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1574. {
  1575. return ticks / (double) getHighResolutionTicksPerSecond();
  1576. }
  1577. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1578. {
  1579. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1580. }
  1581. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1582. {
  1583. return Time (currentTimeMillis());
  1584. }
  1585. const String Time::toString (const bool includeDate,
  1586. const bool includeTime,
  1587. const bool includeSeconds,
  1588. const bool use24HourClock) const throw()
  1589. {
  1590. String result;
  1591. if (includeDate)
  1592. {
  1593. result << getDayOfMonth() << ' '
  1594. << getMonthName (true) << ' '
  1595. << getYear();
  1596. if (includeTime)
  1597. result << ' ';
  1598. }
  1599. if (includeTime)
  1600. {
  1601. const int mins = getMinutes();
  1602. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1603. << (mins < 10 ? ":0" : ":") << mins;
  1604. if (includeSeconds)
  1605. {
  1606. const int secs = getSeconds();
  1607. result << (secs < 10 ? ":0" : ":") << secs;
  1608. }
  1609. if (! use24HourClock)
  1610. result << (isAfternoon() ? "pm" : "am");
  1611. }
  1612. return result.trimEnd();
  1613. }
  1614. const String Time::formatted (const String& format) const
  1615. {
  1616. String buffer;
  1617. int bufferSize = 128;
  1618. buffer.preallocateStorage (bufferSize);
  1619. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1620. while (CharacterFunctions::ftime (buffer.getCharPointer().getAddress(), bufferSize, format.getCharPointer(), &t) <= 0)
  1621. {
  1622. bufferSize += 128;
  1623. buffer.preallocateStorage (bufferSize);
  1624. }
  1625. return buffer;
  1626. }
  1627. int Time::getYear() const throw()
  1628. {
  1629. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1630. }
  1631. int Time::getMonth() const throw()
  1632. {
  1633. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1634. }
  1635. int Time::getDayOfMonth() const throw()
  1636. {
  1637. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1638. }
  1639. int Time::getDayOfWeek() const throw()
  1640. {
  1641. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1642. }
  1643. int Time::getHours() const throw()
  1644. {
  1645. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1646. }
  1647. int Time::getHoursInAmPmFormat() const throw()
  1648. {
  1649. const int hours = getHours();
  1650. if (hours == 0)
  1651. return 12;
  1652. else if (hours <= 12)
  1653. return hours;
  1654. else
  1655. return hours - 12;
  1656. }
  1657. bool Time::isAfternoon() const throw()
  1658. {
  1659. return getHours() >= 12;
  1660. }
  1661. int Time::getMinutes() const throw()
  1662. {
  1663. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1664. }
  1665. int Time::getSeconds() const throw()
  1666. {
  1667. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1668. }
  1669. int Time::getMilliseconds() const throw()
  1670. {
  1671. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1672. }
  1673. bool Time::isDaylightSavingTime() const throw()
  1674. {
  1675. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1676. }
  1677. const String Time::getTimeZone() const throw()
  1678. {
  1679. String zone[2];
  1680. #if JUCE_WINDOWS
  1681. _tzset();
  1682. #ifdef USE_NEW_SECURE_TIME_FNS
  1683. {
  1684. char name [128];
  1685. size_t length;
  1686. for (int i = 0; i < 2; ++i)
  1687. {
  1688. zeromem (name, sizeof (name));
  1689. _get_tzname (&length, name, 127, i);
  1690. zone[i] = name;
  1691. }
  1692. }
  1693. #else
  1694. const char** const zonePtr = (const char**) _tzname;
  1695. zone[0] = zonePtr[0];
  1696. zone[1] = zonePtr[1];
  1697. #endif
  1698. #else
  1699. tzset();
  1700. const char** const zonePtr = (const char**) tzname;
  1701. zone[0] = zonePtr[0];
  1702. zone[1] = zonePtr[1];
  1703. #endif
  1704. if (isDaylightSavingTime())
  1705. {
  1706. zone[0] = zone[1];
  1707. if (zone[0].length() > 3
  1708. && zone[0].containsIgnoreCase ("daylight")
  1709. && zone[0].contains ("GMT"))
  1710. zone[0] = "BST";
  1711. }
  1712. return zone[0].substring (0, 3);
  1713. }
  1714. const String Time::getMonthName (const bool threeLetterVersion) const
  1715. {
  1716. return getMonthName (getMonth(), threeLetterVersion);
  1717. }
  1718. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1719. {
  1720. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1721. }
  1722. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1723. {
  1724. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1725. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1726. monthNumber %= 12;
  1727. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1728. : longMonthNames [monthNumber]);
  1729. }
  1730. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1731. {
  1732. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1733. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1734. day %= 7;
  1735. return TRANS (threeLetterVersion ? shortDayNames [day]
  1736. : longDayNames [day]);
  1737. }
  1738. Time& Time::operator+= (const RelativeTime& delta) { millisSinceEpoch += delta.inMilliseconds(); return *this; }
  1739. Time& Time::operator-= (const RelativeTime& delta) { millisSinceEpoch -= delta.inMilliseconds(); return *this; }
  1740. const Time operator+ (const Time& time, const RelativeTime& delta) { Time t (time); return t += delta; }
  1741. const Time operator- (const Time& time, const RelativeTime& delta) { Time t (time); return t -= delta; }
  1742. const Time operator+ (const RelativeTime& delta, const Time& time) { Time t (time); return t += delta; }
  1743. const RelativeTime operator- (const Time& time1, const Time& time2) { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); }
  1744. bool operator== (const Time& time1, const Time& time2) { return time1.toMilliseconds() == time2.toMilliseconds(); }
  1745. bool operator!= (const Time& time1, const Time& time2) { return time1.toMilliseconds() != time2.toMilliseconds(); }
  1746. bool operator< (const Time& time1, const Time& time2) { return time1.toMilliseconds() < time2.toMilliseconds(); }
  1747. bool operator> (const Time& time1, const Time& time2) { return time1.toMilliseconds() > time2.toMilliseconds(); }
  1748. bool operator<= (const Time& time1, const Time& time2) { return time1.toMilliseconds() <= time2.toMilliseconds(); }
  1749. bool operator>= (const Time& time1, const Time& time2) { return time1.toMilliseconds() >= time2.toMilliseconds(); }
  1750. END_JUCE_NAMESPACE
  1751. /*** End of inlined file: juce_Time.cpp ***/
  1752. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1753. BEGIN_JUCE_NAMESPACE
  1754. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1755. #endif
  1756. #if JUCE_WINDOWS
  1757. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1758. #endif
  1759. #if JUCE_DEBUG
  1760. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1761. #endif
  1762. static bool juceInitialisedNonGUI = false;
  1763. JUCE_API void JUCE_CALLTYPE initialiseJuce_NonGUI()
  1764. {
  1765. if (! juceInitialisedNonGUI)
  1766. {
  1767. juceInitialisedNonGUI = true;
  1768. JUCE_AUTORELEASEPOOL
  1769. DBG (SystemStats::getJUCEVersion());
  1770. SystemStats::initialiseStats();
  1771. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1772. }
  1773. // Some basic tests, to keep an eye on things and make sure these types work ok
  1774. // on all platforms. Let me know if any of these assertions fail on your system!
  1775. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1776. static_jassert (sizeof (int8) == 1);
  1777. static_jassert (sizeof (uint8) == 1);
  1778. static_jassert (sizeof (int16) == 2);
  1779. static_jassert (sizeof (uint16) == 2);
  1780. static_jassert (sizeof (int32) == 4);
  1781. static_jassert (sizeof (uint32) == 4);
  1782. static_jassert (sizeof (int64) == 8);
  1783. static_jassert (sizeof (uint64) == 8);
  1784. }
  1785. JUCE_API void JUCE_CALLTYPE shutdownJuce_NonGUI()
  1786. {
  1787. if (juceInitialisedNonGUI)
  1788. {
  1789. juceInitialisedNonGUI = false;
  1790. JUCE_AUTORELEASEPOOL
  1791. LocalisedStrings::setCurrentMappings (0);
  1792. Thread::stopAllThreads (3000);
  1793. #if JUCE_WINDOWS
  1794. juce_shutdownWin32Sockets();
  1795. #endif
  1796. #if JUCE_DEBUG
  1797. juce_CheckForDanglingStreams();
  1798. #endif
  1799. }
  1800. }
  1801. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1802. static bool juceInitialisedGUI = false;
  1803. JUCE_API void JUCE_CALLTYPE initialiseJuce_GUI()
  1804. {
  1805. if (! juceInitialisedGUI)
  1806. {
  1807. juceInitialisedGUI = true;
  1808. JUCE_AUTORELEASEPOOL
  1809. initialiseJuce_NonGUI();
  1810. MessageManager::getInstance();
  1811. LookAndFeel::setDefaultLookAndFeel (0);
  1812. #if JUCE_DEBUG
  1813. try // This section is just a safety-net for catching builds without RTTI enabled..
  1814. {
  1815. MemoryOutputStream mo;
  1816. OutputStream* o = &mo;
  1817. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1818. o = dynamic_cast <MemoryOutputStream*> (o);
  1819. jassert (o != 0);
  1820. }
  1821. catch (...)
  1822. {
  1823. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1824. jassertfalse;
  1825. }
  1826. #endif
  1827. }
  1828. }
  1829. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1830. {
  1831. if (juceInitialisedGUI)
  1832. {
  1833. juceInitialisedGUI = false;
  1834. JUCE_AUTORELEASEPOOL
  1835. DeletedAtShutdown::deleteAll();
  1836. LookAndFeel::clearDefaultLookAndFeel();
  1837. delete MessageManager::getInstance();
  1838. shutdownJuce_NonGUI();
  1839. }
  1840. }
  1841. #endif
  1842. #if JUCE_UNIT_TESTS
  1843. class AtomicTests : public UnitTest
  1844. {
  1845. public:
  1846. AtomicTests() : UnitTest ("Atomics") {}
  1847. void runTest()
  1848. {
  1849. beginTest ("Misc");
  1850. char a1[7];
  1851. expect (numElementsInArray(a1) == 7);
  1852. int a2[3];
  1853. expect (numElementsInArray(a2) == 3);
  1854. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1855. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1856. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1857. beginTest ("Atomic types");
  1858. AtomicTester <int>::testInteger (*this);
  1859. AtomicTester <unsigned int>::testInteger (*this);
  1860. AtomicTester <int32>::testInteger (*this);
  1861. AtomicTester <uint32>::testInteger (*this);
  1862. AtomicTester <long>::testInteger (*this);
  1863. AtomicTester <void*>::testInteger (*this);
  1864. AtomicTester <int*>::testInteger (*this);
  1865. AtomicTester <float>::testFloat (*this);
  1866. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1867. AtomicTester <int64>::testInteger (*this);
  1868. AtomicTester <uint64>::testInteger (*this);
  1869. AtomicTester <double>::testFloat (*this);
  1870. #endif
  1871. }
  1872. template <typename Type>
  1873. class AtomicTester
  1874. {
  1875. public:
  1876. AtomicTester() {}
  1877. static void testInteger (UnitTest& test)
  1878. {
  1879. Atomic<Type> a, b;
  1880. a.set ((Type) 10);
  1881. a += (Type) 15;
  1882. a.memoryBarrier();
  1883. a -= (Type) 5;
  1884. ++a; ++a; --a;
  1885. a.memoryBarrier();
  1886. testFloat (test);
  1887. }
  1888. static void testFloat (UnitTest& test)
  1889. {
  1890. Atomic<Type> a, b;
  1891. a = (Type) 21;
  1892. a.memoryBarrier();
  1893. /* These are some simple test cases to check the atomics - let me know
  1894. if any of these assertions fail on your system!
  1895. */
  1896. test.expect (a.get() == (Type) 21);
  1897. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1898. test.expect (a.get() == (Type) 21);
  1899. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1900. test.expect (a.get() == (Type) 101);
  1901. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1902. test.expect (a.get() == (Type) 101);
  1903. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1904. test.expect (a.get() == (Type) 200);
  1905. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1906. test.expect (a.get() == (Type) 300);
  1907. b = a;
  1908. test.expect (b.get() == a.get());
  1909. }
  1910. };
  1911. };
  1912. static AtomicTests atomicUnitTests;
  1913. #endif
  1914. END_JUCE_NAMESPACE
  1915. /*** End of inlined file: juce_Initialisation.cpp ***/
  1916. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1917. BEGIN_JUCE_NAMESPACE
  1918. AbstractFifo::AbstractFifo (const int capacity) throw()
  1919. : bufferSize (capacity)
  1920. {
  1921. jassert (bufferSize > 0);
  1922. }
  1923. AbstractFifo::~AbstractFifo() {}
  1924. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1925. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1926. int AbstractFifo::getNumReady() const throw()
  1927. {
  1928. const int vs = validStart.get();
  1929. const int ve = validEnd.get();
  1930. return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1931. }
  1932. void AbstractFifo::reset() throw()
  1933. {
  1934. validEnd = 0;
  1935. validStart = 0;
  1936. }
  1937. void AbstractFifo::setTotalSize (int newSize) throw()
  1938. {
  1939. jassert (newSize > 0);
  1940. reset();
  1941. bufferSize = newSize;
  1942. }
  1943. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1944. {
  1945. const int vs = validStart.get();
  1946. const int ve = validEnd.value;
  1947. const int freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
  1948. numToWrite = jmin (numToWrite, freeSpace - 1);
  1949. if (numToWrite <= 0)
  1950. {
  1951. startIndex1 = 0;
  1952. startIndex2 = 0;
  1953. blockSize1 = 0;
  1954. blockSize2 = 0;
  1955. }
  1956. else
  1957. {
  1958. startIndex1 = ve;
  1959. startIndex2 = 0;
  1960. blockSize1 = jmin (bufferSize - ve, numToWrite);
  1961. numToWrite -= blockSize1;
  1962. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
  1963. }
  1964. }
  1965. void AbstractFifo::finishedWrite (int numWritten) throw()
  1966. {
  1967. jassert (numWritten >= 0 && numWritten < bufferSize);
  1968. int newEnd = validEnd.value + numWritten;
  1969. if (newEnd >= bufferSize)
  1970. newEnd -= bufferSize;
  1971. validEnd = newEnd;
  1972. }
  1973. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1974. {
  1975. const int vs = validStart.value;
  1976. const int ve = validEnd.get();
  1977. const int numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
  1978. numWanted = jmin (numWanted, numReady);
  1979. if (numWanted <= 0)
  1980. {
  1981. startIndex1 = 0;
  1982. startIndex2 = 0;
  1983. blockSize1 = 0;
  1984. blockSize2 = 0;
  1985. }
  1986. else
  1987. {
  1988. startIndex1 = vs;
  1989. startIndex2 = 0;
  1990. blockSize1 = jmin (bufferSize - vs, numWanted);
  1991. numWanted -= blockSize1;
  1992. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
  1993. }
  1994. }
  1995. void AbstractFifo::finishedRead (int numRead) throw()
  1996. {
  1997. jassert (numRead >= 0 && numRead <= bufferSize);
  1998. int newStart = validStart.value + numRead;
  1999. if (newStart >= bufferSize)
  2000. newStart -= bufferSize;
  2001. validStart = newStart;
  2002. }
  2003. #if JUCE_UNIT_TESTS
  2004. class AbstractFifoTests : public UnitTest
  2005. {
  2006. public:
  2007. AbstractFifoTests() : UnitTest ("Abstract Fifo") {}
  2008. class WriteThread : public Thread
  2009. {
  2010. public:
  2011. WriteThread (AbstractFifo& fifo_, int* buffer_)
  2012. : Thread ("fifo writer"), fifo (fifo_), buffer (buffer_)
  2013. {
  2014. startThread();
  2015. }
  2016. ~WriteThread()
  2017. {
  2018. stopThread (5000);
  2019. }
  2020. void run()
  2021. {
  2022. int n = 0;
  2023. while (! threadShouldExit())
  2024. {
  2025. int num = Random::getSystemRandom().nextInt (2000) + 1;
  2026. int start1, size1, start2, size2;
  2027. fifo.prepareToWrite (num, start1, size1, start2, size2);
  2028. jassert (size1 >= 0 && size2 >= 0);
  2029. jassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
  2030. jassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));
  2031. int i;
  2032. for (i = 0; i < size1; ++i)
  2033. buffer [start1 + i] = n++;
  2034. for (i = 0; i < size2; ++i)
  2035. buffer [start2 + i] = n++;
  2036. fifo.finishedWrite (size1 + size2);
  2037. }
  2038. }
  2039. private:
  2040. AbstractFifo& fifo;
  2041. int* buffer;
  2042. };
  2043. void runTest()
  2044. {
  2045. beginTest ("AbstractFifo");
  2046. int buffer [5000];
  2047. AbstractFifo fifo (numElementsInArray (buffer));
  2048. WriteThread writer (fifo, buffer);
  2049. int n = 0;
  2050. for (int count = 1000000; --count >= 0;)
  2051. {
  2052. int num = Random::getSystemRandom().nextInt (6000) + 1;
  2053. int start1, size1, start2, size2;
  2054. fifo.prepareToRead (num, start1, size1, start2, size2);
  2055. if (! (size1 >= 0 && size2 >= 0)
  2056. && (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()))
  2057. && (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize())))
  2058. {
  2059. expect (false, "prepareToRead returned -ve values");
  2060. break;
  2061. }
  2062. bool failed = false;
  2063. int i;
  2064. for (i = 0; i < size1; ++i)
  2065. failed = (buffer [start1 + i] != n++) || failed;
  2066. for (i = 0; i < size2; ++i)
  2067. failed = (buffer [start2 + i] != n++) || failed;
  2068. if (failed)
  2069. {
  2070. expect (false, "read values were incorrect");
  2071. break;
  2072. }
  2073. fifo.finishedRead (size1 + size2);
  2074. }
  2075. }
  2076. };
  2077. static AbstractFifoTests fifoUnitTests;
  2078. #endif
  2079. END_JUCE_NAMESPACE
  2080. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2081. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2082. BEGIN_JUCE_NAMESPACE
  2083. BigInteger::BigInteger()
  2084. : numValues (4),
  2085. highestBit (-1),
  2086. negative (false)
  2087. {
  2088. values.calloc (numValues + 1);
  2089. }
  2090. BigInteger::BigInteger (const int32 value)
  2091. : numValues (4),
  2092. highestBit (31),
  2093. negative (value < 0)
  2094. {
  2095. values.calloc (numValues + 1);
  2096. values[0] = abs (value);
  2097. highestBit = getHighestBit();
  2098. }
  2099. BigInteger::BigInteger (const uint32 value)
  2100. : numValues (4),
  2101. highestBit (31),
  2102. negative (false)
  2103. {
  2104. values.calloc (numValues + 1);
  2105. values[0] = value;
  2106. highestBit = getHighestBit();
  2107. }
  2108. BigInteger::BigInteger (int64 value)
  2109. : numValues (4),
  2110. highestBit (63),
  2111. negative (value < 0)
  2112. {
  2113. values.calloc (numValues + 1);
  2114. if (value < 0)
  2115. value = -value;
  2116. values[0] = (uint32) value;
  2117. values[1] = (uint32) (value >> 32);
  2118. highestBit = getHighestBit();
  2119. }
  2120. BigInteger::BigInteger (const BigInteger& other)
  2121. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2122. highestBit (other.getHighestBit()),
  2123. negative (other.negative)
  2124. {
  2125. values.malloc (numValues + 1);
  2126. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2127. }
  2128. BigInteger::~BigInteger()
  2129. {
  2130. }
  2131. void BigInteger::swapWith (BigInteger& other) throw()
  2132. {
  2133. values.swapWith (other.values);
  2134. swapVariables (numValues, other.numValues);
  2135. swapVariables (highestBit, other.highestBit);
  2136. swapVariables (negative, other.negative);
  2137. }
  2138. BigInteger& BigInteger::operator= (const BigInteger& other)
  2139. {
  2140. if (this != &other)
  2141. {
  2142. highestBit = other.getHighestBit();
  2143. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2144. negative = other.negative;
  2145. values.malloc (numValues + 1);
  2146. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2147. }
  2148. return *this;
  2149. }
  2150. void BigInteger::ensureSize (const int numVals)
  2151. {
  2152. if (numVals + 2 >= numValues)
  2153. {
  2154. int oldSize = numValues;
  2155. numValues = ((numVals + 2) * 3) / 2;
  2156. values.realloc (numValues + 1);
  2157. while (oldSize < numValues)
  2158. values [oldSize++] = 0;
  2159. }
  2160. }
  2161. bool BigInteger::operator[] (const int bit) const throw()
  2162. {
  2163. return bit <= highestBit && bit >= 0
  2164. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2165. }
  2166. int BigInteger::toInteger() const throw()
  2167. {
  2168. const int n = (int) (values[0] & 0x7fffffff);
  2169. return negative ? -n : n;
  2170. }
  2171. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2172. {
  2173. BigInteger r;
  2174. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2175. r.ensureSize (bitToIndex (numBits));
  2176. r.highestBit = numBits;
  2177. int i = 0;
  2178. while (numBits > 0)
  2179. {
  2180. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2181. numBits -= 32;
  2182. startBit += 32;
  2183. }
  2184. r.highestBit = r.getHighestBit();
  2185. return r;
  2186. }
  2187. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2188. {
  2189. if (numBits > 32)
  2190. {
  2191. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2192. numBits = 32;
  2193. }
  2194. numBits = jmin (numBits, highestBit + 1 - startBit);
  2195. if (numBits <= 0)
  2196. return 0;
  2197. const int pos = bitToIndex (startBit);
  2198. const int offset = startBit & 31;
  2199. const int endSpace = 32 - numBits;
  2200. uint32 n = ((uint32) values [pos]) >> offset;
  2201. if (offset > endSpace)
  2202. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2203. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2204. }
  2205. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2206. {
  2207. if (numBits > 32)
  2208. {
  2209. jassertfalse;
  2210. numBits = 32;
  2211. }
  2212. for (int i = 0; i < numBits; ++i)
  2213. {
  2214. setBit (startBit + i, (valueToSet & 1) != 0);
  2215. valueToSet >>= 1;
  2216. }
  2217. }
  2218. void BigInteger::clear()
  2219. {
  2220. if (numValues > 16)
  2221. {
  2222. numValues = 4;
  2223. values.calloc (numValues + 1);
  2224. }
  2225. else
  2226. {
  2227. zeromem (values, sizeof (uint32) * (numValues + 1));
  2228. }
  2229. highestBit = -1;
  2230. negative = false;
  2231. }
  2232. void BigInteger::setBit (const int bit)
  2233. {
  2234. if (bit >= 0)
  2235. {
  2236. if (bit > highestBit)
  2237. {
  2238. ensureSize (bitToIndex (bit));
  2239. highestBit = bit;
  2240. }
  2241. values [bitToIndex (bit)] |= bitToMask (bit);
  2242. }
  2243. }
  2244. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2245. {
  2246. if (shouldBeSet)
  2247. setBit (bit);
  2248. else
  2249. clearBit (bit);
  2250. }
  2251. void BigInteger::clearBit (const int bit) throw()
  2252. {
  2253. if (bit >= 0 && bit <= highestBit)
  2254. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2255. }
  2256. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2257. {
  2258. while (--numBits >= 0)
  2259. setBit (startBit++, shouldBeSet);
  2260. }
  2261. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2262. {
  2263. if (bit >= 0)
  2264. shiftBits (1, bit);
  2265. setBit (bit, shouldBeSet);
  2266. }
  2267. bool BigInteger::isZero() const throw()
  2268. {
  2269. return getHighestBit() < 0;
  2270. }
  2271. bool BigInteger::isOne() const throw()
  2272. {
  2273. return getHighestBit() == 0 && ! negative;
  2274. }
  2275. bool BigInteger::isNegative() const throw()
  2276. {
  2277. return negative && ! isZero();
  2278. }
  2279. void BigInteger::setNegative (const bool neg) throw()
  2280. {
  2281. negative = neg;
  2282. }
  2283. void BigInteger::negate() throw()
  2284. {
  2285. negative = (! negative) && ! isZero();
  2286. }
  2287. #if JUCE_USE_INTRINSICS
  2288. #pragma intrinsic (_BitScanReverse)
  2289. #endif
  2290. namespace BitFunctions
  2291. {
  2292. inline int countBitsInInt32 (uint32 n) throw()
  2293. {
  2294. n -= ((n >> 1) & 0x55555555);
  2295. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  2296. n = (((n >> 4) + n) & 0x0f0f0f0f);
  2297. n += (n >> 8);
  2298. n += (n >> 16);
  2299. return n & 0x3f;
  2300. }
  2301. inline int highestBitInInt (uint32 n) throw()
  2302. {
  2303. jassert (n != 0); // (the built-in functions may not work for n = 0)
  2304. #if JUCE_GCC
  2305. return 31 - __builtin_clz (n);
  2306. #elif JUCE_USE_INTRINSICS
  2307. unsigned long highest;
  2308. _BitScanReverse (&highest, n);
  2309. return (int) highest;
  2310. #else
  2311. n |= (n >> 1);
  2312. n |= (n >> 2);
  2313. n |= (n >> 4);
  2314. n |= (n >> 8);
  2315. n |= (n >> 16);
  2316. return countBitsInInt32 (n >> 1);
  2317. #endif
  2318. }
  2319. }
  2320. int BigInteger::countNumberOfSetBits() const throw()
  2321. {
  2322. int total = 0;
  2323. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2324. total += BitFunctions::countBitsInInt32 (values[i]);
  2325. return total;
  2326. }
  2327. int BigInteger::getHighestBit() const throw()
  2328. {
  2329. for (int i = bitToIndex (highestBit + 1); i >= 0; --i)
  2330. {
  2331. const uint32 n = values[i];
  2332. if (n != 0)
  2333. return BitFunctions::highestBitInInt (n) + (i << 5);
  2334. }
  2335. return -1;
  2336. }
  2337. int BigInteger::findNextSetBit (int i) const throw()
  2338. {
  2339. for (; i <= highestBit; ++i)
  2340. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2341. return i;
  2342. return -1;
  2343. }
  2344. int BigInteger::findNextClearBit (int i) const throw()
  2345. {
  2346. for (; i <= highestBit; ++i)
  2347. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2348. break;
  2349. return i;
  2350. }
  2351. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2352. {
  2353. if (other.isNegative())
  2354. return operator-= (-other);
  2355. if (isNegative())
  2356. {
  2357. if (compareAbsolute (other) < 0)
  2358. {
  2359. BigInteger temp (*this);
  2360. temp.negate();
  2361. *this = other;
  2362. operator-= (temp);
  2363. }
  2364. else
  2365. {
  2366. negate();
  2367. operator-= (other);
  2368. negate();
  2369. }
  2370. }
  2371. else
  2372. {
  2373. if (other.highestBit > highestBit)
  2374. highestBit = other.highestBit;
  2375. ++highestBit;
  2376. const int numInts = bitToIndex (highestBit) + 1;
  2377. ensureSize (numInts);
  2378. int64 remainder = 0;
  2379. for (int i = 0; i <= numInts; ++i)
  2380. {
  2381. if (i < numValues)
  2382. remainder += values[i];
  2383. if (i < other.numValues)
  2384. remainder += other.values[i];
  2385. values[i] = (uint32) remainder;
  2386. remainder >>= 32;
  2387. }
  2388. jassert (remainder == 0);
  2389. highestBit = getHighestBit();
  2390. }
  2391. return *this;
  2392. }
  2393. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2394. {
  2395. if (other.isNegative())
  2396. return operator+= (-other);
  2397. if (! isNegative())
  2398. {
  2399. if (compareAbsolute (other) < 0)
  2400. {
  2401. BigInteger temp (other);
  2402. swapWith (temp);
  2403. operator-= (temp);
  2404. negate();
  2405. return *this;
  2406. }
  2407. }
  2408. else
  2409. {
  2410. negate();
  2411. operator+= (other);
  2412. negate();
  2413. return *this;
  2414. }
  2415. const int numInts = bitToIndex (highestBit) + 1;
  2416. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2417. int64 amountToSubtract = 0;
  2418. for (int i = 0; i <= numInts; ++i)
  2419. {
  2420. if (i <= maxOtherInts)
  2421. amountToSubtract += (int64) other.values[i];
  2422. if (values[i] >= amountToSubtract)
  2423. {
  2424. values[i] = (uint32) (values[i] - amountToSubtract);
  2425. amountToSubtract = 0;
  2426. }
  2427. else
  2428. {
  2429. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2430. values[i] = (uint32) n;
  2431. amountToSubtract = 1;
  2432. }
  2433. }
  2434. return *this;
  2435. }
  2436. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2437. {
  2438. BigInteger total;
  2439. highestBit = getHighestBit();
  2440. const bool wasNegative = isNegative();
  2441. setNegative (false);
  2442. for (int i = 0; i <= highestBit; ++i)
  2443. {
  2444. if (operator[](i))
  2445. {
  2446. BigInteger n (other);
  2447. n.setNegative (false);
  2448. n <<= i;
  2449. total += n;
  2450. }
  2451. }
  2452. total.setNegative (wasNegative ^ other.isNegative());
  2453. swapWith (total);
  2454. return *this;
  2455. }
  2456. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2457. {
  2458. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2459. const int divHB = divisor.getHighestBit();
  2460. const int ourHB = getHighestBit();
  2461. if (divHB < 0 || ourHB < 0)
  2462. {
  2463. // division by zero
  2464. remainder.clear();
  2465. clear();
  2466. }
  2467. else
  2468. {
  2469. const bool wasNegative = isNegative();
  2470. swapWith (remainder);
  2471. remainder.setNegative (false);
  2472. clear();
  2473. BigInteger temp (divisor);
  2474. temp.setNegative (false);
  2475. int leftShift = ourHB - divHB;
  2476. temp <<= leftShift;
  2477. while (leftShift >= 0)
  2478. {
  2479. if (remainder.compareAbsolute (temp) >= 0)
  2480. {
  2481. remainder -= temp;
  2482. setBit (leftShift);
  2483. }
  2484. if (--leftShift >= 0)
  2485. temp >>= 1;
  2486. }
  2487. negative = wasNegative ^ divisor.isNegative();
  2488. remainder.setNegative (wasNegative);
  2489. }
  2490. }
  2491. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2492. {
  2493. BigInteger remainder;
  2494. divideBy (other, remainder);
  2495. return *this;
  2496. }
  2497. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2498. {
  2499. // this operation doesn't take into account negative values..
  2500. jassert (isNegative() == other.isNegative());
  2501. if (other.highestBit >= 0)
  2502. {
  2503. ensureSize (bitToIndex (other.highestBit));
  2504. int n = bitToIndex (other.highestBit) + 1;
  2505. while (--n >= 0)
  2506. values[n] |= other.values[n];
  2507. if (other.highestBit > highestBit)
  2508. highestBit = other.highestBit;
  2509. highestBit = getHighestBit();
  2510. }
  2511. return *this;
  2512. }
  2513. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2514. {
  2515. // this operation doesn't take into account negative values..
  2516. jassert (isNegative() == other.isNegative());
  2517. int n = numValues;
  2518. while (n > other.numValues)
  2519. values[--n] = 0;
  2520. while (--n >= 0)
  2521. values[n] &= other.values[n];
  2522. if (other.highestBit < highestBit)
  2523. highestBit = other.highestBit;
  2524. highestBit = getHighestBit();
  2525. return *this;
  2526. }
  2527. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2528. {
  2529. // this operation will only work with the absolute values
  2530. jassert (isNegative() == other.isNegative());
  2531. if (other.highestBit >= 0)
  2532. {
  2533. ensureSize (bitToIndex (other.highestBit));
  2534. int n = bitToIndex (other.highestBit) + 1;
  2535. while (--n >= 0)
  2536. values[n] ^= other.values[n];
  2537. if (other.highestBit > highestBit)
  2538. highestBit = other.highestBit;
  2539. highestBit = getHighestBit();
  2540. }
  2541. return *this;
  2542. }
  2543. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2544. {
  2545. BigInteger remainder;
  2546. divideBy (divisor, remainder);
  2547. swapWith (remainder);
  2548. return *this;
  2549. }
  2550. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2551. {
  2552. shiftBits (numBitsToShift, 0);
  2553. return *this;
  2554. }
  2555. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2556. {
  2557. return operator<<= (-numBitsToShift);
  2558. }
  2559. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2560. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2561. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2562. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2563. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2564. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2565. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2566. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2567. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2568. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2569. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2570. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2571. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2572. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2573. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2574. int BigInteger::compare (const BigInteger& other) const throw()
  2575. {
  2576. if (isNegative() == other.isNegative())
  2577. {
  2578. const int absComp = compareAbsolute (other);
  2579. return isNegative() ? -absComp : absComp;
  2580. }
  2581. else
  2582. {
  2583. return isNegative() ? -1 : 1;
  2584. }
  2585. }
  2586. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2587. {
  2588. const int h1 = getHighestBit();
  2589. const int h2 = other.getHighestBit();
  2590. if (h1 > h2)
  2591. return 1;
  2592. else if (h1 < h2)
  2593. return -1;
  2594. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2595. if (values[i] != other.values[i])
  2596. return (values[i] > other.values[i]) ? 1 : -1;
  2597. return 0;
  2598. }
  2599. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2600. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2601. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2602. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2603. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2604. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2605. void BigInteger::shiftBits (int bits, const int startBit)
  2606. {
  2607. if (highestBit < 0)
  2608. return;
  2609. if (startBit > 0)
  2610. {
  2611. if (bits < 0)
  2612. {
  2613. // right shift
  2614. for (int i = startBit; i <= highestBit; ++i)
  2615. setBit (i, operator[] (i - bits));
  2616. highestBit = getHighestBit();
  2617. }
  2618. else if (bits > 0)
  2619. {
  2620. // left shift
  2621. for (int i = highestBit + 1; --i >= startBit;)
  2622. setBit (i + bits, operator[] (i));
  2623. while (--bits >= 0)
  2624. clearBit (bits + startBit);
  2625. }
  2626. }
  2627. else
  2628. {
  2629. if (bits < 0)
  2630. {
  2631. // right shift
  2632. bits = -bits;
  2633. if (bits > highestBit)
  2634. {
  2635. clear();
  2636. }
  2637. else
  2638. {
  2639. const int wordsToMove = bitToIndex (bits);
  2640. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2641. highestBit -= bits;
  2642. if (wordsToMove > 0)
  2643. {
  2644. int i;
  2645. for (i = 0; i < top; ++i)
  2646. values [i] = values [i + wordsToMove];
  2647. for (i = 0; i < wordsToMove; ++i)
  2648. values [top + i] = 0;
  2649. bits &= 31;
  2650. }
  2651. if (bits != 0)
  2652. {
  2653. const int invBits = 32 - bits;
  2654. --top;
  2655. for (int i = 0; i < top; ++i)
  2656. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2657. values[top] = (values[top] >> bits);
  2658. }
  2659. highestBit = getHighestBit();
  2660. }
  2661. }
  2662. else if (bits > 0)
  2663. {
  2664. // left shift
  2665. ensureSize (bitToIndex (highestBit + bits) + 1);
  2666. const int wordsToMove = bitToIndex (bits);
  2667. int top = 1 + bitToIndex (highestBit);
  2668. highestBit += bits;
  2669. if (wordsToMove > 0)
  2670. {
  2671. int i;
  2672. for (i = top; --i >= 0;)
  2673. values [i + wordsToMove] = values [i];
  2674. for (i = 0; i < wordsToMove; ++i)
  2675. values [i] = 0;
  2676. bits &= 31;
  2677. }
  2678. if (bits != 0)
  2679. {
  2680. const int invBits = 32 - bits;
  2681. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2682. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2683. values [wordsToMove] = values [wordsToMove] << bits;
  2684. }
  2685. highestBit = getHighestBit();
  2686. }
  2687. }
  2688. }
  2689. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2690. {
  2691. while (! m->isZero())
  2692. {
  2693. if (n->compareAbsolute (*m) > 0)
  2694. swapVariables (m, n);
  2695. *m -= *n;
  2696. }
  2697. return *n;
  2698. }
  2699. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2700. {
  2701. BigInteger m (*this);
  2702. while (! n.isZero())
  2703. {
  2704. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2705. return simpleGCD (&m, &n);
  2706. BigInteger temp1 (m), temp2;
  2707. temp1.divideBy (n, temp2);
  2708. m = n;
  2709. n = temp2;
  2710. }
  2711. return m;
  2712. }
  2713. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2714. {
  2715. BigInteger exp (exponent);
  2716. exp %= modulus;
  2717. BigInteger value (1);
  2718. swapWith (value);
  2719. value %= modulus;
  2720. while (! exp.isZero())
  2721. {
  2722. if (exp [0])
  2723. {
  2724. operator*= (value);
  2725. operator%= (modulus);
  2726. }
  2727. value *= value;
  2728. value %= modulus;
  2729. exp >>= 1;
  2730. }
  2731. }
  2732. void BigInteger::inverseModulo (const BigInteger& modulus)
  2733. {
  2734. if (modulus.isOne() || modulus.isNegative())
  2735. {
  2736. clear();
  2737. return;
  2738. }
  2739. if (isNegative() || compareAbsolute (modulus) >= 0)
  2740. operator%= (modulus);
  2741. if (isOne())
  2742. return;
  2743. if (! (*this)[0])
  2744. {
  2745. // not invertible
  2746. clear();
  2747. return;
  2748. }
  2749. BigInteger a1 (modulus);
  2750. BigInteger a2 (*this);
  2751. BigInteger b1 (modulus);
  2752. BigInteger b2 (1);
  2753. while (! a2.isOne())
  2754. {
  2755. BigInteger temp1, temp2, multiplier (a1);
  2756. multiplier.divideBy (a2, temp1);
  2757. temp1 = a2;
  2758. temp1 *= multiplier;
  2759. temp2 = a1;
  2760. temp2 -= temp1;
  2761. a1 = a2;
  2762. a2 = temp2;
  2763. temp1 = b2;
  2764. temp1 *= multiplier;
  2765. temp2 = b1;
  2766. temp2 -= temp1;
  2767. b1 = b2;
  2768. b2 = temp2;
  2769. }
  2770. while (b2.isNegative())
  2771. b2 += modulus;
  2772. b2 %= modulus;
  2773. swapWith (b2);
  2774. }
  2775. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2776. {
  2777. return stream << value.toString (10);
  2778. }
  2779. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2780. {
  2781. String s;
  2782. BigInteger v (*this);
  2783. if (base == 2 || base == 8 || base == 16)
  2784. {
  2785. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2786. static const char* const hexDigits = "0123456789abcdef";
  2787. for (;;)
  2788. {
  2789. const int remainder = v.getBitRangeAsInt (0, bits);
  2790. v >>= bits;
  2791. if (remainder == 0 && v.isZero())
  2792. break;
  2793. s = String::charToString (hexDigits [remainder]) + s;
  2794. }
  2795. }
  2796. else if (base == 10)
  2797. {
  2798. const BigInteger ten (10);
  2799. BigInteger remainder;
  2800. for (;;)
  2801. {
  2802. v.divideBy (ten, remainder);
  2803. if (remainder.isZero() && v.isZero())
  2804. break;
  2805. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2806. }
  2807. }
  2808. else
  2809. {
  2810. jassertfalse; // can't do the specified base!
  2811. return String::empty;
  2812. }
  2813. s = s.paddedLeft ('0', minimumNumCharacters);
  2814. return isNegative() ? "-" + s : s;
  2815. }
  2816. void BigInteger::parseString (const String& text, const int base)
  2817. {
  2818. clear();
  2819. String::CharPointerType t (text.getCharPointer());
  2820. if (base == 2 || base == 8 || base == 16)
  2821. {
  2822. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2823. for (;;)
  2824. {
  2825. const juce_wchar c = t.getAndAdvance();
  2826. const int digit = CharacterFunctions::getHexDigitValue (c);
  2827. if (((uint32) digit) < (uint32) base)
  2828. {
  2829. operator<<= (bits);
  2830. operator+= (digit);
  2831. }
  2832. else if (c == 0)
  2833. {
  2834. break;
  2835. }
  2836. }
  2837. }
  2838. else if (base == 10)
  2839. {
  2840. const BigInteger ten ((uint32) 10);
  2841. for (;;)
  2842. {
  2843. const juce_wchar c = t.getAndAdvance();
  2844. if (c >= '0' && c <= '9')
  2845. {
  2846. operator*= (ten);
  2847. operator+= ((int) (c - '0'));
  2848. }
  2849. else if (c == 0)
  2850. {
  2851. break;
  2852. }
  2853. }
  2854. }
  2855. setNegative (text.trimStart().startsWithChar ('-'));
  2856. }
  2857. const MemoryBlock BigInteger::toMemoryBlock() const
  2858. {
  2859. const int numBytes = (getHighestBit() + 8) >> 3;
  2860. MemoryBlock mb ((size_t) numBytes);
  2861. for (int i = 0; i < numBytes; ++i)
  2862. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2863. return mb;
  2864. }
  2865. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2866. {
  2867. clear();
  2868. for (int i = (int) data.getSize(); --i >= 0;)
  2869. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2870. }
  2871. END_JUCE_NAMESPACE
  2872. /*** End of inlined file: juce_BigInteger.cpp ***/
  2873. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2874. BEGIN_JUCE_NAMESPACE
  2875. MemoryBlock::MemoryBlock() throw()
  2876. : size (0)
  2877. {
  2878. }
  2879. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2880. {
  2881. if (initialSize > 0)
  2882. {
  2883. size = initialSize;
  2884. data.allocate (initialSize, initialiseToZero);
  2885. }
  2886. else
  2887. {
  2888. size = 0;
  2889. }
  2890. }
  2891. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2892. : size (other.size)
  2893. {
  2894. if (size > 0)
  2895. {
  2896. jassert (other.data != 0);
  2897. data.malloc (size);
  2898. memcpy (data, other.data, size);
  2899. }
  2900. }
  2901. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2902. : size (jmax ((size_t) 0, sizeInBytes))
  2903. {
  2904. jassert (sizeInBytes >= 0);
  2905. if (size > 0)
  2906. {
  2907. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2908. data.malloc (size);
  2909. if (dataToInitialiseFrom != 0)
  2910. memcpy (data, dataToInitialiseFrom, size);
  2911. }
  2912. }
  2913. MemoryBlock::~MemoryBlock() throw()
  2914. {
  2915. jassert (size >= 0); // should never happen
  2916. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2917. }
  2918. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2919. {
  2920. if (this != &other)
  2921. {
  2922. setSize (other.size, false);
  2923. memcpy (data, other.data, size);
  2924. }
  2925. return *this;
  2926. }
  2927. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2928. {
  2929. return matches (other.data, other.size);
  2930. }
  2931. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2932. {
  2933. return ! operator== (other);
  2934. }
  2935. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2936. {
  2937. return size == dataSize
  2938. && memcmp (data, dataToCompare, size) == 0;
  2939. }
  2940. // this will resize the block to this size
  2941. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2942. {
  2943. if (size != newSize)
  2944. {
  2945. if (newSize <= 0)
  2946. {
  2947. data.free();
  2948. size = 0;
  2949. }
  2950. else
  2951. {
  2952. if (data != 0)
  2953. {
  2954. data.realloc (newSize);
  2955. if (initialiseToZero && (newSize > size))
  2956. zeromem (data + size, newSize - size);
  2957. }
  2958. else
  2959. {
  2960. data.allocate (newSize, initialiseToZero);
  2961. }
  2962. size = newSize;
  2963. }
  2964. }
  2965. }
  2966. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2967. {
  2968. if (size < minimumSize)
  2969. setSize (minimumSize, initialiseToZero);
  2970. }
  2971. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2972. {
  2973. swapVariables (size, other.size);
  2974. data.swapWith (other.data);
  2975. }
  2976. void MemoryBlock::fillWith (const uint8 value) throw()
  2977. {
  2978. memset (data, (int) value, size);
  2979. }
  2980. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2981. {
  2982. if (numBytes > 0)
  2983. {
  2984. const size_t oldSize = size;
  2985. setSize (size + numBytes);
  2986. memcpy (data + oldSize, srcData, numBytes);
  2987. }
  2988. }
  2989. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2990. {
  2991. const char* d = static_cast<const char*> (src);
  2992. if (offset < 0)
  2993. {
  2994. d -= offset;
  2995. num -= offset;
  2996. offset = 0;
  2997. }
  2998. if (offset + num > size)
  2999. num = size - offset;
  3000. if (num > 0)
  3001. memcpy (data + offset, d, num);
  3002. }
  3003. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  3004. {
  3005. char* d = static_cast<char*> (dst);
  3006. if (offset < 0)
  3007. {
  3008. zeromem (d, -offset);
  3009. d -= offset;
  3010. num += offset;
  3011. offset = 0;
  3012. }
  3013. if (offset + num > size)
  3014. {
  3015. const size_t newNum = size - offset;
  3016. zeromem (d + newNum, num - newNum);
  3017. num = newNum;
  3018. }
  3019. if (num > 0)
  3020. memcpy (d, data + offset, num);
  3021. }
  3022. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  3023. {
  3024. if (startByte + numBytesToRemove >= size)
  3025. {
  3026. setSize (startByte);
  3027. }
  3028. else if (numBytesToRemove > 0)
  3029. {
  3030. memmove (data + startByte,
  3031. data + startByte + numBytesToRemove,
  3032. size - (startByte + numBytesToRemove));
  3033. setSize (size - numBytesToRemove);
  3034. }
  3035. }
  3036. const String MemoryBlock::toString() const
  3037. {
  3038. return String (static_cast <const char*> (getData()), size);
  3039. }
  3040. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  3041. {
  3042. int res = 0;
  3043. size_t byte = bitRangeStart >> 3;
  3044. int offsetInByte = (int) bitRangeStart & 7;
  3045. size_t bitsSoFar = 0;
  3046. while (numBits > 0 && (size_t) byte < size)
  3047. {
  3048. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3049. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  3050. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  3051. bitsSoFar += bitsThisTime;
  3052. numBits -= bitsThisTime;
  3053. ++byte;
  3054. offsetInByte = 0;
  3055. }
  3056. return res;
  3057. }
  3058. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  3059. {
  3060. size_t byte = bitRangeStart >> 3;
  3061. int offsetInByte = (int) bitRangeStart & 7;
  3062. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3063. while (numBits > 0 && (size_t) byte < size)
  3064. {
  3065. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3066. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3067. const unsigned int tempBits = bitsToSet << offsetInByte;
  3068. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3069. ++byte;
  3070. numBits -= bitsThisTime;
  3071. bitsToSet >>= bitsThisTime;
  3072. mask >>= bitsThisTime;
  3073. offsetInByte = 0;
  3074. }
  3075. }
  3076. void MemoryBlock::loadFromHexString (const String& hex)
  3077. {
  3078. ensureSize (hex.length() >> 1);
  3079. char* dest = data;
  3080. int i = 0;
  3081. for (;;)
  3082. {
  3083. int byte = 0;
  3084. for (int loop = 2; --loop >= 0;)
  3085. {
  3086. byte <<= 4;
  3087. for (;;)
  3088. {
  3089. const juce_wchar c = hex [i++];
  3090. if (c >= '0' && c <= '9')
  3091. {
  3092. byte |= c - '0';
  3093. break;
  3094. }
  3095. else if (c >= 'a' && c <= 'z')
  3096. {
  3097. byte |= c - ('a' - 10);
  3098. break;
  3099. }
  3100. else if (c >= 'A' && c <= 'Z')
  3101. {
  3102. byte |= c - ('A' - 10);
  3103. break;
  3104. }
  3105. else if (c == 0)
  3106. {
  3107. setSize (static_cast <size_t> (dest - data));
  3108. return;
  3109. }
  3110. }
  3111. }
  3112. *dest++ = (char) byte;
  3113. }
  3114. }
  3115. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3116. const String MemoryBlock::toBase64Encoding() const
  3117. {
  3118. const size_t numChars = ((size << 3) + 5) / 6;
  3119. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3120. const int initialLen = destString.length();
  3121. destString.preallocateStorage (initialLen + 2 + numChars);
  3122. String::CharPointerType d (destString.getCharPointer());
  3123. d += initialLen;
  3124. d.write ('.');
  3125. for (size_t i = 0; i < numChars; ++i)
  3126. d.write (encodingTable [getBitRange (i * 6, 6)]);
  3127. d.writeNull();
  3128. return destString;
  3129. }
  3130. bool MemoryBlock::fromBase64Encoding (const String& s)
  3131. {
  3132. const int startPos = s.indexOfChar ('.') + 1;
  3133. if (startPos <= 0)
  3134. return false;
  3135. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3136. setSize (numBytesNeeded, true);
  3137. const int numChars = s.length() - startPos;
  3138. String::CharPointerType srcChars (s.getCharPointer());
  3139. srcChars += startPos;
  3140. int pos = 0;
  3141. for (int i = 0; i < numChars; ++i)
  3142. {
  3143. const char c = (char) srcChars.getAndAdvance();
  3144. for (int j = 0; j < 64; ++j)
  3145. {
  3146. if (encodingTable[j] == c)
  3147. {
  3148. setBitRange (pos, 6, j);
  3149. pos += 6;
  3150. break;
  3151. }
  3152. }
  3153. }
  3154. return true;
  3155. }
  3156. END_JUCE_NAMESPACE
  3157. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3158. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3159. BEGIN_JUCE_NAMESPACE
  3160. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3161. : properties (ignoreCaseOfKeyNames),
  3162. fallbackProperties (0),
  3163. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3164. {
  3165. }
  3166. PropertySet::PropertySet (const PropertySet& other)
  3167. : properties (other.properties),
  3168. fallbackProperties (other.fallbackProperties),
  3169. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3170. {
  3171. }
  3172. PropertySet& PropertySet::operator= (const PropertySet& other)
  3173. {
  3174. properties = other.properties;
  3175. fallbackProperties = other.fallbackProperties;
  3176. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3177. propertyChanged();
  3178. return *this;
  3179. }
  3180. PropertySet::~PropertySet()
  3181. {
  3182. }
  3183. void PropertySet::clear()
  3184. {
  3185. const ScopedLock sl (lock);
  3186. if (properties.size() > 0)
  3187. {
  3188. properties.clear();
  3189. propertyChanged();
  3190. }
  3191. }
  3192. const String PropertySet::getValue (const String& keyName,
  3193. const String& defaultValue) const throw()
  3194. {
  3195. const ScopedLock sl (lock);
  3196. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3197. if (index >= 0)
  3198. return properties.getAllValues() [index];
  3199. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3200. : defaultValue;
  3201. }
  3202. int PropertySet::getIntValue (const String& keyName,
  3203. const int defaultValue) const throw()
  3204. {
  3205. const ScopedLock sl (lock);
  3206. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3207. if (index >= 0)
  3208. return properties.getAllValues() [index].getIntValue();
  3209. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3210. : defaultValue;
  3211. }
  3212. double PropertySet::getDoubleValue (const String& keyName,
  3213. const double defaultValue) const throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3217. if (index >= 0)
  3218. return properties.getAllValues()[index].getDoubleValue();
  3219. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3220. : defaultValue;
  3221. }
  3222. bool PropertySet::getBoolValue (const String& keyName,
  3223. const bool defaultValue) const throw()
  3224. {
  3225. const ScopedLock sl (lock);
  3226. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3227. if (index >= 0)
  3228. return properties.getAllValues() [index].getIntValue() != 0;
  3229. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3230. : defaultValue;
  3231. }
  3232. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3233. {
  3234. return XmlDocument::parse (getValue (keyName));
  3235. }
  3236. void PropertySet::setValue (const String& keyName, const var& v)
  3237. {
  3238. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3239. if (keyName.isNotEmpty())
  3240. {
  3241. const String value (v.toString());
  3242. const ScopedLock sl (lock);
  3243. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3244. if (index < 0 || properties.getAllValues() [index] != value)
  3245. {
  3246. properties.set (keyName, value);
  3247. propertyChanged();
  3248. }
  3249. }
  3250. }
  3251. void PropertySet::removeValue (const String& keyName)
  3252. {
  3253. if (keyName.isNotEmpty())
  3254. {
  3255. const ScopedLock sl (lock);
  3256. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3257. if (index >= 0)
  3258. {
  3259. properties.remove (keyName);
  3260. propertyChanged();
  3261. }
  3262. }
  3263. }
  3264. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3265. {
  3266. setValue (keyName, xml == 0 ? var::null
  3267. : var (xml->createDocument (String::empty, true)));
  3268. }
  3269. bool PropertySet::containsKey (const String& keyName) const throw()
  3270. {
  3271. const ScopedLock sl (lock);
  3272. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3273. }
  3274. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3275. {
  3276. const ScopedLock sl (lock);
  3277. fallbackProperties = fallbackProperties_;
  3278. }
  3279. XmlElement* PropertySet::createXml (const String& nodeName) const
  3280. {
  3281. const ScopedLock sl (lock);
  3282. XmlElement* const xml = new XmlElement (nodeName);
  3283. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3284. {
  3285. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3286. e->setAttribute ("name", properties.getAllKeys()[i]);
  3287. e->setAttribute ("val", properties.getAllValues()[i]);
  3288. }
  3289. return xml;
  3290. }
  3291. void PropertySet::restoreFromXml (const XmlElement& xml)
  3292. {
  3293. const ScopedLock sl (lock);
  3294. clear();
  3295. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3296. {
  3297. if (e->hasAttribute ("name")
  3298. && e->hasAttribute ("val"))
  3299. {
  3300. properties.set (e->getStringAttribute ("name"),
  3301. e->getStringAttribute ("val"));
  3302. }
  3303. }
  3304. if (properties.size() > 0)
  3305. propertyChanged();
  3306. }
  3307. void PropertySet::propertyChanged()
  3308. {
  3309. }
  3310. END_JUCE_NAMESPACE
  3311. /*** End of inlined file: juce_PropertySet.cpp ***/
  3312. /*** Start of inlined file: juce_Identifier.cpp ***/
  3313. BEGIN_JUCE_NAMESPACE
  3314. StringPool& Identifier::getPool()
  3315. {
  3316. static StringPool pool;
  3317. return pool;
  3318. }
  3319. Identifier::Identifier() throw()
  3320. : name (0)
  3321. {
  3322. }
  3323. Identifier::Identifier (const Identifier& other) throw()
  3324. : name (other.name)
  3325. {
  3326. }
  3327. Identifier& Identifier::operator= (const Identifier& other) throw()
  3328. {
  3329. name = other.name;
  3330. return *this;
  3331. }
  3332. Identifier::Identifier (const String& name_)
  3333. : name (Identifier::getPool().getPooledString (name_))
  3334. {
  3335. /* An Identifier string must be suitable for use as a script variable or XML
  3336. attribute, so it can only contain this limited set of characters.. */
  3337. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3338. }
  3339. Identifier::Identifier (const char* const name_)
  3340. : name (Identifier::getPool().getPooledString (name_))
  3341. {
  3342. /* An Identifier string must be suitable for use as a script variable or XML
  3343. attribute, so it can only contain this limited set of characters.. */
  3344. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3345. }
  3346. Identifier::~Identifier()
  3347. {
  3348. }
  3349. END_JUCE_NAMESPACE
  3350. /*** End of inlined file: juce_Identifier.cpp ***/
  3351. /*** Start of inlined file: juce_Variant.cpp ***/
  3352. BEGIN_JUCE_NAMESPACE
  3353. class var::VariantType
  3354. {
  3355. public:
  3356. VariantType() {}
  3357. virtual ~VariantType() {}
  3358. virtual int toInt (const ValueUnion&) const { return 0; }
  3359. virtual double toDouble (const ValueUnion&) const { return 0; }
  3360. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3361. virtual bool toBool (const ValueUnion&) const { return false; }
  3362. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3363. virtual bool isVoid() const throw() { return false; }
  3364. virtual bool isInt() const throw() { return false; }
  3365. virtual bool isBool() const throw() { return false; }
  3366. virtual bool isDouble() const throw() { return false; }
  3367. virtual bool isString() const throw() { return false; }
  3368. virtual bool isObject() const throw() { return false; }
  3369. virtual bool isMethod() const throw() { return false; }
  3370. virtual void cleanUp (ValueUnion&) const throw() {}
  3371. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3372. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3373. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3374. };
  3375. class var::VariantType_Void : public var::VariantType
  3376. {
  3377. public:
  3378. VariantType_Void() {}
  3379. static const VariantType_Void instance;
  3380. bool isVoid() const throw() { return true; }
  3381. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3382. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3383. };
  3384. class var::VariantType_Int : public var::VariantType
  3385. {
  3386. public:
  3387. VariantType_Int() {}
  3388. static const VariantType_Int instance;
  3389. int toInt (const ValueUnion& data) const { return data.intValue; };
  3390. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3391. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3392. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3393. bool isInt() const throw() { return true; }
  3394. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3395. {
  3396. return otherType.toInt (otherData) == data.intValue;
  3397. }
  3398. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3399. {
  3400. output.writeCompressedInt (5);
  3401. output.writeByte (1);
  3402. output.writeInt (data.intValue);
  3403. }
  3404. };
  3405. class var::VariantType_Double : public var::VariantType
  3406. {
  3407. public:
  3408. VariantType_Double() {}
  3409. static const VariantType_Double instance;
  3410. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3411. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3412. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3413. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3414. bool isDouble() const throw() { return true; }
  3415. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3416. {
  3417. return otherType.toDouble (otherData) == data.doubleValue;
  3418. }
  3419. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3420. {
  3421. output.writeCompressedInt (9);
  3422. output.writeByte (4);
  3423. output.writeDouble (data.doubleValue);
  3424. }
  3425. };
  3426. class var::VariantType_Bool : public var::VariantType
  3427. {
  3428. public:
  3429. VariantType_Bool() {}
  3430. static const VariantType_Bool instance;
  3431. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3432. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3433. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3434. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3435. bool isBool() const throw() { return true; }
  3436. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3437. {
  3438. return otherType.toBool (otherData) == data.boolValue;
  3439. }
  3440. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3441. {
  3442. output.writeCompressedInt (1);
  3443. output.writeByte (data.boolValue ? 2 : 3);
  3444. }
  3445. };
  3446. class var::VariantType_String : public var::VariantType
  3447. {
  3448. public:
  3449. VariantType_String() {}
  3450. static const VariantType_String instance;
  3451. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3452. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3453. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3454. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3455. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3456. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3457. || data.stringValue->trim().equalsIgnoreCase ("true")
  3458. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3459. bool isString() const throw() { return true; }
  3460. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3461. {
  3462. return otherType.toString (otherData) == *data.stringValue;
  3463. }
  3464. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3465. {
  3466. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3467. output.writeCompressedInt (len + 1);
  3468. output.writeByte (5);
  3469. HeapBlock<char> temp (len);
  3470. data.stringValue->copyToUTF8 (temp, len);
  3471. output.write (temp, len);
  3472. }
  3473. };
  3474. class var::VariantType_Object : public var::VariantType
  3475. {
  3476. public:
  3477. VariantType_Object() {}
  3478. static const VariantType_Object instance;
  3479. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3480. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3481. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3482. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3483. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3484. bool isObject() const throw() { return true; }
  3485. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3486. {
  3487. return otherType.toObject (otherData) == data.objectValue;
  3488. }
  3489. void writeToStream (const ValueUnion&, OutputStream& output) const
  3490. {
  3491. jassertfalse; // Can't write an object to a stream!
  3492. output.writeCompressedInt (0);
  3493. }
  3494. };
  3495. class var::VariantType_Method : public var::VariantType
  3496. {
  3497. public:
  3498. VariantType_Method() {}
  3499. static const VariantType_Method instance;
  3500. const String toString (const ValueUnion&) const { return "Method"; }
  3501. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3502. bool isMethod() const throw() { return true; }
  3503. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3504. {
  3505. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3506. }
  3507. void writeToStream (const ValueUnion&, OutputStream& output) const
  3508. {
  3509. jassertfalse; // Can't write a method to a stream!
  3510. output.writeCompressedInt (0);
  3511. }
  3512. };
  3513. const var::VariantType_Void var::VariantType_Void::instance;
  3514. const var::VariantType_Int var::VariantType_Int::instance;
  3515. const var::VariantType_Bool var::VariantType_Bool::instance;
  3516. const var::VariantType_Double var::VariantType_Double::instance;
  3517. const var::VariantType_String var::VariantType_String::instance;
  3518. const var::VariantType_Object var::VariantType_Object::instance;
  3519. const var::VariantType_Method var::VariantType_Method::instance;
  3520. var::var() throw() : type (&VariantType_Void::instance)
  3521. {
  3522. }
  3523. var::~var() throw()
  3524. {
  3525. type->cleanUp (value);
  3526. }
  3527. const var var::null;
  3528. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3529. {
  3530. type->createCopy (value, valueToCopy.value);
  3531. }
  3532. var::var (const int value_) throw() : type (&VariantType_Int::instance)
  3533. {
  3534. value.intValue = value_;
  3535. }
  3536. var::var (const bool value_) throw() : type (&VariantType_Bool::instance)
  3537. {
  3538. value.boolValue = value_;
  3539. }
  3540. var::var (const double value_) throw() : type (&VariantType_Double::instance)
  3541. {
  3542. value.doubleValue = value_;
  3543. }
  3544. var::var (const String& value_) : type (&VariantType_String::instance)
  3545. {
  3546. value.stringValue = new String (value_);
  3547. }
  3548. var::var (const char* const value_) : type (&VariantType_String::instance)
  3549. {
  3550. value.stringValue = new String (value_);
  3551. }
  3552. var::var (const juce_wchar* const value_) : type (&VariantType_String::instance)
  3553. {
  3554. value.stringValue = new String (value_);
  3555. }
  3556. var::var (DynamicObject* const object) : type (&VariantType_Object::instance)
  3557. {
  3558. value.objectValue = object;
  3559. if (object != 0)
  3560. object->incReferenceCount();
  3561. }
  3562. var::var (MethodFunction method_) throw() : type (&VariantType_Method::instance)
  3563. {
  3564. value.methodValue = method_;
  3565. }
  3566. bool var::isVoid() const throw() { return type->isVoid(); }
  3567. bool var::isInt() const throw() { return type->isInt(); }
  3568. bool var::isBool() const throw() { return type->isBool(); }
  3569. bool var::isDouble() const throw() { return type->isDouble(); }
  3570. bool var::isString() const throw() { return type->isString(); }
  3571. bool var::isObject() const throw() { return type->isObject(); }
  3572. bool var::isMethod() const throw() { return type->isMethod(); }
  3573. var::operator int() const { return type->toInt (value); }
  3574. var::operator bool() const { return type->toBool (value); }
  3575. var::operator float() const { return (float) type->toDouble (value); }
  3576. var::operator double() const { return type->toDouble (value); }
  3577. const String var::toString() const { return type->toString (value); }
  3578. var::operator const String() const { return type->toString (value); }
  3579. DynamicObject* var::getObject() const { return type->toObject (value); }
  3580. void var::swapWith (var& other) throw()
  3581. {
  3582. swapVariables (type, other.type);
  3583. swapVariables (value, other.value);
  3584. }
  3585. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3586. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3587. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3588. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3589. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3590. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3591. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3592. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3593. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3594. bool var::equals (const var& other) const throw()
  3595. {
  3596. return type->equals (value, other.value, *other.type);
  3597. }
  3598. bool var::equalsWithSameType (const var& other) const throw()
  3599. {
  3600. return type == other.type && equals (other);
  3601. }
  3602. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3603. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3604. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3605. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3606. void var::writeToStream (OutputStream& output) const
  3607. {
  3608. type->writeToStream (value, output);
  3609. }
  3610. const var var::readFromStream (InputStream& input)
  3611. {
  3612. const int numBytes = input.readCompressedInt();
  3613. if (numBytes > 0)
  3614. {
  3615. switch (input.readByte())
  3616. {
  3617. case 1: return var (input.readInt());
  3618. case 2: return var (true);
  3619. case 3: return var (false);
  3620. case 4: return var (input.readDouble());
  3621. case 5:
  3622. {
  3623. MemoryOutputStream mo;
  3624. mo.writeFromInputStream (input, numBytes - 1);
  3625. return var (mo.toUTF8());
  3626. }
  3627. default: input.skipNextBytes (numBytes - 1); break;
  3628. }
  3629. }
  3630. return var::null;
  3631. }
  3632. const var var::operator[] (const Identifier& propertyName) const
  3633. {
  3634. DynamicObject* const o = getObject();
  3635. return o != 0 ? o->getProperty (propertyName) : var::null;
  3636. }
  3637. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3638. {
  3639. DynamicObject* const o = getObject();
  3640. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3641. }
  3642. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3643. {
  3644. if (isMethod())
  3645. {
  3646. DynamicObject* const target = targetObject.getObject();
  3647. if (target != 0)
  3648. return (target->*(value.methodValue)) (arguments, numArguments);
  3649. }
  3650. return var::null;
  3651. }
  3652. const var var::call (const Identifier& method) const
  3653. {
  3654. return invoke (method, 0, 0);
  3655. }
  3656. const var var::call (const Identifier& method, const var& arg1) const
  3657. {
  3658. return invoke (method, &arg1, 1);
  3659. }
  3660. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3661. {
  3662. var args[] = { arg1, arg2 };
  3663. return invoke (method, args, 2);
  3664. }
  3665. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3666. {
  3667. var args[] = { arg1, arg2, arg3 };
  3668. return invoke (method, args, 3);
  3669. }
  3670. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3671. {
  3672. var args[] = { arg1, arg2, arg3, arg4 };
  3673. return invoke (method, args, 4);
  3674. }
  3675. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3676. {
  3677. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3678. return invoke (method, args, 5);
  3679. }
  3680. END_JUCE_NAMESPACE
  3681. /*** End of inlined file: juce_Variant.cpp ***/
  3682. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3683. BEGIN_JUCE_NAMESPACE
  3684. NamedValueSet::NamedValue::NamedValue() throw()
  3685. {
  3686. }
  3687. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3688. : name (name_), value (value_)
  3689. {
  3690. }
  3691. NamedValueSet::NamedValue::NamedValue (const NamedValue& other)
  3692. : name (other.name), value (other.value)
  3693. {
  3694. }
  3695. NamedValueSet::NamedValue& NamedValueSet::NamedValue::operator= (const NamedValueSet::NamedValue& other)
  3696. {
  3697. name = other.name;
  3698. value = other.value;
  3699. return *this;
  3700. }
  3701. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3702. {
  3703. return name == other.name && value == other.value;
  3704. }
  3705. NamedValueSet::NamedValueSet() throw()
  3706. {
  3707. }
  3708. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3709. {
  3710. values.addCopyOfList (other.values);
  3711. }
  3712. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3713. {
  3714. clear();
  3715. values.addCopyOfList (other.values);
  3716. return *this;
  3717. }
  3718. NamedValueSet::~NamedValueSet()
  3719. {
  3720. clear();
  3721. }
  3722. void NamedValueSet::clear()
  3723. {
  3724. values.deleteAll();
  3725. }
  3726. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3727. {
  3728. const NamedValue* i1 = values;
  3729. const NamedValue* i2 = other.values;
  3730. while (i1 != 0 && i2 != 0)
  3731. {
  3732. if (! (*i1 == *i2))
  3733. return false;
  3734. i1 = i1->nextListItem;
  3735. i2 = i2->nextListItem;
  3736. }
  3737. return true;
  3738. }
  3739. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3740. {
  3741. return ! operator== (other);
  3742. }
  3743. int NamedValueSet::size() const throw()
  3744. {
  3745. return values.size();
  3746. }
  3747. const var& NamedValueSet::operator[] (const Identifier& name) const
  3748. {
  3749. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3750. if (i->name == name)
  3751. return i->value;
  3752. return var::null;
  3753. }
  3754. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3755. {
  3756. const var* v = getVarPointer (name);
  3757. return v != 0 ? *v : defaultReturnValue;
  3758. }
  3759. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3760. {
  3761. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3762. if (i->name == name)
  3763. return &(i->value);
  3764. return 0;
  3765. }
  3766. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3767. {
  3768. LinkedListPointer<NamedValue>* i = &values;
  3769. while (i->get() != 0)
  3770. {
  3771. NamedValue* const v = i->get();
  3772. if (v->name == name)
  3773. {
  3774. if (v->value == newValue)
  3775. return false;
  3776. v->value = newValue;
  3777. return true;
  3778. }
  3779. i = &(v->nextListItem);
  3780. }
  3781. i->insertNext (new NamedValue (name, newValue));
  3782. return true;
  3783. }
  3784. bool NamedValueSet::contains (const Identifier& name) const
  3785. {
  3786. return getVarPointer (name) != 0;
  3787. }
  3788. bool NamedValueSet::remove (const Identifier& name)
  3789. {
  3790. LinkedListPointer<NamedValue>* i = &values;
  3791. for (;;)
  3792. {
  3793. NamedValue* const v = i->get();
  3794. if (v == 0)
  3795. break;
  3796. if (v->name == name)
  3797. {
  3798. delete i->removeNext();
  3799. return true;
  3800. }
  3801. i = &(v->nextListItem);
  3802. }
  3803. return false;
  3804. }
  3805. const Identifier NamedValueSet::getName (const int index) const
  3806. {
  3807. const NamedValue* const v = values[index];
  3808. jassert (v != 0);
  3809. return v->name;
  3810. }
  3811. const var NamedValueSet::getValueAt (const int index) const
  3812. {
  3813. const NamedValue* const v = values[index];
  3814. jassert (v != 0);
  3815. return v->value;
  3816. }
  3817. void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
  3818. {
  3819. clear();
  3820. LinkedListPointer<NamedValue>::Appender appender (values);
  3821. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  3822. for (int i = 0; i < numAtts; ++i)
  3823. appender.append (new NamedValue (xml.getAttributeName (i), var (xml.getAttributeValue (i))));
  3824. }
  3825. void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
  3826. {
  3827. for (NamedValue* i = values; i != 0; i = i->nextListItem)
  3828. {
  3829. jassert (! i->value.isObject()); // DynamicObjects can't be stored as XML!
  3830. xml.setAttribute (i->name.toString(),
  3831. i->value.toString());
  3832. }
  3833. }
  3834. END_JUCE_NAMESPACE
  3835. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3836. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3837. BEGIN_JUCE_NAMESPACE
  3838. DynamicObject::DynamicObject()
  3839. {
  3840. }
  3841. DynamicObject::~DynamicObject()
  3842. {
  3843. }
  3844. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3845. {
  3846. var* const v = properties.getVarPointer (propertyName);
  3847. return v != 0 && ! v->isMethod();
  3848. }
  3849. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3850. {
  3851. return properties [propertyName];
  3852. }
  3853. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3854. {
  3855. properties.set (propertyName, newValue);
  3856. }
  3857. void DynamicObject::removeProperty (const Identifier& propertyName)
  3858. {
  3859. properties.remove (propertyName);
  3860. }
  3861. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3862. {
  3863. return getProperty (methodName).isMethod();
  3864. }
  3865. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3866. const var* parameters,
  3867. int numParameters)
  3868. {
  3869. return properties [methodName].invoke (var (this), parameters, numParameters);
  3870. }
  3871. void DynamicObject::setMethod (const Identifier& name,
  3872. var::MethodFunction methodFunction)
  3873. {
  3874. properties.set (name, var (methodFunction));
  3875. }
  3876. void DynamicObject::clear()
  3877. {
  3878. properties.clear();
  3879. }
  3880. END_JUCE_NAMESPACE
  3881. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3882. /*** Start of inlined file: juce_Expression.cpp ***/
  3883. BEGIN_JUCE_NAMESPACE
  3884. class Expression::Term : public ReferenceCountedObject
  3885. {
  3886. public:
  3887. Term() {}
  3888. virtual ~Term() {}
  3889. virtual Type getType() const throw() = 0;
  3890. virtual Term* clone() const = 0;
  3891. virtual const ReferenceCountedObjectPtr<Term> resolve (const Scope&, int recursionDepth) = 0;
  3892. virtual const String toString() const = 0;
  3893. virtual double toDouble() const { return 0; }
  3894. virtual int getInputIndexFor (const Term*) const { return -1; }
  3895. virtual int getOperatorPrecedence() const { return 0; }
  3896. virtual int getNumInputs() const { return 0; }
  3897. virtual Term* getInput (int) const { return 0; }
  3898. virtual const ReferenceCountedObjectPtr<Term> negated();
  3899. virtual const ReferenceCountedObjectPtr<Term> createTermToEvaluateInput (const Scope&, const Term* /*inputTerm*/,
  3900. double /*overallTarget*/, Term* /*topLevelTerm*/) const
  3901. {
  3902. jassertfalse;
  3903. return 0;
  3904. }
  3905. virtual const String getName() const
  3906. {
  3907. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  3908. return String::empty;
  3909. }
  3910. virtual void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  3911. {
  3912. for (int i = getNumInputs(); --i >= 0;)
  3913. getInput (i)->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  3914. }
  3915. class SymbolVisitor
  3916. {
  3917. public:
  3918. virtual ~SymbolVisitor() {}
  3919. virtual void useSymbol (const Symbol&) = 0;
  3920. };
  3921. virtual void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  3922. {
  3923. for (int i = getNumInputs(); --i >= 0;)
  3924. getInput(i)->visitAllSymbols (visitor, scope, recursionDepth);
  3925. }
  3926. private:
  3927. JUCE_DECLARE_NON_COPYABLE (Term);
  3928. };
  3929. class Expression::Helpers
  3930. {
  3931. public:
  3932. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3933. // This helper function is needed to work around VC6 scoping bugs
  3934. static inline const TermPtr& getTermFor (const Expression& exp) throw() { return exp.term; }
  3935. static void checkRecursionDepth (const int depth)
  3936. {
  3937. if (depth > 256)
  3938. throw EvaluationError ("Recursive symbol references");
  3939. }
  3940. friend class Expression::Term; // (also only needed as a VC6 workaround)
  3941. /** An exception that can be thrown by Expression::evaluate(). */
  3942. class EvaluationError : public std::exception
  3943. {
  3944. public:
  3945. EvaluationError (const String& description_)
  3946. : description (description_)
  3947. {
  3948. DBG ("Expression::EvaluationError: " + description);
  3949. }
  3950. String description;
  3951. };
  3952. class Constant : public Term
  3953. {
  3954. public:
  3955. Constant (const double value_, const bool isResolutionTarget_)
  3956. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3957. Type getType() const throw() { return constantType; }
  3958. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3959. const TermPtr resolve (const Scope&, int) { return this; }
  3960. double toDouble() const { return value; }
  3961. const TermPtr negated() { return new Constant (-value, isResolutionTarget); }
  3962. const String toString() const
  3963. {
  3964. String s (value);
  3965. if (isResolutionTarget)
  3966. s = "@" + s;
  3967. return s;
  3968. }
  3969. double value;
  3970. bool isResolutionTarget;
  3971. };
  3972. class BinaryTerm : public Term
  3973. {
  3974. public:
  3975. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3976. {
  3977. jassert (left_ != 0 && right_ != 0);
  3978. }
  3979. int getInputIndexFor (const Term* possibleInput) const
  3980. {
  3981. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3982. }
  3983. Type getType() const throw() { return operatorType; }
  3984. int getNumInputs() const { return 2; }
  3985. Term* getInput (int index) const { return index == 0 ? left.getObject() : (index == 1 ? right.getObject() : 0); }
  3986. virtual double performFunction (double left, double right) const = 0;
  3987. virtual void writeOperator (String& dest) const = 0;
  3988. const TermPtr resolve (const Scope& scope, int recursionDepth)
  3989. {
  3990. return new Constant (performFunction (left->resolve (scope, recursionDepth)->toDouble(),
  3991. right->resolve (scope, recursionDepth)->toDouble()), false);
  3992. }
  3993. const String toString() const
  3994. {
  3995. String s;
  3996. const int ourPrecendence = getOperatorPrecedence();
  3997. if (left->getOperatorPrecedence() > ourPrecendence)
  3998. s << '(' << left->toString() << ')';
  3999. else
  4000. s = left->toString();
  4001. writeOperator (s);
  4002. if (right->getOperatorPrecedence() >= ourPrecendence)
  4003. s << '(' << right->toString() << ')';
  4004. else
  4005. s << right->toString();
  4006. return s;
  4007. }
  4008. protected:
  4009. const TermPtr left, right;
  4010. const TermPtr createDestinationTerm (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4011. {
  4012. jassert (input == left || input == right);
  4013. if (input != left && input != right)
  4014. return 0;
  4015. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4016. if (dest == 0)
  4017. return new Constant (overallTarget, false);
  4018. return dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm);
  4019. }
  4020. };
  4021. class SymbolTerm : public Term
  4022. {
  4023. public:
  4024. explicit SymbolTerm (const String& symbol_) : symbol (symbol_) {}
  4025. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4026. {
  4027. checkRecursionDepth (recursionDepth);
  4028. return getTermFor (scope.getSymbolValue (symbol))->resolve (scope, recursionDepth + 1);
  4029. }
  4030. Type getType() const throw() { return symbolType; }
  4031. Term* clone() const { return new SymbolTerm (symbol); }
  4032. const String toString() const { return symbol; }
  4033. const String getName() const { return symbol; }
  4034. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4035. {
  4036. checkRecursionDepth (recursionDepth);
  4037. visitor.useSymbol (Symbol (scope.getScopeUID(), symbol));
  4038. getTermFor (scope.getSymbolValue (symbol))->visitAllSymbols (visitor, scope, recursionDepth + 1);
  4039. }
  4040. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int /*recursionDepth*/)
  4041. {
  4042. if (oldSymbol.symbolName == symbol && scope.getScopeUID() == oldSymbol.scopeUID)
  4043. symbol = newName;
  4044. }
  4045. String symbol;
  4046. };
  4047. class Function : public Term
  4048. {
  4049. public:
  4050. explicit Function (const String& functionName_) : functionName (functionName_) {}
  4051. Function (const String& functionName_, const Array<Expression>& parameters_)
  4052. : functionName (functionName_), parameters (parameters_)
  4053. {}
  4054. Type getType() const throw() { return functionType; }
  4055. Term* clone() const { return new Function (functionName, parameters); }
  4056. int getNumInputs() const { return parameters.size(); }
  4057. Term* getInput (int i) const { return getTermFor (parameters [i]); }
  4058. const String getName() const { return functionName; }
  4059. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4060. {
  4061. checkRecursionDepth (recursionDepth);
  4062. double result = 0;
  4063. const int numParams = parameters.size();
  4064. if (numParams > 0)
  4065. {
  4066. HeapBlock<double> params (numParams);
  4067. for (int i = 0; i < numParams; ++i)
  4068. params[i] = getTermFor (parameters.getReference(i))->resolve (scope, recursionDepth + 1)->toDouble();
  4069. result = scope.evaluateFunction (functionName, params, numParams);
  4070. }
  4071. else
  4072. {
  4073. result = scope.evaluateFunction (functionName, 0, 0);
  4074. }
  4075. return new Constant (result, false);
  4076. }
  4077. int getInputIndexFor (const Term* possibleInput) const
  4078. {
  4079. for (int i = 0; i < parameters.size(); ++i)
  4080. if (getTermFor (parameters.getReference(i)) == possibleInput)
  4081. return i;
  4082. return -1;
  4083. }
  4084. const String toString() const
  4085. {
  4086. if (parameters.size() == 0)
  4087. return functionName + "()";
  4088. String s (functionName + " (");
  4089. for (int i = 0; i < parameters.size(); ++i)
  4090. {
  4091. s << getTermFor (parameters.getReference(i))->toString();
  4092. if (i < parameters.size() - 1)
  4093. s << ", ";
  4094. }
  4095. s << ')';
  4096. return s;
  4097. }
  4098. const String functionName;
  4099. Array<Expression> parameters;
  4100. };
  4101. class DotOperator : public BinaryTerm
  4102. {
  4103. public:
  4104. DotOperator (SymbolTerm* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4105. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4106. {
  4107. checkRecursionDepth (recursionDepth);
  4108. EvaluationVisitor visitor (right, recursionDepth + 1);
  4109. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4110. return visitor.output;
  4111. }
  4112. Term* clone() const { return new DotOperator (getSymbol(), right); }
  4113. const String getName() const { return "."; }
  4114. int getOperatorPrecedence() const { return 1; }
  4115. void writeOperator (String& dest) const { dest << '.'; }
  4116. double performFunction (double, double) const { return 0.0; }
  4117. void visitAllSymbols (SymbolVisitor& visitor, const Scope& scope, int recursionDepth)
  4118. {
  4119. checkRecursionDepth (recursionDepth);
  4120. visitor.useSymbol (Symbol (scope.getScopeUID(), getSymbol()->symbol));
  4121. SymbolVisitingVisitor v (right, visitor, recursionDepth + 1);
  4122. try
  4123. {
  4124. scope.visitRelativeScope (getSymbol()->symbol, v);
  4125. }
  4126. catch (...) {}
  4127. }
  4128. void renameSymbol (const Symbol& oldSymbol, const String& newName, const Scope& scope, int recursionDepth)
  4129. {
  4130. checkRecursionDepth (recursionDepth);
  4131. getSymbol()->renameSymbol (oldSymbol, newName, scope, recursionDepth);
  4132. SymbolRenamingVisitor visitor (right, oldSymbol, newName, recursionDepth + 1);
  4133. try
  4134. {
  4135. scope.visitRelativeScope (getSymbol()->symbol, visitor);
  4136. }
  4137. catch (...) {}
  4138. }
  4139. private:
  4140. class EvaluationVisitor : public Scope::Visitor
  4141. {
  4142. public:
  4143. EvaluationVisitor (const TermPtr& input_, const int recursionCount_)
  4144. : input (input_), output (input_), recursionCount (recursionCount_) {}
  4145. void visit (const Scope& scope) { output = input->resolve (scope, recursionCount); }
  4146. const TermPtr input;
  4147. TermPtr output;
  4148. const int recursionCount;
  4149. private:
  4150. JUCE_DECLARE_NON_COPYABLE (EvaluationVisitor);
  4151. };
  4152. class SymbolVisitingVisitor : public Scope::Visitor
  4153. {
  4154. public:
  4155. SymbolVisitingVisitor (const TermPtr& input_, SymbolVisitor& visitor_, const int recursionCount_)
  4156. : input (input_), visitor (visitor_), recursionCount (recursionCount_) {}
  4157. void visit (const Scope& scope) { input->visitAllSymbols (visitor, scope, recursionCount); }
  4158. private:
  4159. const TermPtr input;
  4160. SymbolVisitor& visitor;
  4161. const int recursionCount;
  4162. JUCE_DECLARE_NON_COPYABLE (SymbolVisitingVisitor);
  4163. };
  4164. class SymbolRenamingVisitor : public Scope::Visitor
  4165. {
  4166. public:
  4167. SymbolRenamingVisitor (const TermPtr& input_, const Expression::Symbol& symbol_, const String& newName_, const int recursionCount_)
  4168. : input (input_), symbol (symbol_), newName (newName_), recursionCount (recursionCount_) {}
  4169. void visit (const Scope& scope) { input->renameSymbol (symbol, newName, scope, recursionCount); }
  4170. private:
  4171. const TermPtr input;
  4172. const Symbol& symbol;
  4173. const String newName;
  4174. const int recursionCount;
  4175. JUCE_DECLARE_NON_COPYABLE (SymbolRenamingVisitor);
  4176. };
  4177. SymbolTerm* getSymbol() const { return static_cast <SymbolTerm*> (left.getObject()); }
  4178. JUCE_DECLARE_NON_COPYABLE (DotOperator);
  4179. };
  4180. class Negate : public Term
  4181. {
  4182. public:
  4183. explicit Negate (const TermPtr& input_) : input (input_)
  4184. {
  4185. jassert (input_ != 0);
  4186. }
  4187. Type getType() const throw() { return operatorType; }
  4188. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  4189. int getNumInputs() const { return 1; }
  4190. Term* getInput (int index) const { return index == 0 ? input.getObject() : 0; }
  4191. Term* clone() const { return new Negate (input->clone()); }
  4192. const TermPtr resolve (const Scope& scope, int recursionDepth)
  4193. {
  4194. return new Constant (-input->resolve (scope, recursionDepth)->toDouble(), false);
  4195. }
  4196. const String getName() const { return "-"; }
  4197. const TermPtr negated() { return input; }
  4198. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input_, double overallTarget, Term* topLevelTerm) const
  4199. {
  4200. (void) input_;
  4201. jassert (input_ == input);
  4202. const Term* const dest = findDestinationFor (topLevelTerm, this);
  4203. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  4204. : dest->createTermToEvaluateInput (scope, this, overallTarget, topLevelTerm));
  4205. }
  4206. const String toString() const
  4207. {
  4208. if (input->getOperatorPrecedence() > 0)
  4209. return "-(" + input->toString() + ")";
  4210. else
  4211. return "-" + input->toString();
  4212. }
  4213. private:
  4214. const TermPtr input;
  4215. };
  4216. class Add : public BinaryTerm
  4217. {
  4218. public:
  4219. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4220. Term* clone() const { return new Add (left->clone(), right->clone()); }
  4221. double performFunction (double lhs, double rhs) const { return lhs + rhs; }
  4222. int getOperatorPrecedence() const { return 3; }
  4223. const String getName() const { return "+"; }
  4224. void writeOperator (String& dest) const { dest << " + "; }
  4225. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4226. {
  4227. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4228. if (newDest == 0)
  4229. return 0;
  4230. return new Subtract (newDest, (input == left ? right : left)->clone());
  4231. }
  4232. private:
  4233. JUCE_DECLARE_NON_COPYABLE (Add);
  4234. };
  4235. class Subtract : public BinaryTerm
  4236. {
  4237. public:
  4238. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4239. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4240. double performFunction (double lhs, double rhs) const { return lhs - rhs; }
  4241. int getOperatorPrecedence() const { return 3; }
  4242. const String getName() const { return "-"; }
  4243. void writeOperator (String& dest) const { dest << " - "; }
  4244. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4245. {
  4246. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4247. if (newDest == 0)
  4248. return 0;
  4249. if (input == left)
  4250. return new Add (newDest, right->clone());
  4251. else
  4252. return new Subtract (left->clone(), newDest);
  4253. }
  4254. private:
  4255. JUCE_DECLARE_NON_COPYABLE (Subtract);
  4256. };
  4257. class Multiply : public BinaryTerm
  4258. {
  4259. public:
  4260. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4261. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4262. double performFunction (double lhs, double rhs) const { return lhs * rhs; }
  4263. const String getName() const { return "*"; }
  4264. void writeOperator (String& dest) const { dest << " * "; }
  4265. int getOperatorPrecedence() const { return 2; }
  4266. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4267. {
  4268. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4269. if (newDest == 0)
  4270. return 0;
  4271. return new Divide (newDest, (input == left ? right : left)->clone());
  4272. }
  4273. private:
  4274. JUCE_DECLARE_NON_COPYABLE (Multiply);
  4275. };
  4276. class Divide : public BinaryTerm
  4277. {
  4278. public:
  4279. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4280. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4281. double performFunction (double lhs, double rhs) const { return lhs / rhs; }
  4282. const String getName() const { return "/"; }
  4283. void writeOperator (String& dest) const { dest << " / "; }
  4284. int getOperatorPrecedence() const { return 2; }
  4285. const TermPtr createTermToEvaluateInput (const Scope& scope, const Term* input, double overallTarget, Term* topLevelTerm) const
  4286. {
  4287. const TermPtr newDest (createDestinationTerm (scope, input, overallTarget, topLevelTerm));
  4288. if (newDest == 0)
  4289. return 0;
  4290. if (input == left)
  4291. return new Multiply (newDest, right->clone());
  4292. else
  4293. return new Divide (left->clone(), newDest);
  4294. }
  4295. private:
  4296. JUCE_DECLARE_NON_COPYABLE (Divide);
  4297. };
  4298. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4299. {
  4300. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4301. if (inputIndex >= 0)
  4302. return topLevel;
  4303. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4304. {
  4305. Term* const t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4306. if (t != 0)
  4307. return t;
  4308. }
  4309. return 0;
  4310. }
  4311. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4312. {
  4313. {
  4314. Constant* const c = dynamic_cast<Constant*> (term);
  4315. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4316. return c;
  4317. }
  4318. if (dynamic_cast<Function*> (term) != 0)
  4319. return 0;
  4320. int i;
  4321. const int numIns = term->getNumInputs();
  4322. for (i = 0; i < numIns; ++i)
  4323. {
  4324. Constant* const c = dynamic_cast<Constant*> (term->getInput (i));
  4325. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4326. return c;
  4327. }
  4328. for (i = 0; i < numIns; ++i)
  4329. {
  4330. Constant* const c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4331. if (c != 0)
  4332. return c;
  4333. }
  4334. return 0;
  4335. }
  4336. static bool containsAnySymbols (const Term* const t)
  4337. {
  4338. if (t->getType() == Expression::symbolType)
  4339. return true;
  4340. for (int i = t->getNumInputs(); --i >= 0;)
  4341. if (containsAnySymbols (t->getInput (i)))
  4342. return true;
  4343. return false;
  4344. }
  4345. class SymbolCheckVisitor : public Term::SymbolVisitor
  4346. {
  4347. public:
  4348. SymbolCheckVisitor (const Symbol& symbol_) : wasFound (false), symbol (symbol_) {}
  4349. void useSymbol (const Symbol& s) { wasFound = wasFound || s == symbol; }
  4350. bool wasFound;
  4351. private:
  4352. const Symbol& symbol;
  4353. JUCE_DECLARE_NON_COPYABLE (SymbolCheckVisitor);
  4354. };
  4355. class SymbolListVisitor : public Term::SymbolVisitor
  4356. {
  4357. public:
  4358. SymbolListVisitor (Array<Symbol>& list_) : list (list_) {}
  4359. void useSymbol (const Symbol& s) { list.addIfNotAlreadyThere (s); }
  4360. private:
  4361. Array<Symbol>& list;
  4362. JUCE_DECLARE_NON_COPYABLE (SymbolListVisitor);
  4363. };
  4364. class Parser
  4365. {
  4366. public:
  4367. Parser (String::CharPointerType& stringToParse)
  4368. : text (stringToParse)
  4369. {
  4370. }
  4371. const TermPtr readUpToComma()
  4372. {
  4373. if (text.isEmpty())
  4374. return new Constant (0.0, false);
  4375. const TermPtr e (readExpression());
  4376. if (e == 0 || ((! readOperator (",")) && ! text.isEmpty()))
  4377. throw ParseError ("Syntax error: \"" + String (text) + "\"");
  4378. return e;
  4379. }
  4380. private:
  4381. String::CharPointerType& text;
  4382. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4383. {
  4384. return c >= '0' && c <= '9';
  4385. }
  4386. bool readChar (const juce_wchar required) throw()
  4387. {
  4388. if (*text == required)
  4389. {
  4390. ++text;
  4391. return true;
  4392. }
  4393. return false;
  4394. }
  4395. bool readOperator (const char* ops, char* const opType = 0) throw()
  4396. {
  4397. text = text.findEndOfWhitespace();
  4398. while (*ops != 0)
  4399. {
  4400. if (readChar (*ops))
  4401. {
  4402. if (opType != 0)
  4403. *opType = *ops;
  4404. return true;
  4405. }
  4406. ++ops;
  4407. }
  4408. return false;
  4409. }
  4410. bool readIdentifier (String& identifier) throw()
  4411. {
  4412. text = text.findEndOfWhitespace();
  4413. String::CharPointerType t (text);
  4414. int numChars = 0;
  4415. if (t.isLetter() || *t == '_')
  4416. {
  4417. ++t;
  4418. ++numChars;
  4419. while (t.isLetterOrDigit() || *t == '_')
  4420. {
  4421. ++t;
  4422. ++numChars;
  4423. }
  4424. }
  4425. if (numChars > 0)
  4426. {
  4427. identifier = String (text, numChars);
  4428. text = t;
  4429. return true;
  4430. }
  4431. return false;
  4432. }
  4433. Term* readNumber() throw()
  4434. {
  4435. text = text.findEndOfWhitespace();
  4436. String::CharPointerType t (text);
  4437. const bool isResolutionTarget = (*t == '@');
  4438. if (isResolutionTarget)
  4439. {
  4440. ++t;
  4441. t = t.findEndOfWhitespace();
  4442. text = t;
  4443. }
  4444. if (*t == '-')
  4445. {
  4446. ++t;
  4447. t = t.findEndOfWhitespace();
  4448. }
  4449. if (isDecimalDigit (*t) || (*t == '.' && isDecimalDigit (t[1])))
  4450. return new Constant (CharacterFunctions::readDoubleValue (text), isResolutionTarget);
  4451. return 0;
  4452. }
  4453. const TermPtr readExpression()
  4454. {
  4455. TermPtr lhs (readMultiplyOrDivideExpression());
  4456. char opType;
  4457. while (lhs != 0 && readOperator ("+-", &opType))
  4458. {
  4459. TermPtr rhs (readMultiplyOrDivideExpression());
  4460. if (rhs == 0)
  4461. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4462. if (opType == '+')
  4463. lhs = new Add (lhs, rhs);
  4464. else
  4465. lhs = new Subtract (lhs, rhs);
  4466. }
  4467. return lhs;
  4468. }
  4469. const TermPtr readMultiplyOrDivideExpression()
  4470. {
  4471. TermPtr lhs (readUnaryExpression());
  4472. char opType;
  4473. while (lhs != 0 && readOperator ("*/", &opType))
  4474. {
  4475. TermPtr rhs (readUnaryExpression());
  4476. if (rhs == 0)
  4477. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4478. if (opType == '*')
  4479. lhs = new Multiply (lhs, rhs);
  4480. else
  4481. lhs = new Divide (lhs, rhs);
  4482. }
  4483. return lhs;
  4484. }
  4485. const TermPtr readUnaryExpression()
  4486. {
  4487. char opType;
  4488. if (readOperator ("+-", &opType))
  4489. {
  4490. TermPtr term (readUnaryExpression());
  4491. if (term == 0)
  4492. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4493. if (opType == '-')
  4494. term = term->negated();
  4495. return term;
  4496. }
  4497. return readPrimaryExpression();
  4498. }
  4499. const TermPtr readPrimaryExpression()
  4500. {
  4501. TermPtr e (readParenthesisedExpression());
  4502. if (e != 0)
  4503. return e;
  4504. e = readNumber();
  4505. if (e != 0)
  4506. return e;
  4507. return readSymbolOrFunction();
  4508. }
  4509. const TermPtr readSymbolOrFunction()
  4510. {
  4511. String identifier;
  4512. if (readIdentifier (identifier))
  4513. {
  4514. if (readOperator ("(")) // method call...
  4515. {
  4516. Function* const f = new Function (identifier);
  4517. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4518. TermPtr param (readExpression());
  4519. if (param == 0)
  4520. {
  4521. if (readOperator (")"))
  4522. return func.release();
  4523. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4524. }
  4525. f->parameters.add (Expression (param));
  4526. while (readOperator (","))
  4527. {
  4528. param = readExpression();
  4529. if (param == 0)
  4530. throw ParseError ("Expected expression after \",\"");
  4531. f->parameters.add (Expression (param));
  4532. }
  4533. if (readOperator (")"))
  4534. return func.release();
  4535. throw ParseError ("Expected \")\"");
  4536. }
  4537. else if (readOperator ("."))
  4538. {
  4539. TermPtr rhs (readSymbolOrFunction());
  4540. if (rhs == 0)
  4541. throw ParseError ("Expected symbol or function after \".\"");
  4542. if (identifier == "this")
  4543. return rhs;
  4544. return new DotOperator (new SymbolTerm (identifier), rhs);
  4545. }
  4546. else // just a symbol..
  4547. {
  4548. jassert (identifier.trim() == identifier);
  4549. return new SymbolTerm (identifier);
  4550. }
  4551. }
  4552. return 0;
  4553. }
  4554. const TermPtr readParenthesisedExpression()
  4555. {
  4556. if (! readOperator ("("))
  4557. return 0;
  4558. const TermPtr e (readExpression());
  4559. if (e == 0 || ! readOperator (")"))
  4560. return 0;
  4561. return e;
  4562. }
  4563. JUCE_DECLARE_NON_COPYABLE (Parser);
  4564. };
  4565. };
  4566. Expression::Expression()
  4567. : term (new Expression::Helpers::Constant (0, false))
  4568. {
  4569. }
  4570. Expression::~Expression()
  4571. {
  4572. }
  4573. Expression::Expression (Term* const term_)
  4574. : term (term_)
  4575. {
  4576. jassert (term != 0);
  4577. }
  4578. Expression::Expression (const double constant)
  4579. : term (new Expression::Helpers::Constant (constant, false))
  4580. {
  4581. }
  4582. Expression::Expression (const Expression& other)
  4583. : term (other.term)
  4584. {
  4585. }
  4586. Expression& Expression::operator= (const Expression& other)
  4587. {
  4588. term = other.term;
  4589. return *this;
  4590. }
  4591. Expression::Expression (const String& stringToParse)
  4592. {
  4593. String::CharPointerType text (stringToParse.getCharPointer());
  4594. Helpers::Parser parser (text);
  4595. term = parser.readUpToComma();
  4596. }
  4597. const Expression Expression::parse (String::CharPointerType& stringToParse)
  4598. {
  4599. Helpers::Parser parser (stringToParse);
  4600. return Expression (parser.readUpToComma());
  4601. }
  4602. double Expression::evaluate() const
  4603. {
  4604. return evaluate (Expression::Scope());
  4605. }
  4606. double Expression::evaluate (const Expression::Scope& scope) const
  4607. {
  4608. try
  4609. {
  4610. return term->resolve (scope, 0)->toDouble();
  4611. }
  4612. catch (Helpers::EvaluationError&)
  4613. {}
  4614. return 0;
  4615. }
  4616. double Expression::evaluate (const Scope& scope, String& evaluationError) const
  4617. {
  4618. try
  4619. {
  4620. return term->resolve (scope, 0)->toDouble();
  4621. }
  4622. catch (Helpers::EvaluationError& e)
  4623. {
  4624. evaluationError = e.description;
  4625. }
  4626. return 0;
  4627. }
  4628. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4629. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4630. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4631. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4632. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4633. const Expression Expression::symbol (const String& symbol) { return Expression (new Helpers::SymbolTerm (symbol)); }
  4634. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4635. {
  4636. return Expression (new Helpers::Function (functionName, parameters));
  4637. }
  4638. const Expression Expression::adjustedToGiveNewResult (const double targetValue, const Expression::Scope& scope) const
  4639. {
  4640. ScopedPointer<Term> newTerm (term->clone());
  4641. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4642. if (termToAdjust == 0)
  4643. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4644. if (termToAdjust == 0)
  4645. {
  4646. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4647. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4648. }
  4649. jassert (termToAdjust != 0);
  4650. const Term* const parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4651. if (parent == 0)
  4652. {
  4653. termToAdjust->value = targetValue;
  4654. }
  4655. else
  4656. {
  4657. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (scope, termToAdjust, targetValue, newTerm));
  4658. if (reverseTerm == 0)
  4659. return Expression (targetValue);
  4660. termToAdjust->value = reverseTerm->resolve (scope, 0)->toDouble();
  4661. }
  4662. return Expression (newTerm.release());
  4663. }
  4664. const Expression Expression::withRenamedSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Scope& scope) const
  4665. {
  4666. jassert (newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4667. if (oldSymbol.symbolName == newName)
  4668. return *this;
  4669. Expression e (term->clone());
  4670. e.term->renameSymbol (oldSymbol, newName, scope, 0);
  4671. return e;
  4672. }
  4673. bool Expression::referencesSymbol (const Expression::Symbol& symbol, const Scope& scope) const
  4674. {
  4675. Helpers::SymbolCheckVisitor visitor (symbol);
  4676. try
  4677. {
  4678. term->visitAllSymbols (visitor, scope, 0);
  4679. }
  4680. catch (Helpers::EvaluationError&)
  4681. {}
  4682. return visitor.wasFound;
  4683. }
  4684. void Expression::findReferencedSymbols (Array<Symbol>& results, const Scope& scope) const
  4685. {
  4686. try
  4687. {
  4688. Helpers::SymbolListVisitor visitor (results);
  4689. term->visitAllSymbols (visitor, scope, 0);
  4690. }
  4691. catch (Helpers::EvaluationError&)
  4692. {}
  4693. }
  4694. const String Expression::toString() const { return term->toString(); }
  4695. bool Expression::usesAnySymbols() const { return Helpers::containsAnySymbols (term); }
  4696. Expression::Type Expression::getType() const throw() { return term->getType(); }
  4697. const String Expression::getSymbolOrFunction() const { return term->getName(); }
  4698. int Expression::getNumInputs() const { return term->getNumInputs(); }
  4699. const Expression Expression::getInput (int index) const { return Expression (term->getInput (index)); }
  4700. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4701. {
  4702. return new Helpers::Negate (this);
  4703. }
  4704. Expression::ParseError::ParseError (const String& message)
  4705. : description (message)
  4706. {
  4707. DBG ("Expression::ParseError: " + message);
  4708. }
  4709. Expression::Symbol::Symbol (const String& scopeUID_, const String& symbolName_)
  4710. : scopeUID (scopeUID_), symbolName (symbolName_)
  4711. {
  4712. }
  4713. bool Expression::Symbol::operator== (const Symbol& other) const throw()
  4714. {
  4715. return symbolName == other.symbolName && scopeUID == other.scopeUID;
  4716. }
  4717. bool Expression::Symbol::operator!= (const Symbol& other) const throw()
  4718. {
  4719. return ! operator== (other);
  4720. }
  4721. Expression::Scope::Scope() {}
  4722. Expression::Scope::~Scope() {}
  4723. const Expression Expression::Scope::getSymbolValue (const String& symbol) const
  4724. {
  4725. throw Helpers::EvaluationError ("Unknown symbol: " + symbol);
  4726. }
  4727. double Expression::Scope::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4728. {
  4729. if (numParams > 0)
  4730. {
  4731. if (functionName == "min")
  4732. {
  4733. double v = parameters[0];
  4734. for (int i = 1; i < numParams; ++i)
  4735. v = jmin (v, parameters[i]);
  4736. return v;
  4737. }
  4738. else if (functionName == "max")
  4739. {
  4740. double v = parameters[0];
  4741. for (int i = 1; i < numParams; ++i)
  4742. v = jmax (v, parameters[i]);
  4743. return v;
  4744. }
  4745. else if (numParams == 1)
  4746. {
  4747. if (functionName == "sin") return sin (parameters[0]);
  4748. else if (functionName == "cos") return cos (parameters[0]);
  4749. else if (functionName == "tan") return tan (parameters[0]);
  4750. else if (functionName == "abs") return std::abs (parameters[0]);
  4751. }
  4752. }
  4753. throw Helpers::EvaluationError ("Unknown function: \"" + functionName + "\"");
  4754. }
  4755. void Expression::Scope::visitRelativeScope (const String& scopeName, Visitor&) const
  4756. {
  4757. throw Helpers::EvaluationError ("Unknown symbol: " + scopeName);
  4758. }
  4759. const String Expression::Scope::getScopeUID() const
  4760. {
  4761. return String::empty;
  4762. }
  4763. END_JUCE_NAMESPACE
  4764. /*** End of inlined file: juce_Expression.cpp ***/
  4765. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4766. BEGIN_JUCE_NAMESPACE
  4767. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4768. {
  4769. jassert (keyData != 0);
  4770. jassert (keyBytes > 0);
  4771. static const uint32 initialPValues [18] =
  4772. {
  4773. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4774. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4775. 0x9216d5d9, 0x8979fb1b
  4776. };
  4777. static const uint32 initialSValues [4 * 256] =
  4778. {
  4779. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4780. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4781. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4782. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4783. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4784. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4785. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4786. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4787. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4788. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4789. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4790. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4791. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4792. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4793. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4794. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4795. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4796. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4797. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4798. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4799. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4800. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4801. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4802. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4803. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4804. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4805. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4806. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4807. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4808. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4809. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4810. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4811. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4812. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4813. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4814. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4815. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4816. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4817. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4818. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4819. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4820. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4821. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4822. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4823. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4824. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4825. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4826. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4827. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4828. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4829. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4830. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4831. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4832. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4833. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4834. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4835. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4836. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4837. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4838. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4839. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4840. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4841. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4842. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4843. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4844. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4845. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4846. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4847. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4848. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4849. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4850. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4851. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4852. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4853. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4854. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4855. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4856. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4857. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4858. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4859. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4860. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4861. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4862. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4863. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4864. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4865. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4866. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4867. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4868. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4869. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4870. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4871. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4872. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4873. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4874. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4875. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4876. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4877. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4878. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4879. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4880. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4881. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4882. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4883. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4884. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4885. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4886. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4887. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4888. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4889. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4890. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4891. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4892. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4893. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4894. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4895. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4896. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4897. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4898. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4899. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4900. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4901. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4902. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4903. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4904. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4905. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4906. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4907. };
  4908. memcpy (p, initialPValues, sizeof (p));
  4909. int i, j = 0;
  4910. for (i = 4; --i >= 0;)
  4911. {
  4912. s[i].malloc (256);
  4913. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4914. }
  4915. for (i = 0; i < 18; ++i)
  4916. {
  4917. uint32 d = 0;
  4918. for (int k = 0; k < 4; ++k)
  4919. {
  4920. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4921. if (++j >= keyBytes)
  4922. j = 0;
  4923. }
  4924. p[i] = initialPValues[i] ^ d;
  4925. }
  4926. uint32 l = 0, r = 0;
  4927. for (i = 0; i < 18; i += 2)
  4928. {
  4929. encrypt (l, r);
  4930. p[i] = l;
  4931. p[i + 1] = r;
  4932. }
  4933. for (i = 0; i < 4; ++i)
  4934. {
  4935. for (j = 0; j < 256; j += 2)
  4936. {
  4937. encrypt (l, r);
  4938. s[i][j] = l;
  4939. s[i][j + 1] = r;
  4940. }
  4941. }
  4942. }
  4943. BlowFish::BlowFish (const BlowFish& other)
  4944. {
  4945. for (int i = 4; --i >= 0;)
  4946. s[i].malloc (256);
  4947. operator= (other);
  4948. }
  4949. BlowFish& BlowFish::operator= (const BlowFish& other)
  4950. {
  4951. memcpy (p, other.p, sizeof (p));
  4952. for (int i = 4; --i >= 0;)
  4953. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4954. return *this;
  4955. }
  4956. BlowFish::~BlowFish()
  4957. {
  4958. }
  4959. uint32 BlowFish::F (const uint32 x) const throw()
  4960. {
  4961. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4962. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4963. }
  4964. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4965. {
  4966. uint32 l = data1;
  4967. uint32 r = data2;
  4968. for (int i = 0; i < 16; ++i)
  4969. {
  4970. l ^= p[i];
  4971. r ^= F(l);
  4972. swapVariables (l, r);
  4973. }
  4974. data1 = r ^ p[17];
  4975. data2 = l ^ p[16];
  4976. }
  4977. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4978. {
  4979. uint32 l = data1;
  4980. uint32 r = data2;
  4981. for (int i = 17; i > 1; --i)
  4982. {
  4983. l ^= p[i];
  4984. r ^= F(l);
  4985. swapVariables (l, r);
  4986. }
  4987. data1 = r ^ p[0];
  4988. data2 = l ^ p[1];
  4989. }
  4990. END_JUCE_NAMESPACE
  4991. /*** End of inlined file: juce_BlowFish.cpp ***/
  4992. /*** Start of inlined file: juce_MD5.cpp ***/
  4993. BEGIN_JUCE_NAMESPACE
  4994. MD5::MD5()
  4995. {
  4996. zerostruct (result);
  4997. }
  4998. MD5::MD5 (const MD5& other)
  4999. {
  5000. memcpy (result, other.result, sizeof (result));
  5001. }
  5002. MD5& MD5::operator= (const MD5& other)
  5003. {
  5004. memcpy (result, other.result, sizeof (result));
  5005. return *this;
  5006. }
  5007. MD5::MD5 (const MemoryBlock& data)
  5008. {
  5009. ProcessContext context;
  5010. context.processBlock (data.getData(), data.getSize());
  5011. context.finish (result);
  5012. }
  5013. MD5::MD5 (const void* data, const size_t numBytes)
  5014. {
  5015. ProcessContext context;
  5016. context.processBlock (data, numBytes);
  5017. context.finish (result);
  5018. }
  5019. MD5::MD5 (const String& text)
  5020. {
  5021. ProcessContext context;
  5022. String::CharPointerType t (text.getCharPointer());
  5023. while (! t.isEmpty())
  5024. {
  5025. // force the string into integer-sized unicode characters, to try to make it
  5026. // get the same results on all platforms + compilers.
  5027. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t.getAndAdvance());
  5028. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  5029. }
  5030. context.finish (result);
  5031. }
  5032. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  5033. {
  5034. ProcessContext context;
  5035. if (numBytesToRead < 0)
  5036. numBytesToRead = std::numeric_limits<int64>::max();
  5037. while (numBytesToRead > 0)
  5038. {
  5039. uint8 tempBuffer [512];
  5040. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  5041. if (bytesRead <= 0)
  5042. break;
  5043. numBytesToRead -= bytesRead;
  5044. context.processBlock (tempBuffer, bytesRead);
  5045. }
  5046. context.finish (result);
  5047. }
  5048. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  5049. {
  5050. processStream (input, numBytesToRead);
  5051. }
  5052. MD5::MD5 (const File& file)
  5053. {
  5054. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  5055. if (fin != 0)
  5056. processStream (*fin, -1);
  5057. else
  5058. zerostruct (result);
  5059. }
  5060. MD5::~MD5()
  5061. {
  5062. }
  5063. namespace MD5Functions
  5064. {
  5065. void encode (void* const output, const void* const input, const int numBytes) throw()
  5066. {
  5067. for (int i = 0; i < (numBytes >> 2); ++i)
  5068. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  5069. }
  5070. inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  5071. inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  5072. inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  5073. inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  5074. inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  5075. void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5076. {
  5077. a += F (b, c, d) + x + ac;
  5078. a = rotateLeft (a, s) + b;
  5079. }
  5080. void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5081. {
  5082. a += G (b, c, d) + x + ac;
  5083. a = rotateLeft (a, s) + b;
  5084. }
  5085. void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5086. {
  5087. a += H (b, c, d) + x + ac;
  5088. a = rotateLeft (a, s) + b;
  5089. }
  5090. void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  5091. {
  5092. a += I (b, c, d) + x + ac;
  5093. a = rotateLeft (a, s) + b;
  5094. }
  5095. }
  5096. MD5::ProcessContext::ProcessContext()
  5097. {
  5098. state[0] = 0x67452301;
  5099. state[1] = 0xefcdab89;
  5100. state[2] = 0x98badcfe;
  5101. state[3] = 0x10325476;
  5102. count[0] = 0;
  5103. count[1] = 0;
  5104. }
  5105. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  5106. {
  5107. int bufferPos = ((count[0] >> 3) & 0x3F);
  5108. count[0] += (uint32) (dataSize << 3);
  5109. if (count[0] < ((uint32) dataSize << 3))
  5110. count[1]++;
  5111. count[1] += (uint32) (dataSize >> 29);
  5112. const size_t spaceLeft = 64 - bufferPos;
  5113. size_t i = 0;
  5114. if (dataSize >= spaceLeft)
  5115. {
  5116. memcpy (buffer + bufferPos, data, spaceLeft);
  5117. transform (buffer);
  5118. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  5119. transform (static_cast <const char*> (data) + i);
  5120. bufferPos = 0;
  5121. }
  5122. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  5123. }
  5124. void MD5::ProcessContext::finish (void* const result)
  5125. {
  5126. unsigned char encodedLength[8];
  5127. MD5Functions::encode (encodedLength, count, 8);
  5128. // Pad out to 56 mod 64.
  5129. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  5130. const int paddingLength = (index < 56) ? (56 - index)
  5131. : (120 - index);
  5132. uint8 paddingBuffer [64];
  5133. zeromem (paddingBuffer, paddingLength);
  5134. paddingBuffer [0] = 0x80;
  5135. processBlock (paddingBuffer, paddingLength);
  5136. processBlock (encodedLength, 8);
  5137. MD5Functions::encode (result, state, 16);
  5138. zerostruct (buffer);
  5139. }
  5140. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  5141. {
  5142. using namespace MD5Functions;
  5143. uint32 a = state[0];
  5144. uint32 b = state[1];
  5145. uint32 c = state[2];
  5146. uint32 d = state[3];
  5147. uint32 x[16];
  5148. encode (x, bufferToTransform, 64);
  5149. enum Constants
  5150. {
  5151. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  5152. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  5153. };
  5154. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  5155. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  5156. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  5157. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  5158. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  5159. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  5160. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  5161. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  5162. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  5163. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  5164. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  5165. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  5166. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  5167. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  5168. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  5169. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  5170. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  5171. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  5172. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  5173. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  5174. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  5175. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  5176. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  5177. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  5178. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  5179. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  5180. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  5181. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  5182. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  5183. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  5184. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  5185. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  5186. state[0] += a;
  5187. state[1] += b;
  5188. state[2] += c;
  5189. state[3] += d;
  5190. zerostruct (x);
  5191. }
  5192. const MemoryBlock MD5::getRawChecksumData() const
  5193. {
  5194. return MemoryBlock (result, sizeof (result));
  5195. }
  5196. const String MD5::toHexString() const
  5197. {
  5198. return String::toHexString (result, sizeof (result), 0);
  5199. }
  5200. bool MD5::operator== (const MD5& other) const
  5201. {
  5202. return memcmp (result, other.result, sizeof (result)) == 0;
  5203. }
  5204. bool MD5::operator!= (const MD5& other) const
  5205. {
  5206. return ! operator== (other);
  5207. }
  5208. END_JUCE_NAMESPACE
  5209. /*** End of inlined file: juce_MD5.cpp ***/
  5210. /*** Start of inlined file: juce_Primes.cpp ***/
  5211. BEGIN_JUCE_NAMESPACE
  5212. namespace PrimesHelpers
  5213. {
  5214. void createSmallSieve (const int numBits, BigInteger& result)
  5215. {
  5216. result.setBit (numBits);
  5217. result.clearBit (numBits); // to enlarge the array
  5218. result.setBit (0);
  5219. int n = 2;
  5220. do
  5221. {
  5222. for (int i = n + n; i < numBits; i += n)
  5223. result.setBit (i);
  5224. n = result.findNextClearBit (n + 1);
  5225. }
  5226. while (n <= (numBits >> 1));
  5227. }
  5228. void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5229. const BigInteger& smallSieve, const int smallSieveSize)
  5230. {
  5231. jassert (! base[0]); // must be even!
  5232. result.setBit (numBits);
  5233. result.clearBit (numBits); // to enlarge the array
  5234. int index = smallSieve.findNextClearBit (0);
  5235. do
  5236. {
  5237. const int prime = (index << 1) + 1;
  5238. BigInteger r (base), remainder;
  5239. r.divideBy (prime, remainder);
  5240. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5241. if (r.isZero())
  5242. i += prime;
  5243. if ((i & 1) == 0)
  5244. i += prime;
  5245. i = (i - 1) >> 1;
  5246. while (i < numBits)
  5247. {
  5248. result.setBit (i);
  5249. i += prime;
  5250. }
  5251. index = smallSieve.findNextClearBit (index + 1);
  5252. }
  5253. while (index < smallSieveSize);
  5254. }
  5255. bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5256. const int numBits, BigInteger& result, const int certainty)
  5257. {
  5258. for (int i = 0; i < numBits; ++i)
  5259. {
  5260. if (! sieve[i])
  5261. {
  5262. result = base + (unsigned int) ((i << 1) + 1);
  5263. if (Primes::isProbablyPrime (result, certainty))
  5264. return true;
  5265. }
  5266. }
  5267. return false;
  5268. }
  5269. bool passesMillerRabin (const BigInteger& n, int iterations)
  5270. {
  5271. const BigInteger one (1), two (2);
  5272. const BigInteger nMinusOne (n - one);
  5273. BigInteger d (nMinusOne);
  5274. const int s = d.findNextSetBit (0);
  5275. d >>= s;
  5276. BigInteger smallPrimes;
  5277. int numBitsInSmallPrimes = 0;
  5278. for (;;)
  5279. {
  5280. numBitsInSmallPrimes += 256;
  5281. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5282. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5283. if (numPrimesFound > iterations + 1)
  5284. break;
  5285. }
  5286. int smallPrime = 2;
  5287. while (--iterations >= 0)
  5288. {
  5289. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5290. BigInteger r (smallPrime);
  5291. r.exponentModulo (d, n);
  5292. if (r != one && r != nMinusOne)
  5293. {
  5294. for (int j = 0; j < s; ++j)
  5295. {
  5296. r.exponentModulo (two, n);
  5297. if (r == nMinusOne)
  5298. break;
  5299. }
  5300. if (r != nMinusOne)
  5301. return false;
  5302. }
  5303. }
  5304. return true;
  5305. }
  5306. }
  5307. const BigInteger Primes::createProbablePrime (const int bitLength,
  5308. const int certainty,
  5309. const int* randomSeeds,
  5310. int numRandomSeeds)
  5311. {
  5312. using namespace PrimesHelpers;
  5313. int defaultSeeds [16];
  5314. if (numRandomSeeds <= 0)
  5315. {
  5316. randomSeeds = defaultSeeds;
  5317. numRandomSeeds = numElementsInArray (defaultSeeds);
  5318. Random r (0);
  5319. for (int j = 10; --j >= 0;)
  5320. {
  5321. r.setSeedRandomly();
  5322. for (int i = numRandomSeeds; --i >= 0;)
  5323. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5324. }
  5325. }
  5326. BigInteger smallSieve;
  5327. const int smallSieveSize = 15000;
  5328. createSmallSieve (smallSieveSize, smallSieve);
  5329. BigInteger p;
  5330. for (int i = numRandomSeeds; --i >= 0;)
  5331. {
  5332. BigInteger p2;
  5333. Random r (randomSeeds[i]);
  5334. r.fillBitsRandomly (p2, 0, bitLength);
  5335. p ^= p2;
  5336. }
  5337. p.setBit (bitLength - 1);
  5338. p.clearBit (0);
  5339. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5340. while (p.getHighestBit() < bitLength)
  5341. {
  5342. p += 2 * searchLen;
  5343. BigInteger sieve;
  5344. bigSieve (p, searchLen, sieve,
  5345. smallSieve, smallSieveSize);
  5346. BigInteger candidate;
  5347. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5348. return candidate;
  5349. }
  5350. jassertfalse;
  5351. return BigInteger();
  5352. }
  5353. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5354. {
  5355. using namespace PrimesHelpers;
  5356. if (! number[0])
  5357. return false;
  5358. if (number.getHighestBit() <= 10)
  5359. {
  5360. const int num = number.getBitRangeAsInt (0, 10);
  5361. for (int i = num / 2; --i > 1;)
  5362. if (num % i == 0)
  5363. return false;
  5364. return true;
  5365. }
  5366. else
  5367. {
  5368. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5369. return false;
  5370. return passesMillerRabin (number, certainty);
  5371. }
  5372. }
  5373. END_JUCE_NAMESPACE
  5374. /*** End of inlined file: juce_Primes.cpp ***/
  5375. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5376. BEGIN_JUCE_NAMESPACE
  5377. RSAKey::RSAKey()
  5378. {
  5379. }
  5380. RSAKey::RSAKey (const String& s)
  5381. {
  5382. if (s.containsChar (','))
  5383. {
  5384. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5385. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5386. }
  5387. else
  5388. {
  5389. // the string needs to be two hex numbers, comma-separated..
  5390. jassertfalse;
  5391. }
  5392. }
  5393. RSAKey::~RSAKey()
  5394. {
  5395. }
  5396. bool RSAKey::operator== (const RSAKey& other) const throw()
  5397. {
  5398. return part1 == other.part1 && part2 == other.part2;
  5399. }
  5400. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5401. {
  5402. return ! operator== (other);
  5403. }
  5404. const String RSAKey::toString() const
  5405. {
  5406. return part1.toString (16) + "," + part2.toString (16);
  5407. }
  5408. bool RSAKey::applyToValue (BigInteger& value) const
  5409. {
  5410. if (part1.isZero() || part2.isZero() || value <= 0)
  5411. {
  5412. jassertfalse; // using an uninitialised key
  5413. value.clear();
  5414. return false;
  5415. }
  5416. BigInteger result;
  5417. while (! value.isZero())
  5418. {
  5419. result *= part2;
  5420. BigInteger remainder;
  5421. value.divideBy (part2, remainder);
  5422. remainder.exponentModulo (part1, part2);
  5423. result += remainder;
  5424. }
  5425. value.swapWith (result);
  5426. return true;
  5427. }
  5428. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5429. {
  5430. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5431. // are fast to divide + multiply
  5432. for (int i = 2; i <= 65536; i *= 2)
  5433. {
  5434. const BigInteger e (1 + i);
  5435. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5436. return e;
  5437. }
  5438. BigInteger e (4);
  5439. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5440. ++e;
  5441. return e;
  5442. }
  5443. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5444. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5445. {
  5446. jassert (numBits > 16); // not much point using less than this..
  5447. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5448. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5449. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5450. const BigInteger n (p * q);
  5451. const BigInteger m (--p * --q);
  5452. const BigInteger e (findBestCommonDivisor (p, q));
  5453. BigInteger d (e);
  5454. d.inverseModulo (m);
  5455. publicKey.part1 = e;
  5456. publicKey.part2 = n;
  5457. privateKey.part1 = d;
  5458. privateKey.part2 = n;
  5459. }
  5460. END_JUCE_NAMESPACE
  5461. /*** End of inlined file: juce_RSAKey.cpp ***/
  5462. /*** Start of inlined file: juce_InputStream.cpp ***/
  5463. BEGIN_JUCE_NAMESPACE
  5464. char InputStream::readByte()
  5465. {
  5466. char temp = 0;
  5467. read (&temp, 1);
  5468. return temp;
  5469. }
  5470. bool InputStream::readBool()
  5471. {
  5472. return readByte() != 0;
  5473. }
  5474. short InputStream::readShort()
  5475. {
  5476. char temp[2];
  5477. if (read (temp, 2) == 2)
  5478. return (short) ByteOrder::littleEndianShort (temp);
  5479. return 0;
  5480. }
  5481. short InputStream::readShortBigEndian()
  5482. {
  5483. char temp[2];
  5484. if (read (temp, 2) == 2)
  5485. return (short) ByteOrder::bigEndianShort (temp);
  5486. return 0;
  5487. }
  5488. int InputStream::readInt()
  5489. {
  5490. char temp[4];
  5491. if (read (temp, 4) == 4)
  5492. return (int) ByteOrder::littleEndianInt (temp);
  5493. return 0;
  5494. }
  5495. int InputStream::readIntBigEndian()
  5496. {
  5497. char temp[4];
  5498. if (read (temp, 4) == 4)
  5499. return (int) ByteOrder::bigEndianInt (temp);
  5500. return 0;
  5501. }
  5502. int InputStream::readCompressedInt()
  5503. {
  5504. const unsigned char sizeByte = readByte();
  5505. if (sizeByte == 0)
  5506. return 0;
  5507. const int numBytes = (sizeByte & 0x7f);
  5508. if (numBytes > 4)
  5509. {
  5510. jassertfalse; // trying to read corrupt data - this method must only be used
  5511. // to read data that was written by OutputStream::writeCompressedInt()
  5512. return 0;
  5513. }
  5514. char bytes[4] = { 0, 0, 0, 0 };
  5515. if (read (bytes, numBytes) != numBytes)
  5516. return 0;
  5517. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5518. return (sizeByte >> 7) ? -num : num;
  5519. }
  5520. int64 InputStream::readInt64()
  5521. {
  5522. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5523. if (read (n.asBytes, 8) == 8)
  5524. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5525. return 0;
  5526. }
  5527. int64 InputStream::readInt64BigEndian()
  5528. {
  5529. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5530. if (read (n.asBytes, 8) == 8)
  5531. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5532. return 0;
  5533. }
  5534. float InputStream::readFloat()
  5535. {
  5536. // the union below relies on these types being the same size...
  5537. static_jassert (sizeof (int32) == sizeof (float));
  5538. union { int32 asInt; float asFloat; } n;
  5539. n.asInt = (int32) readInt();
  5540. return n.asFloat;
  5541. }
  5542. float InputStream::readFloatBigEndian()
  5543. {
  5544. union { int32 asInt; float asFloat; } n;
  5545. n.asInt = (int32) readIntBigEndian();
  5546. return n.asFloat;
  5547. }
  5548. double InputStream::readDouble()
  5549. {
  5550. union { int64 asInt; double asDouble; } n;
  5551. n.asInt = readInt64();
  5552. return n.asDouble;
  5553. }
  5554. double InputStream::readDoubleBigEndian()
  5555. {
  5556. union { int64 asInt; double asDouble; } n;
  5557. n.asInt = readInt64BigEndian();
  5558. return n.asDouble;
  5559. }
  5560. const String InputStream::readString()
  5561. {
  5562. MemoryBlock buffer (256);
  5563. char* data = static_cast<char*> (buffer.getData());
  5564. size_t i = 0;
  5565. while ((data[i] = readByte()) != 0)
  5566. {
  5567. if (++i >= buffer.getSize())
  5568. {
  5569. buffer.setSize (buffer.getSize() + 512);
  5570. data = static_cast<char*> (buffer.getData());
  5571. }
  5572. }
  5573. return String::fromUTF8 (data, (int) i);
  5574. }
  5575. const String InputStream::readNextLine()
  5576. {
  5577. MemoryBlock buffer (256);
  5578. char* data = static_cast<char*> (buffer.getData());
  5579. size_t i = 0;
  5580. while ((data[i] = readByte()) != 0)
  5581. {
  5582. if (data[i] == '\n')
  5583. break;
  5584. if (data[i] == '\r')
  5585. {
  5586. const int64 lastPos = getPosition();
  5587. if (readByte() != '\n')
  5588. setPosition (lastPos);
  5589. break;
  5590. }
  5591. if (++i >= buffer.getSize())
  5592. {
  5593. buffer.setSize (buffer.getSize() + 512);
  5594. data = static_cast<char*> (buffer.getData());
  5595. }
  5596. }
  5597. return String::fromUTF8 (data, (int) i);
  5598. }
  5599. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5600. {
  5601. MemoryOutputStream mo (block, true);
  5602. return mo.writeFromInputStream (*this, numBytes);
  5603. }
  5604. const String InputStream::readEntireStreamAsString()
  5605. {
  5606. MemoryOutputStream mo;
  5607. mo.writeFromInputStream (*this, -1);
  5608. return mo.toString();
  5609. }
  5610. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5611. {
  5612. if (numBytesToSkip > 0)
  5613. {
  5614. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5615. HeapBlock<char> temp (skipBufferSize);
  5616. while (numBytesToSkip > 0 && ! isExhausted())
  5617. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5618. }
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_InputStream.cpp ***/
  5622. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. #if JUCE_DEBUG
  5625. static Array<void*, CriticalSection> activeStreams;
  5626. void juce_CheckForDanglingStreams()
  5627. {
  5628. /*
  5629. It's always a bad idea to leak any object, but if you're leaking output
  5630. streams, then there's a good chance that you're failing to flush a file
  5631. to disk properly, which could result in corrupted data and other similar
  5632. nastiness..
  5633. */
  5634. jassert (activeStreams.size() == 0);
  5635. };
  5636. #endif
  5637. OutputStream::OutputStream()
  5638. : newLineString (NewLine::getDefault())
  5639. {
  5640. #if JUCE_DEBUG
  5641. activeStreams.add (this);
  5642. #endif
  5643. }
  5644. OutputStream::~OutputStream()
  5645. {
  5646. #if JUCE_DEBUG
  5647. activeStreams.removeValue (this);
  5648. #endif
  5649. }
  5650. void OutputStream::writeBool (const bool b)
  5651. {
  5652. writeByte (b ? (char) 1
  5653. : (char) 0);
  5654. }
  5655. void OutputStream::writeByte (char byte)
  5656. {
  5657. write (&byte, 1);
  5658. }
  5659. void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat)
  5660. {
  5661. while (--numTimesToRepeat >= 0)
  5662. writeByte (byte);
  5663. }
  5664. void OutputStream::writeShort (short value)
  5665. {
  5666. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5667. write (&v, 2);
  5668. }
  5669. void OutputStream::writeShortBigEndian (short value)
  5670. {
  5671. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5672. write (&v, 2);
  5673. }
  5674. void OutputStream::writeInt (int value)
  5675. {
  5676. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5677. write (&v, 4);
  5678. }
  5679. void OutputStream::writeIntBigEndian (int value)
  5680. {
  5681. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5682. write (&v, 4);
  5683. }
  5684. void OutputStream::writeCompressedInt (int value)
  5685. {
  5686. unsigned int un = (value < 0) ? (unsigned int) -value
  5687. : (unsigned int) value;
  5688. uint8 data[5];
  5689. int num = 0;
  5690. while (un > 0)
  5691. {
  5692. data[++num] = (uint8) un;
  5693. un >>= 8;
  5694. }
  5695. data[0] = (uint8) num;
  5696. if (value < 0)
  5697. data[0] |= 0x80;
  5698. write (data, num + 1);
  5699. }
  5700. void OutputStream::writeInt64 (int64 value)
  5701. {
  5702. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5703. write (&v, 8);
  5704. }
  5705. void OutputStream::writeInt64BigEndian (int64 value)
  5706. {
  5707. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5708. write (&v, 8);
  5709. }
  5710. void OutputStream::writeFloat (float value)
  5711. {
  5712. union { int asInt; float asFloat; } n;
  5713. n.asFloat = value;
  5714. writeInt (n.asInt);
  5715. }
  5716. void OutputStream::writeFloatBigEndian (float value)
  5717. {
  5718. union { int asInt; float asFloat; } n;
  5719. n.asFloat = value;
  5720. writeIntBigEndian (n.asInt);
  5721. }
  5722. void OutputStream::writeDouble (double value)
  5723. {
  5724. union { int64 asInt; double asDouble; } n;
  5725. n.asDouble = value;
  5726. writeInt64 (n.asInt);
  5727. }
  5728. void OutputStream::writeDoubleBigEndian (double value)
  5729. {
  5730. union { int64 asInt; double asDouble; } n;
  5731. n.asDouble = value;
  5732. writeInt64BigEndian (n.asInt);
  5733. }
  5734. void OutputStream::writeString (const String& text)
  5735. {
  5736. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5737. // if lots of large, persistent strings were to be written to streams).
  5738. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5739. HeapBlock<char> temp (numBytes);
  5740. text.copyToUTF8 (temp, numBytes);
  5741. write (temp, numBytes);
  5742. }
  5743. void OutputStream::writeText (const String& text, const bool asUTF16,
  5744. const bool writeUTF16ByteOrderMark)
  5745. {
  5746. if (asUTF16)
  5747. {
  5748. if (writeUTF16ByteOrderMark)
  5749. write ("\x0ff\x0fe", 2);
  5750. String::CharPointerType src (text.getCharPointer());
  5751. bool lastCharWasReturn = false;
  5752. for (;;)
  5753. {
  5754. const juce_wchar c = src.getAndAdvance();
  5755. if (c == 0)
  5756. break;
  5757. if (c == '\n' && ! lastCharWasReturn)
  5758. writeShort ((short) '\r');
  5759. lastCharWasReturn = (c == L'\r');
  5760. writeShort ((short) c);
  5761. }
  5762. }
  5763. else
  5764. {
  5765. const char* src = text.toUTF8();
  5766. const char* t = src;
  5767. for (;;)
  5768. {
  5769. if (*t == '\n')
  5770. {
  5771. if (t > src)
  5772. write (src, (int) (t - src));
  5773. write ("\r\n", 2);
  5774. src = t + 1;
  5775. }
  5776. else if (*t == '\r')
  5777. {
  5778. if (t[1] == '\n')
  5779. ++t;
  5780. }
  5781. else if (*t == 0)
  5782. {
  5783. if (t > src)
  5784. write (src, (int) (t - src));
  5785. break;
  5786. }
  5787. ++t;
  5788. }
  5789. }
  5790. }
  5791. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5792. {
  5793. if (numBytesToWrite < 0)
  5794. numBytesToWrite = std::numeric_limits<int64>::max();
  5795. int numWritten = 0;
  5796. while (numBytesToWrite > 0 && ! source.isExhausted())
  5797. {
  5798. char buffer [8192];
  5799. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5800. if (num <= 0)
  5801. break;
  5802. write (buffer, num);
  5803. numBytesToWrite -= num;
  5804. numWritten += num;
  5805. }
  5806. return numWritten;
  5807. }
  5808. void OutputStream::setNewLineString (const String& newLineString_)
  5809. {
  5810. newLineString = newLineString_;
  5811. }
  5812. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5813. {
  5814. return stream << String (number);
  5815. }
  5816. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5817. {
  5818. return stream << String (number);
  5819. }
  5820. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5821. {
  5822. stream.writeByte (character);
  5823. return stream;
  5824. }
  5825. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5826. {
  5827. stream.write (text, (int) strlen (text));
  5828. return stream;
  5829. }
  5830. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5831. {
  5832. stream.write (data.getData(), (int) data.getSize());
  5833. return stream;
  5834. }
  5835. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5836. {
  5837. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5838. if (in != 0)
  5839. stream.writeFromInputStream (*in, -1);
  5840. return stream;
  5841. }
  5842. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&)
  5843. {
  5844. return stream << stream.getNewLineString();
  5845. }
  5846. END_JUCE_NAMESPACE
  5847. /*** End of inlined file: juce_OutputStream.cpp ***/
  5848. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5849. BEGIN_JUCE_NAMESPACE
  5850. DirectoryIterator::DirectoryIterator (const File& directory,
  5851. bool isRecursive_,
  5852. const String& wildCard_,
  5853. const int whatToLookFor_)
  5854. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5855. wildCard (wildCard_),
  5856. path (File::addTrailingSeparator (directory.getFullPathName())),
  5857. index (-1),
  5858. totalNumFiles (-1),
  5859. whatToLookFor (whatToLookFor_),
  5860. isRecursive (isRecursive_),
  5861. hasBeenAdvanced (false)
  5862. {
  5863. // you have to specify the type of files you're looking for!
  5864. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5865. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5866. }
  5867. DirectoryIterator::~DirectoryIterator()
  5868. {
  5869. }
  5870. bool DirectoryIterator::next()
  5871. {
  5872. return next (0, 0, 0, 0, 0, 0);
  5873. }
  5874. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5875. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5876. {
  5877. hasBeenAdvanced = true;
  5878. if (subIterator != 0)
  5879. {
  5880. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5881. return true;
  5882. subIterator = 0;
  5883. }
  5884. String filename;
  5885. bool isDirectory, isHidden;
  5886. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5887. {
  5888. ++index;
  5889. if (! filename.containsOnly ("."))
  5890. {
  5891. const File fileFound (path + filename, 0);
  5892. bool matches = false;
  5893. if (isDirectory)
  5894. {
  5895. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5896. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5897. matches = (whatToLookFor & File::findDirectories) != 0;
  5898. }
  5899. else
  5900. {
  5901. matches = (whatToLookFor & File::findFiles) != 0;
  5902. }
  5903. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5904. if (matches && isRecursive)
  5905. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5906. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5907. matches = ! isHidden;
  5908. if (matches)
  5909. {
  5910. currentFile = fileFound;
  5911. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5912. if (isDirResult != 0) *isDirResult = isDirectory;
  5913. return true;
  5914. }
  5915. else if (subIterator != 0)
  5916. {
  5917. return next();
  5918. }
  5919. }
  5920. }
  5921. return false;
  5922. }
  5923. const File DirectoryIterator::getFile() const
  5924. {
  5925. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5926. return subIterator->getFile();
  5927. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5928. jassert (hasBeenAdvanced);
  5929. return currentFile;
  5930. }
  5931. float DirectoryIterator::getEstimatedProgress() const
  5932. {
  5933. if (totalNumFiles < 0)
  5934. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5935. if (totalNumFiles <= 0)
  5936. return 0.0f;
  5937. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5938. : (float) index;
  5939. return detailedIndex / totalNumFiles;
  5940. }
  5941. END_JUCE_NAMESPACE
  5942. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5943. /*** Start of inlined file: juce_File.cpp ***/
  5944. #if ! JUCE_WINDOWS
  5945. #include <pwd.h>
  5946. #endif
  5947. BEGIN_JUCE_NAMESPACE
  5948. File::File (const String& fullPathName)
  5949. : fullPath (parseAbsolutePath (fullPathName))
  5950. {
  5951. }
  5952. File::File (const String& path, int)
  5953. : fullPath (path)
  5954. {
  5955. }
  5956. const File File::createFileWithoutCheckingPath (const String& path)
  5957. {
  5958. return File (path, 0);
  5959. }
  5960. File::File (const File& other)
  5961. : fullPath (other.fullPath)
  5962. {
  5963. }
  5964. File& File::operator= (const String& newPath)
  5965. {
  5966. fullPath = parseAbsolutePath (newPath);
  5967. return *this;
  5968. }
  5969. File& File::operator= (const File& other)
  5970. {
  5971. fullPath = other.fullPath;
  5972. return *this;
  5973. }
  5974. const File File::nonexistent;
  5975. const String File::parseAbsolutePath (const String& p)
  5976. {
  5977. if (p.isEmpty())
  5978. return String::empty;
  5979. #if JUCE_WINDOWS
  5980. // Windows..
  5981. String path (p.replaceCharacter ('/', '\\'));
  5982. if (path.startsWithChar (File::separator))
  5983. {
  5984. if (path[1] != File::separator)
  5985. {
  5986. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5987. If you're trying to parse a string that may be either a relative path or an absolute path,
  5988. you MUST provide a context against which the partial path can be evaluated - you can do
  5989. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5990. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5991. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5992. */
  5993. jassertfalse;
  5994. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5995. }
  5996. }
  5997. else if (! path.containsChar (':'))
  5998. {
  5999. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6000. If you're trying to parse a string that may be either a relative path or an absolute path,
  6001. you MUST provide a context against which the partial path can be evaluated - you can do
  6002. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6003. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6004. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6005. */
  6006. jassertfalse;
  6007. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6008. }
  6009. #else
  6010. // Mac or Linux..
  6011. String path (p.replaceCharacter ('\\', '/'));
  6012. if (path.startsWithChar ('~'))
  6013. {
  6014. if (path[1] == File::separator || path[1] == 0)
  6015. {
  6016. // expand a name of the form "~/abc"
  6017. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  6018. + path.substring (1);
  6019. }
  6020. else
  6021. {
  6022. // expand a name of type "~dave/abc"
  6023. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  6024. struct passwd* const pw = getpwnam (userName.toUTF8());
  6025. if (pw != 0)
  6026. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  6027. }
  6028. }
  6029. else if (! path.startsWithChar (File::separator))
  6030. {
  6031. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  6032. If you're trying to parse a string that may be either a relative path or an absolute path,
  6033. you MUST provide a context against which the partial path can be evaluated - you can do
  6034. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  6035. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  6036. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  6037. */
  6038. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  6039. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  6040. }
  6041. #endif
  6042. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  6043. path = path.dropLastCharacters (1);
  6044. return path;
  6045. }
  6046. const String File::addTrailingSeparator (const String& path)
  6047. {
  6048. return path.endsWithChar (File::separator) ? path
  6049. : path + File::separator;
  6050. }
  6051. #if JUCE_LINUX
  6052. #define NAMES_ARE_CASE_SENSITIVE 1
  6053. #endif
  6054. bool File::areFileNamesCaseSensitive()
  6055. {
  6056. #if NAMES_ARE_CASE_SENSITIVE
  6057. return true;
  6058. #else
  6059. return false;
  6060. #endif
  6061. }
  6062. bool File::operator== (const File& other) const
  6063. {
  6064. #if NAMES_ARE_CASE_SENSITIVE
  6065. return fullPath == other.fullPath;
  6066. #else
  6067. return fullPath.equalsIgnoreCase (other.fullPath);
  6068. #endif
  6069. }
  6070. bool File::operator!= (const File& other) const
  6071. {
  6072. return ! operator== (other);
  6073. }
  6074. bool File::operator< (const File& other) const
  6075. {
  6076. #if NAMES_ARE_CASE_SENSITIVE
  6077. return fullPath < other.fullPath;
  6078. #else
  6079. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  6080. #endif
  6081. }
  6082. bool File::operator> (const File& other) const
  6083. {
  6084. #if NAMES_ARE_CASE_SENSITIVE
  6085. return fullPath > other.fullPath;
  6086. #else
  6087. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  6088. #endif
  6089. }
  6090. bool File::setReadOnly (const bool shouldBeReadOnly,
  6091. const bool applyRecursively) const
  6092. {
  6093. bool worked = true;
  6094. if (applyRecursively && isDirectory())
  6095. {
  6096. Array <File> subFiles;
  6097. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6098. for (int i = subFiles.size(); --i >= 0;)
  6099. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  6100. }
  6101. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  6102. }
  6103. bool File::deleteRecursively() const
  6104. {
  6105. bool worked = true;
  6106. if (isDirectory())
  6107. {
  6108. Array<File> subFiles;
  6109. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  6110. for (int i = subFiles.size(); --i >= 0;)
  6111. worked = subFiles.getReference(i).deleteRecursively() && worked;
  6112. }
  6113. return deleteFile() && worked;
  6114. }
  6115. bool File::moveFileTo (const File& newFile) const
  6116. {
  6117. if (newFile.fullPath == fullPath)
  6118. return true;
  6119. #if ! NAMES_ARE_CASE_SENSITIVE
  6120. if (*this != newFile)
  6121. #endif
  6122. if (! newFile.deleteFile())
  6123. return false;
  6124. return moveInternal (newFile);
  6125. }
  6126. bool File::copyFileTo (const File& newFile) const
  6127. {
  6128. return (*this == newFile)
  6129. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  6130. }
  6131. bool File::copyDirectoryTo (const File& newDirectory) const
  6132. {
  6133. if (isDirectory() && newDirectory.createDirectory())
  6134. {
  6135. Array<File> subFiles;
  6136. findChildFiles (subFiles, File::findFiles, false);
  6137. int i;
  6138. for (i = 0; i < subFiles.size(); ++i)
  6139. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6140. return false;
  6141. subFiles.clear();
  6142. findChildFiles (subFiles, File::findDirectories, false);
  6143. for (i = 0; i < subFiles.size(); ++i)
  6144. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  6145. return false;
  6146. return true;
  6147. }
  6148. return false;
  6149. }
  6150. const String File::getPathUpToLastSlash() const
  6151. {
  6152. const int lastSlash = fullPath.lastIndexOfChar (separator);
  6153. if (lastSlash > 0)
  6154. return fullPath.substring (0, lastSlash);
  6155. else if (lastSlash == 0)
  6156. return separatorString;
  6157. else
  6158. return fullPath;
  6159. }
  6160. const File File::getParentDirectory() const
  6161. {
  6162. return File (getPathUpToLastSlash(), (int) 0);
  6163. }
  6164. const String File::getFileName() const
  6165. {
  6166. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  6167. }
  6168. int File::hashCode() const
  6169. {
  6170. return fullPath.hashCode();
  6171. }
  6172. int64 File::hashCode64() const
  6173. {
  6174. return fullPath.hashCode64();
  6175. }
  6176. const String File::getFileNameWithoutExtension() const
  6177. {
  6178. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  6179. const int lastDot = fullPath.lastIndexOfChar ('.');
  6180. if (lastDot > lastSlash)
  6181. return fullPath.substring (lastSlash, lastDot);
  6182. else
  6183. return fullPath.substring (lastSlash);
  6184. }
  6185. bool File::isAChildOf (const File& potentialParent) const
  6186. {
  6187. if (potentialParent == File::nonexistent)
  6188. return false;
  6189. const String ourPath (getPathUpToLastSlash());
  6190. #if NAMES_ARE_CASE_SENSITIVE
  6191. if (potentialParent.fullPath == ourPath)
  6192. #else
  6193. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  6194. #endif
  6195. {
  6196. return true;
  6197. }
  6198. else if (potentialParent.fullPath.length() >= ourPath.length())
  6199. {
  6200. return false;
  6201. }
  6202. else
  6203. {
  6204. return getParentDirectory().isAChildOf (potentialParent);
  6205. }
  6206. }
  6207. bool File::isAbsolutePath (const String& path)
  6208. {
  6209. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  6210. #if JUCE_WINDOWS
  6211. || (path.isNotEmpty() && path[1] == ':');
  6212. #else
  6213. || path.startsWithChar ('~');
  6214. #endif
  6215. }
  6216. const File File::getChildFile (String relativePath) const
  6217. {
  6218. if (isAbsolutePath (relativePath))
  6219. {
  6220. // the path is really absolute..
  6221. return File (relativePath);
  6222. }
  6223. else
  6224. {
  6225. // it's relative, so remove any ../ or ./ bits at the start.
  6226. String path (fullPath);
  6227. if (relativePath[0] == '.')
  6228. {
  6229. #if JUCE_WINDOWS
  6230. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6231. #else
  6232. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6233. #endif
  6234. while (relativePath[0] == '.')
  6235. {
  6236. if (relativePath[1] == '.')
  6237. {
  6238. if (relativePath [2] == 0 || relativePath[2] == separator)
  6239. {
  6240. const int lastSlash = path.lastIndexOfChar (separator);
  6241. if (lastSlash >= 0)
  6242. path = path.substring (0, lastSlash);
  6243. relativePath = relativePath.substring (3);
  6244. }
  6245. else
  6246. {
  6247. break;
  6248. }
  6249. }
  6250. else if (relativePath[1] == separator)
  6251. {
  6252. relativePath = relativePath.substring (2);
  6253. }
  6254. else
  6255. {
  6256. break;
  6257. }
  6258. }
  6259. }
  6260. return File (addTrailingSeparator (path) + relativePath);
  6261. }
  6262. }
  6263. const File File::getSiblingFile (const String& fileName) const
  6264. {
  6265. return getParentDirectory().getChildFile (fileName);
  6266. }
  6267. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6268. {
  6269. if (bytes == 1)
  6270. {
  6271. return "1 byte";
  6272. }
  6273. else if (bytes < 1024)
  6274. {
  6275. return String ((int) bytes) + " bytes";
  6276. }
  6277. else if (bytes < 1024 * 1024)
  6278. {
  6279. return String (bytes / 1024.0, 1) + " KB";
  6280. }
  6281. else if (bytes < 1024 * 1024 * 1024)
  6282. {
  6283. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6284. }
  6285. else
  6286. {
  6287. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6288. }
  6289. }
  6290. bool File::create() const
  6291. {
  6292. if (exists())
  6293. return true;
  6294. {
  6295. const File parentDir (getParentDirectory());
  6296. if (parentDir == *this || ! parentDir.createDirectory())
  6297. return false;
  6298. FileOutputStream fo (*this, 8);
  6299. }
  6300. return exists();
  6301. }
  6302. bool File::createDirectory() const
  6303. {
  6304. if (! isDirectory())
  6305. {
  6306. const File parentDir (getParentDirectory());
  6307. if (parentDir == *this || ! parentDir.createDirectory())
  6308. return false;
  6309. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6310. return isDirectory();
  6311. }
  6312. return true;
  6313. }
  6314. const Time File::getCreationTime() const
  6315. {
  6316. int64 m, a, c;
  6317. getFileTimesInternal (m, a, c);
  6318. return Time (c);
  6319. }
  6320. const Time File::getLastModificationTime() const
  6321. {
  6322. int64 m, a, c;
  6323. getFileTimesInternal (m, a, c);
  6324. return Time (m);
  6325. }
  6326. const Time File::getLastAccessTime() const
  6327. {
  6328. int64 m, a, c;
  6329. getFileTimesInternal (m, a, c);
  6330. return Time (a);
  6331. }
  6332. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6333. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6334. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6335. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6336. {
  6337. if (! existsAsFile())
  6338. return false;
  6339. FileInputStream in (*this);
  6340. return getSize() == in.readIntoMemoryBlock (destBlock);
  6341. }
  6342. const String File::loadFileAsString() const
  6343. {
  6344. if (! existsAsFile())
  6345. return String::empty;
  6346. FileInputStream in (*this);
  6347. return in.readEntireStreamAsString();
  6348. }
  6349. int File::findChildFiles (Array<File>& results,
  6350. const int whatToLookFor,
  6351. const bool searchRecursively,
  6352. const String& wildCardPattern) const
  6353. {
  6354. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6355. int total = 0;
  6356. while (di.next())
  6357. {
  6358. results.add (di.getFile());
  6359. ++total;
  6360. }
  6361. return total;
  6362. }
  6363. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6364. {
  6365. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6366. int total = 0;
  6367. while (di.next())
  6368. ++total;
  6369. return total;
  6370. }
  6371. bool File::containsSubDirectories() const
  6372. {
  6373. if (isDirectory())
  6374. {
  6375. DirectoryIterator di (*this, false, "*", findDirectories);
  6376. return di.next();
  6377. }
  6378. return false;
  6379. }
  6380. const File File::getNonexistentChildFile (const String& prefix_,
  6381. const String& suffix,
  6382. bool putNumbersInBrackets) const
  6383. {
  6384. File f (getChildFile (prefix_ + suffix));
  6385. if (f.exists())
  6386. {
  6387. int num = 2;
  6388. String prefix (prefix_);
  6389. // remove any bracketed numbers that may already be on the end..
  6390. if (prefix.trim().endsWithChar (')'))
  6391. {
  6392. putNumbersInBrackets = true;
  6393. const int openBracks = prefix.lastIndexOfChar ('(');
  6394. const int closeBracks = prefix.lastIndexOfChar (')');
  6395. if (openBracks > 0
  6396. && closeBracks > openBracks
  6397. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6398. {
  6399. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6400. prefix = prefix.substring (0, openBracks);
  6401. }
  6402. }
  6403. // also use brackets if it ends in a digit.
  6404. putNumbersInBrackets = putNumbersInBrackets
  6405. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6406. do
  6407. {
  6408. if (putNumbersInBrackets)
  6409. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6410. else
  6411. f = getChildFile (prefix + String (num++) + suffix);
  6412. } while (f.exists());
  6413. }
  6414. return f;
  6415. }
  6416. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6417. {
  6418. if (exists())
  6419. {
  6420. return getParentDirectory()
  6421. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6422. getFileExtension(),
  6423. putNumbersInBrackets);
  6424. }
  6425. else
  6426. {
  6427. return *this;
  6428. }
  6429. }
  6430. const String File::getFileExtension() const
  6431. {
  6432. String ext;
  6433. if (! isDirectory())
  6434. {
  6435. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6436. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6437. ext = fullPath.substring (indexOfDot);
  6438. }
  6439. return ext;
  6440. }
  6441. bool File::hasFileExtension (const String& possibleSuffix) const
  6442. {
  6443. if (possibleSuffix.isEmpty())
  6444. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6445. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6446. if (semicolon >= 0)
  6447. {
  6448. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6449. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6450. }
  6451. else
  6452. {
  6453. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6454. {
  6455. if (possibleSuffix.startsWithChar ('.'))
  6456. return true;
  6457. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6458. if (dotPos >= 0)
  6459. return fullPath [dotPos] == '.';
  6460. }
  6461. }
  6462. return false;
  6463. }
  6464. const File File::withFileExtension (const String& newExtension) const
  6465. {
  6466. if (fullPath.isEmpty())
  6467. return File::nonexistent;
  6468. String filePart (getFileName());
  6469. int i = filePart.lastIndexOfChar ('.');
  6470. if (i >= 0)
  6471. filePart = filePart.substring (0, i);
  6472. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6473. filePart << '.';
  6474. return getSiblingFile (filePart + newExtension);
  6475. }
  6476. bool File::startAsProcess (const String& parameters) const
  6477. {
  6478. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6479. }
  6480. FileInputStream* File::createInputStream() const
  6481. {
  6482. if (existsAsFile())
  6483. return new FileInputStream (*this);
  6484. return 0;
  6485. }
  6486. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6487. {
  6488. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6489. if (out->failedToOpen())
  6490. return 0;
  6491. return out.release();
  6492. }
  6493. bool File::appendData (const void* const dataToAppend,
  6494. const int numberOfBytes) const
  6495. {
  6496. if (numberOfBytes > 0)
  6497. {
  6498. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6499. if (out == 0)
  6500. return false;
  6501. out->write (dataToAppend, numberOfBytes);
  6502. }
  6503. return true;
  6504. }
  6505. bool File::replaceWithData (const void* const dataToWrite,
  6506. const int numberOfBytes) const
  6507. {
  6508. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6509. if (numberOfBytes <= 0)
  6510. return deleteFile();
  6511. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6512. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6513. return tempFile.overwriteTargetFileWithTemporary();
  6514. }
  6515. bool File::appendText (const String& text,
  6516. const bool asUnicode,
  6517. const bool writeUnicodeHeaderBytes) const
  6518. {
  6519. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6520. if (out != 0)
  6521. {
  6522. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6523. return true;
  6524. }
  6525. return false;
  6526. }
  6527. bool File::replaceWithText (const String& textToWrite,
  6528. const bool asUnicode,
  6529. const bool writeUnicodeHeaderBytes) const
  6530. {
  6531. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6532. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6533. return tempFile.overwriteTargetFileWithTemporary();
  6534. }
  6535. bool File::hasIdenticalContentTo (const File& other) const
  6536. {
  6537. if (other == *this)
  6538. return true;
  6539. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6540. {
  6541. FileInputStream in1 (*this), in2 (other);
  6542. const int bufferSize = 4096;
  6543. HeapBlock <char> buffer1, buffer2;
  6544. buffer1.malloc (bufferSize);
  6545. buffer2.malloc (bufferSize);
  6546. for (;;)
  6547. {
  6548. const int num1 = in1.read (buffer1, bufferSize);
  6549. const int num2 = in2.read (buffer2, bufferSize);
  6550. if (num1 != num2)
  6551. break;
  6552. if (num1 <= 0)
  6553. return true;
  6554. if (memcmp (buffer1, buffer2, num1) != 0)
  6555. break;
  6556. }
  6557. }
  6558. return false;
  6559. }
  6560. const String File::createLegalPathName (const String& original)
  6561. {
  6562. String s (original);
  6563. String start;
  6564. if (s[1] == ':')
  6565. {
  6566. start = s.substring (0, 2);
  6567. s = s.substring (2);
  6568. }
  6569. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6570. .substring (0, 1024);
  6571. }
  6572. const String File::createLegalFileName (const String& original)
  6573. {
  6574. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6575. const int maxLength = 128; // only the length of the filename, not the whole path
  6576. const int len = s.length();
  6577. if (len > maxLength)
  6578. {
  6579. const int lastDot = s.lastIndexOfChar ('.');
  6580. if (lastDot > jmax (0, len - 12))
  6581. {
  6582. s = s.substring (0, maxLength - (len - lastDot))
  6583. + s.substring (lastDot);
  6584. }
  6585. else
  6586. {
  6587. s = s.substring (0, maxLength);
  6588. }
  6589. }
  6590. return s;
  6591. }
  6592. const String File::getRelativePathFrom (const File& dir) const
  6593. {
  6594. String thisPath (fullPath);
  6595. while (thisPath.endsWithChar (separator))
  6596. thisPath = thisPath.dropLastCharacters (1);
  6597. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6598. : dir.fullPath));
  6599. const int len = jmin (thisPath.length(), dirPath.length());
  6600. int commonBitLength = 0;
  6601. for (int i = 0; i < len; ++i)
  6602. {
  6603. #if NAMES_ARE_CASE_SENSITIVE
  6604. if (thisPath[i] != dirPath[i])
  6605. #else
  6606. if (CharacterFunctions::toLowerCase (thisPath[i])
  6607. != CharacterFunctions::toLowerCase (dirPath[i]))
  6608. #endif
  6609. {
  6610. break;
  6611. }
  6612. ++commonBitLength;
  6613. }
  6614. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6615. --commonBitLength;
  6616. // if the only common bit is the root, then just return the full path..
  6617. if (commonBitLength <= 0
  6618. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6619. return fullPath;
  6620. thisPath = thisPath.substring (commonBitLength);
  6621. dirPath = dirPath.substring (commonBitLength);
  6622. while (dirPath.isNotEmpty())
  6623. {
  6624. #if JUCE_WINDOWS
  6625. thisPath = "..\\" + thisPath;
  6626. #else
  6627. thisPath = "../" + thisPath;
  6628. #endif
  6629. const int sep = dirPath.indexOfChar (separator);
  6630. if (sep >= 0)
  6631. dirPath = dirPath.substring (sep + 1);
  6632. else
  6633. dirPath = String::empty;
  6634. }
  6635. return thisPath;
  6636. }
  6637. const File File::createTempFile (const String& fileNameEnding)
  6638. {
  6639. const File tempFile (getSpecialLocation (tempDirectory)
  6640. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6641. .withFileExtension (fileNameEnding));
  6642. if (tempFile.exists())
  6643. return createTempFile (fileNameEnding);
  6644. else
  6645. return tempFile;
  6646. }
  6647. #if JUCE_UNIT_TESTS
  6648. class FileTests : public UnitTest
  6649. {
  6650. public:
  6651. FileTests() : UnitTest ("Files") {}
  6652. void runTest()
  6653. {
  6654. beginTest ("Reading");
  6655. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6656. const File temp (File::getSpecialLocation (File::tempDirectory));
  6657. expect (! File::nonexistent.exists());
  6658. expect (home.isDirectory());
  6659. expect (home.exists());
  6660. expect (! home.existsAsFile());
  6661. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6662. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6663. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6664. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6665. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6666. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6667. expect (home.getBytesFreeOnVolume() > 0);
  6668. expect (! home.isHidden());
  6669. expect (home.isOnHardDisk());
  6670. expect (! home.isOnCDRomDrive());
  6671. expect (File::getCurrentWorkingDirectory().exists());
  6672. expect (home.setAsCurrentWorkingDirectory());
  6673. expect (File::getCurrentWorkingDirectory() == home);
  6674. {
  6675. Array<File> roots;
  6676. File::findFileSystemRoots (roots);
  6677. expect (roots.size() > 0);
  6678. int numRootsExisting = 0;
  6679. for (int i = 0; i < roots.size(); ++i)
  6680. if (roots[i].exists())
  6681. ++numRootsExisting;
  6682. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6683. expect (numRootsExisting > 0);
  6684. }
  6685. beginTest ("Writing");
  6686. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6687. expect (demoFolder.deleteRecursively());
  6688. expect (demoFolder.createDirectory());
  6689. expect (demoFolder.isDirectory());
  6690. expect (demoFolder.getParentDirectory() == temp);
  6691. expect (temp.isDirectory());
  6692. {
  6693. Array<File> files;
  6694. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6695. expect (files.contains (demoFolder));
  6696. }
  6697. {
  6698. Array<File> files;
  6699. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6700. expect (files.contains (demoFolder));
  6701. }
  6702. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6703. expect (tempFile.getFileExtension() == ".txt");
  6704. expect (tempFile.hasFileExtension (".txt"));
  6705. expect (tempFile.hasFileExtension ("txt"));
  6706. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6707. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6708. expect (tempFile.hasWriteAccess());
  6709. {
  6710. FileOutputStream fo (tempFile);
  6711. fo.write ("0123456789", 10);
  6712. }
  6713. expect (tempFile.exists());
  6714. expect (tempFile.getSize() == 10);
  6715. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6716. expect (tempFile.loadFileAsString() == "0123456789");
  6717. expect (! demoFolder.containsSubDirectories());
  6718. expectEquals (tempFile.getRelativePathFrom (demoFolder.getParentDirectory()), demoFolder.getFileName() + File::separatorString + tempFile.getFileName());
  6719. expectEquals (demoFolder.getParentDirectory().getRelativePathFrom (tempFile), ".." + File::separatorString + ".." + File::separatorString + demoFolder.getParentDirectory().getFileName());
  6720. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6721. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6722. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6723. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6724. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6725. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6726. expect (demoFolder.containsSubDirectories());
  6727. expect (tempFile.hasWriteAccess());
  6728. tempFile.setReadOnly (true);
  6729. expect (! tempFile.hasWriteAccess());
  6730. tempFile.setReadOnly (false);
  6731. expect (tempFile.hasWriteAccess());
  6732. Time t (Time::getCurrentTime());
  6733. tempFile.setLastModificationTime (t);
  6734. Time t2 = tempFile.getLastModificationTime();
  6735. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6736. {
  6737. MemoryBlock mb;
  6738. tempFile.loadFileAsData (mb);
  6739. expect (mb.getSize() == 10);
  6740. expect (mb[0] == '0');
  6741. }
  6742. expect (tempFile.appendData ("abcdefghij", 10));
  6743. expect (tempFile.getSize() == 20);
  6744. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6745. expect (tempFile.getSize() == 10);
  6746. File tempFile2 (tempFile.getNonexistentSibling (false));
  6747. expect (tempFile.copyFileTo (tempFile2));
  6748. expect (tempFile2.exists());
  6749. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6750. expect (tempFile.deleteFile());
  6751. expect (! tempFile.exists());
  6752. expect (tempFile2.moveFileTo (tempFile));
  6753. expect (tempFile.exists());
  6754. expect (! tempFile2.exists());
  6755. expect (demoFolder.deleteRecursively());
  6756. expect (! demoFolder.exists());
  6757. }
  6758. };
  6759. static FileTests fileUnitTests;
  6760. #endif
  6761. END_JUCE_NAMESPACE
  6762. /*** End of inlined file: juce_File.cpp ***/
  6763. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6764. BEGIN_JUCE_NAMESPACE
  6765. int64 juce_fileSetPosition (void* handle, int64 pos);
  6766. FileInputStream::FileInputStream (const File& f)
  6767. : file (f),
  6768. fileHandle (0),
  6769. currentPosition (0),
  6770. totalSize (0),
  6771. needToSeek (true)
  6772. {
  6773. openHandle();
  6774. }
  6775. FileInputStream::~FileInputStream()
  6776. {
  6777. closeHandle();
  6778. }
  6779. int64 FileInputStream::getTotalLength()
  6780. {
  6781. return totalSize;
  6782. }
  6783. int FileInputStream::read (void* buffer, int bytesToRead)
  6784. {
  6785. if (needToSeek)
  6786. {
  6787. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6788. return 0;
  6789. needToSeek = false;
  6790. }
  6791. const size_t num = readInternal (buffer, bytesToRead);
  6792. currentPosition += num;
  6793. return (int) num;
  6794. }
  6795. bool FileInputStream::isExhausted()
  6796. {
  6797. return currentPosition >= totalSize;
  6798. }
  6799. int64 FileInputStream::getPosition()
  6800. {
  6801. return currentPosition;
  6802. }
  6803. bool FileInputStream::setPosition (int64 pos)
  6804. {
  6805. pos = jlimit ((int64) 0, totalSize, pos);
  6806. needToSeek |= (currentPosition != pos);
  6807. currentPosition = pos;
  6808. return true;
  6809. }
  6810. END_JUCE_NAMESPACE
  6811. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6812. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6813. BEGIN_JUCE_NAMESPACE
  6814. int64 juce_fileSetPosition (void* handle, int64 pos);
  6815. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6816. : file (f),
  6817. fileHandle (0),
  6818. currentPosition (0),
  6819. bufferSize (bufferSize_),
  6820. bytesInBuffer (0),
  6821. buffer (jmax (bufferSize_, 16))
  6822. {
  6823. openHandle();
  6824. }
  6825. FileOutputStream::~FileOutputStream()
  6826. {
  6827. flush();
  6828. closeHandle();
  6829. }
  6830. int64 FileOutputStream::getPosition()
  6831. {
  6832. return currentPosition;
  6833. }
  6834. bool FileOutputStream::setPosition (int64 newPosition)
  6835. {
  6836. if (newPosition != currentPosition)
  6837. {
  6838. flush();
  6839. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6840. }
  6841. return newPosition == currentPosition;
  6842. }
  6843. void FileOutputStream::flush()
  6844. {
  6845. if (bytesInBuffer > 0)
  6846. {
  6847. writeInternal (buffer, bytesInBuffer);
  6848. bytesInBuffer = 0;
  6849. }
  6850. flushInternal();
  6851. }
  6852. bool FileOutputStream::write (const void* const src, const int numBytes)
  6853. {
  6854. if (bytesInBuffer + numBytes < bufferSize)
  6855. {
  6856. memcpy (buffer + bytesInBuffer, src, numBytes);
  6857. bytesInBuffer += numBytes;
  6858. currentPosition += numBytes;
  6859. }
  6860. else
  6861. {
  6862. if (bytesInBuffer > 0)
  6863. {
  6864. // flush the reservoir
  6865. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6866. bytesInBuffer = 0;
  6867. if (! wroteOk)
  6868. return false;
  6869. }
  6870. if (numBytes < bufferSize)
  6871. {
  6872. memcpy (buffer + bytesInBuffer, src, numBytes);
  6873. bytesInBuffer += numBytes;
  6874. currentPosition += numBytes;
  6875. }
  6876. else
  6877. {
  6878. const int bytesWritten = writeInternal (src, numBytes);
  6879. if (bytesWritten < 0)
  6880. return false;
  6881. currentPosition += bytesWritten;
  6882. return bytesWritten == numBytes;
  6883. }
  6884. }
  6885. return true;
  6886. }
  6887. END_JUCE_NAMESPACE
  6888. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6889. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6890. BEGIN_JUCE_NAMESPACE
  6891. FileSearchPath::FileSearchPath()
  6892. {
  6893. }
  6894. FileSearchPath::FileSearchPath (const String& path)
  6895. {
  6896. init (path);
  6897. }
  6898. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6899. : directories (other.directories)
  6900. {
  6901. }
  6902. FileSearchPath::~FileSearchPath()
  6903. {
  6904. }
  6905. FileSearchPath& FileSearchPath::operator= (const String& path)
  6906. {
  6907. init (path);
  6908. return *this;
  6909. }
  6910. void FileSearchPath::init (const String& path)
  6911. {
  6912. directories.clear();
  6913. directories.addTokens (path, ";", "\"");
  6914. directories.trim();
  6915. directories.removeEmptyStrings();
  6916. for (int i = directories.size(); --i >= 0;)
  6917. directories.set (i, directories[i].unquoted());
  6918. }
  6919. int FileSearchPath::getNumPaths() const
  6920. {
  6921. return directories.size();
  6922. }
  6923. const File FileSearchPath::operator[] (const int index) const
  6924. {
  6925. return File (directories [index]);
  6926. }
  6927. const String FileSearchPath::toString() const
  6928. {
  6929. StringArray directories2 (directories);
  6930. for (int i = directories2.size(); --i >= 0;)
  6931. if (directories2[i].containsChar (';'))
  6932. directories2.set (i, directories2[i].quoted());
  6933. return directories2.joinIntoString (";");
  6934. }
  6935. void FileSearchPath::add (const File& dir, const int insertIndex)
  6936. {
  6937. directories.insert (insertIndex, dir.getFullPathName());
  6938. }
  6939. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6940. {
  6941. for (int i = 0; i < directories.size(); ++i)
  6942. if (File (directories[i]) == dir)
  6943. return;
  6944. add (dir);
  6945. }
  6946. void FileSearchPath::remove (const int index)
  6947. {
  6948. directories.remove (index);
  6949. }
  6950. void FileSearchPath::addPath (const FileSearchPath& other)
  6951. {
  6952. for (int i = 0; i < other.getNumPaths(); ++i)
  6953. addIfNotAlreadyThere (other[i]);
  6954. }
  6955. void FileSearchPath::removeRedundantPaths()
  6956. {
  6957. for (int i = directories.size(); --i >= 0;)
  6958. {
  6959. const File d1 (directories[i]);
  6960. for (int j = directories.size(); --j >= 0;)
  6961. {
  6962. const File d2 (directories[j]);
  6963. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6964. {
  6965. directories.remove (i);
  6966. break;
  6967. }
  6968. }
  6969. }
  6970. }
  6971. void FileSearchPath::removeNonExistentPaths()
  6972. {
  6973. for (int i = directories.size(); --i >= 0;)
  6974. if (! File (directories[i]).isDirectory())
  6975. directories.remove (i);
  6976. }
  6977. int FileSearchPath::findChildFiles (Array<File>& results,
  6978. const int whatToLookFor,
  6979. const bool searchRecursively,
  6980. const String& wildCardPattern) const
  6981. {
  6982. int total = 0;
  6983. for (int i = 0; i < directories.size(); ++i)
  6984. total += operator[] (i).findChildFiles (results,
  6985. whatToLookFor,
  6986. searchRecursively,
  6987. wildCardPattern);
  6988. return total;
  6989. }
  6990. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6991. const bool checkRecursively) const
  6992. {
  6993. for (int i = directories.size(); --i >= 0;)
  6994. {
  6995. const File d (directories[i]);
  6996. if (checkRecursively)
  6997. {
  6998. if (fileToCheck.isAChildOf (d))
  6999. return true;
  7000. }
  7001. else
  7002. {
  7003. if (fileToCheck.getParentDirectory() == d)
  7004. return true;
  7005. }
  7006. }
  7007. return false;
  7008. }
  7009. END_JUCE_NAMESPACE
  7010. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  7011. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  7012. BEGIN_JUCE_NAMESPACE
  7013. NamedPipe::NamedPipe()
  7014. : internal (0)
  7015. {
  7016. }
  7017. NamedPipe::~NamedPipe()
  7018. {
  7019. close();
  7020. }
  7021. bool NamedPipe::openExisting (const String& pipeName)
  7022. {
  7023. currentPipeName = pipeName;
  7024. return openInternal (pipeName, false);
  7025. }
  7026. bool NamedPipe::createNewPipe (const String& pipeName)
  7027. {
  7028. currentPipeName = pipeName;
  7029. return openInternal (pipeName, true);
  7030. }
  7031. bool NamedPipe::isOpen() const
  7032. {
  7033. return internal != 0;
  7034. }
  7035. const String NamedPipe::getName() const
  7036. {
  7037. return currentPipeName;
  7038. }
  7039. // other methods for this class are implemented in the platform-specific files
  7040. END_JUCE_NAMESPACE
  7041. /*** End of inlined file: juce_NamedPipe.cpp ***/
  7042. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  7043. BEGIN_JUCE_NAMESPACE
  7044. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  7045. {
  7046. createTempFile (File::getSpecialLocation (File::tempDirectory),
  7047. "temp_" + String (Random::getSystemRandom().nextInt()),
  7048. suffix,
  7049. optionFlags);
  7050. }
  7051. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  7052. : targetFile (targetFile_)
  7053. {
  7054. // If you use this constructor, you need to give it a valid target file!
  7055. jassert (targetFile != File::nonexistent);
  7056. createTempFile (targetFile.getParentDirectory(),
  7057. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  7058. targetFile.getFileExtension(),
  7059. optionFlags);
  7060. }
  7061. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  7062. const String& suffix, const int optionFlags)
  7063. {
  7064. if ((optionFlags & useHiddenFile) != 0)
  7065. name = "." + name;
  7066. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  7067. }
  7068. TemporaryFile::~TemporaryFile()
  7069. {
  7070. if (! deleteTemporaryFile())
  7071. {
  7072. /* Failed to delete our temporary file! The most likely reason for this would be
  7073. that you've not closed an output stream that was being used to write to file.
  7074. If you find that something beyond your control is changing permissions on
  7075. your temporary files and preventing them from being deleted, you may want to
  7076. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  7077. handle them appropriately.
  7078. */
  7079. jassertfalse;
  7080. }
  7081. }
  7082. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  7083. {
  7084. // This method only works if you created this object with the constructor
  7085. // that takes a target file!
  7086. jassert (targetFile != File::nonexistent);
  7087. if (temporaryFile.exists())
  7088. {
  7089. // Have a few attempts at overwriting the file before giving up..
  7090. for (int i = 5; --i >= 0;)
  7091. {
  7092. if (temporaryFile.moveFileTo (targetFile))
  7093. return true;
  7094. Thread::sleep (100);
  7095. }
  7096. }
  7097. else
  7098. {
  7099. // There's no temporary file to use. If your write failed, you should
  7100. // probably check, and not bother calling this method.
  7101. jassertfalse;
  7102. }
  7103. return false;
  7104. }
  7105. bool TemporaryFile::deleteTemporaryFile() const
  7106. {
  7107. // Have a few attempts at deleting the file before giving up..
  7108. for (int i = 5; --i >= 0;)
  7109. {
  7110. if (temporaryFile.deleteFile())
  7111. return true;
  7112. Thread::sleep (50);
  7113. }
  7114. return false;
  7115. }
  7116. END_JUCE_NAMESPACE
  7117. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  7118. /*** Start of inlined file: juce_Socket.cpp ***/
  7119. #if JUCE_WINDOWS
  7120. #include <winsock2.h>
  7121. #if JUCE_MSVC
  7122. #pragma warning (push)
  7123. #pragma warning (disable : 4127 4389 4018)
  7124. #endif
  7125. #else
  7126. #if JUCE_LINUX || JUCE_ANDROID
  7127. #include <sys/types.h>
  7128. #include <sys/socket.h>
  7129. #include <sys/errno.h>
  7130. #include <unistd.h>
  7131. #include <netinet/in.h>
  7132. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  7133. #include <CoreServices/CoreServices.h>
  7134. #endif
  7135. #include <fcntl.h>
  7136. #include <netdb.h>
  7137. #include <arpa/inet.h>
  7138. #include <netinet/tcp.h>
  7139. #endif
  7140. BEGIN_JUCE_NAMESPACE
  7141. #if JUCE_LINUX || JUCE_MAC || JUCE_IOS || JUCE_ANDROID
  7142. typedef socklen_t juce_socklen_t;
  7143. #else
  7144. typedef int juce_socklen_t;
  7145. #endif
  7146. #if JUCE_WINDOWS
  7147. namespace SocketHelpers
  7148. {
  7149. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  7150. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  7151. void initWin32Sockets()
  7152. {
  7153. static CriticalSection lock;
  7154. const ScopedLock sl (lock);
  7155. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  7156. {
  7157. WSADATA wsaData;
  7158. const WORD wVersionRequested = MAKEWORD (1, 1);
  7159. WSAStartup (wVersionRequested, &wsaData);
  7160. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  7161. }
  7162. }
  7163. }
  7164. void juce_shutdownWin32Sockets()
  7165. {
  7166. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  7167. (*SocketHelpers::juce_CloseWin32SocketLib)();
  7168. }
  7169. #endif
  7170. namespace SocketHelpers
  7171. {
  7172. bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  7173. {
  7174. const int sndBufSize = 65536;
  7175. const int rcvBufSize = 65536;
  7176. const int one = 1;
  7177. return handle > 0
  7178. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  7179. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  7180. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  7181. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  7182. }
  7183. bool bindSocketToPort (const int handle, const int port) throw()
  7184. {
  7185. if (handle <= 0 || port <= 0)
  7186. return false;
  7187. struct sockaddr_in servTmpAddr;
  7188. zerostruct (servTmpAddr);
  7189. servTmpAddr.sin_family = PF_INET;
  7190. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7191. servTmpAddr.sin_port = htons ((uint16) port);
  7192. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  7193. }
  7194. int readSocket (const int handle,
  7195. void* const destBuffer, const int maxBytesToRead,
  7196. bool volatile& connected,
  7197. const bool blockUntilSpecifiedAmountHasArrived) throw()
  7198. {
  7199. int bytesRead = 0;
  7200. while (bytesRead < maxBytesToRead)
  7201. {
  7202. int bytesThisTime;
  7203. #if JUCE_WINDOWS
  7204. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  7205. #else
  7206. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  7207. && errno == EINTR
  7208. && connected)
  7209. {
  7210. }
  7211. #endif
  7212. if (bytesThisTime <= 0 || ! connected)
  7213. {
  7214. if (bytesRead == 0)
  7215. bytesRead = -1;
  7216. break;
  7217. }
  7218. bytesRead += bytesThisTime;
  7219. if (! blockUntilSpecifiedAmountHasArrived)
  7220. break;
  7221. }
  7222. return bytesRead;
  7223. }
  7224. int waitForReadiness (const int handle, const bool forReading, const int timeoutMsecs) throw()
  7225. {
  7226. struct timeval timeout;
  7227. struct timeval* timeoutp;
  7228. if (timeoutMsecs >= 0)
  7229. {
  7230. timeout.tv_sec = timeoutMsecs / 1000;
  7231. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7232. timeoutp = &timeout;
  7233. }
  7234. else
  7235. {
  7236. timeoutp = 0;
  7237. }
  7238. fd_set rset, wset;
  7239. FD_ZERO (&rset);
  7240. FD_SET (handle, &rset);
  7241. FD_ZERO (&wset);
  7242. FD_SET (handle, &wset);
  7243. fd_set* const prset = forReading ? &rset : 0;
  7244. fd_set* const pwset = forReading ? 0 : &wset;
  7245. #if JUCE_WINDOWS
  7246. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7247. return -1;
  7248. #else
  7249. {
  7250. int result;
  7251. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7252. && errno == EINTR)
  7253. {
  7254. }
  7255. if (result < 0)
  7256. return -1;
  7257. }
  7258. #endif
  7259. {
  7260. int opt;
  7261. juce_socklen_t len = sizeof (opt);
  7262. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7263. || opt != 0)
  7264. return -1;
  7265. }
  7266. if ((forReading && FD_ISSET (handle, &rset))
  7267. || ((! forReading) && FD_ISSET (handle, &wset)))
  7268. return 1;
  7269. return 0;
  7270. }
  7271. bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7272. {
  7273. #if JUCE_WINDOWS
  7274. u_long nonBlocking = shouldBlock ? 0 : 1;
  7275. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7276. return false;
  7277. #else
  7278. int socketFlags = fcntl (handle, F_GETFL, 0);
  7279. if (socketFlags == -1)
  7280. return false;
  7281. if (shouldBlock)
  7282. socketFlags &= ~O_NONBLOCK;
  7283. else
  7284. socketFlags |= O_NONBLOCK;
  7285. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7286. return false;
  7287. #endif
  7288. return true;
  7289. }
  7290. bool connectSocket (int volatile& handle,
  7291. const bool isDatagram,
  7292. void** serverAddress,
  7293. const String& hostName,
  7294. const int portNumber,
  7295. const int timeOutMillisecs) throw()
  7296. {
  7297. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7298. if (hostEnt == 0)
  7299. return false;
  7300. struct in_addr targetAddress;
  7301. memcpy (&targetAddress.s_addr,
  7302. *(hostEnt->h_addr_list),
  7303. sizeof (targetAddress.s_addr));
  7304. struct sockaddr_in servTmpAddr;
  7305. zerostruct (servTmpAddr);
  7306. servTmpAddr.sin_family = PF_INET;
  7307. servTmpAddr.sin_addr = targetAddress;
  7308. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7309. if (handle < 0)
  7310. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7311. if (handle < 0)
  7312. return false;
  7313. if (isDatagram)
  7314. {
  7315. *serverAddress = new struct sockaddr_in();
  7316. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7317. return true;
  7318. }
  7319. setSocketBlockingState (handle, false);
  7320. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7321. if (result < 0)
  7322. {
  7323. #if JUCE_WINDOWS
  7324. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7325. #else
  7326. if (errno == EINPROGRESS)
  7327. #endif
  7328. {
  7329. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7330. {
  7331. setSocketBlockingState (handle, true);
  7332. return false;
  7333. }
  7334. }
  7335. }
  7336. setSocketBlockingState (handle, true);
  7337. resetSocketOptions (handle, false, false);
  7338. return true;
  7339. }
  7340. }
  7341. StreamingSocket::StreamingSocket()
  7342. : portNumber (0),
  7343. handle (-1),
  7344. connected (false),
  7345. isListener (false)
  7346. {
  7347. #if JUCE_WINDOWS
  7348. SocketHelpers::initWin32Sockets();
  7349. #endif
  7350. }
  7351. StreamingSocket::StreamingSocket (const String& hostName_,
  7352. const int portNumber_,
  7353. const int handle_)
  7354. : hostName (hostName_),
  7355. portNumber (portNumber_),
  7356. handle (handle_),
  7357. connected (true),
  7358. isListener (false)
  7359. {
  7360. #if JUCE_WINDOWS
  7361. SocketHelpers::initWin32Sockets();
  7362. #endif
  7363. SocketHelpers::resetSocketOptions (handle_, false, false);
  7364. }
  7365. StreamingSocket::~StreamingSocket()
  7366. {
  7367. close();
  7368. }
  7369. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7370. {
  7371. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7372. : -1;
  7373. }
  7374. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7375. {
  7376. if (isListener || ! connected)
  7377. return -1;
  7378. #if JUCE_WINDOWS
  7379. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7380. #else
  7381. int result;
  7382. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7383. && errno == EINTR)
  7384. {
  7385. }
  7386. return result;
  7387. #endif
  7388. }
  7389. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7390. const int timeoutMsecs) const
  7391. {
  7392. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7393. : -1;
  7394. }
  7395. bool StreamingSocket::bindToPort (const int port)
  7396. {
  7397. return SocketHelpers::bindSocketToPort (handle, port);
  7398. }
  7399. bool StreamingSocket::connect (const String& remoteHostName,
  7400. const int remotePortNumber,
  7401. const int timeOutMillisecs)
  7402. {
  7403. if (isListener)
  7404. {
  7405. jassertfalse; // a listener socket can't connect to another one!
  7406. return false;
  7407. }
  7408. if (connected)
  7409. close();
  7410. hostName = remoteHostName;
  7411. portNumber = remotePortNumber;
  7412. isListener = false;
  7413. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7414. remotePortNumber, timeOutMillisecs);
  7415. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7416. {
  7417. close();
  7418. return false;
  7419. }
  7420. return true;
  7421. }
  7422. void StreamingSocket::close()
  7423. {
  7424. #if JUCE_WINDOWS
  7425. if (handle != SOCKET_ERROR || connected)
  7426. closesocket (handle);
  7427. connected = false;
  7428. #else
  7429. if (connected)
  7430. {
  7431. connected = false;
  7432. if (isListener)
  7433. {
  7434. // need to do this to interrupt the accept() function..
  7435. StreamingSocket temp;
  7436. temp.connect ("localhost", portNumber, 1000);
  7437. }
  7438. }
  7439. if (handle != -1)
  7440. ::close (handle);
  7441. #endif
  7442. hostName = String::empty;
  7443. portNumber = 0;
  7444. handle = -1;
  7445. isListener = false;
  7446. }
  7447. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7448. {
  7449. if (connected)
  7450. close();
  7451. hostName = "listener";
  7452. portNumber = newPortNumber;
  7453. isListener = true;
  7454. struct sockaddr_in servTmpAddr;
  7455. zerostruct (servTmpAddr);
  7456. servTmpAddr.sin_family = PF_INET;
  7457. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7458. if (localHostName.isNotEmpty())
  7459. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7460. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7461. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7462. if (handle < 0)
  7463. return false;
  7464. const int reuse = 1;
  7465. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7466. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7467. || listen (handle, SOMAXCONN) < 0)
  7468. {
  7469. close();
  7470. return false;
  7471. }
  7472. connected = true;
  7473. return true;
  7474. }
  7475. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7476. {
  7477. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7478. // prepare this socket as a listener.
  7479. if (connected && isListener)
  7480. {
  7481. struct sockaddr address;
  7482. juce_socklen_t len = sizeof (sockaddr);
  7483. const int newSocket = (int) accept (handle, &address, &len);
  7484. if (newSocket >= 0 && connected)
  7485. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7486. portNumber, newSocket);
  7487. }
  7488. return 0;
  7489. }
  7490. bool StreamingSocket::isLocal() const throw()
  7491. {
  7492. return hostName == "127.0.0.1";
  7493. }
  7494. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7495. : portNumber (0),
  7496. handle (-1),
  7497. connected (true),
  7498. allowBroadcast (allowBroadcast_),
  7499. serverAddress (0)
  7500. {
  7501. #if JUCE_WINDOWS
  7502. SocketHelpers::initWin32Sockets();
  7503. #endif
  7504. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7505. bindToPort (localPortNumber);
  7506. }
  7507. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7508. const int handle_, const int localPortNumber)
  7509. : hostName (hostName_),
  7510. portNumber (portNumber_),
  7511. handle (handle_),
  7512. connected (true),
  7513. allowBroadcast (false),
  7514. serverAddress (0)
  7515. {
  7516. #if JUCE_WINDOWS
  7517. SocketHelpers::initWin32Sockets();
  7518. #endif
  7519. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7520. bindToPort (localPortNumber);
  7521. }
  7522. DatagramSocket::~DatagramSocket()
  7523. {
  7524. close();
  7525. delete static_cast <struct sockaddr_in*> (serverAddress);
  7526. serverAddress = 0;
  7527. }
  7528. void DatagramSocket::close()
  7529. {
  7530. #if JUCE_WINDOWS
  7531. closesocket (handle);
  7532. connected = false;
  7533. #else
  7534. connected = false;
  7535. ::close (handle);
  7536. #endif
  7537. hostName = String::empty;
  7538. portNumber = 0;
  7539. handle = -1;
  7540. }
  7541. bool DatagramSocket::bindToPort (const int port)
  7542. {
  7543. return SocketHelpers::bindSocketToPort (handle, port);
  7544. }
  7545. bool DatagramSocket::connect (const String& remoteHostName,
  7546. const int remotePortNumber,
  7547. const int timeOutMillisecs)
  7548. {
  7549. if (connected)
  7550. close();
  7551. hostName = remoteHostName;
  7552. portNumber = remotePortNumber;
  7553. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7554. remoteHostName, remotePortNumber,
  7555. timeOutMillisecs);
  7556. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7557. {
  7558. close();
  7559. return false;
  7560. }
  7561. return true;
  7562. }
  7563. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7564. {
  7565. struct sockaddr address;
  7566. juce_socklen_t len = sizeof (sockaddr);
  7567. while (waitUntilReady (true, -1) == 1)
  7568. {
  7569. char buf[1];
  7570. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7571. {
  7572. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7573. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7574. -1, -1);
  7575. }
  7576. }
  7577. return 0;
  7578. }
  7579. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7580. const int timeoutMsecs) const
  7581. {
  7582. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7583. : -1;
  7584. }
  7585. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7586. {
  7587. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7588. : -1;
  7589. }
  7590. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7591. {
  7592. // You need to call connect() first to set the server address..
  7593. jassert (serverAddress != 0 && connected);
  7594. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7595. numBytesToWrite, 0,
  7596. (const struct sockaddr*) serverAddress,
  7597. sizeof (struct sockaddr_in))
  7598. : -1;
  7599. }
  7600. bool DatagramSocket::isLocal() const throw()
  7601. {
  7602. return hostName == "127.0.0.1";
  7603. }
  7604. #if JUCE_MSVC
  7605. #pragma warning (pop)
  7606. #endif
  7607. END_JUCE_NAMESPACE
  7608. /*** End of inlined file: juce_Socket.cpp ***/
  7609. /*** Start of inlined file: juce_URL.cpp ***/
  7610. BEGIN_JUCE_NAMESPACE
  7611. URL::URL()
  7612. {
  7613. }
  7614. URL::URL (const String& url_)
  7615. : url (url_)
  7616. {
  7617. int i = url.indexOfChar ('?');
  7618. if (i >= 0)
  7619. {
  7620. do
  7621. {
  7622. const int nextAmp = url.indexOfChar (i + 1, '&');
  7623. const int equalsPos = url.indexOfChar (i + 1, '=');
  7624. if (equalsPos > i + 1)
  7625. {
  7626. if (nextAmp < 0)
  7627. {
  7628. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7629. removeEscapeChars (url.substring (equalsPos + 1)));
  7630. }
  7631. else if (nextAmp > 0 && equalsPos < nextAmp)
  7632. {
  7633. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7634. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7635. }
  7636. }
  7637. i = nextAmp;
  7638. }
  7639. while (i >= 0);
  7640. url = url.upToFirstOccurrenceOf ("?", false, false);
  7641. }
  7642. }
  7643. URL::URL (const URL& other)
  7644. : url (other.url),
  7645. postData (other.postData),
  7646. parameters (other.parameters),
  7647. filesToUpload (other.filesToUpload),
  7648. mimeTypes (other.mimeTypes)
  7649. {
  7650. }
  7651. URL& URL::operator= (const URL& other)
  7652. {
  7653. url = other.url;
  7654. postData = other.postData;
  7655. parameters = other.parameters;
  7656. filesToUpload = other.filesToUpload;
  7657. mimeTypes = other.mimeTypes;
  7658. return *this;
  7659. }
  7660. URL::~URL()
  7661. {
  7662. }
  7663. namespace URLHelpers
  7664. {
  7665. const String getMangledParameters (const StringPairArray& parameters)
  7666. {
  7667. String p;
  7668. for (int i = 0; i < parameters.size(); ++i)
  7669. {
  7670. if (i > 0)
  7671. p << '&';
  7672. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7673. << '='
  7674. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7675. }
  7676. return p;
  7677. }
  7678. int findStartOfDomain (const String& url)
  7679. {
  7680. int i = 0;
  7681. while (CharacterFunctions::isLetterOrDigit (url[i])
  7682. || url[i] == '+' || url[i] == '-' || url[i] == '.')
  7683. ++i;
  7684. return url[i] == ':' ? i + 1 : 0;
  7685. }
  7686. void createHeadersAndPostData (const URL& url, String& headers, MemoryBlock& postData)
  7687. {
  7688. MemoryOutputStream data (postData, false);
  7689. if (url.getFilesToUpload().size() > 0)
  7690. {
  7691. // need to upload some files, so do it as multi-part...
  7692. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7693. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7694. data << "--" << boundary;
  7695. int i;
  7696. for (i = 0; i < url.getParameters().size(); ++i)
  7697. {
  7698. data << "\r\nContent-Disposition: form-data; name=\""
  7699. << url.getParameters().getAllKeys() [i]
  7700. << "\"\r\n\r\n"
  7701. << url.getParameters().getAllValues() [i]
  7702. << "\r\n--"
  7703. << boundary;
  7704. }
  7705. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7706. {
  7707. const File file (url.getFilesToUpload().getAllValues() [i]);
  7708. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7709. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7710. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7711. const String mimeType (url.getMimeTypesOfUploadFiles()
  7712. .getValue (paramName, String::empty));
  7713. if (mimeType.isNotEmpty())
  7714. data << "Content-Type: " << mimeType << "\r\n";
  7715. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7716. << file << "\r\n--" << boundary;
  7717. }
  7718. data << "--\r\n";
  7719. data.flush();
  7720. }
  7721. else
  7722. {
  7723. data << getMangledParameters (url.getParameters()) << url.getPostData();
  7724. data.flush();
  7725. // just a short text attachment, so use simple url encoding..
  7726. headers << "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7727. << (int) postData.getSize() << "\r\n";
  7728. }
  7729. }
  7730. }
  7731. const String URL::toString (const bool includeGetParameters) const
  7732. {
  7733. if (includeGetParameters && parameters.size() > 0)
  7734. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7735. else
  7736. return url;
  7737. }
  7738. bool URL::isWellFormed() const
  7739. {
  7740. //xxx TODO
  7741. return url.isNotEmpty();
  7742. }
  7743. const String URL::getDomain() const
  7744. {
  7745. int start = URLHelpers::findStartOfDomain (url);
  7746. while (url[start] == '/')
  7747. ++start;
  7748. const int end1 = url.indexOfChar (start, '/');
  7749. const int end2 = url.indexOfChar (start, ':');
  7750. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7751. : jmin (end1, end2);
  7752. return url.substring (start, end);
  7753. }
  7754. const String URL::getSubPath() const
  7755. {
  7756. int start = URLHelpers::findStartOfDomain (url);
  7757. while (url[start] == '/')
  7758. ++start;
  7759. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7760. return startOfPath <= 0 ? String::empty
  7761. : url.substring (startOfPath);
  7762. }
  7763. const String URL::getScheme() const
  7764. {
  7765. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7766. }
  7767. const URL URL::withNewSubPath (const String& newPath) const
  7768. {
  7769. int start = URLHelpers::findStartOfDomain (url);
  7770. while (url[start] == '/')
  7771. ++start;
  7772. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7773. URL u (*this);
  7774. if (startOfPath > 0)
  7775. u.url = url.substring (0, startOfPath);
  7776. if (! u.url.endsWithChar ('/'))
  7777. u.url << '/';
  7778. if (newPath.startsWithChar ('/'))
  7779. u.url << newPath.substring (1);
  7780. else
  7781. u.url << newPath;
  7782. return u;
  7783. }
  7784. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7785. {
  7786. const char* validProtocols[] = { "http:", "ftp:", "https:" };
  7787. for (int i = 0; i < numElementsInArray (validProtocols); ++i)
  7788. if (possibleURL.startsWithIgnoreCase (validProtocols[i]))
  7789. return true;
  7790. if (possibleURL.containsChar ('@')
  7791. || possibleURL.containsChar (' '))
  7792. return false;
  7793. const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
  7794. .fromLastOccurrenceOf (".", false, false));
  7795. return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
  7796. }
  7797. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7798. {
  7799. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7800. return atSign > 0
  7801. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7802. && (! possibleEmailAddress.endsWithChar ('.'));
  7803. }
  7804. InputStream* URL::createInputStream (const bool usePostCommand,
  7805. OpenStreamProgressCallback* const progressCallback,
  7806. void* const progressCallbackContext,
  7807. const String& extraHeaders,
  7808. const int timeOutMs,
  7809. StringPairArray* const responseHeaders) const
  7810. {
  7811. String headers;
  7812. MemoryBlock headersAndPostData;
  7813. if (usePostCommand)
  7814. URLHelpers::createHeadersAndPostData (*this, headers, headersAndPostData);
  7815. headers += extraHeaders;
  7816. if (! headers.endsWithChar ('\n'))
  7817. headers << "\r\n";
  7818. return createNativeStream (toString (! usePostCommand), usePostCommand, headersAndPostData,
  7819. progressCallback, progressCallbackContext,
  7820. headers, timeOutMs, responseHeaders);
  7821. }
  7822. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7823. const bool usePostCommand) const
  7824. {
  7825. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7826. if (in != 0)
  7827. {
  7828. in->readIntoMemoryBlock (destData);
  7829. return true;
  7830. }
  7831. return false;
  7832. }
  7833. const String URL::readEntireTextStream (const bool usePostCommand) const
  7834. {
  7835. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7836. if (in != 0)
  7837. return in->readEntireStreamAsString();
  7838. return String::empty;
  7839. }
  7840. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7841. {
  7842. return XmlDocument::parse (readEntireTextStream (usePostCommand));
  7843. }
  7844. const URL URL::withParameter (const String& parameterName,
  7845. const String& parameterValue) const
  7846. {
  7847. URL u (*this);
  7848. u.parameters.set (parameterName, parameterValue);
  7849. return u;
  7850. }
  7851. const URL URL::withFileToUpload (const String& parameterName,
  7852. const File& fileToUpload,
  7853. const String& mimeType) const
  7854. {
  7855. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7856. URL u (*this);
  7857. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7858. u.mimeTypes.set (parameterName, mimeType);
  7859. return u;
  7860. }
  7861. const URL URL::withPOSTData (const String& postData_) const
  7862. {
  7863. URL u (*this);
  7864. u.postData = postData_;
  7865. return u;
  7866. }
  7867. const StringPairArray& URL::getParameters() const
  7868. {
  7869. return parameters;
  7870. }
  7871. const StringPairArray& URL::getFilesToUpload() const
  7872. {
  7873. return filesToUpload;
  7874. }
  7875. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7876. {
  7877. return mimeTypes;
  7878. }
  7879. const String URL::removeEscapeChars (const String& s)
  7880. {
  7881. String result (s.replaceCharacter ('+', ' '));
  7882. if (! result.containsChar ('%'))
  7883. return result;
  7884. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7885. // after all the replacements have been made, so that multi-byte chars are handled.
  7886. Array<char> utf8 (result.toUTF8().getAddress(), result.getNumBytesAsUTF8());
  7887. for (int i = 0; i < utf8.size(); ++i)
  7888. {
  7889. if (utf8.getUnchecked(i) == '%')
  7890. {
  7891. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7892. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7893. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7894. {
  7895. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7896. utf8.removeRange (i + 1, 2);
  7897. }
  7898. }
  7899. }
  7900. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7901. }
  7902. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7903. {
  7904. const CharPointer_UTF8 legalChars (isParameter ? "_-.*!'()"
  7905. : ",$_-.*!'()");
  7906. Array<char> utf8 (s.toUTF8().getAddress(), s.getNumBytesAsUTF8());
  7907. for (int i = 0; i < utf8.size(); ++i)
  7908. {
  7909. const char c = utf8.getUnchecked(i);
  7910. if (! (CharacterFunctions::isLetterOrDigit (c)
  7911. || legalChars.indexOf ((juce_wchar) c) >= 0))
  7912. {
  7913. if (c == ' ')
  7914. {
  7915. utf8.set (i, '+');
  7916. }
  7917. else
  7918. {
  7919. static const char* const hexDigits = "0123456789abcdef";
  7920. utf8.set (i, '%');
  7921. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7922. utf8.insert (++i, hexDigits [c & 15]);
  7923. }
  7924. }
  7925. }
  7926. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7927. }
  7928. bool URL::launchInDefaultBrowser() const
  7929. {
  7930. String u (toString (true));
  7931. if (u.containsChar ('@') && ! u.containsChar (':'))
  7932. u = "mailto:" + u;
  7933. return PlatformUtilities::openDocument (u, String::empty);
  7934. }
  7935. END_JUCE_NAMESPACE
  7936. /*** End of inlined file: juce_URL.cpp ***/
  7937. /*** Start of inlined file: juce_MACAddress.cpp ***/
  7938. BEGIN_JUCE_NAMESPACE
  7939. MACAddress::MACAddress()
  7940. : asInt64 (0)
  7941. {
  7942. }
  7943. MACAddress::MACAddress (const MACAddress& other)
  7944. : asInt64 (other.asInt64)
  7945. {
  7946. }
  7947. MACAddress& MACAddress::operator= (const MACAddress& other)
  7948. {
  7949. asInt64 = other.asInt64;
  7950. return *this;
  7951. }
  7952. MACAddress::MACAddress (const uint8 bytes[6])
  7953. : asInt64 (0)
  7954. {
  7955. memcpy (asBytes, bytes, sizeof (asBytes));
  7956. }
  7957. const String MACAddress::toString() const
  7958. {
  7959. String s;
  7960. s.preallocateStorage (18);
  7961. for (int i = 0; i < numElementsInArray (asBytes); ++i)
  7962. {
  7963. s << String::toHexString ((int) asBytes[i]).paddedLeft ('0', 2);
  7964. if (i < numElementsInArray (asBytes) - 1)
  7965. s << '-';
  7966. }
  7967. return s;
  7968. }
  7969. int64 MACAddress::toInt64() const throw()
  7970. {
  7971. int64 n = 0;
  7972. for (int i = numElementsInArray (asBytes); --i >= 0;)
  7973. n = (n << 8) | asBytes[i];
  7974. return n;
  7975. }
  7976. bool MACAddress::isNull() const throw() { return asInt64 == 0; }
  7977. bool MACAddress::operator== (const MACAddress& other) const throw() { return asInt64 == other.asInt64; }
  7978. bool MACAddress::operator!= (const MACAddress& other) const throw() { return asInt64 != other.asInt64; }
  7979. END_JUCE_NAMESPACE
  7980. /*** End of inlined file: juce_MACAddress.cpp ***/
  7981. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7982. BEGIN_JUCE_NAMESPACE
  7983. namespace
  7984. {
  7985. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7986. {
  7987. // You need to supply a real stream when creating a BufferedInputStream
  7988. jassert (source != 0);
  7989. requestedSize = jmax (256, requestedSize);
  7990. const int64 sourceSize = source->getTotalLength();
  7991. if (sourceSize >= 0 && sourceSize < requestedSize)
  7992. requestedSize = jmax (32, (int) sourceSize);
  7993. return requestedSize;
  7994. }
  7995. }
  7996. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7997. const bool deleteSourceWhenDestroyed)
  7998. : source (sourceStream),
  7999. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  8000. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  8001. position (sourceStream->getPosition()),
  8002. lastReadPos (0),
  8003. bufferStart (position),
  8004. bufferOverlap (128)
  8005. {
  8006. buffer.malloc (bufferSize);
  8007. }
  8008. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  8009. : source (&sourceStream),
  8010. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  8011. position (sourceStream.getPosition()),
  8012. lastReadPos (0),
  8013. bufferStart (position),
  8014. bufferOverlap (128)
  8015. {
  8016. buffer.malloc (bufferSize);
  8017. }
  8018. BufferedInputStream::~BufferedInputStream()
  8019. {
  8020. }
  8021. int64 BufferedInputStream::getTotalLength()
  8022. {
  8023. return source->getTotalLength();
  8024. }
  8025. int64 BufferedInputStream::getPosition()
  8026. {
  8027. return position;
  8028. }
  8029. bool BufferedInputStream::setPosition (int64 newPosition)
  8030. {
  8031. position = jmax ((int64) 0, newPosition);
  8032. return true;
  8033. }
  8034. bool BufferedInputStream::isExhausted()
  8035. {
  8036. return (position >= lastReadPos)
  8037. && source->isExhausted();
  8038. }
  8039. void BufferedInputStream::ensureBuffered()
  8040. {
  8041. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  8042. if (position < bufferStart || position >= bufferEndOverlap)
  8043. {
  8044. int bytesRead;
  8045. if (position < lastReadPos
  8046. && position >= bufferEndOverlap
  8047. && position >= bufferStart)
  8048. {
  8049. const int bytesToKeep = (int) (lastReadPos - position);
  8050. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  8051. bufferStart = position;
  8052. bytesRead = source->read (buffer + bytesToKeep,
  8053. bufferSize - bytesToKeep);
  8054. lastReadPos += bytesRead;
  8055. bytesRead += bytesToKeep;
  8056. }
  8057. else
  8058. {
  8059. bufferStart = position;
  8060. source->setPosition (bufferStart);
  8061. bytesRead = source->read (buffer, bufferSize);
  8062. lastReadPos = bufferStart + bytesRead;
  8063. }
  8064. while (bytesRead < bufferSize)
  8065. buffer [bytesRead++] = 0;
  8066. }
  8067. }
  8068. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  8069. {
  8070. if (position >= bufferStart
  8071. && position + maxBytesToRead <= lastReadPos)
  8072. {
  8073. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  8074. position += maxBytesToRead;
  8075. return maxBytesToRead;
  8076. }
  8077. else
  8078. {
  8079. if (position < bufferStart || position >= lastReadPos)
  8080. ensureBuffered();
  8081. int bytesRead = 0;
  8082. while (maxBytesToRead > 0)
  8083. {
  8084. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  8085. if (bytesAvailable > 0)
  8086. {
  8087. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  8088. maxBytesToRead -= bytesAvailable;
  8089. bytesRead += bytesAvailable;
  8090. position += bytesAvailable;
  8091. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  8092. }
  8093. const int64 oldLastReadPos = lastReadPos;
  8094. ensureBuffered();
  8095. if (oldLastReadPos == lastReadPos)
  8096. break; // if ensureBuffered() failed to read any more data, bail out
  8097. if (isExhausted())
  8098. break;
  8099. }
  8100. return bytesRead;
  8101. }
  8102. }
  8103. const String BufferedInputStream::readString()
  8104. {
  8105. if (position >= bufferStart
  8106. && position < lastReadPos)
  8107. {
  8108. const int maxChars = (int) (lastReadPos - position);
  8109. const char* const src = buffer + (int) (position - bufferStart);
  8110. for (int i = 0; i < maxChars; ++i)
  8111. {
  8112. if (src[i] == 0)
  8113. {
  8114. position += i + 1;
  8115. return String::fromUTF8 (src, i);
  8116. }
  8117. }
  8118. }
  8119. return InputStream::readString();
  8120. }
  8121. END_JUCE_NAMESPACE
  8122. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  8123. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  8124. BEGIN_JUCE_NAMESPACE
  8125. FileInputSource::FileInputSource (const File& file_, bool useFileTimeInHashGeneration_)
  8126. : file (file_), useFileTimeInHashGeneration (useFileTimeInHashGeneration_)
  8127. {
  8128. }
  8129. FileInputSource::~FileInputSource()
  8130. {
  8131. }
  8132. InputStream* FileInputSource::createInputStream()
  8133. {
  8134. return file.createInputStream();
  8135. }
  8136. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  8137. {
  8138. return file.getSiblingFile (relatedItemPath).createInputStream();
  8139. }
  8140. int64 FileInputSource::hashCode() const
  8141. {
  8142. int64 h = file.hashCode();
  8143. if (useFileTimeInHashGeneration)
  8144. h ^= file.getLastModificationTime().toMilliseconds();
  8145. return h;
  8146. }
  8147. END_JUCE_NAMESPACE
  8148. /*** End of inlined file: juce_FileInputSource.cpp ***/
  8149. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  8150. BEGIN_JUCE_NAMESPACE
  8151. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  8152. const size_t sourceDataSize,
  8153. const bool keepInternalCopy)
  8154. : data (static_cast <const char*> (sourceData)),
  8155. dataSize (sourceDataSize),
  8156. position (0)
  8157. {
  8158. if (keepInternalCopy)
  8159. {
  8160. internalCopy.append (data, sourceDataSize);
  8161. data = static_cast <const char*> (internalCopy.getData());
  8162. }
  8163. }
  8164. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8165. const bool keepInternalCopy)
  8166. : data (static_cast <const char*> (sourceData.getData())),
  8167. dataSize (sourceData.getSize()),
  8168. position (0)
  8169. {
  8170. if (keepInternalCopy)
  8171. {
  8172. internalCopy = sourceData;
  8173. data = static_cast <const char*> (internalCopy.getData());
  8174. }
  8175. }
  8176. MemoryInputStream::~MemoryInputStream()
  8177. {
  8178. }
  8179. int64 MemoryInputStream::getTotalLength()
  8180. {
  8181. return dataSize;
  8182. }
  8183. int MemoryInputStream::read (void* const buffer, const int howMany)
  8184. {
  8185. jassert (howMany >= 0);
  8186. const int num = jmin (howMany, (int) (dataSize - position));
  8187. memcpy (buffer, data + position, num);
  8188. position += num;
  8189. return (int) num;
  8190. }
  8191. bool MemoryInputStream::isExhausted()
  8192. {
  8193. return (position >= dataSize);
  8194. }
  8195. bool MemoryInputStream::setPosition (const int64 pos)
  8196. {
  8197. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8198. return true;
  8199. }
  8200. int64 MemoryInputStream::getPosition()
  8201. {
  8202. return position;
  8203. }
  8204. #if JUCE_UNIT_TESTS
  8205. class MemoryStreamTests : public UnitTest
  8206. {
  8207. public:
  8208. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8209. void runTest()
  8210. {
  8211. beginTest ("Basics");
  8212. int randomInt = Random::getSystemRandom().nextInt();
  8213. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8214. double randomDouble = Random::getSystemRandom().nextDouble();
  8215. String randomString;
  8216. for (int i = 50; --i >= 0;)
  8217. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8218. MemoryOutputStream mo;
  8219. mo.writeInt (randomInt);
  8220. mo.writeIntBigEndian (randomInt);
  8221. mo.writeCompressedInt (randomInt);
  8222. mo.writeString (randomString);
  8223. mo.writeInt64 (randomInt64);
  8224. mo.writeInt64BigEndian (randomInt64);
  8225. mo.writeDouble (randomDouble);
  8226. mo.writeDoubleBigEndian (randomDouble);
  8227. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8228. expect (mi.readInt() == randomInt);
  8229. expect (mi.readIntBigEndian() == randomInt);
  8230. expect (mi.readCompressedInt() == randomInt);
  8231. expect (mi.readString() == randomString);
  8232. expect (mi.readInt64() == randomInt64);
  8233. expect (mi.readInt64BigEndian() == randomInt64);
  8234. expect (mi.readDouble() == randomDouble);
  8235. expect (mi.readDoubleBigEndian() == randomDouble);
  8236. }
  8237. };
  8238. static MemoryStreamTests memoryInputStreamUnitTests;
  8239. #endif
  8240. END_JUCE_NAMESPACE
  8241. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8242. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8243. BEGIN_JUCE_NAMESPACE
  8244. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8245. : data (internalBlock),
  8246. position (0),
  8247. size (0)
  8248. {
  8249. internalBlock.setSize (initialSize, false);
  8250. }
  8251. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8252. const bool appendToExistingBlockContent)
  8253. : data (memoryBlockToWriteTo),
  8254. position (0),
  8255. size (0)
  8256. {
  8257. if (appendToExistingBlockContent)
  8258. position = size = memoryBlockToWriteTo.getSize();
  8259. }
  8260. MemoryOutputStream::~MemoryOutputStream()
  8261. {
  8262. flush();
  8263. }
  8264. void MemoryOutputStream::flush()
  8265. {
  8266. if (&data != &internalBlock)
  8267. data.setSize (size, false);
  8268. }
  8269. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8270. {
  8271. data.ensureSize (bytesToPreallocate + 1);
  8272. }
  8273. void MemoryOutputStream::reset() throw()
  8274. {
  8275. position = 0;
  8276. size = 0;
  8277. }
  8278. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8279. {
  8280. if (howMany > 0)
  8281. {
  8282. const size_t storageNeeded = position + howMany;
  8283. if (storageNeeded >= data.getSize())
  8284. data.ensureSize ((storageNeeded + jmin ((int) (storageNeeded / 2), 1024 * 1024) + 32) & ~31);
  8285. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8286. position += howMany;
  8287. size = jmax (size, position);
  8288. }
  8289. return true;
  8290. }
  8291. const void* MemoryOutputStream::getData() const throw()
  8292. {
  8293. void* const d = data.getData();
  8294. if (data.getSize() > size)
  8295. static_cast <char*> (d) [size] = 0;
  8296. return d;
  8297. }
  8298. bool MemoryOutputStream::setPosition (int64 newPosition)
  8299. {
  8300. if (newPosition <= (int64) size)
  8301. {
  8302. // ok to seek backwards
  8303. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8304. return true;
  8305. }
  8306. else
  8307. {
  8308. // trying to make it bigger isn't a good thing to do..
  8309. return false;
  8310. }
  8311. }
  8312. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8313. {
  8314. // before writing from an input, see if we can preallocate to make it more efficient..
  8315. int64 availableData = source.getTotalLength() - source.getPosition();
  8316. if (availableData > 0)
  8317. {
  8318. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8319. availableData = maxNumBytesToWrite;
  8320. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8321. }
  8322. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8323. }
  8324. const String MemoryOutputStream::toUTF8() const
  8325. {
  8326. return String::fromUTF8 (static_cast <const char*> (getData()), getDataSize());
  8327. }
  8328. const String MemoryOutputStream::toString() const
  8329. {
  8330. return String::createStringFromData (getData(), (int) getDataSize());
  8331. }
  8332. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8333. {
  8334. stream.write (streamToRead.getData(), (int) streamToRead.getDataSize());
  8335. return stream;
  8336. }
  8337. END_JUCE_NAMESPACE
  8338. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8339. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8340. BEGIN_JUCE_NAMESPACE
  8341. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8342. const int64 startPositionInSourceStream_,
  8343. const int64 lengthOfSourceStream_,
  8344. const bool deleteSourceWhenDestroyed)
  8345. : source (sourceStream),
  8346. startPositionInSourceStream (startPositionInSourceStream_),
  8347. lengthOfSourceStream (lengthOfSourceStream_)
  8348. {
  8349. if (deleteSourceWhenDestroyed)
  8350. sourceToDelete = source;
  8351. setPosition (0);
  8352. }
  8353. SubregionStream::~SubregionStream()
  8354. {
  8355. }
  8356. int64 SubregionStream::getTotalLength()
  8357. {
  8358. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8359. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8360. : srcLen;
  8361. }
  8362. int64 SubregionStream::getPosition()
  8363. {
  8364. return source->getPosition() - startPositionInSourceStream;
  8365. }
  8366. bool SubregionStream::setPosition (int64 newPosition)
  8367. {
  8368. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8369. }
  8370. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8371. {
  8372. if (lengthOfSourceStream < 0)
  8373. {
  8374. return source->read (destBuffer, maxBytesToRead);
  8375. }
  8376. else
  8377. {
  8378. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8379. if (maxBytesToRead <= 0)
  8380. return 0;
  8381. return source->read (destBuffer, maxBytesToRead);
  8382. }
  8383. }
  8384. bool SubregionStream::isExhausted()
  8385. {
  8386. if (lengthOfSourceStream >= 0)
  8387. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8388. else
  8389. return source->isExhausted();
  8390. }
  8391. END_JUCE_NAMESPACE
  8392. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8393. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8394. BEGIN_JUCE_NAMESPACE
  8395. PerformanceCounter::PerformanceCounter (const String& name_,
  8396. int runsPerPrintout,
  8397. const File& loggingFile)
  8398. : name (name_),
  8399. numRuns (0),
  8400. runsPerPrint (runsPerPrintout),
  8401. totalTime (0),
  8402. outputFile (loggingFile)
  8403. {
  8404. if (outputFile != File::nonexistent)
  8405. {
  8406. String s ("**** Counter for \"");
  8407. s << name_ << "\" started at: "
  8408. << Time::getCurrentTime().toString (true, true)
  8409. << newLine;
  8410. outputFile.appendText (s, false, false);
  8411. }
  8412. }
  8413. PerformanceCounter::~PerformanceCounter()
  8414. {
  8415. printStatistics();
  8416. }
  8417. void PerformanceCounter::start()
  8418. {
  8419. started = Time::getHighResolutionTicks();
  8420. }
  8421. void PerformanceCounter::stop()
  8422. {
  8423. const int64 now = Time::getHighResolutionTicks();
  8424. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8425. if (++numRuns == runsPerPrint)
  8426. printStatistics();
  8427. }
  8428. void PerformanceCounter::printStatistics()
  8429. {
  8430. if (numRuns > 0)
  8431. {
  8432. String s ("Performance count for \"");
  8433. s << name << "\" - average over " << numRuns << " run(s) = ";
  8434. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8435. if (micros > 10000)
  8436. s << (micros/1000) << " millisecs";
  8437. else
  8438. s << micros << " microsecs";
  8439. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8440. Logger::outputDebugString (s);
  8441. s << newLine;
  8442. if (outputFile != File::nonexistent)
  8443. outputFile.appendText (s, false, false);
  8444. numRuns = 0;
  8445. totalTime = 0;
  8446. }
  8447. }
  8448. END_JUCE_NAMESPACE
  8449. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8450. /*** Start of inlined file: juce_Uuid.cpp ***/
  8451. BEGIN_JUCE_NAMESPACE
  8452. Uuid::Uuid()
  8453. {
  8454. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8455. // to make it very very unlikely that two UUIDs will ever be the same..
  8456. static int64 macAddresses[2];
  8457. static bool hasCheckedMacAddresses = false;
  8458. if (! hasCheckedMacAddresses)
  8459. {
  8460. hasCheckedMacAddresses = true;
  8461. Array<MACAddress> result;
  8462. MACAddress::findAllAddresses (result);
  8463. for (int i = 0; i < numElementsInArray (macAddresses); ++i)
  8464. macAddresses[i] = result[i].toInt64();
  8465. }
  8466. value.asInt64[0] = macAddresses[0];
  8467. value.asInt64[1] = macAddresses[1];
  8468. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8469. // whose seed will carry over between calls to this method.
  8470. Random r (macAddresses[0] ^ macAddresses[1]
  8471. ^ Random::getSystemRandom().nextInt64());
  8472. for (int i = 4; --i >= 0;)
  8473. {
  8474. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8475. value.asInt[i] ^= r.nextInt();
  8476. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8477. }
  8478. }
  8479. Uuid::~Uuid() throw()
  8480. {
  8481. }
  8482. Uuid::Uuid (const Uuid& other)
  8483. : value (other.value)
  8484. {
  8485. }
  8486. Uuid& Uuid::operator= (const Uuid& other)
  8487. {
  8488. value = other.value;
  8489. return *this;
  8490. }
  8491. bool Uuid::operator== (const Uuid& other) const
  8492. {
  8493. return value.asInt64[0] == other.value.asInt64[0]
  8494. && value.asInt64[1] == other.value.asInt64[1];
  8495. }
  8496. bool Uuid::operator!= (const Uuid& other) const
  8497. {
  8498. return ! operator== (other);
  8499. }
  8500. bool Uuid::isNull() const throw()
  8501. {
  8502. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8503. }
  8504. const String Uuid::toString() const
  8505. {
  8506. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8507. }
  8508. Uuid::Uuid (const String& uuidString)
  8509. {
  8510. operator= (uuidString);
  8511. }
  8512. Uuid& Uuid::operator= (const String& uuidString)
  8513. {
  8514. MemoryBlock mb;
  8515. mb.loadFromHexString (uuidString);
  8516. mb.ensureSize (sizeof (value.asBytes), true);
  8517. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8518. return *this;
  8519. }
  8520. Uuid::Uuid (const uint8* const rawData)
  8521. {
  8522. operator= (rawData);
  8523. }
  8524. Uuid& Uuid::operator= (const uint8* const rawData)
  8525. {
  8526. if (rawData != 0)
  8527. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8528. else
  8529. zeromem (value.asBytes, sizeof (value.asBytes));
  8530. return *this;
  8531. }
  8532. END_JUCE_NAMESPACE
  8533. /*** End of inlined file: juce_Uuid.cpp ***/
  8534. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8535. BEGIN_JUCE_NAMESPACE
  8536. class ZipFile::ZipEntryInfo
  8537. {
  8538. public:
  8539. ZipFile::ZipEntry entry;
  8540. int streamOffset;
  8541. int compressedSize;
  8542. bool compressed;
  8543. };
  8544. class ZipFile::ZipInputStream : public InputStream
  8545. {
  8546. public:
  8547. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8548. : file (file_),
  8549. zipEntryInfo (zei),
  8550. pos (0),
  8551. headerSize (0),
  8552. inputStream (0)
  8553. {
  8554. inputStream = file_.inputStream;
  8555. if (file_.inputSource != 0)
  8556. {
  8557. inputStream = streamToDelete = file.inputSource->createInputStream();
  8558. }
  8559. else
  8560. {
  8561. #if JUCE_DEBUG
  8562. file_.numOpenStreams++;
  8563. #endif
  8564. }
  8565. char buffer [30];
  8566. if (inputStream != 0
  8567. && inputStream->setPosition (zei.streamOffset)
  8568. && inputStream->read (buffer, 30) == 30
  8569. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8570. {
  8571. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8572. + ByteOrder::littleEndianShort (buffer + 28);
  8573. }
  8574. }
  8575. ~ZipInputStream()
  8576. {
  8577. #if JUCE_DEBUG
  8578. if (inputStream != 0 && inputStream == file.inputStream)
  8579. file.numOpenStreams--;
  8580. #endif
  8581. }
  8582. int64 getTotalLength()
  8583. {
  8584. return zipEntryInfo.compressedSize;
  8585. }
  8586. int read (void* buffer, int howMany)
  8587. {
  8588. if (headerSize <= 0)
  8589. return 0;
  8590. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8591. if (inputStream == 0)
  8592. return 0;
  8593. int num;
  8594. if (inputStream == file.inputStream)
  8595. {
  8596. const ScopedLock sl (file.lock);
  8597. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8598. num = inputStream->read (buffer, howMany);
  8599. }
  8600. else
  8601. {
  8602. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8603. num = inputStream->read (buffer, howMany);
  8604. }
  8605. pos += num;
  8606. return num;
  8607. }
  8608. bool isExhausted()
  8609. {
  8610. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8611. }
  8612. int64 getPosition()
  8613. {
  8614. return pos;
  8615. }
  8616. bool setPosition (int64 newPos)
  8617. {
  8618. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8619. return true;
  8620. }
  8621. private:
  8622. ZipFile& file;
  8623. ZipEntryInfo zipEntryInfo;
  8624. int64 pos;
  8625. int headerSize;
  8626. InputStream* inputStream;
  8627. ScopedPointer<InputStream> streamToDelete;
  8628. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  8629. };
  8630. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8631. : inputStream (source_)
  8632. #if JUCE_DEBUG
  8633. , numOpenStreams (0)
  8634. #endif
  8635. {
  8636. if (deleteStreamWhenDestroyed)
  8637. streamToDelete = inputStream;
  8638. init();
  8639. }
  8640. ZipFile::ZipFile (const File& file)
  8641. : inputStream (0)
  8642. #if JUCE_DEBUG
  8643. , numOpenStreams (0)
  8644. #endif
  8645. {
  8646. inputSource = new FileInputSource (file);
  8647. init();
  8648. }
  8649. ZipFile::ZipFile (InputSource* const inputSource_)
  8650. : inputStream (0),
  8651. inputSource (inputSource_)
  8652. #if JUCE_DEBUG
  8653. , numOpenStreams (0)
  8654. #endif
  8655. {
  8656. init();
  8657. }
  8658. ZipFile::~ZipFile()
  8659. {
  8660. #if JUCE_DEBUG
  8661. entries.clear();
  8662. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8663. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8664. Streams can't be kept open after the file is deleted because they need to share the input
  8665. stream that the file uses to read itself.
  8666. */
  8667. jassert (numOpenStreams == 0);
  8668. #endif
  8669. }
  8670. int ZipFile::getNumEntries() const throw()
  8671. {
  8672. return entries.size();
  8673. }
  8674. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8675. {
  8676. ZipEntryInfo* const zei = entries [index];
  8677. return zei != 0 ? &(zei->entry) : 0;
  8678. }
  8679. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8680. {
  8681. for (int i = 0; i < entries.size(); ++i)
  8682. if (entries.getUnchecked (i)->entry.filename == fileName)
  8683. return i;
  8684. return -1;
  8685. }
  8686. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8687. {
  8688. return getEntry (getIndexOfFileName (fileName));
  8689. }
  8690. InputStream* ZipFile::createStreamForEntry (const int index)
  8691. {
  8692. ZipEntryInfo* const zei = entries[index];
  8693. InputStream* stream = 0;
  8694. if (zei != 0)
  8695. {
  8696. stream = new ZipInputStream (*this, *zei);
  8697. if (zei->compressed)
  8698. {
  8699. stream = new GZIPDecompressorInputStream (stream, true, true,
  8700. zei->entry.uncompressedSize);
  8701. // (much faster to unzip in big blocks using a buffer..)
  8702. stream = new BufferedInputStream (stream, 32768, true);
  8703. }
  8704. }
  8705. return stream;
  8706. }
  8707. class ZipFile::ZipFilenameComparator
  8708. {
  8709. public:
  8710. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8711. {
  8712. return first->entry.filename.compare (second->entry.filename);
  8713. }
  8714. };
  8715. void ZipFile::sortEntriesByFilename()
  8716. {
  8717. ZipFilenameComparator sorter;
  8718. entries.sort (sorter);
  8719. }
  8720. void ZipFile::init()
  8721. {
  8722. ScopedPointer <InputStream> toDelete;
  8723. InputStream* in = inputStream;
  8724. if (inputSource != 0)
  8725. {
  8726. in = inputSource->createInputStream();
  8727. toDelete = in;
  8728. }
  8729. if (in != 0)
  8730. {
  8731. int numEntries = 0;
  8732. int pos = findEndOfZipEntryTable (*in, numEntries);
  8733. if (pos >= 0 && pos < in->getTotalLength())
  8734. {
  8735. const int size = (int) (in->getTotalLength() - pos);
  8736. in->setPosition (pos);
  8737. MemoryBlock headerData;
  8738. if (in->readIntoMemoryBlock (headerData, size) == size)
  8739. {
  8740. pos = 0;
  8741. for (int i = 0; i < numEntries; ++i)
  8742. {
  8743. if (pos + 46 > size)
  8744. break;
  8745. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8746. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8747. if (pos + 46 + fileNameLen > size)
  8748. break;
  8749. ZipEntryInfo* const zei = new ZipEntryInfo();
  8750. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8751. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8752. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8753. const int year = 1980 + (date >> 9);
  8754. const int month = ((date >> 5) & 15) - 1;
  8755. const int day = date & 31;
  8756. const int hours = time >> 11;
  8757. const int minutes = (time >> 5) & 63;
  8758. const int seconds = (time & 31) << 1;
  8759. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8760. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8761. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8762. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8763. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8764. entries.add (zei);
  8765. pos += 46 + fileNameLen
  8766. + ByteOrder::littleEndianShort (buffer + 30)
  8767. + ByteOrder::littleEndianShort (buffer + 32);
  8768. }
  8769. }
  8770. }
  8771. }
  8772. }
  8773. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8774. {
  8775. BufferedInputStream in (input, 8192);
  8776. in.setPosition (in.getTotalLength());
  8777. int64 pos = in.getPosition();
  8778. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8779. char buffer [32];
  8780. zeromem (buffer, sizeof (buffer));
  8781. while (pos > lowestPos)
  8782. {
  8783. in.setPosition (pos - 22);
  8784. pos = in.getPosition();
  8785. memcpy (buffer + 22, buffer, 4);
  8786. if (in.read (buffer, 22) != 22)
  8787. return 0;
  8788. for (int i = 0; i < 22; ++i)
  8789. {
  8790. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8791. {
  8792. in.setPosition (pos + i);
  8793. in.read (buffer, 22);
  8794. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8795. return ByteOrder::littleEndianInt (buffer + 16);
  8796. }
  8797. }
  8798. }
  8799. return 0;
  8800. }
  8801. bool ZipFile::uncompressTo (const File& targetDirectory,
  8802. const bool shouldOverwriteFiles)
  8803. {
  8804. for (int i = 0; i < entries.size(); ++i)
  8805. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8806. return false;
  8807. return true;
  8808. }
  8809. bool ZipFile::uncompressEntry (const int index,
  8810. const File& targetDirectory,
  8811. bool shouldOverwriteFiles)
  8812. {
  8813. const ZipEntryInfo* zei = entries [index];
  8814. if (zei != 0)
  8815. {
  8816. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8817. if (zei->entry.filename.endsWithChar ('/'))
  8818. {
  8819. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8820. }
  8821. else
  8822. {
  8823. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8824. if (in != 0)
  8825. {
  8826. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8827. return false;
  8828. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8829. {
  8830. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8831. if (out != 0)
  8832. {
  8833. out->writeFromInputStream (*in, -1);
  8834. out = 0;
  8835. targetFile.setCreationTime (zei->entry.fileTime);
  8836. targetFile.setLastModificationTime (zei->entry.fileTime);
  8837. targetFile.setLastAccessTime (zei->entry.fileTime);
  8838. return true;
  8839. }
  8840. }
  8841. }
  8842. }
  8843. }
  8844. return false;
  8845. }
  8846. END_JUCE_NAMESPACE
  8847. /*** End of inlined file: juce_ZipFile.cpp ***/
  8848. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8849. #if JUCE_MSVC
  8850. #pragma warning (push)
  8851. #pragma warning (disable: 4514 4996)
  8852. #endif
  8853. #if ! JUCE_ANDROID
  8854. #include <cwctype>
  8855. #endif
  8856. #include <cctype>
  8857. #include <ctime>
  8858. BEGIN_JUCE_NAMESPACE
  8859. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  8860. {
  8861. return towupper ((wchar_t) character);
  8862. }
  8863. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  8864. {
  8865. return towlower ((wchar_t) character);
  8866. }
  8867. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  8868. {
  8869. #if JUCE_WINDOWS
  8870. return iswupper ((wchar_t) character) != 0;
  8871. #else
  8872. return toLowerCase (character) != character;
  8873. #endif
  8874. }
  8875. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  8876. {
  8877. #if JUCE_WINDOWS
  8878. return iswlower ((wchar_t) character) != 0;
  8879. #else
  8880. return toUpperCase (character) != character;
  8881. #endif
  8882. }
  8883. bool CharacterFunctions::isWhitespace (const char character) throw()
  8884. {
  8885. return character == ' ' || (character <= 13 && character >= 9);
  8886. }
  8887. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  8888. {
  8889. return iswspace ((wchar_t) character) != 0;
  8890. }
  8891. bool CharacterFunctions::isDigit (const char character) throw()
  8892. {
  8893. return (character >= '0' && character <= '9');
  8894. }
  8895. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  8896. {
  8897. return iswdigit ((wchar_t) character) != 0;
  8898. }
  8899. bool CharacterFunctions::isLetter (const char character) throw()
  8900. {
  8901. return (character >= 'a' && character <= 'z')
  8902. || (character >= 'A' && character <= 'Z');
  8903. }
  8904. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  8905. {
  8906. return iswalpha ((wchar_t) character) != 0;
  8907. }
  8908. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  8909. {
  8910. return (character >= 'a' && character <= 'z')
  8911. || (character >= 'A' && character <= 'Z')
  8912. || (character >= '0' && character <= '9');
  8913. }
  8914. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  8915. {
  8916. return iswalnum ((wchar_t) character) != 0;
  8917. }
  8918. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  8919. {
  8920. unsigned int d = digit - '0';
  8921. if (d < (unsigned int) 10)
  8922. return (int) d;
  8923. d += (unsigned int) ('0' - 'a');
  8924. if (d < (unsigned int) 6)
  8925. return (int) d + 10;
  8926. d += (unsigned int) ('a' - 'A');
  8927. if (d < (unsigned int) 6)
  8928. return (int) d + 10;
  8929. return -1;
  8930. }
  8931. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8932. {
  8933. return (int) strftime (dest, maxChars, format, tm);
  8934. }
  8935. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8936. {
  8937. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  8938. HeapBlock <char> tempDest;
  8939. tempDest.calloc (maxChars + 2);
  8940. int result = ftime (tempDest.getData(), maxChars, String (format).toUTF8(), tm);
  8941. CharPointer_UTF32 (dest).writeAll (CharPointer_UTF8 (tempDest.getData()));
  8942. return result;
  8943. #else
  8944. return (int) wcsftime (dest, maxChars, format, tm);
  8945. #endif
  8946. }
  8947. #if JUCE_MSVC
  8948. #pragma warning (pop)
  8949. #endif
  8950. double CharacterFunctions::mulexp10 (const double value, int exponent) throw()
  8951. {
  8952. if (exponent == 0)
  8953. return value;
  8954. if (value == 0)
  8955. return 0;
  8956. const bool negative = (exponent < 0);
  8957. if (negative)
  8958. exponent = -exponent;
  8959. double result = 1.0, power = 10.0;
  8960. for (int bit = 1; exponent != 0; bit <<= 1)
  8961. {
  8962. if ((exponent & bit) != 0)
  8963. {
  8964. exponent ^= bit;
  8965. result *= power;
  8966. if (exponent == 0)
  8967. break;
  8968. }
  8969. power *= power;
  8970. }
  8971. return negative ? (value / result) : (value * result);
  8972. }
  8973. END_JUCE_NAMESPACE
  8974. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  8975. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  8976. BEGIN_JUCE_NAMESPACE
  8977. LocalisedStrings::LocalisedStrings (const String& fileContents)
  8978. {
  8979. loadFromText (fileContents);
  8980. }
  8981. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  8982. {
  8983. loadFromText (fileToLoad.loadFileAsString());
  8984. }
  8985. LocalisedStrings::~LocalisedStrings()
  8986. {
  8987. }
  8988. const String LocalisedStrings::translate (const String& text) const
  8989. {
  8990. return translations.getValue (text, text);
  8991. }
  8992. namespace
  8993. {
  8994. CriticalSection currentMappingsLock;
  8995. LocalisedStrings* currentMappings = 0;
  8996. int findCloseQuote (const String& text, int startPos)
  8997. {
  8998. juce_wchar lastChar = 0;
  8999. for (;;)
  9000. {
  9001. const juce_wchar c = text [startPos];
  9002. if (c == 0 || (c == '"' && lastChar != '\\'))
  9003. break;
  9004. lastChar = c;
  9005. ++startPos;
  9006. }
  9007. return startPos;
  9008. }
  9009. const String unescapeString (const String& s)
  9010. {
  9011. return s.replace ("\\\"", "\"")
  9012. .replace ("\\\'", "\'")
  9013. .replace ("\\t", "\t")
  9014. .replace ("\\r", "\r")
  9015. .replace ("\\n", "\n");
  9016. }
  9017. }
  9018. void LocalisedStrings::loadFromText (const String& fileContents)
  9019. {
  9020. StringArray lines;
  9021. lines.addLines (fileContents);
  9022. for (int i = 0; i < lines.size(); ++i)
  9023. {
  9024. String line (lines[i].trim());
  9025. if (line.startsWithChar ('"'))
  9026. {
  9027. int closeQuote = findCloseQuote (line, 1);
  9028. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9029. if (originalText.isNotEmpty())
  9030. {
  9031. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9032. closeQuote = findCloseQuote (line, openingQuote + 1);
  9033. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9034. if (newText.isNotEmpty())
  9035. translations.set (originalText, newText);
  9036. }
  9037. }
  9038. else if (line.startsWithIgnoreCase ("language:"))
  9039. {
  9040. languageName = line.substring (9).trim();
  9041. }
  9042. else if (line.startsWithIgnoreCase ("countries:"))
  9043. {
  9044. countryCodes.addTokens (line.substring (10).trim(), true);
  9045. countryCodes.trim();
  9046. countryCodes.removeEmptyStrings();
  9047. }
  9048. }
  9049. }
  9050. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9051. {
  9052. translations.setIgnoresCase (shouldIgnoreCase);
  9053. }
  9054. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9055. {
  9056. const ScopedLock sl (currentMappingsLock);
  9057. delete currentMappings;
  9058. currentMappings = newTranslations;
  9059. }
  9060. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9061. {
  9062. return currentMappings;
  9063. }
  9064. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9065. {
  9066. const ScopedLock sl (currentMappingsLock);
  9067. if (currentMappings != 0)
  9068. return currentMappings->translate (text);
  9069. return text;
  9070. }
  9071. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9072. {
  9073. return translateWithCurrentMappings (String (text));
  9074. }
  9075. END_JUCE_NAMESPACE
  9076. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9077. /*** Start of inlined file: juce_String.cpp ***/
  9078. #if JUCE_MSVC
  9079. #pragma warning (push)
  9080. #pragma warning (disable: 4514 4996)
  9081. #endif
  9082. #include <locale>
  9083. BEGIN_JUCE_NAMESPACE
  9084. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9085. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9086. #endif
  9087. NewLine newLine;
  9088. class StringHolder
  9089. {
  9090. public:
  9091. StringHolder()
  9092. : refCount (0x3fffffff), allocatedNumChars (0)
  9093. {
  9094. text[0] = 0;
  9095. }
  9096. typedef String::CharPointerType CharPointerType;
  9097. static const CharPointerType createUninitialised (const size_t numChars)
  9098. {
  9099. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9100. s->refCount.value = 0;
  9101. s->allocatedNumChars = numChars;
  9102. return CharPointerType (&(s->text[0]));
  9103. }
  9104. template <class CharPointer>
  9105. static const CharPointerType createFromCharPointer (const CharPointer& text)
  9106. {
  9107. if (text.getAddress() == 0 || text.isEmpty())
  9108. return getEmpty();
  9109. const size_t numChars = text.length();
  9110. const CharPointerType dest (createUninitialised (numChars));
  9111. CharPointerType (dest).writeAll (text);
  9112. return dest;
  9113. }
  9114. template <class CharPointer>
  9115. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  9116. {
  9117. if (text.getAddress() == 0 || text.isEmpty())
  9118. return getEmpty();
  9119. size_t numChars = text.lengthUpTo (maxChars);
  9120. if (numChars == 0)
  9121. return getEmpty();
  9122. const CharPointerType dest (createUninitialised (numChars));
  9123. CharPointerType (dest).writeWithCharLimit (text, (int) (numChars + 1));
  9124. return dest;
  9125. }
  9126. static CharPointerType createFromFixedLength (const juce_wchar* const src, const size_t numChars)
  9127. {
  9128. CharPointerType dest (createUninitialised (numChars));
  9129. copyChars (dest, CharPointerType (src), (int) numChars);
  9130. return dest;
  9131. }
  9132. static const CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  9133. {
  9134. const CharPointerType dest (createUninitialised (numChars));
  9135. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  9136. return dest;
  9137. }
  9138. static inline const CharPointerType getEmpty() throw()
  9139. {
  9140. return CharPointerType (&(empty.text[0]));
  9141. }
  9142. static void retain (const CharPointerType& text) throw()
  9143. {
  9144. ++(bufferFromText (text)->refCount);
  9145. }
  9146. static inline void release (StringHolder* const b) throw()
  9147. {
  9148. if (--(b->refCount) == -1 && b != &empty)
  9149. delete[] reinterpret_cast <char*> (b);
  9150. }
  9151. static void release (const CharPointerType& text) throw()
  9152. {
  9153. release (bufferFromText (text));
  9154. }
  9155. static CharPointerType makeUnique (const CharPointerType& text)
  9156. {
  9157. StringHolder* const b = bufferFromText (text);
  9158. if (b->refCount.get() <= 0)
  9159. return text;
  9160. CharPointerType newText (createFromFixedLength (text, b->allocatedNumChars));
  9161. release (b);
  9162. return newText;
  9163. }
  9164. static CharPointerType makeUniqueWithSize (const CharPointerType& text, size_t numChars)
  9165. {
  9166. StringHolder* const b = bufferFromText (text);
  9167. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9168. return text;
  9169. CharPointerType newText (createUninitialised (jmax (b->allocatedNumChars, numChars)));
  9170. copyChars (newText, text, b->allocatedNumChars);
  9171. release (b);
  9172. return newText;
  9173. }
  9174. static size_t getAllocatedNumChars (const CharPointerType& text) throw()
  9175. {
  9176. return bufferFromText (text)->allocatedNumChars;
  9177. }
  9178. static void copyChars (CharPointerType dest, const CharPointerType& src, const size_t numChars) throw()
  9179. {
  9180. jassert (src.getAddress() != 0 && dest.getAddress() != 0);
  9181. memcpy (dest.getAddress(), src.getAddress(), numChars * sizeof (juce_wchar));
  9182. CharPointerType (dest + (int) numChars).writeNull();
  9183. }
  9184. Atomic<int> refCount;
  9185. size_t allocatedNumChars;
  9186. juce_wchar text[1];
  9187. static StringHolder empty;
  9188. private:
  9189. static inline StringHolder* bufferFromText (const CharPointerType& text) throw()
  9190. {
  9191. // (Can't use offsetof() here because of warnings about this not being a POD)
  9192. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  9193. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9194. }
  9195. };
  9196. StringHolder StringHolder::empty;
  9197. const String String::empty;
  9198. void String::appendFixedLength (const juce_wchar* const newText, const int numExtraChars)
  9199. {
  9200. if (numExtraChars > 0)
  9201. {
  9202. const int oldLen = length();
  9203. const int newTotalLen = oldLen + numExtraChars;
  9204. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9205. StringHolder::copyChars (text + oldLen, CharPointer_UTF32 (newText), numExtraChars);
  9206. }
  9207. }
  9208. void String::preallocateStorage (const size_t numChars)
  9209. {
  9210. text = StringHolder::makeUniqueWithSize (text, numChars);
  9211. }
  9212. String::String() throw()
  9213. : text (StringHolder::getEmpty())
  9214. {
  9215. }
  9216. String::~String() throw()
  9217. {
  9218. StringHolder::release (text);
  9219. }
  9220. String::String (const String& other) throw()
  9221. : text (other.text)
  9222. {
  9223. StringHolder::retain (text);
  9224. }
  9225. void String::swapWith (String& other) throw()
  9226. {
  9227. swapVariables (text, other.text);
  9228. }
  9229. String& String::operator= (const String& other) throw()
  9230. {
  9231. StringHolder::retain (other.text);
  9232. StringHolder::release (text.atomicSwap (other.text));
  9233. return *this;
  9234. }
  9235. inline String::Preallocation::Preallocation (const size_t numChars_) : numChars (numChars_) {}
  9236. String::String (const Preallocation& preallocationSize)
  9237. : text (StringHolder::createUninitialised (preallocationSize.numChars))
  9238. {
  9239. }
  9240. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9241. : text (0)
  9242. {
  9243. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9244. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9245. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9246. }
  9247. String::String (const char* const t)
  9248. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  9249. {
  9250. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9251. that contains values greater than 127. These can NOT be correctly converted to unicode
  9252. because there's no way for the String class to know what encoding was used to
  9253. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9254. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9255. string to the String class - so for example if your source data is actually UTF-8,
  9256. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9257. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9258. you use UTF-8 with escape characters in your source code to represent extended characters,
  9259. because there's no other way to represent these strings in a way that isn't dependent on
  9260. the compiler, source code editor and platform.
  9261. */
  9262. jassert (CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  9263. }
  9264. String::String (const char* const t, const size_t maxChars)
  9265. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  9266. {
  9267. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  9268. that contains values greater than 127. These can NOT be correctly converted to unicode
  9269. because there's no way for the String class to know what encoding was used to
  9270. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  9271. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  9272. string to the String class - so for example if your source data is actually UTF-8,
  9273. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  9274. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  9275. you use UTF-8 with escape characters in your source code to represent extended characters,
  9276. because there's no other way to represent these strings in a way that isn't dependent on
  9277. the compiler, source code editor and platform.
  9278. */
  9279. jassert (CharPointer_ASCII::isValidString (t, (int) maxChars));
  9280. }
  9281. String::String (const juce_wchar* const t)
  9282. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t)))
  9283. {
  9284. }
  9285. String::String (const juce_wchar* const t, const size_t maxChars)
  9286. : text (StringHolder::createFromCharPointer (CharPointer_UTF32 (t), maxChars))
  9287. {
  9288. }
  9289. String::String (const CharPointer_UTF8& t)
  9290. : text (StringHolder::createFromCharPointer (t))
  9291. {
  9292. }
  9293. String::String (const CharPointer_UTF16& t)
  9294. : text (StringHolder::createFromCharPointer (t))
  9295. {
  9296. }
  9297. String::String (const CharPointer_UTF32& t)
  9298. : text (StringHolder::createFromCharPointer (t))
  9299. {
  9300. }
  9301. String::String (const CharPointer_UTF32& t, const size_t maxChars)
  9302. : text (StringHolder::createFromCharPointer (t, maxChars))
  9303. {
  9304. }
  9305. String::String (const CharPointer_ASCII& t)
  9306. : text (StringHolder::createFromCharPointer (t))
  9307. {
  9308. }
  9309. #if JUCE_WINDOWS
  9310. String::String (const wchar_t* const t)
  9311. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t)))
  9312. {
  9313. }
  9314. String::String (const wchar_t* const t, size_t maxChars)
  9315. : text (StringHolder::createFromCharPointer (CharPointer_UTF16 (t), maxChars))
  9316. {
  9317. }
  9318. #endif
  9319. const String String::charToString (const juce_wchar character)
  9320. {
  9321. String result (Preallocation (1));
  9322. result.text[0] = character;
  9323. result.text[1] = 0;
  9324. return result;
  9325. }
  9326. namespace NumberToStringConverters
  9327. {
  9328. // pass in a pointer to the END of a buffer..
  9329. juce_wchar* numberToString (juce_wchar* t, const int64 n) throw()
  9330. {
  9331. *--t = 0;
  9332. int64 v = (n >= 0) ? n : -n;
  9333. do
  9334. {
  9335. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9336. v /= 10;
  9337. } while (v > 0);
  9338. if (n < 0)
  9339. *--t = '-';
  9340. return t;
  9341. }
  9342. juce_wchar* numberToString (juce_wchar* t, uint64 v) throw()
  9343. {
  9344. *--t = 0;
  9345. do
  9346. {
  9347. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9348. v /= 10;
  9349. } while (v > 0);
  9350. return t;
  9351. }
  9352. juce_wchar* numberToString (juce_wchar* t, const int n) throw()
  9353. {
  9354. if (n == (int) 0x80000000) // (would cause an overflow)
  9355. return numberToString (t, (int64) n);
  9356. *--t = 0;
  9357. int v = abs (n);
  9358. do
  9359. {
  9360. *--t = (juce_wchar) ('0' + (v % 10));
  9361. v /= 10;
  9362. } while (v > 0);
  9363. if (n < 0)
  9364. *--t = '-';
  9365. return t;
  9366. }
  9367. juce_wchar* numberToString (juce_wchar* t, unsigned int v) throw()
  9368. {
  9369. *--t = 0;
  9370. do
  9371. {
  9372. *--t = (juce_wchar) ('0' + (v % 10));
  9373. v /= 10;
  9374. } while (v > 0);
  9375. return t;
  9376. }
  9377. juce_wchar getDecimalPoint()
  9378. {
  9379. #if JUCE_VC7_OR_EARLIER
  9380. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9381. #else
  9382. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9383. #endif
  9384. return dp;
  9385. }
  9386. char* doubleToString (char* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9387. {
  9388. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9389. {
  9390. char* const end = buffer + numChars;
  9391. char* t = end;
  9392. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9393. *--t = (char) 0;
  9394. while (numDecPlaces >= 0 || v > 0)
  9395. {
  9396. if (numDecPlaces == 0)
  9397. *--t = (char) getDecimalPoint();
  9398. *--t = (char) ('0' + (v % 10));
  9399. v /= 10;
  9400. --numDecPlaces;
  9401. }
  9402. if (n < 0)
  9403. *--t = '-';
  9404. len = end - t - 1;
  9405. return t;
  9406. }
  9407. else
  9408. {
  9409. len = sprintf (buffer, "%.9g", n);
  9410. return buffer;
  9411. }
  9412. }
  9413. template <typename IntegerType>
  9414. const String::CharPointerType createFromInteger (const IntegerType number)
  9415. {
  9416. juce_wchar buffer [32];
  9417. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9418. juce_wchar* const start = numberToString (end, number);
  9419. return StringHolder::createFromFixedLength (start, end - start - 1);
  9420. }
  9421. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  9422. {
  9423. char buffer [48];
  9424. size_t len;
  9425. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9426. return StringHolder::createFromFixedLength (start, len);
  9427. }
  9428. }
  9429. String::String (const int number)
  9430. : text (NumberToStringConverters::createFromInteger (number))
  9431. {
  9432. }
  9433. String::String (const unsigned int number)
  9434. : text (NumberToStringConverters::createFromInteger (number))
  9435. {
  9436. }
  9437. String::String (const short number)
  9438. : text (NumberToStringConverters::createFromInteger ((int) number))
  9439. {
  9440. }
  9441. String::String (const unsigned short number)
  9442. : text (NumberToStringConverters::createFromInteger ((unsigned int) number))
  9443. {
  9444. }
  9445. String::String (const int64 number)
  9446. : text (NumberToStringConverters::createFromInteger (number))
  9447. {
  9448. }
  9449. String::String (const uint64 number)
  9450. : text (NumberToStringConverters::createFromInteger (number))
  9451. {
  9452. }
  9453. String::String (const float number, const int numberOfDecimalPlaces)
  9454. : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces))
  9455. {
  9456. }
  9457. String::String (const double number, const int numberOfDecimalPlaces)
  9458. : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces))
  9459. {
  9460. }
  9461. int String::length() const throw()
  9462. {
  9463. return (int) text.length();
  9464. }
  9465. const juce_wchar String::operator[] (int index) const throw()
  9466. {
  9467. jassert (index == 0 || isPositiveAndNotGreaterThan (index, length()));
  9468. return text [index];
  9469. }
  9470. int String::hashCode() const throw()
  9471. {
  9472. const juce_wchar* t = text;
  9473. int result = 0;
  9474. while (*t != (juce_wchar) 0)
  9475. result = 31 * result + *t++;
  9476. return result;
  9477. }
  9478. int64 String::hashCode64() const throw()
  9479. {
  9480. const juce_wchar* t = text;
  9481. int64 result = 0;
  9482. while (*t != (juce_wchar) 0)
  9483. result = 101 * result + *t++;
  9484. return result;
  9485. }
  9486. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw()
  9487. {
  9488. return string1.compare (string2) == 0;
  9489. }
  9490. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw()
  9491. {
  9492. return string1.compare (string2) == 0;
  9493. }
  9494. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9495. {
  9496. return string1.compare (string2) == 0;
  9497. }
  9498. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF8& string2) throw()
  9499. {
  9500. return string1.getCharPointer().compare (string2) == 0;
  9501. }
  9502. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF16& string2) throw()
  9503. {
  9504. return string1.getCharPointer().compare (string2) == 0;
  9505. }
  9506. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const CharPointer_UTF32& string2) throw()
  9507. {
  9508. return string1.getCharPointer().compare (string2) == 0;
  9509. }
  9510. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9511. {
  9512. return string1.compare (string2) != 0;
  9513. }
  9514. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9515. {
  9516. return string1.compare (string2) != 0;
  9517. }
  9518. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9519. {
  9520. return string1.compare (string2) != 0;
  9521. }
  9522. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF8& string2) throw()
  9523. {
  9524. return string1.getCharPointer().compare (string2) != 0;
  9525. }
  9526. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF16& string2) throw()
  9527. {
  9528. return string1.getCharPointer().compare (string2) != 0;
  9529. }
  9530. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const CharPointer_UTF32& string2) throw()
  9531. {
  9532. return string1.getCharPointer().compare (string2) != 0;
  9533. }
  9534. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9535. {
  9536. return string1.compare (string2) > 0;
  9537. }
  9538. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9539. {
  9540. return string1.compare (string2) < 0;
  9541. }
  9542. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9543. {
  9544. return string1.compare (string2) >= 0;
  9545. }
  9546. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9547. {
  9548. return string1.compare (string2) <= 0;
  9549. }
  9550. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9551. {
  9552. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF32 (t)) == 0
  9553. : isEmpty();
  9554. }
  9555. bool String::equalsIgnoreCase (const char* t) const throw()
  9556. {
  9557. return t != 0 ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  9558. : isEmpty();
  9559. }
  9560. bool String::equalsIgnoreCase (const String& other) const throw()
  9561. {
  9562. return text == other.text
  9563. || text.compareIgnoreCase (other.text) == 0;
  9564. }
  9565. int String::compare (const String& other) const throw()
  9566. {
  9567. return (text == other.text) ? 0 : text.compare (other.text);
  9568. }
  9569. int String::compare (const char* other) const throw()
  9570. {
  9571. return text.compare (CharPointer_UTF8 (other));
  9572. }
  9573. int String::compare (const juce_wchar* other) const throw()
  9574. {
  9575. return text.compare (CharPointer_UTF32 (other));
  9576. }
  9577. int String::compareIgnoreCase (const String& other) const throw()
  9578. {
  9579. return (text == other.text) ? 0 : text.compareIgnoreCase (other.text);
  9580. }
  9581. int String::compareLexicographically (const String& other) const throw()
  9582. {
  9583. CharPointerType s1 (text);
  9584. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  9585. ++s1;
  9586. CharPointerType s2 (other.text);
  9587. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  9588. ++s2;
  9589. return s1.compareIgnoreCase (s2);
  9590. }
  9591. void String::append (const String& textToAppend, size_t maxCharsToTake)
  9592. {
  9593. appendCharPointer (textToAppend.text, maxCharsToTake);
  9594. }
  9595. String& String::operator+= (const juce_wchar* const t)
  9596. {
  9597. appendCharPointer (CharPointer_UTF32 (t));
  9598. return *this;
  9599. }
  9600. String& String::operator+= (const String& other)
  9601. {
  9602. if (isEmpty())
  9603. return operator= (other);
  9604. appendCharPointer (other.text);
  9605. return *this;
  9606. }
  9607. String& String::operator+= (const char ch)
  9608. {
  9609. return operator+= ((juce_wchar) ch);
  9610. }
  9611. String& String::operator+= (const juce_wchar ch)
  9612. {
  9613. const juce_wchar asString[] = { ch, 0 };
  9614. return operator+= (static_cast <const juce_wchar*> (asString));
  9615. }
  9616. #if JUCE_WINDOWS
  9617. String& String::operator+= (const wchar_t ch)
  9618. {
  9619. return operator+= ((juce_wchar) ch);
  9620. }
  9621. String& String::operator+= (const wchar_t* t)
  9622. {
  9623. return operator+= (String (t));
  9624. }
  9625. #endif
  9626. String& String::operator+= (const int number)
  9627. {
  9628. juce_wchar buffer [16];
  9629. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9630. juce_wchar* const start = NumberToStringConverters::numberToString (end, number);
  9631. appendFixedLength (start, (int) (end - start));
  9632. return *this;
  9633. }
  9634. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9635. {
  9636. String s (string1);
  9637. return s += string2;
  9638. }
  9639. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9640. {
  9641. String s (string1);
  9642. return s += string2;
  9643. }
  9644. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9645. {
  9646. return String::charToString (string1) + string2;
  9647. }
  9648. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9649. {
  9650. return String::charToString (string1) + string2;
  9651. }
  9652. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9653. {
  9654. return string1 += string2;
  9655. }
  9656. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9657. {
  9658. return string1 += string2;
  9659. }
  9660. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9661. {
  9662. return string1 += string2;
  9663. }
  9664. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9665. {
  9666. return string1 += string2;
  9667. }
  9668. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9669. {
  9670. return string1 += string2;
  9671. }
  9672. #if JUCE_WINDOWS
  9673. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, wchar_t string2)
  9674. {
  9675. return string1 += string2;
  9676. }
  9677. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const wchar_t* string2)
  9678. {
  9679. string1.appendCharPointer (CharPointer_UTF16 (string2));
  9680. return string1;
  9681. }
  9682. JUCE_API const String JUCE_CALLTYPE operator+ (const wchar_t* string1, const String& string2)
  9683. {
  9684. String s (string1);
  9685. return s += string2;
  9686. }
  9687. #endif
  9688. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9689. {
  9690. return string1 += characterToAppend;
  9691. }
  9692. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9693. {
  9694. return string1 += characterToAppend;
  9695. }
  9696. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9697. {
  9698. return string1 += string2;
  9699. }
  9700. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9701. {
  9702. return string1 += string2;
  9703. }
  9704. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9705. {
  9706. return string1 += string2;
  9707. }
  9708. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9709. {
  9710. return string1 += (int) number;
  9711. }
  9712. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9713. {
  9714. return string1 += number;
  9715. }
  9716. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9717. {
  9718. return string1 += (int) number;
  9719. }
  9720. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9721. {
  9722. return string1 += String (number);
  9723. }
  9724. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9725. {
  9726. return string1 += String (number);
  9727. }
  9728. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9729. {
  9730. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9731. // if lots of large, persistent strings were to be written to streams).
  9732. const int numBytes = text.getNumBytesAsUTF8();
  9733. HeapBlock<char> temp (numBytes + 1);
  9734. text.copyToUTF8 (temp, numBytes + 1);
  9735. stream.write (temp, numBytes);
  9736. return stream;
  9737. }
  9738. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  9739. {
  9740. return string1 += NewLine::getDefault();
  9741. }
  9742. int String::indexOfChar (const juce_wchar character) const throw()
  9743. {
  9744. const juce_wchar* t = text;
  9745. for (;;)
  9746. {
  9747. if (*t == character)
  9748. return (int) (t - text);
  9749. if (*t++ == 0)
  9750. return -1;
  9751. }
  9752. }
  9753. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9754. {
  9755. for (int i = length(); --i >= 0;)
  9756. if (text[i] == character)
  9757. return i;
  9758. return -1;
  9759. }
  9760. int String::indexOf (const String& t) const throw()
  9761. {
  9762. return t.isEmpty() ? 0 : text.indexOf (t.text);
  9763. }
  9764. int String::indexOfChar (const int startIndex,
  9765. const juce_wchar character) const throw()
  9766. {
  9767. if (startIndex > 0 && startIndex >= length())
  9768. return -1;
  9769. const juce_wchar* t = text + jmax (0, startIndex);
  9770. for (;;)
  9771. {
  9772. if (*t == character)
  9773. return (int) (t - text);
  9774. if (*t == 0)
  9775. return -1;
  9776. ++t;
  9777. }
  9778. }
  9779. int String::indexOfAnyOf (const String& charactersToLookFor,
  9780. const int startIndex,
  9781. const bool ignoreCase) const throw()
  9782. {
  9783. if (startIndex > 0 && startIndex >= length())
  9784. return -1;
  9785. CharPointerType t (text);
  9786. int i = jmax (0, startIndex);
  9787. t += i;
  9788. while (! t.isEmpty())
  9789. {
  9790. if (charactersToLookFor.text.indexOf (*t, ignoreCase) >= 0)
  9791. return i;
  9792. ++i;
  9793. ++t;
  9794. }
  9795. return -1;
  9796. }
  9797. int String::indexOf (const int startIndex, const String& other) const throw()
  9798. {
  9799. if (startIndex > 0 && startIndex >= length())
  9800. return -1;
  9801. int i = CharPointerType (text + jmax (0, startIndex)).indexOf (other.text);
  9802. return i >= 0 ? i + startIndex : -1;
  9803. }
  9804. int String::indexOfIgnoreCase (const String& other) const throw()
  9805. {
  9806. if (other.isEmpty())
  9807. return 0;
  9808. const int len = other.length();
  9809. const int end = length() - len;
  9810. for (int i = 0; i <= end; ++i)
  9811. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9812. return i;
  9813. return -1;
  9814. }
  9815. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  9816. {
  9817. if (other.isNotEmpty())
  9818. {
  9819. const int len = other.length();
  9820. const int end = length() - len;
  9821. for (int i = jmax (0, startIndex); i <= end; ++i)
  9822. if (CharPointerType (text + i).compareIgnoreCaseUpTo (other.text, len) == 0)
  9823. return i;
  9824. }
  9825. return -1;
  9826. }
  9827. int String::lastIndexOf (const String& other) const throw()
  9828. {
  9829. if (other.isNotEmpty())
  9830. {
  9831. const int len = other.length();
  9832. int i = length() - len;
  9833. if (i >= 0)
  9834. {
  9835. CharPointerType n (text + i);
  9836. while (i >= 0)
  9837. {
  9838. if (n.compareUpTo (other.text, len) == 0)
  9839. return i;
  9840. --n;
  9841. --i;
  9842. }
  9843. }
  9844. }
  9845. return -1;
  9846. }
  9847. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  9848. {
  9849. if (other.isNotEmpty())
  9850. {
  9851. const int len = other.length();
  9852. int i = length() - len;
  9853. if (i >= 0)
  9854. {
  9855. CharPointerType n (text + i);
  9856. while (i >= 0)
  9857. {
  9858. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  9859. return i;
  9860. --n;
  9861. --i;
  9862. }
  9863. }
  9864. }
  9865. return -1;
  9866. }
  9867. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  9868. {
  9869. for (int i = length(); --i >= 0;)
  9870. if (charactersToLookFor.text.indexOf (text[i], ignoreCase) >= 0)
  9871. return i;
  9872. return -1;
  9873. }
  9874. bool String::contains (const String& other) const throw()
  9875. {
  9876. return indexOf (other) >= 0;
  9877. }
  9878. bool String::containsChar (const juce_wchar character) const throw()
  9879. {
  9880. const juce_wchar* t = text;
  9881. for (;;)
  9882. {
  9883. if (*t == 0)
  9884. return false;
  9885. if (*t == character)
  9886. return true;
  9887. ++t;
  9888. }
  9889. }
  9890. bool String::containsIgnoreCase (const String& t) const throw()
  9891. {
  9892. return indexOfIgnoreCase (t) >= 0;
  9893. }
  9894. int String::indexOfWholeWord (const String& word) const throw()
  9895. {
  9896. if (word.isNotEmpty())
  9897. {
  9898. CharPointerType t (text);
  9899. const int wordLen = word.length();
  9900. const int end = (int) t.length() - wordLen;
  9901. for (int i = 0; i <= end; ++i)
  9902. {
  9903. if (t.compareUpTo (word.text, wordLen) == 0
  9904. && (i == 0 || ! (t - 1).isLetterOrDigit())
  9905. && ! (t + wordLen).isLetterOrDigit())
  9906. return i;
  9907. ++t;
  9908. }
  9909. }
  9910. return -1;
  9911. }
  9912. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  9913. {
  9914. if (word.isNotEmpty())
  9915. {
  9916. CharPointerType t (text);
  9917. const int wordLen = word.length();
  9918. const int end = (int) t.length() - wordLen;
  9919. for (int i = 0; i <= end; ++i)
  9920. {
  9921. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  9922. && (i == 0 || ! (t + -1).isLetterOrDigit())
  9923. && ! (t + wordLen).isLetterOrDigit())
  9924. return i;
  9925. ++t;
  9926. }
  9927. }
  9928. return -1;
  9929. }
  9930. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  9931. {
  9932. return indexOfWholeWord (wordToLookFor) >= 0;
  9933. }
  9934. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  9935. {
  9936. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  9937. }
  9938. namespace WildCardHelpers
  9939. {
  9940. int indexOfMatch (const String::CharPointerType& wildcard,
  9941. String::CharPointerType test,
  9942. const bool ignoreCase) throw()
  9943. {
  9944. int start = 0;
  9945. while (! test.isEmpty())
  9946. {
  9947. String::CharPointerType t (test);
  9948. String::CharPointerType w (wildcard);
  9949. for (;;)
  9950. {
  9951. const juce_wchar wc = *w;
  9952. const juce_wchar tc = *t;
  9953. if (wc == tc
  9954. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9955. || (wc == '?' && tc != 0))
  9956. {
  9957. if (wc == 0)
  9958. return start;
  9959. ++t;
  9960. ++w;
  9961. }
  9962. else
  9963. {
  9964. if (wc == '*' && (w[1] == 0 || indexOfMatch (w + 1, t, ignoreCase) >= 0))
  9965. return start;
  9966. break;
  9967. }
  9968. }
  9969. ++start;
  9970. ++test;
  9971. }
  9972. return -1;
  9973. }
  9974. }
  9975. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  9976. {
  9977. CharPointerType w (wildcard.text);
  9978. CharPointerType t (text);
  9979. for (;;)
  9980. {
  9981. const juce_wchar wc = *w;
  9982. const juce_wchar tc = *t;
  9983. if (wc == tc
  9984. || (ignoreCase && w.toLowerCase() == t.toLowerCase())
  9985. || (wc == '?' && tc != 0))
  9986. {
  9987. if (wc == 0)
  9988. return true;
  9989. ++w;
  9990. ++t;
  9991. }
  9992. else
  9993. {
  9994. return wc == '*' && (w[1] == 0 || WildCardHelpers::indexOfMatch (w + 1, t, ignoreCase) >= 0);
  9995. }
  9996. }
  9997. }
  9998. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  9999. {
  10000. if (numberOfTimesToRepeat <= 0)
  10001. return String::empty;
  10002. const int len = stringToRepeat.length();
  10003. String result (Preallocation (len * numberOfTimesToRepeat + 1));
  10004. CharPointerType n (result.text);
  10005. while (--numberOfTimesToRepeat >= 0)
  10006. {
  10007. StringHolder::copyChars (n, stringToRepeat.text, len);
  10008. n += len;
  10009. }
  10010. return result;
  10011. }
  10012. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10013. {
  10014. jassert (padCharacter != 0);
  10015. const int len = length();
  10016. if (len >= minimumLength || padCharacter == 0)
  10017. return *this;
  10018. String result (Preallocation (minimumLength + 1));
  10019. CharPointerType n (result.text);
  10020. minimumLength -= len;
  10021. while (--minimumLength >= 0)
  10022. n.write (padCharacter);
  10023. StringHolder::copyChars (n, text, len);
  10024. return result;
  10025. }
  10026. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10027. {
  10028. jassert (padCharacter != 0);
  10029. const int len = length();
  10030. if (len >= minimumLength || padCharacter == 0)
  10031. return *this;
  10032. String result (*this, (size_t) minimumLength);
  10033. CharPointerType n (result.text + len);
  10034. minimumLength -= len;
  10035. while (--minimumLength >= 0)
  10036. n.write (padCharacter);
  10037. n.writeNull();
  10038. return result;
  10039. }
  10040. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10041. {
  10042. if (index < 0)
  10043. {
  10044. // a negative index to replace from?
  10045. jassertfalse;
  10046. index = 0;
  10047. }
  10048. if (numCharsToReplace < 0)
  10049. {
  10050. // replacing a negative number of characters?
  10051. numCharsToReplace = 0;
  10052. jassertfalse;
  10053. }
  10054. const int len = length();
  10055. if (index + numCharsToReplace > len)
  10056. {
  10057. if (index > len)
  10058. {
  10059. // replacing beyond the end of the string?
  10060. index = len;
  10061. jassertfalse;
  10062. }
  10063. numCharsToReplace = len - index;
  10064. }
  10065. const int newStringLen = stringToInsert.length();
  10066. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10067. if (newTotalLen <= 0)
  10068. return String::empty;
  10069. String result (Preallocation ((size_t) newTotalLen));
  10070. StringHolder::copyChars (result.text, text, index);
  10071. if (newStringLen > 0)
  10072. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10073. const int endStringLen = newTotalLen - (index + newStringLen);
  10074. if (endStringLen > 0)
  10075. StringHolder::copyChars (result.text + (index + newStringLen),
  10076. text + (index + numCharsToReplace),
  10077. endStringLen);
  10078. return result;
  10079. }
  10080. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10081. {
  10082. const int stringToReplaceLen = stringToReplace.length();
  10083. const int stringToInsertLen = stringToInsert.length();
  10084. int i = 0;
  10085. String result (*this);
  10086. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10087. : result.indexOf (i, stringToReplace))) >= 0)
  10088. {
  10089. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10090. i += stringToInsertLen;
  10091. }
  10092. return result;
  10093. }
  10094. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10095. {
  10096. const int index = indexOfChar (charToReplace);
  10097. if (index < 0)
  10098. return *this;
  10099. String result (*this, size_t());
  10100. CharPointerType t (result.text + index);
  10101. while (! t.isEmpty())
  10102. {
  10103. if (*t == charToReplace)
  10104. t.replaceChar (charToInsert);
  10105. ++t;
  10106. }
  10107. return result;
  10108. }
  10109. const String String::replaceCharacters (const String& charactersToReplace,
  10110. const String& charactersToInsertInstead) const
  10111. {
  10112. String result (*this, size_t());
  10113. CharPointerType t (result.text);
  10114. const int len2 = charactersToInsertInstead.length();
  10115. // the two strings passed in are supposed to be the same length!
  10116. jassert (len2 == charactersToReplace.length());
  10117. while (! t.isEmpty())
  10118. {
  10119. const int index = charactersToReplace.indexOfChar (*t);
  10120. if (isPositiveAndBelow (index, len2))
  10121. t.replaceChar (charactersToInsertInstead [index]);
  10122. ++t;
  10123. }
  10124. return result;
  10125. }
  10126. bool String::startsWith (const String& other) const throw()
  10127. {
  10128. return text.compareUpTo (other.text, other.length()) == 0;
  10129. }
  10130. bool String::startsWithIgnoreCase (const String& other) const throw()
  10131. {
  10132. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  10133. }
  10134. bool String::startsWithChar (const juce_wchar character) const throw()
  10135. {
  10136. jassert (character != 0); // strings can't contain a null character!
  10137. return text[0] == character;
  10138. }
  10139. bool String::endsWithChar (const juce_wchar character) const throw()
  10140. {
  10141. jassert (character != 0); // strings can't contain a null character!
  10142. return text[0] != 0
  10143. && text [length() - 1] == character;
  10144. }
  10145. bool String::endsWith (const String& other) const throw()
  10146. {
  10147. const int thisLen = length();
  10148. const int otherLen = other.length();
  10149. return thisLen >= otherLen
  10150. && CharPointerType (text + thisLen - otherLen).compare (other.text) == 0;
  10151. }
  10152. bool String::endsWithIgnoreCase (const String& other) const throw()
  10153. {
  10154. const int thisLen = length();
  10155. const int otherLen = other.length();
  10156. return thisLen >= otherLen
  10157. && CharPointerType (text + thisLen - otherLen).compareIgnoreCase (other.text) == 0;
  10158. }
  10159. const String String::toUpperCase() const
  10160. {
  10161. String result (Preallocation (this->length()));
  10162. CharPointerType dest (result.text);
  10163. CharPointerType src (text);
  10164. for (;;)
  10165. {
  10166. const juce_wchar c = src.toUpperCase();
  10167. dest.write (c);
  10168. if (c == 0)
  10169. break;
  10170. ++src;
  10171. }
  10172. return result;
  10173. }
  10174. const String String::toLowerCase() const
  10175. {
  10176. String result (Preallocation (this->length()));
  10177. CharPointerType dest (result.text);
  10178. CharPointerType src (text);
  10179. for (;;)
  10180. {
  10181. const juce_wchar c = src.toLowerCase();
  10182. dest.write (c);
  10183. if (c == 0)
  10184. break;
  10185. ++src;
  10186. }
  10187. return result;
  10188. }
  10189. juce_wchar String::getLastCharacter() const throw()
  10190. {
  10191. return isEmpty() ? juce_wchar() : text [length() - 1];
  10192. }
  10193. const String String::substring (int start, int end) const
  10194. {
  10195. if (start < 0)
  10196. start = 0;
  10197. else if (end <= start)
  10198. return empty;
  10199. int len = 0;
  10200. while (len <= end && text [len] != 0)
  10201. ++len;
  10202. if (end >= len)
  10203. {
  10204. if (start == 0)
  10205. return *this;
  10206. end = len;
  10207. }
  10208. return String (text + start, end - start);
  10209. }
  10210. const String String::substring (const int start) const
  10211. {
  10212. if (start <= 0)
  10213. return *this;
  10214. const int len = length();
  10215. if (start >= len)
  10216. return empty;
  10217. return String (text + start, len - start);
  10218. }
  10219. const String String::dropLastCharacters (const int numberToDrop) const
  10220. {
  10221. return String (text, jmax (0, length() - numberToDrop));
  10222. }
  10223. const String String::getLastCharacters (const int numCharacters) const
  10224. {
  10225. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10226. }
  10227. const String String::fromFirstOccurrenceOf (const String& sub,
  10228. const bool includeSubString,
  10229. const bool ignoreCase) const
  10230. {
  10231. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10232. : indexOf (sub);
  10233. if (i < 0)
  10234. return empty;
  10235. return substring (includeSubString ? i : i + sub.length());
  10236. }
  10237. const String String::fromLastOccurrenceOf (const String& sub,
  10238. const bool includeSubString,
  10239. const bool ignoreCase) const
  10240. {
  10241. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10242. : lastIndexOf (sub);
  10243. if (i < 0)
  10244. return *this;
  10245. return substring (includeSubString ? i : i + sub.length());
  10246. }
  10247. const String String::upToFirstOccurrenceOf (const String& sub,
  10248. const bool includeSubString,
  10249. const bool ignoreCase) const
  10250. {
  10251. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10252. : indexOf (sub);
  10253. if (i < 0)
  10254. return *this;
  10255. return substring (0, includeSubString ? i + sub.length() : i);
  10256. }
  10257. const String String::upToLastOccurrenceOf (const String& sub,
  10258. const bool includeSubString,
  10259. const bool ignoreCase) const
  10260. {
  10261. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10262. : lastIndexOf (sub);
  10263. if (i < 0)
  10264. return *this;
  10265. return substring (0, includeSubString ? i + sub.length() : i);
  10266. }
  10267. bool String::isQuotedString() const
  10268. {
  10269. const String trimmed (trimStart());
  10270. return trimmed[0] == '"'
  10271. || trimmed[0] == '\'';
  10272. }
  10273. const String String::unquoted() const
  10274. {
  10275. const int len = length();
  10276. if (len == 0)
  10277. return empty;
  10278. const juce_wchar lastChar = text [len - 1];
  10279. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  10280. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  10281. return substring (dropAtStart, len - dropAtEnd);
  10282. }
  10283. const String String::quoted (const juce_wchar quoteCharacter) const
  10284. {
  10285. if (isEmpty())
  10286. return charToString (quoteCharacter) + quoteCharacter;
  10287. String t (*this);
  10288. if (! t.startsWithChar (quoteCharacter))
  10289. t = charToString (quoteCharacter) + t;
  10290. if (! t.endsWithChar (quoteCharacter))
  10291. t += quoteCharacter;
  10292. return t;
  10293. }
  10294. const String String::trim() const
  10295. {
  10296. if (isEmpty())
  10297. return empty;
  10298. int start = 0;
  10299. while ((text + start).isWhitespace())
  10300. ++start;
  10301. const int len = length();
  10302. int end = len - 1;
  10303. while ((end >= start) && (text + end).isWhitespace())
  10304. --end;
  10305. ++end;
  10306. if (end <= start)
  10307. return empty;
  10308. else if (start > 0 || end < len)
  10309. return String (text + start, end - start);
  10310. return *this;
  10311. }
  10312. const String String::trimStart() const
  10313. {
  10314. if (isEmpty())
  10315. return empty;
  10316. CharPointerType t (text.findEndOfWhitespace());
  10317. if (t == text)
  10318. return *this;
  10319. return String (t);
  10320. }
  10321. const String String::trimEnd() const
  10322. {
  10323. if (isEmpty())
  10324. return empty;
  10325. CharPointerType endT (text);
  10326. endT = endT.findTerminatingNull() - 1;
  10327. while ((endT.getAddress() >= text) && endT.isWhitespace())
  10328. --endT;
  10329. return String (text, 1 + (int) (endT.getAddress() - text));
  10330. }
  10331. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10332. {
  10333. CharPointerType t (text);
  10334. while (charactersToTrim.containsChar (*t))
  10335. ++t;
  10336. return t == text ? *this : String (t);
  10337. }
  10338. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10339. {
  10340. if (isEmpty())
  10341. return empty;
  10342. const int len = length();
  10343. const juce_wchar* endT = text + (len - 1);
  10344. int numToRemove = 0;
  10345. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10346. {
  10347. ++numToRemove;
  10348. --endT;
  10349. }
  10350. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10351. }
  10352. const String String::retainCharacters (const String& charactersToRetain) const
  10353. {
  10354. if (isEmpty())
  10355. return empty;
  10356. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10357. CharPointerType dst (result.text);
  10358. CharPointerType src (text);
  10359. for (;;)
  10360. {
  10361. const juce_wchar c = src.getAndAdvance();
  10362. if (c == 0)
  10363. break;
  10364. if (charactersToRetain.containsChar (c))
  10365. dst.write (c);
  10366. }
  10367. dst.writeNull();
  10368. return result;
  10369. }
  10370. const String String::removeCharacters (const String& charactersToRemove) const
  10371. {
  10372. if (isEmpty())
  10373. return empty;
  10374. String result (Preallocation (StringHolder::getAllocatedNumChars (text)));
  10375. CharPointerType dst (result.text);
  10376. CharPointerType src (text);
  10377. for (;;)
  10378. {
  10379. const juce_wchar c = src.getAndAdvance();
  10380. if (c == 0)
  10381. break;
  10382. if (! charactersToRemove.containsChar (c))
  10383. dst.write (c);
  10384. }
  10385. dst.writeNull();
  10386. return result;
  10387. }
  10388. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10389. {
  10390. int i = 0;
  10391. for (;;)
  10392. {
  10393. if (! permittedCharacters.containsChar (text[i]))
  10394. break;
  10395. ++i;
  10396. }
  10397. return substring (0, i);
  10398. }
  10399. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10400. {
  10401. const juce_wchar* const t = text;
  10402. int i = 0;
  10403. while (t[i] != 0)
  10404. {
  10405. if (charactersToStopAt.containsChar (t[i]))
  10406. return String (text, i);
  10407. ++i;
  10408. }
  10409. return empty;
  10410. }
  10411. bool String::containsOnly (const String& chars) const throw()
  10412. {
  10413. CharPointerType t (text);
  10414. while (! t.isEmpty())
  10415. if (! chars.containsChar (t.getAndAdvance()))
  10416. return false;
  10417. return true;
  10418. }
  10419. bool String::containsAnyOf (const String& chars) const throw()
  10420. {
  10421. const juce_wchar* t = text;
  10422. while (*t != 0)
  10423. if (chars.containsChar (*t++))
  10424. return true;
  10425. return false;
  10426. }
  10427. bool String::containsNonWhitespaceChars() const throw()
  10428. {
  10429. CharPointerType t (text);
  10430. while (! t.isEmpty())
  10431. {
  10432. if (! t.isWhitespace())
  10433. return true;
  10434. ++t;
  10435. }
  10436. return false;
  10437. }
  10438. const String String::formatted (const juce_wchar* const pf, ... )
  10439. {
  10440. jassert (pf != 0);
  10441. va_list args;
  10442. va_start (args, pf);
  10443. size_t bufferSize = 256;
  10444. String result (Preallocation ((size_t) bufferSize));
  10445. result.text[0] = 0;
  10446. for (;;)
  10447. {
  10448. #if JUCE_LINUX && JUCE_64BIT
  10449. va_list tempArgs;
  10450. va_copy (tempArgs, args);
  10451. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, tempArgs);
  10452. va_end (tempArgs);
  10453. #elif JUCE_WINDOWS
  10454. HeapBlock <wchar_t> temp (bufferSize);
  10455. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, String (pf).toUTF16(), args);
  10456. if (num > 0)
  10457. CharPointerType (result.text).writeAll (CharPointer_UTF16 (temp.getData()));
  10458. #elif JUCE_ANDROID
  10459. HeapBlock <char> temp (bufferSize);
  10460. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, String (pf).toUTF8(), args);
  10461. if (num > 0)
  10462. CharPointerType (result.text).writeAll (CharPointer_UTF8 (temp.getData()));
  10463. #else
  10464. const int num = (int) vswprintf (result.text.getAddress(), bufferSize - 1, pf, args);
  10465. #endif
  10466. if (num > 0)
  10467. return result;
  10468. bufferSize += 256;
  10469. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10470. break; // returns -1 because of an error rather than because it needs more space.
  10471. result.preallocateStorage (bufferSize);
  10472. }
  10473. return empty;
  10474. }
  10475. int String::getIntValue() const throw()
  10476. {
  10477. return text.getIntValue32();
  10478. }
  10479. int String::getTrailingIntValue() const throw()
  10480. {
  10481. int n = 0;
  10482. int mult = 1;
  10483. CharPointerType t (text.findTerminatingNull());
  10484. while ((--t).getAddress() >= text)
  10485. {
  10486. if (! t.isDigit())
  10487. {
  10488. if (*t == '-')
  10489. n = -n;
  10490. break;
  10491. }
  10492. n += mult * (*t - '0');
  10493. mult *= 10;
  10494. }
  10495. return n;
  10496. }
  10497. int64 String::getLargeIntValue() const throw()
  10498. {
  10499. return text.getIntValue64();
  10500. }
  10501. float String::getFloatValue() const throw()
  10502. {
  10503. return (float) getDoubleValue();
  10504. }
  10505. double String::getDoubleValue() const throw()
  10506. {
  10507. return text.getDoubleValue();
  10508. }
  10509. static const char* const hexDigits = "0123456789abcdef";
  10510. const String String::toHexString (const int number)
  10511. {
  10512. juce_wchar buffer[32];
  10513. juce_wchar* const end = buffer + 32;
  10514. juce_wchar* t = end;
  10515. *--t = 0;
  10516. unsigned int v = (unsigned int) number;
  10517. do
  10518. {
  10519. *--t = (juce_wchar) hexDigits [v & 15];
  10520. v >>= 4;
  10521. } while (v != 0);
  10522. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10523. }
  10524. const String String::toHexString (const int64 number)
  10525. {
  10526. juce_wchar buffer[32];
  10527. juce_wchar* const end = buffer + 32;
  10528. juce_wchar* t = end;
  10529. *--t = 0;
  10530. uint64 v = (uint64) number;
  10531. do
  10532. {
  10533. *--t = (juce_wchar) hexDigits [(int) (v & 15)];
  10534. v >>= 4;
  10535. } while (v != 0);
  10536. return String (t, (int) (((char*) end) - (char*) t));
  10537. }
  10538. const String String::toHexString (const short number)
  10539. {
  10540. return toHexString ((int) (unsigned short) number);
  10541. }
  10542. const String String::toHexString (const unsigned char* data, const int size, const int groupSize)
  10543. {
  10544. if (size <= 0)
  10545. return empty;
  10546. int numChars = (size * 2) + 2;
  10547. if (groupSize > 0)
  10548. numChars += size / groupSize;
  10549. String s (Preallocation ((size_t) numChars));
  10550. CharPointerType dest (s.text);
  10551. for (int i = 0; i < size; ++i)
  10552. {
  10553. dest.write ((juce_wchar) hexDigits [(*data) >> 4]);
  10554. dest.write ((juce_wchar) hexDigits [(*data) & 0xf]);
  10555. ++data;
  10556. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10557. dest.write ((juce_wchar) ' ');
  10558. }
  10559. dest.writeNull();
  10560. return s;
  10561. }
  10562. int String::getHexValue32() const throw()
  10563. {
  10564. int result = 0;
  10565. CharPointerType t (text);
  10566. while (! t.isEmpty())
  10567. {
  10568. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10569. if (hexValue >= 0)
  10570. result = (result << 4) | hexValue;
  10571. }
  10572. return result;
  10573. }
  10574. int64 String::getHexValue64() const throw()
  10575. {
  10576. int64 result = 0;
  10577. CharPointerType t (text);
  10578. while (! t.isEmpty())
  10579. {
  10580. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  10581. if (hexValue >= 0)
  10582. result = (result << 4) | hexValue;
  10583. }
  10584. return result;
  10585. }
  10586. const String String::createStringFromData (const void* const data_, const int size)
  10587. {
  10588. const uint8* const data = static_cast <const uint8*> (data_);
  10589. if (size <= 0 || data == 0)
  10590. {
  10591. return empty;
  10592. }
  10593. else if (size == 1)
  10594. {
  10595. return charToString ((char) data[0]);
  10596. }
  10597. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  10598. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE1))
  10599. {
  10600. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  10601. const int numChars = size / 2 - 1;
  10602. String result;
  10603. result.preallocateStorage (numChars + 2);
  10604. const uint16* const src = (const uint16*) (data + 2);
  10605. CharPointerType dst (result.getCharPointer());
  10606. if (bigEndian)
  10607. {
  10608. for (int i = 0; i < numChars; ++i)
  10609. dst.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  10610. }
  10611. else
  10612. {
  10613. for (int i = 0; i < numChars; ++i)
  10614. dst.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  10615. }
  10616. dst.writeNull();
  10617. return result;
  10618. }
  10619. else
  10620. {
  10621. if (size >= 3
  10622. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  10623. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  10624. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  10625. return String::fromUTF8 ((const char*) data + 3, size - 3);
  10626. return String::fromUTF8 ((const char*) data, size);
  10627. }
  10628. }
  10629. void* String::createSpaceAtEndOfBuffer (const size_t numExtraBytes) const
  10630. {
  10631. const int currentLen = length() + 1;
  10632. String& mutableThis = const_cast <String&> (*this);
  10633. mutableThis.preallocateStorage (currentLen + 1 + numExtraBytes / sizeof (juce_wchar));
  10634. return (mutableThis.text + currentLen).getAddress();
  10635. }
  10636. const CharPointer_UTF8 String::toUTF8() const
  10637. {
  10638. if (isEmpty())
  10639. return CharPointer_UTF8 (reinterpret_cast <const CharPointer_UTF8::CharType*> (text.getAddress()));
  10640. const size_t extraBytesNeeded = CharPointer_UTF8::getBytesRequiredFor (text);
  10641. CharPointer_UTF8 extraSpace (static_cast <CharPointer_UTF8::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10642. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10643. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10644. #endif
  10645. CharPointer_UTF8 (extraSpace).writeAll (text);
  10646. return extraSpace;
  10647. }
  10648. CharPointer_UTF16 String::toUTF16() const
  10649. {
  10650. if (isEmpty())
  10651. return CharPointer_UTF16 (reinterpret_cast <const CharPointer_UTF16::CharType*> (text.getAddress()));
  10652. const size_t extraBytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text);
  10653. CharPointer_UTF16 extraSpace (static_cast <CharPointer_UTF16::CharType*> (createSpaceAtEndOfBuffer (extraBytesNeeded)));
  10654. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10655. *(juce_wchar*) (addBytesToPointer (extraSpace.getAddress(), (extraBytesNeeded & ~(sizeof (juce_wchar) - 1)))) = 0;
  10656. #endif
  10657. CharPointer_UTF16 (extraSpace).writeAll (text);
  10658. return extraSpace;
  10659. }
  10660. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const throw()
  10661. {
  10662. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10663. if (buffer == 0)
  10664. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10665. return CharPointer_UTF8 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10666. }
  10667. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const throw()
  10668. {
  10669. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10670. if (buffer == 0)
  10671. return (int) CharPointer_UTF16::getBytesRequiredFor (text);
  10672. return CharPointer_UTF16 (buffer).writeWithDestByteLimit (text, maxBufferSizeBytes);
  10673. }
  10674. int String::getNumBytesAsUTF8() const throw()
  10675. {
  10676. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  10677. }
  10678. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10679. {
  10680. if (buffer == 0)
  10681. return empty;
  10682. const int len = (int) (bufferSizeBytes >= 0 ? CharPointer_UTF8 (buffer).lengthUpTo (bufferSizeBytes)
  10683. : CharPointer_UTF8 (buffer).length());
  10684. String result (Preallocation (len + 1));
  10685. CharPointerType (result.text).writeWithCharLimit (CharPointer_UTF8 (buffer), len + 1);
  10686. return result;
  10687. }
  10688. const char* String::toCString() const
  10689. {
  10690. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10691. return toUTF8();
  10692. #else
  10693. if (isEmpty())
  10694. return reinterpret_cast <const char*> (text.getAddress());
  10695. const int len = getNumBytesAsCString();
  10696. char* const extraSpace = static_cast <char*> (createSpaceAtEndOfBuffer (len + 1));
  10697. wcstombs (extraSpace, text, len);
  10698. extraSpace [len] = 0;
  10699. return extraSpace;
  10700. #endif
  10701. }
  10702. int String::getNumBytesAsCString() const throw()
  10703. {
  10704. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10705. return getNumBytesAsUTF8();
  10706. #else
  10707. return (int) wcstombs (0, text, 0);
  10708. #endif
  10709. }
  10710. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  10711. {
  10712. #if JUCE_NATIVE_WCHAR_IS_NOT_UTF32
  10713. return copyToUTF8 (destBuffer, maxBufferSizeBytes);
  10714. #else
  10715. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  10716. if (destBuffer != 0 && numBytes >= 0)
  10717. destBuffer [numBytes] = 0;
  10718. return numBytes;
  10719. #endif
  10720. }
  10721. #if JUCE_MSVC
  10722. #pragma warning (pop)
  10723. #endif
  10724. String::Concatenator::Concatenator (String& stringToAppendTo)
  10725. : result (stringToAppendTo),
  10726. nextIndex (stringToAppendTo.length())
  10727. {
  10728. }
  10729. String::Concatenator::~Concatenator()
  10730. {
  10731. }
  10732. void String::Concatenator::append (const String& s)
  10733. {
  10734. const int len = s.length();
  10735. if (len > 0)
  10736. {
  10737. result.preallocateStorage (nextIndex + len);
  10738. CharPointerType (result.text + nextIndex).writeAll (s.text);
  10739. nextIndex += len;
  10740. }
  10741. }
  10742. #if JUCE_UNIT_TESTS
  10743. class StringTests : public UnitTest
  10744. {
  10745. public:
  10746. StringTests() : UnitTest ("String class") {}
  10747. template <class CharPointerType>
  10748. struct TestUTFConversion
  10749. {
  10750. static void test (UnitTest& test)
  10751. {
  10752. String s (createRandomWideCharString());
  10753. typename CharPointerType::CharType buffer [300];
  10754. memset (buffer, 0xff, sizeof (buffer));
  10755. CharPointerType (buffer).writeAll (s.toUTF32());
  10756. test.expectEquals (String (CharPointerType (buffer)), s);
  10757. memset (buffer, 0xff, sizeof (buffer));
  10758. CharPointerType (buffer).writeAll (s.toUTF16());
  10759. test.expectEquals (String (CharPointerType (buffer)), s);
  10760. memset (buffer, 0xff, sizeof (buffer));
  10761. CharPointerType (buffer).writeAll (s.toUTF8());
  10762. test.expectEquals (String (CharPointerType (buffer)), s);
  10763. }
  10764. };
  10765. static const String createRandomWideCharString()
  10766. {
  10767. juce_wchar buffer [50];
  10768. zerostruct (buffer);
  10769. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  10770. {
  10771. if (Random::getSystemRandom().nextBool())
  10772. {
  10773. do
  10774. {
  10775. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0x10ffff - 1));
  10776. }
  10777. while (buffer[i] >= 0xd800 && buffer[i] <= 0xdfff); // (these code-points are illegal in UTF-16)
  10778. }
  10779. else
  10780. buffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (0xff));
  10781. }
  10782. return buffer;
  10783. }
  10784. void runTest()
  10785. {
  10786. {
  10787. beginTest ("Basics");
  10788. expect (String().length() == 0);
  10789. expect (String() == String::empty);
  10790. String s1, s2 ("abcd");
  10791. expect (s1.isEmpty() && ! s1.isNotEmpty());
  10792. expect (s2.isNotEmpty() && ! s2.isEmpty());
  10793. expect (s2.length() == 4);
  10794. s1 = "abcd";
  10795. expect (s2 == s1 && s1 == s2);
  10796. expect (s1 == "abcd" && s1 == L"abcd");
  10797. expect (String ("abcd") == String (L"abcd"));
  10798. expect (String ("abcdefg", 4) == L"abcd");
  10799. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  10800. expect (String::charToString ('x') == "x");
  10801. expect (String::charToString (0) == String::empty);
  10802. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  10803. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  10804. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  10805. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  10806. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  10807. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  10808. expect (s1.indexOf (String::empty) == 0);
  10809. expect (s1.indexOfIgnoreCase (String::empty) == 0);
  10810. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  10811. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  10812. expect (s1.containsChar ('a'));
  10813. expect (! s1.containsChar ('x'));
  10814. expect (! s1.containsChar (0));
  10815. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  10816. }
  10817. {
  10818. beginTest ("Operations");
  10819. String s ("012345678");
  10820. expect (s.hashCode() != 0);
  10821. expect (s.hashCode64() != 0);
  10822. expect (s.hashCode() != (s + s).hashCode());
  10823. expect (s.hashCode64() != (s + s).hashCode64());
  10824. expect (s.compare (String ("012345678")) == 0);
  10825. expect (s.compare (String ("012345679")) < 0);
  10826. expect (s.compare (String ("012345676")) > 0);
  10827. expect (s.substring (2, 3) == String::charToString (s[2]));
  10828. expect (s.substring (0, 1) == String::charToString (s[0]));
  10829. expect (s.getLastCharacter() == s [s.length() - 1]);
  10830. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  10831. expect (s.substring (0, 3) == L"012");
  10832. expect (s.substring (0, 100) == s);
  10833. expect (s.substring (-1, 100) == s);
  10834. expect (s.substring (3) == "345678");
  10835. expect (s.indexOf (L"45") == 4);
  10836. expect (String ("444445").indexOf ("45") == 4);
  10837. expect (String ("444445").lastIndexOfChar ('4') == 4);
  10838. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  10839. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  10840. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  10841. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  10842. expect (s.indexOfChar (L'4') == 4);
  10843. expect (s + s == "012345678012345678");
  10844. expect (s.startsWith (s));
  10845. expect (s.startsWith (s.substring (0, 4)));
  10846. expect (s.startsWith (s.dropLastCharacters (4)));
  10847. expect (s.endsWith (s.substring (5)));
  10848. expect (s.endsWith (s));
  10849. expect (s.contains (s.substring (3, 6)));
  10850. expect (s.contains (s.substring (3)));
  10851. expect (s.startsWithChar (s[0]));
  10852. expect (s.endsWithChar (s.getLastCharacter()));
  10853. expect (s [s.length()] == 0);
  10854. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  10855. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  10856. String s2 ("123");
  10857. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  10858. s2 += "xyz";
  10859. expect (s2 == "1234567890xyz");
  10860. beginTest ("Numeric conversions");
  10861. expect (String::empty.getIntValue() == 0);
  10862. expect (String::empty.getDoubleValue() == 0.0);
  10863. expect (String::empty.getFloatValue() == 0.0f);
  10864. expect (s.getIntValue() == 12345678);
  10865. expect (s.getLargeIntValue() == (int64) 12345678);
  10866. expect (s.getDoubleValue() == 12345678.0);
  10867. expect (s.getFloatValue() == 12345678.0f);
  10868. expect (String (-1234).getIntValue() == -1234);
  10869. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  10870. expect (String (-1234.56).getDoubleValue() == -1234.56);
  10871. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  10872. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  10873. expect (s.getHexValue32() == 0x12345678);
  10874. expect (s.getHexValue64() == (int64) 0x12345678);
  10875. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10876. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  10877. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  10878. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  10879. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  10880. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  10881. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  10882. beginTest ("Subsections");
  10883. String s3;
  10884. s3 = "abcdeFGHIJ";
  10885. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  10886. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  10887. expect (s3.containsIgnoreCase (s3.substring (3)));
  10888. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  10889. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  10890. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  10891. expect (s3.containsAnyOf (L"zzzFs"));
  10892. expect (s3.startsWith ("abcd"));
  10893. expect (s3.startsWithIgnoreCase (L"abCD"));
  10894. expect (s3.startsWith (String::empty));
  10895. expect (s3.startsWithChar ('a'));
  10896. expect (s3.endsWith (String ("HIJ")));
  10897. expect (s3.endsWithIgnoreCase (L"Hij"));
  10898. expect (s3.endsWith (String::empty));
  10899. expect (s3.endsWithChar (L'J'));
  10900. expect (s3.indexOf ("HIJ") == 7);
  10901. expect (s3.indexOf (L"HIJK") == -1);
  10902. expect (s3.indexOfIgnoreCase ("hij") == 7);
  10903. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  10904. String s4 (s3);
  10905. s4.append (String ("xyz123"), 3);
  10906. expect (s4 == s3 + "xyz");
  10907. expect (String (1234) < String (1235));
  10908. expect (String (1235) > String (1234));
  10909. expect (String (1234) >= String (1234));
  10910. expect (String (1234) <= String (1234));
  10911. expect (String (1235) >= String (1234));
  10912. expect (String (1234) <= String (1235));
  10913. String s5 ("word word2 word3");
  10914. expect (s5.containsWholeWord (String ("word2")));
  10915. expect (s5.indexOfWholeWord ("word2") == 5);
  10916. expect (s5.containsWholeWord (L"word"));
  10917. expect (s5.containsWholeWord ("word3"));
  10918. expect (s5.containsWholeWord (s5));
  10919. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  10920. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  10921. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  10922. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  10923. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  10924. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  10925. expect (s5.containsNonWhitespaceChars());
  10926. expect (s5.containsOnly ("ordw23 "));
  10927. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  10928. expect (s5.matchesWildcard (L"wor*", false));
  10929. expect (s5.matchesWildcard ("wOr*", true));
  10930. expect (s5.matchesWildcard (L"*word3", true));
  10931. expect (s5.matchesWildcard ("*word?", true));
  10932. expect (s5.matchesWildcard (L"Word*3", true));
  10933. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  10934. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  10935. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  10936. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  10937. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  10938. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  10939. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  10940. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  10941. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  10942. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  10943. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  10944. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  10945. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  10946. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  10947. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  10948. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  10949. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  10950. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  10951. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  10952. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  10953. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10954. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  10955. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  10956. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  10957. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  10958. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  10959. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  10960. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  10961. expect (s5.replace ("Word", "", true) == " 2 3");
  10962. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  10963. expect (s5.replaceCharacter (L'w', 'x') != s5);
  10964. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  10965. expect (s5.replaceCharacters ("wo", "xy") != s5);
  10966. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  10967. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  10968. expect (s5.retainCharacters (String::empty).isEmpty());
  10969. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  10970. expectEquals (s5.removeCharacters (String::empty), s5);
  10971. expect (s5.initialSectionContainingOnly ("word") == L"word");
  10972. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  10973. expect (! s5.isQuotedString());
  10974. expect (s5.quoted().isQuotedString());
  10975. expect (! s5.quoted().unquoted().isQuotedString());
  10976. expect (! String ("x'").isQuotedString());
  10977. expect (String ("'x").isQuotedString());
  10978. String s6 (" \t xyz \t\r\n");
  10979. expectEquals (s6.trim(), String ("xyz"));
  10980. expect (s6.trim().trim() == "xyz");
  10981. expectEquals (s5.trim(), s5);
  10982. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  10983. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  10984. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  10985. expect (s6.trimStart() != s6.trimEnd());
  10986. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  10987. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  10988. }
  10989. {
  10990. beginTest ("UTF conversions");
  10991. TestUTFConversion <CharPointer_UTF32>::test (*this);
  10992. TestUTFConversion <CharPointer_UTF8>::test (*this);
  10993. TestUTFConversion <CharPointer_UTF16>::test (*this);
  10994. }
  10995. {
  10996. beginTest ("StringArray");
  10997. StringArray s;
  10998. for (int i = 5; --i >= 0;)
  10999. s.add (String (i));
  11000. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  11001. s.remove (2);
  11002. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  11003. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  11004. s.clear();
  11005. expectEquals (s.joinIntoString ("x"), String::empty);
  11006. }
  11007. }
  11008. };
  11009. static StringTests stringUnitTests;
  11010. #endif
  11011. END_JUCE_NAMESPACE
  11012. /*** End of inlined file: juce_String.cpp ***/
  11013. /*** Start of inlined file: juce_StringArray.cpp ***/
  11014. BEGIN_JUCE_NAMESPACE
  11015. StringArray::StringArray() throw()
  11016. {
  11017. }
  11018. StringArray::StringArray (const StringArray& other)
  11019. : strings (other.strings)
  11020. {
  11021. }
  11022. StringArray::StringArray (const String& firstValue)
  11023. {
  11024. strings.add (firstValue);
  11025. }
  11026. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11027. const int numberOfStrings)
  11028. {
  11029. for (int i = 0; i < numberOfStrings; ++i)
  11030. strings.add (initialStrings [i]);
  11031. }
  11032. StringArray::StringArray (const char* const* const initialStrings,
  11033. const int numberOfStrings)
  11034. {
  11035. for (int i = 0; i < numberOfStrings; ++i)
  11036. strings.add (initialStrings [i]);
  11037. }
  11038. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11039. {
  11040. int i = 0;
  11041. while (initialStrings[i] != 0)
  11042. strings.add (initialStrings [i++]);
  11043. }
  11044. StringArray::StringArray (const char* const* const initialStrings)
  11045. {
  11046. int i = 0;
  11047. while (initialStrings[i] != 0)
  11048. strings.add (initialStrings [i++]);
  11049. }
  11050. StringArray& StringArray::operator= (const StringArray& other)
  11051. {
  11052. strings = other.strings;
  11053. return *this;
  11054. }
  11055. StringArray::~StringArray()
  11056. {
  11057. }
  11058. bool StringArray::operator== (const StringArray& other) const throw()
  11059. {
  11060. if (other.size() != size())
  11061. return false;
  11062. for (int i = size(); --i >= 0;)
  11063. if (other.strings.getReference(i) != strings.getReference(i))
  11064. return false;
  11065. return true;
  11066. }
  11067. bool StringArray::operator!= (const StringArray& other) const throw()
  11068. {
  11069. return ! operator== (other);
  11070. }
  11071. void StringArray::clear()
  11072. {
  11073. strings.clear();
  11074. }
  11075. const String& StringArray::operator[] (const int index) const throw()
  11076. {
  11077. if (isPositiveAndBelow (index, strings.size()))
  11078. return strings.getReference (index);
  11079. return String::empty;
  11080. }
  11081. String& StringArray::getReference (const int index) throw()
  11082. {
  11083. jassert (isPositiveAndBelow (index, strings.size()));
  11084. return strings.getReference (index);
  11085. }
  11086. void StringArray::add (const String& newString)
  11087. {
  11088. strings.add (newString);
  11089. }
  11090. void StringArray::insert (const int index, const String& newString)
  11091. {
  11092. strings.insert (index, newString);
  11093. }
  11094. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11095. {
  11096. if (! contains (newString, ignoreCase))
  11097. add (newString);
  11098. }
  11099. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11100. {
  11101. if (startIndex < 0)
  11102. {
  11103. jassertfalse;
  11104. startIndex = 0;
  11105. }
  11106. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11107. numElementsToAdd = otherArray.size() - startIndex;
  11108. while (--numElementsToAdd >= 0)
  11109. strings.add (otherArray.strings.getReference (startIndex++));
  11110. }
  11111. void StringArray::set (const int index, const String& newString)
  11112. {
  11113. strings.set (index, newString);
  11114. }
  11115. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11116. {
  11117. if (ignoreCase)
  11118. {
  11119. for (int i = size(); --i >= 0;)
  11120. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11121. return true;
  11122. }
  11123. else
  11124. {
  11125. for (int i = size(); --i >= 0;)
  11126. if (stringToLookFor == strings.getReference(i))
  11127. return true;
  11128. }
  11129. return false;
  11130. }
  11131. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11132. {
  11133. if (i < 0)
  11134. i = 0;
  11135. const int numElements = size();
  11136. if (ignoreCase)
  11137. {
  11138. while (i < numElements)
  11139. {
  11140. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11141. return i;
  11142. ++i;
  11143. }
  11144. }
  11145. else
  11146. {
  11147. while (i < numElements)
  11148. {
  11149. if (stringToLookFor == strings.getReference (i))
  11150. return i;
  11151. ++i;
  11152. }
  11153. }
  11154. return -1;
  11155. }
  11156. void StringArray::remove (const int index)
  11157. {
  11158. strings.remove (index);
  11159. }
  11160. void StringArray::removeString (const String& stringToRemove,
  11161. const bool ignoreCase)
  11162. {
  11163. if (ignoreCase)
  11164. {
  11165. for (int i = size(); --i >= 0;)
  11166. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11167. strings.remove (i);
  11168. }
  11169. else
  11170. {
  11171. for (int i = size(); --i >= 0;)
  11172. if (stringToRemove == strings.getReference (i))
  11173. strings.remove (i);
  11174. }
  11175. }
  11176. void StringArray::removeRange (int startIndex, int numberToRemove)
  11177. {
  11178. strings.removeRange (startIndex, numberToRemove);
  11179. }
  11180. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11181. {
  11182. if (removeWhitespaceStrings)
  11183. {
  11184. for (int i = size(); --i >= 0;)
  11185. if (! strings.getReference(i).containsNonWhitespaceChars())
  11186. strings.remove (i);
  11187. }
  11188. else
  11189. {
  11190. for (int i = size(); --i >= 0;)
  11191. if (strings.getReference(i).isEmpty())
  11192. strings.remove (i);
  11193. }
  11194. }
  11195. void StringArray::trim()
  11196. {
  11197. for (int i = size(); --i >= 0;)
  11198. {
  11199. String& s = strings.getReference(i);
  11200. s = s.trim();
  11201. }
  11202. }
  11203. class InternalStringArrayComparator_CaseSensitive
  11204. {
  11205. public:
  11206. static int compareElements (String& first, String& second) { return first.compare (second); }
  11207. };
  11208. class InternalStringArrayComparator_CaseInsensitive
  11209. {
  11210. public:
  11211. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11212. };
  11213. void StringArray::sort (const bool ignoreCase)
  11214. {
  11215. if (ignoreCase)
  11216. {
  11217. InternalStringArrayComparator_CaseInsensitive comp;
  11218. strings.sort (comp);
  11219. }
  11220. else
  11221. {
  11222. InternalStringArrayComparator_CaseSensitive comp;
  11223. strings.sort (comp);
  11224. }
  11225. }
  11226. void StringArray::move (const int currentIndex, int newIndex) throw()
  11227. {
  11228. strings.move (currentIndex, newIndex);
  11229. }
  11230. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11231. {
  11232. const int last = (numberToJoin < 0) ? size()
  11233. : jmin (size(), start + numberToJoin);
  11234. if (start < 0)
  11235. start = 0;
  11236. if (start >= last)
  11237. return String::empty;
  11238. if (start == last - 1)
  11239. return strings.getReference (start);
  11240. const int separatorLen = separator.length();
  11241. int charsNeeded = separatorLen * (last - start - 1);
  11242. for (int i = start; i < last; ++i)
  11243. charsNeeded += strings.getReference(i).length();
  11244. String result;
  11245. result.preallocateStorage (charsNeeded);
  11246. String::CharPointerType dest (result.getCharPointer());
  11247. while (start < last)
  11248. {
  11249. const String& s = strings.getReference (start);
  11250. if (! s.isEmpty())
  11251. dest.writeAll (s.getCharPointer());
  11252. if (++start < last && separatorLen > 0)
  11253. dest.writeAll (separator.getCharPointer());
  11254. }
  11255. dest.writeNull();
  11256. return result;
  11257. }
  11258. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11259. {
  11260. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11261. }
  11262. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11263. {
  11264. int num = 0;
  11265. if (text.isNotEmpty())
  11266. {
  11267. bool insideQuotes = false;
  11268. juce_wchar currentQuoteChar = 0;
  11269. String::CharPointerType t (text.getCharPointer());
  11270. String::CharPointerType tokenStart (t);
  11271. int numChars = 0;
  11272. for (;;)
  11273. {
  11274. const juce_wchar c = t.getAndAdvance();
  11275. ++numChars;
  11276. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11277. if (! isBreak)
  11278. {
  11279. if (quoteCharacters.containsChar (c))
  11280. {
  11281. if (insideQuotes)
  11282. {
  11283. // only break out of quotes-mode if we find a matching quote to the
  11284. // one that we opened with..
  11285. if (currentQuoteChar == c)
  11286. insideQuotes = false;
  11287. }
  11288. else
  11289. {
  11290. insideQuotes = true;
  11291. currentQuoteChar = c;
  11292. }
  11293. }
  11294. }
  11295. else
  11296. {
  11297. add (String (tokenStart, numChars - 1));
  11298. ++num;
  11299. tokenStart = t;
  11300. numChars = 0;
  11301. }
  11302. if (c == 0)
  11303. break;
  11304. }
  11305. }
  11306. return num;
  11307. }
  11308. int StringArray::addLines (const String& sourceText)
  11309. {
  11310. int numLines = 0;
  11311. String::CharPointerType text (sourceText.getCharPointer());
  11312. bool finished = text.isEmpty();
  11313. while (! finished)
  11314. {
  11315. String::CharPointerType startOfLine (text);
  11316. int numChars = 0;
  11317. for (;;)
  11318. {
  11319. const juce_wchar c = text.getAndAdvance();
  11320. if (c == 0)
  11321. {
  11322. finished = true;
  11323. break;
  11324. }
  11325. if (c == '\n')
  11326. break;
  11327. if (c == '\r')
  11328. {
  11329. if (*text == '\n')
  11330. ++text;
  11331. break;
  11332. }
  11333. ++numChars;
  11334. }
  11335. add (String (startOfLine, numChars));
  11336. ++numLines;
  11337. }
  11338. return numLines;
  11339. }
  11340. void StringArray::removeDuplicates (const bool ignoreCase)
  11341. {
  11342. for (int i = 0; i < size() - 1; ++i)
  11343. {
  11344. const String s (strings.getReference(i));
  11345. int nextIndex = i + 1;
  11346. for (;;)
  11347. {
  11348. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11349. if (nextIndex < 0)
  11350. break;
  11351. strings.remove (nextIndex);
  11352. }
  11353. }
  11354. }
  11355. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11356. const bool appendNumberToFirstInstance,
  11357. CharPointer_UTF8 preNumberString,
  11358. CharPointer_UTF8 postNumberString)
  11359. {
  11360. CharPointer_UTF8 defaultPre (" ("), defaultPost (")");
  11361. if (preNumberString.getAddress() == 0)
  11362. preNumberString = defaultPre;
  11363. if (postNumberString.getAddress() == 0)
  11364. postNumberString = defaultPost;
  11365. for (int i = 0; i < size() - 1; ++i)
  11366. {
  11367. String& s = strings.getReference(i);
  11368. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11369. if (nextIndex >= 0)
  11370. {
  11371. const String original (s);
  11372. int number = 0;
  11373. if (appendNumberToFirstInstance)
  11374. s = original + String (preNumberString) + String (++number) + String (postNumberString);
  11375. else
  11376. ++number;
  11377. while (nextIndex >= 0)
  11378. {
  11379. set (nextIndex, (*this)[nextIndex] + String (preNumberString) + String (++number) + String (postNumberString));
  11380. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11381. }
  11382. }
  11383. }
  11384. }
  11385. void StringArray::minimiseStorageOverheads()
  11386. {
  11387. strings.minimiseStorageOverheads();
  11388. }
  11389. END_JUCE_NAMESPACE
  11390. /*** End of inlined file: juce_StringArray.cpp ***/
  11391. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11392. BEGIN_JUCE_NAMESPACE
  11393. StringPairArray::StringPairArray (const bool ignoreCase_)
  11394. : ignoreCase (ignoreCase_)
  11395. {
  11396. }
  11397. StringPairArray::StringPairArray (const StringPairArray& other)
  11398. : keys (other.keys),
  11399. values (other.values),
  11400. ignoreCase (other.ignoreCase)
  11401. {
  11402. }
  11403. StringPairArray::~StringPairArray()
  11404. {
  11405. }
  11406. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11407. {
  11408. keys = other.keys;
  11409. values = other.values;
  11410. return *this;
  11411. }
  11412. bool StringPairArray::operator== (const StringPairArray& other) const
  11413. {
  11414. for (int i = keys.size(); --i >= 0;)
  11415. if (other [keys[i]] != values[i])
  11416. return false;
  11417. return true;
  11418. }
  11419. bool StringPairArray::operator!= (const StringPairArray& other) const
  11420. {
  11421. return ! operator== (other);
  11422. }
  11423. const String& StringPairArray::operator[] (const String& key) const
  11424. {
  11425. return values [keys.indexOf (key, ignoreCase)];
  11426. }
  11427. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11428. {
  11429. const int i = keys.indexOf (key, ignoreCase);
  11430. if (i >= 0)
  11431. return values[i];
  11432. return defaultReturnValue;
  11433. }
  11434. void StringPairArray::set (const String& key, const String& value)
  11435. {
  11436. const int i = keys.indexOf (key, ignoreCase);
  11437. if (i >= 0)
  11438. {
  11439. values.set (i, value);
  11440. }
  11441. else
  11442. {
  11443. keys.add (key);
  11444. values.add (value);
  11445. }
  11446. }
  11447. void StringPairArray::addArray (const StringPairArray& other)
  11448. {
  11449. for (int i = 0; i < other.size(); ++i)
  11450. set (other.keys[i], other.values[i]);
  11451. }
  11452. void StringPairArray::clear()
  11453. {
  11454. keys.clear();
  11455. values.clear();
  11456. }
  11457. void StringPairArray::remove (const String& key)
  11458. {
  11459. remove (keys.indexOf (key, ignoreCase));
  11460. }
  11461. void StringPairArray::remove (const int index)
  11462. {
  11463. keys.remove (index);
  11464. values.remove (index);
  11465. }
  11466. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11467. {
  11468. ignoreCase = shouldIgnoreCase;
  11469. }
  11470. const String StringPairArray::getDescription() const
  11471. {
  11472. String s;
  11473. for (int i = 0; i < keys.size(); ++i)
  11474. {
  11475. s << keys[i] << " = " << values[i];
  11476. if (i < keys.size())
  11477. s << ", ";
  11478. }
  11479. return s;
  11480. }
  11481. void StringPairArray::minimiseStorageOverheads()
  11482. {
  11483. keys.minimiseStorageOverheads();
  11484. values.minimiseStorageOverheads();
  11485. }
  11486. END_JUCE_NAMESPACE
  11487. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11488. /*** Start of inlined file: juce_StringPool.cpp ***/
  11489. BEGIN_JUCE_NAMESPACE
  11490. StringPool::StringPool() throw() {}
  11491. StringPool::~StringPool() {}
  11492. namespace StringPoolHelpers
  11493. {
  11494. template <class StringType>
  11495. const String::CharPointerType getPooledStringFromArray (Array<String>& strings, StringType newString)
  11496. {
  11497. int start = 0;
  11498. int end = strings.size();
  11499. for (;;)
  11500. {
  11501. if (start >= end)
  11502. {
  11503. jassert (start <= end);
  11504. strings.insert (start, newString);
  11505. return strings.getReference (start).getCharPointer();
  11506. }
  11507. else
  11508. {
  11509. const String& startString = strings.getReference (start);
  11510. if (startString == newString)
  11511. return startString.getCharPointer();
  11512. const int halfway = (start + end) >> 1;
  11513. if (halfway == start)
  11514. {
  11515. if (startString.compare (newString) < 0)
  11516. ++start;
  11517. strings.insert (start, newString);
  11518. return strings.getReference (start).getCharPointer();
  11519. }
  11520. const int comp = strings.getReference (halfway).compare (newString);
  11521. if (comp == 0)
  11522. return strings.getReference (halfway).getCharPointer();
  11523. else if (comp < 0)
  11524. start = halfway;
  11525. else
  11526. end = halfway;
  11527. }
  11528. }
  11529. }
  11530. }
  11531. const String::CharPointerType StringPool::getPooledString (const String& s)
  11532. {
  11533. if (s.isEmpty())
  11534. return String::empty.getCharPointer();
  11535. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11536. }
  11537. const String::CharPointerType StringPool::getPooledString (const char* const s)
  11538. {
  11539. if (s == 0 || *s == 0)
  11540. return String::empty.getCharPointer();
  11541. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11542. }
  11543. const String::CharPointerType StringPool::getPooledString (const juce_wchar* const s)
  11544. {
  11545. if (s == 0 || *s == 0)
  11546. return String::empty.getCharPointer();
  11547. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11548. }
  11549. int StringPool::size() const throw()
  11550. {
  11551. return strings.size();
  11552. }
  11553. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11554. {
  11555. return strings [index].getCharPointer();
  11556. }
  11557. END_JUCE_NAMESPACE
  11558. /*** End of inlined file: juce_StringPool.cpp ***/
  11559. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11560. BEGIN_JUCE_NAMESPACE
  11561. XmlDocument::XmlDocument (const String& documentText)
  11562. : originalText (documentText),
  11563. input (0),
  11564. ignoreEmptyTextElements (true)
  11565. {
  11566. }
  11567. XmlDocument::XmlDocument (const File& file)
  11568. : input (0),
  11569. ignoreEmptyTextElements (true),
  11570. inputSource (new FileInputSource (file))
  11571. {
  11572. }
  11573. XmlDocument::~XmlDocument()
  11574. {
  11575. }
  11576. XmlElement* XmlDocument::parse (const File& file)
  11577. {
  11578. XmlDocument doc (file);
  11579. return doc.getDocumentElement();
  11580. }
  11581. XmlElement* XmlDocument::parse (const String& xmlData)
  11582. {
  11583. XmlDocument doc (xmlData);
  11584. return doc.getDocumentElement();
  11585. }
  11586. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11587. {
  11588. inputSource = newSource;
  11589. }
  11590. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11591. {
  11592. ignoreEmptyTextElements = shouldBeIgnored;
  11593. }
  11594. namespace XmlIdentifierChars
  11595. {
  11596. bool isIdentifierCharSlow (const juce_wchar c) throw()
  11597. {
  11598. return CharacterFunctions::isLetterOrDigit (c)
  11599. || c == '_' || c == '-' || c == ':' || c == '.';
  11600. }
  11601. bool isIdentifierChar (const juce_wchar c) throw()
  11602. {
  11603. static const uint32 legalChars[] = { 0, 0x7ff6000, 0x87fffffe, 0x7fffffe, 0 };
  11604. return ((int) c < (int) numElementsInArray (legalChars) * 32) ? ((legalChars [c >> 5] & (1 << (c & 31))) != 0)
  11605. : isIdentifierCharSlow (c);
  11606. }
  11607. /*static void generateIdentifierCharConstants()
  11608. {
  11609. uint32 n[8];
  11610. zerostruct (n);
  11611. for (int i = 0; i < 256; ++i)
  11612. if (isIdentifierCharSlow (i))
  11613. n[i >> 5] |= (1 << (i & 31));
  11614. String s;
  11615. for (int i = 0; i < 8; ++i)
  11616. s << "0x" << String::toHexString ((int) n[i]) << ", ";
  11617. DBG (s);
  11618. }*/
  11619. }
  11620. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11621. {
  11622. String textToParse (originalText);
  11623. if (textToParse.isEmpty() && inputSource != 0)
  11624. {
  11625. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11626. if (in != 0)
  11627. {
  11628. MemoryOutputStream data;
  11629. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11630. textToParse = data.toString();
  11631. if (! onlyReadOuterDocumentElement)
  11632. originalText = textToParse;
  11633. }
  11634. }
  11635. input = textToParse.getCharPointer();
  11636. lastError = String::empty;
  11637. errorOccurred = false;
  11638. outOfData = false;
  11639. needToLoadDTD = true;
  11640. if (textToParse.isEmpty())
  11641. {
  11642. lastError = "not enough input";
  11643. }
  11644. else
  11645. {
  11646. skipHeader();
  11647. if (input.getAddress() != 0)
  11648. {
  11649. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11650. if (! errorOccurred)
  11651. return result.release();
  11652. }
  11653. else
  11654. {
  11655. lastError = "incorrect xml header";
  11656. }
  11657. }
  11658. return 0;
  11659. }
  11660. const String& XmlDocument::getLastParseError() const throw()
  11661. {
  11662. return lastError;
  11663. }
  11664. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11665. {
  11666. lastError = desc;
  11667. errorOccurred = ! carryOn;
  11668. }
  11669. const String XmlDocument::getFileContents (const String& filename) const
  11670. {
  11671. if (inputSource != 0)
  11672. {
  11673. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11674. if (in != 0)
  11675. return in->readEntireStreamAsString();
  11676. }
  11677. return String::empty;
  11678. }
  11679. juce_wchar XmlDocument::readNextChar() throw()
  11680. {
  11681. if (*input != 0)
  11682. return *input++;
  11683. outOfData = true;
  11684. return 0;
  11685. }
  11686. int XmlDocument::findNextTokenLength() throw()
  11687. {
  11688. int len = 0;
  11689. juce_wchar c = *input;
  11690. while (XmlIdentifierChars::isIdentifierChar (c))
  11691. c = input [++len];
  11692. return len;
  11693. }
  11694. void XmlDocument::skipHeader()
  11695. {
  11696. const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));
  11697. if (headerStart >= 0)
  11698. {
  11699. const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
  11700. if (headerEnd < 0)
  11701. return;
  11702. #if JUCE_DEBUG
  11703. const String header ((input + headerStart).getAddress(), headerEnd - headerStart);
  11704. const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
  11705. .fromFirstOccurrenceOf ("=", false, false)
  11706. .fromFirstOccurrenceOf ("\"", false, false)
  11707. .upToFirstOccurrenceOf ("\"", false, false).trim());
  11708. /* If you load an XML document with a non-UTF encoding type, it may have been
  11709. loaded wrongly.. Since all the files are read via the normal juce file streams,
  11710. they're treated as UTF-8, so by the time it gets to the parser, the encoding will
  11711. have been lost. Best plan is to stick to utf-8 or if you have specific files to
  11712. read, use your own code to convert them to a unicode String, and pass that to the
  11713. XML parser.
  11714. */
  11715. jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
  11716. #endif
  11717. input += headerEnd + 2;
  11718. }
  11719. skipNextWhiteSpace();
  11720. const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
  11721. if (docTypeIndex < 0)
  11722. return;
  11723. input += docTypeIndex + 9;
  11724. const String::CharPointerType docType (input);
  11725. int n = 1;
  11726. while (n > 0)
  11727. {
  11728. const juce_wchar c = readNextChar();
  11729. if (outOfData)
  11730. return;
  11731. if (c == '<')
  11732. ++n;
  11733. else if (c == '>')
  11734. --n;
  11735. }
  11736. dtdText = String (docType.getAddress(), (int) (input.getAddress() - (docType.getAddress() + 1))).trim();
  11737. }
  11738. void XmlDocument::skipNextWhiteSpace()
  11739. {
  11740. for (;;)
  11741. {
  11742. juce_wchar c = *input;
  11743. while (CharacterFunctions::isWhitespace (c))
  11744. c = *++input;
  11745. if (c == 0)
  11746. {
  11747. outOfData = true;
  11748. break;
  11749. }
  11750. else if (c == '<')
  11751. {
  11752. if (input[1] == '!'
  11753. && input[2] == '-'
  11754. && input[3] == '-')
  11755. {
  11756. const int closeComment = input.indexOf (CharPointer_UTF8 ("-->"));
  11757. if (closeComment < 0)
  11758. {
  11759. outOfData = true;
  11760. break;
  11761. }
  11762. input += closeComment + 3;
  11763. continue;
  11764. }
  11765. else if (input[1] == '?')
  11766. {
  11767. const int closeBracket = input.indexOf (CharPointer_UTF8 ("?>"));
  11768. if (closeBracket < 0)
  11769. {
  11770. outOfData = true;
  11771. break;
  11772. }
  11773. input += closeBracket + 2;
  11774. continue;
  11775. }
  11776. }
  11777. break;
  11778. }
  11779. }
  11780. void XmlDocument::readQuotedString (String& result)
  11781. {
  11782. const juce_wchar quote = readNextChar();
  11783. while (! outOfData)
  11784. {
  11785. const juce_wchar c = readNextChar();
  11786. if (c == quote)
  11787. break;
  11788. if (c == '&')
  11789. {
  11790. --input;
  11791. readEntity (result);
  11792. }
  11793. else
  11794. {
  11795. --input;
  11796. const String::CharPointerType start (input);
  11797. for (;;)
  11798. {
  11799. const juce_wchar character = *input;
  11800. if (character == quote)
  11801. {
  11802. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11803. ++input;
  11804. return;
  11805. }
  11806. else if (character == '&')
  11807. {
  11808. result.appendCharPointer (start, (int) (input.getAddress() - start.getAddress()));
  11809. break;
  11810. }
  11811. else if (character == 0)
  11812. {
  11813. outOfData = true;
  11814. setLastError ("unmatched quotes", false);
  11815. break;
  11816. }
  11817. ++input;
  11818. }
  11819. }
  11820. }
  11821. }
  11822. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  11823. {
  11824. XmlElement* node = 0;
  11825. skipNextWhiteSpace();
  11826. if (outOfData)
  11827. return 0;
  11828. const int openBracket = input.indexOf ((juce_wchar) '<');
  11829. if (openBracket >= 0)
  11830. {
  11831. input += openBracket + 1;
  11832. int tagLen = findNextTokenLength();
  11833. if (tagLen == 0)
  11834. {
  11835. // no tag name - but allow for a gap after the '<' before giving an error
  11836. skipNextWhiteSpace();
  11837. tagLen = findNextTokenLength();
  11838. if (tagLen == 0)
  11839. {
  11840. setLastError ("tag name missing", false);
  11841. return node;
  11842. }
  11843. }
  11844. node = new XmlElement (String (input.getAddress(), tagLen));
  11845. input += tagLen;
  11846. LinkedListPointer<XmlElement::XmlAttributeNode>::Appender attributeAppender (node->attributes);
  11847. // look for attributes
  11848. for (;;)
  11849. {
  11850. skipNextWhiteSpace();
  11851. const juce_wchar c = *input;
  11852. // empty tag..
  11853. if (c == '/' && input[1] == '>')
  11854. {
  11855. input += 2;
  11856. break;
  11857. }
  11858. // parse the guts of the element..
  11859. if (c == '>')
  11860. {
  11861. ++input;
  11862. if (alsoParseSubElements)
  11863. readChildElements (node);
  11864. break;
  11865. }
  11866. // get an attribute..
  11867. if (XmlIdentifierChars::isIdentifierChar (c))
  11868. {
  11869. const int attNameLen = findNextTokenLength();
  11870. if (attNameLen > 0)
  11871. {
  11872. const String::CharPointerType attNameStart (input);
  11873. input += attNameLen;
  11874. skipNextWhiteSpace();
  11875. if (readNextChar() == '=')
  11876. {
  11877. skipNextWhiteSpace();
  11878. const juce_wchar nextChar = *input;
  11879. if (nextChar == '"' || nextChar == '\'')
  11880. {
  11881. XmlElement::XmlAttributeNode* const newAtt
  11882. = new XmlElement::XmlAttributeNode (String (attNameStart.getAddress(), attNameLen),
  11883. String::empty);
  11884. readQuotedString (newAtt->value);
  11885. attributeAppender.append (newAtt);
  11886. continue;
  11887. }
  11888. }
  11889. }
  11890. }
  11891. else
  11892. {
  11893. if (! outOfData)
  11894. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  11895. }
  11896. break;
  11897. }
  11898. }
  11899. return node;
  11900. }
  11901. void XmlDocument::readChildElements (XmlElement* parent)
  11902. {
  11903. LinkedListPointer<XmlElement>::Appender childAppender (parent->firstChildElement);
  11904. for (;;)
  11905. {
  11906. const String::CharPointerType preWhitespaceInput (input);
  11907. skipNextWhiteSpace();
  11908. if (outOfData)
  11909. {
  11910. setLastError ("unmatched tags", false);
  11911. break;
  11912. }
  11913. if (*input == '<')
  11914. {
  11915. if (input[1] == '/')
  11916. {
  11917. // our close tag..
  11918. const int closeTag = input.indexOf ((juce_wchar) '>');
  11919. if (closeTag >= 0)
  11920. input += closeTag + 1;
  11921. break;
  11922. }
  11923. else if (input[1] == '!'
  11924. && input[2] == '['
  11925. && input[3] == 'C'
  11926. && input[4] == 'D'
  11927. && input[5] == 'A'
  11928. && input[6] == 'T'
  11929. && input[7] == 'A'
  11930. && input[8] == '[')
  11931. {
  11932. input += 9;
  11933. const String::CharPointerType inputStart (input);
  11934. int len = 0;
  11935. for (;;)
  11936. {
  11937. if (*input == 0)
  11938. {
  11939. setLastError ("unterminated CDATA section", false);
  11940. outOfData = true;
  11941. break;
  11942. }
  11943. else if (input[0] == ']'
  11944. && input[1] == ']'
  11945. && input[2] == '>')
  11946. {
  11947. input += 3;
  11948. break;
  11949. }
  11950. ++input;
  11951. ++len;
  11952. }
  11953. childAppender.append (XmlElement::createTextElement (String (inputStart.getAddress(), len)));
  11954. }
  11955. else
  11956. {
  11957. // this is some other element, so parse and add it..
  11958. XmlElement* const n = readNextElement (true);
  11959. if (n != 0)
  11960. childAppender.append (n);
  11961. else
  11962. return;
  11963. }
  11964. }
  11965. else // must be a character block
  11966. {
  11967. input = preWhitespaceInput; // roll back to include the leading whitespace
  11968. String textElementContent;
  11969. for (;;)
  11970. {
  11971. const juce_wchar c = *input;
  11972. if (c == '<')
  11973. break;
  11974. if (c == 0)
  11975. {
  11976. setLastError ("unmatched tags", false);
  11977. outOfData = true;
  11978. return;
  11979. }
  11980. if (c == '&')
  11981. {
  11982. String entity;
  11983. readEntity (entity);
  11984. if (entity.startsWithChar ('<') && entity [1] != 0)
  11985. {
  11986. const String::CharPointerType oldInput (input);
  11987. const bool oldOutOfData = outOfData;
  11988. input = entity.getCharPointer();
  11989. outOfData = false;
  11990. for (;;)
  11991. {
  11992. XmlElement* const n = readNextElement (true);
  11993. if (n == 0)
  11994. break;
  11995. childAppender.append (n);
  11996. }
  11997. input = oldInput;
  11998. outOfData = oldOutOfData;
  11999. }
  12000. else
  12001. {
  12002. textElementContent += entity;
  12003. }
  12004. }
  12005. else
  12006. {
  12007. const String::CharPointerType start (input);
  12008. int len = 0;
  12009. for (;;)
  12010. {
  12011. const juce_wchar nextChar = *input;
  12012. if (nextChar == '<' || nextChar == '&')
  12013. {
  12014. break;
  12015. }
  12016. else if (nextChar == 0)
  12017. {
  12018. setLastError ("unmatched tags", false);
  12019. outOfData = true;
  12020. return;
  12021. }
  12022. ++input;
  12023. ++len;
  12024. }
  12025. textElementContent.append (start.getAddress(), len);
  12026. }
  12027. }
  12028. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12029. {
  12030. childAppender.append (XmlElement::createTextElement (textElementContent));
  12031. }
  12032. }
  12033. }
  12034. }
  12035. void XmlDocument::readEntity (String& result)
  12036. {
  12037. // skip over the ampersand
  12038. ++input;
  12039. if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("amp;"), 4) == 0)
  12040. {
  12041. input += 4;
  12042. result += '&';
  12043. }
  12044. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("quot;"), 5) == 0)
  12045. {
  12046. input += 5;
  12047. result += '"';
  12048. }
  12049. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("apos;"), 5) == 0)
  12050. {
  12051. input += 5;
  12052. result += '\'';
  12053. }
  12054. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("lt;"), 3) == 0)
  12055. {
  12056. input += 3;
  12057. result += '<';
  12058. }
  12059. else if (input.compareIgnoreCaseUpTo (CharPointer_UTF8 ("gt;"), 3) == 0)
  12060. {
  12061. input += 3;
  12062. result += '>';
  12063. }
  12064. else if (*input == '#')
  12065. {
  12066. int charCode = 0;
  12067. ++input;
  12068. if (*input == 'x' || *input == 'X')
  12069. {
  12070. ++input;
  12071. int numChars = 0;
  12072. while (input[0] != ';')
  12073. {
  12074. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12075. if (hexValue < 0 || ++numChars > 8)
  12076. {
  12077. setLastError ("illegal escape sequence", true);
  12078. break;
  12079. }
  12080. charCode = (charCode << 4) | hexValue;
  12081. ++input;
  12082. }
  12083. ++input;
  12084. }
  12085. else if (input[0] >= '0' && input[0] <= '9')
  12086. {
  12087. int numChars = 0;
  12088. while (input[0] != ';')
  12089. {
  12090. if (++numChars > 12)
  12091. {
  12092. setLastError ("illegal escape sequence", true);
  12093. break;
  12094. }
  12095. charCode = charCode * 10 + (input[0] - '0');
  12096. ++input;
  12097. }
  12098. ++input;
  12099. }
  12100. else
  12101. {
  12102. setLastError ("illegal escape sequence", true);
  12103. result += '&';
  12104. return;
  12105. }
  12106. result << (juce_wchar) charCode;
  12107. }
  12108. else
  12109. {
  12110. const String::CharPointerType entityNameStart (input);
  12111. const int closingSemiColon = input.indexOf ((juce_wchar) ';');
  12112. if (closingSemiColon < 0)
  12113. {
  12114. outOfData = true;
  12115. result += '&';
  12116. }
  12117. else
  12118. {
  12119. input += closingSemiColon + 1;
  12120. result += expandExternalEntity (String (entityNameStart.getAddress(), closingSemiColon));
  12121. }
  12122. }
  12123. }
  12124. const String XmlDocument::expandEntity (const String& ent)
  12125. {
  12126. if (ent.equalsIgnoreCase ("amp")) return String::charToString ('&');
  12127. if (ent.equalsIgnoreCase ("quot")) return String::charToString ('"');
  12128. if (ent.equalsIgnoreCase ("apos")) return String::charToString ('\'');
  12129. if (ent.equalsIgnoreCase ("lt")) return String::charToString ('<');
  12130. if (ent.equalsIgnoreCase ("gt")) return String::charToString ('>');
  12131. if (ent[0] == '#')
  12132. {
  12133. if (ent[1] == 'x' || ent[1] == 'X')
  12134. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12135. if (ent[1] >= '0' && ent[1] <= '9')
  12136. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12137. setLastError ("illegal escape sequence", false);
  12138. return String::charToString ('&');
  12139. }
  12140. return expandExternalEntity (ent);
  12141. }
  12142. const String XmlDocument::expandExternalEntity (const String& entity)
  12143. {
  12144. if (needToLoadDTD)
  12145. {
  12146. if (dtdText.isNotEmpty())
  12147. {
  12148. dtdText = dtdText.trimCharactersAtEnd (">");
  12149. tokenisedDTD.addTokens (dtdText, true);
  12150. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12151. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12152. {
  12153. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12154. tokenisedDTD.clear();
  12155. tokenisedDTD.addTokens (getFileContents (fn), true);
  12156. }
  12157. else
  12158. {
  12159. tokenisedDTD.clear();
  12160. const int openBracket = dtdText.indexOfChar ('[');
  12161. if (openBracket > 0)
  12162. {
  12163. const int closeBracket = dtdText.lastIndexOfChar (']');
  12164. if (closeBracket > openBracket)
  12165. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12166. closeBracket), true);
  12167. }
  12168. }
  12169. for (int i = tokenisedDTD.size(); --i >= 0;)
  12170. {
  12171. if (tokenisedDTD[i].startsWithChar ('%')
  12172. && tokenisedDTD[i].endsWithChar (';'))
  12173. {
  12174. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12175. StringArray newToks;
  12176. newToks.addTokens (parsed, true);
  12177. tokenisedDTD.remove (i);
  12178. for (int j = newToks.size(); --j >= 0;)
  12179. tokenisedDTD.insert (i, newToks[j]);
  12180. }
  12181. }
  12182. }
  12183. needToLoadDTD = false;
  12184. }
  12185. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12186. {
  12187. if (tokenisedDTD[i] == entity)
  12188. {
  12189. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12190. {
  12191. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12192. // check for sub-entities..
  12193. int ampersand = ent.indexOfChar ('&');
  12194. while (ampersand >= 0)
  12195. {
  12196. const int semiColon = ent.indexOf (i + 1, ";");
  12197. if (semiColon < 0)
  12198. {
  12199. setLastError ("entity without terminating semi-colon", false);
  12200. break;
  12201. }
  12202. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12203. ent = ent.substring (0, ampersand)
  12204. + resolved
  12205. + ent.substring (semiColon + 1);
  12206. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12207. }
  12208. return ent;
  12209. }
  12210. }
  12211. }
  12212. setLastError ("unknown entity", true);
  12213. return entity;
  12214. }
  12215. const String XmlDocument::getParameterEntity (const String& entity)
  12216. {
  12217. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12218. {
  12219. if (tokenisedDTD[i] == entity
  12220. && tokenisedDTD [i - 1] == "%"
  12221. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12222. {
  12223. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12224. if (ent.equalsIgnoreCase ("system"))
  12225. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12226. else
  12227. return ent.trim().unquoted();
  12228. }
  12229. }
  12230. return entity;
  12231. }
  12232. END_JUCE_NAMESPACE
  12233. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12234. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12235. BEGIN_JUCE_NAMESPACE
  12236. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12237. : name (other.name),
  12238. value (other.value)
  12239. {
  12240. }
  12241. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12242. : name (name_),
  12243. value (value_)
  12244. {
  12245. #if JUCE_DEBUG
  12246. // this checks whether the attribute name string contains any illegal characters..
  12247. for (String::CharPointerType t (name.getCharPointer()); ! t.isEmpty(); ++t)
  12248. jassert (t.isLetterOrDigit() || *t == '_' || *t == '-' || *t == ':');
  12249. #endif
  12250. }
  12251. inline bool XmlElement::XmlAttributeNode::hasName (const String& nameToMatch) const throw()
  12252. {
  12253. return name.equalsIgnoreCase (nameToMatch);
  12254. }
  12255. XmlElement::XmlElement (const String& tagName_) throw()
  12256. : tagName (tagName_)
  12257. {
  12258. // the tag name mustn't be empty, or it'll look like a text element!
  12259. jassert (tagName_.containsNonWhitespaceChars())
  12260. // The tag can't contain spaces or other characters that would create invalid XML!
  12261. jassert (! tagName_.containsAnyOf (" <>/&"));
  12262. }
  12263. XmlElement::XmlElement (int /*dummy*/) throw()
  12264. {
  12265. }
  12266. XmlElement::XmlElement (const XmlElement& other)
  12267. : tagName (other.tagName)
  12268. {
  12269. copyChildrenAndAttributesFrom (other);
  12270. }
  12271. XmlElement& XmlElement::operator= (const XmlElement& other)
  12272. {
  12273. if (this != &other)
  12274. {
  12275. removeAllAttributes();
  12276. deleteAllChildElements();
  12277. tagName = other.tagName;
  12278. copyChildrenAndAttributesFrom (other);
  12279. }
  12280. return *this;
  12281. }
  12282. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12283. {
  12284. jassert (firstChildElement.get() == 0);
  12285. firstChildElement.addCopyOfList (other.firstChildElement);
  12286. jassert (attributes.get() == 0);
  12287. attributes.addCopyOfList (other.attributes);
  12288. }
  12289. XmlElement::~XmlElement() throw()
  12290. {
  12291. firstChildElement.deleteAll();
  12292. attributes.deleteAll();
  12293. }
  12294. namespace XmlOutputFunctions
  12295. {
  12296. /*bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12297. {
  12298. if ((character >= 'a' && character <= 'z')
  12299. || (character >= 'A' && character <= 'Z')
  12300. || (character >= '0' && character <= '9'))
  12301. return true;
  12302. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12303. do
  12304. {
  12305. if (((juce_wchar) (uint8) *t) == character)
  12306. return true;
  12307. }
  12308. while (*++t != 0);
  12309. return false;
  12310. }
  12311. void generateLegalCharConstants()
  12312. {
  12313. uint8 n[32];
  12314. zerostruct (n);
  12315. for (int i = 0; i < 256; ++i)
  12316. if (isLegalXmlCharSlow (i))
  12317. n[i >> 3] |= (1 << (i & 7));
  12318. String s;
  12319. for (int i = 0; i < 32; ++i)
  12320. s << (int) n[i] << ", ";
  12321. DBG (s);
  12322. }*/
  12323. bool isLegalXmlChar (const uint32 c) throw()
  12324. {
  12325. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12326. return c < sizeof (legalChars) * 8
  12327. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12328. }
  12329. void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12330. {
  12331. String::CharPointerType t (text.getCharPointer());
  12332. for (;;)
  12333. {
  12334. const uint32 character = (uint32) t.getAndAdvance();
  12335. if (character == 0)
  12336. break;
  12337. if (isLegalXmlChar (character))
  12338. {
  12339. outputStream << (char) character;
  12340. }
  12341. else
  12342. {
  12343. switch (character)
  12344. {
  12345. case '&': outputStream << "&amp;"; break;
  12346. case '"': outputStream << "&quot;"; break;
  12347. case '>': outputStream << "&gt;"; break;
  12348. case '<': outputStream << "&lt;"; break;
  12349. case '\n':
  12350. case '\r':
  12351. if (! changeNewLines)
  12352. {
  12353. outputStream << (char) character;
  12354. break;
  12355. }
  12356. // Note: deliberate fall-through here!
  12357. default:
  12358. outputStream << "&#" << ((int) character) << ';';
  12359. break;
  12360. }
  12361. }
  12362. }
  12363. }
  12364. void writeSpaces (OutputStream& out, int numSpaces)
  12365. {
  12366. if (numSpaces > 0)
  12367. {
  12368. const char blanks[] = " ";
  12369. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12370. while (numSpaces > blankSize)
  12371. {
  12372. out.write (blanks, blankSize);
  12373. numSpaces -= blankSize;
  12374. }
  12375. out.write (blanks, numSpaces);
  12376. }
  12377. }
  12378. }
  12379. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12380. const int indentationLevel,
  12381. const int lineWrapLength) const
  12382. {
  12383. using namespace XmlOutputFunctions;
  12384. writeSpaces (outputStream, indentationLevel);
  12385. if (! isTextElement())
  12386. {
  12387. outputStream.writeByte ('<');
  12388. outputStream << tagName;
  12389. {
  12390. const int attIndent = indentationLevel + tagName.length() + 1;
  12391. int lineLen = 0;
  12392. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12393. {
  12394. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12395. {
  12396. outputStream << newLine;
  12397. writeSpaces (outputStream, attIndent);
  12398. lineLen = 0;
  12399. }
  12400. const int64 startPos = outputStream.getPosition();
  12401. outputStream.writeByte (' ');
  12402. outputStream << att->name;
  12403. outputStream.write ("=\"", 2);
  12404. escapeIllegalXmlChars (outputStream, att->value, true);
  12405. outputStream.writeByte ('"');
  12406. lineLen += (int) (outputStream.getPosition() - startPos);
  12407. }
  12408. }
  12409. if (firstChildElement != 0)
  12410. {
  12411. outputStream.writeByte ('>');
  12412. XmlElement* child = firstChildElement;
  12413. bool lastWasTextNode = false;
  12414. while (child != 0)
  12415. {
  12416. if (child->isTextElement())
  12417. {
  12418. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12419. lastWasTextNode = true;
  12420. }
  12421. else
  12422. {
  12423. if (indentationLevel >= 0 && ! lastWasTextNode)
  12424. outputStream << newLine;
  12425. child->writeElementAsText (outputStream,
  12426. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12427. lastWasTextNode = false;
  12428. }
  12429. child = child->getNextElement();
  12430. }
  12431. if (indentationLevel >= 0 && ! lastWasTextNode)
  12432. {
  12433. outputStream << newLine;
  12434. writeSpaces (outputStream, indentationLevel);
  12435. }
  12436. outputStream.write ("</", 2);
  12437. outputStream << tagName;
  12438. outputStream.writeByte ('>');
  12439. }
  12440. else
  12441. {
  12442. outputStream.write ("/>", 2);
  12443. }
  12444. }
  12445. else
  12446. {
  12447. escapeIllegalXmlChars (outputStream, getText(), false);
  12448. }
  12449. }
  12450. const String XmlElement::createDocument (const String& dtdToUse,
  12451. const bool allOnOneLine,
  12452. const bool includeXmlHeader,
  12453. const String& encodingType,
  12454. const int lineWrapLength) const
  12455. {
  12456. MemoryOutputStream mem (2048);
  12457. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12458. return mem.toUTF8();
  12459. }
  12460. void XmlElement::writeToStream (OutputStream& output,
  12461. const String& dtdToUse,
  12462. const bool allOnOneLine,
  12463. const bool includeXmlHeader,
  12464. const String& encodingType,
  12465. const int lineWrapLength) const
  12466. {
  12467. using namespace XmlOutputFunctions;
  12468. if (includeXmlHeader)
  12469. {
  12470. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12471. if (allOnOneLine)
  12472. output.writeByte (' ');
  12473. else
  12474. output << newLine << newLine;
  12475. }
  12476. if (dtdToUse.isNotEmpty())
  12477. {
  12478. output << dtdToUse;
  12479. if (allOnOneLine)
  12480. output.writeByte (' ');
  12481. else
  12482. output << newLine;
  12483. }
  12484. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12485. if (! allOnOneLine)
  12486. output << newLine;
  12487. }
  12488. bool XmlElement::writeToFile (const File& file,
  12489. const String& dtdToUse,
  12490. const String& encodingType,
  12491. const int lineWrapLength) const
  12492. {
  12493. if (file.hasWriteAccess())
  12494. {
  12495. TemporaryFile tempFile (file);
  12496. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12497. if (out != 0)
  12498. {
  12499. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12500. out = 0;
  12501. return tempFile.overwriteTargetFileWithTemporary();
  12502. }
  12503. }
  12504. return false;
  12505. }
  12506. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12507. {
  12508. #if JUCE_DEBUG
  12509. // if debugging, check that the case is actually the same, because
  12510. // valid xml is case-sensitive, and although this lets it pass, it's
  12511. // better not to..
  12512. if (tagName.equalsIgnoreCase (tagNameWanted))
  12513. {
  12514. jassert (tagName == tagNameWanted);
  12515. return true;
  12516. }
  12517. else
  12518. {
  12519. return false;
  12520. }
  12521. #else
  12522. return tagName.equalsIgnoreCase (tagNameWanted);
  12523. #endif
  12524. }
  12525. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12526. {
  12527. XmlElement* e = nextListItem;
  12528. while (e != 0 && ! e->hasTagName (requiredTagName))
  12529. e = e->nextListItem;
  12530. return e;
  12531. }
  12532. int XmlElement::getNumAttributes() const throw()
  12533. {
  12534. return attributes.size();
  12535. }
  12536. const String& XmlElement::getAttributeName (const int index) const throw()
  12537. {
  12538. const XmlAttributeNode* const att = attributes [index];
  12539. return att != 0 ? att->name : String::empty;
  12540. }
  12541. const String& XmlElement::getAttributeValue (const int index) const throw()
  12542. {
  12543. const XmlAttributeNode* const att = attributes [index];
  12544. return att != 0 ? att->value : String::empty;
  12545. }
  12546. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12547. {
  12548. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12549. if (att->hasName (attributeName))
  12550. return true;
  12551. return false;
  12552. }
  12553. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12554. {
  12555. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12556. if (att->hasName (attributeName))
  12557. return att->value;
  12558. return String::empty;
  12559. }
  12560. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12561. {
  12562. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12563. if (att->hasName (attributeName))
  12564. return att->value;
  12565. return defaultReturnValue;
  12566. }
  12567. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12568. {
  12569. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12570. if (att->hasName (attributeName))
  12571. return att->value.getIntValue();
  12572. return defaultReturnValue;
  12573. }
  12574. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12575. {
  12576. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12577. if (att->hasName (attributeName))
  12578. return att->value.getDoubleValue();
  12579. return defaultReturnValue;
  12580. }
  12581. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12582. {
  12583. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12584. {
  12585. if (att->hasName (attributeName))
  12586. {
  12587. juce_wchar firstChar = att->value[0];
  12588. if (CharacterFunctions::isWhitespace (firstChar))
  12589. firstChar = att->value.trimStart() [0];
  12590. return firstChar == '1'
  12591. || firstChar == 't'
  12592. || firstChar == 'y'
  12593. || firstChar == 'T'
  12594. || firstChar == 'Y';
  12595. }
  12596. }
  12597. return defaultReturnValue;
  12598. }
  12599. bool XmlElement::compareAttribute (const String& attributeName,
  12600. const String& stringToCompareAgainst,
  12601. const bool ignoreCase) const throw()
  12602. {
  12603. for (const XmlAttributeNode* att = attributes; att != 0; att = att->nextListItem)
  12604. if (att->hasName (attributeName))
  12605. return ignoreCase ? att->value.equalsIgnoreCase (stringToCompareAgainst)
  12606. : att->value == stringToCompareAgainst;
  12607. return false;
  12608. }
  12609. void XmlElement::setAttribute (const String& attributeName, const String& value)
  12610. {
  12611. if (attributes == 0)
  12612. {
  12613. attributes = new XmlAttributeNode (attributeName, value);
  12614. }
  12615. else
  12616. {
  12617. XmlAttributeNode* att = attributes;
  12618. for (;;)
  12619. {
  12620. if (att->hasName (attributeName))
  12621. {
  12622. att->value = value;
  12623. break;
  12624. }
  12625. else if (att->nextListItem == 0)
  12626. {
  12627. att->nextListItem = new XmlAttributeNode (attributeName, value);
  12628. break;
  12629. }
  12630. att = att->nextListItem;
  12631. }
  12632. }
  12633. }
  12634. void XmlElement::setAttribute (const String& attributeName, const int number)
  12635. {
  12636. setAttribute (attributeName, String (number));
  12637. }
  12638. void XmlElement::setAttribute (const String& attributeName, const double number)
  12639. {
  12640. setAttribute (attributeName, String (number));
  12641. }
  12642. void XmlElement::removeAttribute (const String& attributeName) throw()
  12643. {
  12644. LinkedListPointer<XmlAttributeNode>* att = &attributes;
  12645. while (att->get() != 0)
  12646. {
  12647. if (att->get()->hasName (attributeName))
  12648. {
  12649. delete att->removeNext();
  12650. break;
  12651. }
  12652. att = &(att->get()->nextListItem);
  12653. }
  12654. }
  12655. void XmlElement::removeAllAttributes() throw()
  12656. {
  12657. attributes.deleteAll();
  12658. }
  12659. int XmlElement::getNumChildElements() const throw()
  12660. {
  12661. return firstChildElement.size();
  12662. }
  12663. XmlElement* XmlElement::getChildElement (const int index) const throw()
  12664. {
  12665. return firstChildElement [index].get();
  12666. }
  12667. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  12668. {
  12669. XmlElement* child = firstChildElement;
  12670. while (child != 0)
  12671. {
  12672. if (child->hasTagName (childName))
  12673. break;
  12674. child = child->nextListItem;
  12675. }
  12676. return child;
  12677. }
  12678. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  12679. {
  12680. if (newNode != 0)
  12681. firstChildElement.append (newNode);
  12682. }
  12683. void XmlElement::insertChildElement (XmlElement* const newNode,
  12684. int indexToInsertAt) throw()
  12685. {
  12686. if (newNode != 0)
  12687. {
  12688. removeChildElement (newNode, false);
  12689. firstChildElement.insertAtIndex (indexToInsertAt, newNode);
  12690. }
  12691. }
  12692. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  12693. {
  12694. XmlElement* const newElement = new XmlElement (childTagName);
  12695. addChildElement (newElement);
  12696. return newElement;
  12697. }
  12698. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  12699. XmlElement* const newNode) throw()
  12700. {
  12701. if (newNode != 0)
  12702. {
  12703. LinkedListPointer<XmlElement>* const p = firstChildElement.findPointerTo (currentChildElement);
  12704. if (p != 0)
  12705. {
  12706. if (currentChildElement != newNode)
  12707. delete p->replaceNext (newNode);
  12708. return true;
  12709. }
  12710. }
  12711. return false;
  12712. }
  12713. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  12714. const bool shouldDeleteTheChild) throw()
  12715. {
  12716. if (childToRemove != 0)
  12717. {
  12718. firstChildElement.remove (childToRemove);
  12719. if (shouldDeleteTheChild)
  12720. delete childToRemove;
  12721. }
  12722. }
  12723. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  12724. const bool ignoreOrderOfAttributes) const throw()
  12725. {
  12726. if (this != other)
  12727. {
  12728. if (other == 0 || tagName != other->tagName)
  12729. return false;
  12730. if (ignoreOrderOfAttributes)
  12731. {
  12732. int totalAtts = 0;
  12733. const XmlAttributeNode* att = attributes;
  12734. while (att != 0)
  12735. {
  12736. if (! other->compareAttribute (att->name, att->value))
  12737. return false;
  12738. att = att->nextListItem;
  12739. ++totalAtts;
  12740. }
  12741. if (totalAtts != other->getNumAttributes())
  12742. return false;
  12743. }
  12744. else
  12745. {
  12746. const XmlAttributeNode* thisAtt = attributes;
  12747. const XmlAttributeNode* otherAtt = other->attributes;
  12748. for (;;)
  12749. {
  12750. if (thisAtt == 0 || otherAtt == 0)
  12751. {
  12752. if (thisAtt == otherAtt) // both 0, so it's a match
  12753. break;
  12754. return false;
  12755. }
  12756. if (thisAtt->name != otherAtt->name
  12757. || thisAtt->value != otherAtt->value)
  12758. {
  12759. return false;
  12760. }
  12761. thisAtt = thisAtt->nextListItem;
  12762. otherAtt = otherAtt->nextListItem;
  12763. }
  12764. }
  12765. const XmlElement* thisChild = firstChildElement;
  12766. const XmlElement* otherChild = other->firstChildElement;
  12767. for (;;)
  12768. {
  12769. if (thisChild == 0 || otherChild == 0)
  12770. {
  12771. if (thisChild == otherChild) // both 0, so it's a match
  12772. break;
  12773. return false;
  12774. }
  12775. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  12776. return false;
  12777. thisChild = thisChild->nextListItem;
  12778. otherChild = otherChild->nextListItem;
  12779. }
  12780. }
  12781. return true;
  12782. }
  12783. void XmlElement::deleteAllChildElements() throw()
  12784. {
  12785. firstChildElement.deleteAll();
  12786. }
  12787. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  12788. {
  12789. XmlElement* child = firstChildElement;
  12790. while (child != 0)
  12791. {
  12792. XmlElement* const nextChild = child->nextListItem;
  12793. if (child->hasTagName (name))
  12794. removeChildElement (child, true);
  12795. child = nextChild;
  12796. }
  12797. }
  12798. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  12799. {
  12800. return firstChildElement.contains (possibleChild);
  12801. }
  12802. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  12803. {
  12804. if (this == elementToLookFor || elementToLookFor == 0)
  12805. return 0;
  12806. XmlElement* child = firstChildElement;
  12807. while (child != 0)
  12808. {
  12809. if (elementToLookFor == child)
  12810. return this;
  12811. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  12812. if (found != 0)
  12813. return found;
  12814. child = child->nextListItem;
  12815. }
  12816. return 0;
  12817. }
  12818. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  12819. {
  12820. firstChildElement.copyToArray (elems);
  12821. }
  12822. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  12823. {
  12824. XmlElement* e = firstChildElement = elems[0];
  12825. for (int i = 1; i < num; ++i)
  12826. {
  12827. e->nextListItem = elems[i];
  12828. e = e->nextListItem;
  12829. }
  12830. e->nextListItem = 0;
  12831. }
  12832. bool XmlElement::isTextElement() const throw()
  12833. {
  12834. return tagName.isEmpty();
  12835. }
  12836. static const String juce_xmltextContentAttributeName ("text");
  12837. const String& XmlElement::getText() const throw()
  12838. {
  12839. jassert (isTextElement()); // you're trying to get the text from an element that
  12840. // isn't actually a text element.. If this contains text sub-nodes, you
  12841. // probably want to use getAllSubText instead.
  12842. return getStringAttribute (juce_xmltextContentAttributeName);
  12843. }
  12844. void XmlElement::setText (const String& newText)
  12845. {
  12846. if (isTextElement())
  12847. setAttribute (juce_xmltextContentAttributeName, newText);
  12848. else
  12849. jassertfalse; // you can only change the text in a text element, not a normal one.
  12850. }
  12851. const String XmlElement::getAllSubText() const
  12852. {
  12853. if (isTextElement())
  12854. return getText();
  12855. String result;
  12856. String::Concatenator concatenator (result);
  12857. const XmlElement* child = firstChildElement;
  12858. while (child != 0)
  12859. {
  12860. concatenator.append (child->getAllSubText());
  12861. child = child->nextListItem;
  12862. }
  12863. return result;
  12864. }
  12865. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  12866. const String& defaultReturnValue) const
  12867. {
  12868. const XmlElement* const child = getChildByName (childTagName);
  12869. if (child != 0)
  12870. return child->getAllSubText();
  12871. return defaultReturnValue;
  12872. }
  12873. XmlElement* XmlElement::createTextElement (const String& text)
  12874. {
  12875. XmlElement* const e = new XmlElement ((int) 0);
  12876. e->setAttribute (juce_xmltextContentAttributeName, text);
  12877. return e;
  12878. }
  12879. void XmlElement::addTextElement (const String& text)
  12880. {
  12881. addChildElement (createTextElement (text));
  12882. }
  12883. void XmlElement::deleteAllTextElements() throw()
  12884. {
  12885. XmlElement* child = firstChildElement;
  12886. while (child != 0)
  12887. {
  12888. XmlElement* const next = child->nextListItem;
  12889. if (child->isTextElement())
  12890. removeChildElement (child, true);
  12891. child = next;
  12892. }
  12893. }
  12894. END_JUCE_NAMESPACE
  12895. /*** End of inlined file: juce_XmlElement.cpp ***/
  12896. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  12897. BEGIN_JUCE_NAMESPACE
  12898. ReadWriteLock::ReadWriteLock() throw()
  12899. : numWaitingWriters (0),
  12900. numWriters (0),
  12901. writerThreadId (0)
  12902. {
  12903. }
  12904. ReadWriteLock::~ReadWriteLock() throw()
  12905. {
  12906. jassert (readerThreads.size() == 0);
  12907. jassert (numWriters == 0);
  12908. }
  12909. void ReadWriteLock::enterRead() const throw()
  12910. {
  12911. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12912. const ScopedLock sl (accessLock);
  12913. for (;;)
  12914. {
  12915. jassert (readerThreads.size() % 2 == 0);
  12916. int i;
  12917. for (i = 0; i < readerThreads.size(); i += 2)
  12918. if (readerThreads.getUnchecked(i) == threadId)
  12919. break;
  12920. if (i < readerThreads.size()
  12921. || numWriters + numWaitingWriters == 0
  12922. || (threadId == writerThreadId && numWriters > 0))
  12923. {
  12924. if (i < readerThreads.size())
  12925. {
  12926. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  12927. }
  12928. else
  12929. {
  12930. readerThreads.add (threadId);
  12931. readerThreads.add ((Thread::ThreadID) 1);
  12932. }
  12933. return;
  12934. }
  12935. const ScopedUnlock ul (accessLock);
  12936. waitEvent.wait (100);
  12937. }
  12938. }
  12939. void ReadWriteLock::exitRead() const throw()
  12940. {
  12941. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12942. const ScopedLock sl (accessLock);
  12943. for (int i = 0; i < readerThreads.size(); i += 2)
  12944. {
  12945. if (readerThreads.getUnchecked(i) == threadId)
  12946. {
  12947. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  12948. if (newCount == 0)
  12949. {
  12950. readerThreads.removeRange (i, 2);
  12951. waitEvent.signal();
  12952. }
  12953. else
  12954. {
  12955. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  12956. }
  12957. return;
  12958. }
  12959. }
  12960. jassertfalse; // unlocking a lock that wasn't locked..
  12961. }
  12962. void ReadWriteLock::enterWrite() const throw()
  12963. {
  12964. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12965. const ScopedLock sl (accessLock);
  12966. for (;;)
  12967. {
  12968. if (readerThreads.size() + numWriters == 0
  12969. || threadId == writerThreadId
  12970. || (readerThreads.size() == 2
  12971. && readerThreads.getUnchecked(0) == threadId))
  12972. {
  12973. writerThreadId = threadId;
  12974. ++numWriters;
  12975. break;
  12976. }
  12977. ++numWaitingWriters;
  12978. accessLock.exit();
  12979. waitEvent.wait (100);
  12980. accessLock.enter();
  12981. --numWaitingWriters;
  12982. }
  12983. }
  12984. bool ReadWriteLock::tryEnterWrite() const throw()
  12985. {
  12986. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  12987. const ScopedLock sl (accessLock);
  12988. if (readerThreads.size() + numWriters == 0
  12989. || threadId == writerThreadId
  12990. || (readerThreads.size() == 2
  12991. && readerThreads.getUnchecked(0) == threadId))
  12992. {
  12993. writerThreadId = threadId;
  12994. ++numWriters;
  12995. return true;
  12996. }
  12997. return false;
  12998. }
  12999. void ReadWriteLock::exitWrite() const throw()
  13000. {
  13001. const ScopedLock sl (accessLock);
  13002. // check this thread actually had the lock..
  13003. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13004. if (--numWriters == 0)
  13005. {
  13006. writerThreadId = 0;
  13007. waitEvent.signal();
  13008. }
  13009. }
  13010. END_JUCE_NAMESPACE
  13011. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13012. /*** Start of inlined file: juce_Thread.cpp ***/
  13013. BEGIN_JUCE_NAMESPACE
  13014. class RunningThreadsList
  13015. {
  13016. public:
  13017. RunningThreadsList()
  13018. {
  13019. }
  13020. void add (Thread* const thread)
  13021. {
  13022. const ScopedLock sl (lock);
  13023. jassert (! threads.contains (thread));
  13024. threads.add (thread);
  13025. }
  13026. void remove (Thread* const thread)
  13027. {
  13028. const ScopedLock sl (lock);
  13029. jassert (threads.contains (thread));
  13030. threads.removeValue (thread);
  13031. }
  13032. int size() const throw()
  13033. {
  13034. return threads.size();
  13035. }
  13036. Thread* getThreadWithID (const Thread::ThreadID targetID) const throw()
  13037. {
  13038. const ScopedLock sl (lock);
  13039. for (int i = threads.size(); --i >= 0;)
  13040. {
  13041. Thread* const t = threads.getUnchecked(i);
  13042. if (t->getThreadId() == targetID)
  13043. return t;
  13044. }
  13045. return 0;
  13046. }
  13047. void stopAll (const int timeOutMilliseconds)
  13048. {
  13049. signalAllThreadsToStop();
  13050. for (;;)
  13051. {
  13052. Thread* firstThread = getFirstThread();
  13053. if (firstThread != 0)
  13054. firstThread->stopThread (timeOutMilliseconds);
  13055. else
  13056. break;
  13057. }
  13058. }
  13059. static RunningThreadsList& getInstance()
  13060. {
  13061. static RunningThreadsList runningThreads;
  13062. return runningThreads;
  13063. }
  13064. private:
  13065. Array<Thread*> threads;
  13066. CriticalSection lock;
  13067. void signalAllThreadsToStop()
  13068. {
  13069. const ScopedLock sl (lock);
  13070. for (int i = threads.size(); --i >= 0;)
  13071. threads.getUnchecked(i)->signalThreadShouldExit();
  13072. }
  13073. Thread* getFirstThread() const
  13074. {
  13075. const ScopedLock sl (lock);
  13076. return threads.getFirst();
  13077. }
  13078. };
  13079. void Thread::threadEntryPoint()
  13080. {
  13081. RunningThreadsList::getInstance().add (this);
  13082. JUCE_TRY
  13083. {
  13084. if (threadName_.isNotEmpty())
  13085. setCurrentThreadName (threadName_);
  13086. if (startSuspensionEvent_.wait (10000))
  13087. {
  13088. jassert (getCurrentThreadId() == threadId_);
  13089. if (affinityMask_ != 0)
  13090. setCurrentThreadAffinityMask (affinityMask_);
  13091. run();
  13092. }
  13093. }
  13094. JUCE_CATCH_ALL_ASSERT
  13095. RunningThreadsList::getInstance().remove (this);
  13096. closeThreadHandle();
  13097. }
  13098. // used to wrap the incoming call from the platform-specific code
  13099. void JUCE_API juce_threadEntryPoint (void* userData)
  13100. {
  13101. static_cast <Thread*> (userData)->threadEntryPoint();
  13102. }
  13103. Thread::Thread (const String& threadName)
  13104. : threadName_ (threadName),
  13105. threadHandle_ (0),
  13106. threadId_ (0),
  13107. threadPriority_ (5),
  13108. affinityMask_ (0),
  13109. threadShouldExit_ (false)
  13110. {
  13111. }
  13112. Thread::~Thread()
  13113. {
  13114. /* If your thread class's destructor has been called without first stopping the thread, that
  13115. means that this partially destructed object is still performing some work - and that's
  13116. probably a Bad Thing!
  13117. To avoid this type of nastiness, always make sure you call stopThread() before or during
  13118. your subclass's destructor.
  13119. */
  13120. jassert (! isThreadRunning());
  13121. stopThread (100);
  13122. }
  13123. void Thread::startThread()
  13124. {
  13125. const ScopedLock sl (startStopLock);
  13126. threadShouldExit_ = false;
  13127. if (threadHandle_ == 0)
  13128. {
  13129. launchThread();
  13130. setThreadPriority (threadHandle_, threadPriority_);
  13131. startSuspensionEvent_.signal();
  13132. }
  13133. }
  13134. void Thread::startThread (const int priority)
  13135. {
  13136. const ScopedLock sl (startStopLock);
  13137. if (threadHandle_ == 0)
  13138. {
  13139. threadPriority_ = priority;
  13140. startThread();
  13141. }
  13142. else
  13143. {
  13144. setPriority (priority);
  13145. }
  13146. }
  13147. bool Thread::isThreadRunning() const
  13148. {
  13149. return threadHandle_ != 0;
  13150. }
  13151. void Thread::signalThreadShouldExit()
  13152. {
  13153. threadShouldExit_ = true;
  13154. }
  13155. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13156. {
  13157. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13158. jassert (getThreadId() != getCurrentThreadId());
  13159. const int sleepMsPerIteration = 5;
  13160. int count = timeOutMilliseconds / sleepMsPerIteration;
  13161. while (isThreadRunning())
  13162. {
  13163. if (timeOutMilliseconds > 0 && --count < 0)
  13164. return false;
  13165. sleep (sleepMsPerIteration);
  13166. }
  13167. return true;
  13168. }
  13169. void Thread::stopThread (const int timeOutMilliseconds)
  13170. {
  13171. // agh! You can't stop the thread that's calling this method! How on earth
  13172. // would that work??
  13173. jassert (getCurrentThreadId() != getThreadId());
  13174. const ScopedLock sl (startStopLock);
  13175. if (isThreadRunning())
  13176. {
  13177. signalThreadShouldExit();
  13178. notify();
  13179. if (timeOutMilliseconds != 0)
  13180. waitForThreadToExit (timeOutMilliseconds);
  13181. if (isThreadRunning())
  13182. {
  13183. // very bad karma if this point is reached, as there are bound to be
  13184. // locks and events left in silly states when a thread is killed by force..
  13185. jassertfalse;
  13186. Logger::writeToLog ("!! killing thread by force !!");
  13187. killThread();
  13188. RunningThreadsList::getInstance().remove (this);
  13189. threadHandle_ = 0;
  13190. threadId_ = 0;
  13191. }
  13192. }
  13193. }
  13194. bool Thread::setPriority (const int priority)
  13195. {
  13196. const ScopedLock sl (startStopLock);
  13197. if (setThreadPriority (threadHandle_, priority))
  13198. {
  13199. threadPriority_ = priority;
  13200. return true;
  13201. }
  13202. return false;
  13203. }
  13204. bool Thread::setCurrentThreadPriority (const int priority)
  13205. {
  13206. return setThreadPriority (0, priority);
  13207. }
  13208. void Thread::setAffinityMask (const uint32 affinityMask)
  13209. {
  13210. affinityMask_ = affinityMask;
  13211. }
  13212. bool Thread::wait (const int timeOutMilliseconds) const
  13213. {
  13214. return defaultEvent_.wait (timeOutMilliseconds);
  13215. }
  13216. void Thread::notify() const
  13217. {
  13218. defaultEvent_.signal();
  13219. }
  13220. int Thread::getNumRunningThreads()
  13221. {
  13222. return RunningThreadsList::getInstance().size();
  13223. }
  13224. Thread* Thread::getCurrentThread()
  13225. {
  13226. return RunningThreadsList::getInstance().getThreadWithID (getCurrentThreadId());
  13227. }
  13228. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13229. {
  13230. RunningThreadsList::getInstance().stopAll (timeOutMilliseconds);
  13231. }
  13232. END_JUCE_NAMESPACE
  13233. /*** End of inlined file: juce_Thread.cpp ***/
  13234. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13235. BEGIN_JUCE_NAMESPACE
  13236. ThreadPoolJob::ThreadPoolJob (const String& name)
  13237. : jobName (name),
  13238. pool (0),
  13239. shouldStop (false),
  13240. isActive (false),
  13241. shouldBeDeleted (false)
  13242. {
  13243. }
  13244. ThreadPoolJob::~ThreadPoolJob()
  13245. {
  13246. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13247. // to remove it first!
  13248. jassert (pool == 0 || ! pool->contains (this));
  13249. }
  13250. const String ThreadPoolJob::getJobName() const
  13251. {
  13252. return jobName;
  13253. }
  13254. void ThreadPoolJob::setJobName (const String& newName)
  13255. {
  13256. jobName = newName;
  13257. }
  13258. void ThreadPoolJob::signalJobShouldExit()
  13259. {
  13260. shouldStop = true;
  13261. }
  13262. class ThreadPool::ThreadPoolThread : public Thread
  13263. {
  13264. public:
  13265. ThreadPoolThread (ThreadPool& pool_)
  13266. : Thread ("Pool"),
  13267. pool (pool_),
  13268. busy (false)
  13269. {
  13270. }
  13271. void run()
  13272. {
  13273. while (! threadShouldExit())
  13274. {
  13275. if (! pool.runNextJob())
  13276. wait (500);
  13277. }
  13278. }
  13279. private:
  13280. ThreadPool& pool;
  13281. bool volatile busy;
  13282. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ThreadPoolThread);
  13283. };
  13284. ThreadPool::ThreadPool (const int numThreads,
  13285. const bool startThreadsOnlyWhenNeeded,
  13286. const int stopThreadsWhenNotUsedTimeoutMs)
  13287. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13288. priority (5)
  13289. {
  13290. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13291. for (int i = jmax (1, numThreads); --i >= 0;)
  13292. threads.add (new ThreadPoolThread (*this));
  13293. if (! startThreadsOnlyWhenNeeded)
  13294. for (int i = threads.size(); --i >= 0;)
  13295. threads.getUnchecked(i)->startThread (priority);
  13296. }
  13297. ThreadPool::~ThreadPool()
  13298. {
  13299. removeAllJobs (true, 4000);
  13300. int i;
  13301. for (i = threads.size(); --i >= 0;)
  13302. threads.getUnchecked(i)->signalThreadShouldExit();
  13303. for (i = threads.size(); --i >= 0;)
  13304. threads.getUnchecked(i)->stopThread (500);
  13305. }
  13306. void ThreadPool::addJob (ThreadPoolJob* const job)
  13307. {
  13308. jassert (job != 0);
  13309. jassert (job->pool == 0);
  13310. if (job->pool == 0)
  13311. {
  13312. job->pool = this;
  13313. job->shouldStop = false;
  13314. job->isActive = false;
  13315. {
  13316. const ScopedLock sl (lock);
  13317. jobs.add (job);
  13318. int numRunning = 0;
  13319. for (int i = threads.size(); --i >= 0;)
  13320. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13321. ++numRunning;
  13322. if (numRunning < threads.size())
  13323. {
  13324. bool startedOne = false;
  13325. int n = 1000;
  13326. while (--n >= 0 && ! startedOne)
  13327. {
  13328. for (int i = threads.size(); --i >= 0;)
  13329. {
  13330. if (! threads.getUnchecked(i)->isThreadRunning())
  13331. {
  13332. threads.getUnchecked(i)->startThread (priority);
  13333. startedOne = true;
  13334. break;
  13335. }
  13336. }
  13337. if (! startedOne)
  13338. Thread::sleep (2);
  13339. }
  13340. }
  13341. }
  13342. for (int i = threads.size(); --i >= 0;)
  13343. threads.getUnchecked(i)->notify();
  13344. }
  13345. }
  13346. int ThreadPool::getNumJobs() const
  13347. {
  13348. return jobs.size();
  13349. }
  13350. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13351. {
  13352. const ScopedLock sl (lock);
  13353. return jobs [index];
  13354. }
  13355. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13356. {
  13357. const ScopedLock sl (lock);
  13358. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13359. }
  13360. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13361. {
  13362. const ScopedLock sl (lock);
  13363. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13364. }
  13365. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13366. const int timeOutMs) const
  13367. {
  13368. if (job != 0)
  13369. {
  13370. const uint32 start = Time::getMillisecondCounter();
  13371. while (contains (job))
  13372. {
  13373. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13374. return false;
  13375. jobFinishedSignal.wait (2);
  13376. }
  13377. }
  13378. return true;
  13379. }
  13380. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13381. const bool interruptIfRunning,
  13382. const int timeOutMs)
  13383. {
  13384. bool dontWait = true;
  13385. if (job != 0)
  13386. {
  13387. const ScopedLock sl (lock);
  13388. if (jobs.contains (job))
  13389. {
  13390. if (job->isActive)
  13391. {
  13392. if (interruptIfRunning)
  13393. job->signalJobShouldExit();
  13394. dontWait = false;
  13395. }
  13396. else
  13397. {
  13398. jobs.removeValue (job);
  13399. job->pool = 0;
  13400. }
  13401. }
  13402. }
  13403. return dontWait || waitForJobToFinish (job, timeOutMs);
  13404. }
  13405. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13406. const int timeOutMs,
  13407. const bool deleteInactiveJobs,
  13408. ThreadPool::JobSelector* selectedJobsToRemove)
  13409. {
  13410. Array <ThreadPoolJob*> jobsToWaitFor;
  13411. {
  13412. const ScopedLock sl (lock);
  13413. for (int i = jobs.size(); --i >= 0;)
  13414. {
  13415. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13416. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13417. {
  13418. if (job->isActive)
  13419. {
  13420. jobsToWaitFor.add (job);
  13421. if (interruptRunningJobs)
  13422. job->signalJobShouldExit();
  13423. }
  13424. else
  13425. {
  13426. jobs.remove (i);
  13427. if (deleteInactiveJobs)
  13428. delete job;
  13429. else
  13430. job->pool = 0;
  13431. }
  13432. }
  13433. }
  13434. }
  13435. const uint32 start = Time::getMillisecondCounter();
  13436. for (;;)
  13437. {
  13438. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13439. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13440. jobsToWaitFor.remove (i);
  13441. if (jobsToWaitFor.size() == 0)
  13442. break;
  13443. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13444. return false;
  13445. jobFinishedSignal.wait (20);
  13446. }
  13447. return true;
  13448. }
  13449. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13450. {
  13451. StringArray s;
  13452. const ScopedLock sl (lock);
  13453. for (int i = 0; i < jobs.size(); ++i)
  13454. {
  13455. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13456. if (job->isActive || ! onlyReturnActiveJobs)
  13457. s.add (job->getJobName());
  13458. }
  13459. return s;
  13460. }
  13461. bool ThreadPool::setThreadPriorities (const int newPriority)
  13462. {
  13463. bool ok = true;
  13464. if (priority != newPriority)
  13465. {
  13466. priority = newPriority;
  13467. for (int i = threads.size(); --i >= 0;)
  13468. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13469. ok = false;
  13470. }
  13471. return ok;
  13472. }
  13473. bool ThreadPool::runNextJob()
  13474. {
  13475. ThreadPoolJob* job = 0;
  13476. {
  13477. const ScopedLock sl (lock);
  13478. for (int i = 0; i < jobs.size(); ++i)
  13479. {
  13480. job = jobs[i];
  13481. if (job != 0 && ! (job->isActive || job->shouldStop))
  13482. break;
  13483. job = 0;
  13484. }
  13485. if (job != 0)
  13486. job->isActive = true;
  13487. }
  13488. if (job != 0)
  13489. {
  13490. JUCE_TRY
  13491. {
  13492. ThreadPoolJob::JobStatus result = job->runJob();
  13493. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13494. const ScopedLock sl (lock);
  13495. if (jobs.contains (job))
  13496. {
  13497. job->isActive = false;
  13498. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  13499. {
  13500. job->pool = 0;
  13501. job->shouldStop = true;
  13502. jobs.removeValue (job);
  13503. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  13504. delete job;
  13505. jobFinishedSignal.signal();
  13506. }
  13507. else
  13508. {
  13509. // move the job to the end of the queue if it wants another go
  13510. jobs.move (jobs.indexOf (job), -1);
  13511. }
  13512. }
  13513. }
  13514. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  13515. catch (...)
  13516. {
  13517. const ScopedLock sl (lock);
  13518. jobs.removeValue (job);
  13519. }
  13520. #endif
  13521. }
  13522. else
  13523. {
  13524. if (threadStopTimeout > 0
  13525. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  13526. {
  13527. const ScopedLock sl (lock);
  13528. if (jobs.size() == 0)
  13529. for (int i = threads.size(); --i >= 0;)
  13530. threads.getUnchecked(i)->signalThreadShouldExit();
  13531. }
  13532. else
  13533. {
  13534. return false;
  13535. }
  13536. }
  13537. return true;
  13538. }
  13539. END_JUCE_NAMESPACE
  13540. /*** End of inlined file: juce_ThreadPool.cpp ***/
  13541. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  13542. BEGIN_JUCE_NAMESPACE
  13543. TimeSliceThread::TimeSliceThread (const String& threadName)
  13544. : Thread (threadName),
  13545. clientBeingCalled (0)
  13546. {
  13547. }
  13548. TimeSliceThread::~TimeSliceThread()
  13549. {
  13550. stopThread (2000);
  13551. }
  13552. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client, int millisecondsBeforeStarting)
  13553. {
  13554. if (client != 0)
  13555. {
  13556. const ScopedLock sl (listLock);
  13557. client->nextCallTime = Time::getCurrentTime() + RelativeTime::milliseconds (millisecondsBeforeStarting);
  13558. clients.addIfNotAlreadyThere (client);
  13559. notify();
  13560. }
  13561. }
  13562. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  13563. {
  13564. const ScopedLock sl1 (listLock);
  13565. // if there's a chance we're in the middle of calling this client, we need to
  13566. // also lock the outer lock..
  13567. if (clientBeingCalled == client)
  13568. {
  13569. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  13570. const ScopedLock sl2 (callbackLock);
  13571. const ScopedLock sl3 (listLock);
  13572. clients.removeValue (client);
  13573. }
  13574. else
  13575. {
  13576. clients.removeValue (client);
  13577. }
  13578. }
  13579. int TimeSliceThread::getNumClients() const
  13580. {
  13581. return clients.size();
  13582. }
  13583. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  13584. {
  13585. const ScopedLock sl (listLock);
  13586. return clients [i];
  13587. }
  13588. TimeSliceClient* TimeSliceThread::getNextClient (int index) const
  13589. {
  13590. Time soonest;
  13591. TimeSliceClient* client = 0;
  13592. for (int i = clients.size(); --i >= 0;)
  13593. {
  13594. TimeSliceClient* const c = clients.getUnchecked ((i + index) % clients.size());
  13595. if (client == 0 || c->nextCallTime < soonest)
  13596. {
  13597. client = c;
  13598. soonest = c->nextCallTime;
  13599. }
  13600. }
  13601. return client;
  13602. }
  13603. void TimeSliceThread::run()
  13604. {
  13605. int index = 0;
  13606. while (! threadShouldExit())
  13607. {
  13608. int timeToWait = 500;
  13609. {
  13610. Time nextClientTime;
  13611. {
  13612. const ScopedLock sl2 (listLock);
  13613. index = clients.size() > 0 ? ((index + 1) % clients.size()) : 0;
  13614. TimeSliceClient* const firstClient = getNextClient (index);
  13615. if (firstClient != 0)
  13616. nextClientTime = firstClient->nextCallTime;
  13617. }
  13618. const Time now (Time::getCurrentTime());
  13619. if (nextClientTime > now)
  13620. {
  13621. timeToWait = (int) jmin ((int64) 500, (nextClientTime - now).inMilliseconds());
  13622. }
  13623. else
  13624. {
  13625. timeToWait = index == 0 ? 1 : 0;
  13626. const ScopedLock sl (callbackLock);
  13627. {
  13628. const ScopedLock sl2 (listLock);
  13629. clientBeingCalled = getNextClient (index);
  13630. }
  13631. if (clientBeingCalled != 0)
  13632. {
  13633. const int msUntilNextCall = clientBeingCalled->useTimeSlice();
  13634. const ScopedLock sl2 (listLock);
  13635. if (msUntilNextCall >= 0)
  13636. clientBeingCalled->nextCallTime += RelativeTime::milliseconds (msUntilNextCall);
  13637. else
  13638. clients.removeValue (clientBeingCalled);
  13639. clientBeingCalled = 0;
  13640. }
  13641. }
  13642. }
  13643. if (timeToWait > 0)
  13644. wait (timeToWait);
  13645. }
  13646. }
  13647. END_JUCE_NAMESPACE
  13648. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  13649. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  13650. BEGIN_JUCE_NAMESPACE
  13651. DeletedAtShutdown::DeletedAtShutdown()
  13652. {
  13653. const ScopedLock sl (getLock());
  13654. getObjects().add (this);
  13655. }
  13656. DeletedAtShutdown::~DeletedAtShutdown()
  13657. {
  13658. const ScopedLock sl (getLock());
  13659. getObjects().removeValue (this);
  13660. }
  13661. void DeletedAtShutdown::deleteAll()
  13662. {
  13663. // make a local copy of the array, so it can't get into a loop if something
  13664. // creates another DeletedAtShutdown object during its destructor.
  13665. Array <DeletedAtShutdown*> localCopy;
  13666. {
  13667. const ScopedLock sl (getLock());
  13668. localCopy = getObjects();
  13669. }
  13670. for (int i = localCopy.size(); --i >= 0;)
  13671. {
  13672. JUCE_TRY
  13673. {
  13674. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  13675. // double-check that it's not already been deleted during another object's destructor.
  13676. {
  13677. const ScopedLock sl (getLock());
  13678. if (! getObjects().contains (deletee))
  13679. deletee = 0;
  13680. }
  13681. delete deletee;
  13682. }
  13683. JUCE_CATCH_EXCEPTION
  13684. }
  13685. // if no objects got re-created during shutdown, this should have been emptied by their
  13686. // destructors
  13687. jassert (getObjects().size() == 0);
  13688. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  13689. }
  13690. CriticalSection& DeletedAtShutdown::getLock()
  13691. {
  13692. static CriticalSection lock;
  13693. return lock;
  13694. }
  13695. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  13696. {
  13697. static Array <DeletedAtShutdown*> objects;
  13698. return objects;
  13699. }
  13700. END_JUCE_NAMESPACE
  13701. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  13702. /*** Start of inlined file: juce_UnitTest.cpp ***/
  13703. BEGIN_JUCE_NAMESPACE
  13704. UnitTest::UnitTest (const String& name_)
  13705. : name (name_), runner (0)
  13706. {
  13707. getAllTests().add (this);
  13708. }
  13709. UnitTest::~UnitTest()
  13710. {
  13711. getAllTests().removeValue (this);
  13712. }
  13713. Array<UnitTest*>& UnitTest::getAllTests()
  13714. {
  13715. static Array<UnitTest*> tests;
  13716. return tests;
  13717. }
  13718. void UnitTest::initialise() {}
  13719. void UnitTest::shutdown() {}
  13720. void UnitTest::performTest (UnitTestRunner* const runner_)
  13721. {
  13722. jassert (runner_ != 0);
  13723. runner = runner_;
  13724. initialise();
  13725. runTest();
  13726. shutdown();
  13727. }
  13728. void UnitTest::logMessage (const String& message)
  13729. {
  13730. runner->logMessage (message);
  13731. }
  13732. void UnitTest::beginTest (const String& testName)
  13733. {
  13734. runner->beginNewTest (this, testName);
  13735. }
  13736. void UnitTest::expect (const bool result, const String& failureMessage)
  13737. {
  13738. if (result)
  13739. runner->addPass();
  13740. else
  13741. runner->addFail (failureMessage);
  13742. }
  13743. UnitTestRunner::UnitTestRunner()
  13744. : currentTest (0), assertOnFailure (false)
  13745. {
  13746. }
  13747. UnitTestRunner::~UnitTestRunner()
  13748. {
  13749. }
  13750. int UnitTestRunner::getNumResults() const throw()
  13751. {
  13752. return results.size();
  13753. }
  13754. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  13755. {
  13756. return results [index];
  13757. }
  13758. void UnitTestRunner::resultsUpdated()
  13759. {
  13760. }
  13761. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  13762. {
  13763. results.clear();
  13764. assertOnFailure = assertOnFailure_;
  13765. resultsUpdated();
  13766. for (int i = 0; i < tests.size(); ++i)
  13767. {
  13768. try
  13769. {
  13770. tests.getUnchecked(i)->performTest (this);
  13771. }
  13772. catch (...)
  13773. {
  13774. addFail ("An unhandled exception was thrown!");
  13775. }
  13776. }
  13777. endTest();
  13778. }
  13779. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  13780. {
  13781. runTests (UnitTest::getAllTests(), assertOnFailure_);
  13782. }
  13783. void UnitTestRunner::logMessage (const String& message)
  13784. {
  13785. Logger::writeToLog (message);
  13786. }
  13787. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  13788. {
  13789. endTest();
  13790. currentTest = test;
  13791. TestResult* const r = new TestResult();
  13792. r->unitTestName = test->getName();
  13793. r->subcategoryName = subCategory;
  13794. r->passes = 0;
  13795. r->failures = 0;
  13796. results.add (r);
  13797. logMessage ("-----------------------------------------------------------------");
  13798. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  13799. resultsUpdated();
  13800. }
  13801. void UnitTestRunner::endTest()
  13802. {
  13803. if (results.size() > 0)
  13804. {
  13805. TestResult* const r = results.getLast();
  13806. if (r->failures > 0)
  13807. {
  13808. String m ("FAILED!!");
  13809. m << r->failures << (r->failures == 1 ? "test" : "tests")
  13810. << " failed, out of a total of " << (r->passes + r->failures);
  13811. logMessage (String::empty);
  13812. logMessage (m);
  13813. logMessage (String::empty);
  13814. }
  13815. else
  13816. {
  13817. logMessage ("All tests completed successfully");
  13818. }
  13819. }
  13820. }
  13821. void UnitTestRunner::addPass()
  13822. {
  13823. {
  13824. const ScopedLock sl (results.getLock());
  13825. TestResult* const r = results.getLast();
  13826. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13827. r->passes++;
  13828. String message ("Test ");
  13829. message << (r->failures + r->passes) << " passed";
  13830. logMessage (message);
  13831. }
  13832. resultsUpdated();
  13833. }
  13834. void UnitTestRunner::addFail (const String& failureMessage)
  13835. {
  13836. {
  13837. const ScopedLock sl (results.getLock());
  13838. TestResult* const r = results.getLast();
  13839. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  13840. r->failures++;
  13841. String message ("!!! Test ");
  13842. message << (r->failures + r->passes) << " failed";
  13843. if (failureMessage.isNotEmpty())
  13844. message << ": " << failureMessage;
  13845. r->messages.add (message);
  13846. logMessage (message);
  13847. }
  13848. resultsUpdated();
  13849. if (assertOnFailure) { jassertfalse }
  13850. }
  13851. END_JUCE_NAMESPACE
  13852. /*** End of inlined file: juce_UnitTest.cpp ***/
  13853. #endif
  13854. #if JUCE_BUILD_MISC
  13855. /*** Start of inlined file: juce_ValueTree.cpp ***/
  13856. BEGIN_JUCE_NAMESPACE
  13857. class ValueTree::SetPropertyAction : public UndoableAction
  13858. {
  13859. public:
  13860. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  13861. const var& newValue_, const var& oldValue_,
  13862. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  13863. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  13864. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  13865. {
  13866. }
  13867. bool perform()
  13868. {
  13869. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  13870. if (isDeletingProperty)
  13871. target->removeProperty (name, 0);
  13872. else
  13873. target->setProperty (name, newValue, 0);
  13874. return true;
  13875. }
  13876. bool undo()
  13877. {
  13878. if (isAddingNewProperty)
  13879. target->removeProperty (name, 0);
  13880. else
  13881. target->setProperty (name, oldValue, 0);
  13882. return true;
  13883. }
  13884. int getSizeInUnits()
  13885. {
  13886. return (int) sizeof (*this); //xxx should be more accurate
  13887. }
  13888. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13889. {
  13890. if (! (isAddingNewProperty || isDeletingProperty))
  13891. {
  13892. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  13893. if (next != 0 && next->target == target && next->name == name
  13894. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  13895. {
  13896. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  13897. }
  13898. }
  13899. return 0;
  13900. }
  13901. private:
  13902. const SharedObjectPtr target;
  13903. const Identifier name;
  13904. const var newValue;
  13905. var oldValue;
  13906. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  13907. JUCE_DECLARE_NON_COPYABLE (SetPropertyAction);
  13908. };
  13909. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  13910. {
  13911. public:
  13912. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  13913. const SharedObjectPtr& newChild_)
  13914. : target (target_),
  13915. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  13916. childIndex (childIndex_),
  13917. isDeleting (newChild_ == 0)
  13918. {
  13919. jassert (child != 0);
  13920. }
  13921. bool perform()
  13922. {
  13923. if (isDeleting)
  13924. target->removeChild (childIndex, 0);
  13925. else
  13926. target->addChild (child, childIndex, 0);
  13927. return true;
  13928. }
  13929. bool undo()
  13930. {
  13931. if (isDeleting)
  13932. {
  13933. target->addChild (child, childIndex, 0);
  13934. }
  13935. else
  13936. {
  13937. // If you hit this, it seems that your object's state is getting confused - probably
  13938. // because you've interleaved some undoable and non-undoable operations?
  13939. jassert (childIndex < target->children.size());
  13940. target->removeChild (childIndex, 0);
  13941. }
  13942. return true;
  13943. }
  13944. int getSizeInUnits()
  13945. {
  13946. return (int) sizeof (*this); //xxx should be more accurate
  13947. }
  13948. private:
  13949. const SharedObjectPtr target, child;
  13950. const int childIndex;
  13951. const bool isDeleting;
  13952. JUCE_DECLARE_NON_COPYABLE (AddOrRemoveChildAction);
  13953. };
  13954. class ValueTree::MoveChildAction : public UndoableAction
  13955. {
  13956. public:
  13957. MoveChildAction (const SharedObjectPtr& parent_,
  13958. const int startIndex_, const int endIndex_)
  13959. : parent (parent_),
  13960. startIndex (startIndex_),
  13961. endIndex (endIndex_)
  13962. {
  13963. }
  13964. bool perform()
  13965. {
  13966. parent->moveChild (startIndex, endIndex, 0);
  13967. return true;
  13968. }
  13969. bool undo()
  13970. {
  13971. parent->moveChild (endIndex, startIndex, 0);
  13972. return true;
  13973. }
  13974. int getSizeInUnits()
  13975. {
  13976. return (int) sizeof (*this); //xxx should be more accurate
  13977. }
  13978. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  13979. {
  13980. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  13981. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  13982. return new MoveChildAction (parent, startIndex, next->endIndex);
  13983. return 0;
  13984. }
  13985. private:
  13986. const SharedObjectPtr parent;
  13987. const int startIndex, endIndex;
  13988. JUCE_DECLARE_NON_COPYABLE (MoveChildAction);
  13989. };
  13990. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  13991. : type (type_), parent (0)
  13992. {
  13993. }
  13994. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  13995. : type (other.type), properties (other.properties), parent (0)
  13996. {
  13997. for (int i = 0; i < other.children.size(); ++i)
  13998. {
  13999. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14000. child->parent = this;
  14001. children.add (child);
  14002. }
  14003. }
  14004. ValueTree::SharedObject::~SharedObject()
  14005. {
  14006. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14007. for (int i = children.size(); --i >= 0;)
  14008. {
  14009. const SharedObjectPtr c (children.getUnchecked(i));
  14010. c->parent = 0;
  14011. children.remove (i);
  14012. c->sendParentChangeMessage();
  14013. }
  14014. }
  14015. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14016. {
  14017. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14018. {
  14019. ValueTree* const v = valueTreesWithListeners[i];
  14020. if (v != 0)
  14021. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14022. }
  14023. }
  14024. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14025. {
  14026. ValueTree tree (this);
  14027. ValueTree::SharedObject* t = this;
  14028. while (t != 0)
  14029. {
  14030. t->sendPropertyChangeMessage (tree, property);
  14031. t = t->parent;
  14032. }
  14033. }
  14034. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree& tree, ValueTree& child)
  14035. {
  14036. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14037. {
  14038. ValueTree* const v = valueTreesWithListeners[i];
  14039. if (v != 0)
  14040. v->listeners.call (&ValueTree::Listener::valueTreeChildAdded, tree, child);
  14041. }
  14042. }
  14043. void ValueTree::SharedObject::sendChildAddedMessage (ValueTree child)
  14044. {
  14045. ValueTree tree (this);
  14046. ValueTree::SharedObject* t = this;
  14047. while (t != 0)
  14048. {
  14049. t->sendChildAddedMessage (tree, child);
  14050. t = t->parent;
  14051. }
  14052. }
  14053. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree& tree, ValueTree& child)
  14054. {
  14055. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14056. {
  14057. ValueTree* const v = valueTreesWithListeners[i];
  14058. if (v != 0)
  14059. v->listeners.call (&ValueTree::Listener::valueTreeChildRemoved, tree, child);
  14060. }
  14061. }
  14062. void ValueTree::SharedObject::sendChildRemovedMessage (ValueTree child)
  14063. {
  14064. ValueTree tree (this);
  14065. ValueTree::SharedObject* t = this;
  14066. while (t != 0)
  14067. {
  14068. t->sendChildRemovedMessage (tree, child);
  14069. t = t->parent;
  14070. }
  14071. }
  14072. void ValueTree::SharedObject::sendChildOrderChangedMessage (ValueTree& tree)
  14073. {
  14074. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14075. {
  14076. ValueTree* const v = valueTreesWithListeners[i];
  14077. if (v != 0)
  14078. v->listeners.call (&ValueTree::Listener::valueTreeChildOrderChanged, tree);
  14079. }
  14080. }
  14081. void ValueTree::SharedObject::sendChildOrderChangedMessage()
  14082. {
  14083. ValueTree tree (this);
  14084. ValueTree::SharedObject* t = this;
  14085. while (t != 0)
  14086. {
  14087. t->sendChildOrderChangedMessage (tree);
  14088. t = t->parent;
  14089. }
  14090. }
  14091. void ValueTree::SharedObject::sendParentChangeMessage()
  14092. {
  14093. ValueTree tree (this);
  14094. int i;
  14095. for (i = children.size(); --i >= 0;)
  14096. {
  14097. SharedObject* const t = children[i];
  14098. if (t != 0)
  14099. t->sendParentChangeMessage();
  14100. }
  14101. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14102. {
  14103. ValueTree* const v = valueTreesWithListeners[i];
  14104. if (v != 0)
  14105. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14106. }
  14107. }
  14108. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14109. {
  14110. return properties [name];
  14111. }
  14112. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14113. {
  14114. return properties.getWithDefault (name, defaultReturnValue);
  14115. }
  14116. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14117. {
  14118. if (undoManager == 0)
  14119. {
  14120. if (properties.set (name, newValue))
  14121. sendPropertyChangeMessage (name);
  14122. }
  14123. else
  14124. {
  14125. var* const existingValue = properties.getVarPointer (name);
  14126. if (existingValue != 0)
  14127. {
  14128. if (*existingValue != newValue)
  14129. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14130. }
  14131. else
  14132. {
  14133. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14134. }
  14135. }
  14136. }
  14137. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14138. {
  14139. return properties.contains (name);
  14140. }
  14141. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14142. {
  14143. if (undoManager == 0)
  14144. {
  14145. if (properties.remove (name))
  14146. sendPropertyChangeMessage (name);
  14147. }
  14148. else
  14149. {
  14150. if (properties.contains (name))
  14151. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14152. }
  14153. }
  14154. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14155. {
  14156. if (undoManager == 0)
  14157. {
  14158. while (properties.size() > 0)
  14159. {
  14160. const Identifier name (properties.getName (properties.size() - 1));
  14161. properties.remove (name);
  14162. sendPropertyChangeMessage (name);
  14163. }
  14164. }
  14165. else
  14166. {
  14167. for (int i = properties.size(); --i >= 0;)
  14168. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14169. }
  14170. }
  14171. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14172. {
  14173. for (int i = 0; i < children.size(); ++i)
  14174. if (children.getUnchecked(i)->type == typeToMatch)
  14175. return ValueTree (children.getUnchecked(i).getObject());
  14176. return ValueTree::invalid;
  14177. }
  14178. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14179. {
  14180. for (int i = 0; i < children.size(); ++i)
  14181. if (children.getUnchecked(i)->type == typeToMatch)
  14182. return ValueTree (children.getUnchecked(i).getObject());
  14183. SharedObject* const newObject = new SharedObject (typeToMatch);
  14184. addChild (newObject, -1, undoManager);
  14185. return ValueTree (newObject);
  14186. }
  14187. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14188. {
  14189. for (int i = 0; i < children.size(); ++i)
  14190. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14191. return ValueTree (children.getUnchecked(i).getObject());
  14192. return ValueTree::invalid;
  14193. }
  14194. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14195. {
  14196. const SharedObject* p = parent;
  14197. while (p != 0)
  14198. {
  14199. if (p == possibleParent)
  14200. return true;
  14201. p = p->parent;
  14202. }
  14203. return false;
  14204. }
  14205. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14206. {
  14207. return children.indexOf (child.object);
  14208. }
  14209. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14210. {
  14211. if (child != 0 && child->parent != this)
  14212. {
  14213. if (child != this && ! isAChildOf (child))
  14214. {
  14215. // You should always make sure that a child is removed from its previous parent before
  14216. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14217. // undomanager should be used when removing it from its current parent..
  14218. jassert (child->parent == 0);
  14219. if (child->parent != 0)
  14220. {
  14221. jassert (child->parent->children.indexOf (child) >= 0);
  14222. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14223. }
  14224. if (undoManager == 0)
  14225. {
  14226. children.insert (index, child);
  14227. child->parent = this;
  14228. sendChildAddedMessage (ValueTree (child));
  14229. child->sendParentChangeMessage();
  14230. }
  14231. else
  14232. {
  14233. if (index < 0)
  14234. index = children.size();
  14235. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14236. }
  14237. }
  14238. else
  14239. {
  14240. // You're attempting to create a recursive loop! A node
  14241. // can't be a child of one of its own children!
  14242. jassertfalse;
  14243. }
  14244. }
  14245. }
  14246. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14247. {
  14248. const SharedObjectPtr child (children [childIndex]);
  14249. if (child != 0)
  14250. {
  14251. if (undoManager == 0)
  14252. {
  14253. children.remove (childIndex);
  14254. child->parent = 0;
  14255. sendChildRemovedMessage (ValueTree (child));
  14256. child->sendParentChangeMessage();
  14257. }
  14258. else
  14259. {
  14260. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14261. }
  14262. }
  14263. }
  14264. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14265. {
  14266. while (children.size() > 0)
  14267. removeChild (children.size() - 1, undoManager);
  14268. }
  14269. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14270. {
  14271. // The source index must be a valid index!
  14272. jassert (isPositiveAndBelow (currentIndex, children.size()));
  14273. if (currentIndex != newIndex
  14274. && isPositiveAndBelow (currentIndex, children.size()))
  14275. {
  14276. if (undoManager == 0)
  14277. {
  14278. children.move (currentIndex, newIndex);
  14279. sendChildOrderChangedMessage();
  14280. }
  14281. else
  14282. {
  14283. if (! isPositiveAndBelow (newIndex, children.size()))
  14284. newIndex = children.size() - 1;
  14285. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14286. }
  14287. }
  14288. }
  14289. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14290. {
  14291. jassert (newOrder.size() == children.size());
  14292. if (undoManager == 0)
  14293. {
  14294. children = newOrder;
  14295. sendChildOrderChangedMessage();
  14296. }
  14297. else
  14298. {
  14299. for (int i = 0; i < children.size(); ++i)
  14300. {
  14301. const SharedObjectPtr child (newOrder.getUnchecked(i));
  14302. if (children.getUnchecked(i) != child)
  14303. {
  14304. const int oldIndex = children.indexOf (child);
  14305. jassert (oldIndex >= 0);
  14306. moveChild (oldIndex, i, undoManager);
  14307. }
  14308. }
  14309. }
  14310. }
  14311. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14312. {
  14313. if (type != other.type
  14314. || properties.size() != other.properties.size()
  14315. || children.size() != other.children.size()
  14316. || properties != other.properties)
  14317. return false;
  14318. for (int i = 0; i < children.size(); ++i)
  14319. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14320. return false;
  14321. return true;
  14322. }
  14323. ValueTree::ValueTree() throw()
  14324. : object (0)
  14325. {
  14326. }
  14327. const ValueTree ValueTree::invalid;
  14328. ValueTree::ValueTree (const Identifier& type_)
  14329. : object (new ValueTree::SharedObject (type_))
  14330. {
  14331. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14332. }
  14333. ValueTree::ValueTree (SharedObject* const object_)
  14334. : object (object_)
  14335. {
  14336. }
  14337. ValueTree::ValueTree (const ValueTree& other)
  14338. : object (other.object)
  14339. {
  14340. }
  14341. ValueTree& ValueTree::operator= (const ValueTree& other)
  14342. {
  14343. if (listeners.size() > 0)
  14344. {
  14345. if (object != 0)
  14346. object->valueTreesWithListeners.removeValue (this);
  14347. if (other.object != 0)
  14348. other.object->valueTreesWithListeners.add (this);
  14349. }
  14350. object = other.object;
  14351. return *this;
  14352. }
  14353. ValueTree::~ValueTree()
  14354. {
  14355. if (listeners.size() > 0 && object != 0)
  14356. object->valueTreesWithListeners.removeValue (this);
  14357. }
  14358. bool ValueTree::operator== (const ValueTree& other) const throw()
  14359. {
  14360. return object == other.object;
  14361. }
  14362. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14363. {
  14364. return object != other.object;
  14365. }
  14366. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14367. {
  14368. return object == other.object
  14369. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14370. }
  14371. ValueTree ValueTree::createCopy() const
  14372. {
  14373. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14374. }
  14375. bool ValueTree::hasType (const Identifier& typeName) const
  14376. {
  14377. return object != 0 && object->type == typeName;
  14378. }
  14379. const Identifier ValueTree::getType() const
  14380. {
  14381. return object != 0 ? object->type : Identifier();
  14382. }
  14383. ValueTree ValueTree::getParent() const
  14384. {
  14385. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14386. }
  14387. ValueTree ValueTree::getSibling (const int delta) const
  14388. {
  14389. if (object == 0 || object->parent == 0)
  14390. return invalid;
  14391. const int index = object->parent->indexOf (*this) + delta;
  14392. return ValueTree (object->parent->children [index].getObject());
  14393. }
  14394. const var& ValueTree::operator[] (const Identifier& name) const
  14395. {
  14396. return object == 0 ? var::null : object->getProperty (name);
  14397. }
  14398. const var& ValueTree::getProperty (const Identifier& name) const
  14399. {
  14400. return object == 0 ? var::null : object->getProperty (name);
  14401. }
  14402. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14403. {
  14404. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14405. }
  14406. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14407. {
  14408. jassert (name.toString().isNotEmpty());
  14409. if (object != 0 && name.toString().isNotEmpty())
  14410. object->setProperty (name, newValue, undoManager);
  14411. }
  14412. bool ValueTree::hasProperty (const Identifier& name) const
  14413. {
  14414. return object != 0 && object->hasProperty (name);
  14415. }
  14416. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14417. {
  14418. if (object != 0)
  14419. object->removeProperty (name, undoManager);
  14420. }
  14421. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14422. {
  14423. if (object != 0)
  14424. object->removeAllProperties (undoManager);
  14425. }
  14426. int ValueTree::getNumProperties() const
  14427. {
  14428. return object == 0 ? 0 : object->properties.size();
  14429. }
  14430. const Identifier ValueTree::getPropertyName (const int index) const
  14431. {
  14432. return object == 0 ? Identifier()
  14433. : object->properties.getName (index);
  14434. }
  14435. class ValueTreePropertyValueSource : public Value::ValueSource,
  14436. public ValueTree::Listener
  14437. {
  14438. public:
  14439. ValueTreePropertyValueSource (const ValueTree& tree_,
  14440. const Identifier& property_,
  14441. UndoManager* const undoManager_)
  14442. : tree (tree_),
  14443. property (property_),
  14444. undoManager (undoManager_)
  14445. {
  14446. tree.addListener (this);
  14447. }
  14448. ~ValueTreePropertyValueSource()
  14449. {
  14450. tree.removeListener (this);
  14451. }
  14452. const var getValue() const
  14453. {
  14454. return tree [property];
  14455. }
  14456. void setValue (const var& newValue)
  14457. {
  14458. tree.setProperty (property, newValue, undoManager);
  14459. }
  14460. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14461. {
  14462. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14463. sendChangeMessage (false);
  14464. }
  14465. void valueTreeChildAdded (ValueTree&, ValueTree&) {}
  14466. void valueTreeChildRemoved (ValueTree&, ValueTree&) {}
  14467. void valueTreeChildOrderChanged (ValueTree&) {}
  14468. void valueTreeParentChanged (ValueTree&) {}
  14469. private:
  14470. ValueTree tree;
  14471. const Identifier property;
  14472. UndoManager* const undoManager;
  14473. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14474. };
  14475. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14476. {
  14477. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14478. }
  14479. int ValueTree::getNumChildren() const
  14480. {
  14481. return object == 0 ? 0 : object->children.size();
  14482. }
  14483. ValueTree ValueTree::getChild (int index) const
  14484. {
  14485. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14486. }
  14487. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14488. {
  14489. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14490. }
  14491. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14492. {
  14493. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14494. }
  14495. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14496. {
  14497. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14498. }
  14499. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14500. {
  14501. return object != 0 && object->isAChildOf (possibleParent.object);
  14502. }
  14503. int ValueTree::indexOf (const ValueTree& child) const
  14504. {
  14505. return object != 0 ? object->indexOf (child) : -1;
  14506. }
  14507. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14508. {
  14509. if (object != 0)
  14510. object->addChild (child.object, index, undoManager);
  14511. }
  14512. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14513. {
  14514. if (object != 0)
  14515. object->removeChild (childIndex, undoManager);
  14516. }
  14517. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14518. {
  14519. if (object != 0)
  14520. object->removeChild (object->children.indexOf (child.object), undoManager);
  14521. }
  14522. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14523. {
  14524. if (object != 0)
  14525. object->removeAllChildren (undoManager);
  14526. }
  14527. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14528. {
  14529. if (object != 0)
  14530. object->moveChild (currentIndex, newIndex, undoManager);
  14531. }
  14532. void ValueTree::addListener (Listener* listener)
  14533. {
  14534. if (listener != 0)
  14535. {
  14536. if (listeners.size() == 0 && object != 0)
  14537. object->valueTreesWithListeners.add (this);
  14538. listeners.add (listener);
  14539. }
  14540. }
  14541. void ValueTree::removeListener (Listener* listener)
  14542. {
  14543. listeners.remove (listener);
  14544. if (listeners.size() == 0 && object != 0)
  14545. object->valueTreesWithListeners.removeValue (this);
  14546. }
  14547. XmlElement* ValueTree::SharedObject::createXml() const
  14548. {
  14549. XmlElement* const xml = new XmlElement (type.toString());
  14550. properties.copyToXmlAttributes (*xml);
  14551. for (int i = 0; i < children.size(); ++i)
  14552. xml->addChildElement (children.getUnchecked(i)->createXml());
  14553. return xml;
  14554. }
  14555. XmlElement* ValueTree::createXml() const
  14556. {
  14557. return object != 0 ? object->createXml() : 0;
  14558. }
  14559. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14560. {
  14561. ValueTree v (xml.getTagName());
  14562. v.object->properties.setFromXmlAttributes (xml);
  14563. forEachXmlChildElement (xml, e)
  14564. v.addChild (fromXml (*e), -1, 0);
  14565. return v;
  14566. }
  14567. void ValueTree::writeToStream (OutputStream& output)
  14568. {
  14569. output.writeString (getType().toString());
  14570. const int numProps = getNumProperties();
  14571. output.writeCompressedInt (numProps);
  14572. int i;
  14573. for (i = 0; i < numProps; ++i)
  14574. {
  14575. const Identifier name (getPropertyName(i));
  14576. output.writeString (name.toString());
  14577. getProperty(name).writeToStream (output);
  14578. }
  14579. const int numChildren = getNumChildren();
  14580. output.writeCompressedInt (numChildren);
  14581. for (i = 0; i < numChildren; ++i)
  14582. getChild (i).writeToStream (output);
  14583. }
  14584. ValueTree ValueTree::readFromStream (InputStream& input)
  14585. {
  14586. const String type (input.readString());
  14587. if (type.isEmpty())
  14588. return ValueTree::invalid;
  14589. ValueTree v (type);
  14590. const int numProps = input.readCompressedInt();
  14591. if (numProps < 0)
  14592. {
  14593. jassertfalse; // trying to read corrupted data!
  14594. return v;
  14595. }
  14596. int i;
  14597. for (i = 0; i < numProps; ++i)
  14598. {
  14599. const String name (input.readString());
  14600. jassert (name.isNotEmpty());
  14601. const var value (var::readFromStream (input));
  14602. v.object->properties.set (name, value);
  14603. }
  14604. const int numChildren = input.readCompressedInt();
  14605. for (i = 0; i < numChildren; ++i)
  14606. {
  14607. ValueTree child (readFromStream (input));
  14608. v.object->children.add (child.object);
  14609. child.object->parent = v.object;
  14610. }
  14611. return v;
  14612. }
  14613. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  14614. {
  14615. MemoryInputStream in (data, numBytes, false);
  14616. return readFromStream (in);
  14617. }
  14618. END_JUCE_NAMESPACE
  14619. /*** End of inlined file: juce_ValueTree.cpp ***/
  14620. /*** Start of inlined file: juce_Value.cpp ***/
  14621. BEGIN_JUCE_NAMESPACE
  14622. Value::ValueSource::ValueSource()
  14623. {
  14624. }
  14625. Value::ValueSource::~ValueSource()
  14626. {
  14627. }
  14628. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  14629. {
  14630. if (synchronous)
  14631. {
  14632. for (int i = valuesWithListeners.size(); --i >= 0;)
  14633. {
  14634. Value* const v = valuesWithListeners[i];
  14635. if (v != 0)
  14636. v->callListeners();
  14637. }
  14638. }
  14639. else
  14640. {
  14641. triggerAsyncUpdate();
  14642. }
  14643. }
  14644. void Value::ValueSource::handleAsyncUpdate()
  14645. {
  14646. sendChangeMessage (true);
  14647. }
  14648. class SimpleValueSource : public Value::ValueSource
  14649. {
  14650. public:
  14651. SimpleValueSource()
  14652. {
  14653. }
  14654. SimpleValueSource (const var& initialValue)
  14655. : value (initialValue)
  14656. {
  14657. }
  14658. const var getValue() const
  14659. {
  14660. return value;
  14661. }
  14662. void setValue (const var& newValue)
  14663. {
  14664. if (! newValue.equalsWithSameType (value))
  14665. {
  14666. value = newValue;
  14667. sendChangeMessage (false);
  14668. }
  14669. }
  14670. private:
  14671. var value;
  14672. JUCE_DECLARE_NON_COPYABLE (SimpleValueSource);
  14673. };
  14674. Value::Value()
  14675. : value (new SimpleValueSource())
  14676. {
  14677. }
  14678. Value::Value (ValueSource* const value_)
  14679. : value (value_)
  14680. {
  14681. jassert (value_ != 0);
  14682. }
  14683. Value::Value (const var& initialValue)
  14684. : value (new SimpleValueSource (initialValue))
  14685. {
  14686. }
  14687. Value::Value (const Value& other)
  14688. : value (other.value)
  14689. {
  14690. }
  14691. Value& Value::operator= (const Value& other)
  14692. {
  14693. value = other.value;
  14694. return *this;
  14695. }
  14696. Value::~Value()
  14697. {
  14698. if (listeners.size() > 0)
  14699. value->valuesWithListeners.removeValue (this);
  14700. }
  14701. const var Value::getValue() const
  14702. {
  14703. return value->getValue();
  14704. }
  14705. Value::operator const var() const
  14706. {
  14707. return getValue();
  14708. }
  14709. void Value::setValue (const var& newValue)
  14710. {
  14711. value->setValue (newValue);
  14712. }
  14713. const String Value::toString() const
  14714. {
  14715. return value->getValue().toString();
  14716. }
  14717. Value& Value::operator= (const var& newValue)
  14718. {
  14719. value->setValue (newValue);
  14720. return *this;
  14721. }
  14722. void Value::referTo (const Value& valueToReferTo)
  14723. {
  14724. if (valueToReferTo.value != value)
  14725. {
  14726. if (listeners.size() > 0)
  14727. {
  14728. value->valuesWithListeners.removeValue (this);
  14729. valueToReferTo.value->valuesWithListeners.add (this);
  14730. }
  14731. value = valueToReferTo.value;
  14732. callListeners();
  14733. }
  14734. }
  14735. bool Value::refersToSameSourceAs (const Value& other) const
  14736. {
  14737. return value == other.value;
  14738. }
  14739. bool Value::operator== (const Value& other) const
  14740. {
  14741. return value == other.value || value->getValue() == other.getValue();
  14742. }
  14743. bool Value::operator!= (const Value& other) const
  14744. {
  14745. return value != other.value && value->getValue() != other.getValue();
  14746. }
  14747. void Value::addListener (ValueListener* const listener)
  14748. {
  14749. if (listener != 0)
  14750. {
  14751. if (listeners.size() == 0)
  14752. value->valuesWithListeners.add (this);
  14753. listeners.add (listener);
  14754. }
  14755. }
  14756. void Value::removeListener (ValueListener* const listener)
  14757. {
  14758. listeners.remove (listener);
  14759. if (listeners.size() == 0)
  14760. value->valuesWithListeners.removeValue (this);
  14761. }
  14762. void Value::callListeners()
  14763. {
  14764. Value v (*this); // (create a copy in case this gets deleted by a callback)
  14765. listeners.call (&ValueListener::valueChanged, v);
  14766. }
  14767. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  14768. {
  14769. return stream << value.toString();
  14770. }
  14771. END_JUCE_NAMESPACE
  14772. /*** End of inlined file: juce_Value.cpp ***/
  14773. /*** Start of inlined file: juce_Application.cpp ***/
  14774. BEGIN_JUCE_NAMESPACE
  14775. #if JUCE_MAC
  14776. extern void juce_initialiseMacMainMenu();
  14777. #endif
  14778. JUCEApplication::JUCEApplication()
  14779. : appReturnValue (0),
  14780. stillInitialising (true)
  14781. {
  14782. jassert (isStandaloneApp() && appInstance == 0);
  14783. appInstance = this;
  14784. }
  14785. JUCEApplication::~JUCEApplication()
  14786. {
  14787. if (appLock != 0)
  14788. {
  14789. appLock->exit();
  14790. appLock = 0;
  14791. }
  14792. jassert (appInstance == this);
  14793. appInstance = 0;
  14794. }
  14795. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  14796. JUCEApplication* JUCEApplication::appInstance = 0;
  14797. bool JUCEApplication::moreThanOneInstanceAllowed()
  14798. {
  14799. return true;
  14800. }
  14801. void JUCEApplication::anotherInstanceStarted (const String&)
  14802. {
  14803. }
  14804. void JUCEApplication::systemRequestedQuit()
  14805. {
  14806. quit();
  14807. }
  14808. void JUCEApplication::quit()
  14809. {
  14810. MessageManager::getInstance()->stopDispatchLoop();
  14811. }
  14812. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  14813. {
  14814. appReturnValue = newReturnValue;
  14815. }
  14816. void JUCEApplication::actionListenerCallback (const String& message)
  14817. {
  14818. if (message.startsWith (getApplicationName() + "/"))
  14819. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  14820. }
  14821. void JUCEApplication::unhandledException (const std::exception*,
  14822. const String&,
  14823. const int)
  14824. {
  14825. jassertfalse;
  14826. }
  14827. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  14828. const char* const sourceFile,
  14829. const int lineNumber)
  14830. {
  14831. if (appInstance != 0)
  14832. appInstance->unhandledException (e, sourceFile, lineNumber);
  14833. }
  14834. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  14835. {
  14836. return 0;
  14837. }
  14838. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  14839. {
  14840. commands.add (StandardApplicationCommandIDs::quit);
  14841. }
  14842. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  14843. {
  14844. if (commandID == StandardApplicationCommandIDs::quit)
  14845. {
  14846. result.setInfo (TRANS("Quit"),
  14847. TRANS("Quits the application"),
  14848. "Application",
  14849. 0);
  14850. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  14851. }
  14852. }
  14853. bool JUCEApplication::perform (const InvocationInfo& info)
  14854. {
  14855. if (info.commandID == StandardApplicationCommandIDs::quit)
  14856. {
  14857. systemRequestedQuit();
  14858. return true;
  14859. }
  14860. return false;
  14861. }
  14862. bool JUCEApplication::initialiseApp (const String& commandLine)
  14863. {
  14864. commandLineParameters = commandLine.trim();
  14865. #if ! JUCE_IOS
  14866. jassert (appLock == 0); // initialiseApp must only be called once!
  14867. if (! moreThanOneInstanceAllowed())
  14868. {
  14869. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  14870. if (! appLock->enter(0))
  14871. {
  14872. appLock = 0;
  14873. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  14874. DBG ("Another instance is running - quitting...");
  14875. return false;
  14876. }
  14877. }
  14878. #endif
  14879. // let the app do its setting-up..
  14880. initialise (commandLineParameters);
  14881. #if JUCE_MAC
  14882. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  14883. #endif
  14884. // register for broadcast new app messages
  14885. MessageManager::getInstance()->registerBroadcastListener (this);
  14886. stillInitialising = false;
  14887. return true;
  14888. }
  14889. int JUCEApplication::shutdownApp()
  14890. {
  14891. jassert (appInstance == this);
  14892. MessageManager::getInstance()->deregisterBroadcastListener (this);
  14893. JUCE_TRY
  14894. {
  14895. // give the app a chance to clean up..
  14896. shutdown();
  14897. }
  14898. JUCE_CATCH_EXCEPTION
  14899. return getApplicationReturnValue();
  14900. }
  14901. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  14902. void JUCEApplication::appWillTerminateByForce()
  14903. {
  14904. {
  14905. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  14906. if (app != 0)
  14907. app->shutdownApp();
  14908. }
  14909. shutdownJuce_GUI();
  14910. }
  14911. int JUCEApplication::main (const String& commandLine)
  14912. {
  14913. ScopedJuceInitialiser_GUI libraryInitialiser;
  14914. jassert (createInstance != 0);
  14915. int returnCode = 0;
  14916. {
  14917. const ScopedPointer<JUCEApplication> app (createInstance());
  14918. if (! app->initialiseApp (commandLine))
  14919. return 0;
  14920. JUCE_TRY
  14921. {
  14922. // loop until a quit message is received..
  14923. MessageManager::getInstance()->runDispatchLoop();
  14924. }
  14925. JUCE_CATCH_EXCEPTION
  14926. returnCode = app->shutdownApp();
  14927. }
  14928. return returnCode;
  14929. }
  14930. #if JUCE_IOS
  14931. extern int juce_iOSMain (int argc, const char* argv[]);
  14932. #endif
  14933. #if ! JUCE_WINDOWS
  14934. extern const char* juce_Argv0;
  14935. #endif
  14936. int JUCEApplication::main (int argc, const char* argv[])
  14937. {
  14938. JUCE_AUTORELEASEPOOL
  14939. #if ! JUCE_WINDOWS
  14940. jassert (createInstance != 0);
  14941. juce_Argv0 = argv[0];
  14942. #endif
  14943. #if JUCE_IOS
  14944. return juce_iOSMain (argc, argv);
  14945. #else
  14946. String cmd;
  14947. for (int i = 1; i < argc; ++i)
  14948. cmd << argv[i] << ' ';
  14949. return JUCEApplication::main (cmd);
  14950. #endif
  14951. }
  14952. END_JUCE_NAMESPACE
  14953. /*** End of inlined file: juce_Application.cpp ***/
  14954. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14955. BEGIN_JUCE_NAMESPACE
  14956. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  14957. : commandID (commandID_),
  14958. flags (0)
  14959. {
  14960. }
  14961. void ApplicationCommandInfo::setInfo (const String& shortName_,
  14962. const String& description_,
  14963. const String& categoryName_,
  14964. const int flags_) throw()
  14965. {
  14966. shortName = shortName_;
  14967. description = description_;
  14968. categoryName = categoryName_;
  14969. flags = flags_;
  14970. }
  14971. void ApplicationCommandInfo::setActive (const bool b) throw()
  14972. {
  14973. if (b)
  14974. flags &= ~isDisabled;
  14975. else
  14976. flags |= isDisabled;
  14977. }
  14978. void ApplicationCommandInfo::setTicked (const bool b) throw()
  14979. {
  14980. if (b)
  14981. flags |= isTicked;
  14982. else
  14983. flags &= ~isTicked;
  14984. }
  14985. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  14986. {
  14987. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  14988. }
  14989. END_JUCE_NAMESPACE
  14990. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  14991. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  14992. BEGIN_JUCE_NAMESPACE
  14993. ApplicationCommandManager::ApplicationCommandManager()
  14994. : firstTarget (0)
  14995. {
  14996. keyMappings = new KeyPressMappingSet (this);
  14997. Desktop::getInstance().addFocusChangeListener (this);
  14998. }
  14999. ApplicationCommandManager::~ApplicationCommandManager()
  15000. {
  15001. Desktop::getInstance().removeFocusChangeListener (this);
  15002. keyMappings = 0;
  15003. }
  15004. void ApplicationCommandManager::clearCommands()
  15005. {
  15006. commands.clear();
  15007. keyMappings->clearAllKeyPresses();
  15008. triggerAsyncUpdate();
  15009. }
  15010. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15011. {
  15012. // zero isn't a valid command ID!
  15013. jassert (newCommand.commandID != 0);
  15014. // the name isn't optional!
  15015. jassert (newCommand.shortName.isNotEmpty());
  15016. if (getCommandForID (newCommand.commandID) == 0)
  15017. {
  15018. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15019. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15020. commands.add (newInfo);
  15021. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15022. triggerAsyncUpdate();
  15023. }
  15024. else
  15025. {
  15026. // trying to re-register the same command with different parameters?
  15027. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15028. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15029. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15030. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15031. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15032. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15033. }
  15034. }
  15035. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15036. {
  15037. if (target != 0)
  15038. {
  15039. Array <CommandID> commandIDs;
  15040. target->getAllCommands (commandIDs);
  15041. for (int i = 0; i < commandIDs.size(); ++i)
  15042. {
  15043. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15044. target->getCommandInfo (info.commandID, info);
  15045. registerCommand (info);
  15046. }
  15047. }
  15048. }
  15049. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15050. {
  15051. for (int i = commands.size(); --i >= 0;)
  15052. {
  15053. if (commands.getUnchecked (i)->commandID == commandID)
  15054. {
  15055. commands.remove (i);
  15056. triggerAsyncUpdate();
  15057. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15058. for (int j = keys.size(); --j >= 0;)
  15059. keyMappings->removeKeyPress (keys.getReference (j));
  15060. }
  15061. }
  15062. }
  15063. void ApplicationCommandManager::commandStatusChanged()
  15064. {
  15065. triggerAsyncUpdate();
  15066. }
  15067. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15068. {
  15069. for (int i = commands.size(); --i >= 0;)
  15070. if (commands.getUnchecked(i)->commandID == commandID)
  15071. return commands.getUnchecked(i);
  15072. return 0;
  15073. }
  15074. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15075. {
  15076. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15077. return (ci != 0) ? ci->shortName : String::empty;
  15078. }
  15079. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15080. {
  15081. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15082. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15083. : String::empty;
  15084. }
  15085. const StringArray ApplicationCommandManager::getCommandCategories() const
  15086. {
  15087. StringArray s;
  15088. for (int i = 0; i < commands.size(); ++i)
  15089. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15090. return s;
  15091. }
  15092. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15093. {
  15094. Array <CommandID> results;
  15095. for (int i = 0; i < commands.size(); ++i)
  15096. if (commands.getUnchecked(i)->categoryName == categoryName)
  15097. results.add (commands.getUnchecked(i)->commandID);
  15098. return results;
  15099. }
  15100. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15101. {
  15102. ApplicationCommandTarget::InvocationInfo info (commandID);
  15103. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15104. return invoke (info, asynchronously);
  15105. }
  15106. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15107. {
  15108. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15109. // manager first..
  15110. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15111. ApplicationCommandInfo commandInfo (0);
  15112. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15113. if (target == 0)
  15114. return false;
  15115. ApplicationCommandTarget::InvocationInfo info (info_);
  15116. info.commandFlags = commandInfo.flags;
  15117. sendListenerInvokeCallback (info);
  15118. const bool ok = target->invoke (info, asynchronously);
  15119. commandStatusChanged();
  15120. return ok;
  15121. }
  15122. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15123. {
  15124. return firstTarget != 0 ? firstTarget
  15125. : findDefaultComponentTarget();
  15126. }
  15127. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15128. {
  15129. firstTarget = newTarget;
  15130. }
  15131. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15132. ApplicationCommandInfo& upToDateInfo)
  15133. {
  15134. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15135. if (target == 0)
  15136. target = JUCEApplication::getInstance();
  15137. if (target != 0)
  15138. target = target->getTargetForCommand (commandID);
  15139. if (target != 0)
  15140. target->getCommandInfo (commandID, upToDateInfo);
  15141. return target;
  15142. }
  15143. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15144. {
  15145. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15146. if (target == 0 && c != 0)
  15147. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15148. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15149. return target;
  15150. }
  15151. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15152. {
  15153. Component* c = Component::getCurrentlyFocusedComponent();
  15154. if (c == 0)
  15155. {
  15156. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15157. if (activeWindow != 0)
  15158. {
  15159. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15160. if (c == 0)
  15161. c = activeWindow;
  15162. }
  15163. }
  15164. if (c == 0 && Process::isForegroundProcess())
  15165. {
  15166. // getting a bit desperate now - try all desktop comps..
  15167. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15168. {
  15169. ApplicationCommandTarget* const target
  15170. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15171. ->getPeer()->getLastFocusedSubcomponent());
  15172. if (target != 0)
  15173. return target;
  15174. }
  15175. }
  15176. if (c != 0)
  15177. {
  15178. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15179. // if we're focused on a ResizableWindow, chances are that it's the content
  15180. // component that really should get the event. And if not, the event will
  15181. // still be passed up to the top level window anyway, so let's send it to the
  15182. // content comp.
  15183. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15184. c = resizableWindow->getContentComponent();
  15185. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15186. if (target != 0)
  15187. return target;
  15188. }
  15189. return JUCEApplication::getInstance();
  15190. }
  15191. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15192. {
  15193. listeners.add (listener);
  15194. }
  15195. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15196. {
  15197. listeners.remove (listener);
  15198. }
  15199. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15200. {
  15201. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15202. }
  15203. void ApplicationCommandManager::handleAsyncUpdate()
  15204. {
  15205. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15206. }
  15207. void ApplicationCommandManager::globalFocusChanged (Component*)
  15208. {
  15209. commandStatusChanged();
  15210. }
  15211. END_JUCE_NAMESPACE
  15212. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15213. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15214. BEGIN_JUCE_NAMESPACE
  15215. ApplicationCommandTarget::ApplicationCommandTarget()
  15216. {
  15217. }
  15218. ApplicationCommandTarget::~ApplicationCommandTarget()
  15219. {
  15220. messageInvoker = 0;
  15221. }
  15222. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15223. {
  15224. if (isCommandActive (info.commandID))
  15225. {
  15226. if (async)
  15227. {
  15228. if (messageInvoker == 0)
  15229. messageInvoker = new CommandTargetMessageInvoker (this);
  15230. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15231. return true;
  15232. }
  15233. else
  15234. {
  15235. const bool success = perform (info);
  15236. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15237. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15238. // returns the command's info.
  15239. return success;
  15240. }
  15241. }
  15242. return false;
  15243. }
  15244. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15245. {
  15246. Component* c = dynamic_cast <Component*> (this);
  15247. if (c != 0)
  15248. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15249. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15250. return 0;
  15251. }
  15252. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15253. {
  15254. ApplicationCommandTarget* target = this;
  15255. int depth = 0;
  15256. while (target != 0)
  15257. {
  15258. Array <CommandID> commandIDs;
  15259. target->getAllCommands (commandIDs);
  15260. if (commandIDs.contains (commandID))
  15261. return target;
  15262. target = target->getNextCommandTarget();
  15263. ++depth;
  15264. jassert (depth < 100); // could be a recursive command chain??
  15265. jassert (target != this); // definitely a recursive command chain!
  15266. if (depth > 100 || target == this)
  15267. break;
  15268. }
  15269. if (target == 0)
  15270. {
  15271. target = JUCEApplication::getInstance();
  15272. if (target != 0)
  15273. {
  15274. Array <CommandID> commandIDs;
  15275. target->getAllCommands (commandIDs);
  15276. if (commandIDs.contains (commandID))
  15277. return target;
  15278. }
  15279. }
  15280. return 0;
  15281. }
  15282. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15283. {
  15284. ApplicationCommandInfo info (commandID);
  15285. info.flags = ApplicationCommandInfo::isDisabled;
  15286. getCommandInfo (commandID, info);
  15287. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15288. }
  15289. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15290. {
  15291. ApplicationCommandTarget* target = this;
  15292. int depth = 0;
  15293. while (target != 0)
  15294. {
  15295. if (target->tryToInvoke (info, async))
  15296. return true;
  15297. target = target->getNextCommandTarget();
  15298. ++depth;
  15299. jassert (depth < 100); // could be a recursive command chain??
  15300. jassert (target != this); // definitely a recursive command chain!
  15301. if (depth > 100 || target == this)
  15302. break;
  15303. }
  15304. if (target == 0)
  15305. {
  15306. target = JUCEApplication::getInstance();
  15307. if (target != 0)
  15308. return target->tryToInvoke (info, async);
  15309. }
  15310. return false;
  15311. }
  15312. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15313. {
  15314. ApplicationCommandTarget::InvocationInfo info (commandID);
  15315. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15316. return invoke (info, asynchronously);
  15317. }
  15318. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15319. : commandID (commandID_),
  15320. commandFlags (0),
  15321. invocationMethod (direct),
  15322. originatingComponent (0),
  15323. isKeyDown (false),
  15324. millisecsSinceKeyPressed (0)
  15325. {
  15326. }
  15327. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15328. : owner (owner_)
  15329. {
  15330. }
  15331. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15332. {
  15333. }
  15334. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15335. {
  15336. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15337. owner->tryToInvoke (*info, false);
  15338. }
  15339. END_JUCE_NAMESPACE
  15340. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15341. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15342. BEGIN_JUCE_NAMESPACE
  15343. juce_ImplementSingleton (ApplicationProperties)
  15344. ApplicationProperties::ApplicationProperties()
  15345. : msBeforeSaving (3000),
  15346. options (PropertiesFile::storeAsBinary),
  15347. commonSettingsAreReadOnly (0),
  15348. processLock (0)
  15349. {
  15350. }
  15351. ApplicationProperties::~ApplicationProperties()
  15352. {
  15353. closeFiles();
  15354. clearSingletonInstance();
  15355. }
  15356. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15357. const String& fileNameSuffix,
  15358. const String& folderName_,
  15359. const int millisecondsBeforeSaving,
  15360. const int propertiesFileOptions,
  15361. InterProcessLock* processLock_)
  15362. {
  15363. appName = applicationName;
  15364. fileSuffix = fileNameSuffix;
  15365. folderName = folderName_;
  15366. msBeforeSaving = millisecondsBeforeSaving;
  15367. options = propertiesFileOptions;
  15368. processLock = processLock_;
  15369. }
  15370. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15371. const bool testCommonSettings,
  15372. const bool showWarningDialogOnFailure)
  15373. {
  15374. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15375. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15376. if (! (userOk && commonOk))
  15377. {
  15378. if (showWarningDialogOnFailure)
  15379. {
  15380. String filenames;
  15381. if (userProps != 0 && ! userOk)
  15382. filenames << '\n' << userProps->getFile().getFullPathName();
  15383. if (commonProps != 0 && ! commonOk)
  15384. filenames << '\n' << commonProps->getFile().getFullPathName();
  15385. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15386. appName + TRANS(" - Unable to save settings"),
  15387. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15388. + appName + TRANS(" needs to be able to write to the following files:\n")
  15389. + filenames
  15390. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15391. }
  15392. return false;
  15393. }
  15394. return true;
  15395. }
  15396. void ApplicationProperties::openFiles()
  15397. {
  15398. // You need to call setStorageParameters() before trying to get hold of the
  15399. // properties!
  15400. jassert (appName.isNotEmpty());
  15401. if (appName.isNotEmpty())
  15402. {
  15403. if (userProps == 0)
  15404. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15405. false, msBeforeSaving, options, processLock);
  15406. if (commonProps == 0)
  15407. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15408. true, msBeforeSaving, options, processLock);
  15409. userProps->setFallbackPropertySet (commonProps);
  15410. }
  15411. }
  15412. PropertiesFile* ApplicationProperties::getUserSettings()
  15413. {
  15414. if (userProps == 0)
  15415. openFiles();
  15416. return userProps;
  15417. }
  15418. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15419. {
  15420. if (commonProps == 0)
  15421. openFiles();
  15422. if (returnUserPropsIfReadOnly)
  15423. {
  15424. if (commonSettingsAreReadOnly == 0)
  15425. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15426. if (commonSettingsAreReadOnly > 0)
  15427. return userProps;
  15428. }
  15429. return commonProps;
  15430. }
  15431. bool ApplicationProperties::saveIfNeeded()
  15432. {
  15433. return (userProps == 0 || userProps->saveIfNeeded())
  15434. && (commonProps == 0 || commonProps->saveIfNeeded());
  15435. }
  15436. void ApplicationProperties::closeFiles()
  15437. {
  15438. userProps = 0;
  15439. commonProps = 0;
  15440. }
  15441. END_JUCE_NAMESPACE
  15442. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15443. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15444. BEGIN_JUCE_NAMESPACE
  15445. namespace PropertyFileConstants
  15446. {
  15447. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15448. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15449. static const char* const fileTag = "PROPERTIES";
  15450. static const char* const valueTag = "VALUE";
  15451. static const char* const nameAttribute = "name";
  15452. static const char* const valueAttribute = "val";
  15453. }
  15454. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15455. const int options_, InterProcessLock* const processLock_)
  15456. : PropertySet (ignoreCaseOfKeyNames),
  15457. file (f),
  15458. timerInterval (millisecondsBeforeSaving),
  15459. options (options_),
  15460. loadedOk (false),
  15461. needsWriting (false),
  15462. processLock (processLock_)
  15463. {
  15464. // You need to correctly specify just one storage format for the file
  15465. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15466. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15467. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15468. ProcessScopedLock pl (createProcessLock());
  15469. if (pl != 0 && ! pl->isLocked())
  15470. return; // locking failure..
  15471. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15472. if (fileStream != 0)
  15473. {
  15474. int magicNumber = fileStream->readInt();
  15475. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15476. {
  15477. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15478. magicNumber = PropertyFileConstants::magicNumber;
  15479. }
  15480. if (magicNumber == PropertyFileConstants::magicNumber)
  15481. {
  15482. loadedOk = true;
  15483. BufferedInputStream in (fileStream.release(), 2048, true);
  15484. int numValues = in.readInt();
  15485. while (--numValues >= 0 && ! in.isExhausted())
  15486. {
  15487. const String key (in.readString());
  15488. const String value (in.readString());
  15489. jassert (key.isNotEmpty());
  15490. if (key.isNotEmpty())
  15491. getAllProperties().set (key, value);
  15492. }
  15493. }
  15494. else
  15495. {
  15496. // Not a binary props file - let's see if it's XML..
  15497. fileStream = 0;
  15498. XmlDocument parser (f);
  15499. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15500. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15501. {
  15502. doc = parser.getDocumentElement();
  15503. if (doc != 0)
  15504. {
  15505. loadedOk = true;
  15506. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15507. {
  15508. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15509. if (name.isNotEmpty())
  15510. {
  15511. getAllProperties().set (name,
  15512. e->getFirstChildElement() != 0
  15513. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15514. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15515. }
  15516. }
  15517. }
  15518. else
  15519. {
  15520. // must be a pretty broken XML file we're trying to parse here,
  15521. // or a sign that this object needs an InterProcessLock,
  15522. // or just a failure reading the file. This last reason is why
  15523. // we don't jassertfalse here.
  15524. }
  15525. }
  15526. }
  15527. }
  15528. else
  15529. {
  15530. loadedOk = ! f.exists();
  15531. }
  15532. }
  15533. PropertiesFile::~PropertiesFile()
  15534. {
  15535. if (! saveIfNeeded())
  15536. jassertfalse;
  15537. }
  15538. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15539. {
  15540. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15541. }
  15542. bool PropertiesFile::saveIfNeeded()
  15543. {
  15544. const ScopedLock sl (getLock());
  15545. return (! needsWriting) || save();
  15546. }
  15547. bool PropertiesFile::needsToBeSaved() const
  15548. {
  15549. const ScopedLock sl (getLock());
  15550. return needsWriting;
  15551. }
  15552. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15553. {
  15554. const ScopedLock sl (getLock());
  15555. needsWriting = needsToBeSaved_;
  15556. }
  15557. bool PropertiesFile::save()
  15558. {
  15559. const ScopedLock sl (getLock());
  15560. stopTimer();
  15561. if (file == File::nonexistent
  15562. || file.isDirectory()
  15563. || ! file.getParentDirectory().createDirectory())
  15564. return false;
  15565. if ((options & storeAsXML) != 0)
  15566. {
  15567. XmlElement doc (PropertyFileConstants::fileTag);
  15568. for (int i = 0; i < getAllProperties().size(); ++i)
  15569. {
  15570. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  15571. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  15572. // if the value seems to contain xml, store it as such..
  15573. XmlElement* const childElement = XmlDocument::parse (getAllProperties().getAllValues() [i]);
  15574. if (childElement != 0)
  15575. e->addChildElement (childElement);
  15576. else
  15577. e->setAttribute (PropertyFileConstants::valueAttribute,
  15578. getAllProperties().getAllValues() [i]);
  15579. }
  15580. ProcessScopedLock pl (createProcessLock());
  15581. if (pl != 0 && ! pl->isLocked())
  15582. return false; // locking failure..
  15583. if (doc.writeToFile (file, String::empty))
  15584. {
  15585. needsWriting = false;
  15586. return true;
  15587. }
  15588. }
  15589. else
  15590. {
  15591. ProcessScopedLock pl (createProcessLock());
  15592. if (pl != 0 && ! pl->isLocked())
  15593. return false; // locking failure..
  15594. TemporaryFile tempFile (file);
  15595. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  15596. if (out != 0)
  15597. {
  15598. if ((options & storeAsCompressedBinary) != 0)
  15599. {
  15600. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  15601. out->flush();
  15602. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  15603. }
  15604. else
  15605. {
  15606. // have you set up the storage option flags correctly?
  15607. jassert ((options & storeAsBinary) != 0);
  15608. out->writeInt (PropertyFileConstants::magicNumber);
  15609. }
  15610. const int numProperties = getAllProperties().size();
  15611. out->writeInt (numProperties);
  15612. for (int i = 0; i < numProperties; ++i)
  15613. {
  15614. out->writeString (getAllProperties().getAllKeys() [i]);
  15615. out->writeString (getAllProperties().getAllValues() [i]);
  15616. }
  15617. out = 0;
  15618. if (tempFile.overwriteTargetFileWithTemporary())
  15619. {
  15620. needsWriting = false;
  15621. return true;
  15622. }
  15623. }
  15624. }
  15625. return false;
  15626. }
  15627. void PropertiesFile::timerCallback()
  15628. {
  15629. saveIfNeeded();
  15630. }
  15631. void PropertiesFile::propertyChanged()
  15632. {
  15633. sendChangeMessage();
  15634. needsWriting = true;
  15635. if (timerInterval > 0)
  15636. startTimer (timerInterval);
  15637. else if (timerInterval == 0)
  15638. saveIfNeeded();
  15639. }
  15640. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  15641. const String& fileNameSuffix,
  15642. const String& folderName,
  15643. const bool commonToAllUsers)
  15644. {
  15645. // mustn't have illegal characters in this name..
  15646. jassert (applicationName == File::createLegalFileName (applicationName));
  15647. #if JUCE_MAC || JUCE_IOS
  15648. File dir (commonToAllUsers ? "/Library/Preferences"
  15649. : "~/Library/Preferences");
  15650. if (folderName.isNotEmpty())
  15651. dir = dir.getChildFile (folderName);
  15652. #elif JUCE_LINUX || JUCE_ANDROID
  15653. const File dir ((commonToAllUsers ? "/var/" : "~/")
  15654. + (folderName.isNotEmpty() ? folderName
  15655. : ("." + applicationName)));
  15656. #elif JUCE_WINDOWS
  15657. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  15658. : File::userApplicationDataDirectory));
  15659. if (dir == File::nonexistent)
  15660. return File::nonexistent;
  15661. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  15662. : applicationName);
  15663. #endif
  15664. return dir.getChildFile (applicationName)
  15665. .withFileExtension (fileNameSuffix);
  15666. }
  15667. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  15668. const String& fileNameSuffix,
  15669. const String& folderName,
  15670. const bool commonToAllUsers,
  15671. const int millisecondsBeforeSaving,
  15672. const int propertiesFileOptions,
  15673. InterProcessLock* processLock_)
  15674. {
  15675. const File file (getDefaultAppSettingsFile (applicationName,
  15676. fileNameSuffix,
  15677. folderName,
  15678. commonToAllUsers));
  15679. jassert (file != File::nonexistent);
  15680. if (file == File::nonexistent)
  15681. return 0;
  15682. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  15683. }
  15684. END_JUCE_NAMESPACE
  15685. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  15686. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  15687. BEGIN_JUCE_NAMESPACE
  15688. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  15689. const String& fileWildcard_,
  15690. const String& openFileDialogTitle_,
  15691. const String& saveFileDialogTitle_)
  15692. : changedSinceSave (false),
  15693. fileExtension (fileExtension_),
  15694. fileWildcard (fileWildcard_),
  15695. openFileDialogTitle (openFileDialogTitle_),
  15696. saveFileDialogTitle (saveFileDialogTitle_)
  15697. {
  15698. }
  15699. FileBasedDocument::~FileBasedDocument()
  15700. {
  15701. }
  15702. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  15703. {
  15704. if (changedSinceSave != hasChanged)
  15705. {
  15706. changedSinceSave = hasChanged;
  15707. sendChangeMessage();
  15708. }
  15709. }
  15710. void FileBasedDocument::changed()
  15711. {
  15712. changedSinceSave = true;
  15713. sendChangeMessage();
  15714. }
  15715. void FileBasedDocument::setFile (const File& newFile)
  15716. {
  15717. if (documentFile != newFile)
  15718. {
  15719. documentFile = newFile;
  15720. changed();
  15721. }
  15722. }
  15723. bool FileBasedDocument::loadFrom (const File& newFile,
  15724. const bool showMessageOnFailure)
  15725. {
  15726. MouseCursor::showWaitCursor();
  15727. const File oldFile (documentFile);
  15728. documentFile = newFile;
  15729. String error;
  15730. if (newFile.existsAsFile())
  15731. {
  15732. error = loadDocument (newFile);
  15733. if (error.isEmpty())
  15734. {
  15735. setChangedFlag (false);
  15736. MouseCursor::hideWaitCursor();
  15737. setLastDocumentOpened (newFile);
  15738. return true;
  15739. }
  15740. }
  15741. else
  15742. {
  15743. error = "The file doesn't exist";
  15744. }
  15745. documentFile = oldFile;
  15746. MouseCursor::hideWaitCursor();
  15747. if (showMessageOnFailure)
  15748. {
  15749. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15750. TRANS("Failed to open file..."),
  15751. TRANS("There was an error while trying to load the file:\n\n")
  15752. + newFile.getFullPathName()
  15753. + "\n\n"
  15754. + error);
  15755. }
  15756. return false;
  15757. }
  15758. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  15759. {
  15760. FileChooser fc (openFileDialogTitle,
  15761. getLastDocumentOpened(),
  15762. fileWildcard);
  15763. if (fc.browseForFileToOpen())
  15764. return loadFrom (fc.getResult(), showMessageOnFailure);
  15765. return false;
  15766. }
  15767. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  15768. const bool showMessageOnFailure)
  15769. {
  15770. return saveAs (documentFile,
  15771. false,
  15772. askUserForFileIfNotSpecified,
  15773. showMessageOnFailure);
  15774. }
  15775. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  15776. const bool warnAboutOverwritingExistingFiles,
  15777. const bool askUserForFileIfNotSpecified,
  15778. const bool showMessageOnFailure)
  15779. {
  15780. if (newFile == File::nonexistent)
  15781. {
  15782. if (askUserForFileIfNotSpecified)
  15783. {
  15784. return saveAsInteractive (true);
  15785. }
  15786. else
  15787. {
  15788. // can't save to an unspecified file
  15789. jassertfalse;
  15790. return failedToWriteToFile;
  15791. }
  15792. }
  15793. if (warnAboutOverwritingExistingFiles && newFile.exists())
  15794. {
  15795. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15796. TRANS("File already exists"),
  15797. TRANS("There's already a file called:\n\n")
  15798. + newFile.getFullPathName()
  15799. + TRANS("\n\nAre you sure you want to overwrite it?"),
  15800. TRANS("overwrite"),
  15801. TRANS("cancel")))
  15802. {
  15803. return userCancelledSave;
  15804. }
  15805. }
  15806. MouseCursor::showWaitCursor();
  15807. const File oldFile (documentFile);
  15808. documentFile = newFile;
  15809. String error (saveDocument (newFile));
  15810. if (error.isEmpty())
  15811. {
  15812. setChangedFlag (false);
  15813. MouseCursor::hideWaitCursor();
  15814. return savedOk;
  15815. }
  15816. documentFile = oldFile;
  15817. MouseCursor::hideWaitCursor();
  15818. if (showMessageOnFailure)
  15819. {
  15820. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15821. TRANS("Error writing to file..."),
  15822. TRANS("An error occurred while trying to save \"")
  15823. + getDocumentTitle()
  15824. + TRANS("\" to the file:\n\n")
  15825. + newFile.getFullPathName()
  15826. + "\n\n"
  15827. + error);
  15828. }
  15829. return failedToWriteToFile;
  15830. }
  15831. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  15832. {
  15833. if (! hasChangedSinceSaved())
  15834. return savedOk;
  15835. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  15836. TRANS("Closing document..."),
  15837. TRANS("Do you want to save the changes to \"")
  15838. + getDocumentTitle() + "\"?",
  15839. TRANS("save"),
  15840. TRANS("discard changes"),
  15841. TRANS("cancel"));
  15842. if (r == 1)
  15843. {
  15844. // save changes
  15845. return save (true, true);
  15846. }
  15847. else if (r == 2)
  15848. {
  15849. // discard changes
  15850. return savedOk;
  15851. }
  15852. return userCancelledSave;
  15853. }
  15854. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  15855. {
  15856. File f;
  15857. if (documentFile.existsAsFile())
  15858. f = documentFile;
  15859. else
  15860. f = getLastDocumentOpened();
  15861. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  15862. if (legalFilename.isEmpty())
  15863. legalFilename = "unnamed";
  15864. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  15865. f = f.getSiblingFile (legalFilename);
  15866. else
  15867. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  15868. f = f.withFileExtension (fileExtension)
  15869. .getNonexistentSibling (true);
  15870. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  15871. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  15872. {
  15873. File chosen (fc.getResult());
  15874. if (chosen.getFileExtension().isEmpty())
  15875. {
  15876. chosen = chosen.withFileExtension (fileExtension);
  15877. if (chosen.exists())
  15878. {
  15879. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  15880. TRANS("File already exists"),
  15881. TRANS("There's already a file called:")
  15882. + "\n\n" + chosen.getFullPathName()
  15883. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  15884. TRANS("overwrite"),
  15885. TRANS("cancel")))
  15886. {
  15887. return userCancelledSave;
  15888. }
  15889. }
  15890. }
  15891. setLastDocumentOpened (chosen);
  15892. return saveAs (chosen, false, false, true);
  15893. }
  15894. return userCancelledSave;
  15895. }
  15896. END_JUCE_NAMESPACE
  15897. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  15898. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15899. BEGIN_JUCE_NAMESPACE
  15900. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  15901. : maxNumberOfItems (10)
  15902. {
  15903. }
  15904. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  15905. {
  15906. }
  15907. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  15908. {
  15909. maxNumberOfItems = jmax (1, newMaxNumber);
  15910. while (getNumFiles() > maxNumberOfItems)
  15911. files.remove (getNumFiles() - 1);
  15912. }
  15913. int RecentlyOpenedFilesList::getNumFiles() const
  15914. {
  15915. return files.size();
  15916. }
  15917. const File RecentlyOpenedFilesList::getFile (const int index) const
  15918. {
  15919. return File (files [index]);
  15920. }
  15921. void RecentlyOpenedFilesList::clear()
  15922. {
  15923. files.clear();
  15924. }
  15925. void RecentlyOpenedFilesList::addFile (const File& file)
  15926. {
  15927. const String path (file.getFullPathName());
  15928. files.removeString (path, true);
  15929. files.insert (0, path);
  15930. setMaxNumberOfItems (maxNumberOfItems);
  15931. }
  15932. void RecentlyOpenedFilesList::removeNonExistentFiles()
  15933. {
  15934. for (int i = getNumFiles(); --i >= 0;)
  15935. if (! getFile(i).exists())
  15936. files.remove (i);
  15937. }
  15938. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  15939. const int baseItemId,
  15940. const bool showFullPaths,
  15941. const bool dontAddNonExistentFiles,
  15942. const File** filesToAvoid)
  15943. {
  15944. int num = 0;
  15945. for (int i = 0; i < getNumFiles(); ++i)
  15946. {
  15947. const File f (getFile(i));
  15948. if ((! dontAddNonExistentFiles) || f.exists())
  15949. {
  15950. bool needsAvoiding = false;
  15951. if (filesToAvoid != 0)
  15952. {
  15953. const File** avoid = filesToAvoid;
  15954. while (*avoid != 0)
  15955. {
  15956. if (f == **avoid)
  15957. {
  15958. needsAvoiding = true;
  15959. break;
  15960. }
  15961. ++avoid;
  15962. }
  15963. }
  15964. if (! needsAvoiding)
  15965. {
  15966. menuToAddTo.addItem (baseItemId + i,
  15967. showFullPaths ? f.getFullPathName()
  15968. : f.getFileName());
  15969. ++num;
  15970. }
  15971. }
  15972. }
  15973. return num;
  15974. }
  15975. const String RecentlyOpenedFilesList::toString() const
  15976. {
  15977. return files.joinIntoString ("\n");
  15978. }
  15979. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  15980. {
  15981. clear();
  15982. files.addLines (stringifiedVersion);
  15983. setMaxNumberOfItems (maxNumberOfItems);
  15984. }
  15985. END_JUCE_NAMESPACE
  15986. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  15987. /*** Start of inlined file: juce_UndoManager.cpp ***/
  15988. BEGIN_JUCE_NAMESPACE
  15989. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  15990. const int minimumTransactions)
  15991. : totalUnitsStored (0),
  15992. nextIndex (0),
  15993. newTransaction (true),
  15994. reentrancyCheck (false)
  15995. {
  15996. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  15997. minimumTransactions);
  15998. }
  15999. UndoManager::~UndoManager()
  16000. {
  16001. clearUndoHistory();
  16002. }
  16003. void UndoManager::clearUndoHistory()
  16004. {
  16005. transactions.clear();
  16006. transactionNames.clear();
  16007. totalUnitsStored = 0;
  16008. nextIndex = 0;
  16009. sendChangeMessage();
  16010. }
  16011. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16012. {
  16013. return totalUnitsStored;
  16014. }
  16015. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16016. const int minimumTransactions)
  16017. {
  16018. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16019. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16020. }
  16021. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16022. {
  16023. if (command_ != 0)
  16024. {
  16025. ScopedPointer<UndoableAction> command (command_);
  16026. if (actionName.isNotEmpty())
  16027. currentTransactionName = actionName;
  16028. if (reentrancyCheck)
  16029. {
  16030. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16031. // undo() methods, or else these actions won't actually get done.
  16032. return false;
  16033. }
  16034. else if (command->perform())
  16035. {
  16036. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16037. if (commandSet != 0 && ! newTransaction)
  16038. {
  16039. UndoableAction* lastAction = commandSet->getLast();
  16040. if (lastAction != 0)
  16041. {
  16042. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16043. if (coalescedAction != 0)
  16044. {
  16045. command = coalescedAction;
  16046. totalUnitsStored -= lastAction->getSizeInUnits();
  16047. commandSet->removeLast();
  16048. }
  16049. }
  16050. }
  16051. else
  16052. {
  16053. commandSet = new OwnedArray<UndoableAction>();
  16054. transactions.insert (nextIndex, commandSet);
  16055. transactionNames.insert (nextIndex, currentTransactionName);
  16056. ++nextIndex;
  16057. }
  16058. totalUnitsStored += command->getSizeInUnits();
  16059. commandSet->add (command.release());
  16060. newTransaction = false;
  16061. while (nextIndex < transactions.size())
  16062. {
  16063. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16064. for (int i = lastSet->size(); --i >= 0;)
  16065. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16066. transactions.removeLast();
  16067. transactionNames.remove (transactionNames.size() - 1);
  16068. }
  16069. while (nextIndex > 0
  16070. && totalUnitsStored > maxNumUnitsToKeep
  16071. && transactions.size() > minimumTransactionsToKeep)
  16072. {
  16073. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16074. for (int i = firstSet->size(); --i >= 0;)
  16075. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16076. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16077. transactions.remove (0);
  16078. transactionNames.remove (0);
  16079. --nextIndex;
  16080. }
  16081. sendChangeMessage();
  16082. return true;
  16083. }
  16084. }
  16085. return false;
  16086. }
  16087. void UndoManager::beginNewTransaction (const String& actionName)
  16088. {
  16089. newTransaction = true;
  16090. currentTransactionName = actionName;
  16091. }
  16092. void UndoManager::setCurrentTransactionName (const String& newName)
  16093. {
  16094. currentTransactionName = newName;
  16095. }
  16096. bool UndoManager::canUndo() const
  16097. {
  16098. return nextIndex > 0;
  16099. }
  16100. bool UndoManager::canRedo() const
  16101. {
  16102. return nextIndex < transactions.size();
  16103. }
  16104. const String UndoManager::getUndoDescription() const
  16105. {
  16106. return transactionNames [nextIndex - 1];
  16107. }
  16108. const String UndoManager::getRedoDescription() const
  16109. {
  16110. return transactionNames [nextIndex];
  16111. }
  16112. bool UndoManager::undo()
  16113. {
  16114. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16115. if (commandSet == 0)
  16116. return false;
  16117. bool failed = false;
  16118. {
  16119. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16120. for (int i = commandSet->size(); --i >= 0;)
  16121. {
  16122. if (! commandSet->getUnchecked(i)->undo())
  16123. {
  16124. jassertfalse;
  16125. failed = true;
  16126. break;
  16127. }
  16128. }
  16129. }
  16130. if (failed)
  16131. clearUndoHistory();
  16132. else
  16133. --nextIndex;
  16134. beginNewTransaction();
  16135. sendChangeMessage();
  16136. return true;
  16137. }
  16138. bool UndoManager::redo()
  16139. {
  16140. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16141. if (commandSet == 0)
  16142. return false;
  16143. bool failed = false;
  16144. {
  16145. const ScopedValueSetter<bool> setter (reentrancyCheck, true);
  16146. for (int i = 0; i < commandSet->size(); ++i)
  16147. {
  16148. if (! commandSet->getUnchecked(i)->perform())
  16149. {
  16150. jassertfalse;
  16151. failed = true;
  16152. break;
  16153. }
  16154. }
  16155. }
  16156. if (failed)
  16157. clearUndoHistory();
  16158. else
  16159. ++nextIndex;
  16160. beginNewTransaction();
  16161. sendChangeMessage();
  16162. return true;
  16163. }
  16164. bool UndoManager::undoCurrentTransactionOnly()
  16165. {
  16166. return newTransaction ? false : undo();
  16167. }
  16168. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16169. {
  16170. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16171. if (commandSet != 0 && ! newTransaction)
  16172. {
  16173. for (int i = 0; i < commandSet->size(); ++i)
  16174. actionsFound.add (commandSet->getUnchecked(i));
  16175. }
  16176. }
  16177. int UndoManager::getNumActionsInCurrentTransaction() const
  16178. {
  16179. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16180. if (commandSet != 0 && ! newTransaction)
  16181. return commandSet->size();
  16182. return 0;
  16183. }
  16184. END_JUCE_NAMESPACE
  16185. /*** End of inlined file: juce_UndoManager.cpp ***/
  16186. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16187. BEGIN_JUCE_NAMESPACE
  16188. static const char* const aiffFormatName = "AIFF file";
  16189. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16190. class AiffAudioFormatReader : public AudioFormatReader
  16191. {
  16192. public:
  16193. int bytesPerFrame;
  16194. int64 dataChunkStart;
  16195. bool littleEndian;
  16196. AiffAudioFormatReader (InputStream* in)
  16197. : AudioFormatReader (in, TRANS (aiffFormatName))
  16198. {
  16199. if (input->readInt() == chunkName ("FORM"))
  16200. {
  16201. const int len = input->readIntBigEndian();
  16202. const int64 end = input->getPosition() + len;
  16203. const int nextType = input->readInt();
  16204. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16205. {
  16206. bool hasGotVer = false;
  16207. bool hasGotData = false;
  16208. bool hasGotType = false;
  16209. while (input->getPosition() < end)
  16210. {
  16211. const int type = input->readInt();
  16212. const uint32 length = (uint32) input->readIntBigEndian();
  16213. const int64 chunkEnd = input->getPosition() + length;
  16214. if (type == chunkName ("FVER"))
  16215. {
  16216. hasGotVer = true;
  16217. const int ver = input->readIntBigEndian();
  16218. if (ver != 0 && ver != (int) 0xa2805140)
  16219. break;
  16220. }
  16221. else if (type == chunkName ("COMM"))
  16222. {
  16223. hasGotType = true;
  16224. numChannels = (unsigned int) input->readShortBigEndian();
  16225. lengthInSamples = input->readIntBigEndian();
  16226. bitsPerSample = input->readShortBigEndian();
  16227. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16228. unsigned char sampleRateBytes[10];
  16229. input->read (sampleRateBytes, 10);
  16230. const int byte0 = sampleRateBytes[0];
  16231. if ((byte0 & 0x80) != 0
  16232. || byte0 <= 0x3F || byte0 > 0x40
  16233. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16234. break;
  16235. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16236. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16237. sampleRate = (int) sampRate;
  16238. if (length <= 18)
  16239. {
  16240. // some types don't have a chunk large enough to include a compression
  16241. // type, so assume it's just big-endian pcm
  16242. littleEndian = false;
  16243. }
  16244. else
  16245. {
  16246. const int compType = input->readInt();
  16247. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16248. {
  16249. littleEndian = false;
  16250. }
  16251. else if (compType == chunkName ("sowt"))
  16252. {
  16253. littleEndian = true;
  16254. }
  16255. else
  16256. {
  16257. sampleRate = 0;
  16258. break;
  16259. }
  16260. }
  16261. }
  16262. else if (type == chunkName ("SSND"))
  16263. {
  16264. hasGotData = true;
  16265. const int offset = input->readIntBigEndian();
  16266. dataChunkStart = input->getPosition() + 4 + offset;
  16267. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16268. }
  16269. else if ((hasGotVer && hasGotData && hasGotType)
  16270. || chunkEnd < input->getPosition()
  16271. || input->isExhausted())
  16272. {
  16273. break;
  16274. }
  16275. input->setPosition (chunkEnd);
  16276. }
  16277. }
  16278. }
  16279. }
  16280. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16281. int64 startSampleInFile, int numSamples)
  16282. {
  16283. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16284. if (samplesAvailable < numSamples)
  16285. {
  16286. for (int i = numDestChannels; --i >= 0;)
  16287. if (destSamples[i] != 0)
  16288. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16289. numSamples = (int) samplesAvailable;
  16290. }
  16291. if (numSamples <= 0)
  16292. return true;
  16293. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16294. while (numSamples > 0)
  16295. {
  16296. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16297. char tempBuffer [tempBufSize];
  16298. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16299. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16300. if (bytesRead < numThisTime * bytesPerFrame)
  16301. {
  16302. jassert (bytesRead >= 0);
  16303. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16304. }
  16305. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16306. if (littleEndian)
  16307. {
  16308. switch (bitsPerSample)
  16309. {
  16310. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16311. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16312. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16313. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16314. default: jassertfalse; break;
  16315. }
  16316. }
  16317. else
  16318. {
  16319. switch (bitsPerSample)
  16320. {
  16321. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16322. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16323. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16324. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16325. default: jassertfalse; break;
  16326. }
  16327. }
  16328. startOffsetInDestBuffer += numThisTime;
  16329. numSamples -= numThisTime;
  16330. }
  16331. return true;
  16332. }
  16333. private:
  16334. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16335. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatReader);
  16336. };
  16337. class AiffAudioFormatWriter : public AudioFormatWriter
  16338. {
  16339. public:
  16340. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16341. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16342. lengthInSamples (0),
  16343. bytesWritten (0),
  16344. writeFailed (false)
  16345. {
  16346. headerPosition = out->getPosition();
  16347. writeHeader();
  16348. }
  16349. ~AiffAudioFormatWriter()
  16350. {
  16351. if ((bytesWritten & 1) != 0)
  16352. output->writeByte (0);
  16353. writeHeader();
  16354. }
  16355. bool write (const int** data, int numSamples)
  16356. {
  16357. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16358. if (writeFailed)
  16359. return false;
  16360. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16361. tempBlock.ensureSize (bytes, false);
  16362. switch (bitsPerSample)
  16363. {
  16364. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16365. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16366. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16367. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16368. default: jassertfalse; break;
  16369. }
  16370. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16371. || ! output->write (tempBlock.getData(), bytes))
  16372. {
  16373. // failed to write to disk, so let's try writing the header.
  16374. // If it's just run out of disk space, then if it does manage
  16375. // to write the header, we'll still have a useable file..
  16376. writeHeader();
  16377. writeFailed = true;
  16378. return false;
  16379. }
  16380. else
  16381. {
  16382. bytesWritten += bytes;
  16383. lengthInSamples += numSamples;
  16384. return true;
  16385. }
  16386. }
  16387. private:
  16388. MemoryBlock tempBlock;
  16389. uint32 lengthInSamples, bytesWritten;
  16390. int64 headerPosition;
  16391. bool writeFailed;
  16392. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16393. void writeHeader()
  16394. {
  16395. const bool couldSeekOk = output->setPosition (headerPosition);
  16396. (void) couldSeekOk;
  16397. // if this fails, you've given it an output stream that can't seek! It needs
  16398. // to be able to seek back to write the header
  16399. jassert (couldSeekOk);
  16400. const int headerLen = 54;
  16401. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16402. audioBytes += (audioBytes & 1);
  16403. output->writeInt (chunkName ("FORM"));
  16404. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16405. output->writeInt (chunkName ("AIFF"));
  16406. output->writeInt (chunkName ("COMM"));
  16407. output->writeIntBigEndian (18);
  16408. output->writeShortBigEndian ((short) numChannels);
  16409. output->writeIntBigEndian (lengthInSamples);
  16410. output->writeShortBigEndian ((short) bitsPerSample);
  16411. uint8 sampleRateBytes[10];
  16412. zeromem (sampleRateBytes, 10);
  16413. if (sampleRate <= 1)
  16414. {
  16415. sampleRateBytes[0] = 0x3f;
  16416. sampleRateBytes[1] = 0xff;
  16417. sampleRateBytes[2] = 0x80;
  16418. }
  16419. else
  16420. {
  16421. int mask = 0x40000000;
  16422. sampleRateBytes[0] = 0x40;
  16423. if (sampleRate >= mask)
  16424. {
  16425. jassertfalse;
  16426. sampleRateBytes[1] = 0x1d;
  16427. }
  16428. else
  16429. {
  16430. int n = (int) sampleRate;
  16431. int i;
  16432. for (i = 0; i <= 32 ; ++i)
  16433. {
  16434. if ((n & mask) != 0)
  16435. break;
  16436. mask >>= 1;
  16437. }
  16438. n = n << (i + 1);
  16439. sampleRateBytes[1] = (uint8) (29 - i);
  16440. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16441. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16442. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16443. sampleRateBytes[5] = (uint8) (n & 0xff);
  16444. }
  16445. }
  16446. output->write (sampleRateBytes, 10);
  16447. output->writeInt (chunkName ("SSND"));
  16448. output->writeIntBigEndian (audioBytes + 8);
  16449. output->writeInt (0);
  16450. output->writeInt (0);
  16451. jassert (output->getPosition() == headerLen);
  16452. }
  16453. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AiffAudioFormatWriter);
  16454. };
  16455. AiffAudioFormat::AiffAudioFormat()
  16456. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16457. {
  16458. }
  16459. AiffAudioFormat::~AiffAudioFormat()
  16460. {
  16461. }
  16462. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16463. {
  16464. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16465. return Array <int> (rates);
  16466. }
  16467. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16468. {
  16469. const int depths[] = { 8, 16, 24, 0 };
  16470. return Array <int> (depths);
  16471. }
  16472. bool AiffAudioFormat::canDoStereo() { return true; }
  16473. bool AiffAudioFormat::canDoMono() { return true; }
  16474. #if JUCE_MAC
  16475. bool AiffAudioFormat::canHandleFile (const File& f)
  16476. {
  16477. if (AudioFormat::canHandleFile (f))
  16478. return true;
  16479. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16480. return type == 'AIFF' || type == 'AIFC'
  16481. || type == 'aiff' || type == 'aifc';
  16482. }
  16483. #endif
  16484. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16485. {
  16486. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16487. if (w->sampleRate != 0)
  16488. return w.release();
  16489. if (! deleteStreamIfOpeningFails)
  16490. w->input = 0;
  16491. return 0;
  16492. }
  16493. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16494. double sampleRate,
  16495. unsigned int numberOfChannels,
  16496. int bitsPerSample,
  16497. const StringPairArray& /*metadataValues*/,
  16498. int /*qualityOptionIndex*/)
  16499. {
  16500. if (getPossibleBitDepths().contains (bitsPerSample))
  16501. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16502. return 0;
  16503. }
  16504. END_JUCE_NAMESPACE
  16505. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16506. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16507. BEGIN_JUCE_NAMESPACE
  16508. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16509. : formatName (name),
  16510. fileExtensions (extensions)
  16511. {
  16512. }
  16513. AudioFormat::~AudioFormat()
  16514. {
  16515. }
  16516. bool AudioFormat::canHandleFile (const File& f)
  16517. {
  16518. for (int i = 0; i < fileExtensions.size(); ++i)
  16519. if (f.hasFileExtension (fileExtensions[i]))
  16520. return true;
  16521. return false;
  16522. }
  16523. const String& AudioFormat::getFormatName() const { return formatName; }
  16524. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16525. bool AudioFormat::isCompressed() { return false; }
  16526. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16527. END_JUCE_NAMESPACE
  16528. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16529. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16530. BEGIN_JUCE_NAMESPACE
  16531. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16532. const String& formatName_)
  16533. : sampleRate (0),
  16534. bitsPerSample (0),
  16535. lengthInSamples (0),
  16536. numChannels (0),
  16537. usesFloatingPointData (false),
  16538. input (in),
  16539. formatName (formatName_)
  16540. {
  16541. }
  16542. AudioFormatReader::~AudioFormatReader()
  16543. {
  16544. delete input;
  16545. }
  16546. bool AudioFormatReader::read (int* const* destSamples,
  16547. int numDestChannels,
  16548. int64 startSampleInSource,
  16549. int numSamplesToRead,
  16550. const bool fillLeftoverChannelsWithCopies)
  16551. {
  16552. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16553. int startOffsetInDestBuffer = 0;
  16554. if (startSampleInSource < 0)
  16555. {
  16556. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16557. for (int i = numDestChannels; --i >= 0;)
  16558. if (destSamples[i] != 0)
  16559. zeromem (destSamples[i], sizeof (int) * silence);
  16560. startOffsetInDestBuffer += silence;
  16561. numSamplesToRead -= silence;
  16562. startSampleInSource = 0;
  16563. }
  16564. if (numSamplesToRead <= 0)
  16565. return true;
  16566. if (! readSamples (const_cast<int**> (destSamples),
  16567. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  16568. startSampleInSource, numSamplesToRead))
  16569. return false;
  16570. if (numDestChannels > (int) numChannels)
  16571. {
  16572. if (fillLeftoverChannelsWithCopies)
  16573. {
  16574. int* lastFullChannel = destSamples[0];
  16575. for (int i = (int) numChannels; --i > 0;)
  16576. {
  16577. if (destSamples[i] != 0)
  16578. {
  16579. lastFullChannel = destSamples[i];
  16580. break;
  16581. }
  16582. }
  16583. if (lastFullChannel != 0)
  16584. for (int i = numChannels; i < numDestChannels; ++i)
  16585. if (destSamples[i] != 0)
  16586. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  16587. }
  16588. else
  16589. {
  16590. for (int i = numChannels; i < numDestChannels; ++i)
  16591. if (destSamples[i] != 0)
  16592. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  16593. }
  16594. }
  16595. return true;
  16596. }
  16597. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  16598. int64 numSamples,
  16599. float& lowestLeft, float& highestLeft,
  16600. float& lowestRight, float& highestRight)
  16601. {
  16602. if (numSamples <= 0)
  16603. {
  16604. lowestLeft = 0;
  16605. lowestRight = 0;
  16606. highestLeft = 0;
  16607. highestRight = 0;
  16608. return;
  16609. }
  16610. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  16611. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16612. int* tempBuffer[3];
  16613. tempBuffer[0] = tempSpace.getData();
  16614. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16615. tempBuffer[2] = 0;
  16616. if (usesFloatingPointData)
  16617. {
  16618. float lmin = 1.0e6f;
  16619. float lmax = -lmin;
  16620. float rmin = lmin;
  16621. float rmax = lmax;
  16622. while (numSamples > 0)
  16623. {
  16624. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16625. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  16626. numSamples -= numToDo;
  16627. startSampleInFile += numToDo;
  16628. float bufMin, bufMax;
  16629. findMinAndMax (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufMin, bufMax);
  16630. lmin = jmin (lmin, bufMin);
  16631. lmax = jmax (lmax, bufMax);
  16632. if (numChannels > 1)
  16633. {
  16634. findMinAndMax (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufMin, bufMax);
  16635. rmin = jmin (rmin, bufMin);
  16636. rmax = jmax (rmax, bufMax);
  16637. }
  16638. }
  16639. if (numChannels <= 1)
  16640. {
  16641. rmax = lmax;
  16642. rmin = lmin;
  16643. }
  16644. lowestLeft = lmin;
  16645. highestLeft = lmax;
  16646. lowestRight = rmin;
  16647. highestRight = rmax;
  16648. }
  16649. else
  16650. {
  16651. int lmax = std::numeric_limits<int>::min();
  16652. int lmin = std::numeric_limits<int>::max();
  16653. int rmax = std::numeric_limits<int>::min();
  16654. int rmin = std::numeric_limits<int>::max();
  16655. while (numSamples > 0)
  16656. {
  16657. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  16658. if (! read (tempBuffer, 2, startSampleInFile, numToDo, false))
  16659. break;
  16660. numSamples -= numToDo;
  16661. startSampleInFile += numToDo;
  16662. for (int j = numChannels; --j >= 0;)
  16663. {
  16664. int bufMin, bufMax;
  16665. findMinAndMax (tempBuffer[j], numToDo, bufMin, bufMax);
  16666. if (j == 0)
  16667. {
  16668. lmax = jmax (lmax, bufMax);
  16669. lmin = jmin (lmin, bufMin);
  16670. }
  16671. else
  16672. {
  16673. rmax = jmax (rmax, bufMax);
  16674. rmin = jmin (rmin, bufMin);
  16675. }
  16676. }
  16677. }
  16678. if (numChannels <= 1)
  16679. {
  16680. rmax = lmax;
  16681. rmin = lmin;
  16682. }
  16683. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  16684. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  16685. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  16686. highestRight = rmax / (float) std::numeric_limits<int>::max();
  16687. }
  16688. }
  16689. int64 AudioFormatReader::searchForLevel (int64 startSample,
  16690. int64 numSamplesToSearch,
  16691. const double magnitudeRangeMinimum,
  16692. const double magnitudeRangeMaximum,
  16693. const int minimumConsecutiveSamples)
  16694. {
  16695. if (numSamplesToSearch == 0)
  16696. return -1;
  16697. const int bufferSize = 4096;
  16698. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  16699. int* tempBuffer[3];
  16700. tempBuffer[0] = tempSpace.getData();
  16701. tempBuffer[1] = tempSpace.getData() + bufferSize;
  16702. tempBuffer[2] = 0;
  16703. int consecutive = 0;
  16704. int64 firstMatchPos = -1;
  16705. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  16706. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  16707. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  16708. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  16709. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  16710. while (numSamplesToSearch != 0)
  16711. {
  16712. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  16713. int64 bufferStart = startSample;
  16714. if (numSamplesToSearch < 0)
  16715. bufferStart -= numThisTime;
  16716. if (bufferStart >= (int) lengthInSamples)
  16717. break;
  16718. read (tempBuffer, 2, bufferStart, numThisTime, false);
  16719. int num = numThisTime;
  16720. while (--num >= 0)
  16721. {
  16722. if (numSamplesToSearch < 0)
  16723. --startSample;
  16724. bool matches = false;
  16725. const int index = (int) (startSample - bufferStart);
  16726. if (usesFloatingPointData)
  16727. {
  16728. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  16729. if (sample1 >= magnitudeRangeMinimum
  16730. && sample1 <= magnitudeRangeMaximum)
  16731. {
  16732. matches = true;
  16733. }
  16734. else if (numChannels > 1)
  16735. {
  16736. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  16737. matches = (sample2 >= magnitudeRangeMinimum
  16738. && sample2 <= magnitudeRangeMaximum);
  16739. }
  16740. }
  16741. else
  16742. {
  16743. const int sample1 = abs (tempBuffer[0] [index]);
  16744. if (sample1 >= intMagnitudeRangeMinimum
  16745. && sample1 <= intMagnitudeRangeMaximum)
  16746. {
  16747. matches = true;
  16748. }
  16749. else if (numChannels > 1)
  16750. {
  16751. const int sample2 = abs (tempBuffer[1][index]);
  16752. matches = (sample2 >= intMagnitudeRangeMinimum
  16753. && sample2 <= intMagnitudeRangeMaximum);
  16754. }
  16755. }
  16756. if (matches)
  16757. {
  16758. if (firstMatchPos < 0)
  16759. firstMatchPos = startSample;
  16760. if (++consecutive >= minimumConsecutiveSamples)
  16761. {
  16762. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  16763. return -1;
  16764. return firstMatchPos;
  16765. }
  16766. }
  16767. else
  16768. {
  16769. consecutive = 0;
  16770. firstMatchPos = -1;
  16771. }
  16772. if (numSamplesToSearch > 0)
  16773. ++startSample;
  16774. }
  16775. if (numSamplesToSearch > 0)
  16776. numSamplesToSearch -= numThisTime;
  16777. else
  16778. numSamplesToSearch += numThisTime;
  16779. }
  16780. return -1;
  16781. }
  16782. END_JUCE_NAMESPACE
  16783. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  16784. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  16785. BEGIN_JUCE_NAMESPACE
  16786. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  16787. const String& formatName_,
  16788. const double rate,
  16789. const unsigned int numChannels_,
  16790. const unsigned int bitsPerSample_)
  16791. : sampleRate (rate),
  16792. numChannels (numChannels_),
  16793. bitsPerSample (bitsPerSample_),
  16794. usesFloatingPointData (false),
  16795. output (out),
  16796. formatName (formatName_)
  16797. {
  16798. }
  16799. AudioFormatWriter::~AudioFormatWriter()
  16800. {
  16801. delete output;
  16802. }
  16803. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  16804. int64 startSample,
  16805. int64 numSamplesToRead)
  16806. {
  16807. const int bufferSize = 16384;
  16808. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  16809. int* buffers [128];
  16810. zerostruct (buffers);
  16811. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  16812. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  16813. if (numSamplesToRead < 0)
  16814. numSamplesToRead = reader.lengthInSamples;
  16815. while (numSamplesToRead > 0)
  16816. {
  16817. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  16818. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  16819. return false;
  16820. if (reader.usesFloatingPointData != isFloatingPoint())
  16821. {
  16822. int** bufferChan = buffers;
  16823. while (*bufferChan != 0)
  16824. {
  16825. int* b = *bufferChan++;
  16826. if (isFloatingPoint())
  16827. {
  16828. // int -> float
  16829. const double factor = 1.0 / std::numeric_limits<int>::max();
  16830. for (int i = 0; i < numToDo; ++i)
  16831. ((float*) b)[i] = (float) (factor * b[i]);
  16832. }
  16833. else
  16834. {
  16835. // float -> int
  16836. for (int i = 0; i < numToDo; ++i)
  16837. {
  16838. const double samp = *(const float*) b;
  16839. if (samp <= -1.0)
  16840. *b++ = std::numeric_limits<int>::min();
  16841. else if (samp >= 1.0)
  16842. *b++ = std::numeric_limits<int>::max();
  16843. else
  16844. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  16845. }
  16846. }
  16847. }
  16848. }
  16849. if (! write (const_cast<const int**> (buffers), numToDo))
  16850. return false;
  16851. numSamplesToRead -= numToDo;
  16852. startSample += numToDo;
  16853. }
  16854. return true;
  16855. }
  16856. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  16857. {
  16858. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  16859. while (numSamplesToRead > 0)
  16860. {
  16861. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  16862. AudioSourceChannelInfo info;
  16863. info.buffer = &tempBuffer;
  16864. info.startSample = 0;
  16865. info.numSamples = numToDo;
  16866. info.clearActiveBufferRegion();
  16867. source.getNextAudioBlock (info);
  16868. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  16869. return false;
  16870. numSamplesToRead -= numToDo;
  16871. }
  16872. return true;
  16873. }
  16874. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  16875. {
  16876. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  16877. if (numSamples <= 0)
  16878. return true;
  16879. HeapBlock<int> tempBuffer;
  16880. HeapBlock<int*> chans (numChannels + 1);
  16881. chans [numChannels] = 0;
  16882. if (isFloatingPoint())
  16883. {
  16884. for (int i = numChannels; --i >= 0;)
  16885. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  16886. }
  16887. else
  16888. {
  16889. tempBuffer.malloc (numSamples * numChannels);
  16890. for (unsigned int i = 0; i < numChannels; ++i)
  16891. {
  16892. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  16893. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  16894. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  16895. SourceSampleType sourceData (source.getSampleData (i, startSample));
  16896. destData.convertSamples (sourceData, numSamples);
  16897. }
  16898. }
  16899. return write ((const int**) chans.getData(), numSamples);
  16900. }
  16901. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  16902. public AbstractFifo
  16903. {
  16904. public:
  16905. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize_)
  16906. : AbstractFifo (bufferSize_),
  16907. buffer (numChannels, bufferSize_),
  16908. timeSliceThread (timeSliceThread_),
  16909. writer (writer_),
  16910. thumbnailToUpdate (0),
  16911. samplesWritten (0),
  16912. isRunning (true)
  16913. {
  16914. timeSliceThread.addTimeSliceClient (this);
  16915. }
  16916. ~Buffer()
  16917. {
  16918. isRunning = false;
  16919. timeSliceThread.removeTimeSliceClient (this);
  16920. while (useTimeSlice() == 0)
  16921. {}
  16922. }
  16923. bool write (const float** data, int numSamples)
  16924. {
  16925. if (numSamples <= 0 || ! isRunning)
  16926. return true;
  16927. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  16928. int start1, size1, start2, size2;
  16929. prepareToWrite (numSamples, start1, size1, start2, size2);
  16930. if (size1 + size2 < numSamples)
  16931. return false;
  16932. for (int i = buffer.getNumChannels(); --i >= 0;)
  16933. {
  16934. buffer.copyFrom (i, start1, data[i], size1);
  16935. buffer.copyFrom (i, start2, data[i] + size1, size2);
  16936. }
  16937. finishedWrite (size1 + size2);
  16938. timeSliceThread.notify();
  16939. return true;
  16940. }
  16941. int useTimeSlice()
  16942. {
  16943. const int numToDo = getTotalSize() / 4;
  16944. int start1, size1, start2, size2;
  16945. prepareToRead (numToDo, start1, size1, start2, size2);
  16946. if (size1 <= 0)
  16947. return 10;
  16948. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  16949. const ScopedLock sl (thumbnailLock);
  16950. if (thumbnailToUpdate != 0)
  16951. thumbnailToUpdate->addBlock (samplesWritten, buffer, start1, size1);
  16952. samplesWritten += size1;
  16953. if (size2 > 0)
  16954. {
  16955. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  16956. if (thumbnailToUpdate != 0)
  16957. thumbnailToUpdate->addBlock (samplesWritten, buffer, start2, size2);
  16958. samplesWritten += size2;
  16959. }
  16960. finishedRead (size1 + size2);
  16961. return 0;
  16962. }
  16963. void setThumbnail (AudioThumbnail* thumb)
  16964. {
  16965. if (thumb != 0)
  16966. thumb->reset (buffer.getNumChannels(), writer->getSampleRate(), 0);
  16967. const ScopedLock sl (thumbnailLock);
  16968. thumbnailToUpdate = thumb;
  16969. samplesWritten = 0;
  16970. }
  16971. private:
  16972. AudioSampleBuffer buffer;
  16973. TimeSliceThread& timeSliceThread;
  16974. ScopedPointer<AudioFormatWriter> writer;
  16975. CriticalSection thumbnailLock;
  16976. AudioThumbnail* thumbnailToUpdate;
  16977. int64 samplesWritten;
  16978. volatile bool isRunning;
  16979. JUCE_DECLARE_NON_COPYABLE (Buffer);
  16980. };
  16981. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  16982. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  16983. {
  16984. }
  16985. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  16986. {
  16987. }
  16988. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  16989. {
  16990. return buffer->write (data, numSamples);
  16991. }
  16992. void AudioFormatWriter::ThreadedWriter::setThumbnailToUpdate (AudioThumbnail* thumb)
  16993. {
  16994. buffer->setThumbnail (thumb);
  16995. }
  16996. END_JUCE_NAMESPACE
  16997. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  16998. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  16999. BEGIN_JUCE_NAMESPACE
  17000. AudioFormatManager::AudioFormatManager()
  17001. : defaultFormatIndex (0)
  17002. {
  17003. }
  17004. AudioFormatManager::~AudioFormatManager()
  17005. {
  17006. }
  17007. void AudioFormatManager::registerFormat (AudioFormat* newFormat, const bool makeThisTheDefaultFormat)
  17008. {
  17009. jassert (newFormat != 0);
  17010. if (newFormat != 0)
  17011. {
  17012. #if JUCE_DEBUG
  17013. for (int i = getNumKnownFormats(); --i >= 0;)
  17014. {
  17015. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17016. {
  17017. jassertfalse; // trying to add the same format twice!
  17018. }
  17019. }
  17020. #endif
  17021. if (makeThisTheDefaultFormat)
  17022. defaultFormatIndex = getNumKnownFormats();
  17023. knownFormats.add (newFormat);
  17024. }
  17025. }
  17026. void AudioFormatManager::registerBasicFormats()
  17027. {
  17028. #if JUCE_MAC
  17029. registerFormat (new AiffAudioFormat(), true);
  17030. registerFormat (new WavAudioFormat(), false);
  17031. #else
  17032. registerFormat (new WavAudioFormat(), true);
  17033. registerFormat (new AiffAudioFormat(), false);
  17034. #endif
  17035. #if JUCE_USE_FLAC
  17036. registerFormat (new FlacAudioFormat(), false);
  17037. #endif
  17038. #if JUCE_USE_OGGVORBIS
  17039. registerFormat (new OggVorbisAudioFormat(), false);
  17040. #endif
  17041. }
  17042. void AudioFormatManager::clearFormats()
  17043. {
  17044. knownFormats.clear();
  17045. defaultFormatIndex = 0;
  17046. }
  17047. int AudioFormatManager::getNumKnownFormats() const
  17048. {
  17049. return knownFormats.size();
  17050. }
  17051. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17052. {
  17053. return knownFormats [index];
  17054. }
  17055. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17056. {
  17057. return getKnownFormat (defaultFormatIndex);
  17058. }
  17059. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17060. {
  17061. String e (fileExtension);
  17062. if (! e.startsWithChar ('.'))
  17063. e = "." + e;
  17064. for (int i = 0; i < getNumKnownFormats(); ++i)
  17065. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17066. return getKnownFormat(i);
  17067. return 0;
  17068. }
  17069. const String AudioFormatManager::getWildcardForAllFormats() const
  17070. {
  17071. StringArray allExtensions;
  17072. int i;
  17073. for (i = 0; i < getNumKnownFormats(); ++i)
  17074. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17075. allExtensions.trim();
  17076. allExtensions.removeEmptyStrings();
  17077. String s;
  17078. for (i = 0; i < allExtensions.size(); ++i)
  17079. {
  17080. s << '*';
  17081. if (! allExtensions[i].startsWithChar ('.'))
  17082. s << '.';
  17083. s << allExtensions[i];
  17084. if (i < allExtensions.size() - 1)
  17085. s << ';';
  17086. }
  17087. return s;
  17088. }
  17089. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17090. {
  17091. // you need to actually register some formats before the manager can
  17092. // use them to open a file!
  17093. jassert (getNumKnownFormats() > 0);
  17094. for (int i = 0; i < getNumKnownFormats(); ++i)
  17095. {
  17096. AudioFormat* const af = getKnownFormat(i);
  17097. if (af->canHandleFile (file))
  17098. {
  17099. InputStream* const in = file.createInputStream();
  17100. if (in != 0)
  17101. {
  17102. AudioFormatReader* const r = af->createReaderFor (in, true);
  17103. if (r != 0)
  17104. return r;
  17105. }
  17106. }
  17107. }
  17108. return 0;
  17109. }
  17110. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17111. {
  17112. // you need to actually register some formats before the manager can
  17113. // use them to open a file!
  17114. jassert (getNumKnownFormats() > 0);
  17115. ScopedPointer <InputStream> in (audioFileStream);
  17116. if (in != 0)
  17117. {
  17118. const int64 originalStreamPos = in->getPosition();
  17119. for (int i = 0; i < getNumKnownFormats(); ++i)
  17120. {
  17121. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17122. if (r != 0)
  17123. {
  17124. in.release();
  17125. return r;
  17126. }
  17127. in->setPosition (originalStreamPos);
  17128. // the stream that is passed-in must be capable of being repositioned so
  17129. // that all the formats can have a go at opening it.
  17130. jassert (in->getPosition() == originalStreamPos);
  17131. }
  17132. }
  17133. return 0;
  17134. }
  17135. END_JUCE_NAMESPACE
  17136. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17137. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17138. BEGIN_JUCE_NAMESPACE
  17139. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17140. const int64 startSample_,
  17141. const int64 length_,
  17142. const bool deleteSourceWhenDeleted_)
  17143. : AudioFormatReader (0, source_->getFormatName()),
  17144. source (source_),
  17145. startSample (startSample_),
  17146. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17147. {
  17148. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17149. sampleRate = source->sampleRate;
  17150. bitsPerSample = source->bitsPerSample;
  17151. lengthInSamples = length;
  17152. numChannels = source->numChannels;
  17153. usesFloatingPointData = source->usesFloatingPointData;
  17154. }
  17155. AudioSubsectionReader::~AudioSubsectionReader()
  17156. {
  17157. if (deleteSourceWhenDeleted)
  17158. delete source;
  17159. }
  17160. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17161. int64 startSampleInFile, int numSamples)
  17162. {
  17163. if (startSampleInFile + numSamples > length)
  17164. {
  17165. for (int i = numDestChannels; --i >= 0;)
  17166. if (destSamples[i] != 0)
  17167. zeromem (destSamples[i], sizeof (int) * numSamples);
  17168. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17169. if (numSamples <= 0)
  17170. return true;
  17171. }
  17172. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17173. startSampleInFile + startSample, numSamples);
  17174. }
  17175. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17176. int64 numSamples,
  17177. float& lowestLeft,
  17178. float& highestLeft,
  17179. float& lowestRight,
  17180. float& highestRight)
  17181. {
  17182. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17183. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17184. source->readMaxLevels (startSampleInFile + startSample,
  17185. numSamples,
  17186. lowestLeft,
  17187. highestLeft,
  17188. lowestRight,
  17189. highestRight);
  17190. }
  17191. END_JUCE_NAMESPACE
  17192. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17193. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17194. BEGIN_JUCE_NAMESPACE
  17195. struct AudioThumbnail::MinMaxValue
  17196. {
  17197. char minValue;
  17198. char maxValue;
  17199. MinMaxValue() : minValue (0), maxValue (0)
  17200. {
  17201. }
  17202. inline void set (const char newMin, const char newMax) throw()
  17203. {
  17204. minValue = newMin;
  17205. maxValue = newMax;
  17206. }
  17207. inline void setFloat (const float newMin, const float newMax) throw()
  17208. {
  17209. minValue = (char) jlimit (-128, 127, roundFloatToInt (newMin * 127.0f));
  17210. maxValue = (char) jlimit (-128, 127, roundFloatToInt (newMax * 127.0f));
  17211. if (maxValue == minValue)
  17212. maxValue = (char) jmin (127, maxValue + 1);
  17213. }
  17214. inline bool isNonZero() const throw()
  17215. {
  17216. return maxValue > minValue;
  17217. }
  17218. inline int getPeak() const throw()
  17219. {
  17220. return jmax (std::abs ((int) minValue),
  17221. std::abs ((int) maxValue));
  17222. }
  17223. inline void read (InputStream& input)
  17224. {
  17225. minValue = input.readByte();
  17226. maxValue = input.readByte();
  17227. }
  17228. inline void write (OutputStream& output)
  17229. {
  17230. output.writeByte (minValue);
  17231. output.writeByte (maxValue);
  17232. }
  17233. };
  17234. class AudioThumbnail::LevelDataSource : public TimeSliceClient
  17235. {
  17236. public:
  17237. LevelDataSource (AudioThumbnail& owner_, AudioFormatReader* newReader, int64 hash)
  17238. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17239. hashCode (hash), owner (owner_), reader (newReader)
  17240. {
  17241. }
  17242. LevelDataSource (AudioThumbnail& owner_, InputSource* source_)
  17243. : lengthInSamples (0), numSamplesFinished (0), sampleRate (0), numChannels (0),
  17244. hashCode (source_->hashCode()), owner (owner_), source (source_)
  17245. {
  17246. }
  17247. ~LevelDataSource()
  17248. {
  17249. owner.cache.removeTimeSliceClient (this);
  17250. }
  17251. enum { timeBeforeDeletingReader = 1000 };
  17252. void initialise (int64 numSamplesFinished_)
  17253. {
  17254. const ScopedLock sl (readerLock);
  17255. numSamplesFinished = numSamplesFinished_;
  17256. createReader();
  17257. if (reader != 0)
  17258. {
  17259. lengthInSamples = reader->lengthInSamples;
  17260. numChannels = reader->numChannels;
  17261. sampleRate = reader->sampleRate;
  17262. if (lengthInSamples <= 0 || isFullyLoaded())
  17263. reader = 0;
  17264. else
  17265. owner.cache.addTimeSliceClient (this);
  17266. }
  17267. }
  17268. void getLevels (int64 startSample, int numSamples, Array<float>& levels)
  17269. {
  17270. const ScopedLock sl (readerLock);
  17271. if (reader == 0)
  17272. {
  17273. createReader();
  17274. if (reader != 0)
  17275. owner.cache.addTimeSliceClient (this);
  17276. }
  17277. if (reader != 0)
  17278. {
  17279. float l[4] = { 0 };
  17280. reader->readMaxLevels (startSample, numSamples, l[0], l[1], l[2], l[3]);
  17281. levels.clearQuick();
  17282. levels.addArray ((const float*) l, 4);
  17283. }
  17284. }
  17285. void releaseResources()
  17286. {
  17287. const ScopedLock sl (readerLock);
  17288. reader = 0;
  17289. }
  17290. int useTimeSlice()
  17291. {
  17292. if (isFullyLoaded())
  17293. {
  17294. if (reader != 0 && source != 0)
  17295. releaseResources();
  17296. return -1;
  17297. }
  17298. bool justFinished = false;
  17299. {
  17300. const ScopedLock sl (readerLock);
  17301. createReader();
  17302. if (reader != 0)
  17303. {
  17304. if (! readNextBlock())
  17305. return 0;
  17306. justFinished = true;
  17307. }
  17308. }
  17309. if (justFinished)
  17310. owner.cache.storeThumb (owner, hashCode);
  17311. return timeBeforeDeletingReader;
  17312. }
  17313. bool isFullyLoaded() const throw()
  17314. {
  17315. return numSamplesFinished >= lengthInSamples;
  17316. }
  17317. inline int sampleToThumbSample (const int64 originalSample) const throw()
  17318. {
  17319. return (int) (originalSample / owner.samplesPerThumbSample);
  17320. }
  17321. int64 lengthInSamples, numSamplesFinished;
  17322. double sampleRate;
  17323. int numChannels;
  17324. int64 hashCode;
  17325. private:
  17326. AudioThumbnail& owner;
  17327. ScopedPointer <InputSource> source;
  17328. ScopedPointer <AudioFormatReader> reader;
  17329. CriticalSection readerLock;
  17330. void createReader()
  17331. {
  17332. if (reader == 0 && source != 0)
  17333. {
  17334. InputStream* audioFileStream = source->createInputStream();
  17335. if (audioFileStream != 0)
  17336. reader = owner.formatManagerToUse.createReaderFor (audioFileStream);
  17337. }
  17338. }
  17339. bool readNextBlock()
  17340. {
  17341. jassert (reader != 0);
  17342. if (! isFullyLoaded())
  17343. {
  17344. const int numToDo = (int) jmin (256 * (int64) owner.samplesPerThumbSample, lengthInSamples - numSamplesFinished);
  17345. if (numToDo > 0)
  17346. {
  17347. int64 startSample = numSamplesFinished;
  17348. const int firstThumbIndex = sampleToThumbSample (startSample);
  17349. const int lastThumbIndex = sampleToThumbSample (startSample + numToDo);
  17350. const int numThumbSamps = lastThumbIndex - firstThumbIndex;
  17351. HeapBlock<MinMaxValue> levelData (numThumbSamps * 2);
  17352. MinMaxValue* levels[2] = { levelData, levelData + numThumbSamps };
  17353. for (int i = 0; i < numThumbSamps; ++i)
  17354. {
  17355. float lowestLeft, highestLeft, lowestRight, highestRight;
  17356. reader->readMaxLevels ((firstThumbIndex + i) * owner.samplesPerThumbSample, owner.samplesPerThumbSample,
  17357. lowestLeft, highestLeft, lowestRight, highestRight);
  17358. levels[0][i].setFloat (lowestLeft, highestLeft);
  17359. levels[1][i].setFloat (lowestRight, highestRight);
  17360. }
  17361. {
  17362. const ScopedUnlock su (readerLock);
  17363. owner.setLevels (levels, firstThumbIndex, 2, numThumbSamps);
  17364. }
  17365. numSamplesFinished += numToDo;
  17366. }
  17367. }
  17368. return isFullyLoaded();
  17369. }
  17370. };
  17371. class AudioThumbnail::ThumbData
  17372. {
  17373. public:
  17374. ThumbData (const int numThumbSamples)
  17375. : peakLevel (-1)
  17376. {
  17377. ensureSize (numThumbSamples);
  17378. }
  17379. inline MinMaxValue* getData (const int thumbSampleIndex) throw()
  17380. {
  17381. jassert (thumbSampleIndex < data.size());
  17382. return data.getRawDataPointer() + thumbSampleIndex;
  17383. }
  17384. int getSize() const throw()
  17385. {
  17386. return data.size();
  17387. }
  17388. void getMinMax (int startSample, int endSample, MinMaxValue& result) throw()
  17389. {
  17390. if (startSample >= 0)
  17391. {
  17392. endSample = jmin (endSample, data.size() - 1);
  17393. char mx = -128;
  17394. char mn = 127;
  17395. while (startSample <= endSample)
  17396. {
  17397. const MinMaxValue& v = data.getReference (startSample);
  17398. if (v.minValue < mn) mn = v.minValue;
  17399. if (v.maxValue > mx) mx = v.maxValue;
  17400. ++startSample;
  17401. }
  17402. if (mn <= mx)
  17403. {
  17404. result.set (mn, mx);
  17405. return;
  17406. }
  17407. }
  17408. result.set (1, 0);
  17409. }
  17410. void write (const MinMaxValue* const source, const int startIndex, const int numValues)
  17411. {
  17412. resetPeak();
  17413. if (startIndex + numValues > data.size())
  17414. ensureSize (startIndex + numValues);
  17415. MinMaxValue* const dest = getData (startIndex);
  17416. for (int i = 0; i < numValues; ++i)
  17417. dest[i] = source[i];
  17418. }
  17419. void resetPeak()
  17420. {
  17421. peakLevel = -1;
  17422. }
  17423. int getPeak()
  17424. {
  17425. if (peakLevel < 0)
  17426. {
  17427. for (int i = 0; i < data.size(); ++i)
  17428. {
  17429. const int peak = data[i].getPeak();
  17430. if (peak > peakLevel)
  17431. peakLevel = peak;
  17432. }
  17433. }
  17434. return peakLevel;
  17435. }
  17436. private:
  17437. Array <MinMaxValue> data;
  17438. int peakLevel;
  17439. void ensureSize (const int thumbSamples)
  17440. {
  17441. const int extraNeeded = thumbSamples - data.size();
  17442. if (extraNeeded > 0)
  17443. data.insertMultiple (-1, MinMaxValue(), extraNeeded);
  17444. }
  17445. };
  17446. class AudioThumbnail::CachedWindow
  17447. {
  17448. public:
  17449. CachedWindow()
  17450. : cachedStart (0), cachedTimePerPixel (0),
  17451. numChannelsCached (0), numSamplesCached (0),
  17452. cacheNeedsRefilling (true)
  17453. {
  17454. }
  17455. void invalidate()
  17456. {
  17457. cacheNeedsRefilling = true;
  17458. }
  17459. void drawChannel (Graphics& g, const Rectangle<int>& area,
  17460. const double startTime, const double endTime,
  17461. const int channelNum, const float verticalZoomFactor,
  17462. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17463. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17464. {
  17465. refillCache (area.getWidth(), startTime, endTime, sampleRate,
  17466. numChannels, samplesPerThumbSample, levelData, channels);
  17467. if (isPositiveAndBelow (channelNum, numChannelsCached))
  17468. {
  17469. const Rectangle<int> clip (g.getClipBounds().getIntersection (area.withWidth (jmin (numSamplesCached, area.getWidth()))));
  17470. if (! clip.isEmpty())
  17471. {
  17472. const float topY = (float) area.getY();
  17473. const float bottomY = (float) area.getBottom();
  17474. const float midY = (topY + bottomY) * 0.5f;
  17475. const float vscale = verticalZoomFactor * (bottomY - topY) / 256.0f;
  17476. const MinMaxValue* cacheData = getData (channelNum, clip.getX() - area.getX());
  17477. int x = clip.getX();
  17478. for (int w = clip.getWidth(); --w >= 0;)
  17479. {
  17480. if (cacheData->isNonZero())
  17481. g.drawVerticalLine (x, jmax (midY - cacheData->maxValue * vscale - 0.3f, topY),
  17482. jmin (midY - cacheData->minValue * vscale + 0.3f, bottomY));
  17483. ++x;
  17484. ++cacheData;
  17485. }
  17486. }
  17487. }
  17488. }
  17489. private:
  17490. Array <MinMaxValue> data;
  17491. double cachedStart, cachedTimePerPixel;
  17492. int numChannelsCached, numSamplesCached;
  17493. bool cacheNeedsRefilling;
  17494. void refillCache (const int numSamples, double startTime, const double endTime,
  17495. const double sampleRate, const int numChannels, const int samplesPerThumbSample,
  17496. LevelDataSource* levelData, const OwnedArray<ThumbData>& channels)
  17497. {
  17498. const double timePerPixel = (endTime - startTime) / numSamples;
  17499. if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0)
  17500. {
  17501. invalidate();
  17502. return;
  17503. }
  17504. if (numSamples == numSamplesCached
  17505. && numChannelsCached == numChannels
  17506. && startTime == cachedStart
  17507. && timePerPixel == cachedTimePerPixel
  17508. && ! cacheNeedsRefilling)
  17509. {
  17510. return;
  17511. }
  17512. numSamplesCached = numSamples;
  17513. numChannelsCached = numChannels;
  17514. cachedStart = startTime;
  17515. cachedTimePerPixel = timePerPixel;
  17516. cacheNeedsRefilling = false;
  17517. ensureSize (numSamples);
  17518. if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != 0)
  17519. {
  17520. int sample = roundToInt (startTime * sampleRate);
  17521. Array<float> levels;
  17522. int i;
  17523. for (i = 0; i < numSamples; ++i)
  17524. {
  17525. const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate);
  17526. if (sample >= 0)
  17527. {
  17528. if (sample >= levelData->lengthInSamples)
  17529. break;
  17530. levelData->getLevels (sample, jmax (1, nextSample - sample), levels);
  17531. const int numChans = jmin (levels.size() / 2, numChannelsCached);
  17532. for (int chan = 0; chan < numChans; ++chan)
  17533. getData (chan, i)->setFloat (levels.getUnchecked (chan * 2),
  17534. levels.getUnchecked (chan * 2 + 1));
  17535. }
  17536. startTime += timePerPixel;
  17537. sample = nextSample;
  17538. }
  17539. numSamplesCached = i;
  17540. }
  17541. else
  17542. {
  17543. jassert (channels.size() == numChannelsCached);
  17544. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17545. {
  17546. ThumbData* channelData = channels.getUnchecked (channelNum);
  17547. MinMaxValue* cacheData = getData (channelNum, 0);
  17548. const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample;
  17549. startTime = cachedStart;
  17550. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17551. for (int i = numSamples; --i >= 0;)
  17552. {
  17553. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17554. channelData->getMinMax (sample, nextSample, *cacheData);
  17555. ++cacheData;
  17556. startTime += timePerPixel;
  17557. sample = nextSample;
  17558. }
  17559. }
  17560. }
  17561. }
  17562. MinMaxValue* getData (const int channelNum, const int cacheIndex) throw()
  17563. {
  17564. jassert (isPositiveAndBelow (channelNum, numChannelsCached) && isPositiveAndBelow (cacheIndex, data.size()));
  17565. return data.getRawDataPointer() + channelNum * numSamplesCached
  17566. + cacheIndex;
  17567. }
  17568. void ensureSize (const int numSamples)
  17569. {
  17570. const int itemsRequired = numSamples * numChannelsCached;
  17571. if (data.size() < itemsRequired)
  17572. data.insertMultiple (-1, MinMaxValue(), itemsRequired - data.size());
  17573. }
  17574. };
  17575. AudioThumbnail::AudioThumbnail (const int originalSamplesPerThumbnailSample,
  17576. AudioFormatManager& formatManagerToUse_,
  17577. AudioThumbnailCache& cacheToUse)
  17578. : formatManagerToUse (formatManagerToUse_),
  17579. cache (cacheToUse),
  17580. window (new CachedWindow()),
  17581. samplesPerThumbSample (originalSamplesPerThumbnailSample),
  17582. totalSamples (0),
  17583. numChannels (0),
  17584. sampleRate (0)
  17585. {
  17586. }
  17587. AudioThumbnail::~AudioThumbnail()
  17588. {
  17589. clear();
  17590. }
  17591. void AudioThumbnail::clear()
  17592. {
  17593. source = 0;
  17594. const ScopedLock sl (lock);
  17595. window->invalidate();
  17596. channels.clear();
  17597. totalSamples = numSamplesFinished = 0;
  17598. numChannels = 0;
  17599. sampleRate = 0;
  17600. sendChangeMessage();
  17601. }
  17602. void AudioThumbnail::reset (int newNumChannels, double newSampleRate, int64 totalSamplesInSource)
  17603. {
  17604. clear();
  17605. numChannels = newNumChannels;
  17606. sampleRate = newSampleRate;
  17607. totalSamples = totalSamplesInSource;
  17608. createChannels (1 + (int) (totalSamplesInSource / samplesPerThumbSample));
  17609. }
  17610. void AudioThumbnail::createChannels (const int length)
  17611. {
  17612. while (channels.size() < numChannels)
  17613. channels.add (new ThumbData (length));
  17614. }
  17615. void AudioThumbnail::loadFrom (InputStream& input)
  17616. {
  17617. clear();
  17618. if (input.readByte() != 'j' || input.readByte() != 'a' || input.readByte() != 't' || input.readByte() != 'm')
  17619. return;
  17620. samplesPerThumbSample = input.readInt();
  17621. totalSamples = input.readInt64(); // Total number of source samples.
  17622. numSamplesFinished = input.readInt64(); // Number of valid source samples that have been read into the thumbnail.
  17623. int32 numThumbnailSamples = input.readInt(); // Number of samples in the thumbnail data.
  17624. numChannels = input.readInt(); // Number of audio channels.
  17625. sampleRate = input.readInt(); // Source sample rate.
  17626. input.skipNextBytes (16); // reserved area
  17627. createChannels (numThumbnailSamples);
  17628. for (int i = 0; i < numThumbnailSamples; ++i)
  17629. for (int chan = 0; chan < numChannels; ++chan)
  17630. channels.getUnchecked(chan)->getData(i)->read (input);
  17631. }
  17632. void AudioThumbnail::saveTo (OutputStream& output) const
  17633. {
  17634. const ScopedLock sl (lock);
  17635. const int numThumbnailSamples = channels.size() == 0 ? 0 : channels.getUnchecked(0)->getSize();
  17636. output.write ("jatm", 4);
  17637. output.writeInt (samplesPerThumbSample);
  17638. output.writeInt64 (totalSamples);
  17639. output.writeInt64 (numSamplesFinished);
  17640. output.writeInt (numThumbnailSamples);
  17641. output.writeInt (numChannels);
  17642. output.writeInt ((int) sampleRate);
  17643. output.writeInt64 (0);
  17644. output.writeInt64 (0);
  17645. for (int i = 0; i < numThumbnailSamples; ++i)
  17646. for (int chan = 0; chan < numChannels; ++chan)
  17647. channels.getUnchecked(chan)->getData(i)->write (output);
  17648. }
  17649. bool AudioThumbnail::setDataSource (LevelDataSource* newSource)
  17650. {
  17651. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  17652. numSamplesFinished = 0;
  17653. if (cache.loadThumb (*this, newSource->hashCode) && isFullyLoaded())
  17654. {
  17655. source = newSource; // (make sure this isn't done before loadThumb is called)
  17656. source->lengthInSamples = totalSamples;
  17657. source->sampleRate = sampleRate;
  17658. source->numChannels = numChannels;
  17659. source->numSamplesFinished = numSamplesFinished;
  17660. }
  17661. else
  17662. {
  17663. source = newSource; // (make sure this isn't done before loadThumb is called)
  17664. const ScopedLock sl (lock);
  17665. source->initialise (numSamplesFinished);
  17666. totalSamples = source->lengthInSamples;
  17667. sampleRate = source->sampleRate;
  17668. numChannels = source->numChannels;
  17669. createChannels (1 + (int) (totalSamples / samplesPerThumbSample));
  17670. }
  17671. return sampleRate > 0 && totalSamples > 0;
  17672. }
  17673. bool AudioThumbnail::setSource (InputSource* const newSource)
  17674. {
  17675. clear();
  17676. return newSource != 0 && setDataSource (new LevelDataSource (*this, newSource));
  17677. }
  17678. void AudioThumbnail::setReader (AudioFormatReader* newReader, int64 hash)
  17679. {
  17680. clear();
  17681. if (newReader != 0)
  17682. setDataSource (new LevelDataSource (*this, newReader, hash));
  17683. }
  17684. int64 AudioThumbnail::getHashCode() const
  17685. {
  17686. return source == 0 ? 0 : source->hashCode;
  17687. }
  17688. void AudioThumbnail::addBlock (const int64 startSample, const AudioSampleBuffer& incoming,
  17689. int startOffsetInBuffer, int numSamples)
  17690. {
  17691. jassert (startSample >= 0);
  17692. const int firstThumbIndex = (int) (startSample / samplesPerThumbSample);
  17693. const int lastThumbIndex = (int) ((startSample + numSamples + (samplesPerThumbSample - 1)) / samplesPerThumbSample);
  17694. const int numToDo = lastThumbIndex - firstThumbIndex;
  17695. if (numToDo > 0)
  17696. {
  17697. const int numChans = jmin (channels.size(), incoming.getNumChannels());
  17698. const HeapBlock<MinMaxValue> thumbData (numToDo * numChans);
  17699. const HeapBlock<MinMaxValue*> thumbChannels (numChans);
  17700. for (int chan = 0; chan < numChans; ++chan)
  17701. {
  17702. const float* const sourceData = incoming.getSampleData (chan, startOffsetInBuffer);
  17703. MinMaxValue* const dest = thumbData + numToDo * chan;
  17704. thumbChannels [chan] = dest;
  17705. for (int i = 0; i < numToDo; ++i)
  17706. {
  17707. float low, high;
  17708. const int start = i * samplesPerThumbSample;
  17709. findMinAndMax (sourceData + start, jmin (samplesPerThumbSample, numSamples - start), low, high);
  17710. dest[i].setFloat (low, high);
  17711. }
  17712. }
  17713. setLevels (thumbChannels, firstThumbIndex, numChans, numToDo);
  17714. }
  17715. }
  17716. void AudioThumbnail::setLevels (const MinMaxValue* const* values, int thumbIndex, int numChans, int numValues)
  17717. {
  17718. const ScopedLock sl (lock);
  17719. for (int i = jmin (numChans, channels.size()); --i >= 0;)
  17720. channels.getUnchecked(i)->write (values[i], thumbIndex, numValues);
  17721. numSamplesFinished = jmax (numSamplesFinished, (thumbIndex + numValues) * (int64) samplesPerThumbSample);
  17722. totalSamples = jmax (numSamplesFinished, totalSamples);
  17723. window->invalidate();
  17724. sendChangeMessage();
  17725. }
  17726. int AudioThumbnail::getNumChannels() const throw()
  17727. {
  17728. return numChannels;
  17729. }
  17730. double AudioThumbnail::getTotalLength() const throw()
  17731. {
  17732. return totalSamples / sampleRate;
  17733. }
  17734. bool AudioThumbnail::isFullyLoaded() const throw()
  17735. {
  17736. return numSamplesFinished >= totalSamples - samplesPerThumbSample;
  17737. }
  17738. int64 AudioThumbnail::getNumSamplesFinished() const throw()
  17739. {
  17740. return numSamplesFinished;
  17741. }
  17742. float AudioThumbnail::getApproximatePeak() const
  17743. {
  17744. int peak = 0;
  17745. for (int i = channels.size(); --i >= 0;)
  17746. peak = jmax (peak, channels.getUnchecked(i)->getPeak());
  17747. return jlimit (0, 127, peak) / 127.0f;
  17748. }
  17749. void AudioThumbnail::drawChannel (Graphics& g, const Rectangle<int>& area, double startTime,
  17750. double endTime, int channelNum, float verticalZoomFactor)
  17751. {
  17752. const ScopedLock sl (lock);
  17753. window->drawChannel (g, area, startTime, endTime, channelNum, verticalZoomFactor,
  17754. sampleRate, numChannels, samplesPerThumbSample, source, channels);
  17755. }
  17756. void AudioThumbnail::drawChannels (Graphics& g, const Rectangle<int>& area, double startTimeSeconds,
  17757. double endTimeSeconds, float verticalZoomFactor)
  17758. {
  17759. for (int i = 0; i < numChannels; ++i)
  17760. {
  17761. const int y1 = roundToInt ((i * area.getHeight()) / numChannels);
  17762. const int y2 = roundToInt (((i + 1) * area.getHeight()) / numChannels);
  17763. drawChannel (g, Rectangle<int> (area.getX(), area.getY() + y1, area.getWidth(), y2 - y1),
  17764. startTimeSeconds, endTimeSeconds, i, verticalZoomFactor);
  17765. }
  17766. }
  17767. END_JUCE_NAMESPACE
  17768. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  17769. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  17770. BEGIN_JUCE_NAMESPACE
  17771. struct ThumbnailCacheEntry
  17772. {
  17773. int64 hash;
  17774. uint32 lastUsed;
  17775. MemoryBlock data;
  17776. JUCE_LEAK_DETECTOR (ThumbnailCacheEntry);
  17777. };
  17778. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  17779. : TimeSliceThread ("thumb cache"),
  17780. maxNumThumbsToStore (maxNumThumbsToStore_)
  17781. {
  17782. startThread (2);
  17783. }
  17784. AudioThumbnailCache::~AudioThumbnailCache()
  17785. {
  17786. }
  17787. ThumbnailCacheEntry* AudioThumbnailCache::findThumbFor (const int64 hash) const
  17788. {
  17789. for (int i = thumbs.size(); --i >= 0;)
  17790. if (thumbs.getUnchecked(i)->hash == hash)
  17791. return thumbs.getUnchecked(i);
  17792. return 0;
  17793. }
  17794. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  17795. {
  17796. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17797. if (te != 0)
  17798. {
  17799. te->lastUsed = Time::getMillisecondCounter();
  17800. MemoryInputStream in (te->data, false);
  17801. thumb.loadFrom (in);
  17802. return true;
  17803. }
  17804. return false;
  17805. }
  17806. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  17807. const int64 hashCode)
  17808. {
  17809. ThumbnailCacheEntry* te = findThumbFor (hashCode);
  17810. if (te == 0)
  17811. {
  17812. te = new ThumbnailCacheEntry();
  17813. te->hash = hashCode;
  17814. if (thumbs.size() < maxNumThumbsToStore)
  17815. {
  17816. thumbs.add (te);
  17817. }
  17818. else
  17819. {
  17820. int oldest = 0;
  17821. uint32 oldestTime = Time::getMillisecondCounter() + 1;
  17822. for (int i = thumbs.size(); --i >= 0;)
  17823. {
  17824. if (thumbs.getUnchecked(i)->lastUsed < oldestTime)
  17825. {
  17826. oldest = i;
  17827. oldestTime = thumbs.getUnchecked(i)->lastUsed;
  17828. }
  17829. }
  17830. thumbs.set (oldest, te);
  17831. }
  17832. }
  17833. te->lastUsed = Time::getMillisecondCounter();
  17834. MemoryOutputStream out (te->data, false);
  17835. thumb.saveTo (out);
  17836. }
  17837. void AudioThumbnailCache::clear()
  17838. {
  17839. thumbs.clear();
  17840. }
  17841. END_JUCE_NAMESPACE
  17842. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  17843. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  17844. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  17845. #if ! JUCE_WINDOWS
  17846. #include <QuickTime/Movies.h>
  17847. #include <QuickTime/QTML.h>
  17848. #include <QuickTime/QuickTimeComponents.h>
  17849. #include <QuickTime/MediaHandlers.h>
  17850. #include <QuickTime/ImageCodec.h>
  17851. #else
  17852. #if JUCE_MSVC
  17853. #pragma warning (push)
  17854. #pragma warning (disable : 4100)
  17855. #endif
  17856. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  17857. add its header directory to your include path.
  17858. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  17859. flag in juce_Config.h
  17860. */
  17861. #include <Movies.h>
  17862. #include <QTML.h>
  17863. #include <QuickTimeComponents.h>
  17864. #include <MediaHandlers.h>
  17865. #include <ImageCodec.h>
  17866. #if JUCE_MSVC
  17867. #pragma warning (pop)
  17868. #endif
  17869. #endif
  17870. BEGIN_JUCE_NAMESPACE
  17871. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  17872. static const char* const quickTimeFormatName = "QuickTime file";
  17873. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  17874. class QTAudioReader : public AudioFormatReader
  17875. {
  17876. public:
  17877. QTAudioReader (InputStream* const input_, const int trackNum_)
  17878. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  17879. ok (false),
  17880. movie (0),
  17881. trackNum (trackNum_),
  17882. lastSampleRead (0),
  17883. lastThreadId (0),
  17884. extractor (0),
  17885. dataHandle (0)
  17886. {
  17887. JUCE_AUTORELEASEPOOL
  17888. bufferList.calloc (256, 1);
  17889. #if JUCE_WINDOWS
  17890. if (InitializeQTML (0) != noErr)
  17891. return;
  17892. #endif
  17893. if (EnterMovies() != noErr)
  17894. return;
  17895. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  17896. if (! opened)
  17897. return;
  17898. {
  17899. const int numTracks = GetMovieTrackCount (movie);
  17900. int trackCount = 0;
  17901. for (int i = 1; i <= numTracks; ++i)
  17902. {
  17903. track = GetMovieIndTrack (movie, i);
  17904. media = GetTrackMedia (track);
  17905. OSType mediaType;
  17906. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  17907. if (mediaType == SoundMediaType
  17908. && trackCount++ == trackNum_)
  17909. {
  17910. ok = true;
  17911. break;
  17912. }
  17913. }
  17914. }
  17915. if (! ok)
  17916. return;
  17917. ok = false;
  17918. lengthInSamples = GetMediaDecodeDuration (media);
  17919. usesFloatingPointData = false;
  17920. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  17921. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  17922. / GetMediaTimeScale (media);
  17923. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  17924. unsigned long output_layout_size;
  17925. err = MovieAudioExtractionGetPropertyInfo (extractor,
  17926. kQTPropertyClass_MovieAudioExtraction_Audio,
  17927. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17928. 0, &output_layout_size, 0);
  17929. if (err != noErr)
  17930. return;
  17931. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  17932. qt_audio_channel_layout.calloc (output_layout_size, 1);
  17933. err = MovieAudioExtractionGetProperty (extractor,
  17934. kQTPropertyClass_MovieAudioExtraction_Audio,
  17935. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17936. output_layout_size, qt_audio_channel_layout, 0);
  17937. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  17938. err = MovieAudioExtractionSetProperty (extractor,
  17939. kQTPropertyClass_MovieAudioExtraction_Audio,
  17940. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  17941. output_layout_size,
  17942. qt_audio_channel_layout);
  17943. err = MovieAudioExtractionGetProperty (extractor,
  17944. kQTPropertyClass_MovieAudioExtraction_Audio,
  17945. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17946. sizeof (inputStreamDesc),
  17947. &inputStreamDesc, 0);
  17948. if (err != noErr)
  17949. return;
  17950. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  17951. | kAudioFormatFlagIsPacked
  17952. | kAudioFormatFlagsNativeEndian;
  17953. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  17954. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  17955. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  17956. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  17957. err = MovieAudioExtractionSetProperty (extractor,
  17958. kQTPropertyClass_MovieAudioExtraction_Audio,
  17959. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  17960. sizeof (inputStreamDesc),
  17961. &inputStreamDesc);
  17962. if (err != noErr)
  17963. return;
  17964. Boolean allChannelsDiscrete = false;
  17965. err = MovieAudioExtractionSetProperty (extractor,
  17966. kQTPropertyClass_MovieAudioExtraction_Movie,
  17967. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  17968. sizeof (allChannelsDiscrete),
  17969. &allChannelsDiscrete);
  17970. if (err != noErr)
  17971. return;
  17972. bufferList->mNumberBuffers = 1;
  17973. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  17974. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  17975. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  17976. bufferList->mBuffers[0].mData = dataBuffer;
  17977. sampleRate = inputStreamDesc.mSampleRate;
  17978. bitsPerSample = 16;
  17979. numChannels = inputStreamDesc.mChannelsPerFrame;
  17980. detachThread();
  17981. ok = true;
  17982. }
  17983. ~QTAudioReader()
  17984. {
  17985. JUCE_AUTORELEASEPOOL
  17986. checkThreadIsAttached();
  17987. if (dataHandle != 0)
  17988. DisposeHandle (dataHandle);
  17989. if (extractor != 0)
  17990. {
  17991. MovieAudioExtractionEnd (extractor);
  17992. extractor = 0;
  17993. }
  17994. DisposeMovie (movie);
  17995. #if JUCE_MAC
  17996. ExitMoviesOnThread ();
  17997. #endif
  17998. }
  17999. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18000. int64 startSampleInFile, int numSamples)
  18001. {
  18002. JUCE_AUTORELEASEPOOL
  18003. checkThreadIsAttached();
  18004. bool ok = true;
  18005. while (numSamples > 0)
  18006. {
  18007. if (lastSampleRead != startSampleInFile)
  18008. {
  18009. TimeRecord time;
  18010. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18011. time.base = 0;
  18012. time.value.hi = 0;
  18013. time.value.lo = (UInt32) startSampleInFile;
  18014. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18015. kQTPropertyClass_MovieAudioExtraction_Movie,
  18016. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18017. sizeof (time), &time);
  18018. if (err != noErr)
  18019. {
  18020. ok = false;
  18021. break;
  18022. }
  18023. }
  18024. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18025. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18026. UInt32 outFlags = 0;
  18027. UInt32 actualNumFrames = framesToDo;
  18028. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18029. if (err != noErr)
  18030. {
  18031. ok = false;
  18032. break;
  18033. }
  18034. lastSampleRead = startSampleInFile + actualNumFrames;
  18035. const int samplesReceived = actualNumFrames;
  18036. for (int j = numDestChannels; --j >= 0;)
  18037. {
  18038. if (destSamples[j] != 0)
  18039. {
  18040. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18041. for (int i = 0; i < samplesReceived; ++i)
  18042. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18043. }
  18044. }
  18045. startOffsetInDestBuffer += samplesReceived;
  18046. startSampleInFile += samplesReceived;
  18047. numSamples -= samplesReceived;
  18048. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18049. {
  18050. for (int j = numDestChannels; --j >= 0;)
  18051. if (destSamples[j] != 0)
  18052. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18053. break;
  18054. }
  18055. }
  18056. detachThread();
  18057. return ok;
  18058. }
  18059. bool ok;
  18060. private:
  18061. Movie movie;
  18062. Media media;
  18063. Track track;
  18064. const int trackNum;
  18065. double trackUnitsPerFrame;
  18066. int samplesPerFrame;
  18067. int64 lastSampleRead;
  18068. Thread::ThreadID lastThreadId;
  18069. MovieAudioExtractionRef extractor;
  18070. AudioStreamBasicDescription inputStreamDesc;
  18071. HeapBlock <AudioBufferList> bufferList;
  18072. HeapBlock <char> dataBuffer;
  18073. Handle dataHandle;
  18074. void checkThreadIsAttached()
  18075. {
  18076. #if JUCE_MAC
  18077. if (Thread::getCurrentThreadId() != lastThreadId)
  18078. EnterMoviesOnThread (0);
  18079. AttachMovieToCurrentThread (movie);
  18080. #endif
  18081. }
  18082. void detachThread()
  18083. {
  18084. #if JUCE_MAC
  18085. DetachMovieFromCurrentThread (movie);
  18086. #endif
  18087. }
  18088. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (QTAudioReader);
  18089. };
  18090. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18091. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18092. {
  18093. }
  18094. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18095. {
  18096. }
  18097. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18098. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18099. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18100. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18101. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18102. const bool deleteStreamIfOpeningFails)
  18103. {
  18104. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18105. if (r->ok)
  18106. return r.release();
  18107. if (! deleteStreamIfOpeningFails)
  18108. r->input = 0;
  18109. return 0;
  18110. }
  18111. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18112. double /*sampleRateToUse*/,
  18113. unsigned int /*numberOfChannels*/,
  18114. int /*bitsPerSample*/,
  18115. const StringPairArray& /*metadataValues*/,
  18116. int /*qualityOptionIndex*/)
  18117. {
  18118. jassertfalse; // not yet implemented!
  18119. return 0;
  18120. }
  18121. END_JUCE_NAMESPACE
  18122. #endif
  18123. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18124. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18125. BEGIN_JUCE_NAMESPACE
  18126. static const char* const wavFormatName = "WAV file";
  18127. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18128. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18129. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18130. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18131. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18132. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18133. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18134. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18135. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18136. const String& originator,
  18137. const String& originatorRef,
  18138. const Time& date,
  18139. const int64 timeReferenceSamples,
  18140. const String& codingHistory)
  18141. {
  18142. StringPairArray m;
  18143. m.set (bwavDescription, description);
  18144. m.set (bwavOriginator, originator);
  18145. m.set (bwavOriginatorRef, originatorRef);
  18146. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18147. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18148. m.set (bwavTimeReference, String (timeReferenceSamples));
  18149. m.set (bwavCodingHistory, codingHistory);
  18150. return m;
  18151. }
  18152. namespace WavFileHelpers
  18153. {
  18154. #if JUCE_MSVC
  18155. #pragma pack (push, 1)
  18156. #define PACKED
  18157. #elif JUCE_GCC
  18158. #define PACKED __attribute__((packed))
  18159. #else
  18160. #define PACKED
  18161. #endif
  18162. struct BWAVChunk
  18163. {
  18164. char description [256];
  18165. char originator [32];
  18166. char originatorRef [32];
  18167. char originationDate [10];
  18168. char originationTime [8];
  18169. uint32 timeRefLow;
  18170. uint32 timeRefHigh;
  18171. uint16 version;
  18172. uint8 umid[64];
  18173. uint8 reserved[190];
  18174. char codingHistory[1];
  18175. void copyTo (StringPairArray& values) const
  18176. {
  18177. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18178. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18179. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18180. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18181. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18182. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18183. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18184. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18185. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18186. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18187. }
  18188. static MemoryBlock createFrom (const StringPairArray& values)
  18189. {
  18190. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18191. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18192. data.fillWith (0);
  18193. BWAVChunk* b = (BWAVChunk*) data.getData();
  18194. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18195. // as they get called in the right order..
  18196. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18197. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18198. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18199. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18200. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18201. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18202. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18203. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18204. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18205. if (b->description[0] != 0
  18206. || b->originator[0] != 0
  18207. || b->originationDate[0] != 0
  18208. || b->originationTime[0] != 0
  18209. || b->codingHistory[0] != 0
  18210. || time != 0)
  18211. {
  18212. return data;
  18213. }
  18214. return MemoryBlock();
  18215. }
  18216. } PACKED;
  18217. struct SMPLChunk
  18218. {
  18219. struct SampleLoop
  18220. {
  18221. uint32 identifier;
  18222. uint32 type;
  18223. uint32 start;
  18224. uint32 end;
  18225. uint32 fraction;
  18226. uint32 playCount;
  18227. } PACKED;
  18228. uint32 manufacturer;
  18229. uint32 product;
  18230. uint32 samplePeriod;
  18231. uint32 midiUnityNote;
  18232. uint32 midiPitchFraction;
  18233. uint32 smpteFormat;
  18234. uint32 smpteOffset;
  18235. uint32 numSampleLoops;
  18236. uint32 samplerData;
  18237. SampleLoop loops[1];
  18238. void copyTo (StringPairArray& values, const int totalSize) const
  18239. {
  18240. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18241. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18242. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18243. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18244. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18245. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18246. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18247. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18248. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18249. for (uint32 i = 0; i < numSampleLoops; ++i)
  18250. {
  18251. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18252. break;
  18253. const String prefix ("Loop" + String(i));
  18254. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18255. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18256. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18257. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18258. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18259. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18260. }
  18261. }
  18262. static MemoryBlock createFrom (const StringPairArray& values)
  18263. {
  18264. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18265. if (numLoops <= 0)
  18266. return MemoryBlock();
  18267. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18268. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18269. data.fillWith (0);
  18270. SMPLChunk* s = (SMPLChunk*) data.getData();
  18271. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18272. // as they get called in the right order..
  18273. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18274. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18275. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18276. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18277. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18278. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18279. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18280. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18281. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18282. for (int i = 0; i < numLoops; ++i)
  18283. {
  18284. const String prefix ("Loop" + String(i));
  18285. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18286. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18287. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18288. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18289. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18290. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18291. }
  18292. return data;
  18293. }
  18294. } PACKED;
  18295. struct ExtensibleWavSubFormat
  18296. {
  18297. uint32 data1;
  18298. uint16 data2;
  18299. uint16 data3;
  18300. uint8 data4[8];
  18301. } PACKED;
  18302. struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise
  18303. {
  18304. uint32 riffSizeLow; // low 4 byte size of RF64 block
  18305. uint32 riffSizeHigh; // high 4 byte size of RF64 block
  18306. uint32 dataSizeLow; // low 4 byte size of data chunk
  18307. uint32 dataSizeHigh; // high 4 byte size of data chunk
  18308. uint32 sampleCountLow; // low 4 byte sample count of fact chunk
  18309. uint32 sampleCountHigh; // high 4 byte sample count of fact chunk
  18310. uint32 tableLength; // number of valid entries in array 'table'
  18311. } PACKED;
  18312. #if JUCE_MSVC
  18313. #pragma pack (pop)
  18314. #endif
  18315. #undef PACKED
  18316. inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18317. }
  18318. class WavAudioFormatReader : public AudioFormatReader
  18319. {
  18320. public:
  18321. WavAudioFormatReader (InputStream* const in)
  18322. : AudioFormatReader (in, TRANS (wavFormatName)),
  18323. bwavChunkStart (0),
  18324. bwavSize (0),
  18325. dataLength (0),
  18326. isRF64 (false)
  18327. {
  18328. using namespace WavFileHelpers;
  18329. uint64 len = 0;
  18330. int64 end = 0;
  18331. bool hasGotType = false;
  18332. bool hasGotData = false;
  18333. const int firstChunkType = input->readInt();
  18334. if (firstChunkType == chunkName ("RF64"))
  18335. {
  18336. input->skipNextBytes (4); // size is -1 for RF64
  18337. isRF64 = true;
  18338. }
  18339. else if (firstChunkType == chunkName ("RIFF"))
  18340. {
  18341. len = (uint64) input->readInt();
  18342. end = input->getPosition() + len;
  18343. }
  18344. else
  18345. {
  18346. return;
  18347. }
  18348. const int64 startOfRIFFChunk = input->getPosition();
  18349. if (input->readInt() == chunkName ("WAVE"))
  18350. {
  18351. if (isRF64 && input->readInt() == chunkName ("ds64"))
  18352. {
  18353. uint32 length = (uint32) input->readInt();
  18354. if (length < 28)
  18355. {
  18356. return;
  18357. }
  18358. else
  18359. {
  18360. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18361. len = input->readInt64();
  18362. end = startOfRIFFChunk + len;
  18363. dataLength = input->readInt64();
  18364. input->setPosition (chunkEnd);
  18365. }
  18366. }
  18367. while (input->getPosition() < end && ! input->isExhausted())
  18368. {
  18369. const int chunkType = input->readInt();
  18370. uint32 length = (uint32) input->readInt();
  18371. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18372. if (chunkType == chunkName ("fmt "))
  18373. {
  18374. // read the format chunk
  18375. const unsigned short format = input->readShort();
  18376. const short numChans = input->readShort();
  18377. sampleRate = input->readInt();
  18378. const int bytesPerSec = input->readInt();
  18379. numChannels = numChans;
  18380. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18381. bitsPerSample = 8 * bytesPerFrame / numChans;
  18382. if (format == 3)
  18383. {
  18384. usesFloatingPointData = true;
  18385. }
  18386. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18387. {
  18388. if (length < 40) // too short
  18389. {
  18390. bytesPerFrame = 0;
  18391. }
  18392. else
  18393. {
  18394. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18395. ExtensibleWavSubFormat subFormat;
  18396. subFormat.data1 = input->readInt();
  18397. subFormat.data2 = input->readShort();
  18398. subFormat.data3 = input->readShort();
  18399. input->read (subFormat.data4, sizeof (subFormat.data4));
  18400. const ExtensibleWavSubFormat pcmFormat
  18401. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18402. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18403. {
  18404. const ExtensibleWavSubFormat ambisonicFormat
  18405. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18406. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18407. bytesPerFrame = 0;
  18408. }
  18409. }
  18410. }
  18411. else if (format != 1)
  18412. {
  18413. bytesPerFrame = 0;
  18414. }
  18415. hasGotType = true;
  18416. }
  18417. else if (chunkType == chunkName ("data"))
  18418. {
  18419. // get the data chunk's position
  18420. if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk
  18421. dataLength = length;
  18422. dataChunkStart = input->getPosition();
  18423. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18424. hasGotData = true;
  18425. }
  18426. else if (chunkType == chunkName ("bext"))
  18427. {
  18428. bwavChunkStart = input->getPosition();
  18429. bwavSize = length;
  18430. // Broadcast-wav extension chunk..
  18431. HeapBlock <BWAVChunk> bwav;
  18432. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18433. input->read (bwav, length);
  18434. bwav->copyTo (metadataValues);
  18435. }
  18436. else if (chunkType == chunkName ("smpl"))
  18437. {
  18438. HeapBlock <SMPLChunk> smpl;
  18439. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18440. input->read (smpl, length);
  18441. smpl->copyTo (metadataValues, length);
  18442. }
  18443. else if (chunkEnd <= input->getPosition())
  18444. {
  18445. break;
  18446. }
  18447. input->setPosition (chunkEnd);
  18448. }
  18449. }
  18450. }
  18451. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18452. int64 startSampleInFile, int numSamples)
  18453. {
  18454. jassert (destSamples != 0);
  18455. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18456. if (samplesAvailable < numSamples)
  18457. {
  18458. for (int i = numDestChannels; --i >= 0;)
  18459. if (destSamples[i] != 0)
  18460. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18461. numSamples = (int) samplesAvailable;
  18462. }
  18463. if (numSamples <= 0)
  18464. return true;
  18465. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18466. while (numSamples > 0)
  18467. {
  18468. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18469. char tempBuffer [tempBufSize];
  18470. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18471. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18472. if (bytesRead < numThisTime * bytesPerFrame)
  18473. {
  18474. jassert (bytesRead >= 0);
  18475. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18476. }
  18477. switch (bitsPerSample)
  18478. {
  18479. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18480. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18481. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18482. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18483. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18484. default: jassertfalse; break;
  18485. }
  18486. startOffsetInDestBuffer += numThisTime;
  18487. numSamples -= numThisTime;
  18488. }
  18489. return true;
  18490. }
  18491. int64 bwavChunkStart, bwavSize;
  18492. private:
  18493. ScopedPointer<AudioData::Converter> converter;
  18494. int bytesPerFrame;
  18495. int64 dataChunkStart, dataLength;
  18496. bool isRF64;
  18497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader);
  18498. };
  18499. class WavAudioFormatWriter : public AudioFormatWriter
  18500. {
  18501. public:
  18502. WavAudioFormatWriter (OutputStream* const out, const double sampleRate_,
  18503. const unsigned int numChannels_, const int bits,
  18504. const StringPairArray& metadataValues)
  18505. : AudioFormatWriter (out, TRANS (wavFormatName), sampleRate_, numChannels_, bits),
  18506. lengthInSamples (0),
  18507. bytesWritten (0),
  18508. writeFailed (false)
  18509. {
  18510. using namespace WavFileHelpers;
  18511. if (metadataValues.size() > 0)
  18512. {
  18513. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18514. smplChunk = SMPLChunk::createFrom (metadataValues);
  18515. }
  18516. headerPosition = out->getPosition();
  18517. writeHeader();
  18518. }
  18519. ~WavAudioFormatWriter()
  18520. {
  18521. if ((bytesWritten & 1) != 0) // pad to an even length
  18522. {
  18523. ++bytesWritten;
  18524. output->writeByte (0);
  18525. }
  18526. writeHeader();
  18527. }
  18528. bool write (const int** data, int numSamples)
  18529. {
  18530. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18531. if (writeFailed)
  18532. return false;
  18533. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18534. tempBlock.ensureSize (bytes, false);
  18535. switch (bitsPerSample)
  18536. {
  18537. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18538. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18539. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18540. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18541. default: jassertfalse; break;
  18542. }
  18543. if (! output->write (tempBlock.getData(), bytes))
  18544. {
  18545. // failed to write to disk, so let's try writing the header.
  18546. // If it's just run out of disk space, then if it does manage
  18547. // to write the header, we'll still have a useable file..
  18548. writeHeader();
  18549. writeFailed = true;
  18550. return false;
  18551. }
  18552. else
  18553. {
  18554. bytesWritten += bytes;
  18555. lengthInSamples += numSamples;
  18556. return true;
  18557. }
  18558. }
  18559. private:
  18560. ScopedPointer<AudioData::Converter> converter;
  18561. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18562. uint64 lengthInSamples, bytesWritten;
  18563. int64 headerPosition;
  18564. bool writeFailed;
  18565. static int getChannelMask (const int numChannels) throw()
  18566. {
  18567. switch (numChannels)
  18568. {
  18569. case 1: return 0;
  18570. case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT
  18571. case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18572. case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT
  18573. default: break;
  18574. }
  18575. return 0;
  18576. }
  18577. void writeHeader()
  18578. {
  18579. using namespace WavFileHelpers;
  18580. const bool seekedOk = output->setPosition (headerPosition);
  18581. (void) seekedOk;
  18582. // if this fails, you've given it an output stream that can't seek! It needs
  18583. // to be able to seek back to write the header
  18584. jassert (seekedOk);
  18585. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18586. int64 audioDataSize = bytesPerFrame * lengthInSamples;
  18587. const bool isRF64 = (bytesWritten >= literal64bit (0x100000000));
  18588. int64 riffChunkSize = 4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */
  18589. + 8 + audioDataSize + (audioDataSize & 1)
  18590. + (bwavChunk.getSize() > 0 ? (8 + bwavChunk.getSize()) : 0)
  18591. + (smplChunk.getSize() > 0 ? (8 + smplChunk.getSize()) : 0)
  18592. + (8 + 28); // (ds64 chunk)
  18593. riffChunkSize += (riffChunkSize & 0x1);
  18594. output->writeInt (chunkName (isRF64 ? "RF64" : "RIFF"));
  18595. output->writeInt (isRF64 ? -1 : (int) riffChunkSize);
  18596. output->writeInt (chunkName ("WAVE"));
  18597. if (! isRF64)
  18598. {
  18599. output->writeInt (chunkName ("JUNK"));
  18600. output->writeInt (28 + 24);
  18601. output->writeRepeatedByte (0, 28 /* ds64 */ + 24 /* extra waveformatex */);
  18602. }
  18603. else
  18604. {
  18605. // write ds64 chunk
  18606. output->writeInt (chunkName ("ds64"));
  18607. output->writeInt (28); // chunk size for uncompressed data (no table)
  18608. output->writeInt64 (riffChunkSize);
  18609. output->writeInt64 (audioDataSize);
  18610. output->writeRepeatedByte (0, 12);
  18611. }
  18612. output->writeInt (chunkName ("fmt "));
  18613. if (isRF64)
  18614. {
  18615. output->writeInt (40); // chunk size
  18616. output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE
  18617. }
  18618. else
  18619. {
  18620. output->writeInt (16); // chunk size
  18621. output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/
  18622. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18623. }
  18624. output->writeShort ((short) numChannels);
  18625. output->writeInt ((int) sampleRate);
  18626. output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec
  18627. output->writeShort ((short) bytesPerFrame); // nBlockAlign
  18628. output->writeShort ((short) bitsPerSample); // wBitsPerSample
  18629. if (isRF64)
  18630. {
  18631. output->writeShort (22); // cbSize (size of the extension)
  18632. output->writeShort ((short) bitsPerSample); // wValidBitsPerSample
  18633. output->writeInt (getChannelMask (numChannels));
  18634. const ExtensibleWavSubFormat pcmFormat
  18635. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18636. const ExtensibleWavSubFormat IEEEFloatFormat
  18637. = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18638. const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat;
  18639. output->writeInt ((int) subFormat.data1);
  18640. output->writeShort ((short) subFormat.data2);
  18641. output->writeShort ((short) subFormat.data3);
  18642. output->write (subFormat.data4, sizeof (subFormat.data4));
  18643. }
  18644. if (bwavChunk.getSize() > 0)
  18645. {
  18646. output->writeInt (chunkName ("bext"));
  18647. output->writeInt ((int) bwavChunk.getSize());
  18648. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18649. }
  18650. if (smplChunk.getSize() > 0)
  18651. {
  18652. output->writeInt (chunkName ("smpl"));
  18653. output->writeInt ((int) smplChunk.getSize());
  18654. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18655. }
  18656. output->writeInt (chunkName ("data"));
  18657. output->writeInt (isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame));
  18658. usesFloatingPointData = (bitsPerSample == 32);
  18659. }
  18660. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter);
  18661. };
  18662. WavAudioFormat::WavAudioFormat()
  18663. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18664. {
  18665. }
  18666. WavAudioFormat::~WavAudioFormat()
  18667. {
  18668. }
  18669. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18670. {
  18671. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18672. return Array <int> (rates);
  18673. }
  18674. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18675. {
  18676. const int depths[] = { 8, 16, 24, 32, 0 };
  18677. return Array <int> (depths);
  18678. }
  18679. bool WavAudioFormat::canDoStereo() { return true; }
  18680. bool WavAudioFormat::canDoMono() { return true; }
  18681. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18682. const bool deleteStreamIfOpeningFails)
  18683. {
  18684. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18685. if (r->sampleRate != 0)
  18686. return r.release();
  18687. if (! deleteStreamIfOpeningFails)
  18688. r->input = 0;
  18689. return 0;
  18690. }
  18691. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate,
  18692. unsigned int numChannels, int bitsPerSample,
  18693. const StringPairArray& metadataValues, int /*qualityOptionIndex*/)
  18694. {
  18695. if (getPossibleBitDepths().contains (bitsPerSample))
  18696. return new WavAudioFormatWriter (out, sampleRate, numChannels, bitsPerSample, metadataValues);
  18697. return 0;
  18698. }
  18699. namespace WavFileHelpers
  18700. {
  18701. bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18702. {
  18703. TemporaryFile tempFile (file);
  18704. WavAudioFormat wav;
  18705. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18706. if (reader != 0)
  18707. {
  18708. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18709. if (outStream != 0)
  18710. {
  18711. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18712. reader->numChannels, reader->bitsPerSample,
  18713. metadata, 0));
  18714. if (writer != 0)
  18715. {
  18716. outStream.release();
  18717. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18718. writer = 0;
  18719. reader = 0;
  18720. return ok && tempFile.overwriteTargetFileWithTemporary();
  18721. }
  18722. }
  18723. }
  18724. return false;
  18725. }
  18726. }
  18727. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18728. {
  18729. using namespace WavFileHelpers;
  18730. ScopedPointer <WavAudioFormatReader> reader (static_cast <WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true)));
  18731. if (reader != 0)
  18732. {
  18733. const int64 bwavPos = reader->bwavChunkStart;
  18734. const int64 bwavSize = reader->bwavSize;
  18735. reader = 0;
  18736. if (bwavSize > 0)
  18737. {
  18738. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18739. if (chunk.getSize() <= (size_t) bwavSize)
  18740. {
  18741. // the new one will fit in the space available, so write it directly..
  18742. const int64 oldSize = wavFile.getSize();
  18743. {
  18744. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18745. out->setPosition (bwavPos);
  18746. out->write (chunk.getData(), (int) chunk.getSize());
  18747. out->setPosition (oldSize);
  18748. }
  18749. jassert (wavFile.getSize() == oldSize);
  18750. return true;
  18751. }
  18752. }
  18753. }
  18754. return slowCopyWavFileWithNewMetadata (wavFile, newMetadata);
  18755. }
  18756. END_JUCE_NAMESPACE
  18757. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18758. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18759. #if JUCE_USE_CDREADER
  18760. BEGIN_JUCE_NAMESPACE
  18761. int AudioCDReader::getNumTracks() const
  18762. {
  18763. return trackStartSamples.size() - 1;
  18764. }
  18765. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18766. {
  18767. return trackStartSamples [trackNum];
  18768. }
  18769. const Array<int>& AudioCDReader::getTrackOffsets() const
  18770. {
  18771. return trackStartSamples;
  18772. }
  18773. int AudioCDReader::getCDDBId()
  18774. {
  18775. int checksum = 0;
  18776. const int numTracks = getNumTracks();
  18777. for (int i = 0; i < numTracks; ++i)
  18778. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18779. checksum += offset % 10;
  18780. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18781. // CCLLLLTT: checksum, length, tracks
  18782. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18783. }
  18784. END_JUCE_NAMESPACE
  18785. #endif
  18786. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18787. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18788. BEGIN_JUCE_NAMESPACE
  18789. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18790. const bool deleteReaderWhenThisIsDeleted)
  18791. : reader (reader_),
  18792. deleteReader (deleteReaderWhenThisIsDeleted),
  18793. nextPlayPos (0),
  18794. looping (false)
  18795. {
  18796. jassert (reader != 0);
  18797. }
  18798. AudioFormatReaderSource::~AudioFormatReaderSource()
  18799. {
  18800. releaseResources();
  18801. if (deleteReader)
  18802. delete reader;
  18803. }
  18804. void AudioFormatReaderSource::setNextReadPosition (int64 newPosition)
  18805. {
  18806. nextPlayPos = newPosition;
  18807. }
  18808. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18809. {
  18810. looping = shouldLoop;
  18811. }
  18812. int64 AudioFormatReaderSource::getNextReadPosition() const
  18813. {
  18814. return looping ? nextPlayPos % reader->lengthInSamples
  18815. : nextPlayPos;
  18816. }
  18817. int64 AudioFormatReaderSource::getTotalLength() const
  18818. {
  18819. return reader->lengthInSamples;
  18820. }
  18821. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18822. double /*sampleRate*/)
  18823. {
  18824. }
  18825. void AudioFormatReaderSource::releaseResources()
  18826. {
  18827. }
  18828. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18829. {
  18830. if (info.numSamples > 0)
  18831. {
  18832. const int64 start = nextPlayPos;
  18833. if (looping)
  18834. {
  18835. const int newStart = start % (int) reader->lengthInSamples;
  18836. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  18837. if (newEnd > newStart)
  18838. {
  18839. info.buffer->readFromAudioReader (reader,
  18840. info.startSample,
  18841. newEnd - newStart,
  18842. newStart,
  18843. true, true);
  18844. }
  18845. else
  18846. {
  18847. const int endSamps = (int) reader->lengthInSamples - newStart;
  18848. info.buffer->readFromAudioReader (reader,
  18849. info.startSample,
  18850. endSamps,
  18851. newStart,
  18852. true, true);
  18853. info.buffer->readFromAudioReader (reader,
  18854. info.startSample + endSamps,
  18855. newEnd,
  18856. 0,
  18857. true, true);
  18858. }
  18859. nextPlayPos = newEnd;
  18860. }
  18861. else
  18862. {
  18863. info.buffer->readFromAudioReader (reader,
  18864. info.startSample,
  18865. info.numSamples,
  18866. start,
  18867. true, true);
  18868. nextPlayPos += info.numSamples;
  18869. }
  18870. }
  18871. }
  18872. END_JUCE_NAMESPACE
  18873. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18874. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  18875. BEGIN_JUCE_NAMESPACE
  18876. AudioSourcePlayer::AudioSourcePlayer()
  18877. : source (0),
  18878. sampleRate (0),
  18879. bufferSize (0),
  18880. tempBuffer (2, 8),
  18881. lastGain (1.0f),
  18882. gain (1.0f)
  18883. {
  18884. }
  18885. AudioSourcePlayer::~AudioSourcePlayer()
  18886. {
  18887. setSource (0);
  18888. }
  18889. void AudioSourcePlayer::setSource (AudioSource* newSource)
  18890. {
  18891. if (source != newSource)
  18892. {
  18893. AudioSource* const oldSource = source;
  18894. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  18895. newSource->prepareToPlay (bufferSize, sampleRate);
  18896. {
  18897. const ScopedLock sl (readLock);
  18898. source = newSource;
  18899. }
  18900. if (oldSource != 0)
  18901. oldSource->releaseResources();
  18902. }
  18903. }
  18904. void AudioSourcePlayer::setGain (const float newGain) throw()
  18905. {
  18906. gain = newGain;
  18907. }
  18908. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  18909. int totalNumInputChannels,
  18910. float** outputChannelData,
  18911. int totalNumOutputChannels,
  18912. int numSamples)
  18913. {
  18914. // these should have been prepared by audioDeviceAboutToStart()...
  18915. jassert (sampleRate > 0 && bufferSize > 0);
  18916. const ScopedLock sl (readLock);
  18917. if (source != 0)
  18918. {
  18919. AudioSourceChannelInfo info;
  18920. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  18921. // messy stuff needed to compact the channels down into an array
  18922. // of non-zero pointers..
  18923. for (i = 0; i < totalNumInputChannels; ++i)
  18924. {
  18925. if (inputChannelData[i] != 0)
  18926. {
  18927. inputChans [numInputs++] = inputChannelData[i];
  18928. if (numInputs >= numElementsInArray (inputChans))
  18929. break;
  18930. }
  18931. }
  18932. for (i = 0; i < totalNumOutputChannels; ++i)
  18933. {
  18934. if (outputChannelData[i] != 0)
  18935. {
  18936. outputChans [numOutputs++] = outputChannelData[i];
  18937. if (numOutputs >= numElementsInArray (outputChans))
  18938. break;
  18939. }
  18940. }
  18941. if (numInputs > numOutputs)
  18942. {
  18943. // if there aren't enough output channels for the number of
  18944. // inputs, we need to create some temporary extra ones (can't
  18945. // use the input data in case it gets written to)
  18946. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  18947. false, false, true);
  18948. for (i = 0; i < numOutputs; ++i)
  18949. {
  18950. channels[numActiveChans] = outputChans[i];
  18951. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18952. ++numActiveChans;
  18953. }
  18954. for (i = numOutputs; i < numInputs; ++i)
  18955. {
  18956. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  18957. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18958. ++numActiveChans;
  18959. }
  18960. }
  18961. else
  18962. {
  18963. for (i = 0; i < numInputs; ++i)
  18964. {
  18965. channels[numActiveChans] = outputChans[i];
  18966. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  18967. ++numActiveChans;
  18968. }
  18969. for (i = numInputs; i < numOutputs; ++i)
  18970. {
  18971. channels[numActiveChans] = outputChans[i];
  18972. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  18973. ++numActiveChans;
  18974. }
  18975. }
  18976. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  18977. info.buffer = &buffer;
  18978. info.startSample = 0;
  18979. info.numSamples = numSamples;
  18980. source->getNextAudioBlock (info);
  18981. for (i = info.buffer->getNumChannels(); --i >= 0;)
  18982. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  18983. lastGain = gain;
  18984. }
  18985. else
  18986. {
  18987. for (int i = 0; i < totalNumOutputChannels; ++i)
  18988. if (outputChannelData[i] != 0)
  18989. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  18990. }
  18991. }
  18992. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  18993. {
  18994. sampleRate = device->getCurrentSampleRate();
  18995. bufferSize = device->getCurrentBufferSizeSamples();
  18996. zeromem (channels, sizeof (channels));
  18997. if (source != 0)
  18998. source->prepareToPlay (bufferSize, sampleRate);
  18999. }
  19000. void AudioSourcePlayer::audioDeviceStopped()
  19001. {
  19002. if (source != 0)
  19003. source->releaseResources();
  19004. sampleRate = 0.0;
  19005. bufferSize = 0;
  19006. tempBuffer.setSize (2, 8);
  19007. }
  19008. END_JUCE_NAMESPACE
  19009. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19010. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19011. BEGIN_JUCE_NAMESPACE
  19012. AudioTransportSource::AudioTransportSource()
  19013. : source (0),
  19014. resamplerSource (0),
  19015. bufferingSource (0),
  19016. positionableSource (0),
  19017. masterSource (0),
  19018. gain (1.0f),
  19019. lastGain (1.0f),
  19020. playing (false),
  19021. stopped (true),
  19022. sampleRate (44100.0),
  19023. sourceSampleRate (0.0),
  19024. blockSize (128),
  19025. readAheadBufferSize (0),
  19026. isPrepared (false),
  19027. inputStreamEOF (false)
  19028. {
  19029. }
  19030. AudioTransportSource::~AudioTransportSource()
  19031. {
  19032. setSource (0);
  19033. releaseResources();
  19034. }
  19035. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19036. int readAheadBufferSize_,
  19037. double sourceSampleRateToCorrectFor,
  19038. int maxNumChannels)
  19039. {
  19040. if (source == newSource)
  19041. {
  19042. if (source == 0)
  19043. return;
  19044. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19045. }
  19046. readAheadBufferSize = readAheadBufferSize_;
  19047. sourceSampleRate = sourceSampleRateToCorrectFor;
  19048. ResamplingAudioSource* newResamplerSource = 0;
  19049. BufferingAudioSource* newBufferingSource = 0;
  19050. PositionableAudioSource* newPositionableSource = 0;
  19051. AudioSource* newMasterSource = 0;
  19052. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19053. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19054. AudioSource* oldMasterSource = masterSource;
  19055. if (newSource != 0)
  19056. {
  19057. newPositionableSource = newSource;
  19058. if (readAheadBufferSize_ > 0)
  19059. newPositionableSource = newBufferingSource
  19060. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19061. newPositionableSource->setNextReadPosition (0);
  19062. if (sourceSampleRateToCorrectFor != 0)
  19063. newMasterSource = newResamplerSource
  19064. = new ResamplingAudioSource (newPositionableSource, false, maxNumChannels);
  19065. else
  19066. newMasterSource = newPositionableSource;
  19067. if (isPrepared)
  19068. {
  19069. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19070. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19071. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19072. }
  19073. }
  19074. {
  19075. const ScopedLock sl (callbackLock);
  19076. source = newSource;
  19077. resamplerSource = newResamplerSource;
  19078. bufferingSource = newBufferingSource;
  19079. masterSource = newMasterSource;
  19080. positionableSource = newPositionableSource;
  19081. playing = false;
  19082. }
  19083. if (oldMasterSource != 0)
  19084. oldMasterSource->releaseResources();
  19085. }
  19086. void AudioTransportSource::start()
  19087. {
  19088. if ((! playing) && masterSource != 0)
  19089. {
  19090. {
  19091. const ScopedLock sl (callbackLock);
  19092. playing = true;
  19093. stopped = false;
  19094. inputStreamEOF = false;
  19095. }
  19096. sendChangeMessage();
  19097. }
  19098. }
  19099. void AudioTransportSource::stop()
  19100. {
  19101. if (playing)
  19102. {
  19103. {
  19104. const ScopedLock sl (callbackLock);
  19105. playing = false;
  19106. }
  19107. int n = 500;
  19108. while (--n >= 0 && ! stopped)
  19109. Thread::sleep (2);
  19110. sendChangeMessage();
  19111. }
  19112. }
  19113. void AudioTransportSource::setPosition (double newPosition)
  19114. {
  19115. if (sampleRate > 0.0)
  19116. setNextReadPosition ((int64) (newPosition * sampleRate));
  19117. }
  19118. double AudioTransportSource::getCurrentPosition() const
  19119. {
  19120. if (sampleRate > 0.0)
  19121. return getNextReadPosition() / sampleRate;
  19122. else
  19123. return 0.0;
  19124. }
  19125. double AudioTransportSource::getLengthInSeconds() const
  19126. {
  19127. return getTotalLength() / sampleRate;
  19128. }
  19129. void AudioTransportSource::setNextReadPosition (int64 newPosition)
  19130. {
  19131. if (positionableSource != 0)
  19132. {
  19133. if (sampleRate > 0 && sourceSampleRate > 0)
  19134. newPosition = (int64) (newPosition * sourceSampleRate / sampleRate);
  19135. positionableSource->setNextReadPosition (newPosition);
  19136. }
  19137. }
  19138. int64 AudioTransportSource::getNextReadPosition() const
  19139. {
  19140. if (positionableSource != 0)
  19141. {
  19142. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19143. return (int64) (positionableSource->getNextReadPosition() * ratio);
  19144. }
  19145. return 0;
  19146. }
  19147. int64 AudioTransportSource::getTotalLength() const
  19148. {
  19149. const ScopedLock sl (callbackLock);
  19150. if (positionableSource != 0)
  19151. {
  19152. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19153. return (int64) (positionableSource->getTotalLength() * ratio);
  19154. }
  19155. return 0;
  19156. }
  19157. bool AudioTransportSource::isLooping() const
  19158. {
  19159. const ScopedLock sl (callbackLock);
  19160. return positionableSource != 0
  19161. && positionableSource->isLooping();
  19162. }
  19163. void AudioTransportSource::setGain (const float newGain) throw()
  19164. {
  19165. gain = newGain;
  19166. }
  19167. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19168. double sampleRate_)
  19169. {
  19170. const ScopedLock sl (callbackLock);
  19171. sampleRate = sampleRate_;
  19172. blockSize = samplesPerBlockExpected;
  19173. if (masterSource != 0)
  19174. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19175. if (resamplerSource != 0 && sourceSampleRate != 0)
  19176. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19177. isPrepared = true;
  19178. }
  19179. void AudioTransportSource::releaseResources()
  19180. {
  19181. const ScopedLock sl (callbackLock);
  19182. if (masterSource != 0)
  19183. masterSource->releaseResources();
  19184. isPrepared = false;
  19185. }
  19186. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19187. {
  19188. const ScopedLock sl (callbackLock);
  19189. inputStreamEOF = false;
  19190. if (masterSource != 0 && ! stopped)
  19191. {
  19192. masterSource->getNextAudioBlock (info);
  19193. if (! playing)
  19194. {
  19195. // just stopped playing, so fade out the last block..
  19196. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19197. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19198. if (info.numSamples > 256)
  19199. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19200. }
  19201. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19202. && ! positionableSource->isLooping())
  19203. {
  19204. playing = false;
  19205. inputStreamEOF = true;
  19206. sendChangeMessage();
  19207. }
  19208. stopped = ! playing;
  19209. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19210. {
  19211. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19212. lastGain, gain);
  19213. }
  19214. }
  19215. else
  19216. {
  19217. info.clearActiveBufferRegion();
  19218. stopped = true;
  19219. }
  19220. lastGain = gain;
  19221. }
  19222. END_JUCE_NAMESPACE
  19223. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19224. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19225. BEGIN_JUCE_NAMESPACE
  19226. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19227. public Thread,
  19228. private Timer
  19229. {
  19230. public:
  19231. SharedBufferingAudioSourceThread()
  19232. : Thread ("Audio Buffer")
  19233. {
  19234. }
  19235. ~SharedBufferingAudioSourceThread()
  19236. {
  19237. stopThread (10000);
  19238. clearSingletonInstance();
  19239. }
  19240. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19241. void addSource (BufferingAudioSource* source)
  19242. {
  19243. const ScopedLock sl (lock);
  19244. if (! sources.contains (source))
  19245. {
  19246. sources.add (source);
  19247. startThread();
  19248. stopTimer();
  19249. }
  19250. notify();
  19251. }
  19252. void removeSource (BufferingAudioSource* source)
  19253. {
  19254. const ScopedLock sl (lock);
  19255. sources.removeValue (source);
  19256. if (sources.size() == 0)
  19257. startTimer (5000);
  19258. }
  19259. private:
  19260. Array <BufferingAudioSource*> sources;
  19261. CriticalSection lock;
  19262. void run()
  19263. {
  19264. while (! threadShouldExit())
  19265. {
  19266. bool busy = false;
  19267. for (int i = sources.size(); --i >= 0;)
  19268. {
  19269. if (threadShouldExit())
  19270. return;
  19271. const ScopedLock sl (lock);
  19272. BufferingAudioSource* const b = sources[i];
  19273. if (b != 0 && b->readNextBufferChunk())
  19274. busy = true;
  19275. }
  19276. if (! busy)
  19277. wait (500);
  19278. }
  19279. }
  19280. void timerCallback()
  19281. {
  19282. stopTimer();
  19283. if (sources.size() == 0)
  19284. deleteInstance();
  19285. }
  19286. JUCE_DECLARE_NON_COPYABLE (SharedBufferingAudioSourceThread);
  19287. };
  19288. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19289. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19290. const bool deleteSourceWhenDeleted_,
  19291. int numberOfSamplesToBuffer_)
  19292. : source (source_),
  19293. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19294. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19295. buffer (2, 0),
  19296. bufferValidStart (0),
  19297. bufferValidEnd (0),
  19298. nextPlayPos (0),
  19299. wasSourceLooping (false)
  19300. {
  19301. jassert (source_ != 0);
  19302. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19303. // not using a larger buffer..
  19304. }
  19305. BufferingAudioSource::~BufferingAudioSource()
  19306. {
  19307. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19308. if (thread != 0)
  19309. thread->removeSource (this);
  19310. if (deleteSourceWhenDeleted)
  19311. delete source;
  19312. }
  19313. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19314. {
  19315. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19316. sampleRate = sampleRate_;
  19317. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19318. buffer.clear();
  19319. bufferValidStart = 0;
  19320. bufferValidEnd = 0;
  19321. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19322. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19323. buffer.getNumSamples() / 2))
  19324. {
  19325. SharedBufferingAudioSourceThread::getInstance()->notify();
  19326. Thread::sleep (5);
  19327. }
  19328. }
  19329. void BufferingAudioSource::releaseResources()
  19330. {
  19331. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19332. if (thread != 0)
  19333. thread->removeSource (this);
  19334. buffer.setSize (2, 0);
  19335. source->releaseResources();
  19336. }
  19337. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19338. {
  19339. const ScopedLock sl (bufferStartPosLock);
  19340. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  19341. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  19342. if (validStart == validEnd)
  19343. {
  19344. // total cache miss
  19345. info.clearActiveBufferRegion();
  19346. }
  19347. else
  19348. {
  19349. if (validStart > 0)
  19350. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19351. if (validEnd < info.numSamples)
  19352. info.buffer->clear (info.startSample + validEnd,
  19353. info.numSamples - validEnd); // partial cache miss at end
  19354. if (validStart < validEnd)
  19355. {
  19356. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19357. {
  19358. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19359. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19360. if (startBufferIndex < endBufferIndex)
  19361. {
  19362. info.buffer->copyFrom (chan, info.startSample + validStart,
  19363. buffer,
  19364. chan, startBufferIndex,
  19365. validEnd - validStart);
  19366. }
  19367. else
  19368. {
  19369. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19370. info.buffer->copyFrom (chan, info.startSample + validStart,
  19371. buffer,
  19372. chan, startBufferIndex,
  19373. initialSize);
  19374. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19375. buffer,
  19376. chan, 0,
  19377. (validEnd - validStart) - initialSize);
  19378. }
  19379. }
  19380. }
  19381. nextPlayPos += info.numSamples;
  19382. if (source->isLooping() && nextPlayPos > 0)
  19383. nextPlayPos %= source->getTotalLength();
  19384. }
  19385. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19386. if (thread != 0)
  19387. thread->notify();
  19388. }
  19389. int64 BufferingAudioSource::getNextReadPosition() const
  19390. {
  19391. return (source->isLooping() && nextPlayPos > 0)
  19392. ? nextPlayPos % source->getTotalLength()
  19393. : nextPlayPos;
  19394. }
  19395. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  19396. {
  19397. const ScopedLock sl (bufferStartPosLock);
  19398. nextPlayPos = newPosition;
  19399. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19400. if (thread != 0)
  19401. thread->notify();
  19402. }
  19403. bool BufferingAudioSource::readNextBufferChunk()
  19404. {
  19405. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19406. {
  19407. const ScopedLock sl (bufferStartPosLock);
  19408. if (wasSourceLooping != isLooping())
  19409. {
  19410. wasSourceLooping = isLooping();
  19411. bufferValidStart = 0;
  19412. bufferValidEnd = 0;
  19413. }
  19414. newBVS = jmax ((int64) 0, nextPlayPos);
  19415. newBVE = newBVS + buffer.getNumSamples() - 4;
  19416. sectionToReadStart = 0;
  19417. sectionToReadEnd = 0;
  19418. const int maxChunkSize = 2048;
  19419. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19420. {
  19421. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19422. sectionToReadStart = newBVS;
  19423. sectionToReadEnd = newBVE;
  19424. bufferValidStart = 0;
  19425. bufferValidEnd = 0;
  19426. }
  19427. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  19428. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  19429. {
  19430. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19431. sectionToReadStart = bufferValidEnd;
  19432. sectionToReadEnd = newBVE;
  19433. bufferValidStart = newBVS;
  19434. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19435. }
  19436. }
  19437. if (sectionToReadStart != sectionToReadEnd)
  19438. {
  19439. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19440. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19441. if (bufferIndexStart < bufferIndexEnd)
  19442. {
  19443. readBufferSection (sectionToReadStart,
  19444. (int) (sectionToReadEnd - sectionToReadStart),
  19445. bufferIndexStart);
  19446. }
  19447. else
  19448. {
  19449. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19450. readBufferSection (sectionToReadStart,
  19451. initialSize,
  19452. bufferIndexStart);
  19453. readBufferSection (sectionToReadStart + initialSize,
  19454. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  19455. 0);
  19456. }
  19457. const ScopedLock sl2 (bufferStartPosLock);
  19458. bufferValidStart = newBVS;
  19459. bufferValidEnd = newBVE;
  19460. return true;
  19461. }
  19462. else
  19463. {
  19464. return false;
  19465. }
  19466. }
  19467. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  19468. {
  19469. if (source->getNextReadPosition() != start)
  19470. source->setNextReadPosition (start);
  19471. AudioSourceChannelInfo info;
  19472. info.buffer = &buffer;
  19473. info.startSample = bufferOffset;
  19474. info.numSamples = length;
  19475. source->getNextAudioBlock (info);
  19476. }
  19477. END_JUCE_NAMESPACE
  19478. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19479. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19480. BEGIN_JUCE_NAMESPACE
  19481. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19482. const bool deleteSourceWhenDeleted_)
  19483. : requiredNumberOfChannels (2),
  19484. source (source_),
  19485. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19486. buffer (2, 16)
  19487. {
  19488. remappedInfo.buffer = &buffer;
  19489. remappedInfo.startSample = 0;
  19490. }
  19491. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19492. {
  19493. if (deleteSourceWhenDeleted)
  19494. delete source;
  19495. }
  19496. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19497. {
  19498. const ScopedLock sl (lock);
  19499. requiredNumberOfChannels = requiredNumberOfChannels_;
  19500. }
  19501. void ChannelRemappingAudioSource::clearAllMappings()
  19502. {
  19503. const ScopedLock sl (lock);
  19504. remappedInputs.clear();
  19505. remappedOutputs.clear();
  19506. }
  19507. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19508. {
  19509. const ScopedLock sl (lock);
  19510. while (remappedInputs.size() < destIndex)
  19511. remappedInputs.add (-1);
  19512. remappedInputs.set (destIndex, sourceIndex);
  19513. }
  19514. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19515. {
  19516. const ScopedLock sl (lock);
  19517. while (remappedOutputs.size() < sourceIndex)
  19518. remappedOutputs.add (-1);
  19519. remappedOutputs.set (sourceIndex, destIndex);
  19520. }
  19521. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19522. {
  19523. const ScopedLock sl (lock);
  19524. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19525. return remappedInputs.getUnchecked (inputChannelIndex);
  19526. return -1;
  19527. }
  19528. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19529. {
  19530. const ScopedLock sl (lock);
  19531. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19532. return remappedOutputs .getUnchecked (outputChannelIndex);
  19533. return -1;
  19534. }
  19535. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19536. {
  19537. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19538. }
  19539. void ChannelRemappingAudioSource::releaseResources()
  19540. {
  19541. source->releaseResources();
  19542. }
  19543. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19544. {
  19545. const ScopedLock sl (lock);
  19546. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19547. const int numChans = bufferToFill.buffer->getNumChannels();
  19548. int i;
  19549. for (i = 0; i < buffer.getNumChannels(); ++i)
  19550. {
  19551. const int remappedChan = getRemappedInputChannel (i);
  19552. if (remappedChan >= 0 && remappedChan < numChans)
  19553. {
  19554. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19555. remappedChan,
  19556. bufferToFill.startSample,
  19557. bufferToFill.numSamples);
  19558. }
  19559. else
  19560. {
  19561. buffer.clear (i, 0, bufferToFill.numSamples);
  19562. }
  19563. }
  19564. remappedInfo.numSamples = bufferToFill.numSamples;
  19565. source->getNextAudioBlock (remappedInfo);
  19566. bufferToFill.clearActiveBufferRegion();
  19567. for (i = 0; i < requiredNumberOfChannels; ++i)
  19568. {
  19569. const int remappedChan = getRemappedOutputChannel (i);
  19570. if (remappedChan >= 0 && remappedChan < numChans)
  19571. {
  19572. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19573. buffer, i, 0, bufferToFill.numSamples);
  19574. }
  19575. }
  19576. }
  19577. XmlElement* ChannelRemappingAudioSource::createXml() const
  19578. {
  19579. XmlElement* e = new XmlElement ("MAPPINGS");
  19580. String ins, outs;
  19581. int i;
  19582. const ScopedLock sl (lock);
  19583. for (i = 0; i < remappedInputs.size(); ++i)
  19584. ins << remappedInputs.getUnchecked(i) << ' ';
  19585. for (i = 0; i < remappedOutputs.size(); ++i)
  19586. outs << remappedOutputs.getUnchecked(i) << ' ';
  19587. e->setAttribute ("inputs", ins.trimEnd());
  19588. e->setAttribute ("outputs", outs.trimEnd());
  19589. return e;
  19590. }
  19591. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19592. {
  19593. if (e.hasTagName ("MAPPINGS"))
  19594. {
  19595. const ScopedLock sl (lock);
  19596. clearAllMappings();
  19597. StringArray ins, outs;
  19598. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19599. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19600. int i;
  19601. for (i = 0; i < ins.size(); ++i)
  19602. remappedInputs.add (ins[i].getIntValue());
  19603. for (i = 0; i < outs.size(); ++i)
  19604. remappedOutputs.add (outs[i].getIntValue());
  19605. }
  19606. }
  19607. END_JUCE_NAMESPACE
  19608. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19609. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19610. BEGIN_JUCE_NAMESPACE
  19611. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19612. const bool deleteInputWhenDeleted_)
  19613. : input (inputSource),
  19614. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19615. {
  19616. jassert (inputSource != 0);
  19617. for (int i = 2; --i >= 0;)
  19618. iirFilters.add (new IIRFilter());
  19619. }
  19620. IIRFilterAudioSource::~IIRFilterAudioSource()
  19621. {
  19622. if (deleteInputWhenDeleted)
  19623. delete input;
  19624. }
  19625. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19626. {
  19627. for (int i = iirFilters.size(); --i >= 0;)
  19628. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19629. }
  19630. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19631. {
  19632. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19633. for (int i = iirFilters.size(); --i >= 0;)
  19634. iirFilters.getUnchecked(i)->reset();
  19635. }
  19636. void IIRFilterAudioSource::releaseResources()
  19637. {
  19638. input->releaseResources();
  19639. }
  19640. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19641. {
  19642. input->getNextAudioBlock (bufferToFill);
  19643. const int numChannels = bufferToFill.buffer->getNumChannels();
  19644. while (numChannels > iirFilters.size())
  19645. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19646. for (int i = 0; i < numChannels; ++i)
  19647. iirFilters.getUnchecked(i)
  19648. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19649. bufferToFill.numSamples);
  19650. }
  19651. END_JUCE_NAMESPACE
  19652. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19653. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19654. BEGIN_JUCE_NAMESPACE
  19655. MixerAudioSource::MixerAudioSource()
  19656. : tempBuffer (2, 0),
  19657. currentSampleRate (0.0),
  19658. bufferSizeExpected (0)
  19659. {
  19660. }
  19661. MixerAudioSource::~MixerAudioSource()
  19662. {
  19663. removeAllInputs();
  19664. }
  19665. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19666. {
  19667. if (input != 0 && ! inputs.contains (input))
  19668. {
  19669. double localRate;
  19670. int localBufferSize;
  19671. {
  19672. const ScopedLock sl (lock);
  19673. localRate = currentSampleRate;
  19674. localBufferSize = bufferSizeExpected;
  19675. }
  19676. if (localRate != 0.0)
  19677. input->prepareToPlay (localBufferSize, localRate);
  19678. const ScopedLock sl (lock);
  19679. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19680. inputs.add (input);
  19681. }
  19682. }
  19683. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19684. {
  19685. if (input != 0)
  19686. {
  19687. int index;
  19688. {
  19689. const ScopedLock sl (lock);
  19690. index = inputs.indexOf (input);
  19691. if (index >= 0)
  19692. {
  19693. inputsToDelete.shiftBits (index, 1);
  19694. inputs.remove (index);
  19695. }
  19696. }
  19697. if (index >= 0)
  19698. {
  19699. input->releaseResources();
  19700. if (deleteInput)
  19701. delete input;
  19702. }
  19703. }
  19704. }
  19705. void MixerAudioSource::removeAllInputs()
  19706. {
  19707. OwnedArray<AudioSource> toDelete;
  19708. {
  19709. const ScopedLock sl (lock);
  19710. for (int i = inputs.size(); --i >= 0;)
  19711. if (inputsToDelete[i])
  19712. toDelete.add (inputs.getUnchecked(i));
  19713. }
  19714. }
  19715. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19716. {
  19717. tempBuffer.setSize (2, samplesPerBlockExpected);
  19718. const ScopedLock sl (lock);
  19719. currentSampleRate = sampleRate;
  19720. bufferSizeExpected = samplesPerBlockExpected;
  19721. for (int i = inputs.size(); --i >= 0;)
  19722. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19723. }
  19724. void MixerAudioSource::releaseResources()
  19725. {
  19726. const ScopedLock sl (lock);
  19727. for (int i = inputs.size(); --i >= 0;)
  19728. inputs.getUnchecked(i)->releaseResources();
  19729. tempBuffer.setSize (2, 0);
  19730. currentSampleRate = 0;
  19731. bufferSizeExpected = 0;
  19732. }
  19733. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19734. {
  19735. const ScopedLock sl (lock);
  19736. if (inputs.size() > 0)
  19737. {
  19738. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19739. if (inputs.size() > 1)
  19740. {
  19741. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19742. info.buffer->getNumSamples());
  19743. AudioSourceChannelInfo info2;
  19744. info2.buffer = &tempBuffer;
  19745. info2.numSamples = info.numSamples;
  19746. info2.startSample = 0;
  19747. for (int i = 1; i < inputs.size(); ++i)
  19748. {
  19749. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19750. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19751. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19752. }
  19753. }
  19754. }
  19755. else
  19756. {
  19757. info.clearActiveBufferRegion();
  19758. }
  19759. }
  19760. END_JUCE_NAMESPACE
  19761. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19762. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19763. BEGIN_JUCE_NAMESPACE
  19764. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19765. const bool deleteInputWhenDeleted_,
  19766. const int numChannels_)
  19767. : input (inputSource),
  19768. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19769. ratio (1.0),
  19770. lastRatio (1.0),
  19771. buffer (numChannels_, 0),
  19772. sampsInBuffer (0),
  19773. numChannels (numChannels_)
  19774. {
  19775. jassert (input != 0);
  19776. }
  19777. ResamplingAudioSource::~ResamplingAudioSource()
  19778. {
  19779. if (deleteInputWhenDeleted)
  19780. delete input;
  19781. }
  19782. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19783. {
  19784. jassert (samplesInPerOutputSample > 0);
  19785. const ScopedLock sl (ratioLock);
  19786. ratio = jmax (0.0, samplesInPerOutputSample);
  19787. }
  19788. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19789. double sampleRate)
  19790. {
  19791. const ScopedLock sl (ratioLock);
  19792. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19793. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19794. buffer.clear();
  19795. sampsInBuffer = 0;
  19796. bufferPos = 0;
  19797. subSampleOffset = 0.0;
  19798. filterStates.calloc (numChannels);
  19799. srcBuffers.calloc (numChannels);
  19800. destBuffers.calloc (numChannels);
  19801. createLowPass (ratio);
  19802. resetFilters();
  19803. }
  19804. void ResamplingAudioSource::releaseResources()
  19805. {
  19806. input->releaseResources();
  19807. buffer.setSize (numChannels, 0);
  19808. }
  19809. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19810. {
  19811. double localRatio;
  19812. {
  19813. const ScopedLock sl (ratioLock);
  19814. localRatio = ratio;
  19815. }
  19816. if (lastRatio != localRatio)
  19817. {
  19818. createLowPass (localRatio);
  19819. lastRatio = localRatio;
  19820. }
  19821. const int sampsNeeded = roundToInt (info.numSamples * localRatio) + 2;
  19822. int bufferSize = buffer.getNumSamples();
  19823. if (bufferSize < sampsNeeded + 8)
  19824. {
  19825. bufferPos %= bufferSize;
  19826. bufferSize = sampsNeeded + 32;
  19827. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19828. }
  19829. bufferPos %= bufferSize;
  19830. int endOfBufferPos = bufferPos + sampsInBuffer;
  19831. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19832. while (sampsNeeded > sampsInBuffer)
  19833. {
  19834. endOfBufferPos %= bufferSize;
  19835. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19836. bufferSize - endOfBufferPos);
  19837. AudioSourceChannelInfo readInfo;
  19838. readInfo.buffer = &buffer;
  19839. readInfo.numSamples = numToDo;
  19840. readInfo.startSample = endOfBufferPos;
  19841. input->getNextAudioBlock (readInfo);
  19842. if (localRatio > 1.0001)
  19843. {
  19844. // for down-sampling, pre-apply the filter..
  19845. for (int i = channelsToProcess; --i >= 0;)
  19846. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  19847. }
  19848. sampsInBuffer += numToDo;
  19849. endOfBufferPos += numToDo;
  19850. }
  19851. for (int channel = 0; channel < channelsToProcess; ++channel)
  19852. {
  19853. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  19854. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  19855. }
  19856. int nextPos = (bufferPos + 1) % bufferSize;
  19857. for (int m = info.numSamples; --m >= 0;)
  19858. {
  19859. const float alpha = (float) subSampleOffset;
  19860. const float invAlpha = 1.0f - alpha;
  19861. for (int channel = 0; channel < channelsToProcess; ++channel)
  19862. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  19863. subSampleOffset += localRatio;
  19864. jassert (sampsInBuffer > 0);
  19865. while (subSampleOffset >= 1.0)
  19866. {
  19867. if (++bufferPos >= bufferSize)
  19868. bufferPos = 0;
  19869. --sampsInBuffer;
  19870. nextPos = (bufferPos + 1) % bufferSize;
  19871. subSampleOffset -= 1.0;
  19872. }
  19873. }
  19874. if (localRatio < 0.9999)
  19875. {
  19876. // for up-sampling, apply the filter after transposing..
  19877. for (int i = channelsToProcess; --i >= 0;)
  19878. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  19879. }
  19880. else if (localRatio <= 1.0001)
  19881. {
  19882. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  19883. for (int i = channelsToProcess; --i >= 0;)
  19884. {
  19885. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  19886. FilterState& fs = filterStates[i];
  19887. if (info.numSamples > 1)
  19888. {
  19889. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  19890. }
  19891. else
  19892. {
  19893. fs.y2 = fs.y1;
  19894. fs.x2 = fs.x1;
  19895. }
  19896. fs.y1 = fs.x1 = *endOfBuffer;
  19897. }
  19898. }
  19899. jassert (sampsInBuffer >= 0);
  19900. }
  19901. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  19902. {
  19903. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  19904. : 0.5 * frequencyRatio;
  19905. const double n = 1.0 / std::tan (double_Pi * jmax (0.001, proportionalRate));
  19906. const double nSquared = n * n;
  19907. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  19908. setFilterCoefficients (c1,
  19909. c1 * 2.0f,
  19910. c1,
  19911. 1.0,
  19912. c1 * 2.0 * (1.0 - nSquared),
  19913. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  19914. }
  19915. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  19916. {
  19917. const double a = 1.0 / c4;
  19918. c1 *= a;
  19919. c2 *= a;
  19920. c3 *= a;
  19921. c5 *= a;
  19922. c6 *= a;
  19923. coefficients[0] = c1;
  19924. coefficients[1] = c2;
  19925. coefficients[2] = c3;
  19926. coefficients[3] = c4;
  19927. coefficients[4] = c5;
  19928. coefficients[5] = c6;
  19929. }
  19930. void ResamplingAudioSource::resetFilters()
  19931. {
  19932. zeromem (filterStates, sizeof (FilterState) * numChannels);
  19933. }
  19934. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  19935. {
  19936. while (--num >= 0)
  19937. {
  19938. const double in = *samples;
  19939. double out = coefficients[0] * in
  19940. + coefficients[1] * fs.x1
  19941. + coefficients[2] * fs.x2
  19942. - coefficients[4] * fs.y1
  19943. - coefficients[5] * fs.y2;
  19944. #if JUCE_INTEL
  19945. if (! (out < -1.0e-8 || out > 1.0e-8))
  19946. out = 0;
  19947. #endif
  19948. fs.x2 = fs.x1;
  19949. fs.x1 = in;
  19950. fs.y2 = fs.y1;
  19951. fs.y1 = out;
  19952. *samples++ = (float) out;
  19953. }
  19954. }
  19955. END_JUCE_NAMESPACE
  19956. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  19957. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  19958. BEGIN_JUCE_NAMESPACE
  19959. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  19960. : frequency (1000.0),
  19961. sampleRate (44100.0),
  19962. currentPhase (0.0),
  19963. phasePerSample (0.0),
  19964. amplitude (0.5f)
  19965. {
  19966. }
  19967. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  19968. {
  19969. }
  19970. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  19971. {
  19972. amplitude = newAmplitude;
  19973. }
  19974. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  19975. {
  19976. frequency = newFrequencyHz;
  19977. phasePerSample = 0.0;
  19978. }
  19979. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19980. double sampleRate_)
  19981. {
  19982. currentPhase = 0.0;
  19983. phasePerSample = 0.0;
  19984. sampleRate = sampleRate_;
  19985. }
  19986. void ToneGeneratorAudioSource::releaseResources()
  19987. {
  19988. }
  19989. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19990. {
  19991. if (phasePerSample == 0.0)
  19992. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19993. for (int i = 0; i < info.numSamples; ++i)
  19994. {
  19995. const float sample = amplitude * (float) std::sin (currentPhase);
  19996. currentPhase += phasePerSample;
  19997. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  19998. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  19999. }
  20000. }
  20001. END_JUCE_NAMESPACE
  20002. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20003. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20004. BEGIN_JUCE_NAMESPACE
  20005. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20006. : sampleRate (0),
  20007. bufferSize (0),
  20008. useDefaultInputChannels (true),
  20009. useDefaultOutputChannels (true)
  20010. {
  20011. }
  20012. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20013. {
  20014. return outputDeviceName == other.outputDeviceName
  20015. && inputDeviceName == other.inputDeviceName
  20016. && sampleRate == other.sampleRate
  20017. && bufferSize == other.bufferSize
  20018. && inputChannels == other.inputChannels
  20019. && useDefaultInputChannels == other.useDefaultInputChannels
  20020. && outputChannels == other.outputChannels
  20021. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20022. }
  20023. AudioDeviceManager::AudioDeviceManager()
  20024. : currentAudioDevice (0),
  20025. numInputChansNeeded (0),
  20026. numOutputChansNeeded (2),
  20027. listNeedsScanning (true),
  20028. useInputNames (false),
  20029. inputLevelMeasurementEnabledCount (0),
  20030. inputLevel (0),
  20031. tempBuffer (2, 2),
  20032. defaultMidiOutput (0),
  20033. cpuUsageMs (0),
  20034. timeToCpuScale (0)
  20035. {
  20036. callbackHandler.owner = this;
  20037. }
  20038. AudioDeviceManager::~AudioDeviceManager()
  20039. {
  20040. currentAudioDevice = 0;
  20041. defaultMidiOutput = 0;
  20042. }
  20043. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20044. {
  20045. if (availableDeviceTypes.size() == 0)
  20046. {
  20047. createAudioDeviceTypes (availableDeviceTypes);
  20048. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20049. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20050. if (availableDeviceTypes.size() > 0)
  20051. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20052. }
  20053. }
  20054. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20055. {
  20056. scanDevicesIfNeeded();
  20057. return availableDeviceTypes;
  20058. }
  20059. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20060. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20061. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20062. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20063. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20064. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20065. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20066. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20067. {
  20068. (void) list; // (to avoid 'unused param' warnings)
  20069. #if JUCE_WINDOWS
  20070. #if JUCE_WASAPI
  20071. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20072. list.add (juce_createAudioIODeviceType_WASAPI());
  20073. #endif
  20074. #if JUCE_DIRECTSOUND
  20075. list.add (juce_createAudioIODeviceType_DirectSound());
  20076. #endif
  20077. #if JUCE_ASIO
  20078. list.add (juce_createAudioIODeviceType_ASIO());
  20079. #endif
  20080. #endif
  20081. #if JUCE_MAC
  20082. list.add (juce_createAudioIODeviceType_CoreAudio());
  20083. #endif
  20084. #if JUCE_IOS
  20085. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20086. #endif
  20087. #if JUCE_LINUX && JUCE_ALSA
  20088. list.add (juce_createAudioIODeviceType_ALSA());
  20089. #endif
  20090. #if JUCE_LINUX && JUCE_JACK
  20091. list.add (juce_createAudioIODeviceType_JACK());
  20092. #endif
  20093. }
  20094. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20095. const int numOutputChannelsNeeded,
  20096. const XmlElement* const e,
  20097. const bool selectDefaultDeviceOnFailure,
  20098. const String& preferredDefaultDeviceName,
  20099. const AudioDeviceSetup* preferredSetupOptions)
  20100. {
  20101. scanDevicesIfNeeded();
  20102. numInputChansNeeded = numInputChannelsNeeded;
  20103. numOutputChansNeeded = numOutputChannelsNeeded;
  20104. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20105. {
  20106. lastExplicitSettings = new XmlElement (*e);
  20107. String error;
  20108. AudioDeviceSetup setup;
  20109. if (preferredSetupOptions != 0)
  20110. setup = *preferredSetupOptions;
  20111. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20112. {
  20113. setup.inputDeviceName = setup.outputDeviceName
  20114. = e->getStringAttribute ("audioDeviceName");
  20115. }
  20116. else
  20117. {
  20118. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20119. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20120. }
  20121. currentDeviceType = e->getStringAttribute ("deviceType");
  20122. if (currentDeviceType.isEmpty())
  20123. {
  20124. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20125. if (type != 0)
  20126. currentDeviceType = type->getTypeName();
  20127. else if (availableDeviceTypes.size() > 0)
  20128. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20129. }
  20130. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20131. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20132. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20133. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20134. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20135. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20136. error = setAudioDeviceSetup (setup, true);
  20137. midiInsFromXml.clear();
  20138. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20139. midiInsFromXml.add (c->getStringAttribute ("name"));
  20140. const StringArray allMidiIns (MidiInput::getDevices());
  20141. for (int i = allMidiIns.size(); --i >= 0;)
  20142. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20143. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20144. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20145. false, preferredDefaultDeviceName);
  20146. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20147. return error;
  20148. }
  20149. else
  20150. {
  20151. AudioDeviceSetup setup;
  20152. if (preferredSetupOptions != 0)
  20153. {
  20154. setup = *preferredSetupOptions;
  20155. }
  20156. else if (preferredDefaultDeviceName.isNotEmpty())
  20157. {
  20158. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20159. {
  20160. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20161. StringArray outs (type->getDeviceNames (false));
  20162. int i;
  20163. for (i = 0; i < outs.size(); ++i)
  20164. {
  20165. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20166. {
  20167. setup.outputDeviceName = outs[i];
  20168. break;
  20169. }
  20170. }
  20171. StringArray ins (type->getDeviceNames (true));
  20172. for (i = 0; i < ins.size(); ++i)
  20173. {
  20174. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20175. {
  20176. setup.inputDeviceName = ins[i];
  20177. break;
  20178. }
  20179. }
  20180. }
  20181. }
  20182. insertDefaultDeviceNames (setup);
  20183. return setAudioDeviceSetup (setup, false);
  20184. }
  20185. }
  20186. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20187. {
  20188. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20189. if (type != 0)
  20190. {
  20191. if (setup.outputDeviceName.isEmpty())
  20192. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20193. if (setup.inputDeviceName.isEmpty())
  20194. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20195. }
  20196. }
  20197. XmlElement* AudioDeviceManager::createStateXml() const
  20198. {
  20199. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20200. }
  20201. void AudioDeviceManager::scanDevicesIfNeeded()
  20202. {
  20203. if (listNeedsScanning)
  20204. {
  20205. listNeedsScanning = false;
  20206. createDeviceTypesIfNeeded();
  20207. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20208. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20209. }
  20210. }
  20211. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20212. {
  20213. scanDevicesIfNeeded();
  20214. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20215. {
  20216. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20217. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20218. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20219. {
  20220. return type;
  20221. }
  20222. }
  20223. return 0;
  20224. }
  20225. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20226. {
  20227. setup = currentSetup;
  20228. }
  20229. void AudioDeviceManager::deleteCurrentDevice()
  20230. {
  20231. currentAudioDevice = 0;
  20232. currentSetup.inputDeviceName = String::empty;
  20233. currentSetup.outputDeviceName = String::empty;
  20234. }
  20235. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20236. const bool treatAsChosenDevice)
  20237. {
  20238. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20239. {
  20240. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20241. && currentDeviceType != type)
  20242. {
  20243. currentDeviceType = type;
  20244. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20245. insertDefaultDeviceNames (s);
  20246. setAudioDeviceSetup (s, treatAsChosenDevice);
  20247. sendChangeMessage();
  20248. break;
  20249. }
  20250. }
  20251. }
  20252. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20253. {
  20254. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20255. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20256. return availableDeviceTypes[i];
  20257. return availableDeviceTypes[0];
  20258. }
  20259. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20260. const bool treatAsChosenDevice)
  20261. {
  20262. jassert (&newSetup != &currentSetup); // this will have no effect
  20263. if (newSetup == currentSetup && currentAudioDevice != 0)
  20264. return String::empty;
  20265. if (! (newSetup == currentSetup))
  20266. sendChangeMessage();
  20267. stopDevice();
  20268. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20269. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20270. String error;
  20271. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20272. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20273. {
  20274. deleteCurrentDevice();
  20275. if (treatAsChosenDevice)
  20276. updateXml();
  20277. return String::empty;
  20278. }
  20279. if (currentSetup.inputDeviceName != newInputDeviceName
  20280. || currentSetup.outputDeviceName != newOutputDeviceName
  20281. || currentAudioDevice == 0)
  20282. {
  20283. deleteCurrentDevice();
  20284. scanDevicesIfNeeded();
  20285. if (newOutputDeviceName.isNotEmpty()
  20286. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20287. {
  20288. return "No such device: " + newOutputDeviceName;
  20289. }
  20290. if (newInputDeviceName.isNotEmpty()
  20291. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20292. {
  20293. return "No such device: " + newInputDeviceName;
  20294. }
  20295. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20296. if (currentAudioDevice == 0)
  20297. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  20298. else
  20299. error = currentAudioDevice->getLastError();
  20300. if (error.isNotEmpty())
  20301. {
  20302. deleteCurrentDevice();
  20303. return error;
  20304. }
  20305. if (newSetup.useDefaultInputChannels)
  20306. {
  20307. inputChannels.clear();
  20308. inputChannels.setRange (0, numInputChansNeeded, true);
  20309. }
  20310. if (newSetup.useDefaultOutputChannels)
  20311. {
  20312. outputChannels.clear();
  20313. outputChannels.setRange (0, numOutputChansNeeded, true);
  20314. }
  20315. if (newInputDeviceName.isEmpty())
  20316. inputChannels.clear();
  20317. if (newOutputDeviceName.isEmpty())
  20318. outputChannels.clear();
  20319. }
  20320. if (! newSetup.useDefaultInputChannels)
  20321. inputChannels = newSetup.inputChannels;
  20322. if (! newSetup.useDefaultOutputChannels)
  20323. outputChannels = newSetup.outputChannels;
  20324. currentSetup = newSetup;
  20325. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20326. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  20327. error = currentAudioDevice->open (inputChannels,
  20328. outputChannels,
  20329. currentSetup.sampleRate,
  20330. currentSetup.bufferSize);
  20331. if (error.isEmpty())
  20332. {
  20333. currentDeviceType = currentAudioDevice->getTypeName();
  20334. currentAudioDevice->start (&callbackHandler);
  20335. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20336. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20337. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20338. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20339. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20340. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20341. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20342. if (treatAsChosenDevice)
  20343. updateXml();
  20344. }
  20345. else
  20346. {
  20347. deleteCurrentDevice();
  20348. }
  20349. return error;
  20350. }
  20351. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20352. {
  20353. jassert (currentAudioDevice != 0);
  20354. if (rate > 0)
  20355. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20356. if (currentAudioDevice->getSampleRate (i) == rate)
  20357. return rate;
  20358. double lowestAbove44 = 0.0;
  20359. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20360. {
  20361. const double sr = currentAudioDevice->getSampleRate (i);
  20362. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20363. lowestAbove44 = sr;
  20364. }
  20365. if (lowestAbove44 > 0.0)
  20366. return lowestAbove44;
  20367. return currentAudioDevice->getSampleRate (0);
  20368. }
  20369. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  20370. {
  20371. jassert (currentAudioDevice != 0);
  20372. if (bufferSize > 0)
  20373. for (int i = currentAudioDevice->getNumBufferSizesAvailable(); --i >= 0;)
  20374. if (currentAudioDevice->getBufferSizeSamples(i) == bufferSize)
  20375. return bufferSize;
  20376. return currentAudioDevice->getDefaultBufferSize();
  20377. }
  20378. void AudioDeviceManager::stopDevice()
  20379. {
  20380. if (currentAudioDevice != 0)
  20381. currentAudioDevice->stop();
  20382. testSound = 0;
  20383. }
  20384. void AudioDeviceManager::closeAudioDevice()
  20385. {
  20386. stopDevice();
  20387. currentAudioDevice = 0;
  20388. }
  20389. void AudioDeviceManager::restartLastAudioDevice()
  20390. {
  20391. if (currentAudioDevice == 0)
  20392. {
  20393. if (currentSetup.inputDeviceName.isEmpty()
  20394. && currentSetup.outputDeviceName.isEmpty())
  20395. {
  20396. // This method will only reload the last device that was running
  20397. // before closeAudioDevice() was called - you need to actually open
  20398. // one first, with setAudioDevice().
  20399. jassertfalse;
  20400. return;
  20401. }
  20402. AudioDeviceSetup s (currentSetup);
  20403. setAudioDeviceSetup (s, false);
  20404. }
  20405. }
  20406. void AudioDeviceManager::updateXml()
  20407. {
  20408. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20409. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20410. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20411. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20412. if (currentAudioDevice != 0)
  20413. {
  20414. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20415. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20416. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20417. if (! currentSetup.useDefaultInputChannels)
  20418. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20419. if (! currentSetup.useDefaultOutputChannels)
  20420. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20421. }
  20422. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20423. {
  20424. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20425. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20426. }
  20427. if (midiInsFromXml.size() > 0)
  20428. {
  20429. // Add any midi devices that have been enabled before, but which aren't currently
  20430. // open because the device has been disconnected.
  20431. const StringArray availableMidiDevices (MidiInput::getDevices());
  20432. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20433. {
  20434. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20435. {
  20436. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20437. m->setAttribute ("name", midiInsFromXml[i]);
  20438. }
  20439. }
  20440. }
  20441. if (defaultMidiOutputName.isNotEmpty())
  20442. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20443. }
  20444. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20445. {
  20446. {
  20447. const ScopedLock sl (audioCallbackLock);
  20448. if (callbacks.contains (newCallback))
  20449. return;
  20450. }
  20451. if (currentAudioDevice != 0 && newCallback != 0)
  20452. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20453. const ScopedLock sl (audioCallbackLock);
  20454. callbacks.add (newCallback);
  20455. }
  20456. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  20457. {
  20458. if (callbackToRemove != 0)
  20459. {
  20460. bool needsDeinitialising = currentAudioDevice != 0;
  20461. {
  20462. const ScopedLock sl (audioCallbackLock);
  20463. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  20464. callbacks.removeValue (callbackToRemove);
  20465. }
  20466. if (needsDeinitialising)
  20467. callbackToRemove->audioDeviceStopped();
  20468. }
  20469. }
  20470. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20471. int numInputChannels,
  20472. float** outputChannelData,
  20473. int numOutputChannels,
  20474. int numSamples)
  20475. {
  20476. const ScopedLock sl (audioCallbackLock);
  20477. if (inputLevelMeasurementEnabledCount > 0)
  20478. {
  20479. for (int j = 0; j < numSamples; ++j)
  20480. {
  20481. float s = 0;
  20482. for (int i = 0; i < numInputChannels; ++i)
  20483. s += std::abs (inputChannelData[i][j]);
  20484. s /= numInputChannels;
  20485. const double decayFactor = 0.99992;
  20486. if (s > inputLevel)
  20487. inputLevel = s;
  20488. else if (inputLevel > 0.001f)
  20489. inputLevel *= decayFactor;
  20490. else
  20491. inputLevel = 0;
  20492. }
  20493. }
  20494. if (callbacks.size() > 0)
  20495. {
  20496. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20497. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20498. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20499. outputChannelData, numOutputChannels, numSamples);
  20500. float** const tempChans = tempBuffer.getArrayOfChannels();
  20501. for (int i = callbacks.size(); --i > 0;)
  20502. {
  20503. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20504. tempChans, numOutputChannels, numSamples);
  20505. for (int chan = 0; chan < numOutputChannels; ++chan)
  20506. {
  20507. const float* const src = tempChans [chan];
  20508. float* const dst = outputChannelData [chan];
  20509. if (src != 0 && dst != 0)
  20510. for (int j = 0; j < numSamples; ++j)
  20511. dst[j] += src[j];
  20512. }
  20513. }
  20514. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20515. const double filterAmount = 0.2;
  20516. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20517. }
  20518. else
  20519. {
  20520. for (int i = 0; i < numOutputChannels; ++i)
  20521. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20522. }
  20523. if (testSound != 0)
  20524. {
  20525. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20526. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20527. for (int i = 0; i < numOutputChannels; ++i)
  20528. for (int j = 0; j < numSamps; ++j)
  20529. outputChannelData [i][j] += src[j];
  20530. testSoundPosition += numSamps;
  20531. if (testSoundPosition >= testSound->getNumSamples())
  20532. testSound = 0;
  20533. }
  20534. }
  20535. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20536. {
  20537. cpuUsageMs = 0;
  20538. const double sampleRate = device->getCurrentSampleRate();
  20539. const int blockSize = device->getCurrentBufferSizeSamples();
  20540. if (sampleRate > 0.0 && blockSize > 0)
  20541. {
  20542. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20543. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20544. }
  20545. {
  20546. const ScopedLock sl (audioCallbackLock);
  20547. for (int i = callbacks.size(); --i >= 0;)
  20548. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20549. }
  20550. sendChangeMessage();
  20551. }
  20552. void AudioDeviceManager::audioDeviceStoppedInt()
  20553. {
  20554. cpuUsageMs = 0;
  20555. timeToCpuScale = 0;
  20556. sendChangeMessage();
  20557. const ScopedLock sl (audioCallbackLock);
  20558. for (int i = callbacks.size(); --i >= 0;)
  20559. callbacks.getUnchecked(i)->audioDeviceStopped();
  20560. }
  20561. double AudioDeviceManager::getCpuUsage() const
  20562. {
  20563. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20564. }
  20565. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20566. const bool enabled)
  20567. {
  20568. if (enabled != isMidiInputEnabled (name))
  20569. {
  20570. if (enabled)
  20571. {
  20572. const int index = MidiInput::getDevices().indexOf (name);
  20573. if (index >= 0)
  20574. {
  20575. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20576. if (min != 0)
  20577. {
  20578. enabledMidiInputs.add (min);
  20579. min->start();
  20580. }
  20581. }
  20582. }
  20583. else
  20584. {
  20585. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20586. if (enabledMidiInputs[i]->getName() == name)
  20587. enabledMidiInputs.remove (i);
  20588. }
  20589. updateXml();
  20590. sendChangeMessage();
  20591. }
  20592. }
  20593. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20594. {
  20595. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20596. if (enabledMidiInputs[i]->getName() == name)
  20597. return true;
  20598. return false;
  20599. }
  20600. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20601. MidiInputCallback* callbackToAdd)
  20602. {
  20603. removeMidiInputCallback (name, callbackToAdd);
  20604. if (name.isEmpty() || isMidiInputEnabled (name))
  20605. {
  20606. const ScopedLock sl (midiCallbackLock);
  20607. midiCallbacks.add (callbackToAdd);
  20608. midiCallbackDevices.add (name);
  20609. }
  20610. }
  20611. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callback)
  20612. {
  20613. for (int i = midiCallbacks.size(); --i >= 0;)
  20614. {
  20615. if (midiCallbackDevices[i] == name && midiCallbacks.getUnchecked(i) == callback)
  20616. {
  20617. const ScopedLock sl (midiCallbackLock);
  20618. midiCallbacks.remove (i);
  20619. midiCallbackDevices.remove (i);
  20620. }
  20621. }
  20622. }
  20623. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20624. const MidiMessage& message)
  20625. {
  20626. if (! message.isActiveSense())
  20627. {
  20628. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20629. const ScopedLock sl (midiCallbackLock);
  20630. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20631. {
  20632. const String name (midiCallbackDevices[i]);
  20633. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  20634. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20635. }
  20636. }
  20637. }
  20638. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20639. {
  20640. if (defaultMidiOutputName != deviceName)
  20641. {
  20642. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20643. {
  20644. const ScopedLock sl (audioCallbackLock);
  20645. oldCallbacks = callbacks;
  20646. callbacks.clear();
  20647. }
  20648. if (currentAudioDevice != 0)
  20649. for (int i = oldCallbacks.size(); --i >= 0;)
  20650. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20651. defaultMidiOutput = 0;
  20652. defaultMidiOutputName = deviceName;
  20653. if (deviceName.isNotEmpty())
  20654. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20655. if (currentAudioDevice != 0)
  20656. for (int i = oldCallbacks.size(); --i >= 0;)
  20657. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20658. {
  20659. const ScopedLock sl (audioCallbackLock);
  20660. callbacks = oldCallbacks;
  20661. }
  20662. updateXml();
  20663. sendChangeMessage();
  20664. }
  20665. }
  20666. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20667. int numInputChannels,
  20668. float** outputChannelData,
  20669. int numOutputChannels,
  20670. int numSamples)
  20671. {
  20672. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20673. }
  20674. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20675. {
  20676. owner->audioDeviceAboutToStartInt (device);
  20677. }
  20678. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20679. {
  20680. owner->audioDeviceStoppedInt();
  20681. }
  20682. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20683. {
  20684. owner->handleIncomingMidiMessageInt (source, message);
  20685. }
  20686. void AudioDeviceManager::playTestSound()
  20687. {
  20688. { // cunningly nested to swap, unlock and delete in that order.
  20689. ScopedPointer <AudioSampleBuffer> oldSound;
  20690. {
  20691. const ScopedLock sl (audioCallbackLock);
  20692. oldSound = testSound;
  20693. }
  20694. }
  20695. testSoundPosition = 0;
  20696. if (currentAudioDevice != 0)
  20697. {
  20698. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20699. const int soundLength = (int) sampleRate;
  20700. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20701. float* samples = newSound->getSampleData (0);
  20702. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20703. const float amplitude = 0.5f;
  20704. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20705. for (int i = 0; i < soundLength; ++i)
  20706. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20707. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20708. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20709. const ScopedLock sl (audioCallbackLock);
  20710. testSound = newSound;
  20711. }
  20712. }
  20713. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20714. {
  20715. const ScopedLock sl (audioCallbackLock);
  20716. if (enableMeasurement)
  20717. ++inputLevelMeasurementEnabledCount;
  20718. else
  20719. --inputLevelMeasurementEnabledCount;
  20720. inputLevel = 0;
  20721. }
  20722. double AudioDeviceManager::getCurrentInputLevel() const
  20723. {
  20724. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20725. return inputLevel;
  20726. }
  20727. END_JUCE_NAMESPACE
  20728. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20729. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20730. BEGIN_JUCE_NAMESPACE
  20731. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20732. : name (deviceName),
  20733. typeName (typeName_)
  20734. {
  20735. }
  20736. AudioIODevice::~AudioIODevice()
  20737. {
  20738. }
  20739. bool AudioIODevice::hasControlPanel() const
  20740. {
  20741. return false;
  20742. }
  20743. bool AudioIODevice::showControlPanel()
  20744. {
  20745. jassertfalse; // this should only be called for devices which return true from
  20746. // their hasControlPanel() method.
  20747. return false;
  20748. }
  20749. END_JUCE_NAMESPACE
  20750. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20751. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20752. BEGIN_JUCE_NAMESPACE
  20753. AudioIODeviceType::AudioIODeviceType (const String& name)
  20754. : typeName (name)
  20755. {
  20756. }
  20757. AudioIODeviceType::~AudioIODeviceType()
  20758. {
  20759. }
  20760. END_JUCE_NAMESPACE
  20761. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20762. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20763. BEGIN_JUCE_NAMESPACE
  20764. MidiOutput::MidiOutput()
  20765. : Thread ("midi out"),
  20766. internal (0),
  20767. firstMessage (0)
  20768. {
  20769. }
  20770. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20771. const double sampleNumber)
  20772. : message (data, len, sampleNumber)
  20773. {
  20774. }
  20775. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20776. const double millisecondCounterToStartAt,
  20777. double samplesPerSecondForBuffer)
  20778. {
  20779. // You've got to call startBackgroundThread() for this to actually work..
  20780. jassert (isThreadRunning());
  20781. // this needs to be a value in the future - RTFM for this method!
  20782. jassert (millisecondCounterToStartAt > 0);
  20783. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20784. MidiBuffer::Iterator i (buffer);
  20785. const uint8* data;
  20786. int len, time;
  20787. while (i.getNextEvent (data, len, time))
  20788. {
  20789. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20790. PendingMessage* const m
  20791. = new PendingMessage (data, len, eventTime);
  20792. const ScopedLock sl (lock);
  20793. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20794. {
  20795. m->next = firstMessage;
  20796. firstMessage = m;
  20797. }
  20798. else
  20799. {
  20800. PendingMessage* mm = firstMessage;
  20801. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20802. mm = mm->next;
  20803. m->next = mm->next;
  20804. mm->next = m;
  20805. }
  20806. }
  20807. notify();
  20808. }
  20809. void MidiOutput::clearAllPendingMessages()
  20810. {
  20811. const ScopedLock sl (lock);
  20812. while (firstMessage != 0)
  20813. {
  20814. PendingMessage* const m = firstMessage;
  20815. firstMessage = firstMessage->next;
  20816. delete m;
  20817. }
  20818. }
  20819. void MidiOutput::startBackgroundThread()
  20820. {
  20821. startThread (9);
  20822. }
  20823. void MidiOutput::stopBackgroundThread()
  20824. {
  20825. stopThread (5000);
  20826. }
  20827. void MidiOutput::run()
  20828. {
  20829. while (! threadShouldExit())
  20830. {
  20831. uint32 now = Time::getMillisecondCounter();
  20832. uint32 eventTime = 0;
  20833. uint32 timeToWait = 500;
  20834. PendingMessage* message;
  20835. {
  20836. const ScopedLock sl (lock);
  20837. message = firstMessage;
  20838. if (message != 0)
  20839. {
  20840. eventTime = roundToInt (message->message.getTimeStamp());
  20841. if (eventTime > now + 20)
  20842. {
  20843. timeToWait = eventTime - (now + 20);
  20844. message = 0;
  20845. }
  20846. else
  20847. {
  20848. firstMessage = message->next;
  20849. }
  20850. }
  20851. }
  20852. if (message != 0)
  20853. {
  20854. if (eventTime > now)
  20855. {
  20856. Time::waitForMillisecondCounter (eventTime);
  20857. if (threadShouldExit())
  20858. break;
  20859. }
  20860. if (eventTime > now - 200)
  20861. sendMessageNow (message->message);
  20862. delete message;
  20863. }
  20864. else
  20865. {
  20866. jassert (timeToWait < 1000 * 30);
  20867. wait (timeToWait);
  20868. }
  20869. }
  20870. clearAllPendingMessages();
  20871. }
  20872. END_JUCE_NAMESPACE
  20873. /*** End of inlined file: juce_MidiOutput.cpp ***/
  20874. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  20875. BEGIN_JUCE_NAMESPACE
  20876. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20877. {
  20878. const double maxVal = (double) 0x7fff;
  20879. char* intData = static_cast <char*> (dest);
  20880. if (dest != (void*) source || destBytesPerSample <= 4)
  20881. {
  20882. for (int i = 0; i < numSamples; ++i)
  20883. {
  20884. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20885. intData += destBytesPerSample;
  20886. }
  20887. }
  20888. else
  20889. {
  20890. intData += destBytesPerSample * numSamples;
  20891. for (int i = numSamples; --i >= 0;)
  20892. {
  20893. intData -= destBytesPerSample;
  20894. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20895. }
  20896. }
  20897. }
  20898. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20899. {
  20900. const double maxVal = (double) 0x7fff;
  20901. char* intData = static_cast <char*> (dest);
  20902. if (dest != (void*) source || destBytesPerSample <= 4)
  20903. {
  20904. for (int i = 0; i < numSamples; ++i)
  20905. {
  20906. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20907. intData += destBytesPerSample;
  20908. }
  20909. }
  20910. else
  20911. {
  20912. intData += destBytesPerSample * numSamples;
  20913. for (int i = numSamples; --i >= 0;)
  20914. {
  20915. intData -= destBytesPerSample;
  20916. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20917. }
  20918. }
  20919. }
  20920. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20921. {
  20922. const double maxVal = (double) 0x7fffff;
  20923. char* intData = static_cast <char*> (dest);
  20924. if (dest != (void*) source || destBytesPerSample <= 4)
  20925. {
  20926. for (int i = 0; i < numSamples; ++i)
  20927. {
  20928. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20929. intData += destBytesPerSample;
  20930. }
  20931. }
  20932. else
  20933. {
  20934. intData += destBytesPerSample * numSamples;
  20935. for (int i = numSamples; --i >= 0;)
  20936. {
  20937. intData -= destBytesPerSample;
  20938. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20939. }
  20940. }
  20941. }
  20942. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20943. {
  20944. const double maxVal = (double) 0x7fffff;
  20945. char* intData = static_cast <char*> (dest);
  20946. if (dest != (void*) source || destBytesPerSample <= 4)
  20947. {
  20948. for (int i = 0; i < numSamples; ++i)
  20949. {
  20950. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20951. intData += destBytesPerSample;
  20952. }
  20953. }
  20954. else
  20955. {
  20956. intData += destBytesPerSample * numSamples;
  20957. for (int i = numSamples; --i >= 0;)
  20958. {
  20959. intData -= destBytesPerSample;
  20960. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  20961. }
  20962. }
  20963. }
  20964. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20965. {
  20966. const double maxVal = (double) 0x7fffffff;
  20967. char* intData = static_cast <char*> (dest);
  20968. if (dest != (void*) source || destBytesPerSample <= 4)
  20969. {
  20970. for (int i = 0; i < numSamples; ++i)
  20971. {
  20972. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20973. intData += destBytesPerSample;
  20974. }
  20975. }
  20976. else
  20977. {
  20978. intData += destBytesPerSample * numSamples;
  20979. for (int i = numSamples; --i >= 0;)
  20980. {
  20981. intData -= destBytesPerSample;
  20982. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20983. }
  20984. }
  20985. }
  20986. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  20987. {
  20988. const double maxVal = (double) 0x7fffffff;
  20989. char* intData = static_cast <char*> (dest);
  20990. if (dest != (void*) source || destBytesPerSample <= 4)
  20991. {
  20992. for (int i = 0; i < numSamples; ++i)
  20993. {
  20994. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  20995. intData += destBytesPerSample;
  20996. }
  20997. }
  20998. else
  20999. {
  21000. intData += destBytesPerSample * numSamples;
  21001. for (int i = numSamples; --i >= 0;)
  21002. {
  21003. intData -= destBytesPerSample;
  21004. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21005. }
  21006. }
  21007. }
  21008. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21009. {
  21010. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21011. char* d = static_cast <char*> (dest);
  21012. for (int i = 0; i < numSamples; ++i)
  21013. {
  21014. *(float*) d = source[i];
  21015. #if JUCE_BIG_ENDIAN
  21016. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21017. #endif
  21018. d += destBytesPerSample;
  21019. }
  21020. }
  21021. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21022. {
  21023. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21024. char* d = static_cast <char*> (dest);
  21025. for (int i = 0; i < numSamples; ++i)
  21026. {
  21027. *(float*) d = source[i];
  21028. #if JUCE_LITTLE_ENDIAN
  21029. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21030. #endif
  21031. d += destBytesPerSample;
  21032. }
  21033. }
  21034. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21035. {
  21036. const float scale = 1.0f / 0x7fff;
  21037. const char* intData = static_cast <const char*> (source);
  21038. if (source != (void*) dest || srcBytesPerSample >= 4)
  21039. {
  21040. for (int i = 0; i < numSamples; ++i)
  21041. {
  21042. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21043. intData += srcBytesPerSample;
  21044. }
  21045. }
  21046. else
  21047. {
  21048. intData += srcBytesPerSample * numSamples;
  21049. for (int i = numSamples; --i >= 0;)
  21050. {
  21051. intData -= srcBytesPerSample;
  21052. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21053. }
  21054. }
  21055. }
  21056. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21057. {
  21058. const float scale = 1.0f / 0x7fff;
  21059. const char* intData = static_cast <const char*> (source);
  21060. if (source != (void*) dest || srcBytesPerSample >= 4)
  21061. {
  21062. for (int i = 0; i < numSamples; ++i)
  21063. {
  21064. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21065. intData += srcBytesPerSample;
  21066. }
  21067. }
  21068. else
  21069. {
  21070. intData += srcBytesPerSample * numSamples;
  21071. for (int i = numSamples; --i >= 0;)
  21072. {
  21073. intData -= srcBytesPerSample;
  21074. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21075. }
  21076. }
  21077. }
  21078. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21079. {
  21080. const float scale = 1.0f / 0x7fffff;
  21081. const char* intData = static_cast <const char*> (source);
  21082. if (source != (void*) dest || srcBytesPerSample >= 4)
  21083. {
  21084. for (int i = 0; i < numSamples; ++i)
  21085. {
  21086. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21087. intData += srcBytesPerSample;
  21088. }
  21089. }
  21090. else
  21091. {
  21092. intData += srcBytesPerSample * numSamples;
  21093. for (int i = numSamples; --i >= 0;)
  21094. {
  21095. intData -= srcBytesPerSample;
  21096. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21097. }
  21098. }
  21099. }
  21100. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21101. {
  21102. const float scale = 1.0f / 0x7fffff;
  21103. const char* intData = static_cast <const char*> (source);
  21104. if (source != (void*) dest || srcBytesPerSample >= 4)
  21105. {
  21106. for (int i = 0; i < numSamples; ++i)
  21107. {
  21108. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21109. intData += srcBytesPerSample;
  21110. }
  21111. }
  21112. else
  21113. {
  21114. intData += srcBytesPerSample * numSamples;
  21115. for (int i = numSamples; --i >= 0;)
  21116. {
  21117. intData -= srcBytesPerSample;
  21118. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21119. }
  21120. }
  21121. }
  21122. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21123. {
  21124. const float scale = 1.0f / 0x7fffffff;
  21125. const char* intData = static_cast <const char*> (source);
  21126. if (source != (void*) dest || srcBytesPerSample >= 4)
  21127. {
  21128. for (int i = 0; i < numSamples; ++i)
  21129. {
  21130. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21131. intData += srcBytesPerSample;
  21132. }
  21133. }
  21134. else
  21135. {
  21136. intData += srcBytesPerSample * numSamples;
  21137. for (int i = numSamples; --i >= 0;)
  21138. {
  21139. intData -= srcBytesPerSample;
  21140. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21141. }
  21142. }
  21143. }
  21144. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21145. {
  21146. const float scale = 1.0f / 0x7fffffff;
  21147. const char* intData = static_cast <const char*> (source);
  21148. if (source != (void*) dest || srcBytesPerSample >= 4)
  21149. {
  21150. for (int i = 0; i < numSamples; ++i)
  21151. {
  21152. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21153. intData += srcBytesPerSample;
  21154. }
  21155. }
  21156. else
  21157. {
  21158. intData += srcBytesPerSample * numSamples;
  21159. for (int i = numSamples; --i >= 0;)
  21160. {
  21161. intData -= srcBytesPerSample;
  21162. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21163. }
  21164. }
  21165. }
  21166. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21167. {
  21168. const char* s = static_cast <const char*> (source);
  21169. for (int i = 0; i < numSamples; ++i)
  21170. {
  21171. dest[i] = *(float*)s;
  21172. #if JUCE_BIG_ENDIAN
  21173. uint32* const d = (uint32*) (dest + i);
  21174. *d = ByteOrder::swap (*d);
  21175. #endif
  21176. s += srcBytesPerSample;
  21177. }
  21178. }
  21179. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21180. {
  21181. const char* s = static_cast <const char*> (source);
  21182. for (int i = 0; i < numSamples; ++i)
  21183. {
  21184. dest[i] = *(float*)s;
  21185. #if JUCE_LITTLE_ENDIAN
  21186. uint32* const d = (uint32*) (dest + i);
  21187. *d = ByteOrder::swap (*d);
  21188. #endif
  21189. s += srcBytesPerSample;
  21190. }
  21191. }
  21192. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21193. const float* const source,
  21194. void* const dest,
  21195. const int numSamples)
  21196. {
  21197. switch (destFormat)
  21198. {
  21199. case int16LE:
  21200. convertFloatToInt16LE (source, dest, numSamples);
  21201. break;
  21202. case int16BE:
  21203. convertFloatToInt16BE (source, dest, numSamples);
  21204. break;
  21205. case int24LE:
  21206. convertFloatToInt24LE (source, dest, numSamples);
  21207. break;
  21208. case int24BE:
  21209. convertFloatToInt24BE (source, dest, numSamples);
  21210. break;
  21211. case int32LE:
  21212. convertFloatToInt32LE (source, dest, numSamples);
  21213. break;
  21214. case int32BE:
  21215. convertFloatToInt32BE (source, dest, numSamples);
  21216. break;
  21217. case float32LE:
  21218. convertFloatToFloat32LE (source, dest, numSamples);
  21219. break;
  21220. case float32BE:
  21221. convertFloatToFloat32BE (source, dest, numSamples);
  21222. break;
  21223. default:
  21224. jassertfalse;
  21225. break;
  21226. }
  21227. }
  21228. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21229. const void* const source,
  21230. float* const dest,
  21231. const int numSamples)
  21232. {
  21233. switch (sourceFormat)
  21234. {
  21235. case int16LE:
  21236. convertInt16LEToFloat (source, dest, numSamples);
  21237. break;
  21238. case int16BE:
  21239. convertInt16BEToFloat (source, dest, numSamples);
  21240. break;
  21241. case int24LE:
  21242. convertInt24LEToFloat (source, dest, numSamples);
  21243. break;
  21244. case int24BE:
  21245. convertInt24BEToFloat (source, dest, numSamples);
  21246. break;
  21247. case int32LE:
  21248. convertInt32LEToFloat (source, dest, numSamples);
  21249. break;
  21250. case int32BE:
  21251. convertInt32BEToFloat (source, dest, numSamples);
  21252. break;
  21253. case float32LE:
  21254. convertFloat32LEToFloat (source, dest, numSamples);
  21255. break;
  21256. case float32BE:
  21257. convertFloat32BEToFloat (source, dest, numSamples);
  21258. break;
  21259. default:
  21260. jassertfalse;
  21261. break;
  21262. }
  21263. }
  21264. void AudioDataConverters::interleaveSamples (const float** const source,
  21265. float* const dest,
  21266. const int numSamples,
  21267. const int numChannels)
  21268. {
  21269. for (int chan = 0; chan < numChannels; ++chan)
  21270. {
  21271. int i = chan;
  21272. const float* src = source [chan];
  21273. for (int j = 0; j < numSamples; ++j)
  21274. {
  21275. dest [i] = src [j];
  21276. i += numChannels;
  21277. }
  21278. }
  21279. }
  21280. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21281. float** const dest,
  21282. const int numSamples,
  21283. const int numChannels)
  21284. {
  21285. for (int chan = 0; chan < numChannels; ++chan)
  21286. {
  21287. int i = chan;
  21288. float* dst = dest [chan];
  21289. for (int j = 0; j < numSamples; ++j)
  21290. {
  21291. dst [j] = source [i];
  21292. i += numChannels;
  21293. }
  21294. }
  21295. }
  21296. #if JUCE_UNIT_TESTS
  21297. class AudioConversionTests : public UnitTest
  21298. {
  21299. public:
  21300. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21301. template <class F1, class E1, class F2, class E2>
  21302. struct Test5
  21303. {
  21304. static void test (UnitTest& unitTest)
  21305. {
  21306. test (unitTest, false);
  21307. test (unitTest, true);
  21308. }
  21309. static void test (UnitTest& unitTest, bool inPlace)
  21310. {
  21311. const int numSamples = 2048;
  21312. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21313. {
  21314. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21315. bool clippingFailed = false;
  21316. for (int i = 0; i < numSamples / 2; ++i)
  21317. {
  21318. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21319. if (! d.isFloatingPoint())
  21320. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21321. ++d;
  21322. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21323. ++d;
  21324. }
  21325. unitTest.expect (! clippingFailed);
  21326. }
  21327. // convert data from the source to dest format..
  21328. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21329. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21330. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21331. // ..and back again..
  21332. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21333. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21334. if (! inPlace)
  21335. zerostruct (reversed);
  21336. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21337. {
  21338. int biggestDiff = 0;
  21339. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21340. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21341. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21342. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21343. for (int i = 0; i < numSamples; ++i)
  21344. {
  21345. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21346. ++d1;
  21347. ++d2;
  21348. }
  21349. unitTest.expect (biggestDiff <= errorMargin);
  21350. }
  21351. }
  21352. };
  21353. template <class F1, class E1, class FormatType>
  21354. struct Test3
  21355. {
  21356. static void test (UnitTest& unitTest)
  21357. {
  21358. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21359. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21360. }
  21361. };
  21362. template <class FormatType, class Endianness>
  21363. struct Test2
  21364. {
  21365. static void test (UnitTest& unitTest)
  21366. {
  21367. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21368. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21369. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21370. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21371. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21372. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21373. }
  21374. };
  21375. template <class FormatType>
  21376. struct Test1
  21377. {
  21378. static void test (UnitTest& unitTest)
  21379. {
  21380. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21381. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21382. }
  21383. };
  21384. void runTest()
  21385. {
  21386. beginTest ("Round-trip conversion");
  21387. Test1 <AudioData::Int8>::test (*this);
  21388. Test1 <AudioData::Int16>::test (*this);
  21389. Test1 <AudioData::Int24>::test (*this);
  21390. Test1 <AudioData::Int32>::test (*this);
  21391. Test1 <AudioData::Float32>::test (*this);
  21392. }
  21393. };
  21394. static AudioConversionTests audioConversionUnitTests;
  21395. #endif
  21396. END_JUCE_NAMESPACE
  21397. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21398. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21399. BEGIN_JUCE_NAMESPACE
  21400. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21401. const int numSamples) throw()
  21402. : numChannels (numChannels_),
  21403. size (numSamples)
  21404. {
  21405. jassert (numSamples >= 0);
  21406. jassert (numChannels_ > 0);
  21407. allocateData();
  21408. }
  21409. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21410. : numChannels (other.numChannels),
  21411. size (other.size)
  21412. {
  21413. allocateData();
  21414. const size_t numBytes = size * sizeof (float);
  21415. for (int i = 0; i < numChannels; ++i)
  21416. memcpy (channels[i], other.channels[i], numBytes);
  21417. }
  21418. void AudioSampleBuffer::allocateData()
  21419. {
  21420. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21421. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21422. allocatedData.malloc (allocatedBytes);
  21423. channels = reinterpret_cast <float**> (allocatedData.getData());
  21424. float* chan = (float*) (allocatedData + channelListSize);
  21425. for (int i = 0; i < numChannels; ++i)
  21426. {
  21427. channels[i] = chan;
  21428. chan += size;
  21429. }
  21430. channels [numChannels] = 0;
  21431. }
  21432. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21433. const int numChannels_,
  21434. const int numSamples) throw()
  21435. : numChannels (numChannels_),
  21436. size (numSamples),
  21437. allocatedBytes (0)
  21438. {
  21439. jassert (numChannels_ > 0);
  21440. allocateChannels (dataToReferTo, 0);
  21441. }
  21442. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21443. const int numChannels_,
  21444. const int startSample,
  21445. const int numSamples) throw()
  21446. : numChannels (numChannels_),
  21447. size (numSamples),
  21448. allocatedBytes (0)
  21449. {
  21450. jassert (numChannels_ > 0);
  21451. allocateChannels (dataToReferTo, startSample);
  21452. }
  21453. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21454. const int newNumChannels,
  21455. const int newNumSamples) throw()
  21456. {
  21457. jassert (newNumChannels > 0);
  21458. allocatedBytes = 0;
  21459. allocatedData.free();
  21460. numChannels = newNumChannels;
  21461. size = newNumSamples;
  21462. allocateChannels (dataToReferTo, 0);
  21463. }
  21464. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo, int offset)
  21465. {
  21466. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21467. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21468. {
  21469. channels = static_cast <float**> (preallocatedChannelSpace);
  21470. }
  21471. else
  21472. {
  21473. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21474. channels = reinterpret_cast <float**> (allocatedData.getData());
  21475. }
  21476. for (int i = 0; i < numChannels; ++i)
  21477. {
  21478. // you have to pass in the same number of valid pointers as numChannels
  21479. jassert (dataToReferTo[i] != 0);
  21480. channels[i] = dataToReferTo[i] + offset;
  21481. }
  21482. channels [numChannels] = 0;
  21483. }
  21484. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21485. {
  21486. if (this != &other)
  21487. {
  21488. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21489. const size_t numBytes = size * sizeof (float);
  21490. for (int i = 0; i < numChannels; ++i)
  21491. memcpy (channels[i], other.channels[i], numBytes);
  21492. }
  21493. return *this;
  21494. }
  21495. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21496. {
  21497. }
  21498. void AudioSampleBuffer::setSize (const int newNumChannels,
  21499. const int newNumSamples,
  21500. const bool keepExistingContent,
  21501. const bool clearExtraSpace,
  21502. const bool avoidReallocating) throw()
  21503. {
  21504. jassert (newNumChannels > 0);
  21505. if (newNumSamples != size || newNumChannels != numChannels)
  21506. {
  21507. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21508. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21509. if (keepExistingContent)
  21510. {
  21511. HeapBlock <char> newData;
  21512. newData.allocate (newTotalBytes, clearExtraSpace);
  21513. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21514. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21515. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21516. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21517. for (int i = 0; i < numChansToCopy; ++i)
  21518. {
  21519. memcpy (newChan, channels[i], numBytesToCopy);
  21520. newChannels[i] = newChan;
  21521. newChan += newNumSamples;
  21522. }
  21523. allocatedData.swapWith (newData);
  21524. allocatedBytes = (int) newTotalBytes;
  21525. channels = newChannels;
  21526. }
  21527. else
  21528. {
  21529. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21530. {
  21531. if (clearExtraSpace)
  21532. zeromem (allocatedData, newTotalBytes);
  21533. }
  21534. else
  21535. {
  21536. allocatedBytes = newTotalBytes;
  21537. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21538. channels = reinterpret_cast <float**> (allocatedData.getData());
  21539. }
  21540. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21541. for (int i = 0; i < newNumChannels; ++i)
  21542. {
  21543. channels[i] = chan;
  21544. chan += newNumSamples;
  21545. }
  21546. }
  21547. channels [newNumChannels] = 0;
  21548. size = newNumSamples;
  21549. numChannels = newNumChannels;
  21550. }
  21551. }
  21552. void AudioSampleBuffer::clear() throw()
  21553. {
  21554. for (int i = 0; i < numChannels; ++i)
  21555. zeromem (channels[i], size * sizeof (float));
  21556. }
  21557. void AudioSampleBuffer::clear (const int startSample,
  21558. const int numSamples) throw()
  21559. {
  21560. jassert (startSample >= 0 && startSample + numSamples <= size);
  21561. for (int i = 0; i < numChannels; ++i)
  21562. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21563. }
  21564. void AudioSampleBuffer::clear (const int channel,
  21565. const int startSample,
  21566. const int numSamples) throw()
  21567. {
  21568. jassert (isPositiveAndBelow (channel, numChannels));
  21569. jassert (startSample >= 0 && startSample + numSamples <= size);
  21570. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21571. }
  21572. void AudioSampleBuffer::applyGain (const int channel,
  21573. const int startSample,
  21574. int numSamples,
  21575. const float gain) throw()
  21576. {
  21577. jassert (isPositiveAndBelow (channel, numChannels));
  21578. jassert (startSample >= 0 && startSample + numSamples <= size);
  21579. if (gain != 1.0f)
  21580. {
  21581. float* d = channels [channel] + startSample;
  21582. if (gain == 0.0f)
  21583. {
  21584. zeromem (d, sizeof (float) * numSamples);
  21585. }
  21586. else
  21587. {
  21588. while (--numSamples >= 0)
  21589. *d++ *= gain;
  21590. }
  21591. }
  21592. }
  21593. void AudioSampleBuffer::applyGainRamp (const int channel,
  21594. const int startSample,
  21595. int numSamples,
  21596. float startGain,
  21597. float endGain) throw()
  21598. {
  21599. if (startGain == endGain)
  21600. {
  21601. applyGain (channel, startSample, numSamples, startGain);
  21602. }
  21603. else
  21604. {
  21605. jassert (isPositiveAndBelow (channel, numChannels));
  21606. jassert (startSample >= 0 && startSample + numSamples <= size);
  21607. const float increment = (endGain - startGain) / numSamples;
  21608. float* d = channels [channel] + startSample;
  21609. while (--numSamples >= 0)
  21610. {
  21611. *d++ *= startGain;
  21612. startGain += increment;
  21613. }
  21614. }
  21615. }
  21616. void AudioSampleBuffer::applyGain (const int startSample,
  21617. const int numSamples,
  21618. const float gain) throw()
  21619. {
  21620. for (int i = 0; i < numChannels; ++i)
  21621. applyGain (i, startSample, numSamples, gain);
  21622. }
  21623. void AudioSampleBuffer::addFrom (const int destChannel,
  21624. const int destStartSample,
  21625. const AudioSampleBuffer& source,
  21626. const int sourceChannel,
  21627. const int sourceStartSample,
  21628. int numSamples,
  21629. const float gain) throw()
  21630. {
  21631. jassert (&source != this || sourceChannel != destChannel);
  21632. jassert (isPositiveAndBelow (destChannel, numChannels));
  21633. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21634. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21635. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21636. if (gain != 0.0f && numSamples > 0)
  21637. {
  21638. float* d = channels [destChannel] + destStartSample;
  21639. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21640. if (gain != 1.0f)
  21641. {
  21642. while (--numSamples >= 0)
  21643. *d++ += gain * *s++;
  21644. }
  21645. else
  21646. {
  21647. while (--numSamples >= 0)
  21648. *d++ += *s++;
  21649. }
  21650. }
  21651. }
  21652. void AudioSampleBuffer::addFrom (const int destChannel,
  21653. const int destStartSample,
  21654. const float* source,
  21655. int numSamples,
  21656. const float gain) throw()
  21657. {
  21658. jassert (isPositiveAndBelow (destChannel, numChannels));
  21659. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21660. jassert (source != 0);
  21661. if (gain != 0.0f && numSamples > 0)
  21662. {
  21663. float* d = channels [destChannel] + destStartSample;
  21664. if (gain != 1.0f)
  21665. {
  21666. while (--numSamples >= 0)
  21667. *d++ += gain * *source++;
  21668. }
  21669. else
  21670. {
  21671. while (--numSamples >= 0)
  21672. *d++ += *source++;
  21673. }
  21674. }
  21675. }
  21676. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21677. const int destStartSample,
  21678. const float* source,
  21679. int numSamples,
  21680. float startGain,
  21681. const float endGain) throw()
  21682. {
  21683. jassert (isPositiveAndBelow (destChannel, numChannels));
  21684. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21685. jassert (source != 0);
  21686. if (startGain == endGain)
  21687. {
  21688. addFrom (destChannel,
  21689. destStartSample,
  21690. source,
  21691. numSamples,
  21692. startGain);
  21693. }
  21694. else
  21695. {
  21696. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21697. {
  21698. const float increment = (endGain - startGain) / numSamples;
  21699. float* d = channels [destChannel] + destStartSample;
  21700. while (--numSamples >= 0)
  21701. {
  21702. *d++ += startGain * *source++;
  21703. startGain += increment;
  21704. }
  21705. }
  21706. }
  21707. }
  21708. void AudioSampleBuffer::copyFrom (const int destChannel,
  21709. const int destStartSample,
  21710. const AudioSampleBuffer& source,
  21711. const int sourceChannel,
  21712. const int sourceStartSample,
  21713. int numSamples) throw()
  21714. {
  21715. jassert (&source != this || sourceChannel != destChannel);
  21716. jassert (isPositiveAndBelow (destChannel, numChannels));
  21717. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21718. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  21719. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21720. if (numSamples > 0)
  21721. {
  21722. memcpy (channels [destChannel] + destStartSample,
  21723. source.channels [sourceChannel] + sourceStartSample,
  21724. sizeof (float) * numSamples);
  21725. }
  21726. }
  21727. void AudioSampleBuffer::copyFrom (const int destChannel,
  21728. const int destStartSample,
  21729. const float* source,
  21730. int numSamples) throw()
  21731. {
  21732. jassert (isPositiveAndBelow (destChannel, numChannels));
  21733. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21734. jassert (source != 0);
  21735. if (numSamples > 0)
  21736. {
  21737. memcpy (channels [destChannel] + destStartSample,
  21738. source,
  21739. sizeof (float) * numSamples);
  21740. }
  21741. }
  21742. void AudioSampleBuffer::copyFrom (const int destChannel,
  21743. const int destStartSample,
  21744. const float* source,
  21745. int numSamples,
  21746. const float gain) throw()
  21747. {
  21748. jassert (isPositiveAndBelow (destChannel, numChannels));
  21749. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21750. jassert (source != 0);
  21751. if (numSamples > 0)
  21752. {
  21753. float* d = channels [destChannel] + destStartSample;
  21754. if (gain != 1.0f)
  21755. {
  21756. if (gain == 0)
  21757. {
  21758. zeromem (d, sizeof (float) * numSamples);
  21759. }
  21760. else
  21761. {
  21762. while (--numSamples >= 0)
  21763. *d++ = gain * *source++;
  21764. }
  21765. }
  21766. else
  21767. {
  21768. memcpy (d, source, sizeof (float) * numSamples);
  21769. }
  21770. }
  21771. }
  21772. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21773. const int destStartSample,
  21774. const float* source,
  21775. int numSamples,
  21776. float startGain,
  21777. float endGain) throw()
  21778. {
  21779. jassert (isPositiveAndBelow (destChannel, numChannels));
  21780. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21781. jassert (source != 0);
  21782. if (startGain == endGain)
  21783. {
  21784. copyFrom (destChannel,
  21785. destStartSample,
  21786. source,
  21787. numSamples,
  21788. startGain);
  21789. }
  21790. else
  21791. {
  21792. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21793. {
  21794. const float increment = (endGain - startGain) / numSamples;
  21795. float* d = channels [destChannel] + destStartSample;
  21796. while (--numSamples >= 0)
  21797. {
  21798. *d++ = startGain * *source++;
  21799. startGain += increment;
  21800. }
  21801. }
  21802. }
  21803. }
  21804. void AudioSampleBuffer::findMinMax (const int channel,
  21805. const int startSample,
  21806. int numSamples,
  21807. float& minVal,
  21808. float& maxVal) const throw()
  21809. {
  21810. jassert (isPositiveAndBelow (channel, numChannels));
  21811. jassert (startSample >= 0 && startSample + numSamples <= size);
  21812. findMinAndMax (channels [channel] + startSample, numSamples, minVal, maxVal);
  21813. }
  21814. float AudioSampleBuffer::getMagnitude (const int channel,
  21815. const int startSample,
  21816. const int numSamples) const throw()
  21817. {
  21818. jassert (isPositiveAndBelow (channel, numChannels));
  21819. jassert (startSample >= 0 && startSample + numSamples <= size);
  21820. float mn, mx;
  21821. findMinMax (channel, startSample, numSamples, mn, mx);
  21822. return jmax (mn, -mn, mx, -mx);
  21823. }
  21824. float AudioSampleBuffer::getMagnitude (const int startSample,
  21825. const int numSamples) const throw()
  21826. {
  21827. float mag = 0.0f;
  21828. for (int i = 0; i < numChannels; ++i)
  21829. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  21830. return mag;
  21831. }
  21832. float AudioSampleBuffer::getRMSLevel (const int channel,
  21833. const int startSample,
  21834. const int numSamples) const throw()
  21835. {
  21836. jassert (isPositiveAndBelow (channel, numChannels));
  21837. jassert (startSample >= 0 && startSample + numSamples <= size);
  21838. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  21839. return 0.0f;
  21840. const float* const data = channels [channel] + startSample;
  21841. double sum = 0.0;
  21842. for (int i = 0; i < numSamples; ++i)
  21843. {
  21844. const float sample = data [i];
  21845. sum += sample * sample;
  21846. }
  21847. return (float) std::sqrt (sum / numSamples);
  21848. }
  21849. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  21850. const int startSample,
  21851. const int numSamples,
  21852. const int64 readerStartSample,
  21853. const bool useLeftChan,
  21854. const bool useRightChan)
  21855. {
  21856. jassert (reader != 0);
  21857. jassert (startSample >= 0 && startSample + numSamples <= size);
  21858. if (numSamples > 0)
  21859. {
  21860. int* chans[3];
  21861. if (useLeftChan == useRightChan)
  21862. {
  21863. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21864. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  21865. }
  21866. else if (useLeftChan || (reader->numChannels == 1))
  21867. {
  21868. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21869. chans[1] = 0;
  21870. }
  21871. else if (useRightChan)
  21872. {
  21873. chans[0] = 0;
  21874. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  21875. }
  21876. chans[2] = 0;
  21877. reader->read (chans, 2, readerStartSample, numSamples, true);
  21878. if (! reader->usesFloatingPointData)
  21879. {
  21880. for (int j = 0; j < 2; ++j)
  21881. {
  21882. float* const d = reinterpret_cast <float*> (chans[j]);
  21883. if (d != 0)
  21884. {
  21885. const float multiplier = 1.0f / 0x7fffffff;
  21886. for (int i = 0; i < numSamples; ++i)
  21887. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  21888. }
  21889. }
  21890. }
  21891. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  21892. {
  21893. // if this is a stereo buffer and the source was mono, dupe the first channel..
  21894. memcpy (getSampleData (1, startSample),
  21895. getSampleData (0, startSample),
  21896. sizeof (float) * numSamples);
  21897. }
  21898. }
  21899. }
  21900. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  21901. const int startSample,
  21902. const int numSamples) const
  21903. {
  21904. jassert (writer != 0);
  21905. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  21906. }
  21907. END_JUCE_NAMESPACE
  21908. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  21909. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  21910. BEGIN_JUCE_NAMESPACE
  21911. IIRFilter::IIRFilter()
  21912. : active (false)
  21913. {
  21914. reset();
  21915. }
  21916. IIRFilter::IIRFilter (const IIRFilter& other)
  21917. : active (other.active)
  21918. {
  21919. const ScopedLock sl (other.processLock);
  21920. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  21921. reset();
  21922. }
  21923. IIRFilter::~IIRFilter()
  21924. {
  21925. }
  21926. void IIRFilter::reset() throw()
  21927. {
  21928. const ScopedLock sl (processLock);
  21929. x1 = 0;
  21930. x2 = 0;
  21931. y1 = 0;
  21932. y2 = 0;
  21933. }
  21934. float IIRFilter::processSingleSampleRaw (const float in) throw()
  21935. {
  21936. float out = coefficients[0] * in
  21937. + coefficients[1] * x1
  21938. + coefficients[2] * x2
  21939. - coefficients[4] * y1
  21940. - coefficients[5] * y2;
  21941. #if JUCE_INTEL
  21942. if (! (out < -1.0e-8 || out > 1.0e-8))
  21943. out = 0;
  21944. #endif
  21945. x2 = x1;
  21946. x1 = in;
  21947. y2 = y1;
  21948. y1 = out;
  21949. return out;
  21950. }
  21951. void IIRFilter::processSamples (float* const samples,
  21952. const int numSamples) throw()
  21953. {
  21954. const ScopedLock sl (processLock);
  21955. if (active)
  21956. {
  21957. for (int i = 0; i < numSamples; ++i)
  21958. {
  21959. const float in = samples[i];
  21960. float out = coefficients[0] * in
  21961. + coefficients[1] * x1
  21962. + coefficients[2] * x2
  21963. - coefficients[4] * y1
  21964. - coefficients[5] * y2;
  21965. #if JUCE_INTEL
  21966. if (! (out < -1.0e-8 || out > 1.0e-8))
  21967. out = 0;
  21968. #endif
  21969. x2 = x1;
  21970. x1 = in;
  21971. y2 = y1;
  21972. y1 = out;
  21973. samples[i] = out;
  21974. }
  21975. }
  21976. }
  21977. void IIRFilter::makeLowPass (const double sampleRate,
  21978. const double frequency) throw()
  21979. {
  21980. jassert (sampleRate > 0);
  21981. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  21982. const double nSquared = n * n;
  21983. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21984. setCoefficients (c1,
  21985. c1 * 2.0f,
  21986. c1,
  21987. 1.0,
  21988. c1 * 2.0 * (1.0 - nSquared),
  21989. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  21990. }
  21991. void IIRFilter::makeHighPass (const double sampleRate,
  21992. const double frequency) throw()
  21993. {
  21994. const double n = tan (double_Pi * frequency / sampleRate);
  21995. const double nSquared = n * n;
  21996. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  21997. setCoefficients (c1,
  21998. c1 * -2.0f,
  21999. c1,
  22000. 1.0,
  22001. c1 * 2.0 * (nSquared - 1.0),
  22002. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22003. }
  22004. void IIRFilter::makeLowShelf (const double sampleRate,
  22005. const double cutOffFrequency,
  22006. const double Q,
  22007. const float gainFactor) throw()
  22008. {
  22009. jassert (sampleRate > 0);
  22010. jassert (Q > 0);
  22011. const double A = jmax (0.0f, gainFactor);
  22012. const double aminus1 = A - 1.0;
  22013. const double aplus1 = A + 1.0;
  22014. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22015. const double coso = std::cos (omega);
  22016. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22017. const double aminus1TimesCoso = aminus1 * coso;
  22018. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22019. A * 2.0 * (aminus1 - aplus1 * coso),
  22020. A * (aplus1 - aminus1TimesCoso - beta),
  22021. aplus1 + aminus1TimesCoso + beta,
  22022. -2.0 * (aminus1 + aplus1 * coso),
  22023. aplus1 + aminus1TimesCoso - beta);
  22024. }
  22025. void IIRFilter::makeHighShelf (const double sampleRate,
  22026. const double cutOffFrequency,
  22027. const double Q,
  22028. const float gainFactor) throw()
  22029. {
  22030. jassert (sampleRate > 0);
  22031. jassert (Q > 0);
  22032. const double A = jmax (0.0f, gainFactor);
  22033. const double aminus1 = A - 1.0;
  22034. const double aplus1 = A + 1.0;
  22035. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22036. const double coso = std::cos (omega);
  22037. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22038. const double aminus1TimesCoso = aminus1 * coso;
  22039. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22040. A * -2.0 * (aminus1 + aplus1 * coso),
  22041. A * (aplus1 + aminus1TimesCoso - beta),
  22042. aplus1 - aminus1TimesCoso + beta,
  22043. 2.0 * (aminus1 - aplus1 * coso),
  22044. aplus1 - aminus1TimesCoso - beta);
  22045. }
  22046. void IIRFilter::makeBandPass (const double sampleRate,
  22047. const double centreFrequency,
  22048. const double Q,
  22049. const float gainFactor) throw()
  22050. {
  22051. jassert (sampleRate > 0);
  22052. jassert (Q > 0);
  22053. const double A = jmax (0.0f, gainFactor);
  22054. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22055. const double alpha = 0.5 * std::sin (omega) / Q;
  22056. const double c2 = -2.0 * std::cos (omega);
  22057. const double alphaTimesA = alpha * A;
  22058. const double alphaOverA = alpha / A;
  22059. setCoefficients (1.0 + alphaTimesA,
  22060. c2,
  22061. 1.0 - alphaTimesA,
  22062. 1.0 + alphaOverA,
  22063. c2,
  22064. 1.0 - alphaOverA);
  22065. }
  22066. void IIRFilter::makeInactive() throw()
  22067. {
  22068. const ScopedLock sl (processLock);
  22069. active = false;
  22070. }
  22071. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22072. {
  22073. const ScopedLock sl (processLock);
  22074. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22075. active = other.active;
  22076. }
  22077. void IIRFilter::setCoefficients (double c1,
  22078. double c2,
  22079. double c3,
  22080. double c4,
  22081. double c5,
  22082. double c6) throw()
  22083. {
  22084. const double a = 1.0 / c4;
  22085. c1 *= a;
  22086. c2 *= a;
  22087. c3 *= a;
  22088. c5 *= a;
  22089. c6 *= a;
  22090. const ScopedLock sl (processLock);
  22091. coefficients[0] = (float) c1;
  22092. coefficients[1] = (float) c2;
  22093. coefficients[2] = (float) c3;
  22094. coefficients[3] = (float) c4;
  22095. coefficients[4] = (float) c5;
  22096. coefficients[5] = (float) c6;
  22097. active = true;
  22098. }
  22099. END_JUCE_NAMESPACE
  22100. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22101. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22102. BEGIN_JUCE_NAMESPACE
  22103. MidiBuffer::MidiBuffer() throw()
  22104. : bytesUsed (0)
  22105. {
  22106. }
  22107. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22108. : bytesUsed (0)
  22109. {
  22110. addEvent (message, 0);
  22111. }
  22112. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22113. : data (other.data),
  22114. bytesUsed (other.bytesUsed)
  22115. {
  22116. }
  22117. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22118. {
  22119. bytesUsed = other.bytesUsed;
  22120. data = other.data;
  22121. return *this;
  22122. }
  22123. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22124. {
  22125. data.swapWith (other.data);
  22126. swapVariables <int> (bytesUsed, other.bytesUsed);
  22127. }
  22128. MidiBuffer::~MidiBuffer()
  22129. {
  22130. }
  22131. inline uint8* MidiBuffer::getData() const throw()
  22132. {
  22133. return static_cast <uint8*> (data.getData());
  22134. }
  22135. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22136. {
  22137. return *static_cast <const int*> (d);
  22138. }
  22139. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22140. {
  22141. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22142. }
  22143. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22144. {
  22145. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22146. }
  22147. void MidiBuffer::clear() throw()
  22148. {
  22149. bytesUsed = 0;
  22150. }
  22151. void MidiBuffer::clear (const int startSample, const int numSamples)
  22152. {
  22153. uint8* const start = findEventAfter (getData(), startSample - 1);
  22154. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22155. if (end > start)
  22156. {
  22157. const int bytesToMove = bytesUsed - (int) (end - getData());
  22158. if (bytesToMove > 0)
  22159. memmove (start, end, bytesToMove);
  22160. bytesUsed -= (int) (end - start);
  22161. }
  22162. }
  22163. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22164. {
  22165. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22166. }
  22167. namespace MidiBufferHelpers
  22168. {
  22169. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22170. {
  22171. unsigned int byte = (unsigned int) *data;
  22172. int size = 0;
  22173. if (byte == 0xf0 || byte == 0xf7)
  22174. {
  22175. const uint8* d = data + 1;
  22176. while (d < data + maxBytes)
  22177. if (*d++ == 0xf7)
  22178. break;
  22179. size = (int) (d - data);
  22180. }
  22181. else if (byte == 0xff)
  22182. {
  22183. int n;
  22184. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22185. size = jmin (maxBytes, n + 2 + bytesLeft);
  22186. }
  22187. else if (byte >= 0x80)
  22188. {
  22189. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22190. }
  22191. return size;
  22192. }
  22193. }
  22194. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22195. {
  22196. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22197. if (numBytes > 0)
  22198. {
  22199. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22200. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22201. uint8* d = findEventAfter (getData(), sampleNumber);
  22202. const int bytesToMove = bytesUsed - (int) (d - getData());
  22203. if (bytesToMove > 0)
  22204. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22205. *reinterpret_cast <int*> (d) = sampleNumber;
  22206. d += sizeof (int);
  22207. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22208. d += sizeof (uint16);
  22209. memcpy (d, newData, numBytes);
  22210. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22211. }
  22212. }
  22213. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22214. const int startSample,
  22215. const int numSamples,
  22216. const int sampleDeltaToAdd)
  22217. {
  22218. Iterator i (otherBuffer);
  22219. i.setNextSamplePosition (startSample);
  22220. const uint8* eventData;
  22221. int eventSize, position;
  22222. while (i.getNextEvent (eventData, eventSize, position)
  22223. && (position < startSample + numSamples || numSamples < 0))
  22224. {
  22225. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22226. }
  22227. }
  22228. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22229. {
  22230. data.ensureSize (minimumNumBytes);
  22231. }
  22232. bool MidiBuffer::isEmpty() const throw()
  22233. {
  22234. return bytesUsed == 0;
  22235. }
  22236. int MidiBuffer::getNumEvents() const throw()
  22237. {
  22238. int n = 0;
  22239. const uint8* d = getData();
  22240. const uint8* const end = d + bytesUsed;
  22241. while (d < end)
  22242. {
  22243. d += getEventTotalSize (d);
  22244. ++n;
  22245. }
  22246. return n;
  22247. }
  22248. int MidiBuffer::getFirstEventTime() const throw()
  22249. {
  22250. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22251. }
  22252. int MidiBuffer::getLastEventTime() const throw()
  22253. {
  22254. if (bytesUsed == 0)
  22255. return 0;
  22256. const uint8* d = getData();
  22257. const uint8* const endData = d + bytesUsed;
  22258. for (;;)
  22259. {
  22260. const uint8* const nextOne = d + getEventTotalSize (d);
  22261. if (nextOne >= endData)
  22262. return getEventTime (d);
  22263. d = nextOne;
  22264. }
  22265. }
  22266. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22267. {
  22268. const uint8* const endData = getData() + bytesUsed;
  22269. while (d < endData && getEventTime (d) <= samplePosition)
  22270. d += getEventTotalSize (d);
  22271. return d;
  22272. }
  22273. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22274. : buffer (buffer_),
  22275. data (buffer_.getData())
  22276. {
  22277. }
  22278. MidiBuffer::Iterator::~Iterator() throw()
  22279. {
  22280. }
  22281. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22282. {
  22283. data = buffer.getData();
  22284. const uint8* dataEnd = data + buffer.bytesUsed;
  22285. while (data < dataEnd && getEventTime (data) < samplePosition)
  22286. data += getEventTotalSize (data);
  22287. }
  22288. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22289. {
  22290. if (data >= buffer.getData() + buffer.bytesUsed)
  22291. return false;
  22292. samplePosition = getEventTime (data);
  22293. numBytes = getEventDataSize (data);
  22294. data += sizeof (int) + sizeof (uint16);
  22295. midiData = data;
  22296. data += numBytes;
  22297. return true;
  22298. }
  22299. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22300. {
  22301. if (data >= buffer.getData() + buffer.bytesUsed)
  22302. return false;
  22303. samplePosition = getEventTime (data);
  22304. const int numBytes = getEventDataSize (data);
  22305. data += sizeof (int) + sizeof (uint16);
  22306. result = MidiMessage (data, numBytes, samplePosition);
  22307. data += numBytes;
  22308. return true;
  22309. }
  22310. END_JUCE_NAMESPACE
  22311. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22312. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22313. BEGIN_JUCE_NAMESPACE
  22314. namespace MidiFileHelpers
  22315. {
  22316. void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22317. {
  22318. unsigned int buffer = v & 0x7F;
  22319. while ((v >>= 7) != 0)
  22320. {
  22321. buffer <<= 8;
  22322. buffer |= ((v & 0x7F) | 0x80);
  22323. }
  22324. for (;;)
  22325. {
  22326. out.writeByte ((char) buffer);
  22327. if (buffer & 0x80)
  22328. buffer >>= 8;
  22329. else
  22330. break;
  22331. }
  22332. }
  22333. bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22334. {
  22335. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22336. data += 4;
  22337. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22338. {
  22339. bool ok = false;
  22340. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22341. {
  22342. for (int i = 0; i < 8; ++i)
  22343. {
  22344. ch = ByteOrder::bigEndianInt (data);
  22345. data += 4;
  22346. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22347. {
  22348. ok = true;
  22349. break;
  22350. }
  22351. }
  22352. }
  22353. if (! ok)
  22354. return false;
  22355. }
  22356. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22357. data += 4;
  22358. fileType = (short) ByteOrder::bigEndianShort (data);
  22359. data += 2;
  22360. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22361. data += 2;
  22362. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22363. data += 2;
  22364. bytesRemaining -= 6;
  22365. data += bytesRemaining;
  22366. return true;
  22367. }
  22368. double convertTicksToSeconds (const double time,
  22369. const MidiMessageSequence& tempoEvents,
  22370. const int timeFormat)
  22371. {
  22372. if (timeFormat > 0)
  22373. {
  22374. int numer = 4, denom = 4;
  22375. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22376. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22377. double secsPerTick = 0.5 * tickLen;
  22378. const int numEvents = tempoEvents.getNumEvents();
  22379. for (int i = 0; i < numEvents; ++i)
  22380. {
  22381. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22382. if (time <= m.getTimeStamp())
  22383. break;
  22384. if (timeFormat > 0)
  22385. {
  22386. correctedTempoTime = correctedTempoTime
  22387. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22388. }
  22389. else
  22390. {
  22391. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22392. }
  22393. tempoTime = m.getTimeStamp();
  22394. if (m.isTempoMetaEvent())
  22395. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22396. else if (m.isTimeSignatureMetaEvent())
  22397. m.getTimeSignatureInfo (numer, denom);
  22398. while (i + 1 < numEvents)
  22399. {
  22400. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22401. if (m2.getTimeStamp() == tempoTime)
  22402. {
  22403. ++i;
  22404. if (m2.isTempoMetaEvent())
  22405. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22406. else if (m2.isTimeSignatureMetaEvent())
  22407. m2.getTimeSignatureInfo (numer, denom);
  22408. }
  22409. else
  22410. {
  22411. break;
  22412. }
  22413. }
  22414. }
  22415. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22416. }
  22417. else
  22418. {
  22419. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22420. }
  22421. }
  22422. // a comparator that puts all the note-offs before note-ons that have the same time
  22423. struct Sorter
  22424. {
  22425. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22426. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22427. {
  22428. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22429. if (diff == 0)
  22430. {
  22431. if (first->message.isNoteOff() && second->message.isNoteOn())
  22432. return -1;
  22433. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22434. return 1;
  22435. else
  22436. return 0;
  22437. }
  22438. else
  22439. {
  22440. return (diff > 0) ? 1 : -1;
  22441. }
  22442. }
  22443. };
  22444. }
  22445. MidiFile::MidiFile()
  22446. : timeFormat ((short) (unsigned short) 0xe728)
  22447. {
  22448. }
  22449. MidiFile::~MidiFile()
  22450. {
  22451. clear();
  22452. }
  22453. void MidiFile::clear()
  22454. {
  22455. tracks.clear();
  22456. }
  22457. int MidiFile::getNumTracks() const throw()
  22458. {
  22459. return tracks.size();
  22460. }
  22461. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22462. {
  22463. return tracks [index];
  22464. }
  22465. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22466. {
  22467. tracks.add (new MidiMessageSequence (trackSequence));
  22468. }
  22469. short MidiFile::getTimeFormat() const throw()
  22470. {
  22471. return timeFormat;
  22472. }
  22473. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22474. {
  22475. timeFormat = (short) ticks;
  22476. }
  22477. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22478. const int subframeResolution) throw()
  22479. {
  22480. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22481. }
  22482. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22483. {
  22484. for (int i = tracks.size(); --i >= 0;)
  22485. {
  22486. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22487. for (int j = 0; j < numEvents; ++j)
  22488. {
  22489. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22490. if (m.isTempoMetaEvent())
  22491. tempoChangeEvents.addEvent (m);
  22492. }
  22493. }
  22494. }
  22495. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22496. {
  22497. for (int i = tracks.size(); --i >= 0;)
  22498. {
  22499. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22500. for (int j = 0; j < numEvents; ++j)
  22501. {
  22502. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22503. if (m.isTimeSignatureMetaEvent())
  22504. timeSigEvents.addEvent (m);
  22505. }
  22506. }
  22507. }
  22508. double MidiFile::getLastTimestamp() const
  22509. {
  22510. double t = 0.0;
  22511. for (int i = tracks.size(); --i >= 0;)
  22512. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22513. return t;
  22514. }
  22515. bool MidiFile::readFrom (InputStream& sourceStream)
  22516. {
  22517. clear();
  22518. MemoryBlock data;
  22519. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22520. // (put a sanity-check on the file size, as midi files are generally small)
  22521. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22522. {
  22523. size_t size = data.getSize();
  22524. const uint8* d = static_cast <const uint8*> (data.getData());
  22525. short fileType, expectedTracks;
  22526. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22527. {
  22528. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22529. int track = 0;
  22530. while (size > 0 && track < expectedTracks)
  22531. {
  22532. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22533. d += 4;
  22534. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22535. d += 4;
  22536. if (chunkSize <= 0)
  22537. break;
  22538. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22539. {
  22540. readNextTrack (d, chunkSize);
  22541. }
  22542. size -= chunkSize + 8;
  22543. d += chunkSize;
  22544. ++track;
  22545. }
  22546. return true;
  22547. }
  22548. }
  22549. return false;
  22550. }
  22551. void MidiFile::readNextTrack (const uint8* data, int size)
  22552. {
  22553. double time = 0;
  22554. char lastStatusByte = 0;
  22555. MidiMessageSequence result;
  22556. while (size > 0)
  22557. {
  22558. int bytesUsed;
  22559. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22560. data += bytesUsed;
  22561. size -= bytesUsed;
  22562. time += delay;
  22563. int messSize = 0;
  22564. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22565. if (messSize <= 0)
  22566. break;
  22567. size -= messSize;
  22568. data += messSize;
  22569. result.addEvent (mm);
  22570. const char firstByte = *(mm.getRawData());
  22571. if ((firstByte & 0xf0) != 0xf0)
  22572. lastStatusByte = firstByte;
  22573. }
  22574. // use a sort that puts all the note-offs before note-ons that have the same time
  22575. MidiFileHelpers::Sorter sorter;
  22576. result.list.sort (sorter, true);
  22577. result.updateMatchedPairs();
  22578. addTrack (result);
  22579. }
  22580. void MidiFile::convertTimestampTicksToSeconds()
  22581. {
  22582. MidiMessageSequence tempoEvents;
  22583. findAllTempoEvents (tempoEvents);
  22584. findAllTimeSigEvents (tempoEvents);
  22585. for (int i = 0; i < tracks.size(); ++i)
  22586. {
  22587. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22588. for (int j = ms.getNumEvents(); --j >= 0;)
  22589. {
  22590. MidiMessage& m = ms.getEventPointer(j)->message;
  22591. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22592. tempoEvents,
  22593. timeFormat));
  22594. }
  22595. }
  22596. }
  22597. bool MidiFile::writeTo (OutputStream& out)
  22598. {
  22599. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22600. out.writeIntBigEndian (6);
  22601. out.writeShortBigEndian (1); // type
  22602. out.writeShortBigEndian ((short) tracks.size());
  22603. out.writeShortBigEndian (timeFormat);
  22604. for (int i = 0; i < tracks.size(); ++i)
  22605. writeTrack (out, i);
  22606. out.flush();
  22607. return true;
  22608. }
  22609. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  22610. {
  22611. MemoryOutputStream out;
  22612. const MidiMessageSequence& ms = *tracks[trackNum];
  22613. int lastTick = 0;
  22614. char lastStatusByte = 0;
  22615. for (int i = 0; i < ms.getNumEvents(); ++i)
  22616. {
  22617. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22618. const int tick = roundToInt (mm.getTimeStamp());
  22619. const int delta = jmax (0, tick - lastTick);
  22620. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22621. lastTick = tick;
  22622. const char statusByte = *(mm.getRawData());
  22623. if ((statusByte == lastStatusByte)
  22624. && ((statusByte & 0xf0) != 0xf0)
  22625. && i > 0
  22626. && mm.getRawDataSize() > 1)
  22627. {
  22628. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22629. }
  22630. else
  22631. {
  22632. out.write (mm.getRawData(), mm.getRawDataSize());
  22633. }
  22634. lastStatusByte = statusByte;
  22635. }
  22636. out.writeByte (0);
  22637. const MidiMessage m (MidiMessage::endOfTrack());
  22638. out.write (m.getRawData(),
  22639. m.getRawDataSize());
  22640. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22641. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22642. mainOut.write (out.getData(), (int) out.getDataSize());
  22643. }
  22644. END_JUCE_NAMESPACE
  22645. /*** End of inlined file: juce_MidiFile.cpp ***/
  22646. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22647. BEGIN_JUCE_NAMESPACE
  22648. MidiKeyboardState::MidiKeyboardState()
  22649. {
  22650. zerostruct (noteStates);
  22651. }
  22652. MidiKeyboardState::~MidiKeyboardState()
  22653. {
  22654. }
  22655. void MidiKeyboardState::reset()
  22656. {
  22657. const ScopedLock sl (lock);
  22658. zerostruct (noteStates);
  22659. eventsToAdd.clear();
  22660. }
  22661. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22662. {
  22663. jassert (midiChannel >= 0 && midiChannel <= 16);
  22664. return isPositiveAndBelow (n, (int) 128)
  22665. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22666. }
  22667. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22668. {
  22669. return isPositiveAndBelow (n, (int) 128)
  22670. && (noteStates[n] & midiChannelMask) != 0;
  22671. }
  22672. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22673. {
  22674. jassert (midiChannel >= 0 && midiChannel <= 16);
  22675. jassert (isPositiveAndBelow (midiNoteNumber, (int) 128));
  22676. const ScopedLock sl (lock);
  22677. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22678. {
  22679. const int timeNow = (int) Time::getMillisecondCounter();
  22680. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22681. eventsToAdd.clear (0, timeNow - 500);
  22682. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22683. }
  22684. }
  22685. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22686. {
  22687. if (isPositiveAndBelow (midiNoteNumber, (int) 128))
  22688. {
  22689. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22690. for (int i = listeners.size(); --i >= 0;)
  22691. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22692. }
  22693. }
  22694. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22695. {
  22696. const ScopedLock sl (lock);
  22697. if (isNoteOn (midiChannel, midiNoteNumber))
  22698. {
  22699. const int timeNow = (int) Time::getMillisecondCounter();
  22700. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22701. eventsToAdd.clear (0, timeNow - 500);
  22702. noteOffInternal (midiChannel, midiNoteNumber);
  22703. }
  22704. }
  22705. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22706. {
  22707. if (isNoteOn (midiChannel, midiNoteNumber))
  22708. {
  22709. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22710. for (int i = listeners.size(); --i >= 0;)
  22711. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22712. }
  22713. }
  22714. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22715. {
  22716. const ScopedLock sl (lock);
  22717. if (midiChannel <= 0)
  22718. {
  22719. for (int i = 1; i <= 16; ++i)
  22720. allNotesOff (i);
  22721. }
  22722. else
  22723. {
  22724. for (int i = 0; i < 128; ++i)
  22725. noteOff (midiChannel, i);
  22726. }
  22727. }
  22728. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22729. {
  22730. if (message.isNoteOn())
  22731. {
  22732. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22733. }
  22734. else if (message.isNoteOff())
  22735. {
  22736. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22737. }
  22738. else if (message.isAllNotesOff())
  22739. {
  22740. for (int i = 0; i < 128; ++i)
  22741. noteOffInternal (message.getChannel(), i);
  22742. }
  22743. }
  22744. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22745. const int startSample,
  22746. const int numSamples,
  22747. const bool injectIndirectEvents)
  22748. {
  22749. MidiBuffer::Iterator i (buffer);
  22750. MidiMessage message (0xf4, 0.0);
  22751. int time;
  22752. const ScopedLock sl (lock);
  22753. while (i.getNextEvent (message, time))
  22754. processNextMidiEvent (message);
  22755. if (injectIndirectEvents)
  22756. {
  22757. MidiBuffer::Iterator i2 (eventsToAdd);
  22758. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22759. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22760. while (i2.getNextEvent (message, time))
  22761. {
  22762. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22763. buffer.addEvent (message, startSample + pos);
  22764. }
  22765. }
  22766. eventsToAdd.clear();
  22767. }
  22768. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22769. {
  22770. const ScopedLock sl (lock);
  22771. listeners.addIfNotAlreadyThere (listener);
  22772. }
  22773. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22774. {
  22775. const ScopedLock sl (lock);
  22776. listeners.removeValue (listener);
  22777. }
  22778. END_JUCE_NAMESPACE
  22779. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22780. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22781. BEGIN_JUCE_NAMESPACE
  22782. namespace MidiHelpers
  22783. {
  22784. inline uint8 initialByte (const int type, const int channel) throw()
  22785. {
  22786. return (uint8) (type | jlimit (0, 15, channel - 1));
  22787. }
  22788. inline uint8 validVelocity (const int v) throw()
  22789. {
  22790. return (uint8) jlimit (0, 127, v);
  22791. }
  22792. }
  22793. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22794. {
  22795. numBytesUsed = 0;
  22796. int v = 0;
  22797. int i;
  22798. do
  22799. {
  22800. i = (int) *data++;
  22801. if (++numBytesUsed > 6)
  22802. break;
  22803. v = (v << 7) + (i & 0x7f);
  22804. } while (i & 0x80);
  22805. return v;
  22806. }
  22807. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22808. {
  22809. // this method only works for valid starting bytes of a short midi message
  22810. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  22811. static const char messageLengths[] =
  22812. {
  22813. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22814. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22815. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22816. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22817. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22818. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22819. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22820. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22821. };
  22822. return messageLengths [firstByte & 0x7f];
  22823. }
  22824. MidiMessage::MidiMessage() throw()
  22825. : timeStamp (0),
  22826. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22827. size (2)
  22828. {
  22829. data[0] = 0xf0;
  22830. data[1] = 0xf7;
  22831. }
  22832. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  22833. : timeStamp (t),
  22834. size (dataSize)
  22835. {
  22836. jassert (dataSize > 0);
  22837. if (dataSize <= 4)
  22838. data = static_cast<uint8*> (preallocatedData.asBytes);
  22839. else
  22840. data = new uint8 [dataSize];
  22841. memcpy (data, d, dataSize);
  22842. // check that the length matches the data..
  22843. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  22844. }
  22845. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  22846. : timeStamp (t),
  22847. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22848. size (1)
  22849. {
  22850. data[0] = (uint8) byte1;
  22851. // check that the length matches the data..
  22852. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  22853. }
  22854. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  22855. : timeStamp (t),
  22856. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22857. size (2)
  22858. {
  22859. data[0] = (uint8) byte1;
  22860. data[1] = (uint8) byte2;
  22861. // check that the length matches the data..
  22862. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  22863. }
  22864. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  22865. : timeStamp (t),
  22866. data (static_cast<uint8*> (preallocatedData.asBytes)),
  22867. size (3)
  22868. {
  22869. data[0] = (uint8) byte1;
  22870. data[1] = (uint8) byte2;
  22871. data[2] = (uint8) byte3;
  22872. // check that the length matches the data..
  22873. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  22874. }
  22875. MidiMessage::MidiMessage (const MidiMessage& other)
  22876. : timeStamp (other.timeStamp),
  22877. size (other.size)
  22878. {
  22879. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22880. {
  22881. data = new uint8 [size];
  22882. memcpy (data, other.data, size);
  22883. }
  22884. else
  22885. {
  22886. data = static_cast<uint8*> (preallocatedData.asBytes);
  22887. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22888. }
  22889. }
  22890. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  22891. : timeStamp (newTimeStamp),
  22892. size (other.size)
  22893. {
  22894. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  22895. {
  22896. data = new uint8 [size];
  22897. memcpy (data, other.data, size);
  22898. }
  22899. else
  22900. {
  22901. data = static_cast<uint8*> (preallocatedData.asBytes);
  22902. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  22903. }
  22904. }
  22905. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  22906. : timeStamp (t),
  22907. data (static_cast<uint8*> (preallocatedData.asBytes))
  22908. {
  22909. const uint8* src = static_cast <const uint8*> (src_);
  22910. unsigned int byte = (unsigned int) *src;
  22911. if (byte < 0x80)
  22912. {
  22913. byte = (unsigned int) (uint8) lastStatusByte;
  22914. numBytesUsed = -1;
  22915. }
  22916. else
  22917. {
  22918. numBytesUsed = 0;
  22919. --sz;
  22920. ++src;
  22921. }
  22922. if (byte >= 0x80)
  22923. {
  22924. if (byte == 0xf0)
  22925. {
  22926. const uint8* d = src;
  22927. bool haveReadAllLengthBytes = false;
  22928. while (d < src + sz)
  22929. {
  22930. if (*d >= 0x80)
  22931. {
  22932. if (*d == 0xf7)
  22933. {
  22934. ++d; // include the trailing 0xf7 when we hit it
  22935. break;
  22936. }
  22937. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  22938. break; // bytes, assume it's the end of the sysex
  22939. ++d;
  22940. continue;
  22941. }
  22942. haveReadAllLengthBytes = true;
  22943. ++d;
  22944. }
  22945. size = 1 + (int) (d - src);
  22946. data = new uint8 [size];
  22947. *data = (uint8) byte;
  22948. memcpy (data + 1, src, size - 1);
  22949. }
  22950. else if (byte == 0xff)
  22951. {
  22952. int n;
  22953. const int bytesLeft = readVariableLengthVal (src + 1, n);
  22954. size = jmin (sz + 1, n + 2 + bytesLeft);
  22955. data = new uint8 [size];
  22956. *data = (uint8) byte;
  22957. memcpy (data + 1, src, size - 1);
  22958. }
  22959. else
  22960. {
  22961. preallocatedData.asInt32 = 0;
  22962. size = getMessageLengthFromFirstByte ((uint8) byte);
  22963. data[0] = (uint8) byte;
  22964. if (size > 1)
  22965. {
  22966. data[1] = src[0];
  22967. if (size > 2)
  22968. data[2] = src[1];
  22969. }
  22970. }
  22971. numBytesUsed += size;
  22972. }
  22973. else
  22974. {
  22975. preallocatedData.asInt32 = 0;
  22976. size = 0;
  22977. }
  22978. }
  22979. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  22980. {
  22981. if (this != &other)
  22982. {
  22983. timeStamp = other.timeStamp;
  22984. size = other.size;
  22985. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  22986. delete[] data;
  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. return *this;
  22999. }
  23000. MidiMessage::~MidiMessage()
  23001. {
  23002. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23003. delete[] data;
  23004. }
  23005. int MidiMessage::getChannel() const throw()
  23006. {
  23007. if ((data[0] & 0xf0) != 0xf0)
  23008. return (data[0] & 0xf) + 1;
  23009. else
  23010. return 0;
  23011. }
  23012. bool MidiMessage::isForChannel (const int channel) const throw()
  23013. {
  23014. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23015. return ((data[0] & 0xf) == channel - 1)
  23016. && ((data[0] & 0xf0) != 0xf0);
  23017. }
  23018. void MidiMessage::setChannel (const int channel) throw()
  23019. {
  23020. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23021. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23022. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  23023. | (uint8)(channel - 1));
  23024. }
  23025. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23026. {
  23027. return ((data[0] & 0xf0) == 0x90)
  23028. && (returnTrueForVelocity0 || data[2] != 0);
  23029. }
  23030. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23031. {
  23032. return ((data[0] & 0xf0) == 0x80)
  23033. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23034. }
  23035. bool MidiMessage::isNoteOnOrOff() const throw()
  23036. {
  23037. const int d = data[0] & 0xf0;
  23038. return (d == 0x90) || (d == 0x80);
  23039. }
  23040. int MidiMessage::getNoteNumber() const throw()
  23041. {
  23042. return data[1];
  23043. }
  23044. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23045. {
  23046. if (isNoteOnOrOff())
  23047. data[1] = newNoteNumber & 127;
  23048. }
  23049. uint8 MidiMessage::getVelocity() const throw()
  23050. {
  23051. if (isNoteOnOrOff())
  23052. return data[2];
  23053. else
  23054. return 0;
  23055. }
  23056. float MidiMessage::getFloatVelocity() const throw()
  23057. {
  23058. return getVelocity() * (1.0f / 127.0f);
  23059. }
  23060. void MidiMessage::setVelocity (const float newVelocity) throw()
  23061. {
  23062. if (isNoteOnOrOff())
  23063. data[2] = MidiHelpers::validVelocity (roundToInt (newVelocity * 127.0f));
  23064. }
  23065. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23066. {
  23067. if (isNoteOnOrOff())
  23068. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  23069. }
  23070. bool MidiMessage::isAftertouch() const throw()
  23071. {
  23072. return (data[0] & 0xf0) == 0xa0;
  23073. }
  23074. int MidiMessage::getAfterTouchValue() const throw()
  23075. {
  23076. return data[2];
  23077. }
  23078. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23079. const int noteNum,
  23080. const int aftertouchValue) throw()
  23081. {
  23082. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23083. jassert (isPositiveAndBelow (noteNum, (int) 128));
  23084. jassert (isPositiveAndBelow (aftertouchValue, (int) 128));
  23085. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  23086. noteNum & 0x7f,
  23087. aftertouchValue & 0x7f);
  23088. }
  23089. bool MidiMessage::isChannelPressure() const throw()
  23090. {
  23091. return (data[0] & 0xf0) == 0xd0;
  23092. }
  23093. int MidiMessage::getChannelPressureValue() const throw()
  23094. {
  23095. jassert (isChannelPressure());
  23096. return data[1];
  23097. }
  23098. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23099. const int pressure) throw()
  23100. {
  23101. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23102. jassert (isPositiveAndBelow (pressure, (int) 128));
  23103. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  23104. }
  23105. bool MidiMessage::isProgramChange() const throw()
  23106. {
  23107. return (data[0] & 0xf0) == 0xc0;
  23108. }
  23109. int MidiMessage::getProgramChangeNumber() const throw()
  23110. {
  23111. return data[1];
  23112. }
  23113. const MidiMessage MidiMessage::programChange (const int channel,
  23114. const int programNumber) throw()
  23115. {
  23116. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23117. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  23118. }
  23119. bool MidiMessage::isPitchWheel() const throw()
  23120. {
  23121. return (data[0] & 0xf0) == 0xe0;
  23122. }
  23123. int MidiMessage::getPitchWheelValue() const throw()
  23124. {
  23125. return data[1] | (data[2] << 7);
  23126. }
  23127. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23128. const int position) throw()
  23129. {
  23130. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23131. jassert (isPositiveAndBelow (position, (int) 0x4000));
  23132. return MidiMessage (MidiHelpers::initialByte (0xe0, channel), position & 127, (position >> 7) & 127);
  23133. }
  23134. bool MidiMessage::isController() const throw()
  23135. {
  23136. return (data[0] & 0xf0) == 0xb0;
  23137. }
  23138. int MidiMessage::getControllerNumber() const throw()
  23139. {
  23140. jassert (isController());
  23141. return data[1];
  23142. }
  23143. int MidiMessage::getControllerValue() const throw()
  23144. {
  23145. jassert (isController());
  23146. return data[2];
  23147. }
  23148. const MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) throw()
  23149. {
  23150. // the channel must be between 1 and 16 inclusive
  23151. jassert (channel > 0 && channel <= 16);
  23152. return MidiMessage (MidiHelpers::initialByte (0xb0, channel), controllerType & 127, value & 127);
  23153. }
  23154. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) throw()
  23155. {
  23156. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23157. }
  23158. const MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) throw()
  23159. {
  23160. jassert (channel > 0 && channel <= 16);
  23161. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23162. return MidiMessage (MidiHelpers::initialByte (0x90, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23163. }
  23164. const MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) throw()
  23165. {
  23166. jassert (channel > 0 && channel <= 16);
  23167. jassert (isPositiveAndBelow (noteNumber, (int) 128));
  23168. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, MidiHelpers::validVelocity (velocity));
  23169. }
  23170. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23171. {
  23172. return controllerEvent (channel, 123, 0);
  23173. }
  23174. bool MidiMessage::isAllNotesOff() const throw()
  23175. {
  23176. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  23177. }
  23178. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23179. {
  23180. return controllerEvent (channel, 120, 0);
  23181. }
  23182. bool MidiMessage::isAllSoundOff() const throw()
  23183. {
  23184. return (data[0] & 0xf0) == 0xb0 && data[1] == 120;
  23185. }
  23186. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23187. {
  23188. return controllerEvent (channel, 121, 0);
  23189. }
  23190. const MidiMessage MidiMessage::masterVolume (const float volume)
  23191. {
  23192. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23193. uint8 buf[8];
  23194. buf[0] = 0xf0;
  23195. buf[1] = 0x7f;
  23196. buf[2] = 0x7f;
  23197. buf[3] = 0x04;
  23198. buf[4] = 0x01;
  23199. buf[5] = (uint8) (vol & 0x7f);
  23200. buf[6] = (uint8) (vol >> 7);
  23201. buf[7] = 0xf7;
  23202. return MidiMessage (buf, 8);
  23203. }
  23204. bool MidiMessage::isSysEx() const throw()
  23205. {
  23206. return *data == 0xf0;
  23207. }
  23208. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23209. {
  23210. HeapBlock<uint8> m (dataSize + 2);
  23211. m[0] = 0xf0;
  23212. memcpy (m + 1, sysexData, dataSize);
  23213. m[dataSize + 1] = 0xf7;
  23214. return MidiMessage (m, dataSize + 2);
  23215. }
  23216. const uint8* MidiMessage::getSysExData() const throw()
  23217. {
  23218. return isSysEx() ? getRawData() + 1 : 0;
  23219. }
  23220. int MidiMessage::getSysExDataSize() const throw()
  23221. {
  23222. return isSysEx() ? size - 2 : 0;
  23223. }
  23224. bool MidiMessage::isMetaEvent() const throw()
  23225. {
  23226. return *data == 0xff;
  23227. }
  23228. bool MidiMessage::isActiveSense() const throw()
  23229. {
  23230. return *data == 0xfe;
  23231. }
  23232. int MidiMessage::getMetaEventType() const throw()
  23233. {
  23234. return *data != 0xff ? -1 : data[1];
  23235. }
  23236. int MidiMessage::getMetaEventLength() const throw()
  23237. {
  23238. if (*data == 0xff)
  23239. {
  23240. int n;
  23241. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23242. }
  23243. return 0;
  23244. }
  23245. const uint8* MidiMessage::getMetaEventData() const throw()
  23246. {
  23247. int n;
  23248. const uint8* d = data + 2;
  23249. readVariableLengthVal (d, n);
  23250. return d + n;
  23251. }
  23252. bool MidiMessage::isTrackMetaEvent() const throw()
  23253. {
  23254. return getMetaEventType() == 0;
  23255. }
  23256. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23257. {
  23258. return getMetaEventType() == 47;
  23259. }
  23260. bool MidiMessage::isTextMetaEvent() const throw()
  23261. {
  23262. const int t = getMetaEventType();
  23263. return t > 0 && t < 16;
  23264. }
  23265. const String MidiMessage::getTextFromTextMetaEvent() const
  23266. {
  23267. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23268. }
  23269. bool MidiMessage::isTrackNameEvent() const throw()
  23270. {
  23271. return (data[1] == 3) && (*data == 0xff);
  23272. }
  23273. bool MidiMessage::isTempoMetaEvent() const throw()
  23274. {
  23275. return (data[1] == 81) && (*data == 0xff);
  23276. }
  23277. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23278. {
  23279. return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1);
  23280. }
  23281. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23282. {
  23283. return data[3] + 1;
  23284. }
  23285. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23286. {
  23287. if (! isTempoMetaEvent())
  23288. return 0.0;
  23289. const uint8* const d = getMetaEventData();
  23290. return (((unsigned int) d[0] << 16)
  23291. | ((unsigned int) d[1] << 8)
  23292. | d[2])
  23293. / 1000000.0;
  23294. }
  23295. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23296. {
  23297. if (timeFormat > 0)
  23298. {
  23299. if (! isTempoMetaEvent())
  23300. return 0.5 / timeFormat;
  23301. return getTempoSecondsPerQuarterNote() / timeFormat;
  23302. }
  23303. else
  23304. {
  23305. const int frameCode = (-timeFormat) >> 8;
  23306. double framesPerSecond;
  23307. switch (frameCode)
  23308. {
  23309. case 24: framesPerSecond = 24.0; break;
  23310. case 25: framesPerSecond = 25.0; break;
  23311. case 29: framesPerSecond = 29.97; break;
  23312. case 30: framesPerSecond = 30.0; break;
  23313. default: framesPerSecond = 30.0; break;
  23314. }
  23315. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23316. }
  23317. }
  23318. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23319. {
  23320. uint8 d[8];
  23321. d[0] = 0xff;
  23322. d[1] = 81;
  23323. d[2] = 3;
  23324. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23325. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23326. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23327. return MidiMessage (d, 6, 0.0);
  23328. }
  23329. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23330. {
  23331. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  23332. }
  23333. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23334. {
  23335. if (isTimeSignatureMetaEvent())
  23336. {
  23337. const uint8* const d = getMetaEventData();
  23338. numerator = d[0];
  23339. denominator = 1 << d[1];
  23340. }
  23341. else
  23342. {
  23343. numerator = 4;
  23344. denominator = 4;
  23345. }
  23346. }
  23347. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23348. {
  23349. uint8 d[8];
  23350. d[0] = 0xff;
  23351. d[1] = 0x58;
  23352. d[2] = 0x04;
  23353. d[3] = (uint8) numerator;
  23354. int n = 1;
  23355. int powerOfTwo = 0;
  23356. while (n < denominator)
  23357. {
  23358. n <<= 1;
  23359. ++powerOfTwo;
  23360. }
  23361. d[4] = (uint8) powerOfTwo;
  23362. d[5] = 0x01;
  23363. d[6] = 96;
  23364. return MidiMessage (d, 7, 0.0);
  23365. }
  23366. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23367. {
  23368. uint8 d[8];
  23369. d[0] = 0xff;
  23370. d[1] = 0x20;
  23371. d[2] = 0x01;
  23372. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23373. return MidiMessage (d, 4, 0.0);
  23374. }
  23375. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23376. {
  23377. return getMetaEventType() == 89;
  23378. }
  23379. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23380. {
  23381. return (int) *getMetaEventData();
  23382. }
  23383. const MidiMessage MidiMessage::endOfTrack() throw()
  23384. {
  23385. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23386. }
  23387. bool MidiMessage::isSongPositionPointer() const throw()
  23388. {
  23389. return *data == 0xf2;
  23390. }
  23391. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23392. {
  23393. return data[1] | (data[2] << 7);
  23394. }
  23395. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23396. {
  23397. return MidiMessage (0xf2,
  23398. positionInMidiBeats & 127,
  23399. (positionInMidiBeats >> 7) & 127);
  23400. }
  23401. bool MidiMessage::isMidiStart() const throw()
  23402. {
  23403. return *data == 0xfa;
  23404. }
  23405. const MidiMessage MidiMessage::midiStart() throw()
  23406. {
  23407. return MidiMessage (0xfa);
  23408. }
  23409. bool MidiMessage::isMidiContinue() const throw()
  23410. {
  23411. return *data == 0xfb;
  23412. }
  23413. const MidiMessage MidiMessage::midiContinue() throw()
  23414. {
  23415. return MidiMessage (0xfb);
  23416. }
  23417. bool MidiMessage::isMidiStop() const throw()
  23418. {
  23419. return *data == 0xfc;
  23420. }
  23421. const MidiMessage MidiMessage::midiStop() throw()
  23422. {
  23423. return MidiMessage (0xfc);
  23424. }
  23425. bool MidiMessage::isMidiClock() const throw()
  23426. {
  23427. return *data == 0xf8;
  23428. }
  23429. const MidiMessage MidiMessage::midiClock() throw()
  23430. {
  23431. return MidiMessage (0xf8);
  23432. }
  23433. bool MidiMessage::isQuarterFrame() const throw()
  23434. {
  23435. return *data == 0xf1;
  23436. }
  23437. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23438. {
  23439. return ((int) data[1]) >> 4;
  23440. }
  23441. int MidiMessage::getQuarterFrameValue() const throw()
  23442. {
  23443. return ((int) data[1]) & 0x0f;
  23444. }
  23445. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23446. const int value) throw()
  23447. {
  23448. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23449. }
  23450. bool MidiMessage::isFullFrame() const throw()
  23451. {
  23452. return data[0] == 0xf0
  23453. && data[1] == 0x7f
  23454. && size >= 10
  23455. && data[3] == 0x01
  23456. && data[4] == 0x01;
  23457. }
  23458. void MidiMessage::getFullFrameParameters (int& hours,
  23459. int& minutes,
  23460. int& seconds,
  23461. int& frames,
  23462. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23463. {
  23464. jassert (isFullFrame());
  23465. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23466. hours = data[5] & 0x1f;
  23467. minutes = data[6];
  23468. seconds = data[7];
  23469. frames = data[8];
  23470. }
  23471. const MidiMessage MidiMessage::fullFrame (const int hours,
  23472. const int minutes,
  23473. const int seconds,
  23474. const int frames,
  23475. MidiMessage::SmpteTimecodeType timecodeType)
  23476. {
  23477. uint8 d[10];
  23478. d[0] = 0xf0;
  23479. d[1] = 0x7f;
  23480. d[2] = 0x7f;
  23481. d[3] = 0x01;
  23482. d[4] = 0x01;
  23483. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23484. d[6] = (uint8) minutes;
  23485. d[7] = (uint8) seconds;
  23486. d[8] = (uint8) frames;
  23487. d[9] = 0xf7;
  23488. return MidiMessage (d, 10, 0.0);
  23489. }
  23490. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23491. {
  23492. return data[0] == 0xf0
  23493. && data[1] == 0x7f
  23494. && data[3] == 0x06
  23495. && size > 5;
  23496. }
  23497. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23498. {
  23499. jassert (isMidiMachineControlMessage());
  23500. return (MidiMachineControlCommand) data[4];
  23501. }
  23502. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23503. {
  23504. uint8 d[6];
  23505. d[0] = 0xf0;
  23506. d[1] = 0x7f;
  23507. d[2] = 0x00;
  23508. d[3] = 0x06;
  23509. d[4] = (uint8) command;
  23510. d[5] = 0xf7;
  23511. return MidiMessage (d, 6, 0.0);
  23512. }
  23513. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23514. int& minutes,
  23515. int& seconds,
  23516. int& frames) const throw()
  23517. {
  23518. if (size >= 12
  23519. && data[0] == 0xf0
  23520. && data[1] == 0x7f
  23521. && data[3] == 0x06
  23522. && data[4] == 0x44
  23523. && data[5] == 0x06
  23524. && data[6] == 0x01)
  23525. {
  23526. hours = data[7] % 24; // (that some machines send out hours > 24)
  23527. minutes = data[8];
  23528. seconds = data[9];
  23529. frames = data[10];
  23530. return true;
  23531. }
  23532. return false;
  23533. }
  23534. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23535. int minutes,
  23536. int seconds,
  23537. int frames)
  23538. {
  23539. uint8 d[12];
  23540. d[0] = 0xf0;
  23541. d[1] = 0x7f;
  23542. d[2] = 0x00;
  23543. d[3] = 0x06;
  23544. d[4] = 0x44;
  23545. d[5] = 0x06;
  23546. d[6] = 0x01;
  23547. d[7] = (uint8) hours;
  23548. d[8] = (uint8) minutes;
  23549. d[9] = (uint8) seconds;
  23550. d[10] = (uint8) frames;
  23551. d[11] = 0xf7;
  23552. return MidiMessage (d, 12, 0.0);
  23553. }
  23554. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23555. {
  23556. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23557. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23558. if (isPositiveAndBelow (note, (int) 128))
  23559. {
  23560. String s (useSharps ? sharpNoteNames [note % 12]
  23561. : flatNoteNames [note % 12]);
  23562. if (includeOctaveNumber)
  23563. s << (note / 12 + (octaveNumForMiddleC - 5));
  23564. return s;
  23565. }
  23566. return String::empty;
  23567. }
  23568. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23569. {
  23570. noteNumber -= 12 * 6 + 9; // now 0 = A
  23571. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23572. }
  23573. const String MidiMessage::getGMInstrumentName (const int n)
  23574. {
  23575. const char* names[] =
  23576. {
  23577. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23578. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23579. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23580. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23581. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23582. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23583. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23584. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23585. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23586. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23587. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23588. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23589. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23590. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23591. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23592. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23593. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23594. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23595. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23596. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23597. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23598. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23599. "Applause", "Gunshot"
  23600. };
  23601. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23602. }
  23603. const String MidiMessage::getGMInstrumentBankName (const int n)
  23604. {
  23605. const char* names[] =
  23606. {
  23607. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23608. "Bass", "Strings", "Ensemble", "Brass",
  23609. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23610. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23611. };
  23612. return isPositiveAndBelow (n, (int) 16) ? names[n] : (const char*) 0;
  23613. }
  23614. const String MidiMessage::getRhythmInstrumentName (const int n)
  23615. {
  23616. const char* names[] =
  23617. {
  23618. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23619. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23620. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23621. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23622. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23623. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23624. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23625. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23626. "Mute Triangle", "Open Triangle"
  23627. };
  23628. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23629. }
  23630. const String MidiMessage::getControllerName (const int n)
  23631. {
  23632. const char* names[] =
  23633. {
  23634. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23635. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23636. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23637. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23638. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23639. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23640. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23641. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23642. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23643. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23644. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23645. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23646. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23647. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23648. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23649. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23650. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23651. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23652. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23654. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23655. "Poly Operation"
  23656. };
  23657. return isPositiveAndBelow (n, (int) 128) ? names[n] : (const char*) 0;
  23658. }
  23659. END_JUCE_NAMESPACE
  23660. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23661. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23662. BEGIN_JUCE_NAMESPACE
  23663. MidiMessageCollector::MidiMessageCollector()
  23664. : lastCallbackTime (0),
  23665. sampleRate (44100.0001)
  23666. {
  23667. }
  23668. MidiMessageCollector::~MidiMessageCollector()
  23669. {
  23670. }
  23671. void MidiMessageCollector::reset (const double sampleRate_)
  23672. {
  23673. jassert (sampleRate_ > 0);
  23674. const ScopedLock sl (midiCallbackLock);
  23675. sampleRate = sampleRate_;
  23676. incomingMessages.clear();
  23677. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23678. }
  23679. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23680. {
  23681. // you need to call reset() to set the correct sample rate before using this object
  23682. jassert (sampleRate != 44100.0001);
  23683. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23684. // for details of what the number should be.
  23685. jassert (message.getTimeStamp() != 0);
  23686. const ScopedLock sl (midiCallbackLock);
  23687. const int sampleNumber
  23688. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23689. incomingMessages.addEvent (message, sampleNumber);
  23690. // if the messages don't get used for over a second, we'd better
  23691. // get rid of any old ones to avoid the queue getting too big
  23692. if (sampleNumber > sampleRate)
  23693. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23694. }
  23695. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23696. const int numSamples)
  23697. {
  23698. // you need to call reset() to set the correct sample rate before using this object
  23699. jassert (sampleRate != 44100.0001);
  23700. const double timeNow = Time::getMillisecondCounterHiRes();
  23701. const double msElapsed = timeNow - lastCallbackTime;
  23702. const ScopedLock sl (midiCallbackLock);
  23703. lastCallbackTime = timeNow;
  23704. if (! incomingMessages.isEmpty())
  23705. {
  23706. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23707. int startSample = 0;
  23708. int scale = 1 << 16;
  23709. const uint8* midiData;
  23710. int numBytes, samplePosition;
  23711. MidiBuffer::Iterator iter (incomingMessages);
  23712. if (numSourceSamples > numSamples)
  23713. {
  23714. // if our list of events is longer than the buffer we're being
  23715. // asked for, scale them down to squeeze them all in..
  23716. const int maxBlockLengthToUse = numSamples << 5;
  23717. if (numSourceSamples > maxBlockLengthToUse)
  23718. {
  23719. startSample = numSourceSamples - maxBlockLengthToUse;
  23720. numSourceSamples = maxBlockLengthToUse;
  23721. iter.setNextSamplePosition (startSample);
  23722. }
  23723. scale = (numSamples << 10) / numSourceSamples;
  23724. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23725. {
  23726. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23727. destBuffer.addEvent (midiData, numBytes,
  23728. jlimit (0, numSamples - 1, samplePosition));
  23729. }
  23730. }
  23731. else
  23732. {
  23733. // if our event list is shorter than the number we need, put them
  23734. // towards the end of the buffer
  23735. startSample = numSamples - numSourceSamples;
  23736. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23737. {
  23738. destBuffer.addEvent (midiData, numBytes,
  23739. jlimit (0, numSamples - 1, samplePosition + startSample));
  23740. }
  23741. }
  23742. incomingMessages.clear();
  23743. }
  23744. }
  23745. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23746. {
  23747. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23748. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23749. addMessageToQueue (m);
  23750. }
  23751. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23752. {
  23753. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23754. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23755. addMessageToQueue (m);
  23756. }
  23757. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23758. {
  23759. addMessageToQueue (message);
  23760. }
  23761. END_JUCE_NAMESPACE
  23762. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23763. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23764. BEGIN_JUCE_NAMESPACE
  23765. MidiMessageSequence::MidiMessageSequence()
  23766. {
  23767. }
  23768. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23769. {
  23770. list.ensureStorageAllocated (other.list.size());
  23771. for (int i = 0; i < other.list.size(); ++i)
  23772. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23773. }
  23774. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23775. {
  23776. MidiMessageSequence otherCopy (other);
  23777. swapWith (otherCopy);
  23778. return *this;
  23779. }
  23780. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23781. {
  23782. list.swapWithArray (other.list);
  23783. }
  23784. MidiMessageSequence::~MidiMessageSequence()
  23785. {
  23786. }
  23787. void MidiMessageSequence::clear()
  23788. {
  23789. list.clear();
  23790. }
  23791. int MidiMessageSequence::getNumEvents() const
  23792. {
  23793. return list.size();
  23794. }
  23795. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23796. {
  23797. return list [index];
  23798. }
  23799. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23800. {
  23801. const MidiEventHolder* const meh = list [index];
  23802. if (meh != 0 && meh->noteOffObject != 0)
  23803. return meh->noteOffObject->message.getTimeStamp();
  23804. else
  23805. return 0.0;
  23806. }
  23807. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23808. {
  23809. const MidiEventHolder* const meh = list [index];
  23810. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23811. }
  23812. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23813. {
  23814. return list.indexOf (event);
  23815. }
  23816. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  23817. {
  23818. const int numEvents = list.size();
  23819. int i;
  23820. for (i = 0; i < numEvents; ++i)
  23821. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  23822. break;
  23823. return i;
  23824. }
  23825. double MidiMessageSequence::getStartTime() const
  23826. {
  23827. if (list.size() > 0)
  23828. return list.getUnchecked(0)->message.getTimeStamp();
  23829. else
  23830. return 0;
  23831. }
  23832. double MidiMessageSequence::getEndTime() const
  23833. {
  23834. if (list.size() > 0)
  23835. return list.getLast()->message.getTimeStamp();
  23836. else
  23837. return 0;
  23838. }
  23839. double MidiMessageSequence::getEventTime (const int index) const
  23840. {
  23841. if (isPositiveAndBelow (index, list.size()))
  23842. return list.getUnchecked (index)->message.getTimeStamp();
  23843. return 0.0;
  23844. }
  23845. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  23846. double timeAdjustment)
  23847. {
  23848. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  23849. timeAdjustment += newMessage.getTimeStamp();
  23850. newOne->message.setTimeStamp (timeAdjustment);
  23851. int i;
  23852. for (i = list.size(); --i >= 0;)
  23853. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  23854. break;
  23855. list.insert (i + 1, newOne);
  23856. }
  23857. void MidiMessageSequence::deleteEvent (const int index,
  23858. const bool deleteMatchingNoteUp)
  23859. {
  23860. if (isPositiveAndBelow (index, list.size()))
  23861. {
  23862. if (deleteMatchingNoteUp)
  23863. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  23864. list.remove (index);
  23865. }
  23866. }
  23867. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  23868. double timeAdjustment,
  23869. double firstAllowableTime,
  23870. double endOfAllowableDestTimes)
  23871. {
  23872. firstAllowableTime -= timeAdjustment;
  23873. endOfAllowableDestTimes -= timeAdjustment;
  23874. for (int i = 0; i < other.list.size(); ++i)
  23875. {
  23876. const MidiMessage& m = other.list.getUnchecked(i)->message;
  23877. const double t = m.getTimeStamp();
  23878. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  23879. {
  23880. MidiEventHolder* const newOne = new MidiEventHolder (m);
  23881. newOne->message.setTimeStamp (timeAdjustment + t);
  23882. list.add (newOne);
  23883. }
  23884. }
  23885. sort();
  23886. }
  23887. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  23888. const MidiMessageSequence::MidiEventHolder* const second) throw()
  23889. {
  23890. const double diff = first->message.getTimeStamp()
  23891. - second->message.getTimeStamp();
  23892. return (diff > 0) - (diff < 0);
  23893. }
  23894. void MidiMessageSequence::sort()
  23895. {
  23896. list.sort (*this, true);
  23897. }
  23898. void MidiMessageSequence::updateMatchedPairs()
  23899. {
  23900. for (int i = 0; i < list.size(); ++i)
  23901. {
  23902. const MidiMessage& m1 = list.getUnchecked(i)->message;
  23903. if (m1.isNoteOn())
  23904. {
  23905. list.getUnchecked(i)->noteOffObject = 0;
  23906. const int note = m1.getNoteNumber();
  23907. const int chan = m1.getChannel();
  23908. const int len = list.size();
  23909. for (int j = i + 1; j < len; ++j)
  23910. {
  23911. const MidiMessage& m = list.getUnchecked(j)->message;
  23912. if (m.getNoteNumber() == note && m.getChannel() == chan)
  23913. {
  23914. if (m.isNoteOff())
  23915. {
  23916. list.getUnchecked(i)->noteOffObject = list[j];
  23917. break;
  23918. }
  23919. else if (m.isNoteOn())
  23920. {
  23921. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  23922. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  23923. list.getUnchecked(i)->noteOffObject = list[j];
  23924. break;
  23925. }
  23926. }
  23927. }
  23928. }
  23929. }
  23930. }
  23931. void MidiMessageSequence::addTimeToMessages (const double delta)
  23932. {
  23933. for (int i = list.size(); --i >= 0;)
  23934. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  23935. + delta);
  23936. }
  23937. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  23938. MidiMessageSequence& destSequence,
  23939. const bool alsoIncludeMetaEvents) const
  23940. {
  23941. for (int i = 0; i < list.size(); ++i)
  23942. {
  23943. const MidiMessage& mm = list.getUnchecked(i)->message;
  23944. if (mm.isForChannel (channelNumberToExtract)
  23945. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  23946. {
  23947. destSequence.addEvent (mm);
  23948. }
  23949. }
  23950. }
  23951. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  23952. {
  23953. for (int i = 0; i < list.size(); ++i)
  23954. {
  23955. const MidiMessage& mm = list.getUnchecked(i)->message;
  23956. if (mm.isSysEx())
  23957. destSequence.addEvent (mm);
  23958. }
  23959. }
  23960. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  23961. {
  23962. for (int i = list.size(); --i >= 0;)
  23963. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  23964. list.remove(i);
  23965. }
  23966. void MidiMessageSequence::deleteSysExMessages()
  23967. {
  23968. for (int i = list.size(); --i >= 0;)
  23969. if (list.getUnchecked(i)->message.isSysEx())
  23970. list.remove(i);
  23971. }
  23972. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  23973. const double time,
  23974. OwnedArray<MidiMessage>& dest)
  23975. {
  23976. bool doneProg = false;
  23977. bool donePitchWheel = false;
  23978. Array <int> doneControllers;
  23979. doneControllers.ensureStorageAllocated (32);
  23980. for (int i = list.size(); --i >= 0;)
  23981. {
  23982. const MidiMessage& mm = list.getUnchecked(i)->message;
  23983. if (mm.isForChannel (channelNumber)
  23984. && mm.getTimeStamp() <= time)
  23985. {
  23986. if (mm.isProgramChange())
  23987. {
  23988. if (! doneProg)
  23989. {
  23990. dest.add (new MidiMessage (mm, 0.0));
  23991. doneProg = true;
  23992. }
  23993. }
  23994. else if (mm.isController())
  23995. {
  23996. if (! doneControllers.contains (mm.getControllerNumber()))
  23997. {
  23998. dest.add (new MidiMessage (mm, 0.0));
  23999. doneControllers.add (mm.getControllerNumber());
  24000. }
  24001. }
  24002. else if (mm.isPitchWheel())
  24003. {
  24004. if (! donePitchWheel)
  24005. {
  24006. dest.add (new MidiMessage (mm, 0.0));
  24007. donePitchWheel = true;
  24008. }
  24009. }
  24010. }
  24011. }
  24012. }
  24013. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24014. : message (message_),
  24015. noteOffObject (0)
  24016. {
  24017. }
  24018. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24019. {
  24020. }
  24021. END_JUCE_NAMESPACE
  24022. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24023. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24024. BEGIN_JUCE_NAMESPACE
  24025. AudioPluginFormat::AudioPluginFormat() throw()
  24026. {
  24027. }
  24028. AudioPluginFormat::~AudioPluginFormat()
  24029. {
  24030. }
  24031. END_JUCE_NAMESPACE
  24032. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24033. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24034. BEGIN_JUCE_NAMESPACE
  24035. AudioPluginFormatManager::AudioPluginFormatManager()
  24036. {
  24037. }
  24038. AudioPluginFormatManager::~AudioPluginFormatManager()
  24039. {
  24040. clearSingletonInstance();
  24041. }
  24042. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24043. void AudioPluginFormatManager::addDefaultFormats()
  24044. {
  24045. #if JUCE_DEBUG
  24046. // you should only call this method once!
  24047. for (int i = formats.size(); --i >= 0;)
  24048. {
  24049. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24050. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24051. #endif
  24052. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24053. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24054. #endif
  24055. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24056. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24057. #endif
  24058. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24059. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24060. #endif
  24061. }
  24062. #endif
  24063. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24064. formats.add (new AudioUnitPluginFormat());
  24065. #endif
  24066. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24067. formats.add (new VSTPluginFormat());
  24068. #endif
  24069. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24070. formats.add (new DirectXPluginFormat());
  24071. #endif
  24072. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24073. formats.add (new LADSPAPluginFormat());
  24074. #endif
  24075. }
  24076. int AudioPluginFormatManager::getNumFormats()
  24077. {
  24078. return formats.size();
  24079. }
  24080. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24081. {
  24082. return formats [index];
  24083. }
  24084. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24085. {
  24086. formats.add (format);
  24087. }
  24088. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24089. String& errorMessage) const
  24090. {
  24091. AudioPluginInstance* result = 0;
  24092. for (int i = 0; i < formats.size(); ++i)
  24093. {
  24094. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24095. if (result != 0)
  24096. break;
  24097. }
  24098. if (result == 0)
  24099. {
  24100. if (! doesPluginStillExist (description))
  24101. errorMessage = TRANS ("This plug-in file no longer exists");
  24102. else
  24103. errorMessage = TRANS ("This plug-in failed to load correctly");
  24104. }
  24105. return result;
  24106. }
  24107. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24108. {
  24109. for (int i = 0; i < formats.size(); ++i)
  24110. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24111. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24112. return false;
  24113. }
  24114. END_JUCE_NAMESPACE
  24115. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24116. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24117. #define JUCE_PLUGIN_HOST 1
  24118. BEGIN_JUCE_NAMESPACE
  24119. AudioPluginInstance::AudioPluginInstance()
  24120. {
  24121. }
  24122. AudioPluginInstance::~AudioPluginInstance()
  24123. {
  24124. }
  24125. void* AudioPluginInstance::getPlatformSpecificData()
  24126. {
  24127. return 0;
  24128. }
  24129. END_JUCE_NAMESPACE
  24130. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24131. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24132. BEGIN_JUCE_NAMESPACE
  24133. KnownPluginList::KnownPluginList()
  24134. {
  24135. }
  24136. KnownPluginList::~KnownPluginList()
  24137. {
  24138. }
  24139. void KnownPluginList::clear()
  24140. {
  24141. if (types.size() > 0)
  24142. {
  24143. types.clear();
  24144. sendChangeMessage();
  24145. }
  24146. }
  24147. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24148. {
  24149. for (int i = 0; i < types.size(); ++i)
  24150. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24151. return types.getUnchecked(i);
  24152. return 0;
  24153. }
  24154. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24155. {
  24156. for (int i = 0; i < types.size(); ++i)
  24157. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24158. return types.getUnchecked(i);
  24159. return 0;
  24160. }
  24161. bool KnownPluginList::addType (const PluginDescription& type)
  24162. {
  24163. for (int i = types.size(); --i >= 0;)
  24164. {
  24165. if (types.getUnchecked(i)->isDuplicateOf (type))
  24166. {
  24167. // strange - found a duplicate plugin with different info..
  24168. jassert (types.getUnchecked(i)->name == type.name);
  24169. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24170. *types.getUnchecked(i) = type;
  24171. return false;
  24172. }
  24173. }
  24174. types.add (new PluginDescription (type));
  24175. sendChangeMessage();
  24176. return true;
  24177. }
  24178. void KnownPluginList::removeType (const int index)
  24179. {
  24180. types.remove (index);
  24181. sendChangeMessage();
  24182. }
  24183. namespace
  24184. {
  24185. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24186. {
  24187. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24188. return File (fileOrIdentifier).getLastModificationTime();
  24189. return Time();
  24190. }
  24191. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24192. {
  24193. return t1 != t2 || t1 == Time();
  24194. }
  24195. }
  24196. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24197. {
  24198. if (getTypeForFile (fileOrIdentifier) == 0)
  24199. return false;
  24200. for (int i = types.size(); --i >= 0;)
  24201. {
  24202. const PluginDescription* const d = types.getUnchecked(i);
  24203. if (d->fileOrIdentifier == fileOrIdentifier
  24204. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24205. {
  24206. return false;
  24207. }
  24208. }
  24209. return true;
  24210. }
  24211. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24212. const bool dontRescanIfAlreadyInList,
  24213. OwnedArray <PluginDescription>& typesFound,
  24214. AudioPluginFormat& format)
  24215. {
  24216. bool addedOne = false;
  24217. if (dontRescanIfAlreadyInList
  24218. && getTypeForFile (fileOrIdentifier) != 0)
  24219. {
  24220. bool needsRescanning = false;
  24221. for (int i = types.size(); --i >= 0;)
  24222. {
  24223. const PluginDescription* const d = types.getUnchecked(i);
  24224. if (d->fileOrIdentifier == fileOrIdentifier)
  24225. {
  24226. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24227. needsRescanning = true;
  24228. else
  24229. typesFound.add (new PluginDescription (*d));
  24230. }
  24231. }
  24232. if (! needsRescanning)
  24233. return false;
  24234. }
  24235. OwnedArray <PluginDescription> found;
  24236. format.findAllTypesForFile (found, fileOrIdentifier);
  24237. for (int i = 0; i < found.size(); ++i)
  24238. {
  24239. PluginDescription* const desc = found.getUnchecked(i);
  24240. jassert (desc != 0);
  24241. if (addType (*desc))
  24242. addedOne = true;
  24243. typesFound.add (new PluginDescription (*desc));
  24244. }
  24245. return addedOne;
  24246. }
  24247. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24248. OwnedArray <PluginDescription>& typesFound)
  24249. {
  24250. for (int i = 0; i < files.size(); ++i)
  24251. {
  24252. bool loaded = false;
  24253. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24254. {
  24255. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24256. if (scanAndAddFile (files[i], true, typesFound, *format))
  24257. loaded = true;
  24258. }
  24259. if (! loaded)
  24260. {
  24261. const File f (files[i]);
  24262. if (f.isDirectory())
  24263. {
  24264. StringArray s;
  24265. {
  24266. Array<File> subFiles;
  24267. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24268. for (int j = 0; j < subFiles.size(); ++j)
  24269. s.add (subFiles.getReference(j).getFullPathName());
  24270. }
  24271. scanAndAddDragAndDroppedFiles (s, typesFound);
  24272. }
  24273. }
  24274. }
  24275. }
  24276. class PluginSorter
  24277. {
  24278. public:
  24279. KnownPluginList::SortMethod method;
  24280. PluginSorter() throw() {}
  24281. int compareElements (const PluginDescription* const first,
  24282. const PluginDescription* const second) const
  24283. {
  24284. int diff = 0;
  24285. if (method == KnownPluginList::sortByCategory)
  24286. diff = first->category.compareLexicographically (second->category);
  24287. else if (method == KnownPluginList::sortByManufacturer)
  24288. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24289. else if (method == KnownPluginList::sortByFileSystemLocation)
  24290. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24291. .upToLastOccurrenceOf ("/", false, false)
  24292. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24293. .upToLastOccurrenceOf ("/", false, false));
  24294. if (diff == 0)
  24295. diff = first->name.compareLexicographically (second->name);
  24296. return diff;
  24297. }
  24298. };
  24299. void KnownPluginList::sort (const SortMethod method)
  24300. {
  24301. if (method != defaultOrder)
  24302. {
  24303. PluginSorter sorter;
  24304. sorter.method = method;
  24305. types.sort (sorter, true);
  24306. sendChangeMessage();
  24307. }
  24308. }
  24309. XmlElement* KnownPluginList::createXml() const
  24310. {
  24311. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24312. for (int i = 0; i < types.size(); ++i)
  24313. e->addChildElement (types.getUnchecked(i)->createXml());
  24314. return e;
  24315. }
  24316. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24317. {
  24318. clear();
  24319. if (xml.hasTagName ("KNOWNPLUGINS"))
  24320. {
  24321. forEachXmlChildElement (xml, e)
  24322. {
  24323. PluginDescription info;
  24324. if (info.loadFromXml (*e))
  24325. addType (info);
  24326. }
  24327. }
  24328. }
  24329. const int menuIdBase = 0x324503f4;
  24330. // This is used to turn a bunch of paths into a nested menu structure.
  24331. struct PluginFilesystemTree
  24332. {
  24333. private:
  24334. String folder;
  24335. OwnedArray <PluginFilesystemTree> subFolders;
  24336. Array <PluginDescription*> plugins;
  24337. void addPlugin (PluginDescription* const pd, const String& path)
  24338. {
  24339. if (path.isEmpty())
  24340. {
  24341. plugins.add (pd);
  24342. }
  24343. else
  24344. {
  24345. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24346. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24347. for (int i = subFolders.size(); --i >= 0;)
  24348. {
  24349. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24350. {
  24351. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24352. return;
  24353. }
  24354. }
  24355. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24356. newFolder->folder = firstSubFolder;
  24357. subFolders.add (newFolder);
  24358. newFolder->addPlugin (pd, remainingPath);
  24359. }
  24360. }
  24361. // removes any deeply nested folders that don't contain any actual plugins
  24362. void optimise()
  24363. {
  24364. for (int i = subFolders.size(); --i >= 0;)
  24365. {
  24366. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24367. sub->optimise();
  24368. if (sub->plugins.size() == 0)
  24369. {
  24370. for (int j = 0; j < sub->subFolders.size(); ++j)
  24371. subFolders.add (sub->subFolders.getUnchecked(j));
  24372. sub->subFolders.clear (false);
  24373. subFolders.remove (i);
  24374. }
  24375. }
  24376. }
  24377. public:
  24378. void buildTree (const Array <PluginDescription*>& allPlugins)
  24379. {
  24380. for (int i = 0; i < allPlugins.size(); ++i)
  24381. {
  24382. String path (allPlugins.getUnchecked(i)
  24383. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24384. .upToLastOccurrenceOf ("/", false, false));
  24385. if (path.substring (1, 2) == ":")
  24386. path = path.substring (2);
  24387. addPlugin (allPlugins.getUnchecked(i), path);
  24388. }
  24389. optimise();
  24390. }
  24391. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24392. {
  24393. int i;
  24394. for (i = 0; i < subFolders.size(); ++i)
  24395. {
  24396. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24397. PopupMenu subMenu;
  24398. sub->addToMenu (subMenu, allPlugins);
  24399. #if JUCE_MAC
  24400. // avoid the special AU formatting nonsense on Mac..
  24401. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24402. #else
  24403. m.addSubMenu (sub->folder, subMenu);
  24404. #endif
  24405. }
  24406. for (i = 0; i < plugins.size(); ++i)
  24407. {
  24408. PluginDescription* const plugin = plugins.getUnchecked(i);
  24409. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24410. plugin->name, true, false);
  24411. }
  24412. }
  24413. };
  24414. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24415. {
  24416. Array <PluginDescription*> sorted;
  24417. {
  24418. PluginSorter sorter;
  24419. sorter.method = sortMethod;
  24420. for (int i = 0; i < types.size(); ++i)
  24421. sorted.addSorted (sorter, types.getUnchecked(i));
  24422. }
  24423. if (sortMethod == sortByCategory
  24424. || sortMethod == sortByManufacturer)
  24425. {
  24426. String lastSubMenuName;
  24427. PopupMenu sub;
  24428. for (int i = 0; i < sorted.size(); ++i)
  24429. {
  24430. const PluginDescription* const pd = sorted.getUnchecked(i);
  24431. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24432. : pd->manufacturerName);
  24433. if (! thisSubMenuName.containsNonWhitespaceChars())
  24434. thisSubMenuName = "Other";
  24435. if (thisSubMenuName != lastSubMenuName)
  24436. {
  24437. if (sub.getNumItems() > 0)
  24438. {
  24439. menu.addSubMenu (lastSubMenuName, sub);
  24440. sub.clear();
  24441. }
  24442. lastSubMenuName = thisSubMenuName;
  24443. }
  24444. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24445. }
  24446. if (sub.getNumItems() > 0)
  24447. menu.addSubMenu (lastSubMenuName, sub);
  24448. }
  24449. else if (sortMethod == sortByFileSystemLocation)
  24450. {
  24451. PluginFilesystemTree root;
  24452. root.buildTree (sorted);
  24453. root.addToMenu (menu, types);
  24454. }
  24455. else
  24456. {
  24457. for (int i = 0; i < sorted.size(); ++i)
  24458. {
  24459. const PluginDescription* const pd = sorted.getUnchecked(i);
  24460. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24461. }
  24462. }
  24463. }
  24464. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24465. {
  24466. const int i = menuResultCode - menuIdBase;
  24467. return isPositiveAndBelow (i, types.size()) ? i : -1;
  24468. }
  24469. END_JUCE_NAMESPACE
  24470. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24471. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24472. BEGIN_JUCE_NAMESPACE
  24473. PluginDescription::PluginDescription()
  24474. : uid (0),
  24475. isInstrument (false),
  24476. numInputChannels (0),
  24477. numOutputChannels (0)
  24478. {
  24479. }
  24480. PluginDescription::~PluginDescription()
  24481. {
  24482. }
  24483. PluginDescription::PluginDescription (const PluginDescription& other)
  24484. : name (other.name),
  24485. descriptiveName (other.descriptiveName),
  24486. pluginFormatName (other.pluginFormatName),
  24487. category (other.category),
  24488. manufacturerName (other.manufacturerName),
  24489. version (other.version),
  24490. fileOrIdentifier (other.fileOrIdentifier),
  24491. lastFileModTime (other.lastFileModTime),
  24492. uid (other.uid),
  24493. isInstrument (other.isInstrument),
  24494. numInputChannels (other.numInputChannels),
  24495. numOutputChannels (other.numOutputChannels)
  24496. {
  24497. }
  24498. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24499. {
  24500. name = other.name;
  24501. descriptiveName = other.descriptiveName;
  24502. pluginFormatName = other.pluginFormatName;
  24503. category = other.category;
  24504. manufacturerName = other.manufacturerName;
  24505. version = other.version;
  24506. fileOrIdentifier = other.fileOrIdentifier;
  24507. uid = other.uid;
  24508. isInstrument = other.isInstrument;
  24509. lastFileModTime = other.lastFileModTime;
  24510. numInputChannels = other.numInputChannels;
  24511. numOutputChannels = other.numOutputChannels;
  24512. return *this;
  24513. }
  24514. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24515. {
  24516. return fileOrIdentifier == other.fileOrIdentifier
  24517. && uid == other.uid;
  24518. }
  24519. const String PluginDescription::createIdentifierString() const
  24520. {
  24521. return pluginFormatName
  24522. + "-" + name
  24523. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24524. + "-" + String::toHexString (uid);
  24525. }
  24526. XmlElement* PluginDescription::createXml() const
  24527. {
  24528. XmlElement* const e = new XmlElement ("PLUGIN");
  24529. e->setAttribute ("name", name);
  24530. if (descriptiveName != name)
  24531. e->setAttribute ("descriptiveName", descriptiveName);
  24532. e->setAttribute ("format", pluginFormatName);
  24533. e->setAttribute ("category", category);
  24534. e->setAttribute ("manufacturer", manufacturerName);
  24535. e->setAttribute ("version", version);
  24536. e->setAttribute ("file", fileOrIdentifier);
  24537. e->setAttribute ("uid", String::toHexString (uid));
  24538. e->setAttribute ("isInstrument", isInstrument);
  24539. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24540. e->setAttribute ("numInputs", numInputChannels);
  24541. e->setAttribute ("numOutputs", numOutputChannels);
  24542. return e;
  24543. }
  24544. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24545. {
  24546. if (xml.hasTagName ("PLUGIN"))
  24547. {
  24548. name = xml.getStringAttribute ("name");
  24549. descriptiveName = xml.getStringAttribute ("name", name);
  24550. pluginFormatName = xml.getStringAttribute ("format");
  24551. category = xml.getStringAttribute ("category");
  24552. manufacturerName = xml.getStringAttribute ("manufacturer");
  24553. version = xml.getStringAttribute ("version");
  24554. fileOrIdentifier = xml.getStringAttribute ("file");
  24555. uid = xml.getStringAttribute ("uid").getHexValue32();
  24556. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24557. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24558. numInputChannels = xml.getIntAttribute ("numInputs");
  24559. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24560. return true;
  24561. }
  24562. return false;
  24563. }
  24564. END_JUCE_NAMESPACE
  24565. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24566. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24567. BEGIN_JUCE_NAMESPACE
  24568. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24569. AudioPluginFormat& formatToLookFor,
  24570. FileSearchPath directoriesToSearch,
  24571. const bool recursive,
  24572. const File& deadMansPedalFile_)
  24573. : list (listToAddTo),
  24574. format (formatToLookFor),
  24575. deadMansPedalFile (deadMansPedalFile_),
  24576. nextIndex (0),
  24577. progress (0)
  24578. {
  24579. directoriesToSearch.removeRedundantPaths();
  24580. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24581. // If any plugins have crashed recently when being loaded, move them to the
  24582. // end of the list to give the others a chance to load correctly..
  24583. const StringArray crashedPlugins (getDeadMansPedalFile());
  24584. for (int i = 0; i < crashedPlugins.size(); ++i)
  24585. {
  24586. const String f = crashedPlugins[i];
  24587. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24588. if (f == filesOrIdentifiersToScan[j])
  24589. filesOrIdentifiersToScan.move (j, -1);
  24590. }
  24591. }
  24592. PluginDirectoryScanner::~PluginDirectoryScanner()
  24593. {
  24594. }
  24595. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24596. {
  24597. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24598. }
  24599. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24600. {
  24601. String file (filesOrIdentifiersToScan [nextIndex]);
  24602. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24603. {
  24604. OwnedArray <PluginDescription> typesFound;
  24605. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24606. StringArray crashedPlugins (getDeadMansPedalFile());
  24607. crashedPlugins.removeString (file);
  24608. crashedPlugins.add (file);
  24609. setDeadMansPedalFile (crashedPlugins);
  24610. list.scanAndAddFile (file,
  24611. dontRescanIfAlreadyInList,
  24612. typesFound,
  24613. format);
  24614. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24615. crashedPlugins.removeString (file);
  24616. setDeadMansPedalFile (crashedPlugins);
  24617. if (typesFound.size() == 0)
  24618. failedFiles.add (file);
  24619. }
  24620. return skipNextFile();
  24621. }
  24622. bool PluginDirectoryScanner::skipNextFile()
  24623. {
  24624. if (nextIndex >= filesOrIdentifiersToScan.size())
  24625. return false;
  24626. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24627. return nextIndex < filesOrIdentifiersToScan.size();
  24628. }
  24629. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24630. {
  24631. StringArray lines;
  24632. if (deadMansPedalFile != File::nonexistent)
  24633. {
  24634. lines.addLines (deadMansPedalFile.loadFileAsString());
  24635. lines.removeEmptyStrings();
  24636. }
  24637. return lines;
  24638. }
  24639. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24640. {
  24641. if (deadMansPedalFile != File::nonexistent)
  24642. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24643. }
  24644. END_JUCE_NAMESPACE
  24645. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24646. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24647. BEGIN_JUCE_NAMESPACE
  24648. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24649. const File& deadMansPedalFile_,
  24650. PropertiesFile* const propertiesToUse_)
  24651. : list (listToEdit),
  24652. deadMansPedalFile (deadMansPedalFile_),
  24653. optionsButton ("Options..."),
  24654. propertiesToUse (propertiesToUse_)
  24655. {
  24656. listBox.setModel (this);
  24657. addAndMakeVisible (&listBox);
  24658. addAndMakeVisible (&optionsButton);
  24659. optionsButton.addListener (this);
  24660. optionsButton.setTriggeredOnMouseDown (true);
  24661. setSize (400, 600);
  24662. list.addChangeListener (this);
  24663. changeListenerCallback (0);
  24664. }
  24665. PluginListComponent::~PluginListComponent()
  24666. {
  24667. list.removeChangeListener (this);
  24668. }
  24669. void PluginListComponent::resized()
  24670. {
  24671. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24672. optionsButton.changeWidthToFitText (24);
  24673. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24674. }
  24675. void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
  24676. {
  24677. listBox.updateContent();
  24678. listBox.repaint();
  24679. }
  24680. int PluginListComponent::getNumRows()
  24681. {
  24682. return list.getNumTypes();
  24683. }
  24684. void PluginListComponent::paintListBoxItem (int row,
  24685. Graphics& g,
  24686. int width, int height,
  24687. bool rowIsSelected)
  24688. {
  24689. if (rowIsSelected)
  24690. g.fillAll (findColour (TextEditor::highlightColourId));
  24691. const PluginDescription* const pd = list.getType (row);
  24692. if (pd != 0)
  24693. {
  24694. GlyphArrangement ga;
  24695. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24696. g.setColour (Colours::black);
  24697. ga.draw (g);
  24698. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24699. String desc;
  24700. desc << pd->pluginFormatName
  24701. << (pd->isInstrument ? " instrument" : " effect")
  24702. << " - "
  24703. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24704. << " / "
  24705. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24706. if (pd->manufacturerName.isNotEmpty())
  24707. desc << " - " << pd->manufacturerName;
  24708. if (pd->version.isNotEmpty())
  24709. desc << " - " << pd->version;
  24710. if (pd->category.isNotEmpty())
  24711. desc << " - category: '" << pd->category << '\'';
  24712. g.setColour (Colours::grey);
  24713. ga.clear();
  24714. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24715. ga.draw (g);
  24716. }
  24717. }
  24718. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24719. {
  24720. list.removeType (lastRowSelected);
  24721. }
  24722. void PluginListComponent::buttonClicked (Button* button)
  24723. {
  24724. if (button == &optionsButton)
  24725. {
  24726. PopupMenu menu;
  24727. menu.addItem (1, TRANS("Clear list"));
  24728. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24729. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24730. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24731. menu.addSeparator();
  24732. menu.addItem (2, TRANS("Sort alphabetically"));
  24733. menu.addItem (3, TRANS("Sort by category"));
  24734. menu.addItem (4, TRANS("Sort by manufacturer"));
  24735. menu.addSeparator();
  24736. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24737. {
  24738. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24739. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24740. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24741. }
  24742. const int r = menu.showAt (&optionsButton);
  24743. if (r == 1)
  24744. {
  24745. list.clear();
  24746. }
  24747. else if (r == 2)
  24748. {
  24749. list.sort (KnownPluginList::sortAlphabetically);
  24750. }
  24751. else if (r == 3)
  24752. {
  24753. list.sort (KnownPluginList::sortByCategory);
  24754. }
  24755. else if (r == 4)
  24756. {
  24757. list.sort (KnownPluginList::sortByManufacturer);
  24758. }
  24759. else if (r == 5)
  24760. {
  24761. const SparseSet <int> selected (listBox.getSelectedRows());
  24762. for (int i = list.getNumTypes(); --i >= 0;)
  24763. if (selected.contains (i))
  24764. list.removeType (i);
  24765. }
  24766. else if (r == 6)
  24767. {
  24768. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  24769. if (desc != 0)
  24770. {
  24771. if (File (desc->fileOrIdentifier).existsAsFile())
  24772. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24773. }
  24774. }
  24775. else if (r == 7)
  24776. {
  24777. for (int i = list.getNumTypes(); --i >= 0;)
  24778. {
  24779. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24780. {
  24781. list.removeType (i);
  24782. }
  24783. }
  24784. }
  24785. else if (r != 0)
  24786. {
  24787. typeToScan = r - 10;
  24788. startTimer (1);
  24789. }
  24790. }
  24791. }
  24792. void PluginListComponent::timerCallback()
  24793. {
  24794. stopTimer();
  24795. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24796. }
  24797. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24798. {
  24799. return true;
  24800. }
  24801. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24802. {
  24803. OwnedArray <PluginDescription> typesFound;
  24804. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24805. }
  24806. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24807. {
  24808. if (format == 0)
  24809. return;
  24810. FileSearchPath path (format->getDefaultLocationsToSearch());
  24811. if (propertiesToUse != 0)
  24812. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24813. {
  24814. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24815. FileSearchPathListComponent pathList;
  24816. pathList.setSize (500, 300);
  24817. pathList.setPath (path);
  24818. aw.addCustomComponent (&pathList);
  24819. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24820. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24821. if (aw.runModalLoop() == 0)
  24822. return;
  24823. path = pathList.getPath();
  24824. }
  24825. if (propertiesToUse != 0)
  24826. {
  24827. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24828. propertiesToUse->saveIfNeeded();
  24829. }
  24830. double progress = 0.0;
  24831. AlertWindow aw (TRANS("Scanning for plugins..."),
  24832. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  24833. aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
  24834. aw.addProgressBarComponent (progress);
  24835. aw.enterModalState();
  24836. MessageManager::getInstance()->runDispatchLoopUntil (300);
  24837. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  24838. for (;;)
  24839. {
  24840. aw.setMessage (TRANS("Testing:\n\n")
  24841. + scanner.getNextPluginFileThatWillBeScanned());
  24842. MessageManager::getInstance()->runDispatchLoopUntil (20);
  24843. if (! scanner.scanNextFile (true))
  24844. break;
  24845. if (! aw.isCurrentlyModal())
  24846. break;
  24847. progress = scanner.getProgress();
  24848. }
  24849. if (scanner.getFailedFiles().size() > 0)
  24850. {
  24851. StringArray shortNames;
  24852. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  24853. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  24854. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  24855. TRANS("Scan complete"),
  24856. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  24857. + shortNames.joinIntoString (", "));
  24858. }
  24859. }
  24860. END_JUCE_NAMESPACE
  24861. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  24862. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  24863. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  24864. #include <AudioUnit/AudioUnit.h>
  24865. #include <AudioUnit/AUCocoaUIView.h>
  24866. #include <CoreAudioKit/AUGenericView.h>
  24867. #if JUCE_SUPPORT_CARBON
  24868. #include <AudioToolbox/AudioUnitUtilities.h>
  24869. #include <AudioUnit/AudioUnitCarbonView.h>
  24870. #endif
  24871. BEGIN_JUCE_NAMESPACE
  24872. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24873. #endif
  24874. #if JUCE_MAC
  24875. // Change this to disable logging of various activities
  24876. #ifndef AU_LOGGING
  24877. #define AU_LOGGING 1
  24878. #endif
  24879. #if AU_LOGGING
  24880. #define log(a) Logger::writeToLog(a);
  24881. #else
  24882. #define log(a)
  24883. #endif
  24884. namespace AudioUnitFormatHelpers
  24885. {
  24886. static int insideCallback = 0;
  24887. const String osTypeToString (OSType type)
  24888. {
  24889. char s[4];
  24890. s[0] = (char) (((uint32) type) >> 24);
  24891. s[1] = (char) (((uint32) type) >> 16);
  24892. s[2] = (char) (((uint32) type) >> 8);
  24893. s[3] = (char) ((uint32) type);
  24894. return String (s, 4);
  24895. }
  24896. OSType stringToOSType (const String& s1)
  24897. {
  24898. const String s (s1 + " ");
  24899. return (((OSType) (unsigned char) s[0]) << 24)
  24900. | (((OSType) (unsigned char) s[1]) << 16)
  24901. | (((OSType) (unsigned char) s[2]) << 8)
  24902. | ((OSType) (unsigned char) s[3]);
  24903. }
  24904. static const char* auIdentifierPrefix = "AudioUnit:";
  24905. const String createAUPluginIdentifier (const ComponentDescription& desc)
  24906. {
  24907. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  24908. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  24909. String s (auIdentifierPrefix);
  24910. if (desc.componentType == kAudioUnitType_MusicDevice)
  24911. s << "Synths/";
  24912. else if (desc.componentType == kAudioUnitType_MusicEffect
  24913. || desc.componentType == kAudioUnitType_Effect)
  24914. s << "Effects/";
  24915. else if (desc.componentType == kAudioUnitType_Generator)
  24916. s << "Generators/";
  24917. else if (desc.componentType == kAudioUnitType_Panner)
  24918. s << "Panners/";
  24919. s << osTypeToString (desc.componentType) << ","
  24920. << osTypeToString (desc.componentSubType) << ","
  24921. << osTypeToString (desc.componentManufacturer);
  24922. return s;
  24923. }
  24924. void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  24925. {
  24926. Handle componentNameHandle = NewHandle (sizeof (void*));
  24927. Handle componentInfoHandle = NewHandle (sizeof (void*));
  24928. if (componentNameHandle != 0 && componentInfoHandle != 0)
  24929. {
  24930. ComponentDescription desc;
  24931. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  24932. {
  24933. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  24934. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  24935. if (nameString != 0 && nameString[0] != 0)
  24936. {
  24937. const String all ((const char*) nameString + 1, nameString[0]);
  24938. DBG ("name: "+ all);
  24939. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  24940. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  24941. }
  24942. if (infoString != 0 && infoString[0] != 0)
  24943. {
  24944. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  24945. }
  24946. if (name.isEmpty())
  24947. name = "<Unknown>";
  24948. }
  24949. DisposeHandle (componentNameHandle);
  24950. DisposeHandle (componentInfoHandle);
  24951. }
  24952. }
  24953. bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  24954. String& name, String& version, String& manufacturer)
  24955. {
  24956. zerostruct (desc);
  24957. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  24958. {
  24959. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  24960. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  24961. StringArray tokens;
  24962. tokens.addTokens (s, ",", String::empty);
  24963. tokens.trim();
  24964. tokens.removeEmptyStrings();
  24965. if (tokens.size() == 3)
  24966. {
  24967. desc.componentType = stringToOSType (tokens[0]);
  24968. desc.componentSubType = stringToOSType (tokens[1]);
  24969. desc.componentManufacturer = stringToOSType (tokens[2]);
  24970. ComponentRecord* comp = FindNextComponent (0, &desc);
  24971. if (comp != 0)
  24972. {
  24973. getAUDetails (comp, name, manufacturer);
  24974. return true;
  24975. }
  24976. }
  24977. }
  24978. return false;
  24979. }
  24980. }
  24981. class AudioUnitPluginWindowCarbon;
  24982. class AudioUnitPluginWindowCocoa;
  24983. class AudioUnitPluginInstance : public AudioPluginInstance
  24984. {
  24985. public:
  24986. ~AudioUnitPluginInstance();
  24987. void initialise();
  24988. // AudioPluginInstance methods:
  24989. void fillInPluginDescription (PluginDescription& desc) const
  24990. {
  24991. desc.name = pluginName;
  24992. desc.descriptiveName = pluginName;
  24993. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  24994. desc.uid = ((int) componentDesc.componentType)
  24995. ^ ((int) componentDesc.componentSubType)
  24996. ^ ((int) componentDesc.componentManufacturer);
  24997. desc.lastFileModTime = Time();
  24998. desc.pluginFormatName = "AudioUnit";
  24999. desc.category = getCategory();
  25000. desc.manufacturerName = manufacturer;
  25001. desc.version = version;
  25002. desc.numInputChannels = getNumInputChannels();
  25003. desc.numOutputChannels = getNumOutputChannels();
  25004. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25005. }
  25006. void* getPlatformSpecificData() { return audioUnit; }
  25007. const String getName() const { return pluginName; }
  25008. bool acceptsMidi() const { return wantsMidiMessages; }
  25009. bool producesMidi() const { return false; }
  25010. // AudioProcessor methods:
  25011. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25012. void releaseResources();
  25013. void processBlock (AudioSampleBuffer& buffer,
  25014. MidiBuffer& midiMessages);
  25015. bool hasEditor() const;
  25016. AudioProcessorEditor* createEditor();
  25017. const String getInputChannelName (int index) const;
  25018. bool isInputChannelStereoPair (int index) const;
  25019. const String getOutputChannelName (int index) const;
  25020. bool isOutputChannelStereoPair (int index) const;
  25021. int getNumParameters();
  25022. float getParameter (int index);
  25023. void setParameter (int index, float newValue);
  25024. const String getParameterName (int index);
  25025. const String getParameterText (int index);
  25026. bool isParameterAutomatable (int index) const;
  25027. int getNumPrograms();
  25028. int getCurrentProgram();
  25029. void setCurrentProgram (int index);
  25030. const String getProgramName (int index);
  25031. void changeProgramName (int index, const String& newName);
  25032. void getStateInformation (MemoryBlock& destData);
  25033. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25034. void setStateInformation (const void* data, int sizeInBytes);
  25035. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25036. private:
  25037. friend class AudioUnitPluginWindowCarbon;
  25038. friend class AudioUnitPluginWindowCocoa;
  25039. friend class AudioUnitPluginFormat;
  25040. ComponentDescription componentDesc;
  25041. String pluginName, manufacturer, version;
  25042. String fileOrIdentifier;
  25043. CriticalSection lock;
  25044. bool wantsMidiMessages, wasPlaying, prepared;
  25045. HeapBlock <AudioBufferList> outputBufferList;
  25046. AudioTimeStamp timeStamp;
  25047. AudioSampleBuffer* currentBuffer;
  25048. AudioUnit audioUnit;
  25049. Array <int> parameterIds;
  25050. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25051. void setPluginCallbacks();
  25052. void getParameterListFromPlugin();
  25053. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25054. const AudioTimeStamp* inTimeStamp,
  25055. UInt32 inBusNumber,
  25056. UInt32 inNumberFrames,
  25057. AudioBufferList* ioData) const;
  25058. static OSStatus renderGetInputCallback (void* inRefCon,
  25059. AudioUnitRenderActionFlags* ioActionFlags,
  25060. const AudioTimeStamp* inTimeStamp,
  25061. UInt32 inBusNumber,
  25062. UInt32 inNumberFrames,
  25063. AudioBufferList* ioData)
  25064. {
  25065. return ((AudioUnitPluginInstance*) inRefCon)
  25066. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25067. }
  25068. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25069. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25070. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25071. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25072. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25073. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25074. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25075. {
  25076. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25077. }
  25078. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25079. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25080. Float64* outCurrentMeasureDownBeat)
  25081. {
  25082. return ((AudioUnitPluginInstance*) inHostUserData)
  25083. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25084. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25085. }
  25086. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25087. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25088. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25089. {
  25090. return ((AudioUnitPluginInstance*) inHostUserData)
  25091. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25092. outCurrentSampleInTimeLine, outIsCycling,
  25093. outCycleStartBeat, outCycleEndBeat);
  25094. }
  25095. void getNumChannels (int& numIns, int& numOuts)
  25096. {
  25097. numIns = 0;
  25098. numOuts = 0;
  25099. AUChannelInfo supportedChannels [128];
  25100. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25101. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25102. 0, supportedChannels, &supportedChannelsSize) == noErr
  25103. && supportedChannelsSize > 0)
  25104. {
  25105. int explicitNumIns = 0;
  25106. int explicitNumOuts = 0;
  25107. int maximumNumIns = 0;
  25108. int maximumNumOuts = 0;
  25109. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25110. {
  25111. const int inChannels = (int) supportedChannels[i].inChannels;
  25112. const int outChannels = (int) supportedChannels[i].outChannels;
  25113. if (inChannels < 0)
  25114. maximumNumIns = jmin (maximumNumIns, inChannels);
  25115. else
  25116. explicitNumIns = jmax (explicitNumIns, inChannels);
  25117. if (outChannels < 0)
  25118. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25119. else
  25120. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25121. }
  25122. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25123. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25124. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25125. {
  25126. numIns = numOuts = 2;
  25127. }
  25128. else
  25129. {
  25130. numIns = explicitNumIns;
  25131. numOuts = explicitNumOuts;
  25132. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25133. numIns = 2;
  25134. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25135. numOuts = 2;
  25136. }
  25137. }
  25138. else
  25139. {
  25140. // (this really means the plugin will take any number of ins/outs as long
  25141. // as they are the same)
  25142. numIns = numOuts = 2;
  25143. }
  25144. }
  25145. const String getCategory() const;
  25146. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25147. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginInstance);
  25148. };
  25149. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25150. : fileOrIdentifier (fileOrIdentifier),
  25151. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25152. currentBuffer (0),
  25153. audioUnit (0)
  25154. {
  25155. using namespace AudioUnitFormatHelpers;
  25156. try
  25157. {
  25158. ++insideCallback;
  25159. log ("Opening AU: " + fileOrIdentifier);
  25160. if (getComponentDescFromFile (fileOrIdentifier))
  25161. {
  25162. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25163. if (comp != 0)
  25164. {
  25165. audioUnit = (AudioUnit) OpenComponent (comp);
  25166. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25167. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25168. }
  25169. }
  25170. --insideCallback;
  25171. }
  25172. catch (...)
  25173. {
  25174. --insideCallback;
  25175. }
  25176. }
  25177. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25178. {
  25179. const ScopedLock sl (lock);
  25180. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25181. if (audioUnit != 0)
  25182. {
  25183. AudioUnitUninitialize (audioUnit);
  25184. CloseComponent (audioUnit);
  25185. audioUnit = 0;
  25186. }
  25187. }
  25188. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25189. {
  25190. zerostruct (componentDesc);
  25191. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25192. return true;
  25193. const File file (fileOrIdentifier);
  25194. if (! file.hasFileExtension (".component"))
  25195. return false;
  25196. const char* const utf8 = fileOrIdentifier.toUTF8();
  25197. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25198. strlen (utf8), file.isDirectory());
  25199. if (url != 0)
  25200. {
  25201. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25202. CFRelease (url);
  25203. if (bundleRef != 0)
  25204. {
  25205. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25206. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25207. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25208. if (pluginName.isEmpty())
  25209. pluginName = file.getFileNameWithoutExtension();
  25210. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25211. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25212. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25213. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25214. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25215. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25216. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25217. UseResFile (resFileId);
  25218. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25219. {
  25220. Handle h = Get1IndResource ('thng', i);
  25221. if (h != 0)
  25222. {
  25223. HLock (h);
  25224. const uint32* const types = (const uint32*) *h;
  25225. if (types[0] == kAudioUnitType_MusicDevice
  25226. || types[0] == kAudioUnitType_MusicEffect
  25227. || types[0] == kAudioUnitType_Effect
  25228. || types[0] == kAudioUnitType_Generator
  25229. || types[0] == kAudioUnitType_Panner)
  25230. {
  25231. componentDesc.componentType = types[0];
  25232. componentDesc.componentSubType = types[1];
  25233. componentDesc.componentManufacturer = types[2];
  25234. break;
  25235. }
  25236. HUnlock (h);
  25237. ReleaseResource (h);
  25238. }
  25239. }
  25240. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25241. CFRelease (bundleRef);
  25242. }
  25243. }
  25244. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25245. }
  25246. void AudioUnitPluginInstance::initialise()
  25247. {
  25248. getParameterListFromPlugin();
  25249. setPluginCallbacks();
  25250. int numIns, numOuts;
  25251. getNumChannels (numIns, numOuts);
  25252. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25253. setLatencySamples (0);
  25254. }
  25255. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25256. {
  25257. parameterIds.clear();
  25258. if (audioUnit != 0)
  25259. {
  25260. UInt32 paramListSize = 0;
  25261. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25262. 0, 0, &paramListSize);
  25263. if (paramListSize > 0)
  25264. {
  25265. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25266. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25267. 0, &parameterIds.getReference(0), &paramListSize);
  25268. }
  25269. }
  25270. }
  25271. void AudioUnitPluginInstance::setPluginCallbacks()
  25272. {
  25273. if (audioUnit != 0)
  25274. {
  25275. {
  25276. AURenderCallbackStruct info;
  25277. zerostruct (info);
  25278. info.inputProcRefCon = this;
  25279. info.inputProc = renderGetInputCallback;
  25280. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25281. 0, &info, sizeof (info));
  25282. }
  25283. {
  25284. HostCallbackInfo info;
  25285. zerostruct (info);
  25286. info.hostUserData = this;
  25287. info.beatAndTempoProc = getBeatAndTempoCallback;
  25288. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25289. info.transportStateProc = getTransportStateCallback;
  25290. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25291. 0, &info, sizeof (info));
  25292. }
  25293. }
  25294. }
  25295. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25296. int samplesPerBlockExpected)
  25297. {
  25298. if (audioUnit != 0)
  25299. {
  25300. releaseResources();
  25301. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25302. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25303. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25304. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25305. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25306. {
  25307. Float64 sr = sampleRate_;
  25308. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25309. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25310. }
  25311. int numIns, numOuts;
  25312. getNumChannels (numIns, numOuts);
  25313. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25314. Float64 latencySecs = 0.0;
  25315. UInt32 latencySize = sizeof (latencySecs);
  25316. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25317. 0, &latencySecs, &latencySize);
  25318. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25319. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25320. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25321. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25322. {
  25323. AudioStreamBasicDescription stream;
  25324. zerostruct (stream);
  25325. stream.mSampleRate = sampleRate_;
  25326. stream.mFormatID = kAudioFormatLinearPCM;
  25327. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25328. stream.mFramesPerPacket = 1;
  25329. stream.mBytesPerPacket = 4;
  25330. stream.mBytesPerFrame = 4;
  25331. stream.mBitsPerChannel = 32;
  25332. stream.mChannelsPerFrame = numIns;
  25333. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25334. 0, &stream, sizeof (stream));
  25335. stream.mChannelsPerFrame = numOuts;
  25336. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25337. 0, &stream, sizeof (stream));
  25338. }
  25339. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25340. outputBufferList->mNumberBuffers = numOuts;
  25341. for (int i = numOuts; --i >= 0;)
  25342. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25343. zerostruct (timeStamp);
  25344. timeStamp.mSampleTime = 0;
  25345. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25346. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25347. currentBuffer = 0;
  25348. wasPlaying = false;
  25349. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25350. }
  25351. }
  25352. void AudioUnitPluginInstance::releaseResources()
  25353. {
  25354. if (prepared)
  25355. {
  25356. AudioUnitUninitialize (audioUnit);
  25357. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25358. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25359. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25360. outputBufferList.free();
  25361. currentBuffer = 0;
  25362. prepared = false;
  25363. }
  25364. }
  25365. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25366. const AudioTimeStamp* inTimeStamp,
  25367. UInt32 inBusNumber,
  25368. UInt32 inNumberFrames,
  25369. AudioBufferList* ioData) const
  25370. {
  25371. if (inBusNumber == 0
  25372. && currentBuffer != 0)
  25373. {
  25374. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25375. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25376. {
  25377. if (i < currentBuffer->getNumChannels())
  25378. {
  25379. memcpy (ioData->mBuffers[i].mData,
  25380. currentBuffer->getSampleData (i, 0),
  25381. sizeof (float) * inNumberFrames);
  25382. }
  25383. else
  25384. {
  25385. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25386. }
  25387. }
  25388. }
  25389. return noErr;
  25390. }
  25391. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25392. MidiBuffer& midiMessages)
  25393. {
  25394. const int numSamples = buffer.getNumSamples();
  25395. if (prepared)
  25396. {
  25397. AudioUnitRenderActionFlags flags = 0;
  25398. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25399. for (int i = getNumOutputChannels(); --i >= 0;)
  25400. {
  25401. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25402. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25403. }
  25404. currentBuffer = &buffer;
  25405. if (wantsMidiMessages)
  25406. {
  25407. const uint8* midiEventData;
  25408. int midiEventSize, midiEventPosition;
  25409. MidiBuffer::Iterator i (midiMessages);
  25410. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25411. {
  25412. if (midiEventSize <= 3)
  25413. MusicDeviceMIDIEvent (audioUnit,
  25414. midiEventData[0], midiEventData[1], midiEventData[2],
  25415. midiEventPosition);
  25416. else
  25417. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25418. }
  25419. midiMessages.clear();
  25420. }
  25421. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25422. 0, numSamples, outputBufferList);
  25423. timeStamp.mSampleTime += numSamples;
  25424. }
  25425. else
  25426. {
  25427. // Plugin not working correctly, so just bypass..
  25428. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25429. buffer.clear (i, 0, buffer.getNumSamples());
  25430. }
  25431. }
  25432. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25433. {
  25434. AudioPlayHead* const ph = getPlayHead();
  25435. AudioPlayHead::CurrentPositionInfo result;
  25436. if (ph != 0 && ph->getCurrentPosition (result))
  25437. {
  25438. if (outCurrentBeat != 0)
  25439. *outCurrentBeat = result.ppqPosition;
  25440. if (outCurrentTempo != 0)
  25441. *outCurrentTempo = result.bpm;
  25442. }
  25443. else
  25444. {
  25445. if (outCurrentBeat != 0)
  25446. *outCurrentBeat = 0;
  25447. if (outCurrentTempo != 0)
  25448. *outCurrentTempo = 120.0;
  25449. }
  25450. return noErr;
  25451. }
  25452. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25453. Float32* outTimeSig_Numerator,
  25454. UInt32* outTimeSig_Denominator,
  25455. Float64* outCurrentMeasureDownBeat) const
  25456. {
  25457. AudioPlayHead* const ph = getPlayHead();
  25458. AudioPlayHead::CurrentPositionInfo result;
  25459. if (ph != 0 && ph->getCurrentPosition (result))
  25460. {
  25461. if (outTimeSig_Numerator != 0)
  25462. *outTimeSig_Numerator = result.timeSigNumerator;
  25463. if (outTimeSig_Denominator != 0)
  25464. *outTimeSig_Denominator = result.timeSigDenominator;
  25465. if (outDeltaSampleOffsetToNextBeat != 0)
  25466. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25467. if (outCurrentMeasureDownBeat != 0)
  25468. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25469. }
  25470. else
  25471. {
  25472. if (outDeltaSampleOffsetToNextBeat != 0)
  25473. *outDeltaSampleOffsetToNextBeat = 0;
  25474. if (outTimeSig_Numerator != 0)
  25475. *outTimeSig_Numerator = 4;
  25476. if (outTimeSig_Denominator != 0)
  25477. *outTimeSig_Denominator = 4;
  25478. if (outCurrentMeasureDownBeat != 0)
  25479. *outCurrentMeasureDownBeat = 0;
  25480. }
  25481. return noErr;
  25482. }
  25483. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25484. Boolean* outTransportStateChanged,
  25485. Float64* outCurrentSampleInTimeLine,
  25486. Boolean* outIsCycling,
  25487. Float64* outCycleStartBeat,
  25488. Float64* outCycleEndBeat)
  25489. {
  25490. AudioPlayHead* const ph = getPlayHead();
  25491. AudioPlayHead::CurrentPositionInfo result;
  25492. if (ph != 0 && ph->getCurrentPosition (result))
  25493. {
  25494. if (outIsPlaying != 0)
  25495. *outIsPlaying = result.isPlaying;
  25496. if (outTransportStateChanged != 0)
  25497. {
  25498. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25499. wasPlaying = result.isPlaying;
  25500. }
  25501. if (outCurrentSampleInTimeLine != 0)
  25502. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25503. if (outIsCycling != 0)
  25504. *outIsCycling = false;
  25505. if (outCycleStartBeat != 0)
  25506. *outCycleStartBeat = 0;
  25507. if (outCycleEndBeat != 0)
  25508. *outCycleEndBeat = 0;
  25509. }
  25510. else
  25511. {
  25512. if (outIsPlaying != 0)
  25513. *outIsPlaying = false;
  25514. if (outTransportStateChanged != 0)
  25515. *outTransportStateChanged = false;
  25516. if (outCurrentSampleInTimeLine != 0)
  25517. *outCurrentSampleInTimeLine = 0;
  25518. if (outIsCycling != 0)
  25519. *outIsCycling = false;
  25520. if (outCycleStartBeat != 0)
  25521. *outCycleStartBeat = 0;
  25522. if (outCycleEndBeat != 0)
  25523. *outCycleEndBeat = 0;
  25524. }
  25525. return noErr;
  25526. }
  25527. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25528. public Timer
  25529. {
  25530. public:
  25531. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25532. : AudioProcessorEditor (&plugin_),
  25533. plugin (plugin_)
  25534. {
  25535. addAndMakeVisible (&wrapper);
  25536. setOpaque (true);
  25537. setVisible (true);
  25538. setSize (100, 100);
  25539. createView (createGenericViewIfNeeded);
  25540. }
  25541. ~AudioUnitPluginWindowCocoa()
  25542. {
  25543. const bool wasValid = isValid();
  25544. wrapper.setView (0);
  25545. if (wasValid)
  25546. plugin.editorBeingDeleted (this);
  25547. }
  25548. bool isValid() const { return wrapper.getView() != 0; }
  25549. void paint (Graphics& g)
  25550. {
  25551. g.fillAll (Colours::white);
  25552. }
  25553. void resized()
  25554. {
  25555. wrapper.setSize (getWidth(), getHeight());
  25556. }
  25557. void timerCallback()
  25558. {
  25559. wrapper.resizeToFitView();
  25560. startTimer (jmin (713, getTimerInterval() + 51));
  25561. }
  25562. void childBoundsChanged (Component* child)
  25563. {
  25564. setSize (wrapper.getWidth(), wrapper.getHeight());
  25565. startTimer (70);
  25566. }
  25567. private:
  25568. AudioUnitPluginInstance& plugin;
  25569. NSViewComponent wrapper;
  25570. bool createView (const bool createGenericViewIfNeeded)
  25571. {
  25572. NSView* pluginView = 0;
  25573. UInt32 dataSize = 0;
  25574. Boolean isWritable = false;
  25575. AudioUnitInitialize (plugin.audioUnit);
  25576. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25577. 0, &dataSize, &isWritable) == noErr
  25578. && dataSize != 0
  25579. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25580. 0, &dataSize, &isWritable) == noErr)
  25581. {
  25582. HeapBlock <AudioUnitCocoaViewInfo> info;
  25583. info.calloc (dataSize, 1);
  25584. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25585. 0, info, &dataSize) == noErr)
  25586. {
  25587. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25588. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25589. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25590. Class viewClass = [viewBundle classNamed: viewClassName];
  25591. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25592. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25593. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25594. {
  25595. id factory = [[[viewClass alloc] init] autorelease];
  25596. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25597. withSize: NSMakeSize (getWidth(), getHeight())];
  25598. }
  25599. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25600. CFRelease (info->mCocoaAUViewClass[i]);
  25601. CFRelease (info->mCocoaAUViewBundleLocation);
  25602. }
  25603. }
  25604. if (createGenericViewIfNeeded && (pluginView == 0))
  25605. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25606. wrapper.setView (pluginView);
  25607. if (pluginView != 0)
  25608. {
  25609. timerCallback();
  25610. startTimer (70);
  25611. }
  25612. return pluginView != 0;
  25613. }
  25614. };
  25615. #if JUCE_SUPPORT_CARBON
  25616. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25617. {
  25618. public:
  25619. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25620. : AudioProcessorEditor (&plugin_),
  25621. plugin (plugin_),
  25622. viewComponent (0)
  25623. {
  25624. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25625. setOpaque (true);
  25626. setVisible (true);
  25627. setSize (400, 300);
  25628. ComponentDescription viewList [16];
  25629. UInt32 viewListSize = sizeof (viewList);
  25630. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25631. 0, &viewList, &viewListSize);
  25632. componentRecord = FindNextComponent (0, &viewList[0]);
  25633. }
  25634. ~AudioUnitPluginWindowCarbon()
  25635. {
  25636. innerWrapper = 0;
  25637. if (isValid())
  25638. plugin.editorBeingDeleted (this);
  25639. }
  25640. bool isValid() const throw() { return componentRecord != 0; }
  25641. void paint (Graphics& g)
  25642. {
  25643. g.fillAll (Colours::black);
  25644. }
  25645. void resized()
  25646. {
  25647. innerWrapper->setSize (getWidth(), getHeight());
  25648. }
  25649. bool keyStateChanged (bool)
  25650. {
  25651. return false;
  25652. }
  25653. bool keyPressed (const KeyPress&)
  25654. {
  25655. return false;
  25656. }
  25657. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25658. AudioUnitCarbonView getViewComponent()
  25659. {
  25660. if (viewComponent == 0 && componentRecord != 0)
  25661. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25662. return viewComponent;
  25663. }
  25664. void closeViewComponent()
  25665. {
  25666. if (viewComponent != 0)
  25667. {
  25668. log ("Closing AU GUI: " + plugin.getName());
  25669. CloseComponent (viewComponent);
  25670. viewComponent = 0;
  25671. }
  25672. }
  25673. private:
  25674. AudioUnitPluginInstance& plugin;
  25675. ComponentRecord* componentRecord;
  25676. AudioUnitCarbonView viewComponent;
  25677. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25678. {
  25679. public:
  25680. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25681. : owner (owner_)
  25682. {
  25683. }
  25684. ~InnerWrapperComponent()
  25685. {
  25686. deleteWindow();
  25687. }
  25688. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25689. {
  25690. log ("Opening AU GUI: " + owner->plugin.getName());
  25691. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25692. if (viewComponent == 0)
  25693. return 0;
  25694. Float32Point pos = { 0, 0 };
  25695. Float32Point size = { 250, 200 };
  25696. HIViewRef pluginView = 0;
  25697. AudioUnitCarbonViewCreate (viewComponent,
  25698. owner->getAudioUnit(),
  25699. windowRef,
  25700. rootView,
  25701. &pos,
  25702. &size,
  25703. (ControlRef*) &pluginView);
  25704. return pluginView;
  25705. }
  25706. void removeView (HIViewRef)
  25707. {
  25708. owner->closeViewComponent();
  25709. }
  25710. private:
  25711. AudioUnitPluginWindowCarbon* const owner;
  25712. };
  25713. friend class InnerWrapperComponent;
  25714. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25715. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioUnitPluginWindowCarbon);
  25716. };
  25717. #endif
  25718. bool AudioUnitPluginInstance::hasEditor() const
  25719. {
  25720. return true;
  25721. }
  25722. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25723. {
  25724. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25725. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25726. w = 0;
  25727. #if JUCE_SUPPORT_CARBON
  25728. if (w == 0)
  25729. {
  25730. w = new AudioUnitPluginWindowCarbon (*this);
  25731. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25732. w = 0;
  25733. }
  25734. #endif
  25735. if (w == 0)
  25736. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25737. return w.release();
  25738. }
  25739. const String AudioUnitPluginInstance::getCategory() const
  25740. {
  25741. const char* result = 0;
  25742. switch (componentDesc.componentType)
  25743. {
  25744. case kAudioUnitType_Effect:
  25745. case kAudioUnitType_MusicEffect: result = "Effect"; break;
  25746. case kAudioUnitType_MusicDevice: result = "Synth"; break;
  25747. case kAudioUnitType_Generator: result = "Generator"; break;
  25748. case kAudioUnitType_Panner: result = "Panner"; break;
  25749. default: break;
  25750. }
  25751. return result;
  25752. }
  25753. int AudioUnitPluginInstance::getNumParameters()
  25754. {
  25755. return parameterIds.size();
  25756. }
  25757. float AudioUnitPluginInstance::getParameter (int index)
  25758. {
  25759. const ScopedLock sl (lock);
  25760. Float32 value = 0.0f;
  25761. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25762. {
  25763. AudioUnitGetParameter (audioUnit,
  25764. (UInt32) parameterIds.getUnchecked (index),
  25765. kAudioUnitScope_Global, 0,
  25766. &value);
  25767. }
  25768. return value;
  25769. }
  25770. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25771. {
  25772. const ScopedLock sl (lock);
  25773. if (audioUnit != 0 && isPositiveAndBelow (index, parameterIds.size()))
  25774. {
  25775. AudioUnitSetParameter (audioUnit,
  25776. (UInt32) parameterIds.getUnchecked (index),
  25777. kAudioUnitScope_Global, 0,
  25778. newValue, 0);
  25779. }
  25780. }
  25781. const String AudioUnitPluginInstance::getParameterName (int index)
  25782. {
  25783. AudioUnitParameterInfo info;
  25784. zerostruct (info);
  25785. UInt32 sz = sizeof (info);
  25786. String name;
  25787. if (AudioUnitGetProperty (audioUnit,
  25788. kAudioUnitProperty_ParameterInfo,
  25789. kAudioUnitScope_Global,
  25790. parameterIds [index], &info, &sz) == noErr)
  25791. {
  25792. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25793. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25794. else
  25795. name = String (info.name, sizeof (info.name));
  25796. }
  25797. return name;
  25798. }
  25799. const String AudioUnitPluginInstance::getParameterText (int index)
  25800. {
  25801. return String (getParameter (index));
  25802. }
  25803. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25804. {
  25805. AudioUnitParameterInfo info;
  25806. UInt32 sz = sizeof (info);
  25807. if (AudioUnitGetProperty (audioUnit,
  25808. kAudioUnitProperty_ParameterInfo,
  25809. kAudioUnitScope_Global,
  25810. parameterIds [index], &info, &sz) == noErr)
  25811. {
  25812. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25813. }
  25814. return true;
  25815. }
  25816. int AudioUnitPluginInstance::getNumPrograms()
  25817. {
  25818. CFArrayRef presets;
  25819. UInt32 sz = sizeof (CFArrayRef);
  25820. int num = 0;
  25821. if (AudioUnitGetProperty (audioUnit,
  25822. kAudioUnitProperty_FactoryPresets,
  25823. kAudioUnitScope_Global,
  25824. 0, &presets, &sz) == noErr)
  25825. {
  25826. num = (int) CFArrayGetCount (presets);
  25827. CFRelease (presets);
  25828. }
  25829. return num;
  25830. }
  25831. int AudioUnitPluginInstance::getCurrentProgram()
  25832. {
  25833. AUPreset current;
  25834. current.presetNumber = 0;
  25835. UInt32 sz = sizeof (AUPreset);
  25836. AudioUnitGetProperty (audioUnit,
  25837. kAudioUnitProperty_FactoryPresets,
  25838. kAudioUnitScope_Global,
  25839. 0, &current, &sz);
  25840. return current.presetNumber;
  25841. }
  25842. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  25843. {
  25844. AUPreset current;
  25845. current.presetNumber = newIndex;
  25846. current.presetName = 0;
  25847. AudioUnitSetProperty (audioUnit,
  25848. kAudioUnitProperty_FactoryPresets,
  25849. kAudioUnitScope_Global,
  25850. 0, &current, sizeof (AUPreset));
  25851. }
  25852. const String AudioUnitPluginInstance::getProgramName (int index)
  25853. {
  25854. String s;
  25855. CFArrayRef presets;
  25856. UInt32 sz = sizeof (CFArrayRef);
  25857. if (AudioUnitGetProperty (audioUnit,
  25858. kAudioUnitProperty_FactoryPresets,
  25859. kAudioUnitScope_Global,
  25860. 0, &presets, &sz) == noErr)
  25861. {
  25862. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  25863. {
  25864. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  25865. if (p != 0 && p->presetNumber == index)
  25866. {
  25867. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  25868. break;
  25869. }
  25870. }
  25871. CFRelease (presets);
  25872. }
  25873. return s;
  25874. }
  25875. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  25876. {
  25877. jassertfalse; // xxx not implemented!
  25878. }
  25879. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  25880. {
  25881. if (isPositiveAndBelow (index, getNumInputChannels()))
  25882. return "Input " + String (index + 1);
  25883. return String::empty;
  25884. }
  25885. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  25886. {
  25887. if (! isPositiveAndBelow (index, getNumInputChannels()))
  25888. return false;
  25889. return true;
  25890. }
  25891. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  25892. {
  25893. if (isPositiveAndBelow (index, getNumOutputChannels()))
  25894. return "Output " + String (index + 1);
  25895. return String::empty;
  25896. }
  25897. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  25898. {
  25899. if (! isPositiveAndBelow (index, getNumOutputChannels()))
  25900. return false;
  25901. return true;
  25902. }
  25903. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  25904. {
  25905. getCurrentProgramStateInformation (destData);
  25906. }
  25907. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25908. {
  25909. CFPropertyListRef propertyList = 0;
  25910. UInt32 sz = sizeof (CFPropertyListRef);
  25911. if (AudioUnitGetProperty (audioUnit,
  25912. kAudioUnitProperty_ClassInfo,
  25913. kAudioUnitScope_Global,
  25914. 0, &propertyList, &sz) == noErr)
  25915. {
  25916. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  25917. CFWriteStreamOpen (stream);
  25918. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  25919. CFWriteStreamClose (stream);
  25920. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  25921. destData.setSize (bytesWritten);
  25922. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  25923. CFRelease (data);
  25924. CFRelease (stream);
  25925. CFRelease (propertyList);
  25926. }
  25927. }
  25928. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25929. {
  25930. setCurrentProgramStateInformation (data, sizeInBytes);
  25931. }
  25932. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25933. {
  25934. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  25935. (const UInt8*) data,
  25936. sizeInBytes,
  25937. kCFAllocatorNull);
  25938. CFReadStreamOpen (stream);
  25939. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  25940. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  25941. stream,
  25942. 0,
  25943. kCFPropertyListImmutable,
  25944. &format,
  25945. 0);
  25946. CFRelease (stream);
  25947. if (propertyList != 0)
  25948. AudioUnitSetProperty (audioUnit,
  25949. kAudioUnitProperty_ClassInfo,
  25950. kAudioUnitScope_Global,
  25951. 0, &propertyList, sizeof (propertyList));
  25952. }
  25953. AudioUnitPluginFormat::AudioUnitPluginFormat()
  25954. {
  25955. }
  25956. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  25957. {
  25958. }
  25959. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25960. const String& fileOrIdentifier)
  25961. {
  25962. if (! fileMightContainThisPluginType (fileOrIdentifier))
  25963. return;
  25964. PluginDescription desc;
  25965. desc.fileOrIdentifier = fileOrIdentifier;
  25966. desc.uid = 0;
  25967. try
  25968. {
  25969. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  25970. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  25971. if (auInstance != 0)
  25972. {
  25973. auInstance->fillInPluginDescription (desc);
  25974. results.add (new PluginDescription (desc));
  25975. }
  25976. }
  25977. catch (...)
  25978. {
  25979. // crashed while loading...
  25980. }
  25981. }
  25982. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25983. {
  25984. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  25985. {
  25986. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  25987. if (result->audioUnit != 0)
  25988. {
  25989. result->initialise();
  25990. return result.release();
  25991. }
  25992. }
  25993. return 0;
  25994. }
  25995. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  25996. const bool /*recursive*/)
  25997. {
  25998. StringArray result;
  25999. ComponentRecord* comp = 0;
  26000. ComponentDescription desc;
  26001. zerostruct (desc);
  26002. for (;;)
  26003. {
  26004. zerostruct (desc);
  26005. comp = FindNextComponent (comp, &desc);
  26006. if (comp == 0)
  26007. break;
  26008. GetComponentInfo (comp, &desc, 0, 0, 0);
  26009. if (desc.componentType == kAudioUnitType_MusicDevice
  26010. || desc.componentType == kAudioUnitType_MusicEffect
  26011. || desc.componentType == kAudioUnitType_Effect
  26012. || desc.componentType == kAudioUnitType_Generator
  26013. || desc.componentType == kAudioUnitType_Panner)
  26014. {
  26015. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26016. DBG (s);
  26017. result.add (s);
  26018. }
  26019. }
  26020. return result;
  26021. }
  26022. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26023. {
  26024. ComponentDescription desc;
  26025. String name, version, manufacturer;
  26026. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26027. return FindNextComponent (0, &desc) != 0;
  26028. const File f (fileOrIdentifier);
  26029. return f.hasFileExtension (".component")
  26030. && f.isDirectory();
  26031. }
  26032. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26033. {
  26034. ComponentDescription desc;
  26035. String name, version, manufacturer;
  26036. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26037. if (name.isEmpty())
  26038. name = fileOrIdentifier;
  26039. return name;
  26040. }
  26041. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26042. {
  26043. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26044. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26045. else
  26046. return File (desc.fileOrIdentifier).exists();
  26047. }
  26048. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26049. {
  26050. return FileSearchPath ("/(Default AudioUnit locations)");
  26051. }
  26052. #endif
  26053. END_JUCE_NAMESPACE
  26054. #undef log
  26055. #endif
  26056. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26057. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26058. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26059. #define JUCE_MAC_VST_INCLUDED 1
  26060. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26061. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26062. #if JUCE_WINDOWS
  26063. #undef _WIN32_WINNT
  26064. #define _WIN32_WINNT 0x500
  26065. #undef STRICT
  26066. #define STRICT
  26067. #include <windows.h>
  26068. #include <float.h>
  26069. #pragma warning (disable : 4312 4355)
  26070. #ifdef __INTEL_COMPILER
  26071. #pragma warning (disable : 1899)
  26072. #endif
  26073. #elif JUCE_LINUX
  26074. #include <float.h>
  26075. #include <sys/time.h>
  26076. #include <X11/Xlib.h>
  26077. #include <X11/Xutil.h>
  26078. #include <X11/Xatom.h>
  26079. #undef Font
  26080. #undef KeyPress
  26081. #undef Drawable
  26082. #undef Time
  26083. #else
  26084. #include <Cocoa/Cocoa.h>
  26085. #include <Carbon/Carbon.h>
  26086. #endif
  26087. #if ! (JUCE_MAC && JUCE_64BIT)
  26088. BEGIN_JUCE_NAMESPACE
  26089. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26090. #endif
  26091. #undef PRAGMA_ALIGN_SUPPORTED
  26092. #define VST_FORCE_DEPRECATED 0
  26093. #if JUCE_MSVC
  26094. #pragma warning (push)
  26095. #pragma warning (disable: 4996)
  26096. #endif
  26097. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26098. your include path if you want to add VST support.
  26099. If you're not interested in VSTs, you can disable them by changing the
  26100. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26101. */
  26102. #include <pluginterfaces/vst2.x/aeffectx.h>
  26103. #if JUCE_MSVC
  26104. #pragma warning (pop)
  26105. #endif
  26106. #if JUCE_LINUX
  26107. #define Font JUCE_NAMESPACE::Font
  26108. #define KeyPress JUCE_NAMESPACE::KeyPress
  26109. #define Drawable JUCE_NAMESPACE::Drawable
  26110. #define Time JUCE_NAMESPACE::Time
  26111. #endif
  26112. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26113. #ifdef __aeffect__
  26114. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26115. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26116. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26117. events to the list.
  26118. This is used by both the VST hosting code and the plugin wrapper.
  26119. */
  26120. class VSTMidiEventList
  26121. {
  26122. public:
  26123. VSTMidiEventList()
  26124. : numEventsUsed (0), numEventsAllocated (0)
  26125. {
  26126. }
  26127. ~VSTMidiEventList()
  26128. {
  26129. freeEvents();
  26130. }
  26131. void clear()
  26132. {
  26133. numEventsUsed = 0;
  26134. if (events != 0)
  26135. events->numEvents = 0;
  26136. }
  26137. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26138. {
  26139. ensureSize (numEventsUsed + 1);
  26140. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26141. events->numEvents = ++numEventsUsed;
  26142. if (numBytes <= 4)
  26143. {
  26144. if (e->type == kVstSysExType)
  26145. {
  26146. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26147. e->type = kVstMidiType;
  26148. e->byteSize = sizeof (VstMidiEvent);
  26149. e->noteLength = 0;
  26150. e->noteOffset = 0;
  26151. e->detune = 0;
  26152. e->noteOffVelocity = 0;
  26153. }
  26154. e->deltaFrames = frameOffset;
  26155. memcpy (e->midiData, midiData, numBytes);
  26156. }
  26157. else
  26158. {
  26159. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26160. if (se->type == kVstSysExType)
  26161. delete[] se->sysexDump;
  26162. se->sysexDump = new char [numBytes];
  26163. memcpy (se->sysexDump, midiData, numBytes);
  26164. se->type = kVstSysExType;
  26165. se->byteSize = sizeof (VstMidiSysexEvent);
  26166. se->deltaFrames = frameOffset;
  26167. se->flags = 0;
  26168. se->dumpBytes = numBytes;
  26169. se->resvd1 = 0;
  26170. se->resvd2 = 0;
  26171. }
  26172. }
  26173. // Handy method to pull the events out of an event buffer supplied by the host
  26174. // or plugin.
  26175. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26176. {
  26177. for (int i = 0; i < events->numEvents; ++i)
  26178. {
  26179. const VstEvent* const e = events->events[i];
  26180. if (e != 0)
  26181. {
  26182. if (e->type == kVstMidiType)
  26183. {
  26184. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26185. 4, e->deltaFrames);
  26186. }
  26187. else if (e->type == kVstSysExType)
  26188. {
  26189. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26190. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26191. e->deltaFrames);
  26192. }
  26193. }
  26194. }
  26195. }
  26196. void ensureSize (int numEventsNeeded)
  26197. {
  26198. if (numEventsNeeded > numEventsAllocated)
  26199. {
  26200. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26201. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26202. if (events == 0)
  26203. events.calloc (size, 1);
  26204. else
  26205. events.realloc (size, 1);
  26206. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26207. {
  26208. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26209. (int) sizeof (VstMidiSysexEvent)));
  26210. e->type = kVstMidiType;
  26211. e->byteSize = sizeof (VstMidiEvent);
  26212. events->events[i] = (VstEvent*) e;
  26213. }
  26214. numEventsAllocated = numEventsNeeded;
  26215. }
  26216. }
  26217. void freeEvents()
  26218. {
  26219. if (events != 0)
  26220. {
  26221. for (int i = numEventsAllocated; --i >= 0;)
  26222. {
  26223. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26224. if (e->type == kVstSysExType)
  26225. delete[] (((VstMidiSysexEvent*) e)->sysexDump);
  26226. juce_free (e);
  26227. }
  26228. events.free();
  26229. numEventsUsed = 0;
  26230. numEventsAllocated = 0;
  26231. }
  26232. }
  26233. HeapBlock <VstEvents> events;
  26234. private:
  26235. int numEventsUsed, numEventsAllocated;
  26236. };
  26237. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26238. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26239. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26240. #if ! JUCE_WINDOWS
  26241. static void _fpreset() {}
  26242. static void _clearfp() {}
  26243. #endif
  26244. extern void juce_callAnyTimersSynchronously();
  26245. const int fxbVersionNum = 1;
  26246. struct fxProgram
  26247. {
  26248. long chunkMagic; // 'CcnK'
  26249. long byteSize; // of this chunk, excl. magic + byteSize
  26250. long fxMagic; // 'FxCk'
  26251. long version;
  26252. long fxID; // fx unique id
  26253. long fxVersion;
  26254. long numParams;
  26255. char prgName[28];
  26256. float params[1]; // variable no. of parameters
  26257. };
  26258. struct fxSet
  26259. {
  26260. long chunkMagic; // 'CcnK'
  26261. long byteSize; // of this chunk, excl. magic + byteSize
  26262. long fxMagic; // 'FxBk'
  26263. long version;
  26264. long fxID; // fx unique id
  26265. long fxVersion;
  26266. long numPrograms;
  26267. char future[128];
  26268. fxProgram programs[1]; // variable no. of programs
  26269. };
  26270. struct fxChunkSet
  26271. {
  26272. long chunkMagic; // 'CcnK'
  26273. long byteSize; // of this chunk, excl. magic + byteSize
  26274. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26275. long version;
  26276. long fxID; // fx unique id
  26277. long fxVersion;
  26278. long numPrograms;
  26279. char future[128];
  26280. long chunkSize;
  26281. char chunk[8]; // variable
  26282. };
  26283. struct fxProgramSet
  26284. {
  26285. long chunkMagic; // 'CcnK'
  26286. long byteSize; // of this chunk, excl. magic + byteSize
  26287. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26288. long version;
  26289. long fxID; // fx unique id
  26290. long fxVersion;
  26291. long numPrograms;
  26292. char name[28];
  26293. long chunkSize;
  26294. char chunk[8]; // variable
  26295. };
  26296. namespace
  26297. {
  26298. long vst_swap (const long x) throw()
  26299. {
  26300. #ifdef JUCE_LITTLE_ENDIAN
  26301. return (long) ByteOrder::swap ((uint32) x);
  26302. #else
  26303. return x;
  26304. #endif
  26305. }
  26306. float vst_swapFloat (const float x) throw()
  26307. {
  26308. #ifdef JUCE_LITTLE_ENDIAN
  26309. union { uint32 asInt; float asFloat; } n;
  26310. n.asFloat = x;
  26311. n.asInt = ByteOrder::swap (n.asInt);
  26312. return n.asFloat;
  26313. #else
  26314. return x;
  26315. #endif
  26316. }
  26317. double getVSTHostTimeNanoseconds()
  26318. {
  26319. #if JUCE_WINDOWS
  26320. return timeGetTime() * 1000000.0;
  26321. #elif JUCE_LINUX
  26322. timeval micro;
  26323. gettimeofday (&micro, 0);
  26324. return micro.tv_usec * 1000.0;
  26325. #elif JUCE_MAC
  26326. UnsignedWide micro;
  26327. Microseconds (&micro);
  26328. return micro.lo * 1000.0;
  26329. #endif
  26330. }
  26331. }
  26332. typedef AEffect* (VSTCALLBACK *MainCall) (audioMasterCallback);
  26333. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26334. static int shellUIDToCreate = 0;
  26335. static int insideVSTCallback = 0;
  26336. class VSTPluginWindow;
  26337. // Change this to disable logging of various VST activities
  26338. #ifndef VST_LOGGING
  26339. #define VST_LOGGING 1
  26340. #endif
  26341. #if VST_LOGGING
  26342. #define log(a) Logger::writeToLog(a);
  26343. #else
  26344. #define log(a)
  26345. #endif
  26346. #if JUCE_MAC && JUCE_PPC
  26347. static void* NewCFMFromMachO (void* const machofp) throw()
  26348. {
  26349. void* result = (void*) new char[8];
  26350. ((void**) result)[0] = machofp;
  26351. ((void**) result)[1] = result;
  26352. return result;
  26353. }
  26354. #endif
  26355. #if JUCE_LINUX
  26356. extern Display* display;
  26357. extern XContext windowHandleXContext;
  26358. typedef void (*EventProcPtr) (XEvent* ev);
  26359. static bool xErrorTriggered;
  26360. namespace
  26361. {
  26362. int temporaryErrorHandler (Display*, XErrorEvent*)
  26363. {
  26364. xErrorTriggered = true;
  26365. return 0;
  26366. }
  26367. int getPropertyFromXWindow (Window handle, Atom atom)
  26368. {
  26369. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26370. xErrorTriggered = false;
  26371. int userSize;
  26372. unsigned long bytes, userCount;
  26373. unsigned char* data;
  26374. Atom userType;
  26375. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26376. &userType, &userSize, &userCount, &bytes, &data);
  26377. XSetErrorHandler (oldErrorHandler);
  26378. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26379. : 0;
  26380. }
  26381. Window getChildWindow (Window windowToCheck)
  26382. {
  26383. Window rootWindow, parentWindow;
  26384. Window* childWindows;
  26385. unsigned int numChildren;
  26386. XQueryTree (display,
  26387. windowToCheck,
  26388. &rootWindow,
  26389. &parentWindow,
  26390. &childWindows,
  26391. &numChildren);
  26392. if (numChildren > 0)
  26393. return childWindows [0];
  26394. return 0;
  26395. }
  26396. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26397. {
  26398. if (e.mods.isLeftButtonDown())
  26399. {
  26400. ev.xbutton.button = Button1;
  26401. ev.xbutton.state |= Button1Mask;
  26402. }
  26403. else if (e.mods.isRightButtonDown())
  26404. {
  26405. ev.xbutton.button = Button3;
  26406. ev.xbutton.state |= Button3Mask;
  26407. }
  26408. else if (e.mods.isMiddleButtonDown())
  26409. {
  26410. ev.xbutton.button = Button2;
  26411. ev.xbutton.state |= Button2Mask;
  26412. }
  26413. }
  26414. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26415. {
  26416. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26417. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26418. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26419. }
  26420. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26421. {
  26422. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26423. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26424. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26425. }
  26426. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26427. {
  26428. if (increment < 0)
  26429. {
  26430. ev.xbutton.button = Button5;
  26431. ev.xbutton.state |= Button5Mask;
  26432. }
  26433. else if (increment > 0)
  26434. {
  26435. ev.xbutton.button = Button4;
  26436. ev.xbutton.state |= Button4Mask;
  26437. }
  26438. }
  26439. }
  26440. #endif
  26441. class ModuleHandle : public ReferenceCountedObject
  26442. {
  26443. public:
  26444. File file;
  26445. MainCall moduleMain;
  26446. String pluginName;
  26447. static Array <ModuleHandle*>& getActiveModules()
  26448. {
  26449. static Array <ModuleHandle*> activeModules;
  26450. return activeModules;
  26451. }
  26452. static ModuleHandle* findOrCreateModule (const File& file)
  26453. {
  26454. for (int i = getActiveModules().size(); --i >= 0;)
  26455. {
  26456. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26457. if (module->file == file)
  26458. return module;
  26459. }
  26460. _fpreset(); // (doesn't do any harm)
  26461. ++insideVSTCallback;
  26462. shellUIDToCreate = 0;
  26463. log ("Attempting to load VST: " + file.getFullPathName());
  26464. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26465. if (! m->open())
  26466. m = 0;
  26467. --insideVSTCallback;
  26468. _fpreset(); // (doesn't do any harm)
  26469. return m.release();
  26470. }
  26471. ModuleHandle (const File& file_)
  26472. : file (file_),
  26473. moduleMain (0),
  26474. #if JUCE_WINDOWS || JUCE_LINUX
  26475. hModule (0)
  26476. #elif JUCE_MAC
  26477. fragId (0),
  26478. resHandle (0),
  26479. bundleRef (0),
  26480. resFileId (0)
  26481. #endif
  26482. {
  26483. getActiveModules().add (this);
  26484. #if JUCE_WINDOWS || JUCE_LINUX
  26485. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26486. #elif JUCE_MAC
  26487. FSRef ref;
  26488. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26489. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26490. #endif
  26491. }
  26492. ~ModuleHandle()
  26493. {
  26494. getActiveModules().removeValue (this);
  26495. close();
  26496. }
  26497. #if JUCE_WINDOWS || JUCE_LINUX
  26498. void* hModule;
  26499. String fullParentDirectoryPathName;
  26500. bool open()
  26501. {
  26502. #if JUCE_WINDOWS
  26503. static bool timePeriodSet = false;
  26504. if (! timePeriodSet)
  26505. {
  26506. timePeriodSet = true;
  26507. timeBeginPeriod (2);
  26508. }
  26509. #endif
  26510. pluginName = file.getFileNameWithoutExtension();
  26511. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26512. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26513. if (moduleMain == 0)
  26514. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26515. return moduleMain != 0;
  26516. }
  26517. void close()
  26518. {
  26519. _fpreset(); // (doesn't do any harm)
  26520. PlatformUtilities::freeDynamicLibrary (hModule);
  26521. }
  26522. void closeEffect (AEffect* eff)
  26523. {
  26524. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26525. }
  26526. #else
  26527. CFragConnectionID fragId;
  26528. Handle resHandle;
  26529. CFBundleRef bundleRef;
  26530. FSSpec parentDirFSSpec;
  26531. short resFileId;
  26532. bool open()
  26533. {
  26534. bool ok = false;
  26535. const String filename (file.getFullPathName());
  26536. if (file.hasFileExtension (".vst"))
  26537. {
  26538. const char* const utf8 = filename.toUTF8();
  26539. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26540. strlen (utf8), file.isDirectory());
  26541. if (url != 0)
  26542. {
  26543. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26544. CFRelease (url);
  26545. if (bundleRef != 0)
  26546. {
  26547. if (CFBundleLoadExecutable (bundleRef))
  26548. {
  26549. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26550. if (moduleMain == 0)
  26551. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26552. if (moduleMain != 0)
  26553. {
  26554. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26555. if (name != 0)
  26556. {
  26557. if (CFGetTypeID (name) == CFStringGetTypeID())
  26558. {
  26559. char buffer[1024];
  26560. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26561. pluginName = buffer;
  26562. }
  26563. }
  26564. if (pluginName.isEmpty())
  26565. pluginName = file.getFileNameWithoutExtension();
  26566. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26567. ok = true;
  26568. }
  26569. }
  26570. if (! ok)
  26571. {
  26572. CFBundleUnloadExecutable (bundleRef);
  26573. CFRelease (bundleRef);
  26574. bundleRef = 0;
  26575. }
  26576. }
  26577. }
  26578. }
  26579. #if JUCE_PPC
  26580. else
  26581. {
  26582. FSRef fn;
  26583. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26584. {
  26585. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26586. if (resFileId != -1)
  26587. {
  26588. const int numEffs = Count1Resources ('aEff');
  26589. for (int i = 0; i < numEffs; ++i)
  26590. {
  26591. resHandle = Get1IndResource ('aEff', i + 1);
  26592. if (resHandle != 0)
  26593. {
  26594. OSType type;
  26595. Str255 name;
  26596. SInt16 id;
  26597. GetResInfo (resHandle, &id, &type, name);
  26598. pluginName = String ((const char*) name + 1, name[0]);
  26599. DetachResource (resHandle);
  26600. HLock (resHandle);
  26601. Ptr ptr;
  26602. Str255 errorText;
  26603. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26604. name, kPrivateCFragCopy,
  26605. &fragId, &ptr, errorText);
  26606. if (err == noErr)
  26607. {
  26608. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26609. ok = true;
  26610. }
  26611. else
  26612. {
  26613. HUnlock (resHandle);
  26614. }
  26615. break;
  26616. }
  26617. }
  26618. if (! ok)
  26619. CloseResFile (resFileId);
  26620. }
  26621. }
  26622. }
  26623. #endif
  26624. return ok;
  26625. }
  26626. void close()
  26627. {
  26628. #if JUCE_PPC
  26629. if (fragId != 0)
  26630. {
  26631. if (moduleMain != 0)
  26632. disposeMachOFromCFM ((void*) moduleMain);
  26633. CloseConnection (&fragId);
  26634. HUnlock (resHandle);
  26635. if (resFileId != 0)
  26636. CloseResFile (resFileId);
  26637. }
  26638. else
  26639. #endif
  26640. if (bundleRef != 0)
  26641. {
  26642. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26643. if (CFGetRetainCount (bundleRef) == 1)
  26644. CFBundleUnloadExecutable (bundleRef);
  26645. if (CFGetRetainCount (bundleRef) > 0)
  26646. CFRelease (bundleRef);
  26647. }
  26648. }
  26649. void closeEffect (AEffect* eff)
  26650. {
  26651. #if JUCE_PPC
  26652. if (fragId != 0)
  26653. {
  26654. Array<void*> thingsToDelete;
  26655. thingsToDelete.add ((void*) eff->dispatcher);
  26656. thingsToDelete.add ((void*) eff->process);
  26657. thingsToDelete.add ((void*) eff->setParameter);
  26658. thingsToDelete.add ((void*) eff->getParameter);
  26659. thingsToDelete.add ((void*) eff->processReplacing);
  26660. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26661. for (int i = thingsToDelete.size(); --i >= 0;)
  26662. disposeMachOFromCFM (thingsToDelete[i]);
  26663. }
  26664. else
  26665. #endif
  26666. {
  26667. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26668. }
  26669. }
  26670. #if JUCE_PPC
  26671. static void* newMachOFromCFM (void* cfmfp)
  26672. {
  26673. if (cfmfp == 0)
  26674. return 0;
  26675. UInt32* const mfp = new UInt32[6];
  26676. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26677. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26678. mfp[2] = 0x800c0000;
  26679. mfp[3] = 0x804c0004;
  26680. mfp[4] = 0x7c0903a6;
  26681. mfp[5] = 0x4e800420;
  26682. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26683. return mfp;
  26684. }
  26685. static void disposeMachOFromCFM (void* ptr)
  26686. {
  26687. delete[] static_cast <UInt32*> (ptr);
  26688. }
  26689. void coerceAEffectFunctionCalls (AEffect* eff)
  26690. {
  26691. if (fragId != 0)
  26692. {
  26693. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26694. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26695. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26696. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26697. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26698. }
  26699. }
  26700. #endif
  26701. #endif
  26702. private:
  26703. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ModuleHandle);
  26704. };
  26705. /**
  26706. An instance of a plugin, created by a VSTPluginFormat.
  26707. */
  26708. class VSTPluginInstance : public AudioPluginInstance,
  26709. private Timer,
  26710. private AsyncUpdater
  26711. {
  26712. public:
  26713. ~VSTPluginInstance();
  26714. // AudioPluginInstance methods:
  26715. void fillInPluginDescription (PluginDescription& desc) const
  26716. {
  26717. desc.name = name;
  26718. {
  26719. char buffer [512];
  26720. zerostruct (buffer);
  26721. dispatch (effGetEffectName, 0, 0, buffer, 0);
  26722. desc.descriptiveName = String (buffer).trim();
  26723. if (desc.descriptiveName.isEmpty())
  26724. desc.descriptiveName = name;
  26725. }
  26726. desc.fileOrIdentifier = module->file.getFullPathName();
  26727. desc.uid = getUID();
  26728. desc.lastFileModTime = module->file.getLastModificationTime();
  26729. desc.pluginFormatName = "VST";
  26730. desc.category = getCategory();
  26731. {
  26732. char buffer [kVstMaxVendorStrLen + 8];
  26733. zerostruct (buffer);
  26734. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26735. desc.manufacturerName = buffer;
  26736. }
  26737. desc.version = getVersion();
  26738. desc.numInputChannels = getNumInputChannels();
  26739. desc.numOutputChannels = getNumOutputChannels();
  26740. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26741. }
  26742. void* getPlatformSpecificData() { return effect; }
  26743. const String getName() const { return name; }
  26744. int getUID() const;
  26745. bool acceptsMidi() const { return wantsMidiMessages; }
  26746. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26747. // AudioProcessor methods:
  26748. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26749. void releaseResources();
  26750. void processBlock (AudioSampleBuffer& buffer,
  26751. MidiBuffer& midiMessages);
  26752. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26753. AudioProcessorEditor* createEditor();
  26754. const String getInputChannelName (int index) const;
  26755. bool isInputChannelStereoPair (int index) const;
  26756. const String getOutputChannelName (int index) const;
  26757. bool isOutputChannelStereoPair (int index) const;
  26758. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26759. float getParameter (int index);
  26760. void setParameter (int index, float newValue);
  26761. const String getParameterName (int index);
  26762. const String getParameterText (int index);
  26763. bool isParameterAutomatable (int index) const;
  26764. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26765. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26766. void setCurrentProgram (int index);
  26767. const String getProgramName (int index);
  26768. void changeProgramName (int index, const String& newName);
  26769. void getStateInformation (MemoryBlock& destData);
  26770. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26771. void setStateInformation (const void* data, int sizeInBytes);
  26772. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26773. void timerCallback();
  26774. void handleAsyncUpdate();
  26775. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26776. private:
  26777. friend class VSTPluginWindow;
  26778. friend class VSTPluginFormat;
  26779. AEffect* effect;
  26780. String name;
  26781. CriticalSection lock;
  26782. bool wantsMidiMessages, initialised, isPowerOn;
  26783. mutable StringArray programNames;
  26784. AudioSampleBuffer tempBuffer;
  26785. CriticalSection midiInLock;
  26786. MidiBuffer incomingMidi;
  26787. VSTMidiEventList midiEventsToSend;
  26788. VstTimeInfo vstHostTime;
  26789. ReferenceCountedObjectPtr <ModuleHandle> module;
  26790. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26791. bool restoreProgramSettings (const fxProgram* const prog);
  26792. const String getCurrentProgramName();
  26793. void setParamsInProgramBlock (fxProgram* const prog);
  26794. void updateStoredProgramNames();
  26795. void initialise();
  26796. void handleMidiFromPlugin (const VstEvents* const events);
  26797. void createTempParameterStore (MemoryBlock& dest);
  26798. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26799. const String getParameterLabel (int index) const;
  26800. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26801. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26802. void setChunkData (const char* data, int size, bool isPreset);
  26803. bool loadFromFXBFile (const void* data, int numBytes);
  26804. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26805. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26806. const String getVersion() const;
  26807. const String getCategory() const;
  26808. void setPower (const bool on);
  26809. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26810. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginInstance);
  26811. };
  26812. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26813. : effect (0),
  26814. wantsMidiMessages (false),
  26815. initialised (false),
  26816. isPowerOn (false),
  26817. tempBuffer (1, 1),
  26818. module (module_)
  26819. {
  26820. try
  26821. {
  26822. _fpreset();
  26823. ++insideVSTCallback;
  26824. name = module->pluginName;
  26825. log ("Creating VST instance: " + name);
  26826. #if JUCE_MAC
  26827. if (module->resFileId != 0)
  26828. UseResFile (module->resFileId);
  26829. #if JUCE_PPC
  26830. if (module->fragId != 0)
  26831. {
  26832. static void* audioMasterCoerced = 0;
  26833. if (audioMasterCoerced == 0)
  26834. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26835. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26836. }
  26837. else
  26838. #endif
  26839. #endif
  26840. {
  26841. effect = module->moduleMain (&audioMaster);
  26842. }
  26843. --insideVSTCallback;
  26844. if (effect != 0 && effect->magic == kEffectMagic)
  26845. {
  26846. #if JUCE_PPC
  26847. module->coerceAEffectFunctionCalls (effect);
  26848. #endif
  26849. jassert (effect->resvd2 == 0);
  26850. jassert (effect->object != 0);
  26851. _fpreset(); // some dodgy plugs fuck around with this
  26852. }
  26853. else
  26854. {
  26855. effect = 0;
  26856. }
  26857. }
  26858. catch (...)
  26859. {
  26860. --insideVSTCallback;
  26861. }
  26862. }
  26863. VSTPluginInstance::~VSTPluginInstance()
  26864. {
  26865. const ScopedLock sl (lock);
  26866. jassert (insideVSTCallback == 0);
  26867. if (effect != 0 && effect->magic == kEffectMagic)
  26868. {
  26869. try
  26870. {
  26871. #if JUCE_MAC
  26872. if (module->resFileId != 0)
  26873. UseResFile (module->resFileId);
  26874. #endif
  26875. // Must delete any editors before deleting the plugin instance!
  26876. jassert (getActiveEditor() == 0);
  26877. _fpreset(); // some dodgy plugs fuck around with this
  26878. module->closeEffect (effect);
  26879. }
  26880. catch (...)
  26881. {}
  26882. }
  26883. module = 0;
  26884. effect = 0;
  26885. }
  26886. void VSTPluginInstance::initialise()
  26887. {
  26888. if (initialised || effect == 0)
  26889. return;
  26890. log ("Initialising VST: " + module->pluginName);
  26891. initialised = true;
  26892. dispatch (effIdentify, 0, 0, 0, 0);
  26893. if (getSampleRate() > 0)
  26894. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  26895. if (getBlockSize() > 0)
  26896. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  26897. dispatch (effOpen, 0, 0, 0, 0);
  26898. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26899. getSampleRate(), getBlockSize());
  26900. if (getNumPrograms() > 1)
  26901. setCurrentProgram (0);
  26902. else
  26903. dispatch (effSetProgram, 0, 0, 0, 0);
  26904. int i;
  26905. for (i = effect->numInputs; --i >= 0;)
  26906. dispatch (effConnectInput, i, 1, 0, 0);
  26907. for (i = effect->numOutputs; --i >= 0;)
  26908. dispatch (effConnectOutput, i, 1, 0, 0);
  26909. updateStoredProgramNames();
  26910. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  26911. setLatencySamples (effect->initialDelay);
  26912. }
  26913. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  26914. int samplesPerBlockExpected)
  26915. {
  26916. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  26917. sampleRate_, samplesPerBlockExpected);
  26918. setLatencySamples (effect->initialDelay);
  26919. vstHostTime.tempo = 120.0;
  26920. vstHostTime.timeSigNumerator = 4;
  26921. vstHostTime.timeSigDenominator = 4;
  26922. vstHostTime.sampleRate = sampleRate_;
  26923. vstHostTime.samplePos = 0;
  26924. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  26925. initialise();
  26926. if (initialised)
  26927. {
  26928. wantsMidiMessages = wantsMidiMessages
  26929. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  26930. if (wantsMidiMessages)
  26931. midiEventsToSend.ensureSize (256);
  26932. else
  26933. midiEventsToSend.freeEvents();
  26934. incomingMidi.clear();
  26935. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  26936. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  26937. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  26938. if (! isPowerOn)
  26939. setPower (true);
  26940. // dodgy hack to force some plugins to initialise the sample rate..
  26941. if ((! hasEditor()) && getNumParameters() > 0)
  26942. {
  26943. const float old = getParameter (0);
  26944. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  26945. setParameter (0, old);
  26946. }
  26947. dispatch (effStartProcess, 0, 0, 0, 0);
  26948. }
  26949. }
  26950. void VSTPluginInstance::releaseResources()
  26951. {
  26952. if (initialised)
  26953. {
  26954. dispatch (effStopProcess, 0, 0, 0, 0);
  26955. setPower (false);
  26956. }
  26957. tempBuffer.setSize (1, 1);
  26958. incomingMidi.clear();
  26959. midiEventsToSend.freeEvents();
  26960. }
  26961. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  26962. MidiBuffer& midiMessages)
  26963. {
  26964. const int numSamples = buffer.getNumSamples();
  26965. if (initialised)
  26966. {
  26967. AudioPlayHead* playHead = getPlayHead();
  26968. if (playHead != 0)
  26969. {
  26970. AudioPlayHead::CurrentPositionInfo position;
  26971. playHead->getCurrentPosition (position);
  26972. vstHostTime.tempo = position.bpm;
  26973. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  26974. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  26975. vstHostTime.ppqPos = position.ppqPosition;
  26976. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  26977. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  26978. if (position.isPlaying)
  26979. vstHostTime.flags |= kVstTransportPlaying;
  26980. else
  26981. vstHostTime.flags &= ~kVstTransportPlaying;
  26982. }
  26983. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  26984. if (wantsMidiMessages)
  26985. {
  26986. midiEventsToSend.clear();
  26987. midiEventsToSend.ensureSize (1);
  26988. MidiBuffer::Iterator iter (midiMessages);
  26989. const uint8* midiData;
  26990. int numBytesOfMidiData, samplePosition;
  26991. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  26992. {
  26993. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  26994. jlimit (0, numSamples - 1, samplePosition));
  26995. }
  26996. try
  26997. {
  26998. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  26999. }
  27000. catch (...)
  27001. {}
  27002. }
  27003. _clearfp();
  27004. if ((effect->flags & effFlagsCanReplacing) != 0)
  27005. {
  27006. try
  27007. {
  27008. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27009. }
  27010. catch (...)
  27011. {}
  27012. }
  27013. else
  27014. {
  27015. tempBuffer.setSize (effect->numOutputs, numSamples);
  27016. tempBuffer.clear();
  27017. try
  27018. {
  27019. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27020. }
  27021. catch (...)
  27022. {}
  27023. for (int i = effect->numOutputs; --i >= 0;)
  27024. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27025. }
  27026. }
  27027. else
  27028. {
  27029. // Not initialised, so just bypass..
  27030. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27031. buffer.clear (i, 0, buffer.getNumSamples());
  27032. }
  27033. {
  27034. // copy any incoming midi..
  27035. const ScopedLock sl (midiInLock);
  27036. midiMessages.swapWith (incomingMidi);
  27037. incomingMidi.clear();
  27038. }
  27039. }
  27040. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27041. {
  27042. if (events != 0)
  27043. {
  27044. const ScopedLock sl (midiInLock);
  27045. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27046. }
  27047. }
  27048. static Array <VSTPluginWindow*> activeVSTWindows;
  27049. class VSTPluginWindow : public AudioProcessorEditor,
  27050. #if ! JUCE_MAC
  27051. public ComponentMovementWatcher,
  27052. #endif
  27053. public Timer
  27054. {
  27055. public:
  27056. VSTPluginWindow (VSTPluginInstance& plugin_)
  27057. : AudioProcessorEditor (&plugin_),
  27058. #if ! JUCE_MAC
  27059. ComponentMovementWatcher (this),
  27060. #endif
  27061. plugin (plugin_),
  27062. isOpen (false),
  27063. recursiveResize (false),
  27064. pluginWantsKeys (false),
  27065. pluginRefusesToResize (false),
  27066. alreadyInside (false)
  27067. {
  27068. #if JUCE_WINDOWS
  27069. sizeCheckCount = 0;
  27070. pluginHWND = 0;
  27071. #elif JUCE_LINUX
  27072. pluginWindow = None;
  27073. pluginProc = None;
  27074. #else
  27075. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27076. #endif
  27077. activeVSTWindows.add (this);
  27078. setSize (1, 1);
  27079. setOpaque (true);
  27080. setVisible (true);
  27081. }
  27082. ~VSTPluginWindow()
  27083. {
  27084. #if JUCE_MAC
  27085. innerWrapper = 0;
  27086. #else
  27087. closePluginWindow();
  27088. #endif
  27089. activeVSTWindows.removeValue (this);
  27090. plugin.editorBeingDeleted (this);
  27091. }
  27092. #if ! JUCE_MAC
  27093. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27094. {
  27095. if (recursiveResize)
  27096. return;
  27097. Component* const topComp = getTopLevelComponent();
  27098. if (topComp->getPeer() != 0)
  27099. {
  27100. const Point<int> pos (topComp->getLocalPoint (this, Point<int>()));
  27101. recursiveResize = true;
  27102. #if JUCE_WINDOWS
  27103. if (pluginHWND != 0)
  27104. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27105. #elif JUCE_LINUX
  27106. if (pluginWindow != 0)
  27107. {
  27108. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27109. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27110. XMapRaised (display, pluginWindow);
  27111. }
  27112. #endif
  27113. recursiveResize = false;
  27114. }
  27115. }
  27116. void componentVisibilityChanged()
  27117. {
  27118. if (isShowing())
  27119. openPluginWindow();
  27120. else
  27121. closePluginWindow();
  27122. componentMovedOrResized (true, true);
  27123. }
  27124. void componentPeerChanged()
  27125. {
  27126. closePluginWindow();
  27127. openPluginWindow();
  27128. }
  27129. #endif
  27130. bool keyStateChanged (bool)
  27131. {
  27132. return pluginWantsKeys;
  27133. }
  27134. bool keyPressed (const KeyPress&)
  27135. {
  27136. return pluginWantsKeys;
  27137. }
  27138. #if JUCE_MAC
  27139. void paint (Graphics& g)
  27140. {
  27141. g.fillAll (Colours::black);
  27142. }
  27143. #else
  27144. void paint (Graphics& g)
  27145. {
  27146. if (isOpen)
  27147. {
  27148. ComponentPeer* const peer = getPeer();
  27149. if (peer != 0)
  27150. {
  27151. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27152. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27153. #if JUCE_LINUX
  27154. if (pluginWindow != 0)
  27155. {
  27156. const Rectangle<int> clip (g.getClipBounds());
  27157. XEvent ev;
  27158. zerostruct (ev);
  27159. ev.xexpose.type = Expose;
  27160. ev.xexpose.display = display;
  27161. ev.xexpose.window = pluginWindow;
  27162. ev.xexpose.x = clip.getX();
  27163. ev.xexpose.y = clip.getY();
  27164. ev.xexpose.width = clip.getWidth();
  27165. ev.xexpose.height = clip.getHeight();
  27166. sendEventToChild (&ev);
  27167. }
  27168. #endif
  27169. }
  27170. }
  27171. else
  27172. {
  27173. g.fillAll (Colours::black);
  27174. }
  27175. }
  27176. #endif
  27177. void timerCallback()
  27178. {
  27179. #if JUCE_WINDOWS
  27180. if (--sizeCheckCount <= 0)
  27181. {
  27182. sizeCheckCount = 10;
  27183. checkPluginWindowSize();
  27184. }
  27185. #endif
  27186. try
  27187. {
  27188. static bool reentrant = false;
  27189. if (! reentrant)
  27190. {
  27191. reentrant = true;
  27192. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27193. reentrant = false;
  27194. }
  27195. }
  27196. catch (...)
  27197. {}
  27198. }
  27199. void mouseDown (const MouseEvent& e)
  27200. {
  27201. #if JUCE_LINUX
  27202. if (pluginWindow == 0)
  27203. return;
  27204. toFront (true);
  27205. XEvent ev;
  27206. zerostruct (ev);
  27207. ev.xbutton.display = display;
  27208. ev.xbutton.type = ButtonPress;
  27209. ev.xbutton.window = pluginWindow;
  27210. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27211. ev.xbutton.time = CurrentTime;
  27212. ev.xbutton.x = e.x;
  27213. ev.xbutton.y = e.y;
  27214. ev.xbutton.x_root = e.getScreenX();
  27215. ev.xbutton.y_root = e.getScreenY();
  27216. translateJuceToXButtonModifiers (e, ev);
  27217. sendEventToChild (&ev);
  27218. #elif JUCE_WINDOWS
  27219. (void) e;
  27220. toFront (true);
  27221. #endif
  27222. }
  27223. void broughtToFront()
  27224. {
  27225. activeVSTWindows.removeValue (this);
  27226. activeVSTWindows.add (this);
  27227. #if JUCE_MAC
  27228. dispatch (effEditTop, 0, 0, 0, 0);
  27229. #endif
  27230. }
  27231. private:
  27232. VSTPluginInstance& plugin;
  27233. bool isOpen, recursiveResize;
  27234. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27235. #if JUCE_WINDOWS
  27236. HWND pluginHWND;
  27237. void* originalWndProc;
  27238. int sizeCheckCount;
  27239. #elif JUCE_LINUX
  27240. Window pluginWindow;
  27241. EventProcPtr pluginProc;
  27242. #endif
  27243. #if JUCE_MAC
  27244. void openPluginWindow (WindowRef parentWindow)
  27245. {
  27246. if (isOpen || parentWindow == 0)
  27247. return;
  27248. isOpen = true;
  27249. ERect* rect = 0;
  27250. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27251. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27252. // do this before and after like in the steinberg example
  27253. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27254. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27255. // Install keyboard hooks
  27256. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27257. // double-check it's not too tiny
  27258. int w = 250, h = 150;
  27259. if (rect != 0)
  27260. {
  27261. w = rect->right - rect->left;
  27262. h = rect->bottom - rect->top;
  27263. if (w == 0 || h == 0)
  27264. {
  27265. w = 250;
  27266. h = 150;
  27267. }
  27268. }
  27269. w = jmax (w, 32);
  27270. h = jmax (h, 32);
  27271. setSize (w, h);
  27272. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27273. repaint();
  27274. }
  27275. #else
  27276. void openPluginWindow()
  27277. {
  27278. if (isOpen || getWindowHandle() == 0)
  27279. return;
  27280. log ("Opening VST UI: " + plugin.name);
  27281. isOpen = true;
  27282. ERect* rect = 0;
  27283. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27284. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27285. // do this before and after like in the steinberg example
  27286. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27287. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27288. // Install keyboard hooks
  27289. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27290. #if JUCE_WINDOWS
  27291. originalWndProc = 0;
  27292. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27293. if (pluginHWND == 0)
  27294. {
  27295. isOpen = false;
  27296. setSize (300, 150);
  27297. return;
  27298. }
  27299. #pragma warning (push)
  27300. #pragma warning (disable: 4244)
  27301. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27302. if (! pluginWantsKeys)
  27303. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27304. #pragma warning (pop)
  27305. int w, h;
  27306. RECT r;
  27307. GetWindowRect (pluginHWND, &r);
  27308. w = r.right - r.left;
  27309. h = r.bottom - r.top;
  27310. if (rect != 0)
  27311. {
  27312. const int rw = rect->right - rect->left;
  27313. const int rh = rect->bottom - rect->top;
  27314. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27315. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27316. {
  27317. // very dodgy logic to decide which size is right.
  27318. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27319. {
  27320. SetWindowPos (pluginHWND, 0,
  27321. 0, 0, rw, rh,
  27322. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27323. GetWindowRect (pluginHWND, &r);
  27324. w = r.right - r.left;
  27325. h = r.bottom - r.top;
  27326. pluginRefusesToResize = (w != rw) || (h != rh);
  27327. w = rw;
  27328. h = rh;
  27329. }
  27330. }
  27331. }
  27332. #elif JUCE_LINUX
  27333. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27334. if (pluginWindow != 0)
  27335. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27336. XInternAtom (display, "_XEventProc", False));
  27337. int w = 250, h = 150;
  27338. if (rect != 0)
  27339. {
  27340. w = rect->right - rect->left;
  27341. h = rect->bottom - rect->top;
  27342. if (w == 0 || h == 0)
  27343. {
  27344. w = 250;
  27345. h = 150;
  27346. }
  27347. }
  27348. if (pluginWindow != 0)
  27349. XMapRaised (display, pluginWindow);
  27350. #endif
  27351. // double-check it's not too tiny
  27352. w = jmax (w, 32);
  27353. h = jmax (h, 32);
  27354. setSize (w, h);
  27355. #if JUCE_WINDOWS
  27356. checkPluginWindowSize();
  27357. #endif
  27358. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27359. repaint();
  27360. }
  27361. #endif
  27362. #if ! JUCE_MAC
  27363. void closePluginWindow()
  27364. {
  27365. if (isOpen)
  27366. {
  27367. log ("Closing VST UI: " + plugin.getName());
  27368. isOpen = false;
  27369. dispatch (effEditClose, 0, 0, 0, 0);
  27370. #if JUCE_WINDOWS
  27371. #pragma warning (push)
  27372. #pragma warning (disable: 4244)
  27373. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27374. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27375. #pragma warning (pop)
  27376. stopTimer();
  27377. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27378. DestroyWindow (pluginHWND);
  27379. pluginHWND = 0;
  27380. #elif JUCE_LINUX
  27381. stopTimer();
  27382. pluginWindow = 0;
  27383. pluginProc = 0;
  27384. #endif
  27385. }
  27386. }
  27387. #endif
  27388. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27389. {
  27390. return plugin.dispatch (opcode, index, value, ptr, opt);
  27391. }
  27392. #if JUCE_WINDOWS
  27393. void checkPluginWindowSize()
  27394. {
  27395. RECT r;
  27396. GetWindowRect (pluginHWND, &r);
  27397. const int w = r.right - r.left;
  27398. const int h = r.bottom - r.top;
  27399. if (isShowing() && w > 0 && h > 0
  27400. && (w != getWidth() || h != getHeight())
  27401. && ! pluginRefusesToResize)
  27402. {
  27403. setSize (w, h);
  27404. sizeCheckCount = 0;
  27405. }
  27406. }
  27407. // hooks to get keyboard events from VST windows..
  27408. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27409. {
  27410. for (int i = activeVSTWindows.size(); --i >= 0;)
  27411. {
  27412. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27413. if (w->pluginHWND == hW)
  27414. {
  27415. if (message == WM_CHAR
  27416. || message == WM_KEYDOWN
  27417. || message == WM_SYSKEYDOWN
  27418. || message == WM_KEYUP
  27419. || message == WM_SYSKEYUP
  27420. || message == WM_APPCOMMAND)
  27421. {
  27422. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27423. message, wParam, lParam);
  27424. }
  27425. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27426. (HWND) w->pluginHWND,
  27427. message,
  27428. wParam,
  27429. lParam);
  27430. }
  27431. }
  27432. return DefWindowProc (hW, message, wParam, lParam);
  27433. }
  27434. #endif
  27435. #if JUCE_LINUX
  27436. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27437. void sendEventToChild (XEvent* event)
  27438. {
  27439. if (pluginProc != 0)
  27440. {
  27441. // if the plugin publishes an event procedure, pass the event directly..
  27442. pluginProc (event);
  27443. }
  27444. else if (pluginWindow != 0)
  27445. {
  27446. // if the plugin has a window, then send the event to the window so that
  27447. // its message thread will pick it up..
  27448. XSendEvent (display, pluginWindow, False, 0L, event);
  27449. XFlush (display);
  27450. }
  27451. }
  27452. void mouseEnter (const MouseEvent& e)
  27453. {
  27454. if (pluginWindow != 0)
  27455. {
  27456. XEvent ev;
  27457. zerostruct (ev);
  27458. ev.xcrossing.display = display;
  27459. ev.xcrossing.type = EnterNotify;
  27460. ev.xcrossing.window = pluginWindow;
  27461. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27462. ev.xcrossing.time = CurrentTime;
  27463. ev.xcrossing.x = e.x;
  27464. ev.xcrossing.y = e.y;
  27465. ev.xcrossing.x_root = e.getScreenX();
  27466. ev.xcrossing.y_root = e.getScreenY();
  27467. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27468. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27469. translateJuceToXCrossingModifiers (e, ev);
  27470. sendEventToChild (&ev);
  27471. }
  27472. }
  27473. void mouseExit (const MouseEvent& e)
  27474. {
  27475. if (pluginWindow != 0)
  27476. {
  27477. XEvent ev;
  27478. zerostruct (ev);
  27479. ev.xcrossing.display = display;
  27480. ev.xcrossing.type = LeaveNotify;
  27481. ev.xcrossing.window = pluginWindow;
  27482. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27483. ev.xcrossing.time = CurrentTime;
  27484. ev.xcrossing.x = e.x;
  27485. ev.xcrossing.y = e.y;
  27486. ev.xcrossing.x_root = e.getScreenX();
  27487. ev.xcrossing.y_root = e.getScreenY();
  27488. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27489. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27490. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27491. translateJuceToXCrossingModifiers (e, ev);
  27492. sendEventToChild (&ev);
  27493. }
  27494. }
  27495. void mouseMove (const MouseEvent& e)
  27496. {
  27497. if (pluginWindow != 0)
  27498. {
  27499. XEvent ev;
  27500. zerostruct (ev);
  27501. ev.xmotion.display = display;
  27502. ev.xmotion.type = MotionNotify;
  27503. ev.xmotion.window = pluginWindow;
  27504. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27505. ev.xmotion.time = CurrentTime;
  27506. ev.xmotion.is_hint = NotifyNormal;
  27507. ev.xmotion.x = e.x;
  27508. ev.xmotion.y = e.y;
  27509. ev.xmotion.x_root = e.getScreenX();
  27510. ev.xmotion.y_root = e.getScreenY();
  27511. sendEventToChild (&ev);
  27512. }
  27513. }
  27514. void mouseDrag (const MouseEvent& e)
  27515. {
  27516. if (pluginWindow != 0)
  27517. {
  27518. XEvent ev;
  27519. zerostruct (ev);
  27520. ev.xmotion.display = display;
  27521. ev.xmotion.type = MotionNotify;
  27522. ev.xmotion.window = pluginWindow;
  27523. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27524. ev.xmotion.time = CurrentTime;
  27525. ev.xmotion.x = e.x ;
  27526. ev.xmotion.y = e.y;
  27527. ev.xmotion.x_root = e.getScreenX();
  27528. ev.xmotion.y_root = e.getScreenY();
  27529. ev.xmotion.is_hint = NotifyNormal;
  27530. translateJuceToXMotionModifiers (e, ev);
  27531. sendEventToChild (&ev);
  27532. }
  27533. }
  27534. void mouseUp (const MouseEvent& e)
  27535. {
  27536. if (pluginWindow != 0)
  27537. {
  27538. XEvent ev;
  27539. zerostruct (ev);
  27540. ev.xbutton.display = display;
  27541. ev.xbutton.type = ButtonRelease;
  27542. ev.xbutton.window = pluginWindow;
  27543. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27544. ev.xbutton.time = CurrentTime;
  27545. ev.xbutton.x = e.x;
  27546. ev.xbutton.y = e.y;
  27547. ev.xbutton.x_root = e.getScreenX();
  27548. ev.xbutton.y_root = e.getScreenY();
  27549. translateJuceToXButtonModifiers (e, ev);
  27550. sendEventToChild (&ev);
  27551. }
  27552. }
  27553. void mouseWheelMove (const MouseEvent& e,
  27554. float incrementX,
  27555. float incrementY)
  27556. {
  27557. if (pluginWindow != 0)
  27558. {
  27559. XEvent ev;
  27560. zerostruct (ev);
  27561. ev.xbutton.display = display;
  27562. ev.xbutton.type = ButtonPress;
  27563. ev.xbutton.window = pluginWindow;
  27564. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27565. ev.xbutton.time = CurrentTime;
  27566. ev.xbutton.x = e.x;
  27567. ev.xbutton.y = e.y;
  27568. ev.xbutton.x_root = e.getScreenX();
  27569. ev.xbutton.y_root = e.getScreenY();
  27570. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27571. sendEventToChild (&ev);
  27572. // TODO - put a usleep here ?
  27573. ev.xbutton.type = ButtonRelease;
  27574. sendEventToChild (&ev);
  27575. }
  27576. }
  27577. #endif
  27578. #if JUCE_MAC
  27579. #if ! JUCE_SUPPORT_CARBON
  27580. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27581. #endif
  27582. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27583. {
  27584. public:
  27585. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27586. : owner (owner_),
  27587. alreadyInside (false)
  27588. {
  27589. }
  27590. ~InnerWrapperComponent()
  27591. {
  27592. deleteWindow();
  27593. }
  27594. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27595. {
  27596. owner->openPluginWindow (windowRef);
  27597. return 0;
  27598. }
  27599. void removeView (HIViewRef)
  27600. {
  27601. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27602. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27603. }
  27604. bool getEmbeddedViewSize (int& w, int& h)
  27605. {
  27606. ERect* rect = 0;
  27607. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27608. w = rect->right - rect->left;
  27609. h = rect->bottom - rect->top;
  27610. return true;
  27611. }
  27612. void mouseDown (int x, int y)
  27613. {
  27614. if (! alreadyInside)
  27615. {
  27616. alreadyInside = true;
  27617. getTopLevelComponent()->toFront (true);
  27618. owner->dispatch (effEditMouse, x, y, 0, 0);
  27619. alreadyInside = false;
  27620. }
  27621. else
  27622. {
  27623. PostEvent (::mouseDown, 0);
  27624. }
  27625. }
  27626. void paint()
  27627. {
  27628. ComponentPeer* const peer = getPeer();
  27629. if (peer != 0)
  27630. {
  27631. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27632. ERect r;
  27633. r.left = pos.getX();
  27634. r.right = r.left + getWidth();
  27635. r.top = pos.getY();
  27636. r.bottom = r.top + getHeight();
  27637. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27638. }
  27639. }
  27640. private:
  27641. VSTPluginWindow* const owner;
  27642. bool alreadyInside;
  27643. };
  27644. friend class InnerWrapperComponent;
  27645. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27646. void resized()
  27647. {
  27648. innerWrapper->setSize (getWidth(), getHeight());
  27649. }
  27650. #endif
  27651. private:
  27652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow);
  27653. };
  27654. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27655. {
  27656. if (hasEditor())
  27657. return new VSTPluginWindow (*this);
  27658. return 0;
  27659. }
  27660. void VSTPluginInstance::handleAsyncUpdate()
  27661. {
  27662. // indicates that something about the plugin has changed..
  27663. updateHostDisplay();
  27664. }
  27665. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27666. {
  27667. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27668. {
  27669. changeProgramName (getCurrentProgram(), prog->prgName);
  27670. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27671. setParameter (i, vst_swapFloat (prog->params[i]));
  27672. return true;
  27673. }
  27674. return false;
  27675. }
  27676. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27677. const int dataSize)
  27678. {
  27679. if (dataSize < 28)
  27680. return false;
  27681. const fxSet* const set = (const fxSet*) data;
  27682. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27683. || vst_swap (set->version) > fxbVersionNum)
  27684. return false;
  27685. if (vst_swap (set->fxMagic) == 'FxBk')
  27686. {
  27687. // bank of programs
  27688. if (vst_swap (set->numPrograms) >= 0)
  27689. {
  27690. const int oldProg = getCurrentProgram();
  27691. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27692. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27693. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27694. {
  27695. if (i != oldProg)
  27696. {
  27697. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27698. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27699. return false;
  27700. if (vst_swap (set->numPrograms) > 0)
  27701. setCurrentProgram (i);
  27702. if (! restoreProgramSettings (prog))
  27703. return false;
  27704. }
  27705. }
  27706. if (vst_swap (set->numPrograms) > 0)
  27707. setCurrentProgram (oldProg);
  27708. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27709. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27710. return false;
  27711. if (! restoreProgramSettings (prog))
  27712. return false;
  27713. }
  27714. }
  27715. else if (vst_swap (set->fxMagic) == 'FxCk')
  27716. {
  27717. // single program
  27718. const fxProgram* const prog = (const fxProgram*) data;
  27719. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27720. return false;
  27721. changeProgramName (getCurrentProgram(), prog->prgName);
  27722. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27723. setParameter (i, vst_swapFloat (prog->params[i]));
  27724. }
  27725. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27726. {
  27727. // non-preset chunk
  27728. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27729. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27730. return false;
  27731. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27732. }
  27733. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27734. {
  27735. // preset chunk
  27736. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27737. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27738. return false;
  27739. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27740. changeProgramName (getCurrentProgram(), cset->name);
  27741. }
  27742. else
  27743. {
  27744. return false;
  27745. }
  27746. return true;
  27747. }
  27748. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27749. {
  27750. const int numParams = getNumParameters();
  27751. prog->chunkMagic = vst_swap ('CcnK');
  27752. prog->byteSize = 0;
  27753. prog->fxMagic = vst_swap ('FxCk');
  27754. prog->version = vst_swap (fxbVersionNum);
  27755. prog->fxID = vst_swap (getUID());
  27756. prog->fxVersion = vst_swap (getVersionNumber());
  27757. prog->numParams = vst_swap (numParams);
  27758. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27759. for (int i = 0; i < numParams; ++i)
  27760. prog->params[i] = vst_swapFloat (getParameter (i));
  27761. }
  27762. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27763. {
  27764. const int numPrograms = getNumPrograms();
  27765. const int numParams = getNumParameters();
  27766. if (usesChunks())
  27767. {
  27768. if (isFXB)
  27769. {
  27770. MemoryBlock chunk;
  27771. getChunkData (chunk, false, maxSizeMB);
  27772. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27773. dest.setSize (totalLen, true);
  27774. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27775. set->chunkMagic = vst_swap ('CcnK');
  27776. set->byteSize = 0;
  27777. set->fxMagic = vst_swap ('FBCh');
  27778. set->version = vst_swap (fxbVersionNum);
  27779. set->fxID = vst_swap (getUID());
  27780. set->fxVersion = vst_swap (getVersionNumber());
  27781. set->numPrograms = vst_swap (numPrograms);
  27782. set->chunkSize = vst_swap ((long) chunk.getSize());
  27783. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27784. }
  27785. else
  27786. {
  27787. MemoryBlock chunk;
  27788. getChunkData (chunk, true, maxSizeMB);
  27789. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27790. dest.setSize (totalLen, true);
  27791. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27792. set->chunkMagic = vst_swap ('CcnK');
  27793. set->byteSize = 0;
  27794. set->fxMagic = vst_swap ('FPCh');
  27795. set->version = vst_swap (fxbVersionNum);
  27796. set->fxID = vst_swap (getUID());
  27797. set->fxVersion = vst_swap (getVersionNumber());
  27798. set->numPrograms = vst_swap (numPrograms);
  27799. set->chunkSize = vst_swap ((long) chunk.getSize());
  27800. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27801. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27802. }
  27803. }
  27804. else
  27805. {
  27806. if (isFXB)
  27807. {
  27808. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27809. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27810. dest.setSize (len, true);
  27811. fxSet* const set = (fxSet*) dest.getData();
  27812. set->chunkMagic = vst_swap ('CcnK');
  27813. set->byteSize = 0;
  27814. set->fxMagic = vst_swap ('FxBk');
  27815. set->version = vst_swap (fxbVersionNum);
  27816. set->fxID = vst_swap (getUID());
  27817. set->fxVersion = vst_swap (getVersionNumber());
  27818. set->numPrograms = vst_swap (numPrograms);
  27819. const int oldProgram = getCurrentProgram();
  27820. MemoryBlock oldSettings;
  27821. createTempParameterStore (oldSettings);
  27822. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27823. for (int i = 0; i < numPrograms; ++i)
  27824. {
  27825. if (i != oldProgram)
  27826. {
  27827. setCurrentProgram (i);
  27828. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27829. }
  27830. }
  27831. setCurrentProgram (oldProgram);
  27832. restoreFromTempParameterStore (oldSettings);
  27833. }
  27834. else
  27835. {
  27836. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27837. dest.setSize (totalLen, true);
  27838. setParamsInProgramBlock ((fxProgram*) dest.getData());
  27839. }
  27840. }
  27841. return true;
  27842. }
  27843. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  27844. {
  27845. if (usesChunks())
  27846. {
  27847. void* data = 0;
  27848. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  27849. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  27850. {
  27851. mb.setSize (bytes);
  27852. mb.copyFrom (data, 0, bytes);
  27853. }
  27854. }
  27855. }
  27856. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  27857. {
  27858. if (size > 0 && usesChunks())
  27859. {
  27860. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  27861. if (! isPreset)
  27862. updateStoredProgramNames();
  27863. }
  27864. }
  27865. void VSTPluginInstance::timerCallback()
  27866. {
  27867. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  27868. stopTimer();
  27869. }
  27870. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  27871. {
  27872. const ScopedLock sl (lock);
  27873. ++insideVSTCallback;
  27874. int result = 0;
  27875. try
  27876. {
  27877. if (effect != 0)
  27878. {
  27879. #if JUCE_MAC
  27880. if (module->resFileId != 0)
  27881. UseResFile (module->resFileId);
  27882. #endif
  27883. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  27884. #if JUCE_MAC
  27885. module->resFileId = CurResFile();
  27886. #endif
  27887. --insideVSTCallback;
  27888. return result;
  27889. }
  27890. }
  27891. catch (...)
  27892. {
  27893. }
  27894. --insideVSTCallback;
  27895. return result;
  27896. }
  27897. namespace
  27898. {
  27899. static const int defaultVSTSampleRateValue = 16384;
  27900. static const int defaultVSTBlockSizeValue = 512;
  27901. // handles non plugin-specific callbacks..
  27902. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27903. {
  27904. (void) index;
  27905. (void) value;
  27906. (void) opt;
  27907. switch (opcode)
  27908. {
  27909. case audioMasterCanDo:
  27910. {
  27911. static const char* canDos[] = { "supplyIdle",
  27912. "sendVstEvents",
  27913. "sendVstMidiEvent",
  27914. "sendVstTimeInfo",
  27915. "receiveVstEvents",
  27916. "receiveVstMidiEvent",
  27917. "supportShell",
  27918. "shellCategory" };
  27919. for (int i = 0; i < numElementsInArray (canDos); ++i)
  27920. if (strcmp (canDos[i], (const char*) ptr) == 0)
  27921. return 1;
  27922. return 0;
  27923. }
  27924. case audioMasterVersion: return 0x2400;
  27925. case audioMasterCurrentId: return shellUIDToCreate;
  27926. case audioMasterGetNumAutomatableParameters: return 0;
  27927. case audioMasterGetAutomationState: return 1;
  27928. case audioMasterGetVendorVersion: return 0x0101;
  27929. case audioMasterGetVendorString:
  27930. case audioMasterGetProductString:
  27931. {
  27932. String hostName ("Juce VST Host");
  27933. if (JUCEApplication::getInstance() != 0)
  27934. hostName = JUCEApplication::getInstance()->getApplicationName();
  27935. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  27936. break;
  27937. }
  27938. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  27939. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  27940. case audioMasterSetOutputSampleRate: return 0;
  27941. default:
  27942. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  27943. break;
  27944. }
  27945. return 0;
  27946. }
  27947. }
  27948. // handles callbacks for a specific plugin
  27949. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  27950. {
  27951. switch (opcode)
  27952. {
  27953. case audioMasterAutomate:
  27954. sendParamChangeMessageToListeners (index, opt);
  27955. break;
  27956. case audioMasterProcessEvents:
  27957. handleMidiFromPlugin ((const VstEvents*) ptr);
  27958. break;
  27959. case audioMasterGetTime:
  27960. #if JUCE_MSVC
  27961. #pragma warning (push)
  27962. #pragma warning (disable: 4311)
  27963. #endif
  27964. return (VstIntPtr) &vstHostTime;
  27965. #if JUCE_MSVC
  27966. #pragma warning (pop)
  27967. #endif
  27968. break;
  27969. case audioMasterIdle:
  27970. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  27971. {
  27972. ++insideVSTCallback;
  27973. #if JUCE_MAC
  27974. if (getActiveEditor() != 0)
  27975. dispatch (effEditIdle, 0, 0, 0, 0);
  27976. #endif
  27977. juce_callAnyTimersSynchronously();
  27978. handleUpdateNowIfNeeded();
  27979. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  27980. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  27981. --insideVSTCallback;
  27982. }
  27983. break;
  27984. case audioMasterUpdateDisplay:
  27985. triggerAsyncUpdate();
  27986. break;
  27987. case audioMasterTempoAt:
  27988. // returns (10000 * bpm)
  27989. break;
  27990. case audioMasterNeedIdle:
  27991. startTimer (50);
  27992. break;
  27993. case audioMasterSizeWindow:
  27994. if (getActiveEditor() != 0)
  27995. getActiveEditor()->setSize (index, value);
  27996. return 1;
  27997. case audioMasterGetSampleRate:
  27998. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  27999. case audioMasterGetBlockSize:
  28000. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28001. case audioMasterWantMidi:
  28002. wantsMidiMessages = true;
  28003. break;
  28004. case audioMasterGetDirectory:
  28005. #if JUCE_MAC
  28006. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28007. #else
  28008. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8().getAddress();
  28009. #endif
  28010. case audioMasterGetAutomationState:
  28011. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28012. break;
  28013. // none of these are handled (yet)..
  28014. case audioMasterBeginEdit:
  28015. case audioMasterEndEdit:
  28016. case audioMasterSetTime:
  28017. case audioMasterPinConnected:
  28018. case audioMasterGetParameterQuantization:
  28019. case audioMasterIOChanged:
  28020. case audioMasterGetInputLatency:
  28021. case audioMasterGetOutputLatency:
  28022. case audioMasterGetPreviousPlug:
  28023. case audioMasterGetNextPlug:
  28024. case audioMasterWillReplaceOrAccumulate:
  28025. case audioMasterGetCurrentProcessLevel:
  28026. case audioMasterOfflineStart:
  28027. case audioMasterOfflineRead:
  28028. case audioMasterOfflineWrite:
  28029. case audioMasterOfflineGetCurrentPass:
  28030. case audioMasterOfflineGetCurrentMetaPass:
  28031. case audioMasterVendorSpecific:
  28032. case audioMasterSetIcon:
  28033. case audioMasterGetLanguage:
  28034. case audioMasterOpenWindow:
  28035. case audioMasterCloseWindow:
  28036. break;
  28037. default:
  28038. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28039. }
  28040. return 0;
  28041. }
  28042. // entry point for all callbacks from the plugin
  28043. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28044. {
  28045. try
  28046. {
  28047. if (effect != 0 && effect->resvd2 != 0)
  28048. {
  28049. return ((VSTPluginInstance*)(effect->resvd2))
  28050. ->handleCallback (opcode, index, value, ptr, opt);
  28051. }
  28052. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28053. }
  28054. catch (...)
  28055. {
  28056. return 0;
  28057. }
  28058. }
  28059. const String VSTPluginInstance::getVersion() const
  28060. {
  28061. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28062. String s;
  28063. if (v == 0 || v == -1)
  28064. v = getVersionNumber();
  28065. if (v != 0)
  28066. {
  28067. int versionBits[4];
  28068. int n = 0;
  28069. while (v != 0)
  28070. {
  28071. versionBits [n++] = (v & 0xff);
  28072. v >>= 8;
  28073. }
  28074. s << 'V';
  28075. while (n > 0)
  28076. {
  28077. s << versionBits [--n];
  28078. if (n > 0)
  28079. s << '.';
  28080. }
  28081. }
  28082. return s;
  28083. }
  28084. int VSTPluginInstance::getUID() const
  28085. {
  28086. int uid = effect != 0 ? effect->uniqueID : 0;
  28087. if (uid == 0)
  28088. uid = module->file.hashCode();
  28089. return uid;
  28090. }
  28091. const String VSTPluginInstance::getCategory() const
  28092. {
  28093. const char* result = 0;
  28094. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28095. {
  28096. case kPlugCategEffect: result = "Effect"; break;
  28097. case kPlugCategSynth: result = "Synth"; break;
  28098. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28099. case kPlugCategMastering: result = "Mastering"; break;
  28100. case kPlugCategSpacializer: result = "Spacial"; break;
  28101. case kPlugCategRoomFx: result = "Reverb"; break;
  28102. case kPlugSurroundFx: result = "Surround"; break;
  28103. case kPlugCategRestoration: result = "Restoration"; break;
  28104. case kPlugCategGenerator: result = "Tone generation"; break;
  28105. default: break;
  28106. }
  28107. return result;
  28108. }
  28109. float VSTPluginInstance::getParameter (int index)
  28110. {
  28111. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28112. {
  28113. try
  28114. {
  28115. const ScopedLock sl (lock);
  28116. return effect->getParameter (effect, index);
  28117. }
  28118. catch (...)
  28119. {
  28120. }
  28121. }
  28122. return 0.0f;
  28123. }
  28124. void VSTPluginInstance::setParameter (int index, float newValue)
  28125. {
  28126. if (effect != 0 && isPositiveAndBelow (index, (int) effect->numParams))
  28127. {
  28128. try
  28129. {
  28130. const ScopedLock sl (lock);
  28131. if (effect->getParameter (effect, index) != newValue)
  28132. effect->setParameter (effect, index, newValue);
  28133. }
  28134. catch (...)
  28135. {
  28136. }
  28137. }
  28138. }
  28139. const String VSTPluginInstance::getParameterName (int index)
  28140. {
  28141. if (effect != 0)
  28142. {
  28143. jassert (index >= 0 && index < effect->numParams);
  28144. char nm [256];
  28145. zerostruct (nm);
  28146. dispatch (effGetParamName, index, 0, nm, 0);
  28147. return String (nm).trim();
  28148. }
  28149. return String::empty;
  28150. }
  28151. const String VSTPluginInstance::getParameterLabel (int index) const
  28152. {
  28153. if (effect != 0)
  28154. {
  28155. jassert (index >= 0 && index < effect->numParams);
  28156. char nm [256];
  28157. zerostruct (nm);
  28158. dispatch (effGetParamLabel, index, 0, nm, 0);
  28159. return String (nm).trim();
  28160. }
  28161. return String::empty;
  28162. }
  28163. const String VSTPluginInstance::getParameterText (int index)
  28164. {
  28165. if (effect != 0)
  28166. {
  28167. jassert (index >= 0 && index < effect->numParams);
  28168. char nm [256];
  28169. zerostruct (nm);
  28170. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28171. return String (nm).trim();
  28172. }
  28173. return String::empty;
  28174. }
  28175. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28176. {
  28177. if (effect != 0)
  28178. {
  28179. jassert (index >= 0 && index < effect->numParams);
  28180. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28181. }
  28182. return false;
  28183. }
  28184. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28185. {
  28186. dest.setSize (64 + 4 * getNumParameters());
  28187. dest.fillWith (0);
  28188. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28189. float* const p = (float*) (((char*) dest.getData()) + 64);
  28190. for (int i = 0; i < getNumParameters(); ++i)
  28191. p[i] = getParameter(i);
  28192. }
  28193. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28194. {
  28195. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28196. float* p = (float*) (((char*) m.getData()) + 64);
  28197. for (int i = 0; i < getNumParameters(); ++i)
  28198. setParameter (i, p[i]);
  28199. }
  28200. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28201. {
  28202. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28203. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28204. }
  28205. const String VSTPluginInstance::getProgramName (int index)
  28206. {
  28207. if (index == getCurrentProgram())
  28208. {
  28209. return getCurrentProgramName();
  28210. }
  28211. else if (effect != 0)
  28212. {
  28213. char nm [256];
  28214. zerostruct (nm);
  28215. if (dispatch (effGetProgramNameIndexed,
  28216. jlimit (0, getNumPrograms(), index),
  28217. -1, nm, 0) != 0)
  28218. {
  28219. return String (nm).trim();
  28220. }
  28221. }
  28222. return programNames [index];
  28223. }
  28224. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28225. {
  28226. if (index == getCurrentProgram())
  28227. {
  28228. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28229. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28230. }
  28231. else
  28232. {
  28233. jassertfalse; // xxx not implemented!
  28234. }
  28235. }
  28236. void VSTPluginInstance::updateStoredProgramNames()
  28237. {
  28238. if (effect != 0 && getNumPrograms() > 0)
  28239. {
  28240. char nm [256];
  28241. zerostruct (nm);
  28242. // only do this if the plugin can't use indexed names..
  28243. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28244. {
  28245. const int oldProgram = getCurrentProgram();
  28246. MemoryBlock oldSettings;
  28247. createTempParameterStore (oldSettings);
  28248. for (int i = 0; i < getNumPrograms(); ++i)
  28249. {
  28250. setCurrentProgram (i);
  28251. getCurrentProgramName(); // (this updates the list)
  28252. }
  28253. setCurrentProgram (oldProgram);
  28254. restoreFromTempParameterStore (oldSettings);
  28255. }
  28256. }
  28257. }
  28258. const String VSTPluginInstance::getCurrentProgramName()
  28259. {
  28260. if (effect != 0)
  28261. {
  28262. char nm [256];
  28263. zerostruct (nm);
  28264. dispatch (effGetProgramName, 0, 0, nm, 0);
  28265. const int index = getCurrentProgram();
  28266. if (programNames[index].isEmpty())
  28267. {
  28268. while (programNames.size() < index)
  28269. programNames.add (String::empty);
  28270. programNames.set (index, String (nm).trim());
  28271. }
  28272. return String (nm).trim();
  28273. }
  28274. return String::empty;
  28275. }
  28276. const String VSTPluginInstance::getInputChannelName (int index) const
  28277. {
  28278. if (index >= 0 && index < getNumInputChannels())
  28279. {
  28280. VstPinProperties pinProps;
  28281. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28282. return String (pinProps.label, sizeof (pinProps.label));
  28283. }
  28284. return String::empty;
  28285. }
  28286. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28287. {
  28288. if (index < 0 || index >= getNumInputChannels())
  28289. return false;
  28290. VstPinProperties pinProps;
  28291. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28292. return (pinProps.flags & kVstPinIsStereo) != 0;
  28293. return true;
  28294. }
  28295. const String VSTPluginInstance::getOutputChannelName (int index) const
  28296. {
  28297. if (index >= 0 && index < getNumOutputChannels())
  28298. {
  28299. VstPinProperties pinProps;
  28300. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28301. return String (pinProps.label, sizeof (pinProps.label));
  28302. }
  28303. return String::empty;
  28304. }
  28305. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28306. {
  28307. if (index < 0 || index >= getNumOutputChannels())
  28308. return false;
  28309. VstPinProperties pinProps;
  28310. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28311. return (pinProps.flags & kVstPinIsStereo) != 0;
  28312. return true;
  28313. }
  28314. void VSTPluginInstance::setPower (const bool on)
  28315. {
  28316. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28317. isPowerOn = on;
  28318. }
  28319. const int defaultMaxSizeMB = 64;
  28320. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28321. {
  28322. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28323. }
  28324. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28325. {
  28326. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28327. }
  28328. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28329. {
  28330. loadFromFXBFile (data, sizeInBytes);
  28331. }
  28332. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28333. {
  28334. loadFromFXBFile (data, sizeInBytes);
  28335. }
  28336. VSTPluginFormat::VSTPluginFormat()
  28337. {
  28338. }
  28339. VSTPluginFormat::~VSTPluginFormat()
  28340. {
  28341. }
  28342. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28343. const String& fileOrIdentifier)
  28344. {
  28345. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28346. return;
  28347. PluginDescription desc;
  28348. desc.fileOrIdentifier = fileOrIdentifier;
  28349. desc.uid = 0;
  28350. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28351. if (instance == 0)
  28352. return;
  28353. try
  28354. {
  28355. #if JUCE_MAC
  28356. if (instance->module->resFileId != 0)
  28357. UseResFile (instance->module->resFileId);
  28358. #endif
  28359. instance->fillInPluginDescription (desc);
  28360. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28361. if (category != kPlugCategShell)
  28362. {
  28363. // Normal plugin...
  28364. results.add (new PluginDescription (desc));
  28365. ++insideVSTCallback;
  28366. instance->dispatch (effOpen, 0, 0, 0, 0);
  28367. --insideVSTCallback;
  28368. }
  28369. else
  28370. {
  28371. // It's a shell plugin, so iterate all the subtypes...
  28372. char shellEffectName [64];
  28373. for (;;)
  28374. {
  28375. zerostruct (shellEffectName);
  28376. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28377. if (uid == 0)
  28378. {
  28379. break;
  28380. }
  28381. else
  28382. {
  28383. desc.uid = uid;
  28384. desc.name = shellEffectName;
  28385. desc.descriptiveName = shellEffectName;
  28386. bool alreadyThere = false;
  28387. for (int i = results.size(); --i >= 0;)
  28388. {
  28389. PluginDescription* const d = results.getUnchecked(i);
  28390. if (d->isDuplicateOf (desc))
  28391. {
  28392. alreadyThere = true;
  28393. break;
  28394. }
  28395. }
  28396. if (! alreadyThere)
  28397. results.add (new PluginDescription (desc));
  28398. }
  28399. }
  28400. }
  28401. }
  28402. catch (...)
  28403. {
  28404. // crashed while loading...
  28405. }
  28406. }
  28407. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28408. {
  28409. ScopedPointer <VSTPluginInstance> result;
  28410. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28411. {
  28412. File file (desc.fileOrIdentifier);
  28413. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28414. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28415. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28416. if (module != 0)
  28417. {
  28418. shellUIDToCreate = desc.uid;
  28419. result = new VSTPluginInstance (module);
  28420. if (result->effect != 0)
  28421. {
  28422. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28423. result->initialise();
  28424. }
  28425. else
  28426. {
  28427. result = 0;
  28428. }
  28429. }
  28430. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28431. }
  28432. return result.release();
  28433. }
  28434. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28435. {
  28436. const File f (fileOrIdentifier);
  28437. #if JUCE_MAC
  28438. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28439. return true;
  28440. #if JUCE_PPC
  28441. FSRef fileRef;
  28442. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28443. {
  28444. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28445. if (resFileId != -1)
  28446. {
  28447. const int numEffects = Count1Resources ('aEff');
  28448. CloseResFile (resFileId);
  28449. if (numEffects > 0)
  28450. return true;
  28451. }
  28452. }
  28453. #endif
  28454. return false;
  28455. #elif JUCE_WINDOWS
  28456. return f.existsAsFile() && f.hasFileExtension (".dll");
  28457. #elif JUCE_LINUX
  28458. return f.existsAsFile() && f.hasFileExtension (".so");
  28459. #endif
  28460. }
  28461. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28462. {
  28463. return fileOrIdentifier;
  28464. }
  28465. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28466. {
  28467. return File (desc.fileOrIdentifier).exists();
  28468. }
  28469. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28470. {
  28471. StringArray results;
  28472. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28473. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28474. return results;
  28475. }
  28476. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28477. {
  28478. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28479. // .component or .vst directories.
  28480. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28481. while (iter.next())
  28482. {
  28483. const File f (iter.getFile());
  28484. bool isPlugin = false;
  28485. if (fileMightContainThisPluginType (f.getFullPathName()))
  28486. {
  28487. isPlugin = true;
  28488. results.add (f.getFullPathName());
  28489. }
  28490. if (recursive && (! isPlugin) && f.isDirectory())
  28491. recursiveFileSearch (results, f, true);
  28492. }
  28493. }
  28494. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28495. {
  28496. #if JUCE_MAC
  28497. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28498. #elif JUCE_WINDOWS
  28499. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28500. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28501. #elif JUCE_LINUX
  28502. return FileSearchPath ("/usr/lib/vst");
  28503. #endif
  28504. }
  28505. END_JUCE_NAMESPACE
  28506. #endif
  28507. #undef log
  28508. #endif
  28509. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28510. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28511. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28512. BEGIN_JUCE_NAMESPACE
  28513. AudioProcessor::AudioProcessor()
  28514. : playHead (0),
  28515. sampleRate (0),
  28516. blockSize (0),
  28517. numInputChannels (0),
  28518. numOutputChannels (0),
  28519. latencySamples (0),
  28520. suspended (false),
  28521. nonRealtime (false)
  28522. {
  28523. }
  28524. AudioProcessor::~AudioProcessor()
  28525. {
  28526. // ooh, nasty - the editor should have been deleted before the filter
  28527. // that it refers to is deleted..
  28528. jassert (activeEditor == 0);
  28529. #if JUCE_DEBUG
  28530. // This will fail if you've called beginParameterChangeGesture() for one
  28531. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28532. jassert (changingParams.countNumberOfSetBits() == 0);
  28533. #endif
  28534. }
  28535. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28536. {
  28537. playHead = newPlayHead;
  28538. }
  28539. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28540. {
  28541. const ScopedLock sl (listenerLock);
  28542. listeners.addIfNotAlreadyThere (newListener);
  28543. }
  28544. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28545. {
  28546. const ScopedLock sl (listenerLock);
  28547. listeners.removeValue (listenerToRemove);
  28548. }
  28549. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28550. const int numOuts,
  28551. const double sampleRate_,
  28552. const int blockSize_) throw()
  28553. {
  28554. numInputChannels = numIns;
  28555. numOutputChannels = numOuts;
  28556. sampleRate = sampleRate_;
  28557. blockSize = blockSize_;
  28558. }
  28559. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28560. {
  28561. nonRealtime = nonRealtime_;
  28562. }
  28563. void AudioProcessor::setLatencySamples (const int newLatency)
  28564. {
  28565. if (latencySamples != newLatency)
  28566. {
  28567. latencySamples = newLatency;
  28568. updateHostDisplay();
  28569. }
  28570. }
  28571. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28572. const float newValue)
  28573. {
  28574. setParameter (parameterIndex, newValue);
  28575. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28576. }
  28577. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28578. {
  28579. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28580. for (int i = listeners.size(); --i >= 0;)
  28581. {
  28582. AudioProcessorListener* l;
  28583. {
  28584. const ScopedLock sl (listenerLock);
  28585. l = listeners [i];
  28586. }
  28587. if (l != 0)
  28588. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28589. }
  28590. }
  28591. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28592. {
  28593. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28594. #if JUCE_DEBUG
  28595. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28596. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28597. jassert (! changingParams [parameterIndex]);
  28598. changingParams.setBit (parameterIndex);
  28599. #endif
  28600. for (int i = listeners.size(); --i >= 0;)
  28601. {
  28602. AudioProcessorListener* l;
  28603. {
  28604. const ScopedLock sl (listenerLock);
  28605. l = listeners [i];
  28606. }
  28607. if (l != 0)
  28608. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28609. }
  28610. }
  28611. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28612. {
  28613. jassert (isPositiveAndBelow (parameterIndex, getNumParameters()));
  28614. #if JUCE_DEBUG
  28615. // This means you've called endParameterChangeGesture without having previously called
  28616. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28617. // calls matched correctly.
  28618. jassert (changingParams [parameterIndex]);
  28619. changingParams.clearBit (parameterIndex);
  28620. #endif
  28621. for (int i = listeners.size(); --i >= 0;)
  28622. {
  28623. AudioProcessorListener* l;
  28624. {
  28625. const ScopedLock sl (listenerLock);
  28626. l = listeners [i];
  28627. }
  28628. if (l != 0)
  28629. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28630. }
  28631. }
  28632. void AudioProcessor::updateHostDisplay()
  28633. {
  28634. for (int i = listeners.size(); --i >= 0;)
  28635. {
  28636. AudioProcessorListener* l;
  28637. {
  28638. const ScopedLock sl (listenerLock);
  28639. l = listeners [i];
  28640. }
  28641. if (l != 0)
  28642. l->audioProcessorChanged (this);
  28643. }
  28644. }
  28645. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28646. {
  28647. return true;
  28648. }
  28649. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28650. {
  28651. return false;
  28652. }
  28653. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28654. {
  28655. const ScopedLock sl (callbackLock);
  28656. suspended = shouldBeSuspended;
  28657. }
  28658. void AudioProcessor::reset()
  28659. {
  28660. }
  28661. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28662. {
  28663. const ScopedLock sl (callbackLock);
  28664. if (activeEditor == editor)
  28665. activeEditor = 0;
  28666. }
  28667. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28668. {
  28669. if (activeEditor != 0)
  28670. return activeEditor;
  28671. AudioProcessorEditor* const ed = createEditor();
  28672. // You must make your hasEditor() method return a consistent result!
  28673. jassert (hasEditor() == (ed != 0));
  28674. if (ed != 0)
  28675. {
  28676. // you must give your editor comp a size before returning it..
  28677. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28678. const ScopedLock sl (callbackLock);
  28679. activeEditor = ed;
  28680. }
  28681. return ed;
  28682. }
  28683. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28684. {
  28685. getStateInformation (destData);
  28686. }
  28687. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28688. {
  28689. setStateInformation (data, sizeInBytes);
  28690. }
  28691. // magic number to identify memory blocks that we've stored as XML
  28692. const uint32 magicXmlNumber = 0x21324356;
  28693. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28694. JUCE_NAMESPACE::MemoryBlock& destData)
  28695. {
  28696. const String xmlString (xml.createDocument (String::empty, true, false));
  28697. const int stringLength = xmlString.getNumBytesAsUTF8();
  28698. destData.setSize (stringLength + 10);
  28699. char* const d = static_cast<char*> (destData.getData());
  28700. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28701. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28702. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28703. }
  28704. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28705. const int sizeInBytes)
  28706. {
  28707. if (sizeInBytes > 8
  28708. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28709. {
  28710. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28711. if (stringLength > 0)
  28712. return XmlDocument::parse (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28713. jmin ((sizeInBytes - 8), stringLength)));
  28714. }
  28715. return 0;
  28716. }
  28717. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28718. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28719. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28720. {
  28721. return timeInSeconds == other.timeInSeconds
  28722. && ppqPosition == other.ppqPosition
  28723. && editOriginTime == other.editOriginTime
  28724. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28725. && frameRate == other.frameRate
  28726. && isPlaying == other.isPlaying
  28727. && isRecording == other.isRecording
  28728. && bpm == other.bpm
  28729. && timeSigNumerator == other.timeSigNumerator
  28730. && timeSigDenominator == other.timeSigDenominator;
  28731. }
  28732. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28733. {
  28734. return ! operator== (other);
  28735. }
  28736. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28737. {
  28738. zerostruct (*this);
  28739. timeSigNumerator = 4;
  28740. timeSigDenominator = 4;
  28741. bpm = 120;
  28742. }
  28743. END_JUCE_NAMESPACE
  28744. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28745. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28746. BEGIN_JUCE_NAMESPACE
  28747. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28748. : owner (owner_)
  28749. {
  28750. // the filter must be valid..
  28751. jassert (owner != 0);
  28752. }
  28753. AudioProcessorEditor::~AudioProcessorEditor()
  28754. {
  28755. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28756. // filter for some reason..
  28757. jassert (owner->getActiveEditor() != this);
  28758. }
  28759. END_JUCE_NAMESPACE
  28760. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28761. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28762. BEGIN_JUCE_NAMESPACE
  28763. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28764. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28765. : id (id_),
  28766. processor (processor_),
  28767. isPrepared (false)
  28768. {
  28769. jassert (processor_ != 0);
  28770. }
  28771. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28772. AudioProcessorGraph* const graph)
  28773. {
  28774. if (! isPrepared)
  28775. {
  28776. isPrepared = true;
  28777. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28778. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28779. if (ioProc != 0)
  28780. ioProc->setParentGraph (graph);
  28781. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28782. processor->getNumOutputChannels(),
  28783. sampleRate, blockSize);
  28784. processor->prepareToPlay (sampleRate, blockSize);
  28785. }
  28786. }
  28787. void AudioProcessorGraph::Node::unprepare()
  28788. {
  28789. if (isPrepared)
  28790. {
  28791. isPrepared = false;
  28792. processor->releaseResources();
  28793. }
  28794. }
  28795. AudioProcessorGraph::AudioProcessorGraph()
  28796. : lastNodeId (0),
  28797. renderingBuffers (1, 1),
  28798. currentAudioOutputBuffer (1, 1)
  28799. {
  28800. }
  28801. AudioProcessorGraph::~AudioProcessorGraph()
  28802. {
  28803. clearRenderingSequence();
  28804. clear();
  28805. }
  28806. const String AudioProcessorGraph::getName() const
  28807. {
  28808. return "Audio Graph";
  28809. }
  28810. void AudioProcessorGraph::clear()
  28811. {
  28812. nodes.clear();
  28813. connections.clear();
  28814. triggerAsyncUpdate();
  28815. }
  28816. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28817. {
  28818. for (int i = nodes.size(); --i >= 0;)
  28819. if (nodes.getUnchecked(i)->id == nodeId)
  28820. return nodes.getUnchecked(i);
  28821. return 0;
  28822. }
  28823. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28824. uint32 nodeId)
  28825. {
  28826. if (newProcessor == 0)
  28827. {
  28828. jassertfalse;
  28829. return 0;
  28830. }
  28831. if (nodeId == 0)
  28832. {
  28833. nodeId = ++lastNodeId;
  28834. }
  28835. else
  28836. {
  28837. // you can't add a node with an id that already exists in the graph..
  28838. jassert (getNodeForId (nodeId) == 0);
  28839. removeNode (nodeId);
  28840. }
  28841. lastNodeId = nodeId;
  28842. Node* const n = new Node (nodeId, newProcessor);
  28843. nodes.add (n);
  28844. triggerAsyncUpdate();
  28845. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28846. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  28847. if (ioProc != 0)
  28848. ioProc->setParentGraph (this);
  28849. return n;
  28850. }
  28851. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  28852. {
  28853. disconnectNode (nodeId);
  28854. for (int i = nodes.size(); --i >= 0;)
  28855. {
  28856. if (nodes.getUnchecked(i)->id == nodeId)
  28857. {
  28858. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28859. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  28860. if (ioProc != 0)
  28861. ioProc->setParentGraph (0);
  28862. nodes.remove (i);
  28863. triggerAsyncUpdate();
  28864. return true;
  28865. }
  28866. }
  28867. return false;
  28868. }
  28869. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  28870. const int sourceChannelIndex,
  28871. const uint32 destNodeId,
  28872. const int destChannelIndex) const
  28873. {
  28874. for (int i = connections.size(); --i >= 0;)
  28875. {
  28876. const Connection* const c = connections.getUnchecked(i);
  28877. if (c->sourceNodeId == sourceNodeId
  28878. && c->destNodeId == destNodeId
  28879. && c->sourceChannelIndex == sourceChannelIndex
  28880. && c->destChannelIndex == destChannelIndex)
  28881. {
  28882. return c;
  28883. }
  28884. }
  28885. return 0;
  28886. }
  28887. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  28888. const uint32 possibleDestNodeId) const
  28889. {
  28890. for (int i = connections.size(); --i >= 0;)
  28891. {
  28892. const Connection* const c = connections.getUnchecked(i);
  28893. if (c->sourceNodeId == possibleSourceNodeId
  28894. && c->destNodeId == possibleDestNodeId)
  28895. {
  28896. return true;
  28897. }
  28898. }
  28899. return false;
  28900. }
  28901. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  28902. const int sourceChannelIndex,
  28903. const uint32 destNodeId,
  28904. const int destChannelIndex) const
  28905. {
  28906. if (sourceChannelIndex < 0
  28907. || destChannelIndex < 0
  28908. || sourceNodeId == destNodeId
  28909. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  28910. return false;
  28911. const Node* const source = getNodeForId (sourceNodeId);
  28912. if (source == 0
  28913. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  28914. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  28915. return false;
  28916. const Node* const dest = getNodeForId (destNodeId);
  28917. if (dest == 0
  28918. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  28919. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  28920. return false;
  28921. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  28922. destNodeId, destChannelIndex) == 0;
  28923. }
  28924. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  28925. const int sourceChannelIndex,
  28926. const uint32 destNodeId,
  28927. const int destChannelIndex)
  28928. {
  28929. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  28930. return false;
  28931. Connection* const c = new Connection();
  28932. c->sourceNodeId = sourceNodeId;
  28933. c->sourceChannelIndex = sourceChannelIndex;
  28934. c->destNodeId = destNodeId;
  28935. c->destChannelIndex = destChannelIndex;
  28936. connections.add (c);
  28937. triggerAsyncUpdate();
  28938. return true;
  28939. }
  28940. void AudioProcessorGraph::removeConnection (const int index)
  28941. {
  28942. connections.remove (index);
  28943. triggerAsyncUpdate();
  28944. }
  28945. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  28946. const uint32 destNodeId, const int destChannelIndex)
  28947. {
  28948. bool doneAnything = false;
  28949. for (int i = connections.size(); --i >= 0;)
  28950. {
  28951. const Connection* const c = connections.getUnchecked(i);
  28952. if (c->sourceNodeId == sourceNodeId
  28953. && c->destNodeId == destNodeId
  28954. && c->sourceChannelIndex == sourceChannelIndex
  28955. && c->destChannelIndex == destChannelIndex)
  28956. {
  28957. removeConnection (i);
  28958. doneAnything = true;
  28959. triggerAsyncUpdate();
  28960. }
  28961. }
  28962. return doneAnything;
  28963. }
  28964. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  28965. {
  28966. bool doneAnything = false;
  28967. for (int i = connections.size(); --i >= 0;)
  28968. {
  28969. const Connection* const c = connections.getUnchecked(i);
  28970. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  28971. {
  28972. removeConnection (i);
  28973. doneAnything = true;
  28974. triggerAsyncUpdate();
  28975. }
  28976. }
  28977. return doneAnything;
  28978. }
  28979. bool AudioProcessorGraph::removeIllegalConnections()
  28980. {
  28981. bool doneAnything = false;
  28982. for (int i = connections.size(); --i >= 0;)
  28983. {
  28984. const Connection* const c = connections.getUnchecked(i);
  28985. const Node* const source = getNodeForId (c->sourceNodeId);
  28986. const Node* const dest = getNodeForId (c->destNodeId);
  28987. if (source == 0 || dest == 0
  28988. || (c->sourceChannelIndex != midiChannelIndex
  28989. && ! isPositiveAndBelow (c->sourceChannelIndex, source->processor->getNumOutputChannels()))
  28990. || (c->sourceChannelIndex == midiChannelIndex
  28991. && ! source->processor->producesMidi())
  28992. || (c->destChannelIndex != midiChannelIndex
  28993. && ! isPositiveAndBelow (c->destChannelIndex, dest->processor->getNumInputChannels()))
  28994. || (c->destChannelIndex == midiChannelIndex
  28995. && ! dest->processor->acceptsMidi()))
  28996. {
  28997. removeConnection (i);
  28998. doneAnything = true;
  28999. triggerAsyncUpdate();
  29000. }
  29001. }
  29002. return doneAnything;
  29003. }
  29004. namespace GraphRenderingOps
  29005. {
  29006. class AudioGraphRenderingOp
  29007. {
  29008. public:
  29009. AudioGraphRenderingOp() {}
  29010. virtual ~AudioGraphRenderingOp() {}
  29011. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29012. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29013. const int numSamples) = 0;
  29014. JUCE_LEAK_DETECTOR (AudioGraphRenderingOp);
  29015. };
  29016. class ClearChannelOp : public AudioGraphRenderingOp
  29017. {
  29018. public:
  29019. ClearChannelOp (const int channelNum_)
  29020. : channelNum (channelNum_)
  29021. {}
  29022. ~ClearChannelOp() {}
  29023. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29024. {
  29025. sharedBufferChans.clear (channelNum, 0, numSamples);
  29026. }
  29027. private:
  29028. const int channelNum;
  29029. JUCE_DECLARE_NON_COPYABLE (ClearChannelOp);
  29030. };
  29031. class CopyChannelOp : public AudioGraphRenderingOp
  29032. {
  29033. public:
  29034. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29035. : srcChannelNum (srcChannelNum_),
  29036. dstChannelNum (dstChannelNum_)
  29037. {}
  29038. ~CopyChannelOp() {}
  29039. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29040. {
  29041. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29042. }
  29043. private:
  29044. const int srcChannelNum, dstChannelNum;
  29045. JUCE_DECLARE_NON_COPYABLE (CopyChannelOp);
  29046. };
  29047. class AddChannelOp : public AudioGraphRenderingOp
  29048. {
  29049. public:
  29050. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29051. : srcChannelNum (srcChannelNum_),
  29052. dstChannelNum (dstChannelNum_)
  29053. {}
  29054. ~AddChannelOp() {}
  29055. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29056. {
  29057. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29058. }
  29059. private:
  29060. const int srcChannelNum, dstChannelNum;
  29061. JUCE_DECLARE_NON_COPYABLE (AddChannelOp);
  29062. };
  29063. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29064. {
  29065. public:
  29066. ClearMidiBufferOp (const int bufferNum_)
  29067. : bufferNum (bufferNum_)
  29068. {}
  29069. ~ClearMidiBufferOp() {}
  29070. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29071. {
  29072. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29073. }
  29074. private:
  29075. const int bufferNum;
  29076. JUCE_DECLARE_NON_COPYABLE (ClearMidiBufferOp);
  29077. };
  29078. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29079. {
  29080. public:
  29081. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29082. : srcBufferNum (srcBufferNum_),
  29083. dstBufferNum (dstBufferNum_)
  29084. {}
  29085. ~CopyMidiBufferOp() {}
  29086. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29087. {
  29088. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29089. }
  29090. private:
  29091. const int srcBufferNum, dstBufferNum;
  29092. JUCE_DECLARE_NON_COPYABLE (CopyMidiBufferOp);
  29093. };
  29094. class AddMidiBufferOp : public AudioGraphRenderingOp
  29095. {
  29096. public:
  29097. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29098. : srcBufferNum (srcBufferNum_),
  29099. dstBufferNum (dstBufferNum_)
  29100. {}
  29101. ~AddMidiBufferOp() {}
  29102. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29103. {
  29104. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29105. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29106. }
  29107. private:
  29108. const int srcBufferNum, dstBufferNum;
  29109. JUCE_DECLARE_NON_COPYABLE (AddMidiBufferOp);
  29110. };
  29111. class ProcessBufferOp : public AudioGraphRenderingOp
  29112. {
  29113. public:
  29114. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29115. const Array <int>& audioChannelsToUse_,
  29116. const int totalChans_,
  29117. const int midiBufferToUse_)
  29118. : node (node_),
  29119. processor (node_->getProcessor()),
  29120. audioChannelsToUse (audioChannelsToUse_),
  29121. totalChans (jmax (1, totalChans_)),
  29122. midiBufferToUse (midiBufferToUse_)
  29123. {
  29124. channels.calloc (totalChans);
  29125. while (audioChannelsToUse.size() < totalChans)
  29126. audioChannelsToUse.add (0);
  29127. }
  29128. ~ProcessBufferOp()
  29129. {
  29130. }
  29131. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29132. {
  29133. for (int i = totalChans; --i >= 0;)
  29134. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29135. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29136. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29137. }
  29138. const AudioProcessorGraph::Node::Ptr node;
  29139. AudioProcessor* const processor;
  29140. private:
  29141. Array <int> audioChannelsToUse;
  29142. HeapBlock <float*> channels;
  29143. int totalChans;
  29144. int midiBufferToUse;
  29145. JUCE_DECLARE_NON_COPYABLE (ProcessBufferOp);
  29146. };
  29147. /** Used to calculate the correct sequence of rendering ops needed, based on
  29148. the best re-use of shared buffers at each stage.
  29149. */
  29150. class RenderingOpSequenceCalculator
  29151. {
  29152. public:
  29153. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29154. const Array<void*>& orderedNodes_,
  29155. Array<void*>& renderingOps)
  29156. : graph (graph_),
  29157. orderedNodes (orderedNodes_)
  29158. {
  29159. nodeIds.add ((uint32) zeroNodeID); // first buffer is read-only zeros
  29160. channels.add (0);
  29161. midiNodeIds.add ((uint32) zeroNodeID);
  29162. for (int i = 0; i < orderedNodes.size(); ++i)
  29163. {
  29164. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29165. renderingOps, i);
  29166. markAnyUnusedBuffersAsFree (i);
  29167. }
  29168. }
  29169. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29170. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29171. private:
  29172. AudioProcessorGraph& graph;
  29173. const Array<void*>& orderedNodes;
  29174. Array <int> channels;
  29175. Array <uint32> nodeIds, midiNodeIds;
  29176. enum { freeNodeID = 0xffffffff, zeroNodeID = 0xfffffffe };
  29177. static bool isNodeBusy (uint32 nodeID) throw() { return nodeID != freeNodeID && nodeID != zeroNodeID; }
  29178. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29179. Array<void*>& renderingOps,
  29180. const int ourRenderingIndex)
  29181. {
  29182. const int numIns = node->getProcessor()->getNumInputChannels();
  29183. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29184. const int totalChans = jmax (numIns, numOuts);
  29185. Array <int> audioChannelsToUse;
  29186. int midiBufferToUse = -1;
  29187. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29188. {
  29189. // get a list of all the inputs to this node
  29190. Array <int> sourceNodes, sourceOutputChans;
  29191. for (int i = graph.getNumConnections(); --i >= 0;)
  29192. {
  29193. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29194. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29195. {
  29196. sourceNodes.add (c->sourceNodeId);
  29197. sourceOutputChans.add (c->sourceChannelIndex);
  29198. }
  29199. }
  29200. int bufIndex = -1;
  29201. if (sourceNodes.size() == 0)
  29202. {
  29203. // unconnected input channel
  29204. if (inputChan >= numOuts)
  29205. {
  29206. bufIndex = getReadOnlyEmptyBuffer();
  29207. jassert (bufIndex >= 0);
  29208. }
  29209. else
  29210. {
  29211. bufIndex = getFreeBuffer (false);
  29212. renderingOps.add (new ClearChannelOp (bufIndex));
  29213. }
  29214. }
  29215. else if (sourceNodes.size() == 1)
  29216. {
  29217. // channel with a straightforward single input..
  29218. const int srcNode = sourceNodes.getUnchecked(0);
  29219. const int srcChan = sourceOutputChans.getUnchecked(0);
  29220. bufIndex = getBufferContaining (srcNode, srcChan);
  29221. if (bufIndex < 0)
  29222. {
  29223. // if not found, this is probably a feedback loop
  29224. bufIndex = getReadOnlyEmptyBuffer();
  29225. jassert (bufIndex >= 0);
  29226. }
  29227. if (inputChan < numOuts
  29228. && isBufferNeededLater (ourRenderingIndex,
  29229. inputChan,
  29230. srcNode, srcChan))
  29231. {
  29232. // can't mess up this channel because it's needed later by another node, so we
  29233. // need to use a copy of it..
  29234. const int newFreeBuffer = getFreeBuffer (false);
  29235. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29236. bufIndex = newFreeBuffer;
  29237. }
  29238. }
  29239. else
  29240. {
  29241. // channel with a mix of several inputs..
  29242. // try to find a re-usable channel from our inputs..
  29243. int reusableInputIndex = -1;
  29244. for (int i = 0; i < sourceNodes.size(); ++i)
  29245. {
  29246. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29247. sourceOutputChans.getUnchecked(i));
  29248. if (sourceBufIndex >= 0
  29249. && ! isBufferNeededLater (ourRenderingIndex,
  29250. inputChan,
  29251. sourceNodes.getUnchecked(i),
  29252. sourceOutputChans.getUnchecked(i)))
  29253. {
  29254. // we've found one of our input chans that can be re-used..
  29255. reusableInputIndex = i;
  29256. bufIndex = sourceBufIndex;
  29257. break;
  29258. }
  29259. }
  29260. if (reusableInputIndex < 0)
  29261. {
  29262. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29263. bufIndex = getFreeBuffer (false);
  29264. jassert (bufIndex != 0);
  29265. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29266. sourceOutputChans.getUnchecked (0));
  29267. if (srcIndex < 0)
  29268. {
  29269. // if not found, this is probably a feedback loop
  29270. renderingOps.add (new ClearChannelOp (bufIndex));
  29271. }
  29272. else
  29273. {
  29274. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29275. }
  29276. reusableInputIndex = 0;
  29277. }
  29278. for (int j = 0; j < sourceNodes.size(); ++j)
  29279. {
  29280. if (j != reusableInputIndex)
  29281. {
  29282. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29283. sourceOutputChans.getUnchecked(j));
  29284. if (srcIndex >= 0)
  29285. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29286. }
  29287. }
  29288. }
  29289. jassert (bufIndex >= 0);
  29290. audioChannelsToUse.add (bufIndex);
  29291. if (inputChan < numOuts)
  29292. markBufferAsContaining (bufIndex, node->id, inputChan);
  29293. }
  29294. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29295. {
  29296. const int bufIndex = getFreeBuffer (false);
  29297. jassert (bufIndex != 0);
  29298. audioChannelsToUse.add (bufIndex);
  29299. markBufferAsContaining (bufIndex, node->id, outputChan);
  29300. }
  29301. // Now the same thing for midi..
  29302. Array <int> midiSourceNodes;
  29303. for (int i = graph.getNumConnections(); --i >= 0;)
  29304. {
  29305. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29306. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29307. midiSourceNodes.add (c->sourceNodeId);
  29308. }
  29309. if (midiSourceNodes.size() == 0)
  29310. {
  29311. // No midi inputs..
  29312. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29313. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29314. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29315. }
  29316. else if (midiSourceNodes.size() == 1)
  29317. {
  29318. // One midi input..
  29319. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29320. AudioProcessorGraph::midiChannelIndex);
  29321. if (midiBufferToUse >= 0)
  29322. {
  29323. if (isBufferNeededLater (ourRenderingIndex,
  29324. AudioProcessorGraph::midiChannelIndex,
  29325. midiSourceNodes.getUnchecked(0),
  29326. AudioProcessorGraph::midiChannelIndex))
  29327. {
  29328. // can't mess up this channel because it's needed later by another node, so we
  29329. // need to use a copy of it..
  29330. const int newFreeBuffer = getFreeBuffer (true);
  29331. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29332. midiBufferToUse = newFreeBuffer;
  29333. }
  29334. }
  29335. else
  29336. {
  29337. // probably a feedback loop, so just use an empty one..
  29338. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29339. }
  29340. }
  29341. else
  29342. {
  29343. // More than one midi input being mixed..
  29344. int reusableInputIndex = -1;
  29345. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29346. {
  29347. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29348. AudioProcessorGraph::midiChannelIndex);
  29349. if (sourceBufIndex >= 0
  29350. && ! isBufferNeededLater (ourRenderingIndex,
  29351. AudioProcessorGraph::midiChannelIndex,
  29352. midiSourceNodes.getUnchecked(i),
  29353. AudioProcessorGraph::midiChannelIndex))
  29354. {
  29355. // we've found one of our input buffers that can be re-used..
  29356. reusableInputIndex = i;
  29357. midiBufferToUse = sourceBufIndex;
  29358. break;
  29359. }
  29360. }
  29361. if (reusableInputIndex < 0)
  29362. {
  29363. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29364. midiBufferToUse = getFreeBuffer (true);
  29365. jassert (midiBufferToUse >= 0);
  29366. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29367. AudioProcessorGraph::midiChannelIndex);
  29368. if (srcIndex >= 0)
  29369. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29370. else
  29371. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29372. reusableInputIndex = 0;
  29373. }
  29374. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29375. {
  29376. if (j != reusableInputIndex)
  29377. {
  29378. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29379. AudioProcessorGraph::midiChannelIndex);
  29380. if (srcIndex >= 0)
  29381. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29382. }
  29383. }
  29384. }
  29385. if (node->getProcessor()->producesMidi())
  29386. markBufferAsContaining (midiBufferToUse, node->id,
  29387. AudioProcessorGraph::midiChannelIndex);
  29388. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29389. totalChans, midiBufferToUse));
  29390. }
  29391. int getFreeBuffer (const bool forMidi)
  29392. {
  29393. if (forMidi)
  29394. {
  29395. for (int i = 1; i < midiNodeIds.size(); ++i)
  29396. if (midiNodeIds.getUnchecked(i) == freeNodeID)
  29397. return i;
  29398. midiNodeIds.add ((uint32) freeNodeID);
  29399. return midiNodeIds.size() - 1;
  29400. }
  29401. else
  29402. {
  29403. for (int i = 1; i < nodeIds.size(); ++i)
  29404. if (nodeIds.getUnchecked(i) == freeNodeID)
  29405. return i;
  29406. nodeIds.add ((uint32) freeNodeID);
  29407. channels.add (0);
  29408. return nodeIds.size() - 1;
  29409. }
  29410. }
  29411. int getReadOnlyEmptyBuffer() const
  29412. {
  29413. return 0;
  29414. }
  29415. int getBufferContaining (const uint32 nodeId, const int outputChannel) const
  29416. {
  29417. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29418. {
  29419. for (int i = midiNodeIds.size(); --i >= 0;)
  29420. if (midiNodeIds.getUnchecked(i) == nodeId)
  29421. return i;
  29422. }
  29423. else
  29424. {
  29425. for (int i = nodeIds.size(); --i >= 0;)
  29426. if (nodeIds.getUnchecked(i) == nodeId
  29427. && channels.getUnchecked(i) == outputChannel)
  29428. return i;
  29429. }
  29430. return -1;
  29431. }
  29432. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29433. {
  29434. int i;
  29435. for (i = 0; i < nodeIds.size(); ++i)
  29436. {
  29437. if (isNodeBusy (nodeIds.getUnchecked(i))
  29438. && ! isBufferNeededLater (stepIndex, -1,
  29439. nodeIds.getUnchecked(i),
  29440. channels.getUnchecked(i)))
  29441. {
  29442. nodeIds.set (i, (uint32) freeNodeID);
  29443. }
  29444. }
  29445. for (i = 0; i < midiNodeIds.size(); ++i)
  29446. {
  29447. if (isNodeBusy (midiNodeIds.getUnchecked(i))
  29448. && ! isBufferNeededLater (stepIndex, -1,
  29449. midiNodeIds.getUnchecked(i),
  29450. AudioProcessorGraph::midiChannelIndex))
  29451. {
  29452. midiNodeIds.set (i, (uint32) freeNodeID);
  29453. }
  29454. }
  29455. }
  29456. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29457. int inputChannelOfIndexToIgnore,
  29458. const uint32 nodeId,
  29459. const int outputChanIndex) const
  29460. {
  29461. while (stepIndexToSearchFrom < orderedNodes.size())
  29462. {
  29463. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29464. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29465. {
  29466. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29467. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29468. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29469. return true;
  29470. }
  29471. else
  29472. {
  29473. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29474. if (i != inputChannelOfIndexToIgnore
  29475. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29476. node->id, i) != 0)
  29477. return true;
  29478. }
  29479. inputChannelOfIndexToIgnore = -1;
  29480. ++stepIndexToSearchFrom;
  29481. }
  29482. return false;
  29483. }
  29484. void markBufferAsContaining (int bufferNum, uint32 nodeId, int outputIndex)
  29485. {
  29486. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29487. {
  29488. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29489. midiNodeIds.set (bufferNum, nodeId);
  29490. }
  29491. else
  29492. {
  29493. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29494. nodeIds.set (bufferNum, nodeId);
  29495. channels.set (bufferNum, outputIndex);
  29496. }
  29497. }
  29498. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RenderingOpSequenceCalculator);
  29499. };
  29500. }
  29501. void AudioProcessorGraph::clearRenderingSequence()
  29502. {
  29503. const ScopedLock sl (renderLock);
  29504. for (int i = renderingOps.size(); --i >= 0;)
  29505. {
  29506. GraphRenderingOps::AudioGraphRenderingOp* const r
  29507. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29508. renderingOps.remove (i);
  29509. delete r;
  29510. }
  29511. }
  29512. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29513. const uint32 possibleDestinationId,
  29514. const int recursionCheck) const
  29515. {
  29516. if (recursionCheck > 0)
  29517. {
  29518. for (int i = connections.size(); --i >= 0;)
  29519. {
  29520. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29521. if (c->destNodeId == possibleDestinationId
  29522. && (c->sourceNodeId == possibleInputId
  29523. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29524. return true;
  29525. }
  29526. }
  29527. return false;
  29528. }
  29529. void AudioProcessorGraph::buildRenderingSequence()
  29530. {
  29531. Array<void*> newRenderingOps;
  29532. int numRenderingBuffersNeeded = 2;
  29533. int numMidiBuffersNeeded = 1;
  29534. {
  29535. MessageManagerLock mml;
  29536. Array<void*> orderedNodes;
  29537. int i;
  29538. for (i = 0; i < nodes.size(); ++i)
  29539. {
  29540. Node* const node = nodes.getUnchecked(i);
  29541. node->prepare (getSampleRate(), getBlockSize(), this);
  29542. int j = 0;
  29543. for (; j < orderedNodes.size(); ++j)
  29544. if (isAnInputTo (node->id,
  29545. ((Node*) orderedNodes.getUnchecked (j))->id,
  29546. nodes.size() + 1))
  29547. break;
  29548. orderedNodes.insert (j, node);
  29549. }
  29550. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29551. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29552. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29553. }
  29554. Array<void*> oldRenderingOps (renderingOps);
  29555. {
  29556. // swap over to the new rendering sequence..
  29557. const ScopedLock sl (renderLock);
  29558. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29559. renderingBuffers.clear();
  29560. for (int i = midiBuffers.size(); --i >= 0;)
  29561. midiBuffers.getUnchecked(i)->clear();
  29562. while (midiBuffers.size() < numMidiBuffersNeeded)
  29563. midiBuffers.add (new MidiBuffer());
  29564. renderingOps = newRenderingOps;
  29565. }
  29566. for (int i = oldRenderingOps.size(); --i >= 0;)
  29567. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29568. }
  29569. void AudioProcessorGraph::handleAsyncUpdate()
  29570. {
  29571. buildRenderingSequence();
  29572. }
  29573. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29574. {
  29575. currentAudioInputBuffer = 0;
  29576. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29577. currentMidiInputBuffer = 0;
  29578. currentMidiOutputBuffer.clear();
  29579. clearRenderingSequence();
  29580. buildRenderingSequence();
  29581. }
  29582. void AudioProcessorGraph::releaseResources()
  29583. {
  29584. for (int i = 0; i < nodes.size(); ++i)
  29585. nodes.getUnchecked(i)->unprepare();
  29586. renderingBuffers.setSize (1, 1);
  29587. midiBuffers.clear();
  29588. currentAudioInputBuffer = 0;
  29589. currentAudioOutputBuffer.setSize (1, 1);
  29590. currentMidiInputBuffer = 0;
  29591. currentMidiOutputBuffer.clear();
  29592. }
  29593. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29594. {
  29595. const int numSamples = buffer.getNumSamples();
  29596. const ScopedLock sl (renderLock);
  29597. currentAudioInputBuffer = &buffer;
  29598. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29599. currentAudioOutputBuffer.clear();
  29600. currentMidiInputBuffer = &midiMessages;
  29601. currentMidiOutputBuffer.clear();
  29602. int i;
  29603. for (i = 0; i < renderingOps.size(); ++i)
  29604. {
  29605. GraphRenderingOps::AudioGraphRenderingOp* const op
  29606. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29607. op->perform (renderingBuffers, midiBuffers, numSamples);
  29608. }
  29609. for (i = 0; i < buffer.getNumChannels(); ++i)
  29610. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29611. midiMessages.clear();
  29612. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29613. }
  29614. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29615. {
  29616. return "Input " + String (channelIndex + 1);
  29617. }
  29618. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29619. {
  29620. return "Output " + String (channelIndex + 1);
  29621. }
  29622. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29623. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29624. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29625. bool AudioProcessorGraph::producesMidi() const { return true; }
  29626. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29627. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29628. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29629. : type (type_),
  29630. graph (0)
  29631. {
  29632. }
  29633. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29634. {
  29635. }
  29636. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29637. {
  29638. switch (type)
  29639. {
  29640. case audioOutputNode: return "Audio Output";
  29641. case audioInputNode: return "Audio Input";
  29642. case midiOutputNode: return "Midi Output";
  29643. case midiInputNode: return "Midi Input";
  29644. default: break;
  29645. }
  29646. return String::empty;
  29647. }
  29648. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29649. {
  29650. d.name = getName();
  29651. d.uid = d.name.hashCode();
  29652. d.category = "I/O devices";
  29653. d.pluginFormatName = "Internal";
  29654. d.manufacturerName = "Raw Material Software";
  29655. d.version = "1.0";
  29656. d.isInstrument = false;
  29657. d.numInputChannels = getNumInputChannels();
  29658. if (type == audioOutputNode && graph != 0)
  29659. d.numInputChannels = graph->getNumInputChannels();
  29660. d.numOutputChannels = getNumOutputChannels();
  29661. if (type == audioInputNode && graph != 0)
  29662. d.numOutputChannels = graph->getNumOutputChannels();
  29663. }
  29664. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29665. {
  29666. jassert (graph != 0);
  29667. }
  29668. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29669. {
  29670. }
  29671. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29672. MidiBuffer& midiMessages)
  29673. {
  29674. jassert (graph != 0);
  29675. switch (type)
  29676. {
  29677. case audioOutputNode:
  29678. {
  29679. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29680. buffer.getNumChannels()); --i >= 0;)
  29681. {
  29682. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29683. }
  29684. break;
  29685. }
  29686. case audioInputNode:
  29687. {
  29688. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29689. buffer.getNumChannels()); --i >= 0;)
  29690. {
  29691. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29692. }
  29693. break;
  29694. }
  29695. case midiOutputNode:
  29696. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29697. break;
  29698. case midiInputNode:
  29699. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29700. break;
  29701. default:
  29702. break;
  29703. }
  29704. }
  29705. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29706. {
  29707. return type == midiOutputNode;
  29708. }
  29709. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29710. {
  29711. return type == midiInputNode;
  29712. }
  29713. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29714. {
  29715. switch (type)
  29716. {
  29717. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29718. case midiOutputNode: return "Midi Output";
  29719. default: break;
  29720. }
  29721. return String::empty;
  29722. }
  29723. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29724. {
  29725. switch (type)
  29726. {
  29727. case audioInputNode: return "Input " + String (channelIndex + 1);
  29728. case midiInputNode: return "Midi Input";
  29729. default: break;
  29730. }
  29731. return String::empty;
  29732. }
  29733. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29734. {
  29735. return type == audioInputNode || type == audioOutputNode;
  29736. }
  29737. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29738. {
  29739. return isInputChannelStereoPair (index);
  29740. }
  29741. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29742. {
  29743. return type == audioInputNode || type == midiInputNode;
  29744. }
  29745. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29746. {
  29747. return type == audioOutputNode || type == midiOutputNode;
  29748. }
  29749. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29750. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29751. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29752. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29753. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29754. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29755. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29756. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29757. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29758. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29759. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29760. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29761. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29762. {
  29763. }
  29764. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29765. {
  29766. }
  29767. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29768. {
  29769. graph = newGraph;
  29770. if (graph != 0)
  29771. {
  29772. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29773. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29774. getSampleRate(),
  29775. getBlockSize());
  29776. updateHostDisplay();
  29777. }
  29778. }
  29779. END_JUCE_NAMESPACE
  29780. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29781. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29782. BEGIN_JUCE_NAMESPACE
  29783. AudioProcessorPlayer::AudioProcessorPlayer()
  29784. : processor (0),
  29785. sampleRate (0),
  29786. blockSize (0),
  29787. isPrepared (false),
  29788. numInputChans (0),
  29789. numOutputChans (0),
  29790. tempBuffer (1, 1)
  29791. {
  29792. }
  29793. AudioProcessorPlayer::~AudioProcessorPlayer()
  29794. {
  29795. setProcessor (0);
  29796. }
  29797. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29798. {
  29799. if (processor != processorToPlay)
  29800. {
  29801. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29802. {
  29803. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29804. sampleRate, blockSize);
  29805. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29806. }
  29807. AudioProcessor* oldOne;
  29808. {
  29809. const ScopedLock sl (lock);
  29810. oldOne = isPrepared ? processor : 0;
  29811. processor = processorToPlay;
  29812. isPrepared = true;
  29813. }
  29814. if (oldOne != 0)
  29815. oldOne->releaseResources();
  29816. }
  29817. }
  29818. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29819. const int numInputChannels,
  29820. float** const outputChannelData,
  29821. const int numOutputChannels,
  29822. const int numSamples)
  29823. {
  29824. // these should have been prepared by audioDeviceAboutToStart()...
  29825. jassert (sampleRate > 0 && blockSize > 0);
  29826. incomingMidi.clear();
  29827. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  29828. int i, totalNumChans = 0;
  29829. if (numInputChannels > numOutputChannels)
  29830. {
  29831. // if there aren't enough output channels for the number of
  29832. // inputs, we need to create some temporary extra ones (can't
  29833. // use the input data in case it gets written to)
  29834. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  29835. false, false, true);
  29836. for (i = 0; i < numOutputChannels; ++i)
  29837. {
  29838. channels[totalNumChans] = outputChannelData[i];
  29839. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29840. ++totalNumChans;
  29841. }
  29842. for (i = numOutputChannels; i < numInputChannels; ++i)
  29843. {
  29844. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  29845. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29846. ++totalNumChans;
  29847. }
  29848. }
  29849. else
  29850. {
  29851. for (i = 0; i < numInputChannels; ++i)
  29852. {
  29853. channels[totalNumChans] = outputChannelData[i];
  29854. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  29855. ++totalNumChans;
  29856. }
  29857. for (i = numInputChannels; i < numOutputChannels; ++i)
  29858. {
  29859. channels[totalNumChans] = outputChannelData[i];
  29860. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  29861. ++totalNumChans;
  29862. }
  29863. }
  29864. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  29865. const ScopedLock sl (lock);
  29866. if (processor != 0)
  29867. {
  29868. const ScopedLock sl2 (processor->getCallbackLock());
  29869. if (processor->isSuspended())
  29870. {
  29871. for (i = 0; i < numOutputChannels; ++i)
  29872. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  29873. }
  29874. else
  29875. {
  29876. processor->processBlock (buffer, incomingMidi);
  29877. }
  29878. }
  29879. }
  29880. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  29881. {
  29882. const ScopedLock sl (lock);
  29883. sampleRate = device->getCurrentSampleRate();
  29884. blockSize = device->getCurrentBufferSizeSamples();
  29885. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  29886. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  29887. messageCollector.reset (sampleRate);
  29888. zeromem (channels, sizeof (channels));
  29889. if (processor != 0)
  29890. {
  29891. if (isPrepared)
  29892. processor->releaseResources();
  29893. AudioProcessor* const oldProcessor = processor;
  29894. setProcessor (0);
  29895. setProcessor (oldProcessor);
  29896. }
  29897. }
  29898. void AudioProcessorPlayer::audioDeviceStopped()
  29899. {
  29900. const ScopedLock sl (lock);
  29901. if (processor != 0 && isPrepared)
  29902. processor->releaseResources();
  29903. sampleRate = 0.0;
  29904. blockSize = 0;
  29905. isPrepared = false;
  29906. tempBuffer.setSize (1, 1);
  29907. }
  29908. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  29909. {
  29910. messageCollector.addMessageToQueue (message);
  29911. }
  29912. END_JUCE_NAMESPACE
  29913. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29914. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  29915. BEGIN_JUCE_NAMESPACE
  29916. class ProcessorParameterPropertyComp : public PropertyComponent,
  29917. public AudioProcessorListener,
  29918. public Timer
  29919. {
  29920. public:
  29921. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  29922. : PropertyComponent (name),
  29923. owner (owner_),
  29924. index (index_),
  29925. paramHasChanged (false),
  29926. slider (owner_, index_)
  29927. {
  29928. startTimer (100);
  29929. addAndMakeVisible (&slider);
  29930. owner_.addListener (this);
  29931. }
  29932. ~ProcessorParameterPropertyComp()
  29933. {
  29934. owner.removeListener (this);
  29935. }
  29936. void refresh()
  29937. {
  29938. paramHasChanged = false;
  29939. slider.setValue (owner.getParameter (index), false);
  29940. }
  29941. void audioProcessorChanged (AudioProcessor*) {}
  29942. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  29943. {
  29944. if (parameterIndex == index)
  29945. paramHasChanged = true;
  29946. }
  29947. void timerCallback()
  29948. {
  29949. if (paramHasChanged)
  29950. {
  29951. refresh();
  29952. startTimer (1000 / 50);
  29953. }
  29954. else
  29955. {
  29956. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  29957. }
  29958. }
  29959. private:
  29960. class ParamSlider : public Slider
  29961. {
  29962. public:
  29963. ParamSlider (AudioProcessor& owner_, const int index_)
  29964. : owner (owner_),
  29965. index (index_)
  29966. {
  29967. setRange (0.0, 1.0, 0.0);
  29968. setSliderStyle (Slider::LinearBar);
  29969. setTextBoxIsEditable (false);
  29970. setScrollWheelEnabled (false);
  29971. }
  29972. void valueChanged()
  29973. {
  29974. const float newVal = (float) getValue();
  29975. if (owner.getParameter (index) != newVal)
  29976. owner.setParameter (index, newVal);
  29977. }
  29978. const String getTextFromValue (double /*value*/)
  29979. {
  29980. return owner.getParameterText (index);
  29981. }
  29982. private:
  29983. AudioProcessor& owner;
  29984. const int index;
  29985. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParamSlider);
  29986. };
  29987. AudioProcessor& owner;
  29988. const int index;
  29989. bool volatile paramHasChanged;
  29990. ParamSlider slider;
  29991. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProcessorParameterPropertyComp);
  29992. };
  29993. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  29994. : AudioProcessorEditor (owner_)
  29995. {
  29996. jassert (owner_ != 0);
  29997. setOpaque (true);
  29998. addAndMakeVisible (&panel);
  29999. Array <PropertyComponent*> params;
  30000. const int numParams = owner_->getNumParameters();
  30001. int totalHeight = 0;
  30002. for (int i = 0; i < numParams; ++i)
  30003. {
  30004. String name (owner_->getParameterName (i));
  30005. if (name.trim().isEmpty())
  30006. name = "Unnamed";
  30007. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30008. params.add (pc);
  30009. totalHeight += pc->getPreferredHeight();
  30010. }
  30011. panel.addProperties (params);
  30012. setSize (400, jlimit (25, 400, totalHeight));
  30013. }
  30014. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30015. {
  30016. }
  30017. void GenericAudioProcessorEditor::paint (Graphics& g)
  30018. {
  30019. g.fillAll (Colours::white);
  30020. }
  30021. void GenericAudioProcessorEditor::resized()
  30022. {
  30023. panel.setBounds (getLocalBounds());
  30024. }
  30025. END_JUCE_NAMESPACE
  30026. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30027. /*** Start of inlined file: juce_Sampler.cpp ***/
  30028. BEGIN_JUCE_NAMESPACE
  30029. SamplerSound::SamplerSound (const String& name_,
  30030. AudioFormatReader& source,
  30031. const BigInteger& midiNotes_,
  30032. const int midiNoteForNormalPitch,
  30033. const double attackTimeSecs,
  30034. const double releaseTimeSecs,
  30035. const double maxSampleLengthSeconds)
  30036. : name (name_),
  30037. midiNotes (midiNotes_),
  30038. midiRootNote (midiNoteForNormalPitch)
  30039. {
  30040. sourceSampleRate = source.sampleRate;
  30041. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30042. {
  30043. length = 0;
  30044. attackSamples = 0;
  30045. releaseSamples = 0;
  30046. }
  30047. else
  30048. {
  30049. length = jmin ((int) source.lengthInSamples,
  30050. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30051. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30052. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30053. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30054. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30055. }
  30056. }
  30057. SamplerSound::~SamplerSound()
  30058. {
  30059. }
  30060. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30061. {
  30062. return midiNotes [midiNoteNumber];
  30063. }
  30064. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30065. {
  30066. return true;
  30067. }
  30068. SamplerVoice::SamplerVoice()
  30069. : pitchRatio (0.0),
  30070. sourceSamplePosition (0.0),
  30071. lgain (0.0f),
  30072. rgain (0.0f),
  30073. isInAttack (false),
  30074. isInRelease (false)
  30075. {
  30076. }
  30077. SamplerVoice::~SamplerVoice()
  30078. {
  30079. }
  30080. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30081. {
  30082. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30083. }
  30084. void SamplerVoice::startNote (const int midiNoteNumber,
  30085. const float velocity,
  30086. SynthesiserSound* s,
  30087. const int /*currentPitchWheelPosition*/)
  30088. {
  30089. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30090. jassert (sound != 0); // this object can only play SamplerSounds!
  30091. if (sound != 0)
  30092. {
  30093. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30094. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30095. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30096. sourceSamplePosition = 0.0;
  30097. lgain = velocity;
  30098. rgain = velocity;
  30099. isInAttack = (sound->attackSamples > 0);
  30100. isInRelease = false;
  30101. if (isInAttack)
  30102. {
  30103. attackReleaseLevel = 0.0f;
  30104. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30105. }
  30106. else
  30107. {
  30108. attackReleaseLevel = 1.0f;
  30109. attackDelta = 0.0f;
  30110. }
  30111. if (sound->releaseSamples > 0)
  30112. {
  30113. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30114. }
  30115. else
  30116. {
  30117. releaseDelta = 0.0f;
  30118. }
  30119. }
  30120. }
  30121. void SamplerVoice::stopNote (const bool allowTailOff)
  30122. {
  30123. if (allowTailOff)
  30124. {
  30125. isInAttack = false;
  30126. isInRelease = true;
  30127. }
  30128. else
  30129. {
  30130. clearCurrentNote();
  30131. }
  30132. }
  30133. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30134. {
  30135. }
  30136. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30137. const int /*newValue*/)
  30138. {
  30139. }
  30140. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30141. {
  30142. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30143. if (playingSound != 0)
  30144. {
  30145. const float* const inL = playingSound->data->getSampleData (0, 0);
  30146. const float* const inR = playingSound->data->getNumChannels() > 1
  30147. ? playingSound->data->getSampleData (1, 0) : 0;
  30148. float* outL = outputBuffer.getSampleData (0, startSample);
  30149. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30150. while (--numSamples >= 0)
  30151. {
  30152. const int pos = (int) sourceSamplePosition;
  30153. const float alpha = (float) (sourceSamplePosition - pos);
  30154. const float invAlpha = 1.0f - alpha;
  30155. // just using a very simple linear interpolation here..
  30156. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30157. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30158. : l;
  30159. l *= lgain;
  30160. r *= rgain;
  30161. if (isInAttack)
  30162. {
  30163. l *= attackReleaseLevel;
  30164. r *= attackReleaseLevel;
  30165. attackReleaseLevel += attackDelta;
  30166. if (attackReleaseLevel >= 1.0f)
  30167. {
  30168. attackReleaseLevel = 1.0f;
  30169. isInAttack = false;
  30170. }
  30171. }
  30172. else if (isInRelease)
  30173. {
  30174. l *= attackReleaseLevel;
  30175. r *= attackReleaseLevel;
  30176. attackReleaseLevel += releaseDelta;
  30177. if (attackReleaseLevel <= 0.0f)
  30178. {
  30179. stopNote (false);
  30180. break;
  30181. }
  30182. }
  30183. if (outR != 0)
  30184. {
  30185. *outL++ += l;
  30186. *outR++ += r;
  30187. }
  30188. else
  30189. {
  30190. *outL++ += (l + r) * 0.5f;
  30191. }
  30192. sourceSamplePosition += pitchRatio;
  30193. if (sourceSamplePosition > playingSound->length)
  30194. {
  30195. stopNote (false);
  30196. break;
  30197. }
  30198. }
  30199. }
  30200. }
  30201. END_JUCE_NAMESPACE
  30202. /*** End of inlined file: juce_Sampler.cpp ***/
  30203. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30204. BEGIN_JUCE_NAMESPACE
  30205. SynthesiserSound::SynthesiserSound()
  30206. {
  30207. }
  30208. SynthesiserSound::~SynthesiserSound()
  30209. {
  30210. }
  30211. SynthesiserVoice::SynthesiserVoice()
  30212. : currentSampleRate (44100.0),
  30213. currentlyPlayingNote (-1),
  30214. noteOnTime (0),
  30215. currentlyPlayingSound (0)
  30216. {
  30217. }
  30218. SynthesiserVoice::~SynthesiserVoice()
  30219. {
  30220. }
  30221. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30222. {
  30223. return currentlyPlayingSound != 0
  30224. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30225. }
  30226. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30227. {
  30228. currentSampleRate = newRate;
  30229. }
  30230. void SynthesiserVoice::clearCurrentNote()
  30231. {
  30232. currentlyPlayingNote = -1;
  30233. currentlyPlayingSound = 0;
  30234. }
  30235. Synthesiser::Synthesiser()
  30236. : sampleRate (0),
  30237. lastNoteOnCounter (0),
  30238. shouldStealNotes (true)
  30239. {
  30240. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30241. lastPitchWheelValues[i] = 0x2000;
  30242. }
  30243. Synthesiser::~Synthesiser()
  30244. {
  30245. }
  30246. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30247. {
  30248. const ScopedLock sl (lock);
  30249. return voices [index];
  30250. }
  30251. void Synthesiser::clearVoices()
  30252. {
  30253. const ScopedLock sl (lock);
  30254. voices.clear();
  30255. }
  30256. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30257. {
  30258. const ScopedLock sl (lock);
  30259. voices.add (newVoice);
  30260. }
  30261. void Synthesiser::removeVoice (const int index)
  30262. {
  30263. const ScopedLock sl (lock);
  30264. voices.remove (index);
  30265. }
  30266. void Synthesiser::clearSounds()
  30267. {
  30268. const ScopedLock sl (lock);
  30269. sounds.clear();
  30270. }
  30271. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30272. {
  30273. const ScopedLock sl (lock);
  30274. sounds.add (newSound);
  30275. }
  30276. void Synthesiser::removeSound (const int index)
  30277. {
  30278. const ScopedLock sl (lock);
  30279. sounds.remove (index);
  30280. }
  30281. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30282. {
  30283. shouldStealNotes = shouldStealNotes_;
  30284. }
  30285. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30286. {
  30287. if (sampleRate != newRate)
  30288. {
  30289. const ScopedLock sl (lock);
  30290. allNotesOff (0, false);
  30291. sampleRate = newRate;
  30292. for (int i = voices.size(); --i >= 0;)
  30293. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30294. }
  30295. }
  30296. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30297. const MidiBuffer& midiData,
  30298. int startSample,
  30299. int numSamples)
  30300. {
  30301. // must set the sample rate before using this!
  30302. jassert (sampleRate != 0);
  30303. const ScopedLock sl (lock);
  30304. MidiBuffer::Iterator midiIterator (midiData);
  30305. midiIterator.setNextSamplePosition (startSample);
  30306. MidiMessage m (0xf4, 0.0);
  30307. while (numSamples > 0)
  30308. {
  30309. int midiEventPos;
  30310. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30311. && midiEventPos < startSample + numSamples;
  30312. const int numThisTime = useEvent ? midiEventPos - startSample
  30313. : numSamples;
  30314. if (numThisTime > 0)
  30315. {
  30316. for (int i = voices.size(); --i >= 0;)
  30317. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30318. }
  30319. if (useEvent)
  30320. {
  30321. if (m.isNoteOn())
  30322. {
  30323. const int channel = m.getChannel();
  30324. noteOn (channel,
  30325. m.getNoteNumber(),
  30326. m.getFloatVelocity());
  30327. }
  30328. else if (m.isNoteOff())
  30329. {
  30330. noteOff (m.getChannel(),
  30331. m.getNoteNumber(),
  30332. true);
  30333. }
  30334. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30335. {
  30336. allNotesOff (m.getChannel(), true);
  30337. }
  30338. else if (m.isPitchWheel())
  30339. {
  30340. const int channel = m.getChannel();
  30341. const int wheelPos = m.getPitchWheelValue();
  30342. lastPitchWheelValues [channel - 1] = wheelPos;
  30343. handlePitchWheel (channel, wheelPos);
  30344. }
  30345. else if (m.isController())
  30346. {
  30347. handleController (m.getChannel(),
  30348. m.getControllerNumber(),
  30349. m.getControllerValue());
  30350. }
  30351. }
  30352. startSample += numThisTime;
  30353. numSamples -= numThisTime;
  30354. }
  30355. }
  30356. void Synthesiser::noteOn (const int midiChannel,
  30357. const int midiNoteNumber,
  30358. const float velocity)
  30359. {
  30360. const ScopedLock sl (lock);
  30361. for (int i = sounds.size(); --i >= 0;)
  30362. {
  30363. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30364. if (sound->appliesToNote (midiNoteNumber)
  30365. && sound->appliesToChannel (midiChannel))
  30366. {
  30367. startVoice (findFreeVoice (sound, shouldStealNotes),
  30368. sound, midiChannel, midiNoteNumber, velocity);
  30369. }
  30370. }
  30371. }
  30372. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30373. SynthesiserSound* const sound,
  30374. const int midiChannel,
  30375. const int midiNoteNumber,
  30376. const float velocity)
  30377. {
  30378. if (voice != 0 && sound != 0)
  30379. {
  30380. if (voice->currentlyPlayingSound != 0)
  30381. voice->stopNote (false);
  30382. voice->startNote (midiNoteNumber,
  30383. velocity,
  30384. sound,
  30385. lastPitchWheelValues [midiChannel - 1]);
  30386. voice->currentlyPlayingNote = midiNoteNumber;
  30387. voice->noteOnTime = ++lastNoteOnCounter;
  30388. voice->currentlyPlayingSound = sound;
  30389. }
  30390. }
  30391. void Synthesiser::noteOff (const int midiChannel,
  30392. const int midiNoteNumber,
  30393. const bool allowTailOff)
  30394. {
  30395. const ScopedLock sl (lock);
  30396. for (int i = voices.size(); --i >= 0;)
  30397. {
  30398. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30399. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30400. {
  30401. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30402. if (sound != 0
  30403. && sound->appliesToNote (midiNoteNumber)
  30404. && sound->appliesToChannel (midiChannel))
  30405. {
  30406. voice->stopNote (allowTailOff);
  30407. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30408. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30409. }
  30410. }
  30411. }
  30412. }
  30413. void Synthesiser::allNotesOff (const int midiChannel,
  30414. const bool allowTailOff)
  30415. {
  30416. const ScopedLock sl (lock);
  30417. for (int i = voices.size(); --i >= 0;)
  30418. {
  30419. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30420. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30421. voice->stopNote (allowTailOff);
  30422. }
  30423. }
  30424. void Synthesiser::handlePitchWheel (const int midiChannel,
  30425. const int wheelValue)
  30426. {
  30427. const ScopedLock sl (lock);
  30428. for (int i = voices.size(); --i >= 0;)
  30429. {
  30430. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30431. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30432. {
  30433. voice->pitchWheelMoved (wheelValue);
  30434. }
  30435. }
  30436. }
  30437. void Synthesiser::handleController (const int midiChannel,
  30438. const int controllerNumber,
  30439. const int controllerValue)
  30440. {
  30441. const ScopedLock sl (lock);
  30442. for (int i = voices.size(); --i >= 0;)
  30443. {
  30444. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30445. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30446. voice->controllerMoved (controllerNumber, controllerValue);
  30447. }
  30448. }
  30449. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30450. const bool stealIfNoneAvailable) const
  30451. {
  30452. const ScopedLock sl (lock);
  30453. for (int i = voices.size(); --i >= 0;)
  30454. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30455. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30456. return voices.getUnchecked (i);
  30457. if (stealIfNoneAvailable)
  30458. {
  30459. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30460. SynthesiserVoice* oldest = 0;
  30461. for (int i = voices.size(); --i >= 0;)
  30462. {
  30463. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30464. if (voice->canPlaySound (soundToPlay)
  30465. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30466. oldest = voice;
  30467. }
  30468. jassert (oldest != 0);
  30469. return oldest;
  30470. }
  30471. return 0;
  30472. }
  30473. END_JUCE_NAMESPACE
  30474. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30475. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30476. BEGIN_JUCE_NAMESPACE
  30477. // special message of our own with a string in it
  30478. class ActionMessage : public Message
  30479. {
  30480. public:
  30481. ActionMessage (const String& messageText, ActionListener* const listener_) throw()
  30482. : message (messageText)
  30483. {
  30484. pointerParameter = listener_;
  30485. }
  30486. const String message;
  30487. private:
  30488. JUCE_DECLARE_NON_COPYABLE (ActionMessage);
  30489. };
  30490. ActionBroadcaster::CallbackReceiver::CallbackReceiver() {}
  30491. void ActionBroadcaster::CallbackReceiver::handleMessage (const Message& message)
  30492. {
  30493. const ActionMessage& am = static_cast <const ActionMessage&> (message);
  30494. ActionListener* const target = static_cast <ActionListener*> (am.pointerParameter);
  30495. if (owner->actionListeners.contains (target))
  30496. target->actionListenerCallback (am.message);
  30497. }
  30498. ActionBroadcaster::ActionBroadcaster()
  30499. {
  30500. // are you trying to create this object before or after juce has been intialised??
  30501. jassert (MessageManager::instance != 0);
  30502. callback.owner = this;
  30503. }
  30504. ActionBroadcaster::~ActionBroadcaster()
  30505. {
  30506. // all event-based objects must be deleted BEFORE juce is shut down!
  30507. jassert (MessageManager::instance != 0);
  30508. }
  30509. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30510. {
  30511. const ScopedLock sl (actionListenerLock);
  30512. if (listener != 0)
  30513. actionListeners.add (listener);
  30514. }
  30515. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30516. {
  30517. const ScopedLock sl (actionListenerLock);
  30518. actionListeners.removeValue (listener);
  30519. }
  30520. void ActionBroadcaster::removeAllActionListeners()
  30521. {
  30522. const ScopedLock sl (actionListenerLock);
  30523. actionListeners.clear();
  30524. }
  30525. void ActionBroadcaster::sendActionMessage (const String& message) const
  30526. {
  30527. const ScopedLock sl (actionListenerLock);
  30528. for (int i = actionListeners.size(); --i >= 0;)
  30529. callback.postMessage (new ActionMessage (message, actionListeners.getUnchecked(i)));
  30530. }
  30531. END_JUCE_NAMESPACE
  30532. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30533. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30534. BEGIN_JUCE_NAMESPACE
  30535. class AsyncUpdaterMessage : public CallbackMessage
  30536. {
  30537. public:
  30538. AsyncUpdaterMessage (AsyncUpdater& owner_)
  30539. : owner (owner_)
  30540. {
  30541. }
  30542. void messageCallback()
  30543. {
  30544. if (shouldDeliver.compareAndSetBool (0, 1))
  30545. owner.handleAsyncUpdate();
  30546. }
  30547. Atomic<int> shouldDeliver;
  30548. private:
  30549. AsyncUpdater& owner;
  30550. };
  30551. AsyncUpdater::AsyncUpdater()
  30552. {
  30553. message = new AsyncUpdaterMessage (*this);
  30554. }
  30555. inline Atomic<int>& AsyncUpdater::getDeliveryFlag() const throw()
  30556. {
  30557. return static_cast <AsyncUpdaterMessage*> (message.getObject())->shouldDeliver;
  30558. }
  30559. AsyncUpdater::~AsyncUpdater()
  30560. {
  30561. // You're deleting this object with a background thread while there's an update
  30562. // pending on the main event thread - that's pretty dodgy threading, as the callback could
  30563. // happen after this destructor has finished. You should either use a MessageManagerLock while
  30564. // deleting this object, or find some other way to avoid such a race condition.
  30565. jassert ((! isUpdatePending()) || MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30566. getDeliveryFlag().set (0);
  30567. }
  30568. void AsyncUpdater::triggerAsyncUpdate()
  30569. {
  30570. if (getDeliveryFlag().compareAndSetBool (1, 0))
  30571. message->post();
  30572. }
  30573. void AsyncUpdater::cancelPendingUpdate() throw()
  30574. {
  30575. getDeliveryFlag().set (0);
  30576. }
  30577. void AsyncUpdater::handleUpdateNowIfNeeded()
  30578. {
  30579. // This can only be called by the event thread.
  30580. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30581. if (getDeliveryFlag().exchange (0) != 0)
  30582. handleAsyncUpdate();
  30583. }
  30584. bool AsyncUpdater::isUpdatePending() const throw()
  30585. {
  30586. return getDeliveryFlag().value != 0;
  30587. }
  30588. END_JUCE_NAMESPACE
  30589. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30590. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30591. BEGIN_JUCE_NAMESPACE
  30592. ChangeBroadcaster::ChangeBroadcaster() throw()
  30593. {
  30594. // are you trying to create this object before or after juce has been intialised??
  30595. jassert (MessageManager::instance != 0);
  30596. callback.owner = this;
  30597. }
  30598. ChangeBroadcaster::~ChangeBroadcaster()
  30599. {
  30600. // all event-based objects must be deleted BEFORE juce is shut down!
  30601. jassert (MessageManager::instance != 0);
  30602. }
  30603. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30604. {
  30605. // Listeners can only be safely added when the event thread is locked
  30606. // You can use a MessageManagerLock if you need to call this from another thread.
  30607. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30608. changeListeners.add (listener);
  30609. }
  30610. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30611. {
  30612. // Listeners can only be safely added when the event thread is locked
  30613. // You can use a MessageManagerLock if you need to call this from another thread.
  30614. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30615. changeListeners.remove (listener);
  30616. }
  30617. void ChangeBroadcaster::removeAllChangeListeners()
  30618. {
  30619. // Listeners can only be safely added when the event thread is locked
  30620. // You can use a MessageManagerLock if you need to call this from another thread.
  30621. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30622. changeListeners.clear();
  30623. }
  30624. void ChangeBroadcaster::sendChangeMessage()
  30625. {
  30626. if (changeListeners.size() > 0)
  30627. callback.triggerAsyncUpdate();
  30628. }
  30629. void ChangeBroadcaster::sendSynchronousChangeMessage()
  30630. {
  30631. // This can only be called by the event thread.
  30632. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  30633. callback.cancelPendingUpdate();
  30634. callListeners();
  30635. }
  30636. void ChangeBroadcaster::dispatchPendingMessages()
  30637. {
  30638. callback.handleUpdateNowIfNeeded();
  30639. }
  30640. void ChangeBroadcaster::callListeners()
  30641. {
  30642. changeListeners.call (&ChangeListener::changeListenerCallback, this);
  30643. }
  30644. ChangeBroadcaster::ChangeBroadcasterCallback::ChangeBroadcasterCallback()
  30645. : owner (0)
  30646. {
  30647. }
  30648. void ChangeBroadcaster::ChangeBroadcasterCallback::handleAsyncUpdate()
  30649. {
  30650. jassert (owner != 0);
  30651. owner->callListeners();
  30652. }
  30653. END_JUCE_NAMESPACE
  30654. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30655. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30656. BEGIN_JUCE_NAMESPACE
  30657. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30658. const uint32 magicMessageHeaderNumber)
  30659. : Thread ("Juce IPC connection"),
  30660. callbackConnectionState (false),
  30661. useMessageThread (callbacksOnMessageThread),
  30662. magicMessageHeader (magicMessageHeaderNumber),
  30663. pipeReceiveMessageTimeout (-1)
  30664. {
  30665. }
  30666. InterprocessConnection::~InterprocessConnection()
  30667. {
  30668. callbackConnectionState = false;
  30669. disconnect();
  30670. }
  30671. bool InterprocessConnection::connectToSocket (const String& hostName,
  30672. const int portNumber,
  30673. const int timeOutMillisecs)
  30674. {
  30675. disconnect();
  30676. const ScopedLock sl (pipeAndSocketLock);
  30677. socket = new StreamingSocket();
  30678. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30679. {
  30680. connectionMadeInt();
  30681. startThread();
  30682. return true;
  30683. }
  30684. else
  30685. {
  30686. socket = 0;
  30687. return false;
  30688. }
  30689. }
  30690. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30691. const int pipeReceiveMessageTimeoutMs)
  30692. {
  30693. disconnect();
  30694. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30695. if (newPipe->openExisting (pipeName))
  30696. {
  30697. const ScopedLock sl (pipeAndSocketLock);
  30698. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30699. initialiseWithPipe (newPipe.release());
  30700. return true;
  30701. }
  30702. return false;
  30703. }
  30704. bool InterprocessConnection::createPipe (const String& pipeName,
  30705. const int pipeReceiveMessageTimeoutMs)
  30706. {
  30707. disconnect();
  30708. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30709. if (newPipe->createNewPipe (pipeName))
  30710. {
  30711. const ScopedLock sl (pipeAndSocketLock);
  30712. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30713. initialiseWithPipe (newPipe.release());
  30714. return true;
  30715. }
  30716. return false;
  30717. }
  30718. void InterprocessConnection::disconnect()
  30719. {
  30720. if (socket != 0)
  30721. socket->close();
  30722. if (pipe != 0)
  30723. {
  30724. pipe->cancelPendingReads();
  30725. pipe->close();
  30726. }
  30727. stopThread (4000);
  30728. {
  30729. const ScopedLock sl (pipeAndSocketLock);
  30730. socket = 0;
  30731. pipe = 0;
  30732. }
  30733. connectionLostInt();
  30734. }
  30735. bool InterprocessConnection::isConnected() const
  30736. {
  30737. const ScopedLock sl (pipeAndSocketLock);
  30738. return ((socket != 0 && socket->isConnected())
  30739. || (pipe != 0 && pipe->isOpen()))
  30740. && isThreadRunning();
  30741. }
  30742. const String InterprocessConnection::getConnectedHostName() const
  30743. {
  30744. if (pipe != 0)
  30745. {
  30746. return "localhost";
  30747. }
  30748. else if (socket != 0)
  30749. {
  30750. if (! socket->isLocal())
  30751. return socket->getHostName();
  30752. return "localhost";
  30753. }
  30754. return String::empty;
  30755. }
  30756. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30757. {
  30758. uint32 messageHeader[2];
  30759. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30760. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30761. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30762. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30763. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30764. int bytesWritten = 0;
  30765. const ScopedLock sl (pipeAndSocketLock);
  30766. if (socket != 0)
  30767. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30768. else if (pipe != 0)
  30769. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30770. return bytesWritten == (int) messageData.getSize();
  30771. }
  30772. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  30773. {
  30774. jassert (socket == 0);
  30775. socket = socket_;
  30776. connectionMadeInt();
  30777. startThread();
  30778. }
  30779. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  30780. {
  30781. jassert (pipe == 0);
  30782. pipe = pipe_;
  30783. connectionMadeInt();
  30784. startThread();
  30785. }
  30786. const int messageMagicNumber = 0xb734128b;
  30787. void InterprocessConnection::handleMessage (const Message& message)
  30788. {
  30789. if (message.intParameter1 == messageMagicNumber)
  30790. {
  30791. switch (message.intParameter2)
  30792. {
  30793. case 0:
  30794. {
  30795. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  30796. messageReceived (*data);
  30797. break;
  30798. }
  30799. case 1:
  30800. connectionMade();
  30801. break;
  30802. case 2:
  30803. connectionLost();
  30804. break;
  30805. }
  30806. }
  30807. }
  30808. void InterprocessConnection::connectionMadeInt()
  30809. {
  30810. if (! callbackConnectionState)
  30811. {
  30812. callbackConnectionState = true;
  30813. if (useMessageThread)
  30814. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  30815. else
  30816. connectionMade();
  30817. }
  30818. }
  30819. void InterprocessConnection::connectionLostInt()
  30820. {
  30821. if (callbackConnectionState)
  30822. {
  30823. callbackConnectionState = false;
  30824. if (useMessageThread)
  30825. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  30826. else
  30827. connectionLost();
  30828. }
  30829. }
  30830. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  30831. {
  30832. jassert (callbackConnectionState);
  30833. if (useMessageThread)
  30834. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  30835. else
  30836. messageReceived (data);
  30837. }
  30838. bool InterprocessConnection::readNextMessageInt()
  30839. {
  30840. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  30841. uint32 messageHeader[2];
  30842. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  30843. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  30844. if (bytes == sizeof (messageHeader)
  30845. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  30846. {
  30847. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  30848. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  30849. {
  30850. MemoryBlock messageData (bytesInMessage, true);
  30851. int bytesRead = 0;
  30852. while (bytesInMessage > 0)
  30853. {
  30854. if (threadShouldExit())
  30855. return false;
  30856. const int numThisTime = jmin (bytesInMessage, 65536);
  30857. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  30858. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  30859. if (bytesIn <= 0)
  30860. break;
  30861. bytesRead += bytesIn;
  30862. bytesInMessage -= bytesIn;
  30863. }
  30864. if (bytesRead >= 0)
  30865. deliverDataInt (messageData);
  30866. }
  30867. }
  30868. else if (bytes < 0)
  30869. {
  30870. {
  30871. const ScopedLock sl (pipeAndSocketLock);
  30872. socket = 0;
  30873. }
  30874. connectionLostInt();
  30875. return false;
  30876. }
  30877. return true;
  30878. }
  30879. void InterprocessConnection::run()
  30880. {
  30881. while (! threadShouldExit())
  30882. {
  30883. if (socket != 0)
  30884. {
  30885. const int ready = socket->waitUntilReady (true, 0);
  30886. if (ready < 0)
  30887. {
  30888. {
  30889. const ScopedLock sl (pipeAndSocketLock);
  30890. socket = 0;
  30891. }
  30892. connectionLostInt();
  30893. break;
  30894. }
  30895. else if (ready > 0)
  30896. {
  30897. if (! readNextMessageInt())
  30898. break;
  30899. }
  30900. else
  30901. {
  30902. Thread::sleep (2);
  30903. }
  30904. }
  30905. else if (pipe != 0)
  30906. {
  30907. if (! pipe->isOpen())
  30908. {
  30909. {
  30910. const ScopedLock sl (pipeAndSocketLock);
  30911. pipe = 0;
  30912. }
  30913. connectionLostInt();
  30914. break;
  30915. }
  30916. else
  30917. {
  30918. if (! readNextMessageInt())
  30919. break;
  30920. }
  30921. }
  30922. else
  30923. {
  30924. break;
  30925. }
  30926. }
  30927. }
  30928. END_JUCE_NAMESPACE
  30929. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  30930. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30931. BEGIN_JUCE_NAMESPACE
  30932. InterprocessConnectionServer::InterprocessConnectionServer()
  30933. : Thread ("Juce IPC server")
  30934. {
  30935. }
  30936. InterprocessConnectionServer::~InterprocessConnectionServer()
  30937. {
  30938. stop();
  30939. }
  30940. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  30941. {
  30942. stop();
  30943. socket = new StreamingSocket();
  30944. if (socket->createListener (portNumber))
  30945. {
  30946. startThread();
  30947. return true;
  30948. }
  30949. socket = 0;
  30950. return false;
  30951. }
  30952. void InterprocessConnectionServer::stop()
  30953. {
  30954. signalThreadShouldExit();
  30955. if (socket != 0)
  30956. socket->close();
  30957. stopThread (4000);
  30958. socket = 0;
  30959. }
  30960. void InterprocessConnectionServer::run()
  30961. {
  30962. while ((! threadShouldExit()) && socket != 0)
  30963. {
  30964. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  30965. if (clientSocket != 0)
  30966. {
  30967. InterprocessConnection* newConnection = createConnectionObject();
  30968. if (newConnection != 0)
  30969. newConnection->initialiseWithSocket (clientSocket.release());
  30970. }
  30971. }
  30972. }
  30973. END_JUCE_NAMESPACE
  30974. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  30975. /*** Start of inlined file: juce_Message.cpp ***/
  30976. BEGIN_JUCE_NAMESPACE
  30977. Message::Message() throw()
  30978. : intParameter1 (0),
  30979. intParameter2 (0),
  30980. intParameter3 (0),
  30981. pointerParameter (0),
  30982. messageRecipient (0)
  30983. {
  30984. }
  30985. Message::Message (const int intParameter1_,
  30986. const int intParameter2_,
  30987. const int intParameter3_,
  30988. void* const pointerParameter_) throw()
  30989. : intParameter1 (intParameter1_),
  30990. intParameter2 (intParameter2_),
  30991. intParameter3 (intParameter3_),
  30992. pointerParameter (pointerParameter_),
  30993. messageRecipient (0)
  30994. {
  30995. }
  30996. Message::~Message()
  30997. {
  30998. }
  30999. END_JUCE_NAMESPACE
  31000. /*** End of inlined file: juce_Message.cpp ***/
  31001. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31002. BEGIN_JUCE_NAMESPACE
  31003. MessageListener::MessageListener() throw()
  31004. {
  31005. // are you trying to create a messagelistener before or after juce has been intialised??
  31006. jassert (MessageManager::instance != 0);
  31007. if (MessageManager::instance != 0)
  31008. MessageManager::instance->messageListeners.add (this);
  31009. }
  31010. MessageListener::~MessageListener()
  31011. {
  31012. if (MessageManager::instance != 0)
  31013. MessageManager::instance->messageListeners.removeValue (this);
  31014. }
  31015. void MessageListener::postMessage (Message* const message) const throw()
  31016. {
  31017. message->messageRecipient = const_cast <MessageListener*> (this);
  31018. if (MessageManager::instance == 0)
  31019. MessageManager::getInstance();
  31020. MessageManager::instance->postMessageToQueue (message);
  31021. }
  31022. bool MessageListener::isValidMessageListener() const throw()
  31023. {
  31024. return (MessageManager::instance != 0)
  31025. && MessageManager::instance->messageListeners.contains (this);
  31026. }
  31027. END_JUCE_NAMESPACE
  31028. /*** End of inlined file: juce_MessageListener.cpp ***/
  31029. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31030. BEGIN_JUCE_NAMESPACE
  31031. // platform-specific functions..
  31032. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31033. bool juce_postMessageToSystemQueue (Message* message);
  31034. MessageManager* MessageManager::instance = 0;
  31035. static const int quitMessageId = 0xfffff321;
  31036. MessageManager::MessageManager() throw()
  31037. : quitMessagePosted (false),
  31038. quitMessageReceived (false),
  31039. threadWithLock (0)
  31040. {
  31041. messageThreadId = Thread::getCurrentThreadId();
  31042. if (JUCEApplication::isStandaloneApp())
  31043. Thread::setCurrentThreadName ("Juce Message Thread");
  31044. }
  31045. MessageManager::~MessageManager() throw()
  31046. {
  31047. broadcaster = 0;
  31048. doPlatformSpecificShutdown();
  31049. // If you hit this assertion, then you've probably leaked some kind of MessageListener object..
  31050. jassert (messageListeners.size() == 0);
  31051. jassert (instance == this);
  31052. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31053. }
  31054. MessageManager* MessageManager::getInstance() throw()
  31055. {
  31056. if (instance == 0)
  31057. {
  31058. instance = new MessageManager();
  31059. doPlatformSpecificInitialisation();
  31060. }
  31061. return instance;
  31062. }
  31063. void MessageManager::postMessageToQueue (Message* const message)
  31064. {
  31065. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31066. Message::Ptr deleter (message); // (this will delete messages that were just created with a 0 ref count)
  31067. }
  31068. CallbackMessage::CallbackMessage() throw() {}
  31069. CallbackMessage::~CallbackMessage() {}
  31070. void CallbackMessage::post()
  31071. {
  31072. if (MessageManager::instance != 0)
  31073. MessageManager::instance->postMessageToQueue (this);
  31074. }
  31075. // not for public use..
  31076. void MessageManager::deliverMessage (Message* const message)
  31077. {
  31078. JUCE_TRY
  31079. {
  31080. MessageListener* const recipient = message->messageRecipient;
  31081. if (recipient == 0)
  31082. {
  31083. CallbackMessage* const callbackMessage = dynamic_cast <CallbackMessage*> (message);
  31084. if (callbackMessage != 0)
  31085. {
  31086. callbackMessage->messageCallback();
  31087. }
  31088. else if (message->intParameter1 == quitMessageId)
  31089. {
  31090. quitMessageReceived = true;
  31091. }
  31092. }
  31093. else if (messageListeners.contains (recipient))
  31094. {
  31095. recipient->handleMessage (*message);
  31096. }
  31097. }
  31098. JUCE_CATCH_EXCEPTION
  31099. }
  31100. #if ! (JUCE_MAC || JUCE_IOS)
  31101. void MessageManager::runDispatchLoop()
  31102. {
  31103. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31104. runDispatchLoopUntil (-1);
  31105. }
  31106. void MessageManager::stopDispatchLoop()
  31107. {
  31108. postMessageToQueue (new Message (quitMessageId, 0, 0, 0));
  31109. quitMessagePosted = true;
  31110. }
  31111. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31112. {
  31113. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31114. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31115. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31116. && ! quitMessageReceived)
  31117. {
  31118. JUCE_TRY
  31119. {
  31120. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31121. {
  31122. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31123. if (msToWait > 0)
  31124. Thread::sleep (jmin (5, msToWait));
  31125. }
  31126. }
  31127. JUCE_CATCH_EXCEPTION
  31128. }
  31129. return ! quitMessageReceived;
  31130. }
  31131. #endif
  31132. void MessageManager::deliverBroadcastMessage (const String& value)
  31133. {
  31134. if (broadcaster != 0)
  31135. broadcaster->sendActionMessage (value);
  31136. }
  31137. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31138. {
  31139. if (broadcaster == 0)
  31140. broadcaster = new ActionBroadcaster();
  31141. broadcaster->addActionListener (listener);
  31142. }
  31143. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31144. {
  31145. if (broadcaster != 0)
  31146. broadcaster->removeActionListener (listener);
  31147. }
  31148. bool MessageManager::isThisTheMessageThread() const throw()
  31149. {
  31150. return Thread::getCurrentThreadId() == messageThreadId;
  31151. }
  31152. void MessageManager::setCurrentThreadAsMessageThread()
  31153. {
  31154. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31155. if (messageThreadId != thisThread)
  31156. {
  31157. messageThreadId = thisThread;
  31158. // This is needed on windows to make sure the message window is created by this thread
  31159. doPlatformSpecificShutdown();
  31160. doPlatformSpecificInitialisation();
  31161. }
  31162. }
  31163. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31164. {
  31165. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31166. return thisThread == messageThreadId || thisThread == threadWithLock;
  31167. }
  31168. /* The only safe way to lock the message thread while another thread does
  31169. some work is by posting a special message, whose purpose is to tie up the event
  31170. loop until the other thread has finished its business.
  31171. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31172. get locked before making an event callback, because if the same OS lock gets indirectly
  31173. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31174. in Cocoa).
  31175. */
  31176. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31177. {
  31178. public:
  31179. BlockingMessage() {}
  31180. void messageCallback()
  31181. {
  31182. lockedEvent.signal();
  31183. releaseEvent.wait();
  31184. }
  31185. WaitableEvent lockedEvent, releaseEvent;
  31186. private:
  31187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlockingMessage);
  31188. };
  31189. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31190. : locked (false)
  31191. {
  31192. init (threadToCheck, 0);
  31193. }
  31194. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31195. : locked (false)
  31196. {
  31197. init (0, jobToCheckForExitSignal);
  31198. }
  31199. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31200. {
  31201. if (MessageManager::instance != 0)
  31202. {
  31203. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31204. {
  31205. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31206. }
  31207. else
  31208. {
  31209. if (threadToCheck == 0 && job == 0)
  31210. {
  31211. MessageManager::instance->lockingLock.enter();
  31212. }
  31213. else
  31214. {
  31215. while (! MessageManager::instance->lockingLock.tryEnter())
  31216. {
  31217. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31218. || (job != 0 && job->shouldExit()))
  31219. return;
  31220. Thread::sleep (1);
  31221. }
  31222. }
  31223. blockingMessage = new BlockingMessage();
  31224. blockingMessage->post();
  31225. while (! blockingMessage->lockedEvent.wait (20))
  31226. {
  31227. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31228. || (job != 0 && job->shouldExit()))
  31229. {
  31230. blockingMessage->releaseEvent.signal();
  31231. blockingMessage = 0;
  31232. MessageManager::instance->lockingLock.exit();
  31233. return;
  31234. }
  31235. }
  31236. jassert (MessageManager::instance->threadWithLock == 0);
  31237. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31238. locked = true;
  31239. }
  31240. }
  31241. }
  31242. MessageManagerLock::~MessageManagerLock() throw()
  31243. {
  31244. if (blockingMessage != 0)
  31245. {
  31246. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31247. blockingMessage->releaseEvent.signal();
  31248. blockingMessage = 0;
  31249. if (MessageManager::instance != 0)
  31250. {
  31251. MessageManager::instance->threadWithLock = 0;
  31252. MessageManager::instance->lockingLock.exit();
  31253. }
  31254. }
  31255. }
  31256. END_JUCE_NAMESPACE
  31257. /*** End of inlined file: juce_MessageManager.cpp ***/
  31258. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31259. BEGIN_JUCE_NAMESPACE
  31260. class MultiTimer::MultiTimerCallback : public Timer
  31261. {
  31262. public:
  31263. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31264. : timerId (timerId_),
  31265. owner (owner_)
  31266. {
  31267. }
  31268. ~MultiTimerCallback()
  31269. {
  31270. }
  31271. void timerCallback()
  31272. {
  31273. owner.timerCallback (timerId);
  31274. }
  31275. const int timerId;
  31276. private:
  31277. MultiTimer& owner;
  31278. };
  31279. MultiTimer::MultiTimer() throw()
  31280. {
  31281. }
  31282. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31283. {
  31284. }
  31285. MultiTimer::~MultiTimer()
  31286. {
  31287. const ScopedLock sl (timerListLock);
  31288. timers.clear();
  31289. }
  31290. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31291. {
  31292. const ScopedLock sl (timerListLock);
  31293. for (int i = timers.size(); --i >= 0;)
  31294. {
  31295. MultiTimerCallback* const t = timers.getUnchecked(i);
  31296. if (t->timerId == timerId)
  31297. {
  31298. t->startTimer (intervalInMilliseconds);
  31299. return;
  31300. }
  31301. }
  31302. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31303. timers.add (newTimer);
  31304. newTimer->startTimer (intervalInMilliseconds);
  31305. }
  31306. void MultiTimer::stopTimer (const int timerId) throw()
  31307. {
  31308. const ScopedLock sl (timerListLock);
  31309. for (int i = timers.size(); --i >= 0;)
  31310. {
  31311. MultiTimerCallback* const t = timers.getUnchecked(i);
  31312. if (t->timerId == timerId)
  31313. t->stopTimer();
  31314. }
  31315. }
  31316. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31317. {
  31318. const ScopedLock sl (timerListLock);
  31319. for (int i = timers.size(); --i >= 0;)
  31320. {
  31321. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31322. if (t->timerId == timerId)
  31323. return t->isTimerRunning();
  31324. }
  31325. return false;
  31326. }
  31327. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31328. {
  31329. const ScopedLock sl (timerListLock);
  31330. for (int i = timers.size(); --i >= 0;)
  31331. {
  31332. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31333. if (t->timerId == timerId)
  31334. return t->getTimerInterval();
  31335. }
  31336. return 0;
  31337. }
  31338. END_JUCE_NAMESPACE
  31339. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31340. /*** Start of inlined file: juce_Timer.cpp ***/
  31341. BEGIN_JUCE_NAMESPACE
  31342. class InternalTimerThread : private Thread,
  31343. private MessageListener,
  31344. private DeletedAtShutdown,
  31345. private AsyncUpdater
  31346. {
  31347. public:
  31348. InternalTimerThread()
  31349. : Thread ("Juce Timer"),
  31350. firstTimer (0),
  31351. callbackNeeded (0)
  31352. {
  31353. triggerAsyncUpdate();
  31354. }
  31355. ~InternalTimerThread() throw()
  31356. {
  31357. stopThread (4000);
  31358. jassert (instance == this || instance == 0);
  31359. if (instance == this)
  31360. instance = 0;
  31361. }
  31362. void run()
  31363. {
  31364. uint32 lastTime = Time::getMillisecondCounter();
  31365. Message::Ptr message (new Message());
  31366. while (! threadShouldExit())
  31367. {
  31368. const uint32 now = Time::getMillisecondCounter();
  31369. if (now <= lastTime)
  31370. {
  31371. wait (2);
  31372. continue;
  31373. }
  31374. const int elapsed = now - lastTime;
  31375. lastTime = now;
  31376. const int timeUntilFirstTimer = getTimeUntilFirstTimer (elapsed);
  31377. if (timeUntilFirstTimer <= 0)
  31378. {
  31379. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31380. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31381. but if it fails it means the message-thread changed the value from under us so at least
  31382. some processing is happenening and we can just loop around and try again
  31383. */
  31384. if (callbackNeeded.compareAndSetBool (1, 0))
  31385. {
  31386. postMessage (message);
  31387. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31388. when the app has a modal loop), so this is how long to wait before assuming the
  31389. message has been lost and trying again.
  31390. */
  31391. const uint32 messageDeliveryTimeout = now + 2000;
  31392. while (callbackNeeded.get() != 0)
  31393. {
  31394. wait (4);
  31395. if (threadShouldExit())
  31396. return;
  31397. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31398. break;
  31399. }
  31400. }
  31401. }
  31402. else
  31403. {
  31404. // don't wait for too long because running this loop also helps keep the
  31405. // Time::getApproximateMillisecondTimer value stay up-to-date
  31406. wait (jlimit (1, 50, timeUntilFirstTimer));
  31407. }
  31408. }
  31409. }
  31410. void callTimers()
  31411. {
  31412. const ScopedLock sl (lock);
  31413. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31414. {
  31415. Timer* const t = firstTimer;
  31416. t->countdownMs = t->periodMs;
  31417. removeTimer (t);
  31418. addTimer (t);
  31419. const ScopedUnlock ul (lock);
  31420. JUCE_TRY
  31421. {
  31422. t->timerCallback();
  31423. }
  31424. JUCE_CATCH_EXCEPTION
  31425. }
  31426. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31427. before the boolean is set. This set should never fail since if it was false in the first place,
  31428. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31429. get a message then the value is true and the other thread can only set it to true again and
  31430. we will get another callback to set it to false.
  31431. */
  31432. callbackNeeded.set (0);
  31433. }
  31434. void handleMessage (const Message&)
  31435. {
  31436. callTimers();
  31437. }
  31438. void callTimersSynchronously()
  31439. {
  31440. if (! isThreadRunning())
  31441. {
  31442. // (This is relied on by some plugins in cases where the MM has
  31443. // had to restart and the async callback never started)
  31444. cancelPendingUpdate();
  31445. triggerAsyncUpdate();
  31446. }
  31447. callTimers();
  31448. }
  31449. static void callAnyTimersSynchronously()
  31450. {
  31451. if (InternalTimerThread::instance != 0)
  31452. InternalTimerThread::instance->callTimersSynchronously();
  31453. }
  31454. static inline void add (Timer* const tim) throw()
  31455. {
  31456. if (instance == 0)
  31457. instance = new InternalTimerThread();
  31458. const ScopedLock sl (instance->lock);
  31459. instance->addTimer (tim);
  31460. }
  31461. static inline void remove (Timer* const tim) throw()
  31462. {
  31463. if (instance != 0)
  31464. {
  31465. const ScopedLock sl (instance->lock);
  31466. instance->removeTimer (tim);
  31467. }
  31468. }
  31469. static inline void resetCounter (Timer* const tim,
  31470. const int newCounter) throw()
  31471. {
  31472. if (instance != 0)
  31473. {
  31474. tim->countdownMs = newCounter;
  31475. tim->periodMs = newCounter;
  31476. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31477. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31478. {
  31479. const ScopedLock sl (instance->lock);
  31480. instance->removeTimer (tim);
  31481. instance->addTimer (tim);
  31482. }
  31483. }
  31484. }
  31485. private:
  31486. friend class Timer;
  31487. static InternalTimerThread* instance;
  31488. static CriticalSection lock;
  31489. Timer* volatile firstTimer;
  31490. Atomic <int> callbackNeeded;
  31491. void addTimer (Timer* const t) throw()
  31492. {
  31493. #if JUCE_DEBUG
  31494. Timer* tt = firstTimer;
  31495. while (tt != 0)
  31496. {
  31497. // trying to add a timer that's already here - shouldn't get to this point,
  31498. // so if you get this assertion, let me know!
  31499. jassert (tt != t);
  31500. tt = tt->next;
  31501. }
  31502. jassert (t->previous == 0 && t->next == 0);
  31503. #endif
  31504. Timer* i = firstTimer;
  31505. if (i == 0 || i->countdownMs > t->countdownMs)
  31506. {
  31507. t->next = firstTimer;
  31508. firstTimer = t;
  31509. }
  31510. else
  31511. {
  31512. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31513. i = i->next;
  31514. jassert (i != 0);
  31515. t->next = i->next;
  31516. t->previous = i;
  31517. i->next = t;
  31518. }
  31519. if (t->next != 0)
  31520. t->next->previous = t;
  31521. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31522. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31523. notify();
  31524. }
  31525. void removeTimer (Timer* const t) throw()
  31526. {
  31527. #if JUCE_DEBUG
  31528. Timer* tt = firstTimer;
  31529. bool found = false;
  31530. while (tt != 0)
  31531. {
  31532. if (tt == t)
  31533. {
  31534. found = true;
  31535. break;
  31536. }
  31537. tt = tt->next;
  31538. }
  31539. // trying to remove a timer that's not here - shouldn't get to this point,
  31540. // so if you get this assertion, let me know!
  31541. jassert (found);
  31542. #endif
  31543. if (t->previous != 0)
  31544. {
  31545. jassert (firstTimer != t);
  31546. t->previous->next = t->next;
  31547. }
  31548. else
  31549. {
  31550. jassert (firstTimer == t);
  31551. firstTimer = t->next;
  31552. }
  31553. if (t->next != 0)
  31554. t->next->previous = t->previous;
  31555. t->next = 0;
  31556. t->previous = 0;
  31557. }
  31558. int getTimeUntilFirstTimer (const int numMillisecsElapsed) const
  31559. {
  31560. const ScopedLock sl (lock);
  31561. for (Timer* t = firstTimer; t != 0; t = t->next)
  31562. t->countdownMs -= numMillisecsElapsed;
  31563. return firstTimer != 0 ? firstTimer->countdownMs : 1000;
  31564. }
  31565. void handleAsyncUpdate()
  31566. {
  31567. startThread (7);
  31568. }
  31569. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternalTimerThread);
  31570. };
  31571. InternalTimerThread* InternalTimerThread::instance = 0;
  31572. CriticalSection InternalTimerThread::lock;
  31573. void juce_callAnyTimersSynchronously()
  31574. {
  31575. InternalTimerThread::callAnyTimersSynchronously();
  31576. }
  31577. #if JUCE_DEBUG
  31578. static SortedSet <Timer*> activeTimers;
  31579. #endif
  31580. Timer::Timer() throw()
  31581. : countdownMs (0),
  31582. periodMs (0),
  31583. previous (0),
  31584. next (0)
  31585. {
  31586. #if JUCE_DEBUG
  31587. activeTimers.add (this);
  31588. #endif
  31589. }
  31590. Timer::Timer (const Timer&) throw()
  31591. : countdownMs (0),
  31592. periodMs (0),
  31593. previous (0),
  31594. next (0)
  31595. {
  31596. #if JUCE_DEBUG
  31597. activeTimers.add (this);
  31598. #endif
  31599. }
  31600. Timer::~Timer()
  31601. {
  31602. stopTimer();
  31603. #if JUCE_DEBUG
  31604. activeTimers.removeValue (this);
  31605. #endif
  31606. }
  31607. void Timer::startTimer (const int interval) throw()
  31608. {
  31609. const ScopedLock sl (InternalTimerThread::lock);
  31610. #if JUCE_DEBUG
  31611. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31612. jassert (activeTimers.contains (this));
  31613. #endif
  31614. if (periodMs == 0)
  31615. {
  31616. countdownMs = interval;
  31617. periodMs = jmax (1, interval);
  31618. InternalTimerThread::add (this);
  31619. }
  31620. else
  31621. {
  31622. InternalTimerThread::resetCounter (this, interval);
  31623. }
  31624. }
  31625. void Timer::stopTimer() throw()
  31626. {
  31627. const ScopedLock sl (InternalTimerThread::lock);
  31628. #if JUCE_DEBUG
  31629. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31630. jassert (activeTimers.contains (this));
  31631. #endif
  31632. if (periodMs > 0)
  31633. {
  31634. InternalTimerThread::remove (this);
  31635. periodMs = 0;
  31636. }
  31637. }
  31638. END_JUCE_NAMESPACE
  31639. /*** End of inlined file: juce_Timer.cpp ***/
  31640. #endif
  31641. #if JUCE_BUILD_GUI
  31642. /*** Start of inlined file: juce_Component.cpp ***/
  31643. BEGIN_JUCE_NAMESPACE
  31644. #define CHECK_MESSAGE_MANAGER_IS_LOCKED jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31645. Component* Component::currentlyFocusedComponent = 0;
  31646. class Component::MouseListenerList
  31647. {
  31648. public:
  31649. MouseListenerList()
  31650. : numDeepMouseListeners (0)
  31651. {
  31652. }
  31653. void addListener (MouseListener* const newListener, const bool wantsEventsForAllNestedChildComponents)
  31654. {
  31655. if (! listeners.contains (newListener))
  31656. {
  31657. if (wantsEventsForAllNestedChildComponents)
  31658. {
  31659. listeners.insert (0, newListener);
  31660. ++numDeepMouseListeners;
  31661. }
  31662. else
  31663. {
  31664. listeners.add (newListener);
  31665. }
  31666. }
  31667. }
  31668. void removeListener (MouseListener* const listenerToRemove)
  31669. {
  31670. const int index = listeners.indexOf (listenerToRemove);
  31671. if (index >= 0)
  31672. {
  31673. if (index < numDeepMouseListeners)
  31674. --numDeepMouseListeners;
  31675. listeners.remove (index);
  31676. }
  31677. }
  31678. static void sendMouseEvent (Component& comp, BailOutChecker& checker,
  31679. void (MouseListener::*eventMethod) (const MouseEvent&), const MouseEvent& e)
  31680. {
  31681. if (checker.shouldBailOut())
  31682. return;
  31683. {
  31684. MouseListenerList* const list = comp.mouseListeners;
  31685. if (list != 0)
  31686. {
  31687. for (int i = list->listeners.size(); --i >= 0;)
  31688. {
  31689. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31690. if (checker.shouldBailOut())
  31691. return;
  31692. i = jmin (i, list->listeners.size());
  31693. }
  31694. }
  31695. }
  31696. Component* p = comp.parentComponent;
  31697. while (p != 0)
  31698. {
  31699. MouseListenerList* const list = p->mouseListeners;
  31700. if (list != 0 && list->numDeepMouseListeners > 0)
  31701. {
  31702. BailOutChecker2 checker2 (checker, p);
  31703. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31704. {
  31705. (list->listeners.getUnchecked(i)->*eventMethod) (e);
  31706. if (checker2.shouldBailOut())
  31707. return;
  31708. i = jmin (i, list->numDeepMouseListeners);
  31709. }
  31710. }
  31711. p = p->parentComponent;
  31712. }
  31713. }
  31714. static void sendWheelEvent (Component& comp, BailOutChecker& checker, const MouseEvent& e,
  31715. const float wheelIncrementX, const float wheelIncrementY)
  31716. {
  31717. {
  31718. MouseListenerList* const list = comp.mouseListeners;
  31719. if (list != 0)
  31720. {
  31721. for (int i = list->listeners.size(); --i >= 0;)
  31722. {
  31723. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31724. if (checker.shouldBailOut())
  31725. return;
  31726. i = jmin (i, list->listeners.size());
  31727. }
  31728. }
  31729. }
  31730. Component* p = comp.parentComponent;
  31731. while (p != 0)
  31732. {
  31733. MouseListenerList* const list = p->mouseListeners;
  31734. if (list != 0 && list->numDeepMouseListeners > 0)
  31735. {
  31736. BailOutChecker2 checker2 (checker, p);
  31737. for (int i = list->numDeepMouseListeners; --i >= 0;)
  31738. {
  31739. list->listeners.getUnchecked(i)->mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  31740. if (checker2.shouldBailOut())
  31741. return;
  31742. i = jmin (i, list->numDeepMouseListeners);
  31743. }
  31744. }
  31745. p = p->parentComponent;
  31746. }
  31747. }
  31748. private:
  31749. Array <MouseListener*> listeners;
  31750. int numDeepMouseListeners;
  31751. class BailOutChecker2
  31752. {
  31753. public:
  31754. BailOutChecker2 (BailOutChecker& checker_, Component* const component)
  31755. : checker (checker_), safePointer (component)
  31756. {
  31757. }
  31758. bool shouldBailOut() const throw()
  31759. {
  31760. return checker.shouldBailOut() || safePointer == 0;
  31761. }
  31762. private:
  31763. BailOutChecker& checker;
  31764. const WeakReference<Component> safePointer;
  31765. JUCE_DECLARE_NON_COPYABLE (BailOutChecker2);
  31766. };
  31767. JUCE_DECLARE_NON_COPYABLE (MouseListenerList);
  31768. };
  31769. class Component::ComponentHelpers
  31770. {
  31771. public:
  31772. static void* runModalLoopCallback (void* userData)
  31773. {
  31774. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  31775. }
  31776. static const Identifier getColourPropertyId (const int colourId)
  31777. {
  31778. String s;
  31779. s.preallocateStorage (18);
  31780. s << "jcclr_" << String::toHexString (colourId);
  31781. return s;
  31782. }
  31783. static inline bool hitTest (Component& comp, const Point<int>& localPoint)
  31784. {
  31785. return isPositiveAndBelow (localPoint.getX(), comp.getWidth())
  31786. && isPositiveAndBelow (localPoint.getY(), comp.getHeight())
  31787. && comp.hitTest (localPoint.getX(), localPoint.getY());
  31788. }
  31789. static const Point<int> convertFromParentSpace (const Component& comp, const Point<int>& pointInParentSpace)
  31790. {
  31791. if (comp.affineTransform == 0)
  31792. return pointInParentSpace - comp.getPosition();
  31793. return pointInParentSpace.toFloat().transformedBy (comp.affineTransform->inverted()).toInt() - comp.getPosition();
  31794. }
  31795. static const Rectangle<int> convertFromParentSpace (const Component& comp, const Rectangle<int>& areaInParentSpace)
  31796. {
  31797. if (comp.affineTransform == 0)
  31798. return areaInParentSpace - comp.getPosition();
  31799. return areaInParentSpace.toFloat().transformed (comp.affineTransform->inverted()).getSmallestIntegerContainer() - comp.getPosition();
  31800. }
  31801. static const Point<int> convertToParentSpace (const Component& comp, const Point<int>& pointInLocalSpace)
  31802. {
  31803. if (comp.affineTransform == 0)
  31804. return pointInLocalSpace + comp.getPosition();
  31805. return (pointInLocalSpace + comp.getPosition()).toFloat().transformedBy (*comp.affineTransform).toInt();
  31806. }
  31807. static const Rectangle<int> convertToParentSpace (const Component& comp, const Rectangle<int>& areaInLocalSpace)
  31808. {
  31809. if (comp.affineTransform == 0)
  31810. return areaInLocalSpace + comp.getPosition();
  31811. return (areaInLocalSpace + comp.getPosition()).toFloat().transformed (*comp.affineTransform).getSmallestIntegerContainer();
  31812. }
  31813. template <typename Type>
  31814. static const Type convertFromDistantParentSpace (const Component* parent, const Component& target, Type coordInParent)
  31815. {
  31816. const Component* const directParent = target.getParentComponent();
  31817. jassert (directParent != 0);
  31818. if (directParent == parent)
  31819. return convertFromParentSpace (target, coordInParent);
  31820. return convertFromParentSpace (target, convertFromDistantParentSpace (parent, *directParent, coordInParent));
  31821. }
  31822. template <typename Type>
  31823. static const Type convertCoordinate (const Component* target, const Component* source, Type p)
  31824. {
  31825. while (source != 0)
  31826. {
  31827. if (source == target)
  31828. return p;
  31829. if (source->isParentOf (target))
  31830. return convertFromDistantParentSpace (source, *target, p);
  31831. if (source->isOnDesktop())
  31832. {
  31833. p = source->getPeer()->localToGlobal (p);
  31834. source = 0;
  31835. }
  31836. else
  31837. {
  31838. p = convertToParentSpace (*source, p);
  31839. source = source->getParentComponent();
  31840. }
  31841. }
  31842. jassert (source == 0);
  31843. if (target == 0)
  31844. return p;
  31845. const Component* const topLevelComp = target->getTopLevelComponent();
  31846. if (topLevelComp->isOnDesktop())
  31847. p = topLevelComp->getPeer()->globalToLocal (p);
  31848. else
  31849. p = convertFromParentSpace (*topLevelComp, p);
  31850. if (topLevelComp == target)
  31851. return p;
  31852. return convertFromDistantParentSpace (topLevelComp, *target, p);
  31853. }
  31854. static const Rectangle<int> getUnclippedArea (const Component& comp)
  31855. {
  31856. Rectangle<int> r (comp.getLocalBounds());
  31857. Component* const p = comp.getParentComponent();
  31858. if (p != 0)
  31859. r = r.getIntersection (convertFromParentSpace (comp, getUnclippedArea (*p)));
  31860. return r;
  31861. }
  31862. static void clipObscuredRegions (const Component& comp, Graphics& g, const Rectangle<int>& clipRect, const Point<int>& delta)
  31863. {
  31864. for (int i = comp.childComponentList.size(); --i >= 0;)
  31865. {
  31866. const Component& child = *comp.childComponentList.getUnchecked(i);
  31867. if (child.isVisible() && ! child.isTransformed())
  31868. {
  31869. const Rectangle<int> newClip (clipRect.getIntersection (child.bounds));
  31870. if (! newClip.isEmpty())
  31871. {
  31872. if (child.isOpaque())
  31873. {
  31874. g.excludeClipRegion (newClip + delta);
  31875. }
  31876. else
  31877. {
  31878. const Point<int> childPos (child.getPosition());
  31879. clipObscuredRegions (child, g, newClip - childPos, childPos + delta);
  31880. }
  31881. }
  31882. }
  31883. }
  31884. }
  31885. static void subtractObscuredRegions (const Component& comp, RectangleList& result,
  31886. const Point<int>& delta,
  31887. const Rectangle<int>& clipRect,
  31888. const Component* const compToAvoid)
  31889. {
  31890. for (int i = comp.childComponentList.size(); --i >= 0;)
  31891. {
  31892. const Component* const c = comp.childComponentList.getUnchecked(i);
  31893. if (c != compToAvoid && c->isVisible())
  31894. {
  31895. if (c->isOpaque())
  31896. {
  31897. Rectangle<int> childBounds (c->bounds.getIntersection (clipRect));
  31898. childBounds.translate (delta.getX(), delta.getY());
  31899. result.subtract (childBounds);
  31900. }
  31901. else
  31902. {
  31903. Rectangle<int> newClip (clipRect.getIntersection (c->bounds));
  31904. newClip.translate (-c->getX(), -c->getY());
  31905. subtractObscuredRegions (*c, result, c->getPosition() + delta,
  31906. newClip, compToAvoid);
  31907. }
  31908. }
  31909. }
  31910. }
  31911. static const Rectangle<int> getParentOrMainMonitorBounds (const Component& comp)
  31912. {
  31913. return comp.getParentComponent() != 0 ? comp.getParentComponent()->getLocalBounds()
  31914. : Desktop::getInstance().getMainMonitorArea();
  31915. }
  31916. };
  31917. Component::Component()
  31918. : parentComponent (0),
  31919. lookAndFeel (0),
  31920. effect (0),
  31921. componentFlags (0),
  31922. componentTransparency (0)
  31923. {
  31924. }
  31925. Component::Component (const String& name)
  31926. : componentName (name),
  31927. parentComponent (0),
  31928. lookAndFeel (0),
  31929. effect (0),
  31930. componentFlags (0),
  31931. componentTransparency (0)
  31932. {
  31933. }
  31934. Component::~Component()
  31935. {
  31936. #if ! JUCE_VC6 // (access to private union not allowed in VC6)
  31937. static_jassert (sizeof (flags) <= sizeof (componentFlags));
  31938. #endif
  31939. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31940. weakReferenceMaster.clear();
  31941. while (childComponentList.size() > 0)
  31942. removeChildComponent (childComponentList.size() - 1, false, true);
  31943. if (parentComponent != 0)
  31944. parentComponent->removeChildComponent (parentComponent->childComponentList.indexOf (this), true, false);
  31945. else if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31946. giveAwayFocus (currentlyFocusedComponent != this);
  31947. if (flags.hasHeavyweightPeerFlag)
  31948. removeFromDesktop();
  31949. // Something has added some children to this component during its destructor! Not a smart idea!
  31950. jassert (childComponentList.size() == 0);
  31951. }
  31952. const WeakReference<Component>::SharedRef& Component::getWeakReference()
  31953. {
  31954. return weakReferenceMaster (this);
  31955. }
  31956. void Component::setName (const String& name)
  31957. {
  31958. // if component methods are being called from threads other than the message
  31959. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31960. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31961. if (componentName != name)
  31962. {
  31963. componentName = name;
  31964. if (flags.hasHeavyweightPeerFlag)
  31965. {
  31966. ComponentPeer* const peer = getPeer();
  31967. jassert (peer != 0);
  31968. if (peer != 0)
  31969. peer->setTitle (name);
  31970. }
  31971. BailOutChecker checker (this);
  31972. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31973. }
  31974. }
  31975. void Component::setComponentID (const String& newID)
  31976. {
  31977. componentID = newID;
  31978. }
  31979. void Component::setVisible (bool shouldBeVisible)
  31980. {
  31981. if (flags.visibleFlag != shouldBeVisible)
  31982. {
  31983. // if component methods are being called from threads other than the message
  31984. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31985. CHECK_MESSAGE_MANAGER_IS_LOCKED
  31986. WeakReference<Component> safePointer (this);
  31987. flags.visibleFlag = shouldBeVisible;
  31988. internalRepaint (0, 0, getWidth(), getHeight());
  31989. sendFakeMouseMove();
  31990. if (! shouldBeVisible)
  31991. {
  31992. if (currentlyFocusedComponent == this || isParentOf (currentlyFocusedComponent))
  31993. {
  31994. if (parentComponent != 0)
  31995. parentComponent->grabKeyboardFocus();
  31996. else
  31997. giveAwayFocus (true);
  31998. }
  31999. }
  32000. if (safePointer != 0)
  32001. {
  32002. sendVisibilityChangeMessage();
  32003. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32004. {
  32005. ComponentPeer* const peer = getPeer();
  32006. jassert (peer != 0);
  32007. if (peer != 0)
  32008. {
  32009. peer->setVisible (shouldBeVisible);
  32010. internalHierarchyChanged();
  32011. }
  32012. }
  32013. }
  32014. }
  32015. }
  32016. void Component::visibilityChanged()
  32017. {
  32018. }
  32019. void Component::sendVisibilityChangeMessage()
  32020. {
  32021. BailOutChecker checker (this);
  32022. visibilityChanged();
  32023. if (! checker.shouldBailOut())
  32024. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32025. }
  32026. bool Component::isShowing() const
  32027. {
  32028. if (flags.visibleFlag)
  32029. {
  32030. if (parentComponent != 0)
  32031. {
  32032. return parentComponent->isShowing();
  32033. }
  32034. else
  32035. {
  32036. const ComponentPeer* const peer = getPeer();
  32037. return peer != 0 && ! peer->isMinimised();
  32038. }
  32039. }
  32040. return false;
  32041. }
  32042. void* Component::getWindowHandle() const
  32043. {
  32044. const ComponentPeer* const peer = getPeer();
  32045. if (peer != 0)
  32046. return peer->getNativeHandle();
  32047. return 0;
  32048. }
  32049. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32050. {
  32051. // if component methods are being called from threads other than the message
  32052. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32053. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32054. if (isOpaque())
  32055. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32056. else
  32057. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32058. int currentStyleFlags = 0;
  32059. // don't use getPeer(), so that we only get the peer that's specifically
  32060. // for this comp, and not for one of its parents.
  32061. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32062. if (peer != 0)
  32063. currentStyleFlags = peer->getStyleFlags();
  32064. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32065. {
  32066. WeakReference<Component> safePointer (this);
  32067. #if JUCE_LINUX
  32068. // it's wise to give the component a non-zero size before
  32069. // putting it on the desktop, as X windows get confused by this, and
  32070. // a (1, 1) minimum size is enforced here.
  32071. setSize (jmax (1, getWidth()),
  32072. jmax (1, getHeight()));
  32073. #endif
  32074. const Point<int> topLeft (getScreenPosition());
  32075. bool wasFullscreen = false;
  32076. bool wasMinimised = false;
  32077. ComponentBoundsConstrainer* currentConstainer = 0;
  32078. Rectangle<int> oldNonFullScreenBounds;
  32079. if (peer != 0)
  32080. {
  32081. wasFullscreen = peer->isFullScreen();
  32082. wasMinimised = peer->isMinimised();
  32083. currentConstainer = peer->getConstrainer();
  32084. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32085. removeFromDesktop();
  32086. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32087. }
  32088. if (parentComponent != 0)
  32089. parentComponent->removeChildComponent (this);
  32090. if (safePointer != 0)
  32091. {
  32092. flags.hasHeavyweightPeerFlag = true;
  32093. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32094. Desktop::getInstance().addDesktopComponent (this);
  32095. bounds.setPosition (topLeft);
  32096. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32097. peer->setVisible (isVisible());
  32098. if (wasFullscreen)
  32099. {
  32100. peer->setFullScreen (true);
  32101. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32102. }
  32103. if (wasMinimised)
  32104. peer->setMinimised (true);
  32105. if (isAlwaysOnTop())
  32106. peer->setAlwaysOnTop (true);
  32107. peer->setConstrainer (currentConstainer);
  32108. repaint();
  32109. }
  32110. internalHierarchyChanged();
  32111. }
  32112. }
  32113. void Component::removeFromDesktop()
  32114. {
  32115. // if component methods are being called from threads other than the message
  32116. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32117. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32118. if (flags.hasHeavyweightPeerFlag)
  32119. {
  32120. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32121. flags.hasHeavyweightPeerFlag = false;
  32122. jassert (peer != 0);
  32123. delete peer;
  32124. Desktop::getInstance().removeDesktopComponent (this);
  32125. }
  32126. }
  32127. bool Component::isOnDesktop() const throw()
  32128. {
  32129. return flags.hasHeavyweightPeerFlag;
  32130. }
  32131. void Component::userTriedToCloseWindow()
  32132. {
  32133. /* This means that the user's trying to get rid of your window with the 'close window' system
  32134. menu option (on windows) or possibly the task manager - you should really handle this
  32135. and delete or hide your component in an appropriate way.
  32136. If you want to ignore the event and don't want to trigger this assertion, just override
  32137. this method and do nothing.
  32138. */
  32139. jassertfalse;
  32140. }
  32141. void Component::minimisationStateChanged (bool)
  32142. {
  32143. }
  32144. void Component::setOpaque (const bool shouldBeOpaque)
  32145. {
  32146. if (shouldBeOpaque != flags.opaqueFlag)
  32147. {
  32148. flags.opaqueFlag = shouldBeOpaque;
  32149. if (flags.hasHeavyweightPeerFlag)
  32150. {
  32151. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32152. if (peer != 0)
  32153. {
  32154. // to make it recreate the heavyweight window
  32155. addToDesktop (peer->getStyleFlags());
  32156. }
  32157. }
  32158. repaint();
  32159. }
  32160. }
  32161. bool Component::isOpaque() const throw()
  32162. {
  32163. return flags.opaqueFlag;
  32164. }
  32165. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32166. {
  32167. if (shouldBeBuffered != flags.bufferToImageFlag)
  32168. {
  32169. bufferedImage = Image::null;
  32170. flags.bufferToImageFlag = shouldBeBuffered;
  32171. }
  32172. }
  32173. void Component::moveChildInternal (const int sourceIndex, const int destIndex)
  32174. {
  32175. if (sourceIndex != destIndex)
  32176. {
  32177. Component* const c = childComponentList.getUnchecked (sourceIndex);
  32178. jassert (c != 0);
  32179. c->repaintParent();
  32180. childComponentList.move (sourceIndex, destIndex);
  32181. sendFakeMouseMove();
  32182. internalChildrenChanged();
  32183. }
  32184. }
  32185. void Component::toFront (const bool setAsForeground)
  32186. {
  32187. // if component methods are being called from threads other than the message
  32188. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32189. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32190. if (flags.hasHeavyweightPeerFlag)
  32191. {
  32192. ComponentPeer* const peer = getPeer();
  32193. if (peer != 0)
  32194. {
  32195. peer->toFront (setAsForeground);
  32196. if (setAsForeground && ! hasKeyboardFocus (true))
  32197. grabKeyboardFocus();
  32198. }
  32199. }
  32200. else if (parentComponent != 0)
  32201. {
  32202. const Array<Component*>& childList = parentComponent->childComponentList;
  32203. if (childList.getLast() != this)
  32204. {
  32205. const int index = childList.indexOf (this);
  32206. if (index >= 0)
  32207. {
  32208. int insertIndex = -1;
  32209. if (! flags.alwaysOnTopFlag)
  32210. {
  32211. insertIndex = childList.size() - 1;
  32212. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32213. --insertIndex;
  32214. }
  32215. parentComponent->moveChildInternal (index, insertIndex);
  32216. }
  32217. }
  32218. if (setAsForeground)
  32219. {
  32220. internalBroughtToFront();
  32221. grabKeyboardFocus();
  32222. }
  32223. }
  32224. }
  32225. void Component::toBehind (Component* const other)
  32226. {
  32227. if (other != 0 && other != this)
  32228. {
  32229. // the two components must belong to the same parent..
  32230. jassert (parentComponent == other->parentComponent);
  32231. if (parentComponent != 0)
  32232. {
  32233. const Array<Component*>& childList = parentComponent->childComponentList;
  32234. const int index = childList.indexOf (this);
  32235. if (index >= 0 && childList [index + 1] != other)
  32236. {
  32237. int otherIndex = childList.indexOf (other);
  32238. if (otherIndex >= 0)
  32239. {
  32240. if (index < otherIndex)
  32241. --otherIndex;
  32242. parentComponent->moveChildInternal (index, otherIndex);
  32243. }
  32244. }
  32245. }
  32246. else if (isOnDesktop())
  32247. {
  32248. jassert (other->isOnDesktop());
  32249. if (other->isOnDesktop())
  32250. {
  32251. ComponentPeer* const us = getPeer();
  32252. ComponentPeer* const them = other->getPeer();
  32253. jassert (us != 0 && them != 0);
  32254. if (us != 0 && them != 0)
  32255. us->toBehind (them);
  32256. }
  32257. }
  32258. }
  32259. }
  32260. void Component::toBack()
  32261. {
  32262. if (isOnDesktop())
  32263. {
  32264. jassertfalse; //xxx need to add this to native window
  32265. }
  32266. else if (parentComponent != 0)
  32267. {
  32268. const Array<Component*>& childList = parentComponent->childComponentList;
  32269. if (childList.getFirst() != this)
  32270. {
  32271. const int index = childList.indexOf (this);
  32272. if (index > 0)
  32273. {
  32274. int insertIndex = 0;
  32275. if (flags.alwaysOnTopFlag)
  32276. while (insertIndex < childList.size() && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32277. ++insertIndex;
  32278. parentComponent->moveChildInternal (index, insertIndex);
  32279. }
  32280. }
  32281. }
  32282. }
  32283. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32284. {
  32285. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32286. {
  32287. flags.alwaysOnTopFlag = shouldStayOnTop;
  32288. if (isOnDesktop())
  32289. {
  32290. ComponentPeer* const peer = getPeer();
  32291. jassert (peer != 0);
  32292. if (peer != 0)
  32293. {
  32294. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32295. {
  32296. // some kinds of peer can't change their always-on-top status, so
  32297. // for these, we'll need to create a new window
  32298. const int oldFlags = peer->getStyleFlags();
  32299. removeFromDesktop();
  32300. addToDesktop (oldFlags);
  32301. }
  32302. }
  32303. }
  32304. if (shouldStayOnTop)
  32305. toFront (false);
  32306. internalHierarchyChanged();
  32307. }
  32308. }
  32309. bool Component::isAlwaysOnTop() const throw()
  32310. {
  32311. return flags.alwaysOnTopFlag;
  32312. }
  32313. int Component::proportionOfWidth (const float proportion) const throw()
  32314. {
  32315. return roundToInt (proportion * bounds.getWidth());
  32316. }
  32317. int Component::proportionOfHeight (const float proportion) const throw()
  32318. {
  32319. return roundToInt (proportion * bounds.getHeight());
  32320. }
  32321. int Component::getParentWidth() const throw()
  32322. {
  32323. return (parentComponent != 0) ? parentComponent->getWidth()
  32324. : getParentMonitorArea().getWidth();
  32325. }
  32326. int Component::getParentHeight() const throw()
  32327. {
  32328. return (parentComponent != 0) ? parentComponent->getHeight()
  32329. : getParentMonitorArea().getHeight();
  32330. }
  32331. int Component::getScreenX() const { return getScreenPosition().getX(); }
  32332. int Component::getScreenY() const { return getScreenPosition().getY(); }
  32333. const Point<int> Component::getScreenPosition() const { return localPointToGlobal (Point<int>()); }
  32334. const Rectangle<int> Component::getScreenBounds() const { return localAreaToGlobal (getLocalBounds()); }
  32335. const Point<int> Component::getLocalPoint (const Component* source, const Point<int>& point) const
  32336. {
  32337. return ComponentHelpers::convertCoordinate (this, source, point);
  32338. }
  32339. const Rectangle<int> Component::getLocalArea (const Component* source, const Rectangle<int>& area) const
  32340. {
  32341. return ComponentHelpers::convertCoordinate (this, source, area);
  32342. }
  32343. const Point<int> Component::localPointToGlobal (const Point<int>& point) const
  32344. {
  32345. return ComponentHelpers::convertCoordinate (0, this, point);
  32346. }
  32347. const Rectangle<int> Component::localAreaToGlobal (const Rectangle<int>& area) const
  32348. {
  32349. return ComponentHelpers::convertCoordinate (0, this, area);
  32350. }
  32351. /* Deprecated methods... */
  32352. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32353. {
  32354. return localPointToGlobal (relativePosition);
  32355. }
  32356. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32357. {
  32358. return getLocalPoint (0, screenPosition);
  32359. }
  32360. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32361. {
  32362. return targetComponent == 0 ? localPointToGlobal (positionRelativeToThis)
  32363. : targetComponent->getLocalPoint (this, positionRelativeToThis);
  32364. }
  32365. void Component::setBounds (const int x, const int y, int w, int h)
  32366. {
  32367. // if component methods are being called from threads other than the message
  32368. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32369. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32370. if (w < 0) w = 0;
  32371. if (h < 0) h = 0;
  32372. const bool wasResized = (getWidth() != w || getHeight() != h);
  32373. const bool wasMoved = (getX() != x || getY() != y);
  32374. #if JUCE_DEBUG
  32375. // It's a very bad idea to try to resize a window during its paint() method!
  32376. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32377. #endif
  32378. if (wasMoved || wasResized)
  32379. {
  32380. const bool showing = isShowing();
  32381. if (showing)
  32382. {
  32383. // send a fake mouse move to trigger enter/exit messages if needed..
  32384. sendFakeMouseMove();
  32385. if (! flags.hasHeavyweightPeerFlag)
  32386. repaintParent();
  32387. }
  32388. bounds.setBounds (x, y, w, h);
  32389. if (showing)
  32390. {
  32391. if (wasResized)
  32392. repaint();
  32393. else if (! flags.hasHeavyweightPeerFlag)
  32394. repaintParent();
  32395. }
  32396. if (flags.hasHeavyweightPeerFlag)
  32397. {
  32398. ComponentPeer* const peer = getPeer();
  32399. if (peer != 0)
  32400. {
  32401. if (wasMoved && wasResized)
  32402. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32403. else if (wasMoved)
  32404. peer->setPosition (getX(), getY());
  32405. else if (wasResized)
  32406. peer->setSize (getWidth(), getHeight());
  32407. }
  32408. }
  32409. sendMovedResizedMessages (wasMoved, wasResized);
  32410. }
  32411. }
  32412. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32413. {
  32414. BailOutChecker checker (this);
  32415. if (wasMoved)
  32416. {
  32417. moved();
  32418. if (checker.shouldBailOut())
  32419. return;
  32420. }
  32421. if (wasResized)
  32422. {
  32423. resized();
  32424. if (checker.shouldBailOut())
  32425. return;
  32426. for (int i = childComponentList.size(); --i >= 0;)
  32427. {
  32428. childComponentList.getUnchecked(i)->parentSizeChanged();
  32429. if (checker.shouldBailOut())
  32430. return;
  32431. i = jmin (i, childComponentList.size());
  32432. }
  32433. }
  32434. if (parentComponent != 0)
  32435. parentComponent->childBoundsChanged (this);
  32436. if (! checker.shouldBailOut())
  32437. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32438. *this, wasMoved, wasResized);
  32439. }
  32440. void Component::setSize (const int w, const int h)
  32441. {
  32442. setBounds (getX(), getY(), w, h);
  32443. }
  32444. void Component::setTopLeftPosition (const int x, const int y)
  32445. {
  32446. setBounds (x, y, getWidth(), getHeight());
  32447. }
  32448. void Component::setTopRightPosition (const int x, const int y)
  32449. {
  32450. setTopLeftPosition (x - getWidth(), y);
  32451. }
  32452. void Component::setBounds (const Rectangle<int>& r)
  32453. {
  32454. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32455. }
  32456. void Component::setBounds (const RelativeRectangle& newBounds)
  32457. {
  32458. newBounds.applyToComponent (*this);
  32459. }
  32460. void Component::setBoundsRelative (const float x, const float y,
  32461. const float w, const float h)
  32462. {
  32463. const int pw = getParentWidth();
  32464. const int ph = getParentHeight();
  32465. setBounds (roundToInt (x * pw),
  32466. roundToInt (y * ph),
  32467. roundToInt (w * pw),
  32468. roundToInt (h * ph));
  32469. }
  32470. void Component::setCentrePosition (const int x, const int y)
  32471. {
  32472. setTopLeftPosition (x - getWidth() / 2,
  32473. y - getHeight() / 2);
  32474. }
  32475. void Component::setCentreRelative (const float x, const float y)
  32476. {
  32477. setCentrePosition (roundToInt (getParentWidth() * x),
  32478. roundToInt (getParentHeight() * y));
  32479. }
  32480. void Component::centreWithSize (const int width, const int height)
  32481. {
  32482. const Rectangle<int> parentArea (ComponentHelpers::getParentOrMainMonitorBounds (*this));
  32483. setBounds (parentArea.getCentreX() - width / 2,
  32484. parentArea.getCentreY() - height / 2,
  32485. width, height);
  32486. }
  32487. void Component::setBoundsInset (const BorderSize<int>& borders)
  32488. {
  32489. setBounds (borders.subtractedFrom (ComponentHelpers::getParentOrMainMonitorBounds (*this)));
  32490. }
  32491. void Component::setBoundsToFit (int x, int y, int width, int height,
  32492. const Justification& justification,
  32493. const bool onlyReduceInSize)
  32494. {
  32495. // it's no good calling this method unless both the component and
  32496. // target rectangle have a finite size.
  32497. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32498. if (getWidth() > 0 && getHeight() > 0
  32499. && width > 0 && height > 0)
  32500. {
  32501. int newW, newH;
  32502. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32503. {
  32504. newW = getWidth();
  32505. newH = getHeight();
  32506. }
  32507. else
  32508. {
  32509. const double imageRatio = getHeight() / (double) getWidth();
  32510. const double targetRatio = height / (double) width;
  32511. if (imageRatio <= targetRatio)
  32512. {
  32513. newW = width;
  32514. newH = jmin (height, roundToInt (newW * imageRatio));
  32515. }
  32516. else
  32517. {
  32518. newH = height;
  32519. newW = jmin (width, roundToInt (newH / imageRatio));
  32520. }
  32521. }
  32522. if (newW > 0 && newH > 0)
  32523. setBounds (justification.appliedToRectangle (Rectangle<int> (0, 0, newW, newH),
  32524. Rectangle<int> (x, y, width, height)));
  32525. }
  32526. }
  32527. bool Component::isTransformed() const throw()
  32528. {
  32529. return affineTransform != 0;
  32530. }
  32531. void Component::setTransform (const AffineTransform& newTransform)
  32532. {
  32533. // If you pass in a transform with no inverse, the component will have no dimensions,
  32534. // and there will be all sorts of maths errors when converting coordinates.
  32535. jassert (! newTransform.isSingularity());
  32536. if (newTransform.isIdentity())
  32537. {
  32538. if (affineTransform != 0)
  32539. {
  32540. repaint();
  32541. affineTransform = 0;
  32542. repaint();
  32543. sendMovedResizedMessages (false, false);
  32544. }
  32545. }
  32546. else if (affineTransform == 0)
  32547. {
  32548. repaint();
  32549. affineTransform = new AffineTransform (newTransform);
  32550. repaint();
  32551. sendMovedResizedMessages (false, false);
  32552. }
  32553. else if (*affineTransform != newTransform)
  32554. {
  32555. repaint();
  32556. *affineTransform = newTransform;
  32557. repaint();
  32558. sendMovedResizedMessages (false, false);
  32559. }
  32560. }
  32561. const AffineTransform Component::getTransform() const
  32562. {
  32563. return affineTransform != 0 ? *affineTransform : AffineTransform::identity;
  32564. }
  32565. bool Component::hitTest (int x, int y)
  32566. {
  32567. if (! flags.ignoresMouseClicksFlag)
  32568. return true;
  32569. if (flags.allowChildMouseClicksFlag)
  32570. {
  32571. for (int i = getNumChildComponents(); --i >= 0;)
  32572. {
  32573. Component& child = *getChildComponent (i);
  32574. if (child.isVisible()
  32575. && ComponentHelpers::hitTest (child, ComponentHelpers::convertFromParentSpace (child, Point<int> (x, y))))
  32576. return true;
  32577. }
  32578. }
  32579. return false;
  32580. }
  32581. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32582. const bool allowClicksOnChildComponents) throw()
  32583. {
  32584. flags.ignoresMouseClicksFlag = ! allowClicks;
  32585. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32586. }
  32587. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32588. bool& allowsClicksOnChildComponents) const throw()
  32589. {
  32590. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32591. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32592. }
  32593. bool Component::contains (const Point<int>& point)
  32594. {
  32595. if (ComponentHelpers::hitTest (*this, point))
  32596. {
  32597. if (parentComponent != 0)
  32598. {
  32599. return parentComponent->contains (ComponentHelpers::convertToParentSpace (*this, point));
  32600. }
  32601. else if (flags.hasHeavyweightPeerFlag)
  32602. {
  32603. const ComponentPeer* const peer = getPeer();
  32604. if (peer != 0)
  32605. return peer->contains (point, true);
  32606. }
  32607. }
  32608. return false;
  32609. }
  32610. bool Component::reallyContains (const Point<int>& point, const bool returnTrueIfWithinAChild)
  32611. {
  32612. if (! contains (point))
  32613. return false;
  32614. Component* const top = getTopLevelComponent();
  32615. const Component* const compAtPosition = top->getComponentAt (top->getLocalPoint (this, point));
  32616. return (compAtPosition == this) || (returnTrueIfWithinAChild && isParentOf (compAtPosition));
  32617. }
  32618. Component* Component::getComponentAt (const Point<int>& position)
  32619. {
  32620. if (flags.visibleFlag && ComponentHelpers::hitTest (*this, position))
  32621. {
  32622. for (int i = childComponentList.size(); --i >= 0;)
  32623. {
  32624. Component* child = childComponentList.getUnchecked(i);
  32625. child = child->getComponentAt (ComponentHelpers::convertFromParentSpace (*child, position));
  32626. if (child != 0)
  32627. return child;
  32628. }
  32629. return this;
  32630. }
  32631. return 0;
  32632. }
  32633. Component* Component::getComponentAt (const int x, const int y)
  32634. {
  32635. return getComponentAt (Point<int> (x, y));
  32636. }
  32637. void Component::addChildComponent (Component* const child, int zOrder)
  32638. {
  32639. // if component methods are being called from threads other than the message
  32640. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32641. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32642. if (child != 0 && child->parentComponent != this)
  32643. {
  32644. if (child->parentComponent != 0)
  32645. child->parentComponent->removeChildComponent (child);
  32646. else
  32647. child->removeFromDesktop();
  32648. child->parentComponent = this;
  32649. if (child->isVisible())
  32650. child->repaintParent();
  32651. if (! child->isAlwaysOnTop())
  32652. {
  32653. if (zOrder < 0 || zOrder > childComponentList.size())
  32654. zOrder = childComponentList.size();
  32655. while (zOrder > 0)
  32656. {
  32657. if (! childComponentList.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32658. break;
  32659. --zOrder;
  32660. }
  32661. }
  32662. childComponentList.insert (zOrder, child);
  32663. child->internalHierarchyChanged();
  32664. internalChildrenChanged();
  32665. }
  32666. }
  32667. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32668. {
  32669. if (child != 0)
  32670. {
  32671. child->setVisible (true);
  32672. addChildComponent (child, zOrder);
  32673. }
  32674. }
  32675. void Component::removeChildComponent (Component* const child)
  32676. {
  32677. removeChildComponent (childComponentList.indexOf (child), true, true);
  32678. }
  32679. Component* Component::removeChildComponent (const int index)
  32680. {
  32681. return removeChildComponent (index, true, true);
  32682. }
  32683. Component* Component::removeChildComponent (const int index, bool sendParentEvents, const bool sendChildEvents)
  32684. {
  32685. // if component methods are being called from threads other than the message
  32686. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32687. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32688. Component* const child = childComponentList [index];
  32689. if (child != 0)
  32690. {
  32691. sendParentEvents = sendParentEvents && child->isShowing();
  32692. if (sendParentEvents)
  32693. {
  32694. sendFakeMouseMove();
  32695. child->repaintParent();
  32696. }
  32697. childComponentList.remove (index);
  32698. child->parentComponent = 0;
  32699. // (NB: there are obscure situations where child->isShowing() = false, but it still has the focus)
  32700. if (currentlyFocusedComponent == child || child->isParentOf (currentlyFocusedComponent))
  32701. {
  32702. if (sendParentEvents)
  32703. {
  32704. const WeakReference<Component> thisPointer (this);
  32705. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32706. if (thisPointer == 0)
  32707. return child;
  32708. grabKeyboardFocus();
  32709. }
  32710. else
  32711. {
  32712. giveAwayFocus (sendChildEvents || currentlyFocusedComponent != child);
  32713. }
  32714. }
  32715. if (sendChildEvents)
  32716. child->internalHierarchyChanged();
  32717. if (sendParentEvents)
  32718. internalChildrenChanged();
  32719. }
  32720. return child;
  32721. }
  32722. void Component::removeAllChildren()
  32723. {
  32724. while (childComponentList.size() > 0)
  32725. removeChildComponent (childComponentList.size() - 1);
  32726. }
  32727. void Component::deleteAllChildren()
  32728. {
  32729. while (childComponentList.size() > 0)
  32730. delete (removeChildComponent (childComponentList.size() - 1));
  32731. }
  32732. int Component::getNumChildComponents() const throw()
  32733. {
  32734. return childComponentList.size();
  32735. }
  32736. Component* Component::getChildComponent (const int index) const throw()
  32737. {
  32738. return childComponentList [index];
  32739. }
  32740. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32741. {
  32742. return childComponentList.indexOf (const_cast <Component*> (child));
  32743. }
  32744. Component* Component::getTopLevelComponent() const throw()
  32745. {
  32746. const Component* comp = this;
  32747. while (comp->parentComponent != 0)
  32748. comp = comp->parentComponent;
  32749. return const_cast <Component*> (comp);
  32750. }
  32751. bool Component::isParentOf (const Component* possibleChild) const throw()
  32752. {
  32753. while (possibleChild != 0)
  32754. {
  32755. possibleChild = possibleChild->parentComponent;
  32756. if (possibleChild == this)
  32757. return true;
  32758. }
  32759. return false;
  32760. }
  32761. void Component::parentHierarchyChanged()
  32762. {
  32763. }
  32764. void Component::childrenChanged()
  32765. {
  32766. }
  32767. void Component::internalChildrenChanged()
  32768. {
  32769. if (componentListeners.isEmpty())
  32770. {
  32771. childrenChanged();
  32772. }
  32773. else
  32774. {
  32775. BailOutChecker checker (this);
  32776. childrenChanged();
  32777. if (! checker.shouldBailOut())
  32778. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32779. }
  32780. }
  32781. void Component::internalHierarchyChanged()
  32782. {
  32783. BailOutChecker checker (this);
  32784. parentHierarchyChanged();
  32785. if (checker.shouldBailOut())
  32786. return;
  32787. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32788. if (checker.shouldBailOut())
  32789. return;
  32790. for (int i = childComponentList.size(); --i >= 0;)
  32791. {
  32792. childComponentList.getUnchecked (i)->internalHierarchyChanged();
  32793. if (checker.shouldBailOut())
  32794. {
  32795. // you really shouldn't delete the parent component during a callback telling you
  32796. // that it's changed..
  32797. jassertfalse;
  32798. return;
  32799. }
  32800. i = jmin (i, childComponentList.size());
  32801. }
  32802. }
  32803. int Component::runModalLoop()
  32804. {
  32805. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32806. {
  32807. // use a callback so this can be called from non-gui threads
  32808. return (int) (pointer_sized_int) MessageManager::getInstance()
  32809. ->callFunctionOnMessageThread (&ComponentHelpers::runModalLoopCallback, this);
  32810. }
  32811. if (! isCurrentlyModal())
  32812. enterModalState (true);
  32813. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32814. }
  32815. void Component::enterModalState (const bool shouldTakeKeyboardFocus, ModalComponentManager::Callback* const callback)
  32816. {
  32817. // if component methods are being called from threads other than the message
  32818. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32819. CHECK_MESSAGE_MANAGER_IS_LOCKED
  32820. // Check for an attempt to make a component modal when it already is!
  32821. // This can cause nasty problems..
  32822. jassert (! flags.currentlyModalFlag);
  32823. if (! isCurrentlyModal())
  32824. {
  32825. ModalComponentManager::getInstance()->startModal (this, callback);
  32826. flags.currentlyModalFlag = true;
  32827. setVisible (true);
  32828. if (shouldTakeKeyboardFocus)
  32829. grabKeyboardFocus();
  32830. }
  32831. }
  32832. void Component::exitModalState (const int returnValue)
  32833. {
  32834. if (flags.currentlyModalFlag)
  32835. {
  32836. if (MessageManager::getInstance()->isThisTheMessageThread())
  32837. {
  32838. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32839. flags.currentlyModalFlag = false;
  32840. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  32841. }
  32842. else
  32843. {
  32844. class ExitModalStateMessage : public CallbackMessage
  32845. {
  32846. public:
  32847. ExitModalStateMessage (Component* const target_, const int result_)
  32848. : target (target_), result (result_) {}
  32849. void messageCallback()
  32850. {
  32851. if (target.get() != 0) // (get() required for VS2003 bug)
  32852. target->exitModalState (result);
  32853. }
  32854. private:
  32855. WeakReference<Component> target;
  32856. int result;
  32857. };
  32858. (new ExitModalStateMessage (this, returnValue))->post();
  32859. }
  32860. }
  32861. }
  32862. bool Component::isCurrentlyModal() const throw()
  32863. {
  32864. return flags.currentlyModalFlag
  32865. && getCurrentlyModalComponent() == this;
  32866. }
  32867. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32868. {
  32869. Component* const mc = getCurrentlyModalComponent();
  32870. return mc != 0
  32871. && mc != this
  32872. && (! mc->isParentOf (this))
  32873. && ! mc->canModalEventBeSentToComponent (this);
  32874. }
  32875. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32876. {
  32877. return ModalComponentManager::getInstance()->getNumModalComponents();
  32878. }
  32879. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32880. {
  32881. return ModalComponentManager::getInstance()->getModalComponent (index);
  32882. }
  32883. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  32884. {
  32885. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  32886. }
  32887. bool Component::isBroughtToFrontOnMouseClick() const throw()
  32888. {
  32889. return flags.bringToFrontOnClickFlag;
  32890. }
  32891. void Component::setMouseCursor (const MouseCursor& newCursor)
  32892. {
  32893. if (cursor != newCursor)
  32894. {
  32895. cursor = newCursor;
  32896. if (flags.visibleFlag)
  32897. updateMouseCursor();
  32898. }
  32899. }
  32900. const MouseCursor Component::getMouseCursor()
  32901. {
  32902. return cursor;
  32903. }
  32904. void Component::updateMouseCursor() const
  32905. {
  32906. sendFakeMouseMove();
  32907. }
  32908. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  32909. {
  32910. flags.repaintOnMouseActivityFlag = shouldRepaint;
  32911. }
  32912. void Component::setAlpha (const float newAlpha)
  32913. {
  32914. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  32915. if (componentTransparency != newIntAlpha)
  32916. {
  32917. componentTransparency = newIntAlpha;
  32918. if (flags.hasHeavyweightPeerFlag)
  32919. {
  32920. ComponentPeer* const peer = getPeer();
  32921. if (peer != 0)
  32922. peer->setAlpha (newAlpha);
  32923. }
  32924. else
  32925. {
  32926. repaint();
  32927. }
  32928. }
  32929. }
  32930. float Component::getAlpha() const
  32931. {
  32932. return (255 - componentTransparency) / 255.0f;
  32933. }
  32934. void Component::repaintParent()
  32935. {
  32936. if (flags.visibleFlag)
  32937. internalRepaint (0, 0, getWidth(), getHeight());
  32938. }
  32939. void Component::repaint()
  32940. {
  32941. repaint (0, 0, getWidth(), getHeight());
  32942. }
  32943. void Component::repaint (const int x, const int y,
  32944. const int w, const int h)
  32945. {
  32946. bufferedImage = Image::null;
  32947. if (flags.visibleFlag)
  32948. internalRepaint (x, y, w, h);
  32949. }
  32950. void Component::repaint (const Rectangle<int>& area)
  32951. {
  32952. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  32953. }
  32954. void Component::internalRepaint (int x, int y, int w, int h)
  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. if (x < 0)
  32960. {
  32961. w += x;
  32962. x = 0;
  32963. }
  32964. if (x + w > getWidth())
  32965. w = getWidth() - x;
  32966. if (w > 0)
  32967. {
  32968. if (y < 0)
  32969. {
  32970. h += y;
  32971. y = 0;
  32972. }
  32973. if (y + h > getHeight())
  32974. h = getHeight() - y;
  32975. if (h > 0)
  32976. {
  32977. if (parentComponent != 0)
  32978. {
  32979. if (parentComponent->flags.visibleFlag)
  32980. {
  32981. if (affineTransform == 0)
  32982. {
  32983. parentComponent->internalRepaint (x + getX(), y + getY(), w, h);
  32984. }
  32985. else
  32986. {
  32987. const Rectangle<int> r (ComponentHelpers::convertToParentSpace (*this, Rectangle<int> (x, y, w, h)));
  32988. parentComponent->internalRepaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  32989. }
  32990. }
  32991. }
  32992. else if (flags.hasHeavyweightPeerFlag)
  32993. {
  32994. ComponentPeer* const peer = getPeer();
  32995. if (peer != 0)
  32996. peer->repaint (Rectangle<int> (x, y, w, h));
  32997. }
  32998. }
  32999. }
  33000. }
  33001. void Component::paintComponent (Graphics& g)
  33002. {
  33003. if (flags.bufferToImageFlag)
  33004. {
  33005. if (bufferedImage.isNull())
  33006. {
  33007. bufferedImage = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33008. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33009. Graphics imG (bufferedImage);
  33010. paint (imG);
  33011. }
  33012. g.setColour (Colours::black.withAlpha (getAlpha()));
  33013. g.drawImageAt (bufferedImage, 0, 0);
  33014. }
  33015. else
  33016. {
  33017. paint (g);
  33018. }
  33019. }
  33020. void Component::paintWithinParentContext (Graphics& g)
  33021. {
  33022. g.setOrigin (getX(), getY());
  33023. paintEntireComponent (g, false);
  33024. }
  33025. void Component::paintComponentAndChildren (Graphics& g)
  33026. {
  33027. const Rectangle<int> clipBounds (g.getClipBounds());
  33028. if (flags.dontClipGraphicsFlag)
  33029. {
  33030. paintComponent (g);
  33031. }
  33032. else
  33033. {
  33034. g.saveState();
  33035. ComponentHelpers::clipObscuredRegions (*this, g, clipBounds, Point<int>());
  33036. if (! g.isClipEmpty())
  33037. paintComponent (g);
  33038. g.restoreState();
  33039. }
  33040. for (int i = 0; i < childComponentList.size(); ++i)
  33041. {
  33042. Component& child = *childComponentList.getUnchecked (i);
  33043. if (child.isVisible())
  33044. {
  33045. if (child.affineTransform != 0)
  33046. {
  33047. g.saveState();
  33048. g.addTransform (*child.affineTransform);
  33049. if ((child.flags.dontClipGraphicsFlag && ! g.isClipEmpty()) || g.reduceClipRegion (child.getBounds()))
  33050. child.paintWithinParentContext (g);
  33051. g.restoreState();
  33052. }
  33053. else if (clipBounds.intersects (child.getBounds()))
  33054. {
  33055. g.saveState();
  33056. if (child.flags.dontClipGraphicsFlag)
  33057. {
  33058. child.paintWithinParentContext (g);
  33059. }
  33060. else if (g.reduceClipRegion (child.getBounds()))
  33061. {
  33062. bool nothingClipped = true;
  33063. for (int j = i + 1; j < childComponentList.size(); ++j)
  33064. {
  33065. const Component& sibling = *childComponentList.getUnchecked (j);
  33066. if (sibling.flags.opaqueFlag && sibling.isVisible() && sibling.affineTransform == 0)
  33067. {
  33068. nothingClipped = false;
  33069. g.excludeClipRegion (sibling.getBounds());
  33070. }
  33071. }
  33072. if (nothingClipped || ! g.isClipEmpty())
  33073. child.paintWithinParentContext (g);
  33074. }
  33075. g.restoreState();
  33076. }
  33077. }
  33078. }
  33079. g.saveState();
  33080. paintOverChildren (g);
  33081. g.restoreState();
  33082. }
  33083. void Component::paintEntireComponent (Graphics& g, const bool ignoreAlphaLevel)
  33084. {
  33085. jassert (! g.isClipEmpty());
  33086. #if JUCE_DEBUG
  33087. flags.isInsidePaintCall = true;
  33088. #endif
  33089. if (effect != 0)
  33090. {
  33091. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33092. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33093. {
  33094. Graphics g2 (effectImage);
  33095. paintComponentAndChildren (g2);
  33096. }
  33097. effect->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33098. }
  33099. else if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33100. {
  33101. if (componentTransparency < 255)
  33102. {
  33103. g.beginTransparencyLayer (getAlpha());
  33104. paintComponentAndChildren (g);
  33105. g.endTransparencyLayer();
  33106. }
  33107. }
  33108. else
  33109. {
  33110. paintComponentAndChildren (g);
  33111. }
  33112. #if JUCE_DEBUG
  33113. flags.isInsidePaintCall = false;
  33114. #endif
  33115. }
  33116. void Component::setPaintingIsUnclipped (const bool shouldPaintWithoutClipping) throw()
  33117. {
  33118. flags.dontClipGraphicsFlag = shouldPaintWithoutClipping;
  33119. }
  33120. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33121. const bool clipImageToComponentBounds)
  33122. {
  33123. Rectangle<int> r (areaToGrab);
  33124. if (clipImageToComponentBounds)
  33125. r = r.getIntersection (getLocalBounds());
  33126. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33127. jmax (1, r.getWidth()),
  33128. jmax (1, r.getHeight()),
  33129. true);
  33130. Graphics imageContext (componentImage);
  33131. imageContext.setOrigin (-r.getX(), -r.getY());
  33132. paintEntireComponent (imageContext, true);
  33133. return componentImage;
  33134. }
  33135. void Component::setComponentEffect (ImageEffectFilter* const newEffect)
  33136. {
  33137. if (effect != newEffect)
  33138. {
  33139. effect = newEffect;
  33140. repaint();
  33141. }
  33142. }
  33143. LookAndFeel& Component::getLookAndFeel() const throw()
  33144. {
  33145. const Component* c = this;
  33146. do
  33147. {
  33148. if (c->lookAndFeel != 0)
  33149. return *(c->lookAndFeel);
  33150. c = c->parentComponent;
  33151. }
  33152. while (c != 0);
  33153. return LookAndFeel::getDefaultLookAndFeel();
  33154. }
  33155. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33156. {
  33157. if (lookAndFeel != newLookAndFeel)
  33158. {
  33159. lookAndFeel = newLookAndFeel;
  33160. sendLookAndFeelChange();
  33161. }
  33162. }
  33163. void Component::lookAndFeelChanged()
  33164. {
  33165. }
  33166. void Component::sendLookAndFeelChange()
  33167. {
  33168. repaint();
  33169. WeakReference<Component> safePointer (this);
  33170. lookAndFeelChanged();
  33171. if (safePointer != 0)
  33172. {
  33173. for (int i = childComponentList.size(); --i >= 0;)
  33174. {
  33175. childComponentList.getUnchecked (i)->sendLookAndFeelChange();
  33176. if (safePointer == 0)
  33177. return;
  33178. i = jmin (i, childComponentList.size());
  33179. }
  33180. }
  33181. }
  33182. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33183. {
  33184. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33185. if (v != 0)
  33186. return Colour ((int) *v);
  33187. if (inheritFromParent && parentComponent != 0)
  33188. return parentComponent->findColour (colourId, true);
  33189. return getLookAndFeel().findColour (colourId);
  33190. }
  33191. bool Component::isColourSpecified (const int colourId) const
  33192. {
  33193. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33194. }
  33195. void Component::removeColour (const int colourId)
  33196. {
  33197. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33198. colourChanged();
  33199. }
  33200. void Component::setColour (const int colourId, const Colour& colour)
  33201. {
  33202. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33203. colourChanged();
  33204. }
  33205. void Component::copyAllExplicitColoursTo (Component& target) const
  33206. {
  33207. bool changed = false;
  33208. for (int i = properties.size(); --i >= 0;)
  33209. {
  33210. const Identifier name (properties.getName(i));
  33211. if (name.toString().startsWith ("jcclr_"))
  33212. if (target.properties.set (name, properties [name]))
  33213. changed = true;
  33214. }
  33215. if (changed)
  33216. target.colourChanged();
  33217. }
  33218. void Component::colourChanged()
  33219. {
  33220. }
  33221. MarkerList* Component::getMarkers (bool /*xAxis*/)
  33222. {
  33223. return 0;
  33224. }
  33225. Component::Positioner::Positioner (Component& component_) throw()
  33226. : component (component_)
  33227. {
  33228. }
  33229. Component::Positioner* Component::getPositioner() const throw()
  33230. {
  33231. return positioner;
  33232. }
  33233. void Component::setPositioner (Positioner* newPositioner)
  33234. {
  33235. // You can only assign a positioner to the component that it was created for!
  33236. jassert (newPositioner == 0 || this == &(newPositioner->getComponent()));
  33237. positioner = newPositioner;
  33238. }
  33239. const Rectangle<int> Component::getLocalBounds() const throw()
  33240. {
  33241. return Rectangle<int> (getWidth(), getHeight());
  33242. }
  33243. const Rectangle<int> Component::getBoundsInParent() const throw()
  33244. {
  33245. return affineTransform == 0 ? bounds
  33246. : bounds.toFloat().transformed (*affineTransform).getSmallestIntegerContainer();
  33247. }
  33248. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33249. {
  33250. result.clear();
  33251. const Rectangle<int> unclipped (ComponentHelpers::getUnclippedArea (*this));
  33252. if (! unclipped.isEmpty())
  33253. {
  33254. result.add (unclipped);
  33255. if (includeSiblings)
  33256. {
  33257. const Component* const c = getTopLevelComponent();
  33258. ComponentHelpers::subtractObscuredRegions (*c, result, getLocalPoint (c, Point<int>()),
  33259. c->getLocalBounds(), this);
  33260. }
  33261. ComponentHelpers::subtractObscuredRegions (*this, result, Point<int>(), unclipped, 0);
  33262. result.consolidate();
  33263. }
  33264. }
  33265. void Component::mouseEnter (const MouseEvent&)
  33266. {
  33267. // base class does nothing
  33268. }
  33269. void Component::mouseExit (const MouseEvent&)
  33270. {
  33271. // base class does nothing
  33272. }
  33273. void Component::mouseDown (const MouseEvent&)
  33274. {
  33275. // base class does nothing
  33276. }
  33277. void Component::mouseUp (const MouseEvent&)
  33278. {
  33279. // base class does nothing
  33280. }
  33281. void Component::mouseDrag (const MouseEvent&)
  33282. {
  33283. // base class does nothing
  33284. }
  33285. void Component::mouseMove (const MouseEvent&)
  33286. {
  33287. // base class does nothing
  33288. }
  33289. void Component::mouseDoubleClick (const MouseEvent&)
  33290. {
  33291. // base class does nothing
  33292. }
  33293. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33294. {
  33295. // the base class just passes this event up to its parent..
  33296. if (parentComponent != 0)
  33297. parentComponent->mouseWheelMove (e.getEventRelativeTo (parentComponent),
  33298. wheelIncrementX, wheelIncrementY);
  33299. }
  33300. void Component::resized()
  33301. {
  33302. // base class does nothing
  33303. }
  33304. void Component::moved()
  33305. {
  33306. // base class does nothing
  33307. }
  33308. void Component::childBoundsChanged (Component*)
  33309. {
  33310. // base class does nothing
  33311. }
  33312. void Component::parentSizeChanged()
  33313. {
  33314. // base class does nothing
  33315. }
  33316. void Component::addComponentListener (ComponentListener* const newListener)
  33317. {
  33318. // if component methods are being called from threads other than the message
  33319. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33320. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33321. componentListeners.add (newListener);
  33322. }
  33323. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33324. {
  33325. componentListeners.remove (listenerToRemove);
  33326. }
  33327. void Component::inputAttemptWhenModal()
  33328. {
  33329. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33330. getLookAndFeel().playAlertSound();
  33331. }
  33332. bool Component::canModalEventBeSentToComponent (const Component*)
  33333. {
  33334. return false;
  33335. }
  33336. void Component::internalModalInputAttempt()
  33337. {
  33338. Component* const current = getCurrentlyModalComponent();
  33339. if (current != 0)
  33340. current->inputAttemptWhenModal();
  33341. }
  33342. void Component::paint (Graphics&)
  33343. {
  33344. // all painting is done in the subclasses
  33345. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33346. }
  33347. void Component::paintOverChildren (Graphics&)
  33348. {
  33349. // all painting is done in the subclasses
  33350. }
  33351. void Component::postCommandMessage (const int commandId)
  33352. {
  33353. class CustomCommandMessage : public CallbackMessage
  33354. {
  33355. public:
  33356. CustomCommandMessage (Component* const target_, const int commandId_)
  33357. : target (target_), commandId (commandId_) {}
  33358. void messageCallback()
  33359. {
  33360. if (target.get() != 0) // (get() required for VS2003 bug)
  33361. target->handleCommandMessage (commandId);
  33362. }
  33363. private:
  33364. WeakReference<Component> target;
  33365. int commandId;
  33366. };
  33367. (new CustomCommandMessage (this, commandId))->post();
  33368. }
  33369. void Component::handleCommandMessage (int)
  33370. {
  33371. // used by subclasses
  33372. }
  33373. void Component::addMouseListener (MouseListener* const newListener,
  33374. const bool wantsEventsForAllNestedChildComponents)
  33375. {
  33376. // if component methods are being called from threads other than the message
  33377. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33378. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33379. // If you register a component as a mouselistener for itself, it'll receive all the events
  33380. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33381. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33382. if (mouseListeners == 0)
  33383. mouseListeners = new MouseListenerList();
  33384. mouseListeners->addListener (newListener, wantsEventsForAllNestedChildComponents);
  33385. }
  33386. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33387. {
  33388. // if component methods are being called from threads other than the message
  33389. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33390. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33391. if (mouseListeners != 0)
  33392. mouseListeners->removeListener (listenerToRemove);
  33393. }
  33394. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33395. {
  33396. if (isCurrentlyBlockedByAnotherModalComponent())
  33397. {
  33398. // if something else is modal, always just show a normal mouse cursor
  33399. source.showMouseCursor (MouseCursor::NormalCursor);
  33400. return;
  33401. }
  33402. if (! flags.mouseInsideFlag)
  33403. {
  33404. flags.mouseInsideFlag = true;
  33405. flags.mouseOverFlag = true;
  33406. flags.mouseDownFlag = false;
  33407. BailOutChecker checker (this);
  33408. if (flags.repaintOnMouseActivityFlag)
  33409. repaint();
  33410. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33411. this, this, time, relativePos, time, 0, false);
  33412. mouseEnter (me);
  33413. if (checker.shouldBailOut())
  33414. return;
  33415. Desktop& desktop = Desktop::getInstance();
  33416. desktop.resetTimer();
  33417. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33418. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseEnter, me);
  33419. }
  33420. }
  33421. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33422. {
  33423. BailOutChecker checker (this);
  33424. if (flags.mouseDownFlag)
  33425. {
  33426. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33427. if (checker.shouldBailOut())
  33428. return;
  33429. }
  33430. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33431. {
  33432. flags.mouseInsideFlag = false;
  33433. flags.mouseOverFlag = false;
  33434. flags.mouseDownFlag = false;
  33435. if (flags.repaintOnMouseActivityFlag)
  33436. repaint();
  33437. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33438. this, this, time, relativePos, time, 0, false);
  33439. mouseExit (me);
  33440. if (checker.shouldBailOut())
  33441. return;
  33442. Desktop& desktop = Desktop::getInstance();
  33443. desktop.resetTimer();
  33444. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33445. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseExit, me);
  33446. }
  33447. }
  33448. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33449. {
  33450. Desktop& desktop = Desktop::getInstance();
  33451. BailOutChecker checker (this);
  33452. if (isCurrentlyBlockedByAnotherModalComponent())
  33453. {
  33454. internalModalInputAttempt();
  33455. if (checker.shouldBailOut())
  33456. return;
  33457. // If processing the input attempt has exited the modal loop, we'll allow the event
  33458. // to be delivered..
  33459. if (isCurrentlyBlockedByAnotherModalComponent())
  33460. {
  33461. // allow blocked mouse-events to go to global listeners..
  33462. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33463. this, this, time, relativePos, time,
  33464. source.getNumberOfMultipleClicks(), false);
  33465. desktop.resetTimer();
  33466. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33467. return;
  33468. }
  33469. }
  33470. {
  33471. Component* c = this;
  33472. while (c != 0)
  33473. {
  33474. if (c->isBroughtToFrontOnMouseClick())
  33475. {
  33476. c->toFront (true);
  33477. if (checker.shouldBailOut())
  33478. return;
  33479. }
  33480. c = c->parentComponent;
  33481. }
  33482. }
  33483. if (! flags.dontFocusOnMouseClickFlag)
  33484. {
  33485. grabFocusInternal (focusChangedByMouseClick);
  33486. if (checker.shouldBailOut())
  33487. return;
  33488. }
  33489. flags.mouseDownFlag = true;
  33490. flags.mouseOverFlag = true;
  33491. if (flags.repaintOnMouseActivityFlag)
  33492. repaint();
  33493. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33494. this, this, time, relativePos, time,
  33495. source.getNumberOfMultipleClicks(), false);
  33496. mouseDown (me);
  33497. if (checker.shouldBailOut())
  33498. return;
  33499. desktop.resetTimer();
  33500. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33501. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDown, me);
  33502. }
  33503. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33504. {
  33505. if (flags.mouseDownFlag)
  33506. {
  33507. flags.mouseDownFlag = false;
  33508. BailOutChecker checker (this);
  33509. if (flags.repaintOnMouseActivityFlag)
  33510. repaint();
  33511. const MouseEvent me (source, relativePos,
  33512. oldModifiers, this, this, time,
  33513. getLocalPoint (0, source.getLastMouseDownPosition()),
  33514. source.getLastMouseDownTime(),
  33515. source.getNumberOfMultipleClicks(),
  33516. source.hasMouseMovedSignificantlySincePressed());
  33517. mouseUp (me);
  33518. if (checker.shouldBailOut())
  33519. return;
  33520. Desktop& desktop = Desktop::getInstance();
  33521. desktop.resetTimer();
  33522. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33523. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseUp, me);
  33524. if (checker.shouldBailOut())
  33525. return;
  33526. // check for double-click
  33527. if (me.getNumberOfClicks() >= 2)
  33528. {
  33529. mouseDoubleClick (me);
  33530. if (checker.shouldBailOut())
  33531. return;
  33532. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33533. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDoubleClick, me);
  33534. }
  33535. }
  33536. }
  33537. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33538. {
  33539. if (flags.mouseDownFlag)
  33540. {
  33541. flags.mouseOverFlag = reallyContains (relativePos, false);
  33542. BailOutChecker checker (this);
  33543. const MouseEvent me (source, relativePos,
  33544. source.getCurrentModifiers(), this, this, time,
  33545. getLocalPoint (0, source.getLastMouseDownPosition()),
  33546. source.getLastMouseDownTime(),
  33547. source.getNumberOfMultipleClicks(),
  33548. source.hasMouseMovedSignificantlySincePressed());
  33549. mouseDrag (me);
  33550. if (checker.shouldBailOut())
  33551. return;
  33552. Desktop& desktop = Desktop::getInstance();
  33553. desktop.resetTimer();
  33554. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33555. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseDrag, me);
  33556. }
  33557. }
  33558. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33559. {
  33560. Desktop& desktop = Desktop::getInstance();
  33561. BailOutChecker checker (this);
  33562. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33563. this, this, time, relativePos, time, 0, false);
  33564. if (isCurrentlyBlockedByAnotherModalComponent())
  33565. {
  33566. // allow blocked mouse-events to go to global listeners..
  33567. desktop.sendMouseMove();
  33568. }
  33569. else
  33570. {
  33571. flags.mouseOverFlag = true;
  33572. mouseMove (me);
  33573. if (checker.shouldBailOut())
  33574. return;
  33575. desktop.resetTimer();
  33576. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33577. MouseListenerList::sendMouseEvent (*this, checker, &MouseListener::mouseMove, me);
  33578. }
  33579. }
  33580. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33581. const Time& time, const float amountX, const float amountY)
  33582. {
  33583. Desktop& desktop = Desktop::getInstance();
  33584. BailOutChecker checker (this);
  33585. const float wheelIncrementX = amountX / 256.0f;
  33586. const float wheelIncrementY = amountY / 256.0f;
  33587. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33588. this, this, time, relativePos, time, 0, false);
  33589. if (isCurrentlyBlockedByAnotherModalComponent())
  33590. {
  33591. // allow blocked mouse-events to go to global listeners..
  33592. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33593. }
  33594. else
  33595. {
  33596. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33597. if (checker.shouldBailOut())
  33598. return;
  33599. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33600. if (! checker.shouldBailOut())
  33601. MouseListenerList::sendWheelEvent (*this, checker, me, wheelIncrementX, wheelIncrementY);
  33602. }
  33603. }
  33604. void Component::sendFakeMouseMove() const
  33605. {
  33606. MouseInputSource& mainMouse = Desktop::getInstance().getMainMouseSource();
  33607. if (! mainMouse.isDragging())
  33608. mainMouse.triggerFakeMove();
  33609. }
  33610. void Component::beginDragAutoRepeat (const int interval)
  33611. {
  33612. Desktop::getInstance().beginDragAutoRepeat (interval);
  33613. }
  33614. void Component::broughtToFront()
  33615. {
  33616. }
  33617. void Component::internalBroughtToFront()
  33618. {
  33619. if (flags.hasHeavyweightPeerFlag)
  33620. Desktop::getInstance().componentBroughtToFront (this);
  33621. BailOutChecker checker (this);
  33622. broughtToFront();
  33623. if (checker.shouldBailOut())
  33624. return;
  33625. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33626. if (checker.shouldBailOut())
  33627. return;
  33628. // When brought to the front and there's a modal component blocking this one,
  33629. // we need to bring the modal one to the front instead..
  33630. Component* const cm = getCurrentlyModalComponent();
  33631. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  33632. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  33633. }
  33634. void Component::focusGained (FocusChangeType)
  33635. {
  33636. // base class does nothing
  33637. }
  33638. void Component::internalFocusGain (const FocusChangeType cause)
  33639. {
  33640. internalFocusGain (cause, WeakReference<Component> (this));
  33641. }
  33642. void Component::internalFocusGain (const FocusChangeType cause, const WeakReference<Component>& safePointer)
  33643. {
  33644. focusGained (cause);
  33645. if (safePointer != 0)
  33646. internalChildFocusChange (cause, safePointer);
  33647. }
  33648. void Component::focusLost (FocusChangeType)
  33649. {
  33650. // base class does nothing
  33651. }
  33652. void Component::internalFocusLoss (const FocusChangeType cause)
  33653. {
  33654. WeakReference<Component> safePointer (this);
  33655. focusLost (focusChangedDirectly);
  33656. if (safePointer != 0)
  33657. internalChildFocusChange (cause, safePointer);
  33658. }
  33659. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  33660. {
  33661. // base class does nothing
  33662. }
  33663. void Component::internalChildFocusChange (FocusChangeType cause, const WeakReference<Component>& safePointer)
  33664. {
  33665. const bool childIsNowFocused = hasKeyboardFocus (true);
  33666. if (flags.childCompFocusedFlag != childIsNowFocused)
  33667. {
  33668. flags.childCompFocusedFlag = childIsNowFocused;
  33669. focusOfChildComponentChanged (cause);
  33670. if (safePointer == 0)
  33671. return;
  33672. }
  33673. if (parentComponent != 0)
  33674. parentComponent->internalChildFocusChange (cause, WeakReference<Component> (parentComponent));
  33675. }
  33676. bool Component::isEnabled() const throw()
  33677. {
  33678. return (! flags.isDisabledFlag)
  33679. && (parentComponent == 0 || parentComponent->isEnabled());
  33680. }
  33681. void Component::setEnabled (const bool shouldBeEnabled)
  33682. {
  33683. if (flags.isDisabledFlag == shouldBeEnabled)
  33684. {
  33685. flags.isDisabledFlag = ! shouldBeEnabled;
  33686. // if any parent components are disabled, setting our flag won't make a difference,
  33687. // so no need to send a change message
  33688. if (parentComponent == 0 || parentComponent->isEnabled())
  33689. sendEnablementChangeMessage();
  33690. }
  33691. }
  33692. void Component::sendEnablementChangeMessage()
  33693. {
  33694. WeakReference<Component> safePointer (this);
  33695. enablementChanged();
  33696. if (safePointer == 0)
  33697. return;
  33698. for (int i = getNumChildComponents(); --i >= 0;)
  33699. {
  33700. Component* const c = getChildComponent (i);
  33701. if (c != 0)
  33702. {
  33703. c->sendEnablementChangeMessage();
  33704. if (safePointer == 0)
  33705. return;
  33706. }
  33707. }
  33708. }
  33709. void Component::enablementChanged()
  33710. {
  33711. }
  33712. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  33713. {
  33714. flags.wantsFocusFlag = wantsFocus;
  33715. }
  33716. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  33717. {
  33718. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  33719. }
  33720. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  33721. {
  33722. return ! flags.dontFocusOnMouseClickFlag;
  33723. }
  33724. bool Component::getWantsKeyboardFocus() const throw()
  33725. {
  33726. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  33727. }
  33728. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  33729. {
  33730. flags.isFocusContainerFlag = shouldBeFocusContainer;
  33731. }
  33732. bool Component::isFocusContainer() const throw()
  33733. {
  33734. return flags.isFocusContainerFlag;
  33735. }
  33736. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  33737. int Component::getExplicitFocusOrder() const
  33738. {
  33739. return properties [juce_explicitFocusOrderId];
  33740. }
  33741. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  33742. {
  33743. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  33744. }
  33745. KeyboardFocusTraverser* Component::createFocusTraverser()
  33746. {
  33747. if (flags.isFocusContainerFlag || parentComponent == 0)
  33748. return new KeyboardFocusTraverser();
  33749. return parentComponent->createFocusTraverser();
  33750. }
  33751. void Component::takeKeyboardFocus (const FocusChangeType cause)
  33752. {
  33753. // give the focus to this component
  33754. if (currentlyFocusedComponent != this)
  33755. {
  33756. // get the focus onto our desktop window
  33757. ComponentPeer* const peer = getPeer();
  33758. if (peer != 0)
  33759. {
  33760. WeakReference<Component> safePointer (this);
  33761. peer->grabFocus();
  33762. if (peer->isFocused() && currentlyFocusedComponent != this)
  33763. {
  33764. WeakReference<Component> componentLosingFocus (currentlyFocusedComponent);
  33765. currentlyFocusedComponent = this;
  33766. Desktop::getInstance().triggerFocusCallback();
  33767. // call this after setting currentlyFocusedComponent so that the one that's
  33768. // losing it has a chance to see where focus is going
  33769. if (componentLosingFocus != 0)
  33770. componentLosingFocus->internalFocusLoss (cause);
  33771. if (currentlyFocusedComponent == this)
  33772. internalFocusGain (cause, safePointer);
  33773. }
  33774. }
  33775. }
  33776. }
  33777. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  33778. {
  33779. if (isShowing())
  33780. {
  33781. if (flags.wantsFocusFlag && (isEnabled() || parentComponent == 0))
  33782. {
  33783. takeKeyboardFocus (cause);
  33784. }
  33785. else
  33786. {
  33787. if (isParentOf (currentlyFocusedComponent)
  33788. && currentlyFocusedComponent->isShowing())
  33789. {
  33790. // do nothing if the focused component is actually a child of ours..
  33791. }
  33792. else
  33793. {
  33794. // find the default child component..
  33795. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33796. if (traverser != 0)
  33797. {
  33798. Component* const defaultComp = traverser->getDefaultComponent (this);
  33799. traverser = 0;
  33800. if (defaultComp != 0)
  33801. {
  33802. defaultComp->grabFocusInternal (cause, false);
  33803. return;
  33804. }
  33805. }
  33806. if (canTryParent && parentComponent != 0)
  33807. {
  33808. // if no children want it and we're allowed to try our parent comp,
  33809. // then pass up to parent, which will try our siblings.
  33810. parentComponent->grabFocusInternal (cause, true);
  33811. }
  33812. }
  33813. }
  33814. }
  33815. }
  33816. void Component::grabKeyboardFocus()
  33817. {
  33818. // if component methods are being called from threads other than the message
  33819. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33820. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33821. grabFocusInternal (focusChangedDirectly);
  33822. }
  33823. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  33824. {
  33825. // if component methods are being called from threads other than the message
  33826. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33827. CHECK_MESSAGE_MANAGER_IS_LOCKED
  33828. if (parentComponent != 0)
  33829. {
  33830. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  33831. if (traverser != 0)
  33832. {
  33833. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  33834. : traverser->getPreviousComponent (this);
  33835. traverser = 0;
  33836. if (nextComp != 0)
  33837. {
  33838. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33839. {
  33840. WeakReference<Component> nextCompPointer (nextComp);
  33841. internalModalInputAttempt();
  33842. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  33843. return;
  33844. }
  33845. nextComp->grabFocusInternal (focusChangedByTabKey);
  33846. return;
  33847. }
  33848. }
  33849. parentComponent->moveKeyboardFocusToSibling (moveToNext);
  33850. }
  33851. }
  33852. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  33853. {
  33854. return (currentlyFocusedComponent == this)
  33855. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  33856. }
  33857. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  33858. {
  33859. return currentlyFocusedComponent;
  33860. }
  33861. void Component::giveAwayFocus (const bool sendFocusLossEvent)
  33862. {
  33863. Component* const componentLosingFocus = currentlyFocusedComponent;
  33864. currentlyFocusedComponent = 0;
  33865. if (sendFocusLossEvent && componentLosingFocus != 0)
  33866. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  33867. Desktop::getInstance().triggerFocusCallback();
  33868. }
  33869. bool Component::isMouseOver (const bool includeChildren) const
  33870. {
  33871. if (flags.mouseOverFlag)
  33872. return true;
  33873. if (includeChildren)
  33874. {
  33875. Desktop& desktop = Desktop::getInstance();
  33876. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33877. {
  33878. Component* const c = desktop.getMouseSource(i)->getComponentUnderMouse();
  33879. if (isParentOf (c) && c->flags.mouseOverFlag) // (mouseOverFlag checked in case it's being dragged outside the comp)
  33880. return true;
  33881. }
  33882. }
  33883. return false;
  33884. }
  33885. bool Component::isMouseButtonDown() const throw() { return flags.mouseDownFlag; }
  33886. bool Component::isMouseOverOrDragging() const throw() { return flags.mouseOverFlag || flags.mouseDownFlag; }
  33887. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  33888. {
  33889. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  33890. }
  33891. const Point<int> Component::getMouseXYRelative() const
  33892. {
  33893. return getLocalPoint (0, Desktop::getMousePosition());
  33894. }
  33895. const Rectangle<int> Component::getParentMonitorArea() const
  33896. {
  33897. return Desktop::getInstance().getMonitorAreaContaining (getScreenBounds().getCentre());
  33898. }
  33899. void Component::addKeyListener (KeyListener* const newListener)
  33900. {
  33901. if (keyListeners == 0)
  33902. keyListeners = new Array <KeyListener*>();
  33903. keyListeners->addIfNotAlreadyThere (newListener);
  33904. }
  33905. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  33906. {
  33907. if (keyListeners != 0)
  33908. keyListeners->removeValue (listenerToRemove);
  33909. }
  33910. bool Component::keyPressed (const KeyPress&)
  33911. {
  33912. return false;
  33913. }
  33914. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33915. {
  33916. return false;
  33917. }
  33918. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33919. {
  33920. if (parentComponent != 0)
  33921. parentComponent->modifierKeysChanged (modifiers);
  33922. }
  33923. void Component::internalModifierKeysChanged()
  33924. {
  33925. sendFakeMouseMove();
  33926. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33927. }
  33928. ComponentPeer* Component::getPeer() const
  33929. {
  33930. if (flags.hasHeavyweightPeerFlag)
  33931. return ComponentPeer::getPeerFor (this);
  33932. else if (parentComponent == 0)
  33933. return 0;
  33934. return parentComponent->getPeer();
  33935. }
  33936. Component::BailOutChecker::BailOutChecker (Component* const component)
  33937. : safePointer (component)
  33938. {
  33939. jassert (component != 0);
  33940. }
  33941. bool Component::BailOutChecker::shouldBailOut() const throw()
  33942. {
  33943. return safePointer == 0;
  33944. }
  33945. END_JUCE_NAMESPACE
  33946. /*** End of inlined file: juce_Component.cpp ***/
  33947. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  33948. BEGIN_JUCE_NAMESPACE
  33949. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  33950. void ComponentListener::componentBroughtToFront (Component&) {}
  33951. void ComponentListener::componentVisibilityChanged (Component&) {}
  33952. void ComponentListener::componentChildrenChanged (Component&) {}
  33953. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  33954. void ComponentListener::componentNameChanged (Component&) {}
  33955. void ComponentListener::componentBeingDeleted (Component&) {}
  33956. END_JUCE_NAMESPACE
  33957. /*** End of inlined file: juce_ComponentListener.cpp ***/
  33958. /*** Start of inlined file: juce_Desktop.cpp ***/
  33959. BEGIN_JUCE_NAMESPACE
  33960. Desktop::Desktop()
  33961. : mouseClickCounter (0),
  33962. kioskModeComponent (0),
  33963. allowedOrientations (allOrientations)
  33964. {
  33965. createMouseInputSources();
  33966. refreshMonitorSizes();
  33967. }
  33968. Desktop::~Desktop()
  33969. {
  33970. jassert (instance == this);
  33971. instance = 0;
  33972. // doh! If you don't delete all your windows before exiting, you're going to
  33973. // be leaking memory!
  33974. jassert (desktopComponents.size() == 0);
  33975. }
  33976. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  33977. {
  33978. if (instance == 0)
  33979. instance = new Desktop();
  33980. return *instance;
  33981. }
  33982. Desktop* Desktop::instance = 0;
  33983. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  33984. const bool clipToWorkArea);
  33985. void Desktop::refreshMonitorSizes()
  33986. {
  33987. Array <Rectangle<int> > oldClipped, oldUnclipped;
  33988. oldClipped.swapWithArray (monitorCoordsClipped);
  33989. oldUnclipped.swapWithArray (monitorCoordsUnclipped);
  33990. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33991. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33992. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33993. if (oldClipped != monitorCoordsClipped
  33994. || oldUnclipped != monitorCoordsUnclipped)
  33995. {
  33996. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33997. {
  33998. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33999. if (p != 0)
  34000. p->handleScreenSizeChange();
  34001. }
  34002. }
  34003. }
  34004. int Desktop::getNumDisplayMonitors() const throw()
  34005. {
  34006. return monitorCoordsClipped.size();
  34007. }
  34008. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34009. {
  34010. return clippedToWorkArea ? monitorCoordsClipped [index]
  34011. : monitorCoordsUnclipped [index];
  34012. }
  34013. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34014. {
  34015. RectangleList rl;
  34016. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34017. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34018. return rl;
  34019. }
  34020. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34021. {
  34022. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34023. }
  34024. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34025. {
  34026. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34027. double bestDistance = 1.0e10;
  34028. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34029. {
  34030. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34031. if (rect.contains (position))
  34032. return rect;
  34033. const double distance = rect.getCentre().getDistanceFrom (position);
  34034. if (distance < bestDistance)
  34035. {
  34036. bestDistance = distance;
  34037. best = rect;
  34038. }
  34039. }
  34040. return best;
  34041. }
  34042. int Desktop::getNumComponents() const throw()
  34043. {
  34044. return desktopComponents.size();
  34045. }
  34046. Component* Desktop::getComponent (const int index) const throw()
  34047. {
  34048. return desktopComponents [index];
  34049. }
  34050. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34051. {
  34052. for (int i = desktopComponents.size(); --i >= 0;)
  34053. {
  34054. Component* const c = desktopComponents.getUnchecked(i);
  34055. if (c->isVisible())
  34056. {
  34057. const Point<int> relative (c->getLocalPoint (0, screenPosition));
  34058. if (c->contains (relative))
  34059. return c->getComponentAt (relative);
  34060. }
  34061. }
  34062. return 0;
  34063. }
  34064. void Desktop::addDesktopComponent (Component* const c)
  34065. {
  34066. jassert (c != 0);
  34067. jassert (! desktopComponents.contains (c));
  34068. desktopComponents.addIfNotAlreadyThere (c);
  34069. }
  34070. void Desktop::removeDesktopComponent (Component* const c)
  34071. {
  34072. desktopComponents.removeValue (c);
  34073. }
  34074. void Desktop::componentBroughtToFront (Component* const c)
  34075. {
  34076. const int index = desktopComponents.indexOf (c);
  34077. jassert (index >= 0);
  34078. if (index >= 0)
  34079. {
  34080. int newIndex = -1;
  34081. if (! c->isAlwaysOnTop())
  34082. {
  34083. newIndex = desktopComponents.size();
  34084. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34085. --newIndex;
  34086. --newIndex;
  34087. }
  34088. desktopComponents.move (index, newIndex);
  34089. }
  34090. }
  34091. const Point<int> Desktop::getMousePosition()
  34092. {
  34093. return getInstance().getMainMouseSource().getScreenPosition();
  34094. }
  34095. const Point<int> Desktop::getLastMouseDownPosition()
  34096. {
  34097. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34098. }
  34099. int Desktop::getMouseButtonClickCounter()
  34100. {
  34101. return getInstance().mouseClickCounter;
  34102. }
  34103. void Desktop::incrementMouseClickCounter() throw()
  34104. {
  34105. ++mouseClickCounter;
  34106. }
  34107. int Desktop::getNumDraggingMouseSources() const throw()
  34108. {
  34109. int num = 0;
  34110. for (int i = mouseSources.size(); --i >= 0;)
  34111. if (mouseSources.getUnchecked(i)->isDragging())
  34112. ++num;
  34113. return num;
  34114. }
  34115. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34116. {
  34117. int num = 0;
  34118. for (int i = mouseSources.size(); --i >= 0;)
  34119. {
  34120. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34121. if (mi->isDragging())
  34122. {
  34123. if (index == num)
  34124. return mi;
  34125. ++num;
  34126. }
  34127. }
  34128. return 0;
  34129. }
  34130. class MouseDragAutoRepeater : public Timer
  34131. {
  34132. public:
  34133. MouseDragAutoRepeater() {}
  34134. void timerCallback()
  34135. {
  34136. Desktop& desktop = Desktop::getInstance();
  34137. int numMiceDown = 0;
  34138. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  34139. {
  34140. MouseInputSource* const source = desktop.getMouseSource(i);
  34141. if (source->isDragging())
  34142. {
  34143. source->triggerFakeMove();
  34144. ++numMiceDown;
  34145. }
  34146. }
  34147. if (numMiceDown == 0)
  34148. desktop.beginDragAutoRepeat (0);
  34149. }
  34150. private:
  34151. JUCE_DECLARE_NON_COPYABLE (MouseDragAutoRepeater);
  34152. };
  34153. void Desktop::beginDragAutoRepeat (const int interval)
  34154. {
  34155. if (interval > 0)
  34156. {
  34157. if (dragRepeater == 0)
  34158. dragRepeater = new MouseDragAutoRepeater();
  34159. if (dragRepeater->getTimerInterval() != interval)
  34160. dragRepeater->startTimer (interval);
  34161. }
  34162. else
  34163. {
  34164. dragRepeater = 0;
  34165. }
  34166. }
  34167. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34168. {
  34169. focusListeners.add (listener);
  34170. }
  34171. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34172. {
  34173. focusListeners.remove (listener);
  34174. }
  34175. void Desktop::triggerFocusCallback()
  34176. {
  34177. triggerAsyncUpdate();
  34178. }
  34179. void Desktop::handleAsyncUpdate()
  34180. {
  34181. // The component may be deleted during this operation, but we'll use a SafePointer rather than a
  34182. // BailOutChecker so that any remaining listeners will still get a callback (with a null pointer).
  34183. WeakReference<Component> currentFocus (Component::getCurrentlyFocusedComponent());
  34184. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34185. }
  34186. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34187. {
  34188. mouseListeners.add (listener);
  34189. resetTimer();
  34190. }
  34191. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34192. {
  34193. mouseListeners.remove (listener);
  34194. resetTimer();
  34195. }
  34196. void Desktop::timerCallback()
  34197. {
  34198. if (lastFakeMouseMove != getMousePosition())
  34199. sendMouseMove();
  34200. }
  34201. void Desktop::sendMouseMove()
  34202. {
  34203. if (! mouseListeners.isEmpty())
  34204. {
  34205. startTimer (20);
  34206. lastFakeMouseMove = getMousePosition();
  34207. Component* const target = findComponentAt (lastFakeMouseMove);
  34208. if (target != 0)
  34209. {
  34210. Component::BailOutChecker checker (target);
  34211. const Point<int> pos (target->getLocalPoint (0, lastFakeMouseMove));
  34212. const Time now (Time::getCurrentTime());
  34213. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34214. target, target, now, pos, now, 0, false);
  34215. if (me.mods.isAnyMouseButtonDown())
  34216. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34217. else
  34218. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34219. }
  34220. }
  34221. }
  34222. void Desktop::resetTimer()
  34223. {
  34224. if (mouseListeners.size() == 0)
  34225. stopTimer();
  34226. else
  34227. startTimer (100);
  34228. lastFakeMouseMove = getMousePosition();
  34229. }
  34230. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34231. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34232. {
  34233. if (kioskModeComponent != componentToUse)
  34234. {
  34235. // agh! Don't delete or remove a component from the desktop while it's still the kiosk component!
  34236. jassert (kioskModeComponent == 0 || ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34237. if (kioskModeComponent != 0)
  34238. {
  34239. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34240. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34241. }
  34242. kioskModeComponent = componentToUse;
  34243. if (kioskModeComponent != 0)
  34244. {
  34245. // Only components that are already on the desktop can be put into kiosk mode!
  34246. jassert (ComponentPeer::getPeerFor (kioskModeComponent) != 0);
  34247. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34248. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34249. }
  34250. }
  34251. }
  34252. void Desktop::setOrientationsEnabled (const int newOrientations)
  34253. {
  34254. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34255. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34256. allowedOrientations = newOrientations;
  34257. }
  34258. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34259. {
  34260. // Make sure you only pass one valid flag in here...
  34261. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34262. return (allowedOrientations & orientation) != 0;
  34263. }
  34264. END_JUCE_NAMESPACE
  34265. /*** End of inlined file: juce_Desktop.cpp ***/
  34266. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34267. BEGIN_JUCE_NAMESPACE
  34268. class ModalComponentManager::ModalItem : public ComponentMovementWatcher
  34269. {
  34270. public:
  34271. ModalItem (Component* const comp, Callback* const callback)
  34272. : ComponentMovementWatcher (comp),
  34273. component (comp), returnValue (0), isActive (true)
  34274. {
  34275. jassert (comp != 0);
  34276. if (callback != 0)
  34277. callbacks.add (callback);
  34278. }
  34279. void componentMovedOrResized (bool, bool) {}
  34280. void componentPeerChanged()
  34281. {
  34282. if (! component->isShowing())
  34283. cancel();
  34284. }
  34285. void componentVisibilityChanged()
  34286. {
  34287. if (! component->isShowing())
  34288. cancel();
  34289. }
  34290. void componentBeingDeleted (Component& comp)
  34291. {
  34292. ComponentMovementWatcher::componentBeingDeleted (comp);
  34293. if (component == &comp || comp.isParentOf (component))
  34294. cancel();
  34295. }
  34296. void cancel()
  34297. {
  34298. if (isActive)
  34299. {
  34300. isActive = false;
  34301. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34302. }
  34303. }
  34304. Component* component;
  34305. OwnedArray<Callback> callbacks;
  34306. int returnValue;
  34307. bool isActive;
  34308. private:
  34309. JUCE_DECLARE_NON_COPYABLE (ModalItem);
  34310. };
  34311. ModalComponentManager::ModalComponentManager()
  34312. {
  34313. }
  34314. ModalComponentManager::~ModalComponentManager()
  34315. {
  34316. clearSingletonInstance();
  34317. }
  34318. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34319. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34320. {
  34321. if (component != 0)
  34322. stack.add (new ModalItem (component, callback));
  34323. }
  34324. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34325. {
  34326. if (callback != 0)
  34327. {
  34328. ScopedPointer<Callback> callbackDeleter (callback);
  34329. for (int i = stack.size(); --i >= 0;)
  34330. {
  34331. ModalItem* const item = stack.getUnchecked(i);
  34332. if (item->component == component)
  34333. {
  34334. item->callbacks.add (callback);
  34335. callbackDeleter.release();
  34336. break;
  34337. }
  34338. }
  34339. }
  34340. }
  34341. void ModalComponentManager::endModal (Component* component)
  34342. {
  34343. for (int i = stack.size(); --i >= 0;)
  34344. {
  34345. ModalItem* const item = stack.getUnchecked(i);
  34346. if (item->component == component)
  34347. item->cancel();
  34348. }
  34349. }
  34350. void ModalComponentManager::endModal (Component* component, int returnValue)
  34351. {
  34352. for (int i = stack.size(); --i >= 0;)
  34353. {
  34354. ModalItem* const item = stack.getUnchecked(i);
  34355. if (item->component == component)
  34356. {
  34357. item->returnValue = returnValue;
  34358. item->cancel();
  34359. }
  34360. }
  34361. }
  34362. int ModalComponentManager::getNumModalComponents() const
  34363. {
  34364. int n = 0;
  34365. for (int i = 0; i < stack.size(); ++i)
  34366. if (stack.getUnchecked(i)->isActive)
  34367. ++n;
  34368. return n;
  34369. }
  34370. Component* ModalComponentManager::getModalComponent (const int index) const
  34371. {
  34372. int n = 0;
  34373. for (int i = stack.size(); --i >= 0;)
  34374. {
  34375. const ModalItem* const item = stack.getUnchecked(i);
  34376. if (item->isActive)
  34377. if (n++ == index)
  34378. return item->component;
  34379. }
  34380. return 0;
  34381. }
  34382. bool ModalComponentManager::isModal (Component* const comp) const
  34383. {
  34384. for (int i = stack.size(); --i >= 0;)
  34385. {
  34386. const ModalItem* const item = stack.getUnchecked(i);
  34387. if (item->isActive && item->component == comp)
  34388. return true;
  34389. }
  34390. return false;
  34391. }
  34392. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34393. {
  34394. return comp == getModalComponent (0);
  34395. }
  34396. void ModalComponentManager::handleAsyncUpdate()
  34397. {
  34398. for (int i = stack.size(); --i >= 0;)
  34399. {
  34400. const ModalItem* const item = stack.getUnchecked(i);
  34401. if (! item->isActive)
  34402. {
  34403. for (int j = item->callbacks.size(); --j >= 0;)
  34404. {
  34405. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34406. if (! stack.contains (item))
  34407. break;
  34408. }
  34409. stack.removeObject (item);
  34410. }
  34411. }
  34412. }
  34413. void ModalComponentManager::bringModalComponentsToFront()
  34414. {
  34415. ComponentPeer* lastOne = 0;
  34416. for (int i = 0; i < getNumModalComponents(); ++i)
  34417. {
  34418. Component* const c = getModalComponent (i);
  34419. if (c == 0)
  34420. break;
  34421. ComponentPeer* peer = c->getPeer();
  34422. if (peer != 0 && peer != lastOne)
  34423. {
  34424. if (lastOne == 0)
  34425. {
  34426. peer->toFront (true);
  34427. peer->grabFocus();
  34428. }
  34429. else
  34430. peer->toBehind (lastOne);
  34431. lastOne = peer;
  34432. }
  34433. }
  34434. }
  34435. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34436. {
  34437. public:
  34438. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34439. ~ReturnValueRetriever() {}
  34440. void modalStateFinished (int returnValue)
  34441. {
  34442. finished = true;
  34443. value = returnValue;
  34444. }
  34445. private:
  34446. int& value;
  34447. bool& finished;
  34448. JUCE_DECLARE_NON_COPYABLE (ReturnValueRetriever);
  34449. };
  34450. int ModalComponentManager::runEventLoopForCurrentComponent()
  34451. {
  34452. // This can only be run from the message thread!
  34453. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34454. Component* currentlyModal = getModalComponent (0);
  34455. if (currentlyModal == 0)
  34456. return 0;
  34457. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34458. int returnValue = 0;
  34459. bool finished = false;
  34460. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34461. JUCE_TRY
  34462. {
  34463. while (! finished)
  34464. {
  34465. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34466. break;
  34467. }
  34468. }
  34469. JUCE_CATCH_EXCEPTION
  34470. if (prevFocused != 0)
  34471. prevFocused->grabKeyboardFocus();
  34472. return returnValue;
  34473. }
  34474. END_JUCE_NAMESPACE
  34475. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34476. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34477. BEGIN_JUCE_NAMESPACE
  34478. ArrowButton::ArrowButton (const String& name,
  34479. float arrowDirectionInRadians,
  34480. const Colour& arrowColour)
  34481. : Button (name),
  34482. colour (arrowColour)
  34483. {
  34484. path.lineTo (0.0f, 1.0f);
  34485. path.lineTo (1.0f, 0.5f);
  34486. path.closeSubPath();
  34487. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34488. 0.5f, 0.5f));
  34489. setComponentEffect (&shadow);
  34490. buttonStateChanged();
  34491. }
  34492. ArrowButton::~ArrowButton()
  34493. {
  34494. }
  34495. void ArrowButton::paintButton (Graphics& g,
  34496. bool /*isMouseOverButton*/,
  34497. bool /*isButtonDown*/)
  34498. {
  34499. g.setColour (colour);
  34500. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34501. (float) offset,
  34502. (float) (getWidth() - 3),
  34503. (float) (getHeight() - 3),
  34504. false));
  34505. }
  34506. void ArrowButton::buttonStateChanged()
  34507. {
  34508. offset = (isDown()) ? 1 : 0;
  34509. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34510. 0.3f, -1, 0);
  34511. }
  34512. END_JUCE_NAMESPACE
  34513. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34514. /*** Start of inlined file: juce_Button.cpp ***/
  34515. BEGIN_JUCE_NAMESPACE
  34516. class Button::RepeatTimer : public Timer
  34517. {
  34518. public:
  34519. RepeatTimer (Button& owner_) : owner (owner_) {}
  34520. void timerCallback() { owner.repeatTimerCallback(); }
  34521. private:
  34522. Button& owner;
  34523. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RepeatTimer);
  34524. };
  34525. Button::Button (const String& name)
  34526. : Component (name),
  34527. text (name),
  34528. buttonPressTime (0),
  34529. lastRepeatTime (0),
  34530. commandManagerToUse (0),
  34531. autoRepeatDelay (-1),
  34532. autoRepeatSpeed (0),
  34533. autoRepeatMinimumDelay (-1),
  34534. radioGroupId (0),
  34535. commandID (0),
  34536. connectedEdgeFlags (0),
  34537. buttonState (buttonNormal),
  34538. lastToggleState (false),
  34539. clickTogglesState (false),
  34540. needsToRelease (false),
  34541. needsRepainting (false),
  34542. isKeyDown (false),
  34543. triggerOnMouseDown (false),
  34544. generateTooltip (false)
  34545. {
  34546. setWantsKeyboardFocus (true);
  34547. isOn.addListener (this);
  34548. }
  34549. Button::~Button()
  34550. {
  34551. isOn.removeListener (this);
  34552. if (commandManagerToUse != 0)
  34553. commandManagerToUse->removeListener (this);
  34554. repeatTimer = 0;
  34555. clearShortcuts();
  34556. }
  34557. void Button::setButtonText (const String& newText)
  34558. {
  34559. if (text != newText)
  34560. {
  34561. text = newText;
  34562. repaint();
  34563. }
  34564. }
  34565. void Button::setTooltip (const String& newTooltip)
  34566. {
  34567. SettableTooltipClient::setTooltip (newTooltip);
  34568. generateTooltip = false;
  34569. }
  34570. const String Button::getTooltip()
  34571. {
  34572. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34573. {
  34574. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34575. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34576. for (int i = 0; i < keyPresses.size(); ++i)
  34577. {
  34578. const String key (keyPresses.getReference(i).getTextDescription());
  34579. tt << " [";
  34580. if (key.length() == 1)
  34581. tt << TRANS("shortcut") << ": '" << key << "']";
  34582. else
  34583. tt << key << ']';
  34584. }
  34585. return tt;
  34586. }
  34587. return SettableTooltipClient::getTooltip();
  34588. }
  34589. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34590. {
  34591. if (connectedEdgeFlags != connectedEdgeFlags_)
  34592. {
  34593. connectedEdgeFlags = connectedEdgeFlags_;
  34594. repaint();
  34595. }
  34596. }
  34597. void Button::setToggleState (const bool shouldBeOn,
  34598. const bool sendChangeNotification)
  34599. {
  34600. if (shouldBeOn != lastToggleState)
  34601. {
  34602. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34603. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34604. lastToggleState = shouldBeOn;
  34605. repaint();
  34606. WeakReference<Component> deletionWatcher (this);
  34607. if (sendChangeNotification)
  34608. {
  34609. sendClickMessage (ModifierKeys());
  34610. if (deletionWatcher == 0)
  34611. return;
  34612. }
  34613. if (lastToggleState)
  34614. {
  34615. turnOffOtherButtonsInGroup (sendChangeNotification);
  34616. if (deletionWatcher == 0)
  34617. return;
  34618. }
  34619. sendStateMessage();
  34620. }
  34621. }
  34622. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34623. {
  34624. clickTogglesState = shouldToggle;
  34625. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34626. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34627. // it is that this button represents, and the button will update its state to reflect this
  34628. // in the applicationCommandListChanged() method.
  34629. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34630. }
  34631. bool Button::getClickingTogglesState() const throw()
  34632. {
  34633. return clickTogglesState;
  34634. }
  34635. void Button::valueChanged (Value& value)
  34636. {
  34637. if (value.refersToSameSourceAs (isOn))
  34638. setToggleState (isOn.getValue(), true);
  34639. }
  34640. void Button::setRadioGroupId (const int newGroupId)
  34641. {
  34642. if (radioGroupId != newGroupId)
  34643. {
  34644. radioGroupId = newGroupId;
  34645. if (lastToggleState)
  34646. turnOffOtherButtonsInGroup (true);
  34647. }
  34648. }
  34649. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34650. {
  34651. Component* const p = getParentComponent();
  34652. if (p != 0 && radioGroupId != 0)
  34653. {
  34654. WeakReference<Component> deletionWatcher (this);
  34655. for (int i = p->getNumChildComponents(); --i >= 0;)
  34656. {
  34657. Component* const c = p->getChildComponent (i);
  34658. if (c != this)
  34659. {
  34660. Button* const b = dynamic_cast <Button*> (c);
  34661. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34662. {
  34663. b->setToggleState (false, sendChangeNotification);
  34664. if (deletionWatcher == 0)
  34665. return;
  34666. }
  34667. }
  34668. }
  34669. }
  34670. }
  34671. void Button::enablementChanged()
  34672. {
  34673. updateState();
  34674. repaint();
  34675. }
  34676. Button::ButtonState Button::updateState()
  34677. {
  34678. return updateState (isMouseOver (true), isMouseButtonDown());
  34679. }
  34680. Button::ButtonState Button::updateState (const bool over, const bool down)
  34681. {
  34682. ButtonState newState = buttonNormal;
  34683. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34684. {
  34685. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34686. newState = buttonDown;
  34687. else if (over)
  34688. newState = buttonOver;
  34689. }
  34690. setState (newState);
  34691. return newState;
  34692. }
  34693. void Button::setState (const ButtonState newState)
  34694. {
  34695. if (buttonState != newState)
  34696. {
  34697. buttonState = newState;
  34698. repaint();
  34699. if (buttonState == buttonDown)
  34700. {
  34701. buttonPressTime = Time::getApproximateMillisecondCounter();
  34702. lastRepeatTime = 0;
  34703. }
  34704. sendStateMessage();
  34705. }
  34706. }
  34707. bool Button::isDown() const throw()
  34708. {
  34709. return buttonState == buttonDown;
  34710. }
  34711. bool Button::isOver() const throw()
  34712. {
  34713. return buttonState != buttonNormal;
  34714. }
  34715. void Button::buttonStateChanged()
  34716. {
  34717. }
  34718. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  34719. {
  34720. const uint32 now = Time::getApproximateMillisecondCounter();
  34721. return now > buttonPressTime ? now - buttonPressTime : 0;
  34722. }
  34723. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  34724. {
  34725. triggerOnMouseDown = isTriggeredOnMouseDown;
  34726. }
  34727. void Button::clicked()
  34728. {
  34729. }
  34730. void Button::clicked (const ModifierKeys& /*modifiers*/)
  34731. {
  34732. clicked();
  34733. }
  34734. static const int clickMessageId = 0x2f3f4f99;
  34735. void Button::triggerClick()
  34736. {
  34737. postCommandMessage (clickMessageId);
  34738. }
  34739. void Button::internalClickCallback (const ModifierKeys& modifiers)
  34740. {
  34741. if (clickTogglesState)
  34742. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  34743. sendClickMessage (modifiers);
  34744. }
  34745. void Button::flashButtonState()
  34746. {
  34747. if (isEnabled())
  34748. {
  34749. needsToRelease = true;
  34750. setState (buttonDown);
  34751. getRepeatTimer().startTimer (100);
  34752. }
  34753. }
  34754. void Button::handleCommandMessage (int commandId)
  34755. {
  34756. if (commandId == clickMessageId)
  34757. {
  34758. if (isEnabled())
  34759. {
  34760. flashButtonState();
  34761. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34762. }
  34763. }
  34764. else
  34765. {
  34766. Component::handleCommandMessage (commandId);
  34767. }
  34768. }
  34769. void Button::addListener (ButtonListener* const newListener)
  34770. {
  34771. buttonListeners.add (newListener);
  34772. }
  34773. void Button::removeListener (ButtonListener* const listener)
  34774. {
  34775. buttonListeners.remove (listener);
  34776. }
  34777. void Button::addButtonListener (ButtonListener* l) { addListener (l); }
  34778. void Button::removeButtonListener (ButtonListener* l) { removeListener (l); }
  34779. void Button::sendClickMessage (const ModifierKeys& modifiers)
  34780. {
  34781. Component::BailOutChecker checker (this);
  34782. if (commandManagerToUse != 0 && commandID != 0)
  34783. {
  34784. ApplicationCommandTarget::InvocationInfo info (commandID);
  34785. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  34786. info.originatingComponent = this;
  34787. commandManagerToUse->invoke (info, true);
  34788. }
  34789. clicked (modifiers);
  34790. if (! checker.shouldBailOut())
  34791. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  34792. }
  34793. void Button::sendStateMessage()
  34794. {
  34795. Component::BailOutChecker checker (this);
  34796. buttonStateChanged();
  34797. if (! checker.shouldBailOut())
  34798. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  34799. }
  34800. void Button::paint (Graphics& g)
  34801. {
  34802. if (needsToRelease && isEnabled())
  34803. {
  34804. needsToRelease = false;
  34805. needsRepainting = true;
  34806. }
  34807. paintButton (g, isOver(), isDown());
  34808. }
  34809. void Button::mouseEnter (const MouseEvent&)
  34810. {
  34811. updateState (true, false);
  34812. }
  34813. void Button::mouseExit (const MouseEvent&)
  34814. {
  34815. updateState (false, false);
  34816. }
  34817. void Button::mouseDown (const MouseEvent& e)
  34818. {
  34819. updateState (true, true);
  34820. if (isDown())
  34821. {
  34822. if (autoRepeatDelay >= 0)
  34823. getRepeatTimer().startTimer (autoRepeatDelay);
  34824. if (triggerOnMouseDown)
  34825. internalClickCallback (e.mods);
  34826. }
  34827. }
  34828. void Button::mouseUp (const MouseEvent& e)
  34829. {
  34830. const bool wasDown = isDown();
  34831. updateState (isMouseOver(), false);
  34832. if (wasDown && isOver() && ! triggerOnMouseDown)
  34833. internalClickCallback (e.mods);
  34834. }
  34835. void Button::mouseDrag (const MouseEvent&)
  34836. {
  34837. const ButtonState oldState = buttonState;
  34838. updateState (isMouseOver(), true);
  34839. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  34840. getRepeatTimer().startTimer (autoRepeatSpeed);
  34841. }
  34842. void Button::focusGained (FocusChangeType)
  34843. {
  34844. updateState();
  34845. repaint();
  34846. }
  34847. void Button::focusLost (FocusChangeType)
  34848. {
  34849. updateState();
  34850. repaint();
  34851. }
  34852. void Button::visibilityChanged()
  34853. {
  34854. needsToRelease = false;
  34855. updateState();
  34856. }
  34857. void Button::parentHierarchyChanged()
  34858. {
  34859. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  34860. if (newKeySource != keySource.get())
  34861. {
  34862. if (keySource != 0)
  34863. keySource->removeKeyListener (this);
  34864. keySource = newKeySource;
  34865. if (keySource != 0)
  34866. keySource->addKeyListener (this);
  34867. }
  34868. }
  34869. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  34870. const int commandID_,
  34871. const bool generateTooltip_)
  34872. {
  34873. commandID = commandID_;
  34874. generateTooltip = generateTooltip_;
  34875. if (commandManagerToUse != commandManagerToUse_)
  34876. {
  34877. if (commandManagerToUse != 0)
  34878. commandManagerToUse->removeListener (this);
  34879. commandManagerToUse = commandManagerToUse_;
  34880. if (commandManagerToUse != 0)
  34881. commandManagerToUse->addListener (this);
  34882. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34883. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34884. // it is that this button represents, and the button will update its state to reflect this
  34885. // in the applicationCommandListChanged() method.
  34886. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34887. }
  34888. if (commandManagerToUse != 0)
  34889. applicationCommandListChanged();
  34890. else
  34891. setEnabled (true);
  34892. }
  34893. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  34894. {
  34895. if (info.commandID == commandID
  34896. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  34897. {
  34898. flashButtonState();
  34899. }
  34900. }
  34901. void Button::applicationCommandListChanged()
  34902. {
  34903. if (commandManagerToUse != 0)
  34904. {
  34905. ApplicationCommandInfo info (0);
  34906. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  34907. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  34908. if (target != 0)
  34909. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  34910. }
  34911. }
  34912. void Button::addShortcut (const KeyPress& key)
  34913. {
  34914. if (key.isValid())
  34915. {
  34916. jassert (! isRegisteredForShortcut (key)); // already registered!
  34917. shortcuts.add (key);
  34918. parentHierarchyChanged();
  34919. }
  34920. }
  34921. void Button::clearShortcuts()
  34922. {
  34923. shortcuts.clear();
  34924. parentHierarchyChanged();
  34925. }
  34926. bool Button::isShortcutPressed() const
  34927. {
  34928. if (! isCurrentlyBlockedByAnotherModalComponent())
  34929. {
  34930. for (int i = shortcuts.size(); --i >= 0;)
  34931. if (shortcuts.getReference(i).isCurrentlyDown())
  34932. return true;
  34933. }
  34934. return false;
  34935. }
  34936. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  34937. {
  34938. for (int i = shortcuts.size(); --i >= 0;)
  34939. if (key == shortcuts.getReference(i))
  34940. return true;
  34941. return false;
  34942. }
  34943. bool Button::keyStateChanged (const bool, Component*)
  34944. {
  34945. if (! isEnabled())
  34946. return false;
  34947. const bool wasDown = isKeyDown;
  34948. isKeyDown = isShortcutPressed();
  34949. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  34950. getRepeatTimer().startTimer (autoRepeatDelay);
  34951. updateState();
  34952. if (isEnabled() && wasDown && ! isKeyDown)
  34953. {
  34954. internalClickCallback (ModifierKeys::getCurrentModifiers());
  34955. // (return immediately - this button may now have been deleted)
  34956. return true;
  34957. }
  34958. return wasDown || isKeyDown;
  34959. }
  34960. bool Button::keyPressed (const KeyPress&, Component*)
  34961. {
  34962. // returning true will avoid forwarding events for keys that we're using as shortcuts
  34963. return isShortcutPressed();
  34964. }
  34965. bool Button::keyPressed (const KeyPress& key)
  34966. {
  34967. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  34968. {
  34969. triggerClick();
  34970. return true;
  34971. }
  34972. return false;
  34973. }
  34974. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  34975. const int repeatMillisecs,
  34976. const int minimumDelayInMillisecs) throw()
  34977. {
  34978. autoRepeatDelay = initialDelayMillisecs;
  34979. autoRepeatSpeed = repeatMillisecs;
  34980. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  34981. }
  34982. void Button::repeatTimerCallback()
  34983. {
  34984. if (needsRepainting)
  34985. {
  34986. getRepeatTimer().stopTimer();
  34987. updateState();
  34988. needsRepainting = false;
  34989. }
  34990. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState() == buttonDown)))
  34991. {
  34992. int repeatSpeed = autoRepeatSpeed;
  34993. if (autoRepeatMinimumDelay >= 0)
  34994. {
  34995. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  34996. timeHeldDown *= timeHeldDown;
  34997. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  34998. }
  34999. repeatSpeed = jmax (1, repeatSpeed);
  35000. const uint32 now = Time::getMillisecondCounter();
  35001. // if we've been blocked from repeating often enough, speed up the repeat timer to compensate..
  35002. if (lastRepeatTime != 0 && (int) (now - lastRepeatTime) > repeatSpeed * 2)
  35003. repeatSpeed = jmax (1, repeatSpeed / 2);
  35004. lastRepeatTime = now;
  35005. getRepeatTimer().startTimer (repeatSpeed);
  35006. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35007. }
  35008. else if (! needsToRelease)
  35009. {
  35010. getRepeatTimer().stopTimer();
  35011. }
  35012. }
  35013. Button::RepeatTimer& Button::getRepeatTimer()
  35014. {
  35015. if (repeatTimer == 0)
  35016. repeatTimer = new RepeatTimer (*this);
  35017. return *repeatTimer;
  35018. }
  35019. END_JUCE_NAMESPACE
  35020. /*** End of inlined file: juce_Button.cpp ***/
  35021. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35022. BEGIN_JUCE_NAMESPACE
  35023. DrawableButton::DrawableButton (const String& name,
  35024. const DrawableButton::ButtonStyle buttonStyle)
  35025. : Button (name),
  35026. style (buttonStyle),
  35027. currentImage (0),
  35028. edgeIndent (3)
  35029. {
  35030. if (buttonStyle == ImageOnButtonBackground)
  35031. {
  35032. backgroundOff = Colour (0xffbbbbff);
  35033. backgroundOn = Colour (0xff3333ff);
  35034. }
  35035. else
  35036. {
  35037. backgroundOff = Colours::transparentBlack;
  35038. backgroundOn = Colour (0xaabbbbff);
  35039. }
  35040. }
  35041. DrawableButton::~DrawableButton()
  35042. {
  35043. }
  35044. void DrawableButton::setImages (const Drawable* normal,
  35045. const Drawable* over,
  35046. const Drawable* down,
  35047. const Drawable* disabled,
  35048. const Drawable* normalOn,
  35049. const Drawable* overOn,
  35050. const Drawable* downOn,
  35051. const Drawable* disabledOn)
  35052. {
  35053. jassert (normal != 0); // you really need to give it at least a normal image..
  35054. if (normal != 0) normalImage = normal->createCopy();
  35055. if (over != 0) overImage = over->createCopy();
  35056. if (down != 0) downImage = down->createCopy();
  35057. if (disabled != 0) disabledImage = disabled->createCopy();
  35058. if (normalOn != 0) normalImageOn = normalOn->createCopy();
  35059. if (overOn != 0) overImageOn = overOn->createCopy();
  35060. if (downOn != 0) downImageOn = downOn->createCopy();
  35061. if (disabledOn != 0) disabledImageOn = disabledOn->createCopy();
  35062. buttonStateChanged();
  35063. }
  35064. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35065. {
  35066. if (style != newStyle)
  35067. {
  35068. style = newStyle;
  35069. buttonStateChanged();
  35070. }
  35071. }
  35072. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35073. const Colour& toggledOnColour)
  35074. {
  35075. if (backgroundOff != toggledOffColour
  35076. || backgroundOn != toggledOnColour)
  35077. {
  35078. backgroundOff = toggledOffColour;
  35079. backgroundOn = toggledOnColour;
  35080. repaint();
  35081. }
  35082. }
  35083. const Colour& DrawableButton::getBackgroundColour() const throw()
  35084. {
  35085. return getToggleState() ? backgroundOn
  35086. : backgroundOff;
  35087. }
  35088. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35089. {
  35090. edgeIndent = numPixelsIndent;
  35091. repaint();
  35092. resized();
  35093. }
  35094. void DrawableButton::resized()
  35095. {
  35096. Button::resized();
  35097. if (currentImage != 0)
  35098. {
  35099. if (style == ImageRaw)
  35100. {
  35101. currentImage->setOriginWithOriginalSize (Point<float>());
  35102. }
  35103. else
  35104. {
  35105. Rectangle<int> imageSpace;
  35106. if (style == ImageOnButtonBackground)
  35107. {
  35108. imageSpace = getLocalBounds().reduced (getWidth() / 4, getHeight() / 4);
  35109. }
  35110. else
  35111. {
  35112. const int textH = (style == ImageAboveTextLabel) ? jmin (16, proportionOfHeight (0.25f)) : 0;
  35113. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35114. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35115. imageSpace.setBounds (indentX, indentY,
  35116. getWidth() - indentX * 2,
  35117. getHeight() - indentY * 2 - textH);
  35118. }
  35119. currentImage->setTransformToFit (imageSpace.toFloat(), RectanglePlacement::centred);
  35120. }
  35121. }
  35122. }
  35123. void DrawableButton::buttonStateChanged()
  35124. {
  35125. repaint();
  35126. Drawable* imageToDraw = 0;
  35127. float opacity = 1.0f;
  35128. if (isEnabled())
  35129. {
  35130. imageToDraw = getCurrentImage();
  35131. }
  35132. else
  35133. {
  35134. imageToDraw = getToggleState() ? disabledImageOn
  35135. : disabledImage;
  35136. if (imageToDraw == 0)
  35137. {
  35138. opacity = 0.4f;
  35139. imageToDraw = getNormalImage();
  35140. }
  35141. }
  35142. if (imageToDraw != currentImage)
  35143. {
  35144. removeChildComponent (currentImage);
  35145. currentImage = imageToDraw;
  35146. if (currentImage != 0)
  35147. {
  35148. currentImage->setInterceptsMouseClicks (false, false);
  35149. addAndMakeVisible (currentImage);
  35150. DrawableButton::resized();
  35151. }
  35152. }
  35153. if (currentImage != 0)
  35154. currentImage->setAlpha (opacity);
  35155. }
  35156. void DrawableButton::paintButton (Graphics& g,
  35157. bool isMouseOverButton,
  35158. bool isButtonDown)
  35159. {
  35160. if (style == ImageOnButtonBackground)
  35161. {
  35162. getLookAndFeel().drawButtonBackground (g, *this,
  35163. getBackgroundColour(),
  35164. isMouseOverButton,
  35165. isButtonDown);
  35166. }
  35167. else
  35168. {
  35169. g.fillAll (getBackgroundColour());
  35170. const int textH = (style == ImageAboveTextLabel)
  35171. ? jmin (16, proportionOfHeight (0.25f))
  35172. : 0;
  35173. if (textH > 0)
  35174. {
  35175. g.setFont ((float) textH);
  35176. g.setColour (findColour (DrawableButton::textColourId)
  35177. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35178. g.drawFittedText (getButtonText(),
  35179. 2, getHeight() - textH - 1,
  35180. getWidth() - 4, textH,
  35181. Justification::centred, 1);
  35182. }
  35183. }
  35184. }
  35185. Drawable* DrawableButton::getCurrentImage() const throw()
  35186. {
  35187. if (isDown())
  35188. return getDownImage();
  35189. if (isOver())
  35190. return getOverImage();
  35191. return getNormalImage();
  35192. }
  35193. Drawable* DrawableButton::getNormalImage() const throw()
  35194. {
  35195. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35196. : normalImage;
  35197. }
  35198. Drawable* DrawableButton::getOverImage() const throw()
  35199. {
  35200. Drawable* d = normalImage;
  35201. if (getToggleState())
  35202. {
  35203. if (overImageOn != 0)
  35204. d = overImageOn;
  35205. else if (normalImageOn != 0)
  35206. d = normalImageOn;
  35207. else if (overImage != 0)
  35208. d = overImage;
  35209. }
  35210. else
  35211. {
  35212. if (overImage != 0)
  35213. d = overImage;
  35214. }
  35215. return d;
  35216. }
  35217. Drawable* DrawableButton::getDownImage() const throw()
  35218. {
  35219. Drawable* d = normalImage;
  35220. if (getToggleState())
  35221. {
  35222. if (downImageOn != 0)
  35223. d = downImageOn;
  35224. else if (overImageOn != 0)
  35225. d = overImageOn;
  35226. else if (normalImageOn != 0)
  35227. d = normalImageOn;
  35228. else if (downImage != 0)
  35229. d = downImage;
  35230. else
  35231. d = getOverImage();
  35232. }
  35233. else
  35234. {
  35235. if (downImage != 0)
  35236. d = downImage;
  35237. else
  35238. d = getOverImage();
  35239. }
  35240. return d;
  35241. }
  35242. END_JUCE_NAMESPACE
  35243. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35244. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35245. BEGIN_JUCE_NAMESPACE
  35246. HyperlinkButton::HyperlinkButton (const String& linkText,
  35247. const URL& linkURL)
  35248. : Button (linkText),
  35249. url (linkURL),
  35250. font (14.0f, Font::underlined),
  35251. resizeFont (true),
  35252. justification (Justification::centred)
  35253. {
  35254. setMouseCursor (MouseCursor::PointingHandCursor);
  35255. setTooltip (linkURL.toString (false));
  35256. }
  35257. HyperlinkButton::~HyperlinkButton()
  35258. {
  35259. }
  35260. void HyperlinkButton::setFont (const Font& newFont,
  35261. const bool resizeToMatchComponentHeight,
  35262. const Justification& justificationType)
  35263. {
  35264. font = newFont;
  35265. resizeFont = resizeToMatchComponentHeight;
  35266. justification = justificationType;
  35267. repaint();
  35268. }
  35269. void HyperlinkButton::setURL (const URL& newURL) throw()
  35270. {
  35271. url = newURL;
  35272. setTooltip (newURL.toString (false));
  35273. }
  35274. const Font HyperlinkButton::getFontToUse() const
  35275. {
  35276. Font f (font);
  35277. if (resizeFont)
  35278. f.setHeight (getHeight() * 0.7f);
  35279. return f;
  35280. }
  35281. void HyperlinkButton::changeWidthToFitText()
  35282. {
  35283. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35284. }
  35285. void HyperlinkButton::colourChanged()
  35286. {
  35287. repaint();
  35288. }
  35289. void HyperlinkButton::clicked()
  35290. {
  35291. if (url.isWellFormed())
  35292. url.launchInDefaultBrowser();
  35293. }
  35294. void HyperlinkButton::paintButton (Graphics& g,
  35295. bool isMouseOverButton,
  35296. bool isButtonDown)
  35297. {
  35298. const Colour textColour (findColour (textColourId));
  35299. if (isEnabled())
  35300. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35301. : textColour);
  35302. else
  35303. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35304. g.setFont (getFontToUse());
  35305. g.drawText (getButtonText(),
  35306. 2, 0, getWidth() - 2, getHeight(),
  35307. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35308. true);
  35309. }
  35310. END_JUCE_NAMESPACE
  35311. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35312. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35313. BEGIN_JUCE_NAMESPACE
  35314. ImageButton::ImageButton (const String& text_)
  35315. : Button (text_),
  35316. scaleImageToFit (true),
  35317. preserveProportions (true),
  35318. alphaThreshold (0),
  35319. imageX (0),
  35320. imageY (0),
  35321. imageW (0),
  35322. imageH (0),
  35323. normalImage (0),
  35324. overImage (0),
  35325. downImage (0)
  35326. {
  35327. }
  35328. ImageButton::~ImageButton()
  35329. {
  35330. }
  35331. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35332. const bool rescaleImagesWhenButtonSizeChanges,
  35333. const bool preserveImageProportions,
  35334. const Image& normalImage_,
  35335. const float imageOpacityWhenNormal,
  35336. const Colour& overlayColourWhenNormal,
  35337. const Image& overImage_,
  35338. const float imageOpacityWhenOver,
  35339. const Colour& overlayColourWhenOver,
  35340. const Image& downImage_,
  35341. const float imageOpacityWhenDown,
  35342. const Colour& overlayColourWhenDown,
  35343. const float hitTestAlphaThreshold)
  35344. {
  35345. normalImage = normalImage_;
  35346. overImage = overImage_;
  35347. downImage = downImage_;
  35348. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35349. {
  35350. imageW = normalImage.getWidth();
  35351. imageH = normalImage.getHeight();
  35352. setSize (imageW, imageH);
  35353. }
  35354. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35355. preserveProportions = preserveImageProportions;
  35356. normalOpacity = imageOpacityWhenNormal;
  35357. normalOverlay = overlayColourWhenNormal;
  35358. overOpacity = imageOpacityWhenOver;
  35359. overOverlay = overlayColourWhenOver;
  35360. downOpacity = imageOpacityWhenDown;
  35361. downOverlay = overlayColourWhenDown;
  35362. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35363. repaint();
  35364. }
  35365. const Image ImageButton::getCurrentImage() const
  35366. {
  35367. if (isDown() || getToggleState())
  35368. return getDownImage();
  35369. if (isOver())
  35370. return getOverImage();
  35371. return getNormalImage();
  35372. }
  35373. const Image ImageButton::getNormalImage() const
  35374. {
  35375. return normalImage;
  35376. }
  35377. const Image ImageButton::getOverImage() const
  35378. {
  35379. return overImage.isValid() ? overImage
  35380. : normalImage;
  35381. }
  35382. const Image ImageButton::getDownImage() const
  35383. {
  35384. return downImage.isValid() ? downImage
  35385. : getOverImage();
  35386. }
  35387. void ImageButton::paintButton (Graphics& g,
  35388. bool isMouseOverButton,
  35389. bool isButtonDown)
  35390. {
  35391. if (! isEnabled())
  35392. {
  35393. isMouseOverButton = false;
  35394. isButtonDown = false;
  35395. }
  35396. Image im (getCurrentImage());
  35397. if (im.isValid())
  35398. {
  35399. const int iw = im.getWidth();
  35400. const int ih = im.getHeight();
  35401. imageW = getWidth();
  35402. imageH = getHeight();
  35403. imageX = (imageW - iw) >> 1;
  35404. imageY = (imageH - ih) >> 1;
  35405. if (scaleImageToFit)
  35406. {
  35407. if (preserveProportions)
  35408. {
  35409. int newW, newH;
  35410. const float imRatio = ih / (float)iw;
  35411. const float destRatio = imageH / (float)imageW;
  35412. if (imRatio > destRatio)
  35413. {
  35414. newW = roundToInt (imageH / imRatio);
  35415. newH = imageH;
  35416. }
  35417. else
  35418. {
  35419. newW = imageW;
  35420. newH = roundToInt (imageW * imRatio);
  35421. }
  35422. imageX = (imageW - newW) / 2;
  35423. imageY = (imageH - newH) / 2;
  35424. imageW = newW;
  35425. imageH = newH;
  35426. }
  35427. else
  35428. {
  35429. imageX = 0;
  35430. imageY = 0;
  35431. }
  35432. }
  35433. if (! scaleImageToFit)
  35434. {
  35435. imageW = iw;
  35436. imageH = ih;
  35437. }
  35438. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35439. isButtonDown ? downOverlay
  35440. : (isMouseOverButton ? overOverlay
  35441. : normalOverlay),
  35442. isButtonDown ? downOpacity
  35443. : (isMouseOverButton ? overOpacity
  35444. : normalOpacity),
  35445. *this);
  35446. }
  35447. }
  35448. bool ImageButton::hitTest (int x, int y)
  35449. {
  35450. if (alphaThreshold == 0)
  35451. return true;
  35452. Image im (getCurrentImage());
  35453. return im.isNull() || (imageW > 0 && imageH > 0
  35454. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35455. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35456. }
  35457. END_JUCE_NAMESPACE
  35458. /*** End of inlined file: juce_ImageButton.cpp ***/
  35459. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35460. BEGIN_JUCE_NAMESPACE
  35461. ShapeButton::ShapeButton (const String& text_,
  35462. const Colour& normalColour_,
  35463. const Colour& overColour_,
  35464. const Colour& downColour_)
  35465. : Button (text_),
  35466. normalColour (normalColour_),
  35467. overColour (overColour_),
  35468. downColour (downColour_),
  35469. maintainShapeProportions (false),
  35470. outlineWidth (0.0f)
  35471. {
  35472. }
  35473. ShapeButton::~ShapeButton()
  35474. {
  35475. }
  35476. void ShapeButton::setColours (const Colour& newNormalColour,
  35477. const Colour& newOverColour,
  35478. const Colour& newDownColour)
  35479. {
  35480. normalColour = newNormalColour;
  35481. overColour = newOverColour;
  35482. downColour = newDownColour;
  35483. }
  35484. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35485. const float newOutlineWidth)
  35486. {
  35487. outlineColour = newOutlineColour;
  35488. outlineWidth = newOutlineWidth;
  35489. }
  35490. void ShapeButton::setShape (const Path& newShape,
  35491. const bool resizeNowToFitThisShape,
  35492. const bool maintainShapeProportions_,
  35493. const bool hasShadow)
  35494. {
  35495. shape = newShape;
  35496. maintainShapeProportions = maintainShapeProportions_;
  35497. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35498. setComponentEffect ((hasShadow) ? &shadow : 0);
  35499. if (resizeNowToFitThisShape)
  35500. {
  35501. Rectangle<float> bounds (shape.getBounds());
  35502. if (hasShadow)
  35503. bounds.expand (4.0f, 4.0f);
  35504. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35505. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35506. 1 + (int) (bounds.getHeight() + outlineWidth));
  35507. }
  35508. }
  35509. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35510. {
  35511. if (! isEnabled())
  35512. {
  35513. isMouseOverButton = false;
  35514. isButtonDown = false;
  35515. }
  35516. g.setColour ((isButtonDown) ? downColour
  35517. : (isMouseOverButton) ? overColour
  35518. : normalColour);
  35519. int w = getWidth();
  35520. int h = getHeight();
  35521. if (getComponentEffect() != 0)
  35522. {
  35523. w -= 4;
  35524. h -= 4;
  35525. }
  35526. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35527. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35528. w - offset - outlineWidth,
  35529. h - offset - outlineWidth,
  35530. maintainShapeProportions));
  35531. g.fillPath (shape, trans);
  35532. if (outlineWidth > 0.0f)
  35533. {
  35534. g.setColour (outlineColour);
  35535. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35536. }
  35537. }
  35538. END_JUCE_NAMESPACE
  35539. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35540. /*** Start of inlined file: juce_TextButton.cpp ***/
  35541. BEGIN_JUCE_NAMESPACE
  35542. TextButton::TextButton (const String& name,
  35543. const String& toolTip)
  35544. : Button (name)
  35545. {
  35546. setTooltip (toolTip);
  35547. }
  35548. TextButton::~TextButton()
  35549. {
  35550. }
  35551. void TextButton::paintButton (Graphics& g,
  35552. bool isMouseOverButton,
  35553. bool isButtonDown)
  35554. {
  35555. getLookAndFeel().drawButtonBackground (g, *this,
  35556. findColour (getToggleState() ? buttonOnColourId
  35557. : buttonColourId),
  35558. isMouseOverButton,
  35559. isButtonDown);
  35560. getLookAndFeel().drawButtonText (g, *this,
  35561. isMouseOverButton,
  35562. isButtonDown);
  35563. }
  35564. void TextButton::colourChanged()
  35565. {
  35566. repaint();
  35567. }
  35568. const Font TextButton::getFont()
  35569. {
  35570. return Font (jmin (15.0f, getHeight() * 0.6f));
  35571. }
  35572. void TextButton::changeWidthToFitText (const int newHeight)
  35573. {
  35574. if (newHeight >= 0)
  35575. setSize (jmax (1, getWidth()), newHeight);
  35576. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35577. getHeight());
  35578. }
  35579. END_JUCE_NAMESPACE
  35580. /*** End of inlined file: juce_TextButton.cpp ***/
  35581. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35582. BEGIN_JUCE_NAMESPACE
  35583. ToggleButton::ToggleButton (const String& buttonText)
  35584. : Button (buttonText)
  35585. {
  35586. setClickingTogglesState (true);
  35587. }
  35588. ToggleButton::~ToggleButton()
  35589. {
  35590. }
  35591. void ToggleButton::paintButton (Graphics& g,
  35592. bool isMouseOverButton,
  35593. bool isButtonDown)
  35594. {
  35595. getLookAndFeel().drawToggleButton (g, *this,
  35596. isMouseOverButton,
  35597. isButtonDown);
  35598. }
  35599. void ToggleButton::changeWidthToFitText()
  35600. {
  35601. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35602. }
  35603. void ToggleButton::colourChanged()
  35604. {
  35605. repaint();
  35606. }
  35607. END_JUCE_NAMESPACE
  35608. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35609. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35610. BEGIN_JUCE_NAMESPACE
  35611. ToolbarButton::ToolbarButton (const int itemId_, const String& buttonText,
  35612. Drawable* const normalImage_, Drawable* const toggledOnImage_)
  35613. : ToolbarItemComponent (itemId_, buttonText, true),
  35614. normalImage (normalImage_),
  35615. toggledOnImage (toggledOnImage_),
  35616. currentImage (0)
  35617. {
  35618. jassert (normalImage_ != 0);
  35619. }
  35620. ToolbarButton::~ToolbarButton()
  35621. {
  35622. }
  35623. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth, bool /*isToolbarVertical*/, int& preferredSize, int& minSize, int& maxSize)
  35624. {
  35625. preferredSize = minSize = maxSize = toolbarDepth;
  35626. return true;
  35627. }
  35628. void ToolbarButton::paintButtonArea (Graphics&, int /*width*/, int /*height*/, bool /*isMouseOver*/, bool /*isMouseDown*/)
  35629. {
  35630. }
  35631. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35632. {
  35633. buttonStateChanged();
  35634. }
  35635. void ToolbarButton::updateDrawable()
  35636. {
  35637. if (currentImage != 0)
  35638. {
  35639. currentImage->setTransformToFit (getContentArea().toFloat(), RectanglePlacement::centred);
  35640. currentImage->setAlpha (isEnabled() ? 1.0f : 0.5f);
  35641. }
  35642. }
  35643. void ToolbarButton::resized()
  35644. {
  35645. ToolbarItemComponent::resized();
  35646. updateDrawable();
  35647. }
  35648. void ToolbarButton::enablementChanged()
  35649. {
  35650. ToolbarItemComponent::enablementChanged();
  35651. updateDrawable();
  35652. }
  35653. void ToolbarButton::buttonStateChanged()
  35654. {
  35655. Drawable* d = normalImage;
  35656. if (getToggleState() && toggledOnImage != 0)
  35657. d = toggledOnImage;
  35658. if (d != currentImage)
  35659. {
  35660. removeChildComponent (currentImage);
  35661. currentImage = d;
  35662. if (d != 0)
  35663. {
  35664. enablementChanged();
  35665. addAndMakeVisible (d);
  35666. updateDrawable();
  35667. }
  35668. }
  35669. }
  35670. END_JUCE_NAMESPACE
  35671. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35672. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35673. BEGIN_JUCE_NAMESPACE
  35674. class CodeDocumentLine
  35675. {
  35676. public:
  35677. CodeDocumentLine (const String::CharPointerType& line_,
  35678. const int lineLength_,
  35679. const int numNewLineChars,
  35680. const int lineStartInFile_)
  35681. : line (line_, lineLength_),
  35682. lineStartInFile (lineStartInFile_),
  35683. lineLength (lineLength_),
  35684. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35685. {
  35686. }
  35687. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35688. {
  35689. String::CharPointerType t (text.getCharPointer());
  35690. int charNumInFile = 0;
  35691. bool finished = t.isEmpty();
  35692. while (! finished)
  35693. {
  35694. String::CharPointerType startOfLine (t);
  35695. int startOfLineInFile = charNumInFile;
  35696. int lineLength = 0;
  35697. int numNewLineChars = 0;
  35698. for (;;)
  35699. {
  35700. const juce_wchar c = t.getAndAdvance();
  35701. if (c == 0)
  35702. {
  35703. finished = true;
  35704. break;
  35705. }
  35706. ++charNumInFile;
  35707. ++lineLength;
  35708. if (c == '\r')
  35709. {
  35710. ++numNewLineChars;
  35711. if (*t == '\n')
  35712. {
  35713. ++t;
  35714. ++charNumInFile;
  35715. ++lineLength;
  35716. ++numNewLineChars;
  35717. }
  35718. break;
  35719. }
  35720. if (c == '\n')
  35721. {
  35722. ++numNewLineChars;
  35723. break;
  35724. }
  35725. }
  35726. newLines.add (new CodeDocumentLine (startOfLine, lineLength,
  35727. numNewLineChars, startOfLineInFile));
  35728. }
  35729. jassert (charNumInFile == text.length());
  35730. }
  35731. bool endsWithLineBreak() const throw()
  35732. {
  35733. return lineLengthWithoutNewLines != lineLength;
  35734. }
  35735. void updateLength() throw()
  35736. {
  35737. lineLengthWithoutNewLines = lineLength = line.length();
  35738. while (lineLengthWithoutNewLines > 0
  35739. && (line [lineLengthWithoutNewLines - 1] == '\n'
  35740. || line [lineLengthWithoutNewLines - 1] == '\r'))
  35741. {
  35742. --lineLengthWithoutNewLines;
  35743. }
  35744. }
  35745. String line;
  35746. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  35747. };
  35748. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  35749. : document (document_),
  35750. currentLine (document_->lines[0]),
  35751. line (0),
  35752. position (0)
  35753. {
  35754. }
  35755. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  35756. : document (other.document),
  35757. currentLine (other.currentLine),
  35758. line (other.line),
  35759. position (other.position)
  35760. {
  35761. }
  35762. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  35763. {
  35764. document = other.document;
  35765. currentLine = other.currentLine;
  35766. line = other.line;
  35767. position = other.position;
  35768. return *this;
  35769. }
  35770. CodeDocument::Iterator::~Iterator() throw()
  35771. {
  35772. }
  35773. juce_wchar CodeDocument::Iterator::nextChar()
  35774. {
  35775. if (currentLine == 0)
  35776. return 0;
  35777. jassert (currentLine == document->lines.getUnchecked (line));
  35778. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  35779. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35780. {
  35781. ++line;
  35782. currentLine = document->lines [line];
  35783. }
  35784. return result;
  35785. }
  35786. void CodeDocument::Iterator::skip()
  35787. {
  35788. if (currentLine != 0)
  35789. {
  35790. jassert (currentLine == document->lines.getUnchecked (line));
  35791. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  35792. {
  35793. ++line;
  35794. currentLine = document->lines [line];
  35795. }
  35796. }
  35797. }
  35798. void CodeDocument::Iterator::skipToEndOfLine()
  35799. {
  35800. if (currentLine != 0)
  35801. {
  35802. jassert (currentLine == document->lines.getUnchecked (line));
  35803. ++line;
  35804. currentLine = document->lines [line];
  35805. if (currentLine != 0)
  35806. position = currentLine->lineStartInFile;
  35807. else
  35808. position = document->getNumCharacters();
  35809. }
  35810. }
  35811. juce_wchar CodeDocument::Iterator::peekNextChar() const
  35812. {
  35813. if (currentLine == 0)
  35814. return 0;
  35815. jassert (currentLine == document->lines.getUnchecked (line));
  35816. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  35817. }
  35818. void CodeDocument::Iterator::skipWhitespace()
  35819. {
  35820. while (CharacterFunctions::isWhitespace (peekNextChar()))
  35821. skip();
  35822. }
  35823. bool CodeDocument::Iterator::isEOF() const throw()
  35824. {
  35825. return currentLine == 0;
  35826. }
  35827. CodeDocument::Position::Position() throw()
  35828. : owner (0), characterPos (0), line (0),
  35829. indexInLine (0), positionMaintained (false)
  35830. {
  35831. }
  35832. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35833. const int line_, const int indexInLine_) throw()
  35834. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35835. characterPos (0), line (line_),
  35836. indexInLine (indexInLine_), positionMaintained (false)
  35837. {
  35838. setLineAndIndex (line_, indexInLine_);
  35839. }
  35840. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  35841. const int characterPos_) throw()
  35842. : owner (const_cast <CodeDocument*> (ownerDocument)),
  35843. positionMaintained (false)
  35844. {
  35845. setPosition (characterPos_);
  35846. }
  35847. CodeDocument::Position::Position (const Position& other) throw()
  35848. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  35849. indexInLine (other.indexInLine), positionMaintained (false)
  35850. {
  35851. jassert (*this == other);
  35852. }
  35853. CodeDocument::Position::~Position()
  35854. {
  35855. setPositionMaintained (false);
  35856. }
  35857. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  35858. {
  35859. if (this != &other)
  35860. {
  35861. const bool wasPositionMaintained = positionMaintained;
  35862. if (owner != other.owner)
  35863. setPositionMaintained (false);
  35864. owner = other.owner;
  35865. line = other.line;
  35866. indexInLine = other.indexInLine;
  35867. characterPos = other.characterPos;
  35868. setPositionMaintained (wasPositionMaintained);
  35869. jassert (*this == other);
  35870. }
  35871. return *this;
  35872. }
  35873. bool CodeDocument::Position::operator== (const Position& other) const throw()
  35874. {
  35875. jassert ((characterPos == other.characterPos)
  35876. == (line == other.line && indexInLine == other.indexInLine));
  35877. return characterPos == other.characterPos
  35878. && line == other.line
  35879. && indexInLine == other.indexInLine
  35880. && owner == other.owner;
  35881. }
  35882. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  35883. {
  35884. return ! operator== (other);
  35885. }
  35886. void CodeDocument::Position::setLineAndIndex (const int newLineNum, const int newIndexInLine)
  35887. {
  35888. jassert (owner != 0);
  35889. if (owner->lines.size() == 0)
  35890. {
  35891. line = 0;
  35892. indexInLine = 0;
  35893. characterPos = 0;
  35894. }
  35895. else
  35896. {
  35897. if (newLineNum >= owner->lines.size())
  35898. {
  35899. line = owner->lines.size() - 1;
  35900. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35901. jassert (l != 0);
  35902. indexInLine = l->lineLengthWithoutNewLines;
  35903. characterPos = l->lineStartInFile + indexInLine;
  35904. }
  35905. else
  35906. {
  35907. line = jmax (0, newLineNum);
  35908. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35909. jassert (l != 0);
  35910. if (l->lineLengthWithoutNewLines > 0)
  35911. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  35912. else
  35913. indexInLine = 0;
  35914. characterPos = l->lineStartInFile + indexInLine;
  35915. }
  35916. }
  35917. }
  35918. void CodeDocument::Position::setPosition (const int newPosition)
  35919. {
  35920. jassert (owner != 0);
  35921. line = 0;
  35922. indexInLine = 0;
  35923. characterPos = 0;
  35924. if (newPosition > 0)
  35925. {
  35926. int lineStart = 0;
  35927. int lineEnd = owner->lines.size();
  35928. for (;;)
  35929. {
  35930. if (lineEnd - lineStart < 4)
  35931. {
  35932. for (int i = lineStart; i < lineEnd; ++i)
  35933. {
  35934. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  35935. int index = newPosition - l->lineStartInFile;
  35936. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  35937. {
  35938. line = i;
  35939. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  35940. characterPos = l->lineStartInFile + indexInLine;
  35941. }
  35942. }
  35943. break;
  35944. }
  35945. else
  35946. {
  35947. const int midIndex = (lineStart + lineEnd + 1) / 2;
  35948. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  35949. if (newPosition >= mid->lineStartInFile)
  35950. lineStart = midIndex;
  35951. else
  35952. lineEnd = midIndex;
  35953. }
  35954. }
  35955. }
  35956. }
  35957. void CodeDocument::Position::moveBy (int characterDelta)
  35958. {
  35959. jassert (owner != 0);
  35960. if (characterDelta == 1)
  35961. {
  35962. setPosition (getPosition());
  35963. // If moving right, make sure we don't get stuck between the \r and \n characters..
  35964. if (line < owner->lines.size())
  35965. {
  35966. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  35967. if (indexInLine + characterDelta < l->lineLength
  35968. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  35969. ++characterDelta;
  35970. }
  35971. }
  35972. setPosition (characterPos + characterDelta);
  35973. }
  35974. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  35975. {
  35976. CodeDocument::Position p (*this);
  35977. p.moveBy (characterDelta);
  35978. return p;
  35979. }
  35980. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  35981. {
  35982. CodeDocument::Position p (*this);
  35983. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  35984. return p;
  35985. }
  35986. const juce_wchar CodeDocument::Position::getCharacter() const
  35987. {
  35988. const CodeDocumentLine* const l = owner->lines [line];
  35989. return l == 0 ? 0 : l->line [getIndexInLine()];
  35990. }
  35991. const String CodeDocument::Position::getLineText() const
  35992. {
  35993. const CodeDocumentLine* const l = owner->lines [line];
  35994. return l == 0 ? String::empty : l->line;
  35995. }
  35996. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  35997. {
  35998. if (isMaintained != positionMaintained)
  35999. {
  36000. positionMaintained = isMaintained;
  36001. if (owner != 0)
  36002. {
  36003. if (isMaintained)
  36004. {
  36005. jassert (! owner->positionsToMaintain.contains (this));
  36006. owner->positionsToMaintain.add (this);
  36007. }
  36008. else
  36009. {
  36010. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36011. jassert (owner->positionsToMaintain.contains (this));
  36012. owner->positionsToMaintain.removeValue (this);
  36013. }
  36014. }
  36015. }
  36016. }
  36017. CodeDocument::CodeDocument()
  36018. : undoManager (std::numeric_limits<int>::max(), 10000),
  36019. currentActionIndex (0),
  36020. indexOfSavedState (-1),
  36021. maximumLineLength (-1),
  36022. newLineChars ("\r\n")
  36023. {
  36024. }
  36025. CodeDocument::~CodeDocument()
  36026. {
  36027. }
  36028. const String CodeDocument::getAllContent() const
  36029. {
  36030. return getTextBetween (Position (this, 0),
  36031. Position (this, lines.size(), 0));
  36032. }
  36033. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36034. {
  36035. if (end.getPosition() <= start.getPosition())
  36036. return String::empty;
  36037. const int startLine = start.getLineNumber();
  36038. const int endLine = end.getLineNumber();
  36039. if (startLine == endLine)
  36040. {
  36041. CodeDocumentLine* const line = lines [startLine];
  36042. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36043. }
  36044. String result;
  36045. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36046. String::Concatenator concatenator (result);
  36047. const int maxLine = jmin (lines.size() - 1, endLine);
  36048. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36049. {
  36050. const CodeDocumentLine* line = lines.getUnchecked(i);
  36051. int len = line->lineLength;
  36052. if (i == startLine)
  36053. {
  36054. const int index = start.getIndexInLine();
  36055. concatenator.append (line->line.substring (index, len));
  36056. }
  36057. else if (i == endLine)
  36058. {
  36059. len = end.getIndexInLine();
  36060. concatenator.append (line->line.substring (0, len));
  36061. }
  36062. else
  36063. {
  36064. concatenator.append (line->line);
  36065. }
  36066. }
  36067. return result;
  36068. }
  36069. int CodeDocument::getNumCharacters() const throw()
  36070. {
  36071. const CodeDocumentLine* const lastLine = lines.getLast();
  36072. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36073. }
  36074. const String CodeDocument::getLine (const int lineIndex) const throw()
  36075. {
  36076. const CodeDocumentLine* const line = lines [lineIndex];
  36077. return (line == 0) ? String::empty : line->line;
  36078. }
  36079. int CodeDocument::getMaximumLineLength() throw()
  36080. {
  36081. if (maximumLineLength < 0)
  36082. {
  36083. maximumLineLength = 0;
  36084. for (int i = lines.size(); --i >= 0;)
  36085. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36086. }
  36087. return maximumLineLength;
  36088. }
  36089. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36090. {
  36091. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36092. }
  36093. void CodeDocument::insertText (const Position& position, const String& text)
  36094. {
  36095. insert (text, position.getPosition(), true);
  36096. }
  36097. void CodeDocument::replaceAllContent (const String& newContent)
  36098. {
  36099. remove (0, getNumCharacters(), true);
  36100. insert (newContent, 0, true);
  36101. }
  36102. bool CodeDocument::loadFromStream (InputStream& stream)
  36103. {
  36104. replaceAllContent (stream.readEntireStreamAsString());
  36105. setSavePoint();
  36106. clearUndoHistory();
  36107. return true;
  36108. }
  36109. bool CodeDocument::writeToStream (OutputStream& stream)
  36110. {
  36111. for (int i = 0; i < lines.size(); ++i)
  36112. {
  36113. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36114. const char* utf8 = temp.toUTF8();
  36115. if (! stream.write (utf8, (int) strlen (utf8)))
  36116. return false;
  36117. }
  36118. return true;
  36119. }
  36120. void CodeDocument::setNewLineCharacters (const String& newLineChars_) throw()
  36121. {
  36122. jassert (newLineChars_ == "\r\n" || newLineChars_ == "\n" || newLineChars_ == "\r");
  36123. newLineChars = newLineChars_;
  36124. }
  36125. void CodeDocument::newTransaction()
  36126. {
  36127. undoManager.beginNewTransaction (String::empty);
  36128. }
  36129. void CodeDocument::undo()
  36130. {
  36131. newTransaction();
  36132. undoManager.undo();
  36133. }
  36134. void CodeDocument::redo()
  36135. {
  36136. undoManager.redo();
  36137. }
  36138. void CodeDocument::clearUndoHistory()
  36139. {
  36140. undoManager.clearUndoHistory();
  36141. }
  36142. void CodeDocument::setSavePoint() throw()
  36143. {
  36144. indexOfSavedState = currentActionIndex;
  36145. }
  36146. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36147. {
  36148. return currentActionIndex != indexOfSavedState;
  36149. }
  36150. namespace CodeDocumentHelpers
  36151. {
  36152. int getCharacterType (const juce_wchar character) throw()
  36153. {
  36154. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36155. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36156. }
  36157. }
  36158. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36159. {
  36160. Position p (position);
  36161. const int maxDistance = 256;
  36162. int i = 0;
  36163. while (i < maxDistance
  36164. && CharacterFunctions::isWhitespace (p.getCharacter())
  36165. && (i == 0 || (p.getCharacter() != '\n'
  36166. && p.getCharacter() != '\r')))
  36167. {
  36168. ++i;
  36169. p.moveBy (1);
  36170. }
  36171. if (i == 0)
  36172. {
  36173. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36174. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36175. {
  36176. ++i;
  36177. p.moveBy (1);
  36178. }
  36179. while (i < maxDistance
  36180. && CharacterFunctions::isWhitespace (p.getCharacter())
  36181. && (i == 0 || (p.getCharacter() != '\n'
  36182. && p.getCharacter() != '\r')))
  36183. {
  36184. ++i;
  36185. p.moveBy (1);
  36186. }
  36187. }
  36188. return p;
  36189. }
  36190. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36191. {
  36192. Position p (position);
  36193. const int maxDistance = 256;
  36194. int i = 0;
  36195. bool stoppedAtLineStart = false;
  36196. while (i < maxDistance)
  36197. {
  36198. const juce_wchar c = p.movedBy (-1).getCharacter();
  36199. if (c == '\r' || c == '\n')
  36200. {
  36201. stoppedAtLineStart = true;
  36202. if (i > 0)
  36203. break;
  36204. }
  36205. if (! CharacterFunctions::isWhitespace (c))
  36206. break;
  36207. p.moveBy (-1);
  36208. ++i;
  36209. }
  36210. if (i < maxDistance && ! stoppedAtLineStart)
  36211. {
  36212. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36213. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36214. {
  36215. p.moveBy (-1);
  36216. ++i;
  36217. }
  36218. }
  36219. return p;
  36220. }
  36221. void CodeDocument::checkLastLineStatus()
  36222. {
  36223. while (lines.size() > 0
  36224. && lines.getLast()->lineLength == 0
  36225. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36226. {
  36227. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36228. lines.removeLast();
  36229. }
  36230. const CodeDocumentLine* const lastLine = lines.getLast();
  36231. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36232. {
  36233. // check that there's an empty line at the end if the preceding one ends in a newline..
  36234. lines.add (new CodeDocumentLine (String::empty.getCharPointer(), 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36235. }
  36236. }
  36237. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36238. {
  36239. listeners.add (listener);
  36240. }
  36241. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36242. {
  36243. listeners.remove (listener);
  36244. }
  36245. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36246. {
  36247. Position startPos (this, startLine, 0);
  36248. Position endPos (this, endLine, 0);
  36249. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36250. }
  36251. class CodeDocumentInsertAction : public UndoableAction
  36252. {
  36253. public:
  36254. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36255. : owner (owner_),
  36256. text (text_),
  36257. insertPos (insertPos_)
  36258. {
  36259. }
  36260. bool perform()
  36261. {
  36262. owner.currentActionIndex++;
  36263. owner.insert (text, insertPos, false);
  36264. return true;
  36265. }
  36266. bool undo()
  36267. {
  36268. owner.currentActionIndex--;
  36269. owner.remove (insertPos, insertPos + text.length(), false);
  36270. return true;
  36271. }
  36272. int getSizeInUnits() { return text.length() + 32; }
  36273. private:
  36274. CodeDocument& owner;
  36275. const String text;
  36276. int insertPos;
  36277. JUCE_DECLARE_NON_COPYABLE (CodeDocumentInsertAction);
  36278. };
  36279. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36280. {
  36281. if (text.isEmpty())
  36282. return;
  36283. if (undoable)
  36284. {
  36285. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36286. }
  36287. else
  36288. {
  36289. Position pos (this, insertPos);
  36290. const int firstAffectedLine = pos.getLineNumber();
  36291. int lastAffectedLine = firstAffectedLine + 1;
  36292. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36293. String textInsideOriginalLine (text);
  36294. if (firstLine != 0)
  36295. {
  36296. const int index = pos.getIndexInLine();
  36297. textInsideOriginalLine = firstLine->line.substring (0, index)
  36298. + textInsideOriginalLine
  36299. + firstLine->line.substring (index);
  36300. }
  36301. maximumLineLength = -1;
  36302. Array <CodeDocumentLine*> newLines;
  36303. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36304. jassert (newLines.size() > 0);
  36305. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36306. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36307. lines.set (firstAffectedLine, newFirstLine);
  36308. if (newLines.size() > 1)
  36309. {
  36310. for (int i = 1; i < newLines.size(); ++i)
  36311. {
  36312. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36313. lines.insert (firstAffectedLine + i, l);
  36314. }
  36315. lastAffectedLine = lines.size();
  36316. }
  36317. int i, lineStart = newFirstLine->lineStartInFile;
  36318. for (i = firstAffectedLine; i < lines.size(); ++i)
  36319. {
  36320. CodeDocumentLine* const l = lines.getUnchecked (i);
  36321. l->lineStartInFile = lineStart;
  36322. lineStart += l->lineLength;
  36323. }
  36324. checkLastLineStatus();
  36325. const int newTextLength = text.length();
  36326. for (i = 0; i < positionsToMaintain.size(); ++i)
  36327. {
  36328. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36329. if (p->getPosition() >= insertPos)
  36330. p->setPosition (p->getPosition() + newTextLength);
  36331. }
  36332. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36333. }
  36334. }
  36335. class CodeDocumentDeleteAction : public UndoableAction
  36336. {
  36337. public:
  36338. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36339. : owner (owner_),
  36340. startPos (startPos_),
  36341. endPos (endPos_)
  36342. {
  36343. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36344. CodeDocument::Position (&owner, endPos));
  36345. }
  36346. bool perform()
  36347. {
  36348. owner.currentActionIndex++;
  36349. owner.remove (startPos, endPos, false);
  36350. return true;
  36351. }
  36352. bool undo()
  36353. {
  36354. owner.currentActionIndex--;
  36355. owner.insert (removedText, startPos, false);
  36356. return true;
  36357. }
  36358. int getSizeInUnits() { return removedText.length() + 32; }
  36359. private:
  36360. CodeDocument& owner;
  36361. int startPos, endPos;
  36362. String removedText;
  36363. JUCE_DECLARE_NON_COPYABLE (CodeDocumentDeleteAction);
  36364. };
  36365. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36366. {
  36367. if (endPos <= startPos)
  36368. return;
  36369. if (undoable)
  36370. {
  36371. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36372. }
  36373. else
  36374. {
  36375. Position startPosition (this, startPos);
  36376. Position endPosition (this, endPos);
  36377. maximumLineLength = -1;
  36378. const int firstAffectedLine = startPosition.getLineNumber();
  36379. const int endLine = endPosition.getLineNumber();
  36380. int lastAffectedLine = firstAffectedLine + 1;
  36381. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36382. if (firstAffectedLine == endLine)
  36383. {
  36384. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36385. + firstLine->line.substring (endPosition.getIndexInLine());
  36386. firstLine->updateLength();
  36387. }
  36388. else
  36389. {
  36390. lastAffectedLine = lines.size();
  36391. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36392. jassert (lastLine != 0);
  36393. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36394. + lastLine->line.substring (endPosition.getIndexInLine());
  36395. firstLine->updateLength();
  36396. int numLinesToRemove = endLine - firstAffectedLine;
  36397. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36398. }
  36399. int i;
  36400. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36401. {
  36402. CodeDocumentLine* const l = lines.getUnchecked (i);
  36403. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36404. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36405. }
  36406. checkLastLineStatus();
  36407. const int totalChars = getNumCharacters();
  36408. for (i = 0; i < positionsToMaintain.size(); ++i)
  36409. {
  36410. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36411. if (p->getPosition() > startPosition.getPosition())
  36412. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36413. if (p->getPosition() > totalChars)
  36414. p->setPosition (totalChars);
  36415. }
  36416. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36417. }
  36418. }
  36419. END_JUCE_NAMESPACE
  36420. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36421. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36422. BEGIN_JUCE_NAMESPACE
  36423. class CodeEditorComponent::CaretComponent : public Component,
  36424. public Timer
  36425. {
  36426. public:
  36427. CaretComponent (CodeEditorComponent& owner_)
  36428. : owner (owner_)
  36429. {
  36430. setAlwaysOnTop (true);
  36431. setInterceptsMouseClicks (false, false);
  36432. }
  36433. void paint (Graphics& g)
  36434. {
  36435. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36436. }
  36437. void timerCallback()
  36438. {
  36439. setVisible (shouldBeShown() && ! isVisible());
  36440. }
  36441. void updatePosition()
  36442. {
  36443. startTimer (400);
  36444. setVisible (shouldBeShown());
  36445. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36446. }
  36447. private:
  36448. CodeEditorComponent& owner;
  36449. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36450. JUCE_DECLARE_NON_COPYABLE (CaretComponent);
  36451. };
  36452. class CodeEditorComponent::CodeEditorLine
  36453. {
  36454. public:
  36455. CodeEditorLine() throw()
  36456. : highlightColumnStart (0), highlightColumnEnd (0)
  36457. {
  36458. }
  36459. bool update (CodeDocument& document, int lineNum,
  36460. CodeDocument::Iterator& source,
  36461. CodeTokeniser* analyser, const int spacesPerTab,
  36462. const CodeDocument::Position& selectionStart,
  36463. const CodeDocument::Position& selectionEnd)
  36464. {
  36465. Array <SyntaxToken> newTokens;
  36466. newTokens.ensureStorageAllocated (8);
  36467. if (analyser == 0)
  36468. {
  36469. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36470. }
  36471. else if (lineNum < document.getNumLines())
  36472. {
  36473. const CodeDocument::Position pos (&document, lineNum, 0);
  36474. createTokens (pos.getPosition(), pos.getLineText(),
  36475. source, analyser, newTokens);
  36476. }
  36477. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36478. int newHighlightStart = 0;
  36479. int newHighlightEnd = 0;
  36480. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36481. {
  36482. const String line (document.getLine (lineNum));
  36483. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36484. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36485. line, spacesPerTab);
  36486. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36487. line, spacesPerTab);
  36488. }
  36489. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36490. {
  36491. highlightColumnStart = newHighlightStart;
  36492. highlightColumnEnd = newHighlightEnd;
  36493. }
  36494. else
  36495. {
  36496. if (tokens.size() == newTokens.size())
  36497. {
  36498. bool allTheSame = true;
  36499. for (int i = newTokens.size(); --i >= 0;)
  36500. {
  36501. if (tokens.getReference(i) != newTokens.getReference(i))
  36502. {
  36503. allTheSame = false;
  36504. break;
  36505. }
  36506. }
  36507. if (allTheSame)
  36508. return false;
  36509. }
  36510. }
  36511. tokens.swapWithArray (newTokens);
  36512. return true;
  36513. }
  36514. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36515. float x, const int y, const int baselineOffset, const int lineHeight,
  36516. const Colour& highlightColour) const
  36517. {
  36518. if (highlightColumnStart < highlightColumnEnd)
  36519. {
  36520. g.setColour (highlightColour);
  36521. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36522. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36523. }
  36524. int lastType = std::numeric_limits<int>::min();
  36525. for (int i = 0; i < tokens.size(); ++i)
  36526. {
  36527. SyntaxToken& token = tokens.getReference(i);
  36528. if (lastType != token.tokenType)
  36529. {
  36530. lastType = token.tokenType;
  36531. g.setColour (owner.getColourForTokenType (lastType));
  36532. }
  36533. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36534. if (i < tokens.size() - 1)
  36535. {
  36536. if (token.width < 0)
  36537. token.width = font.getStringWidthFloat (token.text);
  36538. x += token.width;
  36539. }
  36540. }
  36541. }
  36542. private:
  36543. struct SyntaxToken
  36544. {
  36545. SyntaxToken (const String& text_, const int type) throw()
  36546. : text (text_), tokenType (type), width (-1.0f)
  36547. {
  36548. }
  36549. bool operator!= (const SyntaxToken& other) const throw()
  36550. {
  36551. return text != other.text || tokenType != other.tokenType;
  36552. }
  36553. String text;
  36554. int tokenType;
  36555. float width;
  36556. };
  36557. Array <SyntaxToken> tokens;
  36558. int highlightColumnStart, highlightColumnEnd;
  36559. static void createTokens (int startPosition, const String& lineText,
  36560. CodeDocument::Iterator& source,
  36561. CodeTokeniser* analyser,
  36562. Array <SyntaxToken>& newTokens)
  36563. {
  36564. CodeDocument::Iterator lastIterator (source);
  36565. const int lineLength = lineText.length();
  36566. for (;;)
  36567. {
  36568. int tokenType = analyser->readNextToken (source);
  36569. int tokenStart = lastIterator.getPosition();
  36570. int tokenEnd = source.getPosition();
  36571. if (tokenEnd <= tokenStart)
  36572. break;
  36573. tokenEnd -= startPosition;
  36574. if (tokenEnd > 0)
  36575. {
  36576. tokenStart -= startPosition;
  36577. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36578. tokenType));
  36579. if (tokenEnd >= lineLength)
  36580. break;
  36581. }
  36582. lastIterator = source;
  36583. }
  36584. source = lastIterator;
  36585. }
  36586. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36587. {
  36588. int x = 0;
  36589. for (int i = 0; i < tokens.size(); ++i)
  36590. {
  36591. SyntaxToken& t = tokens.getReference(i);
  36592. for (;;)
  36593. {
  36594. int tabPos = t.text.indexOfChar ('\t');
  36595. if (tabPos < 0)
  36596. break;
  36597. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36598. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36599. }
  36600. x += t.text.length();
  36601. }
  36602. }
  36603. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36604. {
  36605. jassert (index <= line.length());
  36606. int col = 0;
  36607. for (int i = 0; i < index; ++i)
  36608. {
  36609. if (line[i] != '\t')
  36610. ++col;
  36611. else
  36612. col += spacesPerTab - (col % spacesPerTab);
  36613. }
  36614. return col;
  36615. }
  36616. };
  36617. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36618. CodeTokeniser* const codeTokeniser_)
  36619. : document (document_),
  36620. firstLineOnScreen (0),
  36621. gutter (5),
  36622. spacesPerTab (4),
  36623. lineHeight (0),
  36624. linesOnScreen (0),
  36625. columnsOnScreen (0),
  36626. scrollbarThickness (16),
  36627. columnToTryToMaintain (-1),
  36628. useSpacesForTabs (false),
  36629. xOffset (0),
  36630. verticalScrollBar (true),
  36631. horizontalScrollBar (false),
  36632. codeTokeniser (codeTokeniser_)
  36633. {
  36634. caretPos = CodeDocument::Position (&document_, 0, 0);
  36635. caretPos.setPositionMaintained (true);
  36636. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36637. selectionStart.setPositionMaintained (true);
  36638. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36639. selectionEnd.setPositionMaintained (true);
  36640. setOpaque (true);
  36641. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36642. setWantsKeyboardFocus (true);
  36643. addAndMakeVisible (&verticalScrollBar);
  36644. verticalScrollBar.setSingleStepSize (1.0);
  36645. addAndMakeVisible (&horizontalScrollBar);
  36646. horizontalScrollBar.setSingleStepSize (1.0);
  36647. addAndMakeVisible (caret = new CaretComponent (*this));
  36648. Font f (12.0f);
  36649. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36650. setFont (f);
  36651. resetToDefaultColours();
  36652. verticalScrollBar.addListener (this);
  36653. horizontalScrollBar.addListener (this);
  36654. document.addListener (this);
  36655. }
  36656. CodeEditorComponent::~CodeEditorComponent()
  36657. {
  36658. document.removeListener (this);
  36659. }
  36660. void CodeEditorComponent::loadContent (const String& newContent)
  36661. {
  36662. clearCachedIterators (0);
  36663. document.replaceAllContent (newContent);
  36664. document.clearUndoHistory();
  36665. document.setSavePoint();
  36666. caretPos.setPosition (0);
  36667. selectionStart.setPosition (0);
  36668. selectionEnd.setPosition (0);
  36669. scrollToLine (0);
  36670. }
  36671. bool CodeEditorComponent::isTextInputActive() const
  36672. {
  36673. return true;
  36674. }
  36675. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36676. const CodeDocument::Position& affectedTextEnd)
  36677. {
  36678. clearCachedIterators (affectedTextStart.getLineNumber());
  36679. triggerAsyncUpdate();
  36680. caret->updatePosition();
  36681. columnToTryToMaintain = -1;
  36682. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36683. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36684. deselectAll();
  36685. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36686. || caretPos.getPosition() < affectedTextStart.getPosition())
  36687. moveCaretTo (affectedTextStart, false);
  36688. updateScrollBars();
  36689. }
  36690. void CodeEditorComponent::resized()
  36691. {
  36692. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36693. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36694. lines.clear();
  36695. rebuildLineTokens();
  36696. caret->updatePosition();
  36697. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  36698. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  36699. updateScrollBars();
  36700. }
  36701. void CodeEditorComponent::paint (Graphics& g)
  36702. {
  36703. handleUpdateNowIfNeeded();
  36704. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  36705. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  36706. g.setFont (font);
  36707. const int baselineOffset = (int) font.getAscent();
  36708. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  36709. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  36710. const Rectangle<int> clip (g.getClipBounds());
  36711. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  36712. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  36713. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  36714. {
  36715. lines.getUnchecked(j)->draw (*this, g, font,
  36716. (float) (gutter - xOffset * charWidth),
  36717. lineHeight * j, baselineOffset, lineHeight,
  36718. highlightColour);
  36719. }
  36720. }
  36721. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  36722. {
  36723. if (scrollbarThickness != thickness)
  36724. {
  36725. scrollbarThickness = thickness;
  36726. resized();
  36727. }
  36728. }
  36729. void CodeEditorComponent::handleAsyncUpdate()
  36730. {
  36731. rebuildLineTokens();
  36732. }
  36733. void CodeEditorComponent::rebuildLineTokens()
  36734. {
  36735. cancelPendingUpdate();
  36736. const int numNeeded = linesOnScreen + 1;
  36737. int minLineToRepaint = numNeeded;
  36738. int maxLineToRepaint = 0;
  36739. if (numNeeded != lines.size())
  36740. {
  36741. lines.clear();
  36742. for (int i = numNeeded; --i >= 0;)
  36743. lines.add (new CodeEditorLine());
  36744. minLineToRepaint = 0;
  36745. maxLineToRepaint = numNeeded;
  36746. }
  36747. jassert (numNeeded == lines.size());
  36748. CodeDocument::Iterator source (&document);
  36749. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  36750. for (int i = 0; i < numNeeded; ++i)
  36751. {
  36752. CodeEditorLine* const line = lines.getUnchecked(i);
  36753. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  36754. selectionStart, selectionEnd))
  36755. {
  36756. minLineToRepaint = jmin (minLineToRepaint, i);
  36757. maxLineToRepaint = jmax (maxLineToRepaint, i);
  36758. }
  36759. }
  36760. if (minLineToRepaint <= maxLineToRepaint)
  36761. {
  36762. repaint (gutter, lineHeight * minLineToRepaint - 1,
  36763. verticalScrollBar.getX() - gutter,
  36764. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  36765. }
  36766. }
  36767. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  36768. {
  36769. caretPos = newPos;
  36770. columnToTryToMaintain = -1;
  36771. if (highlighting)
  36772. {
  36773. if (dragType == notDragging)
  36774. {
  36775. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  36776. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  36777. dragType = draggingSelectionStart;
  36778. else
  36779. dragType = draggingSelectionEnd;
  36780. }
  36781. if (dragType == draggingSelectionStart)
  36782. {
  36783. selectionStart = caretPos;
  36784. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36785. {
  36786. const CodeDocument::Position temp (selectionStart);
  36787. selectionStart = selectionEnd;
  36788. selectionEnd = temp;
  36789. dragType = draggingSelectionEnd;
  36790. }
  36791. }
  36792. else
  36793. {
  36794. selectionEnd = caretPos;
  36795. if (selectionEnd.getPosition() < selectionStart.getPosition())
  36796. {
  36797. const CodeDocument::Position temp (selectionStart);
  36798. selectionStart = selectionEnd;
  36799. selectionEnd = temp;
  36800. dragType = draggingSelectionStart;
  36801. }
  36802. }
  36803. triggerAsyncUpdate();
  36804. }
  36805. else
  36806. {
  36807. deselectAll();
  36808. }
  36809. caret->updatePosition();
  36810. scrollToKeepCaretOnScreen();
  36811. updateScrollBars();
  36812. }
  36813. void CodeEditorComponent::deselectAll()
  36814. {
  36815. if (selectionStart != selectionEnd)
  36816. triggerAsyncUpdate();
  36817. selectionStart = caretPos;
  36818. selectionEnd = caretPos;
  36819. }
  36820. void CodeEditorComponent::updateScrollBars()
  36821. {
  36822. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  36823. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  36824. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  36825. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  36826. }
  36827. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  36828. {
  36829. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  36830. newFirstLineOnScreen);
  36831. if (newFirstLineOnScreen != firstLineOnScreen)
  36832. {
  36833. firstLineOnScreen = newFirstLineOnScreen;
  36834. caret->updatePosition();
  36835. updateCachedIterators (firstLineOnScreen);
  36836. triggerAsyncUpdate();
  36837. }
  36838. }
  36839. void CodeEditorComponent::scrollToColumnInternal (double column)
  36840. {
  36841. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  36842. if (xOffset != newOffset)
  36843. {
  36844. xOffset = newOffset;
  36845. caret->updatePosition();
  36846. repaint();
  36847. }
  36848. }
  36849. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  36850. {
  36851. scrollToLineInternal (newFirstLineOnScreen);
  36852. updateScrollBars();
  36853. }
  36854. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  36855. {
  36856. scrollToColumnInternal (newFirstColumnOnScreen);
  36857. updateScrollBars();
  36858. }
  36859. void CodeEditorComponent::scrollBy (int deltaLines)
  36860. {
  36861. scrollToLine (firstLineOnScreen + deltaLines);
  36862. }
  36863. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  36864. {
  36865. if (caretPos.getLineNumber() < firstLineOnScreen)
  36866. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  36867. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  36868. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  36869. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36870. if (column >= xOffset + columnsOnScreen - 1)
  36871. scrollToColumn (column + 1 - columnsOnScreen);
  36872. else if (column < xOffset)
  36873. scrollToColumn (column);
  36874. }
  36875. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  36876. {
  36877. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  36878. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  36879. roundToInt (charWidth),
  36880. lineHeight);
  36881. }
  36882. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  36883. {
  36884. const int line = y / lineHeight + firstLineOnScreen;
  36885. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  36886. const int index = columnToIndex (line, column);
  36887. return CodeDocument::Position (&document, line, index);
  36888. }
  36889. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  36890. {
  36891. document.deleteSection (selectionStart, selectionEnd);
  36892. if (newText.isNotEmpty())
  36893. document.insertText (caretPos, newText);
  36894. scrollToKeepCaretOnScreen();
  36895. }
  36896. void CodeEditorComponent::insertTabAtCaret()
  36897. {
  36898. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  36899. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  36900. {
  36901. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  36902. }
  36903. if (useSpacesForTabs)
  36904. {
  36905. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  36906. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  36907. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  36908. }
  36909. else
  36910. {
  36911. insertTextAtCaret ("\t");
  36912. }
  36913. }
  36914. void CodeEditorComponent::cut()
  36915. {
  36916. insertTextAtCaret (String::empty);
  36917. }
  36918. void CodeEditorComponent::copy()
  36919. {
  36920. newTransaction();
  36921. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  36922. if (selection.isNotEmpty())
  36923. SystemClipboard::copyTextToClipboard (selection);
  36924. }
  36925. void CodeEditorComponent::copyThenCut()
  36926. {
  36927. copy();
  36928. cut();
  36929. newTransaction();
  36930. }
  36931. void CodeEditorComponent::paste()
  36932. {
  36933. newTransaction();
  36934. const String clip (SystemClipboard::getTextFromClipboard());
  36935. if (clip.isNotEmpty())
  36936. insertTextAtCaret (clip);
  36937. newTransaction();
  36938. }
  36939. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  36940. {
  36941. newTransaction();
  36942. if (moveInWholeWordSteps)
  36943. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  36944. else
  36945. moveCaretTo (caretPos.movedBy (-1), selecting);
  36946. }
  36947. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  36948. {
  36949. newTransaction();
  36950. if (moveInWholeWordSteps)
  36951. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  36952. else
  36953. moveCaretTo (caretPos.movedBy (1), selecting);
  36954. }
  36955. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  36956. {
  36957. CodeDocument::Position pos (caretPos);
  36958. const int newLineNum = pos.getLineNumber() + delta;
  36959. if (columnToTryToMaintain < 0)
  36960. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  36961. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  36962. const int colToMaintain = columnToTryToMaintain;
  36963. moveCaretTo (pos, selecting);
  36964. columnToTryToMaintain = colToMaintain;
  36965. }
  36966. void CodeEditorComponent::cursorDown (const bool selecting)
  36967. {
  36968. newTransaction();
  36969. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  36970. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  36971. else
  36972. moveLineDelta (1, selecting);
  36973. }
  36974. void CodeEditorComponent::cursorUp (const bool selecting)
  36975. {
  36976. newTransaction();
  36977. if (caretPos.getLineNumber() == 0)
  36978. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  36979. else
  36980. moveLineDelta (-1, selecting);
  36981. }
  36982. void CodeEditorComponent::pageDown (const bool selecting)
  36983. {
  36984. newTransaction();
  36985. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  36986. moveLineDelta (linesOnScreen, selecting);
  36987. }
  36988. void CodeEditorComponent::pageUp (const bool selecting)
  36989. {
  36990. newTransaction();
  36991. scrollBy (-linesOnScreen);
  36992. moveLineDelta (-linesOnScreen, selecting);
  36993. }
  36994. void CodeEditorComponent::scrollUp()
  36995. {
  36996. newTransaction();
  36997. scrollBy (1);
  36998. if (caretPos.getLineNumber() < firstLineOnScreen)
  36999. moveLineDelta (1, false);
  37000. }
  37001. void CodeEditorComponent::scrollDown()
  37002. {
  37003. newTransaction();
  37004. scrollBy (-1);
  37005. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37006. moveLineDelta (-1, false);
  37007. }
  37008. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37009. {
  37010. newTransaction();
  37011. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37012. }
  37013. namespace CodeEditorHelpers
  37014. {
  37015. int findFirstNonWhitespaceChar (const String& line) throw()
  37016. {
  37017. const int len = line.length();
  37018. for (int i = 0; i < len; ++i)
  37019. if (! CharacterFunctions::isWhitespace (line [i]))
  37020. return i;
  37021. return 0;
  37022. }
  37023. }
  37024. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37025. {
  37026. newTransaction();
  37027. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37028. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37029. index = 0;
  37030. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37031. }
  37032. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37033. {
  37034. newTransaction();
  37035. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37036. }
  37037. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37038. {
  37039. newTransaction();
  37040. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37041. }
  37042. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37043. {
  37044. if (moveInWholeWordSteps)
  37045. {
  37046. cut(); // in case something is already highlighted
  37047. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37048. }
  37049. else
  37050. {
  37051. if (selectionStart == selectionEnd)
  37052. selectionStart.moveBy (-1);
  37053. }
  37054. cut();
  37055. }
  37056. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37057. {
  37058. if (moveInWholeWordSteps)
  37059. {
  37060. cut(); // in case something is already highlighted
  37061. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37062. }
  37063. else
  37064. {
  37065. if (selectionStart == selectionEnd)
  37066. selectionEnd.moveBy (1);
  37067. else
  37068. newTransaction();
  37069. }
  37070. cut();
  37071. }
  37072. void CodeEditorComponent::selectAll()
  37073. {
  37074. newTransaction();
  37075. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37076. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37077. }
  37078. void CodeEditorComponent::undo()
  37079. {
  37080. document.undo();
  37081. scrollToKeepCaretOnScreen();
  37082. }
  37083. void CodeEditorComponent::redo()
  37084. {
  37085. document.redo();
  37086. scrollToKeepCaretOnScreen();
  37087. }
  37088. void CodeEditorComponent::newTransaction()
  37089. {
  37090. document.newTransaction();
  37091. startTimer (600);
  37092. }
  37093. void CodeEditorComponent::timerCallback()
  37094. {
  37095. newTransaction();
  37096. }
  37097. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37098. {
  37099. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37100. }
  37101. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37102. {
  37103. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37104. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37105. }
  37106. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37107. {
  37108. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37109. CodeDocument::Position (&document, range.getEnd()));
  37110. }
  37111. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37112. {
  37113. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37114. const bool shiftDown = key.getModifiers().isShiftDown();
  37115. if (key.isKeyCode (KeyPress::leftKey))
  37116. {
  37117. cursorLeft (moveInWholeWordSteps, shiftDown);
  37118. }
  37119. else if (key.isKeyCode (KeyPress::rightKey))
  37120. {
  37121. cursorRight (moveInWholeWordSteps, shiftDown);
  37122. }
  37123. else if (key.isKeyCode (KeyPress::upKey))
  37124. {
  37125. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37126. scrollDown();
  37127. #if JUCE_MAC
  37128. else if (key.getModifiers().isCommandDown())
  37129. goToStartOfDocument (shiftDown);
  37130. #endif
  37131. else
  37132. cursorUp (shiftDown);
  37133. }
  37134. else if (key.isKeyCode (KeyPress::downKey))
  37135. {
  37136. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37137. scrollUp();
  37138. #if JUCE_MAC
  37139. else if (key.getModifiers().isCommandDown())
  37140. goToEndOfDocument (shiftDown);
  37141. #endif
  37142. else
  37143. cursorDown (shiftDown);
  37144. }
  37145. else if (key.isKeyCode (KeyPress::pageDownKey))
  37146. {
  37147. pageDown (shiftDown);
  37148. }
  37149. else if (key.isKeyCode (KeyPress::pageUpKey))
  37150. {
  37151. pageUp (shiftDown);
  37152. }
  37153. else if (key.isKeyCode (KeyPress::homeKey))
  37154. {
  37155. if (moveInWholeWordSteps)
  37156. goToStartOfDocument (shiftDown);
  37157. else
  37158. goToStartOfLine (shiftDown);
  37159. }
  37160. else if (key.isKeyCode (KeyPress::endKey))
  37161. {
  37162. if (moveInWholeWordSteps)
  37163. goToEndOfDocument (shiftDown);
  37164. else
  37165. goToEndOfLine (shiftDown);
  37166. }
  37167. else if (key.isKeyCode (KeyPress::backspaceKey))
  37168. {
  37169. backspace (moveInWholeWordSteps);
  37170. }
  37171. else if (key.isKeyCode (KeyPress::deleteKey))
  37172. {
  37173. deleteForward (moveInWholeWordSteps);
  37174. }
  37175. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37176. {
  37177. copy();
  37178. }
  37179. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37180. {
  37181. copyThenCut();
  37182. }
  37183. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37184. {
  37185. paste();
  37186. }
  37187. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37188. {
  37189. undo();
  37190. }
  37191. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37192. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37193. {
  37194. redo();
  37195. }
  37196. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37197. {
  37198. selectAll();
  37199. }
  37200. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37201. {
  37202. insertTabAtCaret();
  37203. }
  37204. else if (key == KeyPress::returnKey)
  37205. {
  37206. newTransaction();
  37207. insertTextAtCaret (document.getNewLineCharacters());
  37208. }
  37209. else if (key.isKeyCode (KeyPress::escapeKey))
  37210. {
  37211. newTransaction();
  37212. }
  37213. else if (key.getTextCharacter() >= ' ')
  37214. {
  37215. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37216. }
  37217. else
  37218. {
  37219. return false;
  37220. }
  37221. return true;
  37222. }
  37223. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37224. {
  37225. newTransaction();
  37226. dragType = notDragging;
  37227. if (! e.mods.isPopupMenu())
  37228. {
  37229. beginDragAutoRepeat (100);
  37230. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37231. }
  37232. else
  37233. {
  37234. /*PopupMenu m;
  37235. addPopupMenuItems (m, &e);
  37236. const int result = m.show();
  37237. if (result != 0)
  37238. performPopupMenuAction (result);
  37239. */
  37240. }
  37241. }
  37242. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37243. {
  37244. if (! e.mods.isPopupMenu())
  37245. moveCaretTo (getPositionAt (e.x, e.y), true);
  37246. }
  37247. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37248. {
  37249. newTransaction();
  37250. beginDragAutoRepeat (0);
  37251. dragType = notDragging;
  37252. }
  37253. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37254. {
  37255. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37256. CodeDocument::Position tokenEnd (tokenStart);
  37257. if (e.getNumberOfClicks() > 2)
  37258. {
  37259. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37260. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37261. }
  37262. else
  37263. {
  37264. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37265. tokenEnd.moveBy (1);
  37266. tokenStart = tokenEnd;
  37267. while (tokenStart.getIndexInLine() > 0
  37268. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37269. tokenStart.moveBy (-1);
  37270. }
  37271. moveCaretTo (tokenEnd, false);
  37272. moveCaretTo (tokenStart, true);
  37273. }
  37274. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37275. {
  37276. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37277. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37278. {
  37279. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37280. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37281. }
  37282. else
  37283. {
  37284. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37285. }
  37286. }
  37287. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37288. {
  37289. if (scrollBarThatHasMoved == &verticalScrollBar)
  37290. scrollToLineInternal ((int) newRangeStart);
  37291. else
  37292. scrollToColumnInternal (newRangeStart);
  37293. }
  37294. void CodeEditorComponent::focusGained (FocusChangeType)
  37295. {
  37296. caret->updatePosition();
  37297. }
  37298. void CodeEditorComponent::focusLost (FocusChangeType)
  37299. {
  37300. caret->updatePosition();
  37301. }
  37302. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37303. {
  37304. useSpacesForTabs = insertSpaces;
  37305. if (spacesPerTab != numSpaces)
  37306. {
  37307. spacesPerTab = numSpaces;
  37308. triggerAsyncUpdate();
  37309. }
  37310. }
  37311. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37312. {
  37313. const String line (document.getLine (lineNum));
  37314. jassert (index <= line.length());
  37315. int col = 0;
  37316. for (int i = 0; i < index; ++i)
  37317. {
  37318. if (line[i] != '\t')
  37319. ++col;
  37320. else
  37321. col += getTabSize() - (col % getTabSize());
  37322. }
  37323. return col;
  37324. }
  37325. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37326. {
  37327. const String line (document.getLine (lineNum));
  37328. const int lineLength = line.length();
  37329. int i, col = 0;
  37330. for (i = 0; i < lineLength; ++i)
  37331. {
  37332. if (line[i] != '\t')
  37333. ++col;
  37334. else
  37335. col += getTabSize() - (col % getTabSize());
  37336. if (col > column)
  37337. break;
  37338. }
  37339. return i;
  37340. }
  37341. void CodeEditorComponent::setFont (const Font& newFont)
  37342. {
  37343. font = newFont;
  37344. charWidth = font.getStringWidthFloat ("0");
  37345. lineHeight = roundToInt (font.getHeight());
  37346. resized();
  37347. }
  37348. void CodeEditorComponent::resetToDefaultColours()
  37349. {
  37350. coloursForTokenCategories.clear();
  37351. if (codeTokeniser != 0)
  37352. {
  37353. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37354. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37355. }
  37356. }
  37357. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37358. {
  37359. jassert (tokenType < 256);
  37360. while (coloursForTokenCategories.size() < tokenType)
  37361. coloursForTokenCategories.add (Colours::black);
  37362. coloursForTokenCategories.set (tokenType, colour);
  37363. repaint();
  37364. }
  37365. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37366. {
  37367. if (! isPositiveAndBelow (tokenType, coloursForTokenCategories.size()))
  37368. return findColour (CodeEditorComponent::defaultTextColourId);
  37369. return coloursForTokenCategories.getReference (tokenType);
  37370. }
  37371. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37372. {
  37373. int i;
  37374. for (i = cachedIterators.size(); --i >= 0;)
  37375. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37376. break;
  37377. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37378. }
  37379. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37380. {
  37381. const int maxNumCachedPositions = 5000;
  37382. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37383. if (cachedIterators.size() == 0)
  37384. cachedIterators.add (new CodeDocument::Iterator (&document));
  37385. if (codeTokeniser == 0)
  37386. return;
  37387. for (;;)
  37388. {
  37389. CodeDocument::Iterator* last = cachedIterators.getLast();
  37390. if (last->getLine() >= maxLineNum)
  37391. break;
  37392. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37393. cachedIterators.add (t);
  37394. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37395. for (;;)
  37396. {
  37397. codeTokeniser->readNextToken (*t);
  37398. if (t->getLine() >= targetLine)
  37399. break;
  37400. if (t->isEOF())
  37401. return;
  37402. }
  37403. }
  37404. }
  37405. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37406. {
  37407. if (codeTokeniser == 0)
  37408. return;
  37409. for (int i = cachedIterators.size(); --i >= 0;)
  37410. {
  37411. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37412. if (t->getPosition() <= position)
  37413. {
  37414. source = *t;
  37415. break;
  37416. }
  37417. }
  37418. while (source.getPosition() < position)
  37419. {
  37420. const CodeDocument::Iterator original (source);
  37421. codeTokeniser->readNextToken (source);
  37422. if (source.getPosition() > position || source.isEOF())
  37423. {
  37424. source = original;
  37425. break;
  37426. }
  37427. }
  37428. }
  37429. END_JUCE_NAMESPACE
  37430. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37431. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37432. BEGIN_JUCE_NAMESPACE
  37433. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37434. {
  37435. }
  37436. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37437. {
  37438. }
  37439. namespace CppTokeniser
  37440. {
  37441. bool isIdentifierStart (const juce_wchar c) throw()
  37442. {
  37443. return CharacterFunctions::isLetter (c)
  37444. || c == '_' || c == '@';
  37445. }
  37446. bool isIdentifierBody (const juce_wchar c) throw()
  37447. {
  37448. return CharacterFunctions::isLetterOrDigit (c)
  37449. || c == '_' || c == '@';
  37450. }
  37451. bool isReservedKeyword (String::CharPointerType token, const int tokenLength) throw()
  37452. {
  37453. static const char* const keywords2Char[] =
  37454. { "if", "do", "or", "id", 0 };
  37455. static const char* const keywords3Char[] =
  37456. { "for", "int", "new", "try", "xor", "and", "asm", "not", 0 };
  37457. static const char* const keywords4Char[] =
  37458. { "bool", "void", "this", "true", "long", "else", "char",
  37459. "enum", "case", "goto", "auto", 0 };
  37460. static const char* const keywords5Char[] =
  37461. { "while", "bitor", "break", "catch", "class", "compl", "const", "false",
  37462. "float", "short", "throw", "union", "using", "or_eq", 0 };
  37463. static const char* const keywords6Char[] =
  37464. { "return", "struct", "and_eq", "bitand", "delete", "double", "extern",
  37465. "friend", "inline", "not_eq", "public", "sizeof", "static", "signed",
  37466. "switch", "typeid", "wchar_t", "xor_eq", 0};
  37467. static const char* const keywordsOther[] =
  37468. { "const_cast", "continue", "default", "explicit", "mutable", "namespace",
  37469. "operator", "private", "protected", "register", "reinterpret_cast", "static_cast",
  37470. "template", "typedef", "typename", "unsigned", "virtual", "volatile",
  37471. "@implementation", "@interface", "@end", "@synthesize", "@dynamic", "@public",
  37472. "@private", "@property", "@protected", "@class", 0 };
  37473. const char* const* k;
  37474. switch (tokenLength)
  37475. {
  37476. case 2: k = keywords2Char; break;
  37477. case 3: k = keywords3Char; break;
  37478. case 4: k = keywords4Char; break;
  37479. case 5: k = keywords5Char; break;
  37480. case 6: k = keywords6Char; break;
  37481. default:
  37482. if (tokenLength < 2 || tokenLength > 16)
  37483. return false;
  37484. k = keywordsOther;
  37485. break;
  37486. }
  37487. int i = 0;
  37488. while (k[i] != 0)
  37489. {
  37490. if (token.compare (CharPointer_ASCII (k[i])) == 0)
  37491. return true;
  37492. ++i;
  37493. }
  37494. return false;
  37495. }
  37496. int parseIdentifier (CodeDocument::Iterator& source) throw()
  37497. {
  37498. int tokenLength = 0;
  37499. juce_wchar possibleIdentifier [19];
  37500. while (isIdentifierBody (source.peekNextChar()))
  37501. {
  37502. const juce_wchar c = source.nextChar();
  37503. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37504. possibleIdentifier [tokenLength] = c;
  37505. ++tokenLength;
  37506. }
  37507. if (tokenLength > 1 && tokenLength <= 16)
  37508. {
  37509. possibleIdentifier [tokenLength] = 0;
  37510. if (isReservedKeyword (CharPointer_UTF32 (possibleIdentifier), tokenLength))
  37511. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37512. }
  37513. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37514. }
  37515. bool skipNumberSuffix (CodeDocument::Iterator& source)
  37516. {
  37517. const juce_wchar c = source.peekNextChar();
  37518. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37519. source.skip();
  37520. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37521. return false;
  37522. return true;
  37523. }
  37524. bool isHexDigit (const juce_wchar c) throw()
  37525. {
  37526. return (c >= '0' && c <= '9')
  37527. || (c >= 'a' && c <= 'f')
  37528. || (c >= 'A' && c <= 'F');
  37529. }
  37530. bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37531. {
  37532. if (source.nextChar() != '0')
  37533. return false;
  37534. juce_wchar c = source.nextChar();
  37535. if (c != 'x' && c != 'X')
  37536. return false;
  37537. int numDigits = 0;
  37538. while (isHexDigit (source.peekNextChar()))
  37539. {
  37540. ++numDigits;
  37541. source.skip();
  37542. }
  37543. if (numDigits == 0)
  37544. return false;
  37545. return skipNumberSuffix (source);
  37546. }
  37547. bool isOctalDigit (const juce_wchar c) throw()
  37548. {
  37549. return c >= '0' && c <= '7';
  37550. }
  37551. bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37552. {
  37553. if (source.nextChar() != '0')
  37554. return false;
  37555. if (! isOctalDigit (source.nextChar()))
  37556. return false;
  37557. while (isOctalDigit (source.peekNextChar()))
  37558. source.skip();
  37559. return skipNumberSuffix (source);
  37560. }
  37561. bool isDecimalDigit (const juce_wchar c) throw()
  37562. {
  37563. return c >= '0' && c <= '9';
  37564. }
  37565. bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37566. {
  37567. int numChars = 0;
  37568. while (isDecimalDigit (source.peekNextChar()))
  37569. {
  37570. ++numChars;
  37571. source.skip();
  37572. }
  37573. if (numChars == 0)
  37574. return false;
  37575. return skipNumberSuffix (source);
  37576. }
  37577. bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37578. {
  37579. int numDigits = 0;
  37580. while (isDecimalDigit (source.peekNextChar()))
  37581. {
  37582. source.skip();
  37583. ++numDigits;
  37584. }
  37585. const bool hasPoint = (source.peekNextChar() == '.');
  37586. if (hasPoint)
  37587. {
  37588. source.skip();
  37589. while (isDecimalDigit (source.peekNextChar()))
  37590. {
  37591. source.skip();
  37592. ++numDigits;
  37593. }
  37594. }
  37595. if (numDigits == 0)
  37596. return false;
  37597. juce_wchar c = source.peekNextChar();
  37598. const bool hasExponent = (c == 'e' || c == 'E');
  37599. if (hasExponent)
  37600. {
  37601. source.skip();
  37602. c = source.peekNextChar();
  37603. if (c == '+' || c == '-')
  37604. source.skip();
  37605. int numExpDigits = 0;
  37606. while (isDecimalDigit (source.peekNextChar()))
  37607. {
  37608. source.skip();
  37609. ++numExpDigits;
  37610. }
  37611. if (numExpDigits == 0)
  37612. return false;
  37613. }
  37614. c = source.peekNextChar();
  37615. if (c == 'f' || c == 'F')
  37616. source.skip();
  37617. else if (! (hasExponent || hasPoint))
  37618. return false;
  37619. return true;
  37620. }
  37621. int parseNumber (CodeDocument::Iterator& source)
  37622. {
  37623. const CodeDocument::Iterator original (source);
  37624. if (parseFloatLiteral (source))
  37625. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37626. source = original;
  37627. if (parseHexLiteral (source))
  37628. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37629. source = original;
  37630. if (parseOctalLiteral (source))
  37631. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37632. source = original;
  37633. if (parseDecimalLiteral (source))
  37634. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37635. source = original;
  37636. source.skip();
  37637. return CPlusPlusCodeTokeniser::tokenType_error;
  37638. }
  37639. void skipQuotedString (CodeDocument::Iterator& source) throw()
  37640. {
  37641. const juce_wchar quote = source.nextChar();
  37642. for (;;)
  37643. {
  37644. const juce_wchar c = source.nextChar();
  37645. if (c == quote || c == 0)
  37646. break;
  37647. if (c == '\\')
  37648. source.skip();
  37649. }
  37650. }
  37651. void skipComment (CodeDocument::Iterator& source) throw()
  37652. {
  37653. bool lastWasStar = false;
  37654. for (;;)
  37655. {
  37656. const juce_wchar c = source.nextChar();
  37657. if (c == 0 || (c == '/' && lastWasStar))
  37658. break;
  37659. lastWasStar = (c == '*');
  37660. }
  37661. }
  37662. }
  37663. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37664. {
  37665. int result = tokenType_error;
  37666. source.skipWhitespace();
  37667. juce_wchar firstChar = source.peekNextChar();
  37668. switch (firstChar)
  37669. {
  37670. case 0:
  37671. source.skip();
  37672. break;
  37673. case '0':
  37674. case '1':
  37675. case '2':
  37676. case '3':
  37677. case '4':
  37678. case '5':
  37679. case '6':
  37680. case '7':
  37681. case '8':
  37682. case '9':
  37683. result = CppTokeniser::parseNumber (source);
  37684. break;
  37685. case '.':
  37686. result = CppTokeniser::parseNumber (source);
  37687. if (result == tokenType_error)
  37688. result = tokenType_punctuation;
  37689. break;
  37690. case ',':
  37691. case ';':
  37692. case ':':
  37693. source.skip();
  37694. result = tokenType_punctuation;
  37695. break;
  37696. case '(':
  37697. case ')':
  37698. case '{':
  37699. case '}':
  37700. case '[':
  37701. case ']':
  37702. source.skip();
  37703. result = tokenType_bracket;
  37704. break;
  37705. case '"':
  37706. case '\'':
  37707. CppTokeniser::skipQuotedString (source);
  37708. result = tokenType_stringLiteral;
  37709. break;
  37710. case '+':
  37711. result = tokenType_operator;
  37712. source.skip();
  37713. if (source.peekNextChar() == '+')
  37714. source.skip();
  37715. else if (source.peekNextChar() == '=')
  37716. source.skip();
  37717. break;
  37718. case '-':
  37719. source.skip();
  37720. result = CppTokeniser::parseNumber (source);
  37721. if (result == tokenType_error)
  37722. {
  37723. result = tokenType_operator;
  37724. if (source.peekNextChar() == '-')
  37725. source.skip();
  37726. else if (source.peekNextChar() == '=')
  37727. source.skip();
  37728. }
  37729. break;
  37730. case '*':
  37731. case '%':
  37732. case '=':
  37733. case '!':
  37734. result = tokenType_operator;
  37735. source.skip();
  37736. if (source.peekNextChar() == '=')
  37737. source.skip();
  37738. break;
  37739. case '/':
  37740. result = tokenType_operator;
  37741. source.skip();
  37742. if (source.peekNextChar() == '=')
  37743. {
  37744. source.skip();
  37745. }
  37746. else if (source.peekNextChar() == '/')
  37747. {
  37748. result = tokenType_comment;
  37749. source.skipToEndOfLine();
  37750. }
  37751. else if (source.peekNextChar() == '*')
  37752. {
  37753. source.skip();
  37754. result = tokenType_comment;
  37755. CppTokeniser::skipComment (source);
  37756. }
  37757. break;
  37758. case '?':
  37759. case '~':
  37760. source.skip();
  37761. result = tokenType_operator;
  37762. break;
  37763. case '<':
  37764. source.skip();
  37765. result = tokenType_operator;
  37766. if (source.peekNextChar() == '=')
  37767. {
  37768. source.skip();
  37769. }
  37770. else if (source.peekNextChar() == '<')
  37771. {
  37772. source.skip();
  37773. if (source.peekNextChar() == '=')
  37774. source.skip();
  37775. }
  37776. break;
  37777. case '>':
  37778. source.skip();
  37779. result = tokenType_operator;
  37780. if (source.peekNextChar() == '=')
  37781. {
  37782. source.skip();
  37783. }
  37784. else if (source.peekNextChar() == '<')
  37785. {
  37786. source.skip();
  37787. if (source.peekNextChar() == '=')
  37788. source.skip();
  37789. }
  37790. break;
  37791. case '|':
  37792. source.skip();
  37793. result = tokenType_operator;
  37794. if (source.peekNextChar() == '=')
  37795. {
  37796. source.skip();
  37797. }
  37798. else if (source.peekNextChar() == '|')
  37799. {
  37800. source.skip();
  37801. if (source.peekNextChar() == '=')
  37802. source.skip();
  37803. }
  37804. break;
  37805. case '&':
  37806. source.skip();
  37807. result = tokenType_operator;
  37808. if (source.peekNextChar() == '=')
  37809. {
  37810. source.skip();
  37811. }
  37812. else if (source.peekNextChar() == '&')
  37813. {
  37814. source.skip();
  37815. if (source.peekNextChar() == '=')
  37816. source.skip();
  37817. }
  37818. break;
  37819. case '^':
  37820. source.skip();
  37821. result = tokenType_operator;
  37822. if (source.peekNextChar() == '=')
  37823. {
  37824. source.skip();
  37825. }
  37826. else if (source.peekNextChar() == '^')
  37827. {
  37828. source.skip();
  37829. if (source.peekNextChar() == '=')
  37830. source.skip();
  37831. }
  37832. break;
  37833. case '#':
  37834. result = tokenType_preprocessor;
  37835. source.skipToEndOfLine();
  37836. break;
  37837. default:
  37838. if (CppTokeniser::isIdentifierStart (firstChar))
  37839. result = CppTokeniser::parseIdentifier (source);
  37840. else
  37841. source.skip();
  37842. break;
  37843. }
  37844. return result;
  37845. }
  37846. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  37847. {
  37848. const char* const types[] =
  37849. {
  37850. "Error",
  37851. "Comment",
  37852. "C++ keyword",
  37853. "Identifier",
  37854. "Integer literal",
  37855. "Float literal",
  37856. "String literal",
  37857. "Operator",
  37858. "Bracket",
  37859. "Punctuation",
  37860. "Preprocessor line",
  37861. 0
  37862. };
  37863. return StringArray (types);
  37864. }
  37865. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  37866. {
  37867. const uint32 colours[] =
  37868. {
  37869. 0xffcc0000, // error
  37870. 0xff00aa00, // comment
  37871. 0xff0000cc, // keyword
  37872. 0xff000000, // identifier
  37873. 0xff880000, // int literal
  37874. 0xff885500, // float literal
  37875. 0xff990099, // string literal
  37876. 0xff225500, // operator
  37877. 0xff000055, // bracket
  37878. 0xff004400, // punctuation
  37879. 0xff660000 // preprocessor
  37880. };
  37881. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  37882. return Colour (colours [tokenType]);
  37883. return Colours::black;
  37884. }
  37885. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  37886. {
  37887. return CppTokeniser::isReservedKeyword (token.getCharPointer(), token.length());
  37888. }
  37889. END_JUCE_NAMESPACE
  37890. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37891. /*** Start of inlined file: juce_ComboBox.cpp ***/
  37892. BEGIN_JUCE_NAMESPACE
  37893. ComboBox::ItemInfo::ItemInfo (const String& name_, int itemId_, bool isEnabled_, bool isHeading_)
  37894. : name (name_), itemId (itemId_), isEnabled (isEnabled_), isHeading (isHeading_)
  37895. {
  37896. }
  37897. bool ComboBox::ItemInfo::isSeparator() const throw()
  37898. {
  37899. return name.isEmpty();
  37900. }
  37901. bool ComboBox::ItemInfo::isRealItem() const throw()
  37902. {
  37903. return ! (isHeading || name.isEmpty());
  37904. }
  37905. ComboBox::ComboBox (const String& name)
  37906. : Component (name),
  37907. lastCurrentId (0),
  37908. isButtonDown (false),
  37909. separatorPending (false),
  37910. menuActive (false),
  37911. noChoicesMessage (TRANS("(no choices)"))
  37912. {
  37913. setRepaintsOnMouseActivity (true);
  37914. lookAndFeelChanged();
  37915. currentId.addListener (this);
  37916. }
  37917. ComboBox::~ComboBox()
  37918. {
  37919. currentId.removeListener (this);
  37920. if (menuActive)
  37921. PopupMenu::dismissAllActiveMenus();
  37922. label = 0;
  37923. }
  37924. void ComboBox::setEditableText (const bool isEditable)
  37925. {
  37926. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  37927. {
  37928. label->setEditable (isEditable, isEditable, false);
  37929. setWantsKeyboardFocus (! isEditable);
  37930. resized();
  37931. }
  37932. }
  37933. bool ComboBox::isTextEditable() const throw()
  37934. {
  37935. return label->isEditable();
  37936. }
  37937. void ComboBox::setJustificationType (const Justification& justification)
  37938. {
  37939. label->setJustificationType (justification);
  37940. }
  37941. const Justification ComboBox::getJustificationType() const throw()
  37942. {
  37943. return label->getJustificationType();
  37944. }
  37945. void ComboBox::setTooltip (const String& newTooltip)
  37946. {
  37947. SettableTooltipClient::setTooltip (newTooltip);
  37948. label->setTooltip (newTooltip);
  37949. }
  37950. void ComboBox::addItem (const String& newItemText, const int newItemId)
  37951. {
  37952. // you can't add empty strings to the list..
  37953. jassert (newItemText.isNotEmpty());
  37954. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  37955. jassert (newItemId != 0);
  37956. // you shouldn't use duplicate item IDs!
  37957. jassert (getItemForId (newItemId) == 0);
  37958. if (newItemText.isNotEmpty() && newItemId != 0)
  37959. {
  37960. if (separatorPending)
  37961. {
  37962. separatorPending = false;
  37963. items.add (new ItemInfo (String::empty, 0, false, false));
  37964. }
  37965. items.add (new ItemInfo (newItemText, newItemId, true, false));
  37966. }
  37967. }
  37968. void ComboBox::addSeparator()
  37969. {
  37970. separatorPending = (items.size() > 0);
  37971. }
  37972. void ComboBox::addSectionHeading (const String& headingName)
  37973. {
  37974. // you can't add empty strings to the list..
  37975. jassert (headingName.isNotEmpty());
  37976. if (headingName.isNotEmpty())
  37977. {
  37978. if (separatorPending)
  37979. {
  37980. separatorPending = false;
  37981. items.add (new ItemInfo (String::empty, 0, false, false));
  37982. }
  37983. items.add (new ItemInfo (headingName, 0, true, true));
  37984. }
  37985. }
  37986. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  37987. {
  37988. ItemInfo* const item = getItemForId (itemId);
  37989. if (item != 0)
  37990. item->isEnabled = shouldBeEnabled;
  37991. }
  37992. bool ComboBox::isItemEnabled (int itemId) const throw()
  37993. {
  37994. const ItemInfo* const item = getItemForId (itemId);
  37995. return item != 0 && item->isEnabled;
  37996. }
  37997. void ComboBox::changeItemText (const int itemId, const String& newText)
  37998. {
  37999. ItemInfo* const item = getItemForId (itemId);
  38000. jassert (item != 0);
  38001. if (item != 0)
  38002. item->name = newText;
  38003. }
  38004. void ComboBox::clear (const bool dontSendChangeMessage)
  38005. {
  38006. items.clear();
  38007. separatorPending = false;
  38008. if (! label->isEditable())
  38009. setSelectedItemIndex (-1, dontSendChangeMessage);
  38010. }
  38011. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38012. {
  38013. if (itemId != 0)
  38014. {
  38015. for (int i = items.size(); --i >= 0;)
  38016. if (items.getUnchecked(i)->itemId == itemId)
  38017. return items.getUnchecked(i);
  38018. }
  38019. return 0;
  38020. }
  38021. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38022. {
  38023. for (int n = 0, i = 0; i < items.size(); ++i)
  38024. {
  38025. ItemInfo* const item = items.getUnchecked(i);
  38026. if (item->isRealItem())
  38027. if (n++ == index)
  38028. return item;
  38029. }
  38030. return 0;
  38031. }
  38032. int ComboBox::getNumItems() const throw()
  38033. {
  38034. int n = 0;
  38035. for (int i = items.size(); --i >= 0;)
  38036. if (items.getUnchecked(i)->isRealItem())
  38037. ++n;
  38038. return n;
  38039. }
  38040. const String ComboBox::getItemText (const int index) const
  38041. {
  38042. const ItemInfo* const item = getItemForIndex (index);
  38043. return item != 0 ? item->name : String::empty;
  38044. }
  38045. int ComboBox::getItemId (const int index) const throw()
  38046. {
  38047. const ItemInfo* const item = getItemForIndex (index);
  38048. return item != 0 ? item->itemId : 0;
  38049. }
  38050. int ComboBox::indexOfItemId (const int itemId) const throw()
  38051. {
  38052. for (int n = 0, i = 0; i < items.size(); ++i)
  38053. {
  38054. const ItemInfo* const item = items.getUnchecked(i);
  38055. if (item->isRealItem())
  38056. {
  38057. if (item->itemId == itemId)
  38058. return n;
  38059. ++n;
  38060. }
  38061. }
  38062. return -1;
  38063. }
  38064. int ComboBox::getSelectedItemIndex() const
  38065. {
  38066. int index = indexOfItemId (currentId.getValue());
  38067. if (getText() != getItemText (index))
  38068. index = -1;
  38069. return index;
  38070. }
  38071. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38072. {
  38073. setSelectedId (getItemId (index), dontSendChangeMessage);
  38074. }
  38075. int ComboBox::getSelectedId() const throw()
  38076. {
  38077. const ItemInfo* const item = getItemForId (currentId.getValue());
  38078. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38079. }
  38080. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38081. {
  38082. const ItemInfo* const item = getItemForId (newItemId);
  38083. const String newItemText (item != 0 ? item->name : String::empty);
  38084. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38085. {
  38086. if (! dontSendChangeMessage)
  38087. triggerAsyncUpdate();
  38088. label->setText (newItemText, false);
  38089. lastCurrentId = newItemId;
  38090. currentId = newItemId;
  38091. repaint(); // for the benefit of the 'none selected' text
  38092. }
  38093. }
  38094. bool ComboBox::selectIfEnabled (const int index)
  38095. {
  38096. const ItemInfo* const item = getItemForIndex (index);
  38097. if (item != 0 && item->isEnabled)
  38098. {
  38099. setSelectedItemIndex (index);
  38100. return true;
  38101. }
  38102. return false;
  38103. }
  38104. void ComboBox::valueChanged (Value&)
  38105. {
  38106. if (lastCurrentId != (int) currentId.getValue())
  38107. setSelectedId (currentId.getValue(), false);
  38108. }
  38109. const String ComboBox::getText() const
  38110. {
  38111. return label->getText();
  38112. }
  38113. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38114. {
  38115. for (int i = items.size(); --i >= 0;)
  38116. {
  38117. const ItemInfo* const item = items.getUnchecked(i);
  38118. if (item->isRealItem()
  38119. && item->name == newText)
  38120. {
  38121. setSelectedId (item->itemId, dontSendChangeMessage);
  38122. return;
  38123. }
  38124. }
  38125. lastCurrentId = 0;
  38126. currentId = 0;
  38127. if (label->getText() != newText)
  38128. {
  38129. label->setText (newText, false);
  38130. if (! dontSendChangeMessage)
  38131. triggerAsyncUpdate();
  38132. }
  38133. repaint();
  38134. }
  38135. void ComboBox::showEditor()
  38136. {
  38137. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38138. label->showEditor();
  38139. }
  38140. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38141. {
  38142. if (textWhenNothingSelected != newMessage)
  38143. {
  38144. textWhenNothingSelected = newMessage;
  38145. repaint();
  38146. }
  38147. }
  38148. const String ComboBox::getTextWhenNothingSelected() const
  38149. {
  38150. return textWhenNothingSelected;
  38151. }
  38152. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38153. {
  38154. noChoicesMessage = newMessage;
  38155. }
  38156. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38157. {
  38158. return noChoicesMessage;
  38159. }
  38160. void ComboBox::paint (Graphics& g)
  38161. {
  38162. getLookAndFeel().drawComboBox (g, getWidth(), getHeight(), isButtonDown,
  38163. label->getRight(), 0, getWidth() - label->getRight(), getHeight(),
  38164. *this);
  38165. if (textWhenNothingSelected.isNotEmpty()
  38166. && label->getText().isEmpty()
  38167. && ! label->isBeingEdited())
  38168. {
  38169. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38170. g.setFont (label->getFont());
  38171. g.drawFittedText (textWhenNothingSelected,
  38172. label->getX() + 2, label->getY() + 1,
  38173. label->getWidth() - 4, label->getHeight() - 2,
  38174. label->getJustificationType(),
  38175. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38176. }
  38177. }
  38178. void ComboBox::resized()
  38179. {
  38180. if (getHeight() > 0 && getWidth() > 0)
  38181. getLookAndFeel().positionComboBoxText (*this, *label);
  38182. }
  38183. void ComboBox::enablementChanged()
  38184. {
  38185. repaint();
  38186. }
  38187. void ComboBox::lookAndFeelChanged()
  38188. {
  38189. repaint();
  38190. {
  38191. ScopedPointer <Label> newLabel (getLookAndFeel().createComboBoxTextBox (*this));
  38192. jassert (newLabel != 0);
  38193. if (label != 0)
  38194. {
  38195. newLabel->setEditable (label->isEditable());
  38196. newLabel->setJustificationType (label->getJustificationType());
  38197. newLabel->setTooltip (label->getTooltip());
  38198. newLabel->setText (label->getText(), false);
  38199. }
  38200. label = newLabel;
  38201. }
  38202. addAndMakeVisible (label);
  38203. label->addListener (this);
  38204. label->addMouseListener (this, false);
  38205. label->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38206. label->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38207. label->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38208. label->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38209. label->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38210. label->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38211. resized();
  38212. }
  38213. void ComboBox::colourChanged()
  38214. {
  38215. lookAndFeelChanged();
  38216. }
  38217. bool ComboBox::keyPressed (const KeyPress& key)
  38218. {
  38219. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  38220. {
  38221. int index = getSelectedItemIndex() - 1;
  38222. while (index >= 0 && ! selectIfEnabled (index))
  38223. --index;
  38224. return true;
  38225. }
  38226. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  38227. {
  38228. int index = getSelectedItemIndex() + 1;
  38229. while (index < getNumItems() && ! selectIfEnabled (index))
  38230. ++index;
  38231. return true;
  38232. }
  38233. else if (key.isKeyCode (KeyPress::returnKey))
  38234. {
  38235. showPopup();
  38236. return true;
  38237. }
  38238. return false;
  38239. }
  38240. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38241. {
  38242. // only forward key events that aren't used by this component
  38243. return isKeyDown
  38244. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38245. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38246. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38247. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38248. }
  38249. void ComboBox::focusGained (FocusChangeType) { repaint(); }
  38250. void ComboBox::focusLost (FocusChangeType) { repaint(); }
  38251. void ComboBox::labelTextChanged (Label*)
  38252. {
  38253. triggerAsyncUpdate();
  38254. }
  38255. class ComboBox::Callback : public ModalComponentManager::Callback
  38256. {
  38257. public:
  38258. Callback (ComboBox* const box_)
  38259. : box (box_)
  38260. {
  38261. }
  38262. void modalStateFinished (int returnValue)
  38263. {
  38264. if (box != 0)
  38265. {
  38266. box->menuActive = false;
  38267. if (returnValue != 0)
  38268. box->setSelectedId (returnValue);
  38269. }
  38270. }
  38271. private:
  38272. Component::SafePointer<ComboBox> box;
  38273. JUCE_DECLARE_NON_COPYABLE (Callback);
  38274. };
  38275. void ComboBox::showPopup()
  38276. {
  38277. if (! menuActive)
  38278. {
  38279. const int selectedId = getSelectedId();
  38280. PopupMenu menu;
  38281. menu.setLookAndFeel (&getLookAndFeel());
  38282. for (int i = 0; i < items.size(); ++i)
  38283. {
  38284. const ItemInfo* const item = items.getUnchecked(i);
  38285. if (item->isSeparator())
  38286. menu.addSeparator();
  38287. else if (item->isHeading)
  38288. menu.addSectionHeader (item->name);
  38289. else
  38290. menu.addItem (item->itemId, item->name,
  38291. item->isEnabled, item->itemId == selectedId);
  38292. }
  38293. if (items.size() == 0)
  38294. menu.addItem (1, noChoicesMessage, false);
  38295. menuActive = true;
  38296. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38297. new Callback (this));
  38298. }
  38299. }
  38300. void ComboBox::mouseDown (const MouseEvent& e)
  38301. {
  38302. beginDragAutoRepeat (300);
  38303. isButtonDown = isEnabled() && ! e.mods.isPopupMenu();
  38304. if (isButtonDown && (e.eventComponent == this || ! label->isEditable()))
  38305. showPopup();
  38306. }
  38307. void ComboBox::mouseDrag (const MouseEvent& e)
  38308. {
  38309. beginDragAutoRepeat (50);
  38310. if (isButtonDown && ! e.mouseWasClicked())
  38311. showPopup();
  38312. }
  38313. void ComboBox::mouseUp (const MouseEvent& e2)
  38314. {
  38315. if (isButtonDown)
  38316. {
  38317. isButtonDown = false;
  38318. repaint();
  38319. const MouseEvent e (e2.getEventRelativeTo (this));
  38320. if (reallyContains (e.getPosition(), true)
  38321. && (e2.eventComponent == this || ! label->isEditable()))
  38322. {
  38323. showPopup();
  38324. }
  38325. }
  38326. }
  38327. void ComboBox::addListener (ComboBoxListener* const listener)
  38328. {
  38329. listeners.add (listener);
  38330. }
  38331. void ComboBox::removeListener (ComboBoxListener* const listener)
  38332. {
  38333. listeners.remove (listener);
  38334. }
  38335. void ComboBox::handleAsyncUpdate()
  38336. {
  38337. Component::BailOutChecker checker (this);
  38338. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38339. }
  38340. END_JUCE_NAMESPACE
  38341. /*** End of inlined file: juce_ComboBox.cpp ***/
  38342. /*** Start of inlined file: juce_Label.cpp ***/
  38343. BEGIN_JUCE_NAMESPACE
  38344. Label::Label (const String& componentName,
  38345. const String& labelText)
  38346. : Component (componentName),
  38347. textValue (labelText),
  38348. lastTextValue (labelText),
  38349. font (15.0f),
  38350. justification (Justification::centredLeft),
  38351. ownerComponent (0),
  38352. horizontalBorderSize (5),
  38353. verticalBorderSize (1),
  38354. minimumHorizontalScale (0.7f),
  38355. editSingleClick (false),
  38356. editDoubleClick (false),
  38357. lossOfFocusDiscardsChanges (false)
  38358. {
  38359. setColour (TextEditor::textColourId, Colours::black);
  38360. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38361. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38362. textValue.addListener (this);
  38363. }
  38364. Label::~Label()
  38365. {
  38366. textValue.removeListener (this);
  38367. if (ownerComponent != 0)
  38368. ownerComponent->removeComponentListener (this);
  38369. editor = 0;
  38370. }
  38371. void Label::setText (const String& newText,
  38372. const bool broadcastChangeMessage)
  38373. {
  38374. hideEditor (true);
  38375. if (lastTextValue != newText)
  38376. {
  38377. lastTextValue = newText;
  38378. textValue = newText;
  38379. repaint();
  38380. textWasChanged();
  38381. if (ownerComponent != 0)
  38382. componentMovedOrResized (*ownerComponent, true, true);
  38383. if (broadcastChangeMessage)
  38384. callChangeListeners();
  38385. }
  38386. }
  38387. const String Label::getText (const bool returnActiveEditorContents) const
  38388. {
  38389. return (returnActiveEditorContents && isBeingEdited())
  38390. ? editor->getText()
  38391. : textValue.toString();
  38392. }
  38393. void Label::valueChanged (Value&)
  38394. {
  38395. if (lastTextValue != textValue.toString())
  38396. setText (textValue.toString(), true);
  38397. }
  38398. void Label::setFont (const Font& newFont)
  38399. {
  38400. if (font != newFont)
  38401. {
  38402. font = newFont;
  38403. repaint();
  38404. }
  38405. }
  38406. const Font& Label::getFont() const throw()
  38407. {
  38408. return font;
  38409. }
  38410. void Label::setEditable (const bool editOnSingleClick,
  38411. const bool editOnDoubleClick,
  38412. const bool lossOfFocusDiscardsChanges_)
  38413. {
  38414. editSingleClick = editOnSingleClick;
  38415. editDoubleClick = editOnDoubleClick;
  38416. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38417. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38418. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38419. }
  38420. void Label::setJustificationType (const Justification& newJustification)
  38421. {
  38422. if (justification != newJustification)
  38423. {
  38424. justification = newJustification;
  38425. repaint();
  38426. }
  38427. }
  38428. void Label::setBorderSize (int h, int v)
  38429. {
  38430. if (horizontalBorderSize != h || verticalBorderSize != v)
  38431. {
  38432. horizontalBorderSize = h;
  38433. verticalBorderSize = v;
  38434. repaint();
  38435. }
  38436. }
  38437. Component* Label::getAttachedComponent() const
  38438. {
  38439. return static_cast<Component*> (ownerComponent);
  38440. }
  38441. void Label::attachToComponent (Component* owner,
  38442. const bool onLeft)
  38443. {
  38444. if (ownerComponent != 0)
  38445. ownerComponent->removeComponentListener (this);
  38446. ownerComponent = owner;
  38447. leftOfOwnerComp = onLeft;
  38448. if (ownerComponent != 0)
  38449. {
  38450. setVisible (owner->isVisible());
  38451. ownerComponent->addComponentListener (this);
  38452. componentParentHierarchyChanged (*ownerComponent);
  38453. componentMovedOrResized (*ownerComponent, true, true);
  38454. }
  38455. }
  38456. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38457. {
  38458. if (leftOfOwnerComp)
  38459. {
  38460. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38461. component.getHeight());
  38462. setTopRightPosition (component.getX(), component.getY());
  38463. }
  38464. else
  38465. {
  38466. setSize (component.getWidth(),
  38467. 8 + roundToInt (getFont().getHeight()));
  38468. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38469. }
  38470. }
  38471. void Label::componentParentHierarchyChanged (Component& component)
  38472. {
  38473. if (component.getParentComponent() != 0)
  38474. component.getParentComponent()->addChildComponent (this);
  38475. }
  38476. void Label::componentVisibilityChanged (Component& component)
  38477. {
  38478. setVisible (component.isVisible());
  38479. }
  38480. void Label::textWasEdited()
  38481. {
  38482. }
  38483. void Label::textWasChanged()
  38484. {
  38485. }
  38486. void Label::showEditor()
  38487. {
  38488. if (editor == 0)
  38489. {
  38490. addAndMakeVisible (editor = createEditorComponent());
  38491. editor->setText (getText(), false);
  38492. editor->addListener (this);
  38493. editor->grabKeyboardFocus();
  38494. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38495. editor->addListener (this);
  38496. resized();
  38497. repaint();
  38498. editorShown (editor);
  38499. enterModalState (false);
  38500. editor->grabKeyboardFocus();
  38501. }
  38502. }
  38503. void Label::editorShown (TextEditor*)
  38504. {
  38505. }
  38506. void Label::editorAboutToBeHidden (TextEditor*)
  38507. {
  38508. }
  38509. bool Label::updateFromTextEditorContents (TextEditor& ed)
  38510. {
  38511. const String newText (ed.getText());
  38512. if (textValue.toString() != newText)
  38513. {
  38514. lastTextValue = newText;
  38515. textValue = newText;
  38516. repaint();
  38517. textWasChanged();
  38518. if (ownerComponent != 0)
  38519. componentMovedOrResized (*ownerComponent, true, true);
  38520. return true;
  38521. }
  38522. return false;
  38523. }
  38524. void Label::hideEditor (const bool discardCurrentEditorContents)
  38525. {
  38526. if (editor != 0)
  38527. {
  38528. WeakReference<Component> deletionChecker (this);
  38529. ScopedPointer<TextEditor> outgoingEditor (editor);
  38530. editorAboutToBeHidden (outgoingEditor);
  38531. const bool changed = (! discardCurrentEditorContents)
  38532. && updateFromTextEditorContents (*outgoingEditor);
  38533. outgoingEditor = 0;
  38534. repaint();
  38535. if (changed)
  38536. textWasEdited();
  38537. if (deletionChecker != 0)
  38538. exitModalState (0);
  38539. if (changed && deletionChecker != 0)
  38540. callChangeListeners();
  38541. }
  38542. }
  38543. void Label::inputAttemptWhenModal()
  38544. {
  38545. if (editor != 0)
  38546. {
  38547. if (lossOfFocusDiscardsChanges)
  38548. textEditorEscapeKeyPressed (*editor);
  38549. else
  38550. textEditorReturnKeyPressed (*editor);
  38551. }
  38552. }
  38553. bool Label::isBeingEdited() const throw()
  38554. {
  38555. return editor != 0;
  38556. }
  38557. TextEditor* Label::createEditorComponent()
  38558. {
  38559. TextEditor* const ed = new TextEditor (getName());
  38560. ed->setFont (font);
  38561. // copy these colours from our own settings..
  38562. const int cols[] = { TextEditor::backgroundColourId,
  38563. TextEditor::textColourId,
  38564. TextEditor::highlightColourId,
  38565. TextEditor::highlightedTextColourId,
  38566. TextEditor::caretColourId,
  38567. TextEditor::outlineColourId,
  38568. TextEditor::focusedOutlineColourId,
  38569. TextEditor::shadowColourId };
  38570. for (int i = 0; i < numElementsInArray (cols); ++i)
  38571. ed->setColour (cols[i], findColour (cols[i]));
  38572. return ed;
  38573. }
  38574. void Label::paint (Graphics& g)
  38575. {
  38576. getLookAndFeel().drawLabel (g, *this);
  38577. }
  38578. void Label::mouseUp (const MouseEvent& e)
  38579. {
  38580. if (editSingleClick
  38581. && e.mouseWasClicked()
  38582. && contains (e.getPosition())
  38583. && ! e.mods.isPopupMenu())
  38584. {
  38585. showEditor();
  38586. }
  38587. }
  38588. void Label::mouseDoubleClick (const MouseEvent& e)
  38589. {
  38590. if (editDoubleClick && ! e.mods.isPopupMenu())
  38591. showEditor();
  38592. }
  38593. void Label::resized()
  38594. {
  38595. if (editor != 0)
  38596. editor->setBoundsInset (BorderSize<int> (0));
  38597. }
  38598. void Label::focusGained (FocusChangeType cause)
  38599. {
  38600. if (editSingleClick && cause == focusChangedByTabKey)
  38601. showEditor();
  38602. }
  38603. void Label::enablementChanged()
  38604. {
  38605. repaint();
  38606. }
  38607. void Label::colourChanged()
  38608. {
  38609. repaint();
  38610. }
  38611. void Label::setMinimumHorizontalScale (const float newScale)
  38612. {
  38613. if (minimumHorizontalScale != newScale)
  38614. {
  38615. minimumHorizontalScale = newScale;
  38616. repaint();
  38617. }
  38618. }
  38619. // We'll use a custom focus traverser here to make sure focus goes from the
  38620. // text editor to another component rather than back to the label itself.
  38621. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38622. {
  38623. public:
  38624. LabelKeyboardFocusTraverser() {}
  38625. Component* getNextComponent (Component* current)
  38626. {
  38627. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38628. ? current->getParentComponent() : current);
  38629. }
  38630. Component* getPreviousComponent (Component* current)
  38631. {
  38632. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38633. ? current->getParentComponent() : current);
  38634. }
  38635. };
  38636. KeyboardFocusTraverser* Label::createFocusTraverser()
  38637. {
  38638. return new LabelKeyboardFocusTraverser();
  38639. }
  38640. void Label::addListener (LabelListener* const listener)
  38641. {
  38642. listeners.add (listener);
  38643. }
  38644. void Label::removeListener (LabelListener* const listener)
  38645. {
  38646. listeners.remove (listener);
  38647. }
  38648. void Label::callChangeListeners()
  38649. {
  38650. Component::BailOutChecker checker (this);
  38651. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38652. }
  38653. void Label::textEditorTextChanged (TextEditor& ed)
  38654. {
  38655. if (editor != 0)
  38656. {
  38657. jassert (&ed == editor);
  38658. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38659. {
  38660. if (lossOfFocusDiscardsChanges)
  38661. textEditorEscapeKeyPressed (ed);
  38662. else
  38663. textEditorReturnKeyPressed (ed);
  38664. }
  38665. }
  38666. }
  38667. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38668. {
  38669. if (editor != 0)
  38670. {
  38671. jassert (&ed == editor);
  38672. const bool changed = updateFromTextEditorContents (ed);
  38673. hideEditor (true);
  38674. if (changed)
  38675. {
  38676. WeakReference<Component> deletionChecker (this);
  38677. textWasEdited();
  38678. if (deletionChecker != 0)
  38679. callChangeListeners();
  38680. }
  38681. }
  38682. }
  38683. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  38684. {
  38685. if (editor != 0)
  38686. {
  38687. jassert (&ed == editor);
  38688. (void) ed;
  38689. editor->setText (textValue.toString(), false);
  38690. hideEditor (true);
  38691. }
  38692. }
  38693. void Label::textEditorFocusLost (TextEditor& ed)
  38694. {
  38695. textEditorTextChanged (ed);
  38696. }
  38697. END_JUCE_NAMESPACE
  38698. /*** End of inlined file: juce_Label.cpp ***/
  38699. /*** Start of inlined file: juce_ListBox.cpp ***/
  38700. BEGIN_JUCE_NAMESPACE
  38701. class ListBoxRowComponent : public Component,
  38702. public TooltipClient
  38703. {
  38704. public:
  38705. ListBoxRowComponent (ListBox& owner_)
  38706. : owner (owner_), row (-1),
  38707. selected (false), isDragging (false), selectRowOnMouseUp (false)
  38708. {
  38709. }
  38710. void paint (Graphics& g)
  38711. {
  38712. if (owner.getModel() != 0)
  38713. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  38714. }
  38715. void update (const int row_, const bool selected_)
  38716. {
  38717. if (row != row_ || selected != selected_)
  38718. {
  38719. repaint();
  38720. row = row_;
  38721. selected = selected_;
  38722. }
  38723. if (owner.getModel() != 0)
  38724. {
  38725. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  38726. if (customComponent != 0)
  38727. {
  38728. addAndMakeVisible (customComponent);
  38729. customComponent->setBounds (getLocalBounds());
  38730. }
  38731. }
  38732. }
  38733. void mouseDown (const MouseEvent& e)
  38734. {
  38735. isDragging = false;
  38736. selectRowOnMouseUp = false;
  38737. if (isEnabled())
  38738. {
  38739. if (! selected)
  38740. {
  38741. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  38742. if (owner.getModel() != 0)
  38743. owner.getModel()->listBoxItemClicked (row, e);
  38744. }
  38745. else
  38746. {
  38747. selectRowOnMouseUp = true;
  38748. }
  38749. }
  38750. }
  38751. void mouseUp (const MouseEvent& e)
  38752. {
  38753. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  38754. {
  38755. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  38756. if (owner.getModel() != 0)
  38757. owner.getModel()->listBoxItemClicked (row, e);
  38758. }
  38759. }
  38760. void mouseDoubleClick (const MouseEvent& e)
  38761. {
  38762. if (owner.getModel() != 0 && isEnabled())
  38763. owner.getModel()->listBoxItemDoubleClicked (row, e);
  38764. }
  38765. void mouseDrag (const MouseEvent& e)
  38766. {
  38767. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38768. {
  38769. const SparseSet<int> selectedRows (owner.getSelectedRows());
  38770. if (selectedRows.size() > 0)
  38771. {
  38772. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38773. if (dragDescription.isNotEmpty())
  38774. {
  38775. isDragging = true;
  38776. owner.startDragAndDrop (e, dragDescription);
  38777. }
  38778. }
  38779. }
  38780. }
  38781. void resized()
  38782. {
  38783. if (customComponent != 0)
  38784. customComponent->setBounds (getLocalBounds());
  38785. }
  38786. const String getTooltip()
  38787. {
  38788. if (owner.getModel() != 0)
  38789. return owner.getModel()->getTooltipForRow (row);
  38790. return String::empty;
  38791. }
  38792. ScopedPointer<Component> customComponent;
  38793. private:
  38794. ListBox& owner;
  38795. int row;
  38796. bool selected, isDragging, selectRowOnMouseUp;
  38797. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListBoxRowComponent);
  38798. };
  38799. class ListViewport : public Viewport
  38800. {
  38801. public:
  38802. ListViewport (ListBox& owner_)
  38803. : owner (owner_)
  38804. {
  38805. setWantsKeyboardFocus (false);
  38806. Component* const content = new Component();
  38807. setViewedComponent (content);
  38808. content->addMouseListener (this, false);
  38809. content->setWantsKeyboardFocus (false);
  38810. }
  38811. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  38812. {
  38813. return rows [row % jmax (1, rows.size())];
  38814. }
  38815. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  38816. {
  38817. return (row >= firstIndex && row < firstIndex + rows.size())
  38818. ? getComponentForRow (row) : 0;
  38819. }
  38820. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  38821. {
  38822. const int index = getIndexOfChildComponent (rowComponent);
  38823. const int num = rows.size();
  38824. for (int i = num; --i >= 0;)
  38825. if (((firstIndex + i) % jmax (1, num)) == index)
  38826. return firstIndex + i;
  38827. return -1;
  38828. }
  38829. void visibleAreaChanged (const Rectangle<int>&)
  38830. {
  38831. updateVisibleArea (true);
  38832. if (owner.getModel() != 0)
  38833. owner.getModel()->listWasScrolled();
  38834. }
  38835. void updateVisibleArea (const bool makeSureItUpdatesContent)
  38836. {
  38837. hasUpdated = false;
  38838. const int newX = getViewedComponent()->getX();
  38839. int newY = getViewedComponent()->getY();
  38840. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  38841. const int newH = owner.totalItems * owner.getRowHeight();
  38842. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  38843. newY = getMaximumVisibleHeight() - newH;
  38844. getViewedComponent()->setBounds (newX, newY, newW, newH);
  38845. if (makeSureItUpdatesContent && ! hasUpdated)
  38846. updateContents();
  38847. }
  38848. void updateContents()
  38849. {
  38850. hasUpdated = true;
  38851. const int rowHeight = owner.getRowHeight();
  38852. if (rowHeight > 0)
  38853. {
  38854. const int y = getViewPositionY();
  38855. const int w = getViewedComponent()->getWidth();
  38856. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  38857. rows.removeRange (numNeeded, rows.size());
  38858. while (numNeeded > rows.size())
  38859. {
  38860. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  38861. rows.add (newRow);
  38862. getViewedComponent()->addAndMakeVisible (newRow);
  38863. }
  38864. firstIndex = y / rowHeight;
  38865. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  38866. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  38867. for (int i = 0; i < numNeeded; ++i)
  38868. {
  38869. const int row = i + firstIndex;
  38870. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  38871. if (rowComp != 0)
  38872. {
  38873. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  38874. rowComp->update (row, owner.isRowSelected (row));
  38875. }
  38876. }
  38877. }
  38878. if (owner.headerComponent != 0)
  38879. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  38880. owner.outlineThickness,
  38881. jmax (owner.getWidth() - owner.outlineThickness * 2,
  38882. getViewedComponent()->getWidth()),
  38883. owner.headerComponent->getHeight());
  38884. }
  38885. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  38886. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  38887. {
  38888. hasUpdated = false;
  38889. if (row < firstWholeIndex && ! dontScroll)
  38890. {
  38891. setViewPosition (getViewPositionX(), row * rowHeight);
  38892. }
  38893. else if (row >= lastWholeIndex && ! dontScroll)
  38894. {
  38895. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  38896. if (row >= lastRowSelected + rowsOnScreen
  38897. && rowsOnScreen < totalItems - 1
  38898. && ! isMouseClick)
  38899. {
  38900. setViewPosition (getViewPositionX(),
  38901. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  38902. }
  38903. else
  38904. {
  38905. setViewPosition (getViewPositionX(),
  38906. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38907. }
  38908. }
  38909. if (! hasUpdated)
  38910. updateContents();
  38911. }
  38912. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  38913. {
  38914. if (row < firstWholeIndex)
  38915. {
  38916. setViewPosition (getViewPositionX(), row * rowHeight);
  38917. }
  38918. else if (row >= lastWholeIndex)
  38919. {
  38920. setViewPosition (getViewPositionX(),
  38921. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  38922. }
  38923. }
  38924. void paint (Graphics& g)
  38925. {
  38926. if (isOpaque())
  38927. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  38928. }
  38929. bool keyPressed (const KeyPress& key)
  38930. {
  38931. if (key.isKeyCode (KeyPress::upKey)
  38932. || key.isKeyCode (KeyPress::downKey)
  38933. || key.isKeyCode (KeyPress::pageUpKey)
  38934. || key.isKeyCode (KeyPress::pageDownKey)
  38935. || key.isKeyCode (KeyPress::homeKey)
  38936. || key.isKeyCode (KeyPress::endKey))
  38937. {
  38938. // we want to avoid these keypresses going to the viewport, and instead allow
  38939. // them to pass up to our listbox..
  38940. return false;
  38941. }
  38942. return Viewport::keyPressed (key);
  38943. }
  38944. private:
  38945. ListBox& owner;
  38946. OwnedArray<ListBoxRowComponent> rows;
  38947. int firstIndex, firstWholeIndex, lastWholeIndex;
  38948. bool hasUpdated;
  38949. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ListViewport);
  38950. };
  38951. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  38952. : Component (name),
  38953. model (model_),
  38954. totalItems (0),
  38955. rowHeight (22),
  38956. minimumRowWidth (0),
  38957. outlineThickness (0),
  38958. lastRowSelected (-1),
  38959. mouseMoveSelects (false),
  38960. multipleSelection (false),
  38961. hasDoneInitialUpdate (false)
  38962. {
  38963. addAndMakeVisible (viewport = new ListViewport (*this));
  38964. setWantsKeyboardFocus (true);
  38965. colourChanged();
  38966. }
  38967. ListBox::~ListBox()
  38968. {
  38969. headerComponent = 0;
  38970. viewport = 0;
  38971. }
  38972. void ListBox::setModel (ListBoxModel* const newModel)
  38973. {
  38974. if (model != newModel)
  38975. {
  38976. model = newModel;
  38977. repaint();
  38978. updateContent();
  38979. }
  38980. }
  38981. void ListBox::setMultipleSelectionEnabled (bool b)
  38982. {
  38983. multipleSelection = b;
  38984. }
  38985. void ListBox::setMouseMoveSelectsRows (bool b)
  38986. {
  38987. mouseMoveSelects = b;
  38988. if (b)
  38989. addMouseListener (this, true);
  38990. }
  38991. void ListBox::paint (Graphics& g)
  38992. {
  38993. if (! hasDoneInitialUpdate)
  38994. updateContent();
  38995. g.fillAll (findColour (backgroundColourId));
  38996. }
  38997. void ListBox::paintOverChildren (Graphics& g)
  38998. {
  38999. if (outlineThickness > 0)
  39000. {
  39001. g.setColour (findColour (outlineColourId));
  39002. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39003. }
  39004. }
  39005. void ListBox::resized()
  39006. {
  39007. viewport->setBoundsInset (BorderSize<int> (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39008. outlineThickness, outlineThickness, outlineThickness));
  39009. viewport->setSingleStepSizes (20, getRowHeight());
  39010. viewport->updateVisibleArea (false);
  39011. }
  39012. void ListBox::visibilityChanged()
  39013. {
  39014. viewport->updateVisibleArea (true);
  39015. }
  39016. Viewport* ListBox::getViewport() const throw()
  39017. {
  39018. return viewport;
  39019. }
  39020. void ListBox::updateContent()
  39021. {
  39022. hasDoneInitialUpdate = true;
  39023. totalItems = (model != 0) ? model->getNumRows() : 0;
  39024. bool selectionChanged = false;
  39025. if (selected.size() > 0 && selected [selected.size() - 1] >= totalItems)
  39026. {
  39027. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39028. lastRowSelected = getSelectedRow (0);
  39029. selectionChanged = true;
  39030. }
  39031. viewport->updateVisibleArea (isVisible());
  39032. viewport->resized();
  39033. if (selectionChanged && model != 0)
  39034. model->selectedRowsChanged (lastRowSelected);
  39035. }
  39036. void ListBox::selectRow (const int row,
  39037. bool dontScroll,
  39038. bool deselectOthersFirst)
  39039. {
  39040. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39041. }
  39042. void ListBox::selectRowInternal (const int row,
  39043. bool dontScroll,
  39044. bool deselectOthersFirst,
  39045. bool isMouseClick)
  39046. {
  39047. if (! multipleSelection)
  39048. deselectOthersFirst = true;
  39049. if ((! isRowSelected (row))
  39050. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39051. {
  39052. if (isPositiveAndBelow (row, totalItems))
  39053. {
  39054. if (deselectOthersFirst)
  39055. selected.clear();
  39056. selected.addRange (Range<int> (row, row + 1));
  39057. if (getHeight() == 0 || getWidth() == 0)
  39058. dontScroll = true;
  39059. viewport->selectRow (row, getRowHeight(), dontScroll,
  39060. lastRowSelected, totalItems, isMouseClick);
  39061. lastRowSelected = row;
  39062. model->selectedRowsChanged (row);
  39063. }
  39064. else
  39065. {
  39066. if (deselectOthersFirst)
  39067. deselectAllRows();
  39068. }
  39069. }
  39070. }
  39071. void ListBox::deselectRow (const int row)
  39072. {
  39073. if (selected.contains (row))
  39074. {
  39075. selected.removeRange (Range <int> (row, row + 1));
  39076. if (row == lastRowSelected)
  39077. lastRowSelected = getSelectedRow (0);
  39078. viewport->updateContents();
  39079. model->selectedRowsChanged (lastRowSelected);
  39080. }
  39081. }
  39082. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39083. const bool sendNotificationEventToModel)
  39084. {
  39085. selected = setOfRowsToBeSelected;
  39086. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39087. if (! isRowSelected (lastRowSelected))
  39088. lastRowSelected = getSelectedRow (0);
  39089. viewport->updateContents();
  39090. if ((model != 0) && sendNotificationEventToModel)
  39091. model->selectedRowsChanged (lastRowSelected);
  39092. }
  39093. const SparseSet<int> ListBox::getSelectedRows() const
  39094. {
  39095. return selected;
  39096. }
  39097. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39098. {
  39099. if (multipleSelection && (firstRow != lastRow))
  39100. {
  39101. const int numRows = totalItems - 1;
  39102. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39103. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39104. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39105. jmax (firstRow, lastRow) + 1));
  39106. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39107. }
  39108. selectRowInternal (lastRow, false, false, true);
  39109. }
  39110. void ListBox::flipRowSelection (const int row)
  39111. {
  39112. if (isRowSelected (row))
  39113. deselectRow (row);
  39114. else
  39115. selectRowInternal (row, false, false, true);
  39116. }
  39117. void ListBox::deselectAllRows()
  39118. {
  39119. if (! selected.isEmpty())
  39120. {
  39121. selected.clear();
  39122. lastRowSelected = -1;
  39123. viewport->updateContents();
  39124. if (model != 0)
  39125. model->selectedRowsChanged (lastRowSelected);
  39126. }
  39127. }
  39128. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39129. const ModifierKeys& mods,
  39130. const bool isMouseUpEvent)
  39131. {
  39132. if (multipleSelection && mods.isCommandDown())
  39133. {
  39134. flipRowSelection (row);
  39135. }
  39136. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39137. {
  39138. selectRangeOfRows (lastRowSelected, row);
  39139. }
  39140. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39141. {
  39142. selectRowInternal (row, false, ! (multipleSelection && (! isMouseUpEvent) && isRowSelected (row)), true);
  39143. }
  39144. }
  39145. int ListBox::getNumSelectedRows() const
  39146. {
  39147. return selected.size();
  39148. }
  39149. int ListBox::getSelectedRow (const int index) const
  39150. {
  39151. return (isPositiveAndBelow (index, selected.size()))
  39152. ? selected [index] : -1;
  39153. }
  39154. bool ListBox::isRowSelected (const int row) const
  39155. {
  39156. return selected.contains (row);
  39157. }
  39158. int ListBox::getLastRowSelected() const
  39159. {
  39160. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39161. }
  39162. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39163. {
  39164. if (isPositiveAndBelow (x, getWidth()))
  39165. {
  39166. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39167. if (isPositiveAndBelow (row, totalItems))
  39168. return row;
  39169. }
  39170. return -1;
  39171. }
  39172. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39173. {
  39174. if (isPositiveAndBelow (x, getWidth()))
  39175. {
  39176. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39177. return jlimit (0, totalItems, row);
  39178. }
  39179. return -1;
  39180. }
  39181. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39182. {
  39183. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39184. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39185. }
  39186. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39187. {
  39188. return viewport->getRowNumberOfComponent (rowComponent);
  39189. }
  39190. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39191. const bool relativeToComponentTopLeft) const throw()
  39192. {
  39193. int y = viewport->getY() + rowHeight * rowNumber;
  39194. if (relativeToComponentTopLeft)
  39195. y -= viewport->getViewPositionY();
  39196. return Rectangle<int> (viewport->getX(), y,
  39197. viewport->getViewedComponent()->getWidth(), rowHeight);
  39198. }
  39199. void ListBox::setVerticalPosition (const double proportion)
  39200. {
  39201. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39202. viewport->setViewPosition (viewport->getViewPositionX(),
  39203. jmax (0, roundToInt (proportion * offscreen)));
  39204. }
  39205. double ListBox::getVerticalPosition() const
  39206. {
  39207. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39208. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39209. : 0;
  39210. }
  39211. int ListBox::getVisibleRowWidth() const throw()
  39212. {
  39213. return viewport->getViewWidth();
  39214. }
  39215. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39216. {
  39217. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39218. }
  39219. bool ListBox::keyPressed (const KeyPress& key)
  39220. {
  39221. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39222. const bool multiple = multipleSelection
  39223. && (lastRowSelected >= 0)
  39224. && (key.getModifiers().isShiftDown()
  39225. || key.getModifiers().isCtrlDown()
  39226. || key.getModifiers().isCommandDown());
  39227. if (key.isKeyCode (KeyPress::upKey))
  39228. {
  39229. if (multiple)
  39230. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39231. else
  39232. selectRow (jmax (0, lastRowSelected - 1));
  39233. }
  39234. else if (key.isKeyCode (KeyPress::returnKey)
  39235. && isRowSelected (lastRowSelected))
  39236. {
  39237. if (model != 0)
  39238. model->returnKeyPressed (lastRowSelected);
  39239. }
  39240. else if (key.isKeyCode (KeyPress::pageUpKey))
  39241. {
  39242. if (multiple)
  39243. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39244. else
  39245. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39246. }
  39247. else if (key.isKeyCode (KeyPress::pageDownKey))
  39248. {
  39249. if (multiple)
  39250. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39251. else
  39252. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39253. }
  39254. else if (key.isKeyCode (KeyPress::homeKey))
  39255. {
  39256. if (multiple && key.getModifiers().isShiftDown())
  39257. selectRangeOfRows (lastRowSelected, 0);
  39258. else
  39259. selectRow (0);
  39260. }
  39261. else if (key.isKeyCode (KeyPress::endKey))
  39262. {
  39263. if (multiple && key.getModifiers().isShiftDown())
  39264. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39265. else
  39266. selectRow (totalItems - 1);
  39267. }
  39268. else if (key.isKeyCode (KeyPress::downKey))
  39269. {
  39270. if (multiple)
  39271. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39272. else
  39273. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39274. }
  39275. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39276. && isRowSelected (lastRowSelected))
  39277. {
  39278. if (model != 0)
  39279. model->deleteKeyPressed (lastRowSelected);
  39280. }
  39281. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39282. {
  39283. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39284. }
  39285. else
  39286. {
  39287. return false;
  39288. }
  39289. return true;
  39290. }
  39291. bool ListBox::keyStateChanged (const bool isKeyDown)
  39292. {
  39293. return isKeyDown
  39294. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39295. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39296. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39297. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39298. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39299. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39300. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39301. }
  39302. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39303. {
  39304. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39305. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39306. }
  39307. void ListBox::mouseMove (const MouseEvent& e)
  39308. {
  39309. if (mouseMoveSelects)
  39310. {
  39311. const MouseEvent e2 (e.getEventRelativeTo (this));
  39312. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39313. }
  39314. }
  39315. void ListBox::mouseExit (const MouseEvent& e)
  39316. {
  39317. mouseMove (e);
  39318. }
  39319. void ListBox::mouseUp (const MouseEvent& e)
  39320. {
  39321. if (e.mouseWasClicked() && model != 0)
  39322. model->backgroundClicked();
  39323. }
  39324. void ListBox::setRowHeight (const int newHeight)
  39325. {
  39326. rowHeight = jmax (1, newHeight);
  39327. viewport->setSingleStepSizes (20, rowHeight);
  39328. updateContent();
  39329. }
  39330. int ListBox::getNumRowsOnScreen() const throw()
  39331. {
  39332. return viewport->getMaximumVisibleHeight() / rowHeight;
  39333. }
  39334. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39335. {
  39336. minimumRowWidth = newMinimumWidth;
  39337. updateContent();
  39338. }
  39339. int ListBox::getVisibleContentWidth() const throw()
  39340. {
  39341. return viewport->getMaximumVisibleWidth();
  39342. }
  39343. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39344. {
  39345. return viewport->getVerticalScrollBar();
  39346. }
  39347. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39348. {
  39349. return viewport->getHorizontalScrollBar();
  39350. }
  39351. void ListBox::colourChanged()
  39352. {
  39353. setOpaque (findColour (backgroundColourId).isOpaque());
  39354. viewport->setOpaque (isOpaque());
  39355. repaint();
  39356. }
  39357. void ListBox::setOutlineThickness (const int outlineThickness_)
  39358. {
  39359. outlineThickness = outlineThickness_;
  39360. resized();
  39361. }
  39362. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39363. {
  39364. if (headerComponent != newHeaderComponent)
  39365. {
  39366. headerComponent = newHeaderComponent;
  39367. addAndMakeVisible (newHeaderComponent);
  39368. ListBox::resized();
  39369. }
  39370. }
  39371. void ListBox::repaintRow (const int rowNumber) throw()
  39372. {
  39373. repaint (getRowPosition (rowNumber, true));
  39374. }
  39375. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39376. {
  39377. Rectangle<int> imageArea;
  39378. const int firstRow = getRowContainingPosition (0, 0);
  39379. int i;
  39380. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39381. {
  39382. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39383. if (rowComp != 0 && isRowSelected (firstRow + i))
  39384. {
  39385. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39386. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39387. imageArea = imageArea.getUnion (rowRect);
  39388. }
  39389. }
  39390. imageArea = imageArea.getIntersection (getLocalBounds());
  39391. imageX = imageArea.getX();
  39392. imageY = imageArea.getY();
  39393. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39394. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39395. {
  39396. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39397. if (rowComp != 0 && isRowSelected (firstRow + i))
  39398. {
  39399. const Point<int> pos (getLocalPoint (rowComp, Point<int>()));
  39400. Graphics g (snapshot);
  39401. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39402. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39403. {
  39404. g.beginTransparencyLayer (0.6f);
  39405. rowComp->paintEntireComponent (g, false);
  39406. g.endTransparencyLayer();
  39407. }
  39408. }
  39409. }
  39410. return snapshot;
  39411. }
  39412. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39413. {
  39414. DragAndDropContainer* const dragContainer
  39415. = DragAndDropContainer::findParentDragContainerFor (this);
  39416. if (dragContainer != 0)
  39417. {
  39418. int x, y;
  39419. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39420. MouseEvent e2 (e.getEventRelativeTo (this));
  39421. const Point<int> p (x - e2.x, y - e2.y);
  39422. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39423. }
  39424. else
  39425. {
  39426. // to be able to do a drag-and-drop operation, the listbox needs to
  39427. // be inside a component which is also a DragAndDropContainer.
  39428. jassertfalse;
  39429. }
  39430. }
  39431. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39432. {
  39433. (void) existingComponentToUpdate;
  39434. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39435. return 0;
  39436. }
  39437. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39438. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39439. void ListBoxModel::backgroundClicked() {}
  39440. void ListBoxModel::selectedRowsChanged (int) {}
  39441. void ListBoxModel::deleteKeyPressed (int) {}
  39442. void ListBoxModel::returnKeyPressed (int) {}
  39443. void ListBoxModel::listWasScrolled() {}
  39444. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39445. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39446. END_JUCE_NAMESPACE
  39447. /*** End of inlined file: juce_ListBox.cpp ***/
  39448. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39449. BEGIN_JUCE_NAMESPACE
  39450. ProgressBar::ProgressBar (double& progress_)
  39451. : progress (progress_),
  39452. displayPercentage (true),
  39453. lastCallbackTime (0)
  39454. {
  39455. currentValue = jlimit (0.0, 1.0, progress);
  39456. }
  39457. ProgressBar::~ProgressBar()
  39458. {
  39459. }
  39460. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39461. {
  39462. displayPercentage = shouldDisplayPercentage;
  39463. repaint();
  39464. }
  39465. void ProgressBar::setTextToDisplay (const String& text)
  39466. {
  39467. displayPercentage = false;
  39468. displayedMessage = text;
  39469. }
  39470. void ProgressBar::lookAndFeelChanged()
  39471. {
  39472. setOpaque (findColour (backgroundColourId).isOpaque());
  39473. }
  39474. void ProgressBar::colourChanged()
  39475. {
  39476. lookAndFeelChanged();
  39477. }
  39478. void ProgressBar::paint (Graphics& g)
  39479. {
  39480. String text;
  39481. if (displayPercentage)
  39482. {
  39483. if (currentValue >= 0 && currentValue <= 1.0)
  39484. text << roundToInt (currentValue * 100.0) << '%';
  39485. }
  39486. else
  39487. {
  39488. text = displayedMessage;
  39489. }
  39490. getLookAndFeel().drawProgressBar (g, *this,
  39491. getWidth(), getHeight(),
  39492. currentValue, text);
  39493. }
  39494. void ProgressBar::visibilityChanged()
  39495. {
  39496. if (isVisible())
  39497. startTimer (30);
  39498. else
  39499. stopTimer();
  39500. }
  39501. void ProgressBar::timerCallback()
  39502. {
  39503. double newProgress = progress;
  39504. const uint32 now = Time::getMillisecondCounter();
  39505. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39506. lastCallbackTime = now;
  39507. if (currentValue != newProgress
  39508. || newProgress < 0 || newProgress >= 1.0
  39509. || currentMessage != displayedMessage)
  39510. {
  39511. if (currentValue < newProgress
  39512. && newProgress >= 0 && newProgress < 1.0
  39513. && currentValue >= 0 && currentValue < 1.0)
  39514. {
  39515. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39516. newProgress);
  39517. }
  39518. currentValue = newProgress;
  39519. currentMessage = displayedMessage;
  39520. repaint();
  39521. }
  39522. }
  39523. END_JUCE_NAMESPACE
  39524. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39525. /*** Start of inlined file: juce_Slider.cpp ***/
  39526. BEGIN_JUCE_NAMESPACE
  39527. class SliderPopupDisplayComponent : public BubbleComponent
  39528. {
  39529. public:
  39530. SliderPopupDisplayComponent (Slider* const owner_)
  39531. : owner (owner_),
  39532. font (15.0f, Font::bold)
  39533. {
  39534. setAlwaysOnTop (true);
  39535. }
  39536. ~SliderPopupDisplayComponent()
  39537. {
  39538. }
  39539. void paintContent (Graphics& g, int w, int h)
  39540. {
  39541. g.setFont (font);
  39542. g.setColour (Colours::black);
  39543. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39544. }
  39545. void getContentSize (int& w, int& h)
  39546. {
  39547. w = font.getStringWidth (text) + 18;
  39548. h = (int) (font.getHeight() * 1.6f);
  39549. }
  39550. void updatePosition (const String& newText)
  39551. {
  39552. if (text != newText)
  39553. {
  39554. text = newText;
  39555. repaint();
  39556. }
  39557. BubbleComponent::setPosition (owner);
  39558. }
  39559. private:
  39560. Slider* owner;
  39561. Font font;
  39562. String text;
  39563. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderPopupDisplayComponent);
  39564. };
  39565. Slider::Slider (const String& name)
  39566. : Component (name),
  39567. lastCurrentValue (0),
  39568. lastValueMin (0),
  39569. lastValueMax (0),
  39570. minimum (0),
  39571. maximum (10),
  39572. interval (0),
  39573. skewFactor (1.0),
  39574. velocityModeSensitivity (1.0),
  39575. velocityModeOffset (0.0),
  39576. velocityModeThreshold (1),
  39577. rotaryStart (float_Pi * 1.2f),
  39578. rotaryEnd (float_Pi * 2.8f),
  39579. numDecimalPlaces (7),
  39580. sliderRegionStart (0),
  39581. sliderRegionSize (1),
  39582. sliderBeingDragged (-1),
  39583. pixelsForFullDragExtent (250),
  39584. style (LinearHorizontal),
  39585. textBoxPos (TextBoxLeft),
  39586. textBoxWidth (80),
  39587. textBoxHeight (20),
  39588. incDecButtonMode (incDecButtonsNotDraggable),
  39589. editableText (true),
  39590. doubleClickToValue (false),
  39591. isVelocityBased (false),
  39592. userKeyOverridesVelocity (true),
  39593. rotaryStop (true),
  39594. incDecButtonsSideBySide (false),
  39595. sendChangeOnlyOnRelease (false),
  39596. popupDisplayEnabled (false),
  39597. menuEnabled (false),
  39598. menuShown (false),
  39599. scrollWheelEnabled (true),
  39600. snapsToMousePos (true),
  39601. popupDisplay (0),
  39602. parentForPopupDisplay (0)
  39603. {
  39604. setWantsKeyboardFocus (false);
  39605. setRepaintsOnMouseActivity (true);
  39606. lookAndFeelChanged();
  39607. updateText();
  39608. currentValue.addListener (this);
  39609. valueMin.addListener (this);
  39610. valueMax.addListener (this);
  39611. }
  39612. Slider::~Slider()
  39613. {
  39614. currentValue.removeListener (this);
  39615. valueMin.removeListener (this);
  39616. valueMax.removeListener (this);
  39617. popupDisplay = 0;
  39618. }
  39619. void Slider::handleAsyncUpdate()
  39620. {
  39621. cancelPendingUpdate();
  39622. Component::BailOutChecker checker (this);
  39623. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39624. }
  39625. void Slider::sendDragStart()
  39626. {
  39627. startedDragging();
  39628. Component::BailOutChecker checker (this);
  39629. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39630. }
  39631. void Slider::sendDragEnd()
  39632. {
  39633. stoppedDragging();
  39634. sliderBeingDragged = -1;
  39635. Component::BailOutChecker checker (this);
  39636. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39637. }
  39638. void Slider::addListener (SliderListener* const listener)
  39639. {
  39640. listeners.add (listener);
  39641. }
  39642. void Slider::removeListener (SliderListener* const listener)
  39643. {
  39644. listeners.remove (listener);
  39645. }
  39646. void Slider::setSliderStyle (const SliderStyle newStyle)
  39647. {
  39648. if (style != newStyle)
  39649. {
  39650. style = newStyle;
  39651. repaint();
  39652. lookAndFeelChanged();
  39653. }
  39654. }
  39655. void Slider::setRotaryParameters (const float startAngleRadians,
  39656. const float endAngleRadians,
  39657. const bool stopAtEnd)
  39658. {
  39659. // make sure the values are sensible..
  39660. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  39661. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  39662. jassert (rotaryStart < rotaryEnd);
  39663. rotaryStart = startAngleRadians;
  39664. rotaryEnd = endAngleRadians;
  39665. rotaryStop = stopAtEnd;
  39666. }
  39667. void Slider::setVelocityBasedMode (const bool velBased)
  39668. {
  39669. isVelocityBased = velBased;
  39670. }
  39671. void Slider::setVelocityModeParameters (const double sensitivity,
  39672. const int threshold,
  39673. const double offset,
  39674. const bool userCanPressKeyToSwapMode)
  39675. {
  39676. jassert (threshold >= 0);
  39677. jassert (sensitivity > 0);
  39678. jassert (offset >= 0);
  39679. velocityModeSensitivity = sensitivity;
  39680. velocityModeOffset = offset;
  39681. velocityModeThreshold = threshold;
  39682. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  39683. }
  39684. void Slider::setSkewFactor (const double factor)
  39685. {
  39686. skewFactor = factor;
  39687. }
  39688. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  39689. {
  39690. if (maximum > minimum)
  39691. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  39692. / (maximum - minimum));
  39693. }
  39694. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  39695. {
  39696. jassert (distanceForFullScaleDrag > 0);
  39697. pixelsForFullDragExtent = distanceForFullScaleDrag;
  39698. }
  39699. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  39700. {
  39701. if (incDecButtonMode != mode)
  39702. {
  39703. incDecButtonMode = mode;
  39704. lookAndFeelChanged();
  39705. }
  39706. }
  39707. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  39708. const bool isReadOnly,
  39709. const int textEntryBoxWidth,
  39710. const int textEntryBoxHeight)
  39711. {
  39712. if (textBoxPos != newPosition
  39713. || editableText != (! isReadOnly)
  39714. || textBoxWidth != textEntryBoxWidth
  39715. || textBoxHeight != textEntryBoxHeight)
  39716. {
  39717. textBoxPos = newPosition;
  39718. editableText = ! isReadOnly;
  39719. textBoxWidth = textEntryBoxWidth;
  39720. textBoxHeight = textEntryBoxHeight;
  39721. repaint();
  39722. lookAndFeelChanged();
  39723. }
  39724. }
  39725. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  39726. {
  39727. editableText = shouldBeEditable;
  39728. if (valueBox != 0)
  39729. valueBox->setEditable (shouldBeEditable && isEnabled());
  39730. }
  39731. void Slider::showTextBox()
  39732. {
  39733. jassert (editableText); // this should probably be avoided in read-only sliders.
  39734. if (valueBox != 0)
  39735. valueBox->showEditor();
  39736. }
  39737. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  39738. {
  39739. if (valueBox != 0)
  39740. {
  39741. valueBox->hideEditor (discardCurrentEditorContents);
  39742. if (discardCurrentEditorContents)
  39743. updateText();
  39744. }
  39745. }
  39746. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  39747. {
  39748. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  39749. }
  39750. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  39751. {
  39752. snapsToMousePos = shouldSnapToMouse;
  39753. }
  39754. void Slider::setPopupDisplayEnabled (const bool enabled,
  39755. Component* const parentComponentToUse)
  39756. {
  39757. popupDisplayEnabled = enabled;
  39758. parentForPopupDisplay = parentComponentToUse;
  39759. }
  39760. void Slider::colourChanged()
  39761. {
  39762. lookAndFeelChanged();
  39763. }
  39764. void Slider::lookAndFeelChanged()
  39765. {
  39766. LookAndFeel& lf = getLookAndFeel();
  39767. if (textBoxPos != NoTextBox)
  39768. {
  39769. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  39770. : getTextFromValue (currentValue.getValue()));
  39771. valueBox = 0;
  39772. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  39773. valueBox->setWantsKeyboardFocus (false);
  39774. valueBox->setText (previousTextBoxContent, false);
  39775. valueBox->setEditable (editableText && isEnabled());
  39776. valueBox->addListener (this);
  39777. if (style == LinearBar)
  39778. valueBox->addMouseListener (this, false);
  39779. valueBox->setTooltip (getTooltip());
  39780. }
  39781. else
  39782. {
  39783. valueBox = 0;
  39784. }
  39785. if (style == IncDecButtons)
  39786. {
  39787. addAndMakeVisible (incButton = lf.createSliderButton (true));
  39788. incButton->addListener (this);
  39789. addAndMakeVisible (decButton = lf.createSliderButton (false));
  39790. decButton->addListener (this);
  39791. if (incDecButtonMode != incDecButtonsNotDraggable)
  39792. {
  39793. incButton->addMouseListener (this, false);
  39794. decButton->addMouseListener (this, false);
  39795. }
  39796. else
  39797. {
  39798. incButton->setRepeatSpeed (300, 100, 20);
  39799. incButton->addMouseListener (decButton, false);
  39800. decButton->setRepeatSpeed (300, 100, 20);
  39801. decButton->addMouseListener (incButton, false);
  39802. }
  39803. incButton->setTooltip (getTooltip());
  39804. decButton->setTooltip (getTooltip());
  39805. }
  39806. else
  39807. {
  39808. incButton = 0;
  39809. decButton = 0;
  39810. }
  39811. setComponentEffect (lf.getSliderEffect());
  39812. resized();
  39813. repaint();
  39814. }
  39815. void Slider::setRange (const double newMin,
  39816. const double newMax,
  39817. const double newInt)
  39818. {
  39819. if (minimum != newMin
  39820. || maximum != newMax
  39821. || interval != newInt)
  39822. {
  39823. minimum = newMin;
  39824. maximum = newMax;
  39825. interval = newInt;
  39826. // figure out the number of DPs needed to display all values at this
  39827. // interval setting.
  39828. numDecimalPlaces = 7;
  39829. if (newInt != 0)
  39830. {
  39831. int v = abs ((int) (newInt * 10000000));
  39832. while ((v % 10) == 0)
  39833. {
  39834. --numDecimalPlaces;
  39835. v /= 10;
  39836. }
  39837. }
  39838. // keep the current values inside the new range..
  39839. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39840. {
  39841. setValue (getValue(), false, false);
  39842. }
  39843. else
  39844. {
  39845. setMinValue (getMinValue(), false, false);
  39846. setMaxValue (getMaxValue(), false, false);
  39847. }
  39848. updateText();
  39849. }
  39850. }
  39851. void Slider::triggerChangeMessage (const bool synchronous)
  39852. {
  39853. if (synchronous)
  39854. handleAsyncUpdate();
  39855. else
  39856. triggerAsyncUpdate();
  39857. valueChanged();
  39858. }
  39859. void Slider::valueChanged (Value& value)
  39860. {
  39861. if (value.refersToSameSourceAs (currentValue))
  39862. {
  39863. if (style != TwoValueHorizontal && style != TwoValueVertical)
  39864. setValue (currentValue.getValue(), false, false);
  39865. }
  39866. else if (value.refersToSameSourceAs (valueMin))
  39867. setMinValue (valueMin.getValue(), false, false, true);
  39868. else if (value.refersToSameSourceAs (valueMax))
  39869. setMaxValue (valueMax.getValue(), false, false, true);
  39870. }
  39871. double Slider::getValue() const
  39872. {
  39873. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  39874. // methods to get the two values.
  39875. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39876. return currentValue.getValue();
  39877. }
  39878. void Slider::setValue (double newValue,
  39879. const bool sendUpdateMessage,
  39880. const bool sendMessageSynchronously)
  39881. {
  39882. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  39883. // methods to set the two values.
  39884. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  39885. newValue = constrainedValue (newValue);
  39886. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  39887. {
  39888. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  39889. newValue = jlimit ((double) valueMin.getValue(),
  39890. (double) valueMax.getValue(),
  39891. newValue);
  39892. }
  39893. if (newValue != lastCurrentValue)
  39894. {
  39895. if (valueBox != 0)
  39896. valueBox->hideEditor (true);
  39897. lastCurrentValue = newValue;
  39898. currentValue = newValue;
  39899. updateText();
  39900. repaint();
  39901. if (popupDisplay != 0)
  39902. {
  39903. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39904. ->updatePosition (getTextFromValue (newValue));
  39905. popupDisplay->repaint();
  39906. }
  39907. if (sendUpdateMessage)
  39908. triggerChangeMessage (sendMessageSynchronously);
  39909. }
  39910. }
  39911. double Slider::getMinValue() const
  39912. {
  39913. // The minimum value only applies to sliders that are in two- or three-value mode.
  39914. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39915. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39916. return valueMin.getValue();
  39917. }
  39918. double Slider::getMaxValue() const
  39919. {
  39920. // The maximum value only applies to sliders that are in two- or three-value mode.
  39921. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39922. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39923. return valueMax.getValue();
  39924. }
  39925. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39926. {
  39927. // The minimum value only applies to sliders that are in two- or three-value mode.
  39928. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39929. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39930. newValue = constrainedValue (newValue);
  39931. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39932. {
  39933. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  39934. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39935. newValue = jmin ((double) valueMax.getValue(), newValue);
  39936. }
  39937. else
  39938. {
  39939. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  39940. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39941. newValue = jmin (lastCurrentValue, newValue);
  39942. }
  39943. if (lastValueMin != newValue)
  39944. {
  39945. lastValueMin = newValue;
  39946. valueMin = newValue;
  39947. repaint();
  39948. if (popupDisplay != 0)
  39949. {
  39950. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39951. ->updatePosition (getTextFromValue (newValue));
  39952. popupDisplay->repaint();
  39953. }
  39954. if (sendUpdateMessage)
  39955. triggerChangeMessage (sendMessageSynchronously);
  39956. }
  39957. }
  39958. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  39959. {
  39960. // The maximum value only applies to sliders that are in two- or three-value mode.
  39961. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  39962. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  39963. newValue = constrainedValue (newValue);
  39964. if (style == TwoValueHorizontal || style == TwoValueVertical)
  39965. {
  39966. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  39967. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39968. newValue = jmax ((double) valueMin.getValue(), newValue);
  39969. }
  39970. else
  39971. {
  39972. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  39973. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  39974. newValue = jmax (lastCurrentValue, newValue);
  39975. }
  39976. if (lastValueMax != newValue)
  39977. {
  39978. lastValueMax = newValue;
  39979. valueMax = newValue;
  39980. repaint();
  39981. if (popupDisplay != 0)
  39982. {
  39983. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  39984. ->updatePosition (getTextFromValue (valueMax.getValue()));
  39985. popupDisplay->repaint();
  39986. }
  39987. if (sendUpdateMessage)
  39988. triggerChangeMessage (sendMessageSynchronously);
  39989. }
  39990. }
  39991. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  39992. const double valueToSetOnDoubleClick)
  39993. {
  39994. doubleClickToValue = isDoubleClickEnabled;
  39995. doubleClickReturnValue = valueToSetOnDoubleClick;
  39996. }
  39997. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  39998. {
  39999. isEnabled_ = doubleClickToValue;
  40000. return doubleClickReturnValue;
  40001. }
  40002. void Slider::updateText()
  40003. {
  40004. if (valueBox != 0)
  40005. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40006. }
  40007. void Slider::setTextValueSuffix (const String& suffix)
  40008. {
  40009. if (textSuffix != suffix)
  40010. {
  40011. textSuffix = suffix;
  40012. updateText();
  40013. }
  40014. }
  40015. const String Slider::getTextValueSuffix() const
  40016. {
  40017. return textSuffix;
  40018. }
  40019. const String Slider::getTextFromValue (double v)
  40020. {
  40021. if (getNumDecimalPlacesToDisplay() > 0)
  40022. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40023. else
  40024. return String (roundToInt (v)) + getTextValueSuffix();
  40025. }
  40026. double Slider::getValueFromText (const String& text)
  40027. {
  40028. String t (text.trimStart());
  40029. if (t.endsWith (textSuffix))
  40030. t = t.substring (0, t.length() - textSuffix.length());
  40031. while (t.startsWithChar ('+'))
  40032. t = t.substring (1).trimStart();
  40033. return t.initialSectionContainingOnly ("0123456789.,-")
  40034. .getDoubleValue();
  40035. }
  40036. double Slider::proportionOfLengthToValue (double proportion)
  40037. {
  40038. if (skewFactor != 1.0 && proportion > 0.0)
  40039. proportion = exp (log (proportion) / skewFactor);
  40040. return minimum + (maximum - minimum) * proportion;
  40041. }
  40042. double Slider::valueToProportionOfLength (double value)
  40043. {
  40044. const double n = (value - minimum) / (maximum - minimum);
  40045. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40046. }
  40047. double Slider::snapValue (double attemptedValue, const bool)
  40048. {
  40049. return attemptedValue;
  40050. }
  40051. void Slider::startedDragging()
  40052. {
  40053. }
  40054. void Slider::stoppedDragging()
  40055. {
  40056. }
  40057. void Slider::valueChanged()
  40058. {
  40059. }
  40060. void Slider::enablementChanged()
  40061. {
  40062. repaint();
  40063. }
  40064. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40065. {
  40066. menuEnabled = menuEnabled_;
  40067. }
  40068. void Slider::setScrollWheelEnabled (const bool enabled)
  40069. {
  40070. scrollWheelEnabled = enabled;
  40071. }
  40072. void Slider::labelTextChanged (Label* label)
  40073. {
  40074. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40075. if (newValue != (double) currentValue.getValue())
  40076. {
  40077. sendDragStart();
  40078. setValue (newValue, true, true);
  40079. sendDragEnd();
  40080. }
  40081. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40082. }
  40083. void Slider::buttonClicked (Button* button)
  40084. {
  40085. if (style == IncDecButtons)
  40086. {
  40087. sendDragStart();
  40088. if (button == incButton)
  40089. setValue (snapValue (getValue() + interval, false), true, true);
  40090. else if (button == decButton)
  40091. setValue (snapValue (getValue() - interval, false), true, true);
  40092. sendDragEnd();
  40093. }
  40094. }
  40095. double Slider::constrainedValue (double value) const
  40096. {
  40097. if (interval > 0)
  40098. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40099. if (value <= minimum || maximum <= minimum)
  40100. value = minimum;
  40101. else if (value >= maximum)
  40102. value = maximum;
  40103. return value;
  40104. }
  40105. float Slider::getLinearSliderPos (const double value)
  40106. {
  40107. double sliderPosProportional;
  40108. if (maximum > minimum)
  40109. {
  40110. if (value < minimum)
  40111. {
  40112. sliderPosProportional = 0.0;
  40113. }
  40114. else if (value > maximum)
  40115. {
  40116. sliderPosProportional = 1.0;
  40117. }
  40118. else
  40119. {
  40120. sliderPosProportional = valueToProportionOfLength (value);
  40121. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40122. }
  40123. }
  40124. else
  40125. {
  40126. sliderPosProportional = 0.5;
  40127. }
  40128. if (isVertical() || style == IncDecButtons)
  40129. sliderPosProportional = 1.0 - sliderPosProportional;
  40130. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40131. }
  40132. bool Slider::isHorizontal() const
  40133. {
  40134. return style == LinearHorizontal
  40135. || style == LinearBar
  40136. || style == TwoValueHorizontal
  40137. || style == ThreeValueHorizontal;
  40138. }
  40139. bool Slider::isVertical() const
  40140. {
  40141. return style == LinearVertical
  40142. || style == TwoValueVertical
  40143. || style == ThreeValueVertical;
  40144. }
  40145. bool Slider::incDecDragDirectionIsHorizontal() const
  40146. {
  40147. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40148. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40149. }
  40150. float Slider::getPositionOfValue (const double value)
  40151. {
  40152. if (isHorizontal() || isVertical())
  40153. {
  40154. return getLinearSliderPos (value);
  40155. }
  40156. else
  40157. {
  40158. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40159. return 0.0f;
  40160. }
  40161. }
  40162. void Slider::paint (Graphics& g)
  40163. {
  40164. if (style != IncDecButtons)
  40165. {
  40166. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40167. {
  40168. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40169. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40170. getLookAndFeel().drawRotarySlider (g,
  40171. sliderRect.getX(),
  40172. sliderRect.getY(),
  40173. sliderRect.getWidth(),
  40174. sliderRect.getHeight(),
  40175. sliderPos,
  40176. rotaryStart, rotaryEnd,
  40177. *this);
  40178. }
  40179. else
  40180. {
  40181. getLookAndFeel().drawLinearSlider (g,
  40182. sliderRect.getX(),
  40183. sliderRect.getY(),
  40184. sliderRect.getWidth(),
  40185. sliderRect.getHeight(),
  40186. getLinearSliderPos (lastCurrentValue),
  40187. getLinearSliderPos (lastValueMin),
  40188. getLinearSliderPos (lastValueMax),
  40189. style,
  40190. *this);
  40191. }
  40192. if (style == LinearBar && valueBox == 0)
  40193. {
  40194. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40195. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40196. }
  40197. }
  40198. }
  40199. void Slider::resized()
  40200. {
  40201. int minXSpace = 0;
  40202. int minYSpace = 0;
  40203. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40204. minXSpace = 30;
  40205. else
  40206. minYSpace = 15;
  40207. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40208. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40209. if (style == LinearBar)
  40210. {
  40211. if (valueBox != 0)
  40212. valueBox->setBounds (getLocalBounds());
  40213. }
  40214. else
  40215. {
  40216. if (textBoxPos == NoTextBox)
  40217. {
  40218. sliderRect = getLocalBounds();
  40219. }
  40220. else if (textBoxPos == TextBoxLeft)
  40221. {
  40222. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40223. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40224. }
  40225. else if (textBoxPos == TextBoxRight)
  40226. {
  40227. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40228. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40229. }
  40230. else if (textBoxPos == TextBoxAbove)
  40231. {
  40232. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40233. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40234. }
  40235. else if (textBoxPos == TextBoxBelow)
  40236. {
  40237. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40238. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40239. }
  40240. }
  40241. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40242. if (style == LinearBar)
  40243. {
  40244. const int barIndent = 1;
  40245. sliderRegionStart = barIndent;
  40246. sliderRegionSize = getWidth() - barIndent * 2;
  40247. sliderRect.setBounds (sliderRegionStart, barIndent,
  40248. sliderRegionSize, getHeight() - barIndent * 2);
  40249. }
  40250. else if (isHorizontal())
  40251. {
  40252. sliderRegionStart = sliderRect.getX() + indent;
  40253. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40254. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40255. sliderRegionSize, sliderRect.getHeight());
  40256. }
  40257. else if (isVertical())
  40258. {
  40259. sliderRegionStart = sliderRect.getY() + indent;
  40260. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40261. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40262. sliderRect.getWidth(), sliderRegionSize);
  40263. }
  40264. else
  40265. {
  40266. sliderRegionStart = 0;
  40267. sliderRegionSize = 100;
  40268. }
  40269. if (style == IncDecButtons)
  40270. {
  40271. Rectangle<int> buttonRect (sliderRect);
  40272. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40273. buttonRect.expand (-2, 0);
  40274. else
  40275. buttonRect.expand (0, -2);
  40276. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40277. if (incDecButtonsSideBySide)
  40278. {
  40279. decButton->setBounds (buttonRect.getX(),
  40280. buttonRect.getY(),
  40281. buttonRect.getWidth() / 2,
  40282. buttonRect.getHeight());
  40283. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40284. incButton->setBounds (buttonRect.getCentreX(),
  40285. buttonRect.getY(),
  40286. buttonRect.getWidth() / 2,
  40287. buttonRect.getHeight());
  40288. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40289. }
  40290. else
  40291. {
  40292. incButton->setBounds (buttonRect.getX(),
  40293. buttonRect.getY(),
  40294. buttonRect.getWidth(),
  40295. buttonRect.getHeight() / 2);
  40296. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40297. decButton->setBounds (buttonRect.getX(),
  40298. buttonRect.getCentreY(),
  40299. buttonRect.getWidth(),
  40300. buttonRect.getHeight() / 2);
  40301. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40302. }
  40303. }
  40304. }
  40305. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40306. {
  40307. repaint();
  40308. }
  40309. void Slider::mouseDown (const MouseEvent& e)
  40310. {
  40311. mouseWasHidden = false;
  40312. incDecDragged = false;
  40313. mouseXWhenLastDragged = e.x;
  40314. mouseYWhenLastDragged = e.y;
  40315. mouseDragStartX = e.getMouseDownX();
  40316. mouseDragStartY = e.getMouseDownY();
  40317. if (isEnabled())
  40318. {
  40319. if (e.mods.isPopupMenu() && menuEnabled)
  40320. {
  40321. menuShown = true;
  40322. PopupMenu m;
  40323. m.setLookAndFeel (&getLookAndFeel());
  40324. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40325. m.addSeparator();
  40326. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40327. {
  40328. PopupMenu rotaryMenu;
  40329. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40330. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40331. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40332. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40333. }
  40334. const int r = m.show();
  40335. if (r == 1)
  40336. {
  40337. setVelocityBasedMode (! isVelocityBased);
  40338. }
  40339. else if (r == 2)
  40340. {
  40341. setSliderStyle (Rotary);
  40342. }
  40343. else if (r == 3)
  40344. {
  40345. setSliderStyle (RotaryHorizontalDrag);
  40346. }
  40347. else if (r == 4)
  40348. {
  40349. setSliderStyle (RotaryVerticalDrag);
  40350. }
  40351. }
  40352. else if (maximum > minimum)
  40353. {
  40354. menuShown = false;
  40355. if (valueBox != 0)
  40356. valueBox->hideEditor (true);
  40357. sliderBeingDragged = 0;
  40358. if (style == TwoValueHorizontal
  40359. || style == TwoValueVertical
  40360. || style == ThreeValueHorizontal
  40361. || style == ThreeValueVertical)
  40362. {
  40363. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40364. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40365. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40366. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40367. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40368. {
  40369. if (maxPosDistance <= minPosDistance)
  40370. sliderBeingDragged = 2;
  40371. else
  40372. sliderBeingDragged = 1;
  40373. }
  40374. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40375. {
  40376. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40377. sliderBeingDragged = 1;
  40378. else if (normalPosDistance >= maxPosDistance)
  40379. sliderBeingDragged = 2;
  40380. }
  40381. }
  40382. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40383. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40384. * valueToProportionOfLength (currentValue.getValue());
  40385. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40386. : ((sliderBeingDragged == 1) ? valueMin
  40387. : currentValue)).getValue();
  40388. valueOnMouseDown = valueWhenLastDragged;
  40389. if (popupDisplayEnabled)
  40390. {
  40391. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40392. popupDisplay = popup;
  40393. if (parentForPopupDisplay != 0)
  40394. {
  40395. parentForPopupDisplay->addChildComponent (popup);
  40396. }
  40397. else
  40398. {
  40399. popup->addToDesktop (0);
  40400. }
  40401. popup->setVisible (true);
  40402. }
  40403. sendDragStart();
  40404. mouseDrag (e);
  40405. }
  40406. }
  40407. }
  40408. void Slider::mouseUp (const MouseEvent&)
  40409. {
  40410. if (isEnabled()
  40411. && (! menuShown)
  40412. && (maximum > minimum)
  40413. && (style != IncDecButtons || incDecDragged))
  40414. {
  40415. restoreMouseIfHidden();
  40416. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40417. triggerChangeMessage (false);
  40418. sendDragEnd();
  40419. popupDisplay = 0;
  40420. if (style == IncDecButtons)
  40421. {
  40422. incButton->setState (Button::buttonNormal);
  40423. decButton->setState (Button::buttonNormal);
  40424. }
  40425. }
  40426. }
  40427. void Slider::restoreMouseIfHidden()
  40428. {
  40429. if (mouseWasHidden)
  40430. {
  40431. mouseWasHidden = false;
  40432. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40433. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40434. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40435. : ((sliderBeingDragged == 1) ? getMinValue()
  40436. : (double) currentValue.getValue());
  40437. Point<int> mousePos;
  40438. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40439. {
  40440. mousePos = Desktop::getLastMouseDownPosition();
  40441. if (style == RotaryHorizontalDrag)
  40442. {
  40443. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40444. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40445. }
  40446. else
  40447. {
  40448. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40449. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40450. }
  40451. }
  40452. else
  40453. {
  40454. const int pixelPos = (int) getLinearSliderPos (pos);
  40455. mousePos = localPointToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40456. isVertical() ? pixelPos : (getHeight() / 2)));
  40457. }
  40458. Desktop::setMousePosition (mousePos);
  40459. }
  40460. }
  40461. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40462. {
  40463. if (isEnabled()
  40464. && style != IncDecButtons
  40465. && style != Rotary
  40466. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40467. {
  40468. restoreMouseIfHidden();
  40469. }
  40470. }
  40471. namespace SliderHelpers
  40472. {
  40473. double smallestAngleBetween (double a1, double a2) throw()
  40474. {
  40475. return jmin (std::abs (a1 - a2),
  40476. std::abs (a1 + double_Pi * 2.0 - a2),
  40477. std::abs (a2 + double_Pi * 2.0 - a1));
  40478. }
  40479. }
  40480. void Slider::mouseDrag (const MouseEvent& e)
  40481. {
  40482. if (isEnabled()
  40483. && (! menuShown)
  40484. && (maximum > minimum))
  40485. {
  40486. if (style == Rotary)
  40487. {
  40488. int dx = e.x - sliderRect.getCentreX();
  40489. int dy = e.y - sliderRect.getCentreY();
  40490. if (dx * dx + dy * dy > 25)
  40491. {
  40492. double angle = std::atan2 ((double) dx, (double) -dy);
  40493. while (angle < 0.0)
  40494. angle += double_Pi * 2.0;
  40495. if (rotaryStop && ! e.mouseWasClicked())
  40496. {
  40497. if (std::abs (angle - lastAngle) > double_Pi)
  40498. {
  40499. if (angle >= lastAngle)
  40500. angle -= double_Pi * 2.0;
  40501. else
  40502. angle += double_Pi * 2.0;
  40503. }
  40504. if (angle >= lastAngle)
  40505. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40506. else
  40507. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40508. }
  40509. else
  40510. {
  40511. while (angle < rotaryStart)
  40512. angle += double_Pi * 2.0;
  40513. if (angle > rotaryEnd)
  40514. {
  40515. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40516. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40517. angle = rotaryStart;
  40518. else
  40519. angle = rotaryEnd;
  40520. }
  40521. }
  40522. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40523. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40524. lastAngle = angle;
  40525. }
  40526. }
  40527. else
  40528. {
  40529. if (style == LinearBar && e.mouseWasClicked()
  40530. && valueBox != 0 && valueBox->isEditable())
  40531. return;
  40532. if (style == IncDecButtons && ! incDecDragged)
  40533. {
  40534. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40535. return;
  40536. incDecDragged = true;
  40537. mouseDragStartX = e.x;
  40538. mouseDragStartY = e.y;
  40539. }
  40540. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40541. : false))
  40542. || ((maximum - minimum) / sliderRegionSize < interval))
  40543. {
  40544. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40545. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40546. if (style == RotaryHorizontalDrag
  40547. || style == RotaryVerticalDrag
  40548. || style == IncDecButtons
  40549. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40550. && ! snapsToMousePos))
  40551. {
  40552. const int mouseDiff = (style == RotaryHorizontalDrag
  40553. || style == LinearHorizontal
  40554. || style == LinearBar
  40555. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40556. ? e.x - mouseDragStartX
  40557. : mouseDragStartY - e.y;
  40558. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40559. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40560. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40561. if (style == IncDecButtons)
  40562. {
  40563. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40564. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40565. }
  40566. }
  40567. else
  40568. {
  40569. if (isVertical())
  40570. scaledMousePos = 1.0 - scaledMousePos;
  40571. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40572. }
  40573. }
  40574. else
  40575. {
  40576. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40577. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40578. ? e.x - mouseXWhenLastDragged
  40579. : e.y - mouseYWhenLastDragged;
  40580. const double maxSpeed = jmax (200, sliderRegionSize);
  40581. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40582. if (speed != 0)
  40583. {
  40584. speed = 0.2 * velocityModeSensitivity
  40585. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40586. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40587. / maxSpeed))));
  40588. if (mouseDiff < 0)
  40589. speed = -speed;
  40590. if (isVertical() || style == RotaryVerticalDrag
  40591. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40592. speed = -speed;
  40593. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40594. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40595. e.source.enableUnboundedMouseMovement (true, false);
  40596. mouseWasHidden = true;
  40597. }
  40598. }
  40599. }
  40600. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40601. if (sliderBeingDragged == 0)
  40602. {
  40603. setValue (snapValue (valueWhenLastDragged, true),
  40604. ! sendChangeOnlyOnRelease, true);
  40605. }
  40606. else if (sliderBeingDragged == 1)
  40607. {
  40608. setMinValue (snapValue (valueWhenLastDragged, true),
  40609. ! sendChangeOnlyOnRelease, false, true);
  40610. if (e.mods.isShiftDown())
  40611. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40612. else
  40613. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40614. }
  40615. else
  40616. {
  40617. jassert (sliderBeingDragged == 2);
  40618. setMaxValue (snapValue (valueWhenLastDragged, true),
  40619. ! sendChangeOnlyOnRelease, false, true);
  40620. if (e.mods.isShiftDown())
  40621. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40622. else
  40623. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40624. }
  40625. mouseXWhenLastDragged = e.x;
  40626. mouseYWhenLastDragged = e.y;
  40627. }
  40628. }
  40629. void Slider::mouseDoubleClick (const MouseEvent&)
  40630. {
  40631. if (doubleClickToValue
  40632. && isEnabled()
  40633. && style != IncDecButtons
  40634. && minimum <= doubleClickReturnValue
  40635. && maximum >= doubleClickReturnValue)
  40636. {
  40637. sendDragStart();
  40638. setValue (doubleClickReturnValue, true, true);
  40639. sendDragEnd();
  40640. }
  40641. }
  40642. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40643. {
  40644. if (scrollWheelEnabled && isEnabled()
  40645. && style != TwoValueHorizontal
  40646. && style != TwoValueVertical)
  40647. {
  40648. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40649. {
  40650. if (valueBox != 0)
  40651. valueBox->hideEditor (false);
  40652. const double value = (double) currentValue.getValue();
  40653. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40654. const double currentPos = valueToProportionOfLength (value);
  40655. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  40656. double delta = (newValue != value)
  40657. ? jmax (std::abs (newValue - value), interval) : 0;
  40658. if (value > newValue)
  40659. delta = -delta;
  40660. sendDragStart();
  40661. setValue (snapValue (value + delta, false), true, true);
  40662. sendDragEnd();
  40663. }
  40664. }
  40665. else
  40666. {
  40667. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40668. }
  40669. }
  40670. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  40671. {
  40672. }
  40673. void SliderListener::sliderDragEnded (Slider*)
  40674. {
  40675. }
  40676. END_JUCE_NAMESPACE
  40677. /*** End of inlined file: juce_Slider.cpp ***/
  40678. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  40679. BEGIN_JUCE_NAMESPACE
  40680. class DragOverlayComp : public Component
  40681. {
  40682. public:
  40683. DragOverlayComp (const Image& image_)
  40684. : image (image_)
  40685. {
  40686. image.duplicateIfShared();
  40687. image.multiplyAllAlphas (0.8f);
  40688. setAlwaysOnTop (true);
  40689. }
  40690. void paint (Graphics& g)
  40691. {
  40692. g.drawImageAt (image, 0, 0);
  40693. }
  40694. private:
  40695. Image image;
  40696. JUCE_DECLARE_NON_COPYABLE (DragOverlayComp);
  40697. };
  40698. TableHeaderComponent::TableHeaderComponent()
  40699. : columnsChanged (false),
  40700. columnsResized (false),
  40701. sortChanged (false),
  40702. menuActive (true),
  40703. stretchToFit (false),
  40704. columnIdBeingResized (0),
  40705. columnIdBeingDragged (0),
  40706. columnIdUnderMouse (0),
  40707. lastDeliberateWidth (0)
  40708. {
  40709. }
  40710. TableHeaderComponent::~TableHeaderComponent()
  40711. {
  40712. dragOverlayComp = 0;
  40713. }
  40714. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  40715. {
  40716. menuActive = hasMenu;
  40717. }
  40718. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  40719. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  40720. {
  40721. if (onlyCountVisibleColumns)
  40722. {
  40723. int num = 0;
  40724. for (int i = columns.size(); --i >= 0;)
  40725. if (columns.getUnchecked(i)->isVisible())
  40726. ++num;
  40727. return num;
  40728. }
  40729. else
  40730. {
  40731. return columns.size();
  40732. }
  40733. }
  40734. const String TableHeaderComponent::getColumnName (const int columnId) const
  40735. {
  40736. const ColumnInfo* const ci = getInfoForId (columnId);
  40737. return ci != 0 ? ci->name : String::empty;
  40738. }
  40739. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  40740. {
  40741. ColumnInfo* const ci = getInfoForId (columnId);
  40742. if (ci != 0 && ci->name != newName)
  40743. {
  40744. ci->name = newName;
  40745. sendColumnsChanged();
  40746. }
  40747. }
  40748. void TableHeaderComponent::addColumn (const String& columnName,
  40749. const int columnId,
  40750. const int width,
  40751. const int minimumWidth,
  40752. const int maximumWidth,
  40753. const int propertyFlags,
  40754. const int insertIndex)
  40755. {
  40756. // can't have a duplicate or null ID!
  40757. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  40758. jassert (width > 0);
  40759. ColumnInfo* const ci = new ColumnInfo();
  40760. ci->name = columnName;
  40761. ci->id = columnId;
  40762. ci->width = width;
  40763. ci->lastDeliberateWidth = width;
  40764. ci->minimumWidth = minimumWidth;
  40765. ci->maximumWidth = maximumWidth;
  40766. if (ci->maximumWidth < 0)
  40767. ci->maximumWidth = std::numeric_limits<int>::max();
  40768. jassert (ci->maximumWidth >= ci->minimumWidth);
  40769. ci->propertyFlags = propertyFlags;
  40770. columns.insert (insertIndex, ci);
  40771. sendColumnsChanged();
  40772. }
  40773. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  40774. {
  40775. const int index = getIndexOfColumnId (columnIdToRemove, false);
  40776. if (index >= 0)
  40777. {
  40778. columns.remove (index);
  40779. sortChanged = true;
  40780. sendColumnsChanged();
  40781. }
  40782. }
  40783. void TableHeaderComponent::removeAllColumns()
  40784. {
  40785. if (columns.size() > 0)
  40786. {
  40787. columns.clear();
  40788. sendColumnsChanged();
  40789. }
  40790. }
  40791. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  40792. {
  40793. const int currentIndex = getIndexOfColumnId (columnId, false);
  40794. newIndex = visibleIndexToTotalIndex (newIndex);
  40795. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  40796. {
  40797. columns.move (currentIndex, newIndex);
  40798. sendColumnsChanged();
  40799. }
  40800. }
  40801. int TableHeaderComponent::getColumnWidth (const int columnId) const
  40802. {
  40803. const ColumnInfo* const ci = getInfoForId (columnId);
  40804. return ci != 0 ? ci->width : 0;
  40805. }
  40806. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  40807. {
  40808. ColumnInfo* const ci = getInfoForId (columnId);
  40809. if (ci != 0 && ci->width != newWidth)
  40810. {
  40811. const int numColumns = getNumColumns (true);
  40812. ci->lastDeliberateWidth = ci->width
  40813. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  40814. if (stretchToFit)
  40815. {
  40816. const int index = getIndexOfColumnId (columnId, true) + 1;
  40817. if (isPositiveAndBelow (index, numColumns))
  40818. {
  40819. const int x = getColumnPosition (index).getX();
  40820. if (lastDeliberateWidth == 0)
  40821. lastDeliberateWidth = getTotalWidth();
  40822. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  40823. }
  40824. }
  40825. repaint();
  40826. columnsResized = true;
  40827. triggerAsyncUpdate();
  40828. }
  40829. }
  40830. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  40831. {
  40832. int n = 0;
  40833. for (int i = 0; i < columns.size(); ++i)
  40834. {
  40835. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  40836. {
  40837. if (columns.getUnchecked(i)->id == columnId)
  40838. return n;
  40839. ++n;
  40840. }
  40841. }
  40842. return -1;
  40843. }
  40844. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  40845. {
  40846. if (onlyCountVisibleColumns)
  40847. index = visibleIndexToTotalIndex (index);
  40848. const ColumnInfo* const ci = columns [index];
  40849. return (ci != 0) ? ci->id : 0;
  40850. }
  40851. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  40852. {
  40853. int x = 0, width = 0, n = 0;
  40854. for (int i = 0; i < columns.size(); ++i)
  40855. {
  40856. x += width;
  40857. if (columns.getUnchecked(i)->isVisible())
  40858. {
  40859. width = columns.getUnchecked(i)->width;
  40860. if (n++ == index)
  40861. break;
  40862. }
  40863. else
  40864. {
  40865. width = 0;
  40866. }
  40867. }
  40868. return Rectangle<int> (x, 0, width, getHeight());
  40869. }
  40870. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  40871. {
  40872. if (xToFind >= 0)
  40873. {
  40874. int x = 0;
  40875. for (int i = 0; i < columns.size(); ++i)
  40876. {
  40877. const ColumnInfo* const ci = columns.getUnchecked(i);
  40878. if (ci->isVisible())
  40879. {
  40880. x += ci->width;
  40881. if (xToFind < x)
  40882. return ci->id;
  40883. }
  40884. }
  40885. }
  40886. return 0;
  40887. }
  40888. int TableHeaderComponent::getTotalWidth() const
  40889. {
  40890. int w = 0;
  40891. for (int i = columns.size(); --i >= 0;)
  40892. if (columns.getUnchecked(i)->isVisible())
  40893. w += columns.getUnchecked(i)->width;
  40894. return w;
  40895. }
  40896. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  40897. {
  40898. stretchToFit = shouldStretchToFit;
  40899. lastDeliberateWidth = getTotalWidth();
  40900. resized();
  40901. }
  40902. bool TableHeaderComponent::isStretchToFitActive() const
  40903. {
  40904. return stretchToFit;
  40905. }
  40906. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  40907. {
  40908. if (stretchToFit && getWidth() > 0
  40909. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  40910. {
  40911. lastDeliberateWidth = targetTotalWidth;
  40912. resizeColumnsToFit (0, targetTotalWidth);
  40913. }
  40914. }
  40915. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  40916. {
  40917. targetTotalWidth = jmax (targetTotalWidth, 0);
  40918. StretchableObjectResizer sor;
  40919. int i;
  40920. for (i = firstColumnIndex; i < columns.size(); ++i)
  40921. {
  40922. ColumnInfo* const ci = columns.getUnchecked(i);
  40923. if (ci->isVisible())
  40924. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  40925. }
  40926. sor.resizeToFit (targetTotalWidth);
  40927. int visIndex = 0;
  40928. for (i = firstColumnIndex; i < columns.size(); ++i)
  40929. {
  40930. ColumnInfo* const ci = columns.getUnchecked(i);
  40931. if (ci->isVisible())
  40932. {
  40933. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  40934. (int) std::floor (sor.getItemSize (visIndex++)));
  40935. if (newWidth != ci->width)
  40936. {
  40937. ci->width = newWidth;
  40938. repaint();
  40939. columnsResized = true;
  40940. triggerAsyncUpdate();
  40941. }
  40942. }
  40943. }
  40944. }
  40945. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  40946. {
  40947. ColumnInfo* const ci = getInfoForId (columnId);
  40948. if (ci != 0 && shouldBeVisible != ci->isVisible())
  40949. {
  40950. if (shouldBeVisible)
  40951. ci->propertyFlags |= visible;
  40952. else
  40953. ci->propertyFlags &= ~visible;
  40954. sendColumnsChanged();
  40955. resized();
  40956. }
  40957. }
  40958. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  40959. {
  40960. const ColumnInfo* const ci = getInfoForId (columnId);
  40961. return ci != 0 && ci->isVisible();
  40962. }
  40963. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  40964. {
  40965. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  40966. {
  40967. for (int i = columns.size(); --i >= 0;)
  40968. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  40969. ColumnInfo* const ci = getInfoForId (columnId);
  40970. if (ci != 0)
  40971. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  40972. reSortTable();
  40973. }
  40974. }
  40975. int TableHeaderComponent::getSortColumnId() const
  40976. {
  40977. for (int i = columns.size(); --i >= 0;)
  40978. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40979. return columns.getUnchecked(i)->id;
  40980. return 0;
  40981. }
  40982. bool TableHeaderComponent::isSortedForwards() const
  40983. {
  40984. for (int i = columns.size(); --i >= 0;)
  40985. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  40986. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  40987. return true;
  40988. }
  40989. void TableHeaderComponent::reSortTable()
  40990. {
  40991. sortChanged = true;
  40992. repaint();
  40993. triggerAsyncUpdate();
  40994. }
  40995. const String TableHeaderComponent::toString() const
  40996. {
  40997. String s;
  40998. XmlElement doc ("TABLELAYOUT");
  40999. doc.setAttribute ("sortedCol", getSortColumnId());
  41000. doc.setAttribute ("sortForwards", isSortedForwards());
  41001. for (int i = 0; i < columns.size(); ++i)
  41002. {
  41003. const ColumnInfo* const ci = columns.getUnchecked (i);
  41004. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41005. e->setAttribute ("id", ci->id);
  41006. e->setAttribute ("visible", ci->isVisible());
  41007. e->setAttribute ("width", ci->width);
  41008. }
  41009. return doc.createDocument (String::empty, true, false);
  41010. }
  41011. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41012. {
  41013. ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
  41014. int index = 0;
  41015. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41016. {
  41017. forEachXmlChildElement (*storedXml, col)
  41018. {
  41019. const int tabId = col->getIntAttribute ("id");
  41020. ColumnInfo* const ci = getInfoForId (tabId);
  41021. if (ci != 0)
  41022. {
  41023. columns.move (columns.indexOf (ci), index);
  41024. ci->width = col->getIntAttribute ("width");
  41025. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41026. }
  41027. ++index;
  41028. }
  41029. columnsResized = true;
  41030. sendColumnsChanged();
  41031. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41032. storedXml->getBoolAttribute ("sortForwards", true));
  41033. }
  41034. }
  41035. void TableHeaderComponent::addListener (Listener* const newListener)
  41036. {
  41037. listeners.addIfNotAlreadyThere (newListener);
  41038. }
  41039. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41040. {
  41041. listeners.removeValue (listenerToRemove);
  41042. }
  41043. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41044. {
  41045. const ColumnInfo* const ci = getInfoForId (columnId);
  41046. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41047. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41048. }
  41049. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41050. {
  41051. for (int i = 0; i < columns.size(); ++i)
  41052. {
  41053. const ColumnInfo* const ci = columns.getUnchecked(i);
  41054. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41055. menu.addItem (ci->id, ci->name,
  41056. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41057. isColumnVisible (ci->id));
  41058. }
  41059. }
  41060. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41061. {
  41062. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41063. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41064. }
  41065. void TableHeaderComponent::paint (Graphics& g)
  41066. {
  41067. LookAndFeel& lf = getLookAndFeel();
  41068. lf.drawTableHeaderBackground (g, *this);
  41069. const Rectangle<int> clip (g.getClipBounds());
  41070. int x = 0;
  41071. for (int i = 0; i < columns.size(); ++i)
  41072. {
  41073. const ColumnInfo* const ci = columns.getUnchecked(i);
  41074. if (ci->isVisible())
  41075. {
  41076. if (x + ci->width > clip.getX()
  41077. && (ci->id != columnIdBeingDragged
  41078. || dragOverlayComp == 0
  41079. || ! dragOverlayComp->isVisible()))
  41080. {
  41081. Graphics::ScopedSaveState ss (g);
  41082. g.setOrigin (x, 0);
  41083. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41084. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41085. ci->id == columnIdUnderMouse,
  41086. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41087. ci->propertyFlags);
  41088. }
  41089. x += ci->width;
  41090. if (x >= clip.getRight())
  41091. break;
  41092. }
  41093. }
  41094. }
  41095. void TableHeaderComponent::resized()
  41096. {
  41097. }
  41098. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41099. {
  41100. updateColumnUnderMouse (e.x, e.y);
  41101. }
  41102. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41103. {
  41104. updateColumnUnderMouse (e.x, e.y);
  41105. }
  41106. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41107. {
  41108. updateColumnUnderMouse (e.x, e.y);
  41109. }
  41110. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41111. {
  41112. repaint();
  41113. columnIdBeingResized = 0;
  41114. columnIdBeingDragged = 0;
  41115. if (columnIdUnderMouse != 0)
  41116. {
  41117. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41118. if (e.mods.isPopupMenu())
  41119. columnClicked (columnIdUnderMouse, e.mods);
  41120. }
  41121. if (menuActive && e.mods.isPopupMenu())
  41122. showColumnChooserMenu (columnIdUnderMouse);
  41123. }
  41124. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41125. {
  41126. if (columnIdBeingResized == 0
  41127. && columnIdBeingDragged == 0
  41128. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41129. {
  41130. dragOverlayComp = 0;
  41131. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41132. if (columnIdBeingResized != 0)
  41133. {
  41134. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41135. initialColumnWidth = ci->width;
  41136. }
  41137. else
  41138. {
  41139. beginDrag (e);
  41140. }
  41141. }
  41142. if (columnIdBeingResized != 0)
  41143. {
  41144. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41145. if (ci != 0)
  41146. {
  41147. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41148. initialColumnWidth + e.getDistanceFromDragStartX());
  41149. if (stretchToFit)
  41150. {
  41151. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41152. int minWidthOnRight = 0;
  41153. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41154. if (columns.getUnchecked (i)->isVisible())
  41155. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41156. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41157. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41158. }
  41159. setColumnWidth (columnIdBeingResized, w);
  41160. }
  41161. }
  41162. else if (columnIdBeingDragged != 0)
  41163. {
  41164. if (e.y >= -50 && e.y < getHeight() + 50)
  41165. {
  41166. if (dragOverlayComp != 0)
  41167. {
  41168. dragOverlayComp->setVisible (true);
  41169. dragOverlayComp->setBounds (jlimit (0,
  41170. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41171. e.x - draggingColumnOffset),
  41172. 0,
  41173. dragOverlayComp->getWidth(),
  41174. getHeight());
  41175. for (int i = columns.size(); --i >= 0;)
  41176. {
  41177. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41178. int newIndex = currentIndex;
  41179. if (newIndex > 0)
  41180. {
  41181. // if the previous column isn't draggable, we can't move our column
  41182. // past it, because that'd change the undraggable column's position..
  41183. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41184. if ((previous->propertyFlags & draggable) != 0)
  41185. {
  41186. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41187. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41188. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41189. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41190. {
  41191. --newIndex;
  41192. }
  41193. }
  41194. }
  41195. if (newIndex < columns.size() - 1)
  41196. {
  41197. // if the next column isn't draggable, we can't move our column
  41198. // past it, because that'd change the undraggable column's position..
  41199. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41200. if ((nextCol->propertyFlags & draggable) != 0)
  41201. {
  41202. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41203. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41204. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41205. > abs (dragOverlayComp->getRight() - rightOfNext))
  41206. {
  41207. ++newIndex;
  41208. }
  41209. }
  41210. }
  41211. if (newIndex != currentIndex)
  41212. moveColumn (columnIdBeingDragged, newIndex);
  41213. else
  41214. break;
  41215. }
  41216. }
  41217. }
  41218. else
  41219. {
  41220. endDrag (draggingColumnOriginalIndex);
  41221. }
  41222. }
  41223. }
  41224. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41225. {
  41226. if (columnIdBeingDragged == 0)
  41227. {
  41228. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41229. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41230. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41231. {
  41232. columnIdBeingDragged = 0;
  41233. }
  41234. else
  41235. {
  41236. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41237. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41238. const int temp = columnIdBeingDragged;
  41239. columnIdBeingDragged = 0;
  41240. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41241. columnIdBeingDragged = temp;
  41242. dragOverlayComp->setBounds (columnRect);
  41243. for (int i = listeners.size(); --i >= 0;)
  41244. {
  41245. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41246. i = jmin (i, listeners.size() - 1);
  41247. }
  41248. }
  41249. }
  41250. }
  41251. void TableHeaderComponent::endDrag (const int finalIndex)
  41252. {
  41253. if (columnIdBeingDragged != 0)
  41254. {
  41255. moveColumn (columnIdBeingDragged, finalIndex);
  41256. columnIdBeingDragged = 0;
  41257. repaint();
  41258. for (int i = listeners.size(); --i >= 0;)
  41259. {
  41260. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41261. i = jmin (i, listeners.size() - 1);
  41262. }
  41263. }
  41264. }
  41265. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41266. {
  41267. mouseDrag (e);
  41268. for (int i = columns.size(); --i >= 0;)
  41269. if (columns.getUnchecked (i)->isVisible())
  41270. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41271. columnIdBeingResized = 0;
  41272. repaint();
  41273. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41274. updateColumnUnderMouse (e.x, e.y);
  41275. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41276. columnClicked (columnIdUnderMouse, e.mods);
  41277. dragOverlayComp = 0;
  41278. }
  41279. const MouseCursor TableHeaderComponent::getMouseCursor()
  41280. {
  41281. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41282. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41283. return Component::getMouseCursor();
  41284. }
  41285. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41286. {
  41287. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41288. }
  41289. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41290. {
  41291. for (int i = columns.size(); --i >= 0;)
  41292. if (columns.getUnchecked(i)->id == id)
  41293. return columns.getUnchecked(i);
  41294. return 0;
  41295. }
  41296. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41297. {
  41298. int n = 0;
  41299. for (int i = 0; i < columns.size(); ++i)
  41300. {
  41301. if (columns.getUnchecked(i)->isVisible())
  41302. {
  41303. if (n == visibleIndex)
  41304. return i;
  41305. ++n;
  41306. }
  41307. }
  41308. return -1;
  41309. }
  41310. void TableHeaderComponent::sendColumnsChanged()
  41311. {
  41312. if (stretchToFit && lastDeliberateWidth > 0)
  41313. resizeAllColumnsToFit (lastDeliberateWidth);
  41314. repaint();
  41315. columnsChanged = true;
  41316. triggerAsyncUpdate();
  41317. }
  41318. void TableHeaderComponent::handleAsyncUpdate()
  41319. {
  41320. const bool changed = columnsChanged || sortChanged;
  41321. const bool sized = columnsResized || changed;
  41322. const bool sorted = sortChanged;
  41323. columnsChanged = false;
  41324. columnsResized = false;
  41325. sortChanged = false;
  41326. if (sorted)
  41327. {
  41328. for (int i = listeners.size(); --i >= 0;)
  41329. {
  41330. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41331. i = jmin (i, listeners.size() - 1);
  41332. }
  41333. }
  41334. if (changed)
  41335. {
  41336. for (int i = listeners.size(); --i >= 0;)
  41337. {
  41338. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41339. i = jmin (i, listeners.size() - 1);
  41340. }
  41341. }
  41342. if (sized)
  41343. {
  41344. for (int i = listeners.size(); --i >= 0;)
  41345. {
  41346. listeners.getUnchecked(i)->tableColumnsResized (this);
  41347. i = jmin (i, listeners.size() - 1);
  41348. }
  41349. }
  41350. }
  41351. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41352. {
  41353. if (isPositiveAndBelow (mouseX, getWidth()))
  41354. {
  41355. const int draggableDistance = 3;
  41356. int x = 0;
  41357. for (int i = 0; i < columns.size(); ++i)
  41358. {
  41359. const ColumnInfo* const ci = columns.getUnchecked(i);
  41360. if (ci->isVisible())
  41361. {
  41362. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41363. && (ci->propertyFlags & resizable) != 0)
  41364. return ci->id;
  41365. x += ci->width;
  41366. }
  41367. }
  41368. }
  41369. return 0;
  41370. }
  41371. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41372. {
  41373. const int newCol = (reallyContains (Point<int> (x, y), true) && getResizeDraggerAt (x) == 0)
  41374. ? getColumnIdAtX (x) : 0;
  41375. if (newCol != columnIdUnderMouse)
  41376. {
  41377. columnIdUnderMouse = newCol;
  41378. repaint();
  41379. }
  41380. }
  41381. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41382. {
  41383. PopupMenu m;
  41384. addMenuItems (m, columnIdClicked);
  41385. if (m.getNumItems() > 0)
  41386. {
  41387. m.setLookAndFeel (&getLookAndFeel());
  41388. const int result = m.show();
  41389. if (result != 0)
  41390. reactToMenuItem (result, columnIdClicked);
  41391. }
  41392. }
  41393. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41394. {
  41395. }
  41396. END_JUCE_NAMESPACE
  41397. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41398. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41399. BEGIN_JUCE_NAMESPACE
  41400. class TableListRowComp : public Component,
  41401. public TooltipClient
  41402. {
  41403. public:
  41404. TableListRowComp (TableListBox& owner_)
  41405. : owner (owner_), row (-1), isSelected (false)
  41406. {
  41407. }
  41408. void paint (Graphics& g)
  41409. {
  41410. TableListBoxModel* const model = owner.getModel();
  41411. if (model != 0)
  41412. {
  41413. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41414. const TableHeaderComponent& header = owner.getHeader();
  41415. const int numColumns = header.getNumColumns (true);
  41416. for (int i = 0; i < numColumns; ++i)
  41417. {
  41418. if (columnComponents[i] == 0)
  41419. {
  41420. const int columnId = header.getColumnIdOfIndex (i, true);
  41421. const Rectangle<int> columnRect (header.getColumnPosition(i).withHeight (getHeight()));
  41422. Graphics::ScopedSaveState ss (g);
  41423. g.reduceClipRegion (columnRect);
  41424. g.setOrigin (columnRect.getX(), 0);
  41425. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41426. }
  41427. }
  41428. }
  41429. }
  41430. void update (const int newRow, const bool isNowSelected)
  41431. {
  41432. jassert (newRow >= 0);
  41433. if (newRow != row || isNowSelected != isSelected)
  41434. {
  41435. row = newRow;
  41436. isSelected = isNowSelected;
  41437. repaint();
  41438. }
  41439. TableListBoxModel* const model = owner.getModel();
  41440. if (model != 0 && row < owner.getNumRows())
  41441. {
  41442. const Identifier columnProperty ("_tableColumnId");
  41443. const int numColumns = owner.getHeader().getNumColumns (true);
  41444. for (int i = 0; i < numColumns; ++i)
  41445. {
  41446. const int columnId = owner.getHeader().getColumnIdOfIndex (i, true);
  41447. Component* comp = columnComponents[i];
  41448. if (comp != 0 && columnId != (int) comp->getProperties() [columnProperty])
  41449. {
  41450. columnComponents.set (i, 0);
  41451. comp = 0;
  41452. }
  41453. comp = model->refreshComponentForCell (row, columnId, isSelected, comp);
  41454. columnComponents.set (i, comp, false);
  41455. if (comp != 0)
  41456. {
  41457. comp->getProperties().set (columnProperty, columnId);
  41458. addAndMakeVisible (comp);
  41459. resizeCustomComp (i);
  41460. }
  41461. }
  41462. columnComponents.removeRange (numColumns, columnComponents.size());
  41463. }
  41464. else
  41465. {
  41466. columnComponents.clear();
  41467. }
  41468. }
  41469. void resized()
  41470. {
  41471. for (int i = columnComponents.size(); --i >= 0;)
  41472. resizeCustomComp (i);
  41473. }
  41474. void resizeCustomComp (const int index)
  41475. {
  41476. Component* const c = columnComponents.getUnchecked (index);
  41477. if (c != 0)
  41478. c->setBounds (owner.getHeader().getColumnPosition (index)
  41479. .withY (0).withHeight (getHeight()));
  41480. }
  41481. void mouseDown (const MouseEvent& e)
  41482. {
  41483. isDragging = false;
  41484. selectRowOnMouseUp = false;
  41485. if (isEnabled())
  41486. {
  41487. if (! isSelected)
  41488. {
  41489. owner.selectRowsBasedOnModifierKeys (row, e.mods, false);
  41490. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41491. if (columnId != 0 && owner.getModel() != 0)
  41492. owner.getModel()->cellClicked (row, columnId, e);
  41493. }
  41494. else
  41495. {
  41496. selectRowOnMouseUp = true;
  41497. }
  41498. }
  41499. }
  41500. void mouseDrag (const MouseEvent& e)
  41501. {
  41502. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41503. {
  41504. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41505. if (selectedRows.size() > 0)
  41506. {
  41507. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41508. if (dragDescription.isNotEmpty())
  41509. {
  41510. isDragging = true;
  41511. owner.startDragAndDrop (e, dragDescription);
  41512. }
  41513. }
  41514. }
  41515. }
  41516. void mouseUp (const MouseEvent& e)
  41517. {
  41518. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41519. {
  41520. owner.selectRowsBasedOnModifierKeys (row, e.mods, true);
  41521. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41522. if (columnId != 0 && owner.getModel() != 0)
  41523. owner.getModel()->cellClicked (row, columnId, e);
  41524. }
  41525. }
  41526. void mouseDoubleClick (const MouseEvent& e)
  41527. {
  41528. const int columnId = owner.getHeader().getColumnIdAtX (e.x);
  41529. if (columnId != 0 && owner.getModel() != 0)
  41530. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41531. }
  41532. const String getTooltip()
  41533. {
  41534. const int columnId = owner.getHeader().getColumnIdAtX (getMouseXYRelative().getX());
  41535. if (columnId != 0 && owner.getModel() != 0)
  41536. return owner.getModel()->getCellTooltip (row, columnId);
  41537. return String::empty;
  41538. }
  41539. Component* findChildComponentForColumn (const int columnId) const
  41540. {
  41541. return columnComponents [owner.getHeader().getIndexOfColumnId (columnId, true)];
  41542. }
  41543. private:
  41544. TableListBox& owner;
  41545. OwnedArray<Component> columnComponents;
  41546. int row;
  41547. bool isSelected, isDragging, selectRowOnMouseUp;
  41548. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListRowComp);
  41549. };
  41550. class TableListBoxHeader : public TableHeaderComponent
  41551. {
  41552. public:
  41553. TableListBoxHeader (TableListBox& owner_)
  41554. : owner (owner_)
  41555. {
  41556. }
  41557. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41558. {
  41559. if (owner.isAutoSizeMenuOptionShown())
  41560. {
  41561. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41562. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader().getNumColumns (true) > 0);
  41563. menu.addSeparator();
  41564. }
  41565. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41566. }
  41567. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41568. {
  41569. switch (menuReturnId)
  41570. {
  41571. case autoSizeColumnId: owner.autoSizeColumn (columnIdClicked); break;
  41572. case autoSizeAllId: owner.autoSizeAllColumns(); break;
  41573. default: TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked); break;
  41574. }
  41575. }
  41576. private:
  41577. TableListBox& owner;
  41578. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  41579. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableListBoxHeader);
  41580. };
  41581. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41582. : ListBox (name, 0),
  41583. header (0), model (model_),
  41584. autoSizeOptionsShown (true)
  41585. {
  41586. ListBox::model = this;
  41587. setHeader (new TableListBoxHeader (*this));
  41588. }
  41589. TableListBox::~TableListBox()
  41590. {
  41591. header = 0;
  41592. }
  41593. void TableListBox::setModel (TableListBoxModel* const newModel)
  41594. {
  41595. if (model != newModel)
  41596. {
  41597. model = newModel;
  41598. updateContent();
  41599. }
  41600. }
  41601. void TableListBox::setHeader (TableHeaderComponent* newHeader)
  41602. {
  41603. jassert (newHeader != 0); // you need to supply a real header for a table!
  41604. Rectangle<int> newBounds (0, 0, 100, 28);
  41605. if (header != 0)
  41606. newBounds = header->getBounds();
  41607. header = newHeader;
  41608. header->setBounds (newBounds);
  41609. setHeaderComponent (header);
  41610. header->addListener (this);
  41611. }
  41612. int TableListBox::getHeaderHeight() const
  41613. {
  41614. return header->getHeight();
  41615. }
  41616. void TableListBox::setHeaderHeight (const int newHeight)
  41617. {
  41618. header->setSize (header->getWidth(), newHeight);
  41619. resized();
  41620. }
  41621. void TableListBox::autoSizeColumn (const int columnId)
  41622. {
  41623. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  41624. if (width > 0)
  41625. header->setColumnWidth (columnId, width);
  41626. }
  41627. void TableListBox::autoSizeAllColumns()
  41628. {
  41629. for (int i = 0; i < header->getNumColumns (true); ++i)
  41630. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  41631. }
  41632. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  41633. {
  41634. autoSizeOptionsShown = shouldBeShown;
  41635. }
  41636. bool TableListBox::isAutoSizeMenuOptionShown() const
  41637. {
  41638. return autoSizeOptionsShown;
  41639. }
  41640. const Rectangle<int> TableListBox::getCellPosition (const int columnId, const int rowNumber,
  41641. const bool relativeToComponentTopLeft) const
  41642. {
  41643. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41644. if (relativeToComponentTopLeft)
  41645. headerCell.translate (header->getX(), 0);
  41646. return getRowPosition (rowNumber, relativeToComponentTopLeft)
  41647. .withX (headerCell.getX())
  41648. .withWidth (headerCell.getWidth());
  41649. }
  41650. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  41651. {
  41652. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  41653. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  41654. }
  41655. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  41656. {
  41657. ScrollBar* const scrollbar = getHorizontalScrollBar();
  41658. if (scrollbar != 0)
  41659. {
  41660. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  41661. double x = scrollbar->getCurrentRangeStart();
  41662. const double w = scrollbar->getCurrentRangeSize();
  41663. if (pos.getX() < x)
  41664. x = pos.getX();
  41665. else if (pos.getRight() > x + w)
  41666. x += jmax (0.0, pos.getRight() - (x + w));
  41667. scrollbar->setCurrentRangeStart (x);
  41668. }
  41669. }
  41670. int TableListBox::getNumRows()
  41671. {
  41672. return model != 0 ? model->getNumRows() : 0;
  41673. }
  41674. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  41675. {
  41676. }
  41677. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  41678. {
  41679. if (existingComponentToUpdate == 0)
  41680. existingComponentToUpdate = new TableListRowComp (*this);
  41681. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  41682. return existingComponentToUpdate;
  41683. }
  41684. void TableListBox::selectedRowsChanged (int row)
  41685. {
  41686. if (model != 0)
  41687. model->selectedRowsChanged (row);
  41688. }
  41689. void TableListBox::deleteKeyPressed (int row)
  41690. {
  41691. if (model != 0)
  41692. model->deleteKeyPressed (row);
  41693. }
  41694. void TableListBox::returnKeyPressed (int row)
  41695. {
  41696. if (model != 0)
  41697. model->returnKeyPressed (row);
  41698. }
  41699. void TableListBox::backgroundClicked()
  41700. {
  41701. if (model != 0)
  41702. model->backgroundClicked();
  41703. }
  41704. void TableListBox::listWasScrolled()
  41705. {
  41706. if (model != 0)
  41707. model->listWasScrolled();
  41708. }
  41709. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  41710. {
  41711. setMinimumContentWidth (header->getTotalWidth());
  41712. repaint();
  41713. updateColumnComponents();
  41714. }
  41715. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  41716. {
  41717. setMinimumContentWidth (header->getTotalWidth());
  41718. repaint();
  41719. updateColumnComponents();
  41720. }
  41721. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  41722. {
  41723. if (model != 0)
  41724. model->sortOrderChanged (header->getSortColumnId(),
  41725. header->isSortedForwards());
  41726. }
  41727. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  41728. {
  41729. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  41730. repaint();
  41731. }
  41732. void TableListBox::resized()
  41733. {
  41734. ListBox::resized();
  41735. header->resizeAllColumnsToFit (getVisibleContentWidth());
  41736. setMinimumContentWidth (header->getTotalWidth());
  41737. }
  41738. void TableListBox::updateColumnComponents() const
  41739. {
  41740. const int firstRow = getRowContainingPosition (0, 0);
  41741. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  41742. {
  41743. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  41744. if (rowComp != 0)
  41745. rowComp->resized();
  41746. }
  41747. }
  41748. void TableListBoxModel::cellClicked (int, int, const MouseEvent&) {}
  41749. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&) {}
  41750. void TableListBoxModel::backgroundClicked() {}
  41751. void TableListBoxModel::sortOrderChanged (int, const bool) {}
  41752. int TableListBoxModel::getColumnAutoSizeWidth (int) { return 0; }
  41753. void TableListBoxModel::selectedRowsChanged (int) {}
  41754. void TableListBoxModel::deleteKeyPressed (int) {}
  41755. void TableListBoxModel::returnKeyPressed (int) {}
  41756. void TableListBoxModel::listWasScrolled() {}
  41757. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/) { return String::empty; }
  41758. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  41759. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  41760. {
  41761. (void) existingComponentToUpdate;
  41762. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  41763. return 0;
  41764. }
  41765. END_JUCE_NAMESPACE
  41766. /*** End of inlined file: juce_TableListBox.cpp ***/
  41767. /*** Start of inlined file: juce_TextEditor.cpp ***/
  41768. BEGIN_JUCE_NAMESPACE
  41769. // a word or space that can't be broken down any further
  41770. struct TextAtom
  41771. {
  41772. String atomText;
  41773. float width;
  41774. int numChars;
  41775. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  41776. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  41777. const String getText (const juce_wchar passwordCharacter) const
  41778. {
  41779. if (passwordCharacter == 0)
  41780. return atomText;
  41781. else
  41782. return String::repeatedString (String::charToString (passwordCharacter),
  41783. atomText.length());
  41784. }
  41785. const String getTrimmedText (const juce_wchar passwordCharacter) const
  41786. {
  41787. if (passwordCharacter == 0)
  41788. return atomText.substring (0, numChars);
  41789. else if (isNewLine())
  41790. return String::empty;
  41791. else
  41792. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  41793. }
  41794. };
  41795. // a run of text with a single font and colour
  41796. class TextEditor::UniformTextSection
  41797. {
  41798. public:
  41799. UniformTextSection (const String& text,
  41800. const Font& font_,
  41801. const Colour& colour_,
  41802. const juce_wchar passwordCharacter)
  41803. : font (font_),
  41804. colour (colour_)
  41805. {
  41806. initialiseAtoms (text, passwordCharacter);
  41807. }
  41808. UniformTextSection (const UniformTextSection& other)
  41809. : font (other.font),
  41810. colour (other.colour)
  41811. {
  41812. atoms.ensureStorageAllocated (other.atoms.size());
  41813. for (int i = 0; i < other.atoms.size(); ++i)
  41814. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  41815. }
  41816. ~UniformTextSection()
  41817. {
  41818. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  41819. }
  41820. void clear()
  41821. {
  41822. for (int i = atoms.size(); --i >= 0;)
  41823. delete getAtom(i);
  41824. atoms.clear();
  41825. }
  41826. int getNumAtoms() const
  41827. {
  41828. return atoms.size();
  41829. }
  41830. TextAtom* getAtom (const int index) const throw()
  41831. {
  41832. return atoms.getUnchecked (index);
  41833. }
  41834. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  41835. {
  41836. if (other.atoms.size() > 0)
  41837. {
  41838. TextAtom* const lastAtom = atoms.getLast();
  41839. int i = 0;
  41840. if (lastAtom != 0)
  41841. {
  41842. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  41843. {
  41844. TextAtom* const first = other.getAtom(0);
  41845. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  41846. {
  41847. lastAtom->atomText += first->atomText;
  41848. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  41849. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  41850. delete first;
  41851. ++i;
  41852. }
  41853. }
  41854. }
  41855. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  41856. while (i < other.atoms.size())
  41857. {
  41858. atoms.add (other.getAtom(i));
  41859. ++i;
  41860. }
  41861. }
  41862. }
  41863. UniformTextSection* split (const int indexToBreakAt,
  41864. const juce_wchar passwordCharacter)
  41865. {
  41866. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  41867. font, colour,
  41868. passwordCharacter);
  41869. int index = 0;
  41870. for (int i = 0; i < atoms.size(); ++i)
  41871. {
  41872. TextAtom* const atom = getAtom(i);
  41873. const int nextIndex = index + atom->numChars;
  41874. if (index == indexToBreakAt)
  41875. {
  41876. int j;
  41877. for (j = i; j < atoms.size(); ++j)
  41878. section2->atoms.add (getAtom (j));
  41879. for (j = atoms.size(); --j >= i;)
  41880. atoms.remove (j);
  41881. break;
  41882. }
  41883. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  41884. {
  41885. TextAtom* const secondAtom = new TextAtom();
  41886. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  41887. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  41888. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  41889. section2->atoms.add (secondAtom);
  41890. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  41891. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41892. atom->numChars = (uint16) (indexToBreakAt - index);
  41893. int j;
  41894. for (j = i + 1; j < atoms.size(); ++j)
  41895. section2->atoms.add (getAtom (j));
  41896. for (j = atoms.size(); --j > i;)
  41897. atoms.remove (j);
  41898. break;
  41899. }
  41900. index = nextIndex;
  41901. }
  41902. return section2;
  41903. }
  41904. void appendAllText (String::Concatenator& concatenator) const
  41905. {
  41906. for (int i = 0; i < atoms.size(); ++i)
  41907. concatenator.append (getAtom(i)->atomText);
  41908. }
  41909. void appendSubstring (String::Concatenator& concatenator,
  41910. const Range<int>& range) const
  41911. {
  41912. int index = 0;
  41913. for (int i = 0; i < atoms.size(); ++i)
  41914. {
  41915. const TextAtom* const atom = getAtom (i);
  41916. const int nextIndex = index + atom->numChars;
  41917. if (range.getStart() < nextIndex)
  41918. {
  41919. if (range.getEnd() <= index)
  41920. break;
  41921. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  41922. if (! r.isEmpty())
  41923. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  41924. }
  41925. index = nextIndex;
  41926. }
  41927. }
  41928. int getTotalLength() const
  41929. {
  41930. int total = 0;
  41931. for (int i = atoms.size(); --i >= 0;)
  41932. total += getAtom(i)->numChars;
  41933. return total;
  41934. }
  41935. void setFont (const Font& newFont,
  41936. const juce_wchar passwordCharacter)
  41937. {
  41938. if (font != newFont)
  41939. {
  41940. font = newFont;
  41941. for (int i = atoms.size(); --i >= 0;)
  41942. {
  41943. TextAtom* const atom = atoms.getUnchecked(i);
  41944. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  41945. }
  41946. }
  41947. }
  41948. Font font;
  41949. Colour colour;
  41950. private:
  41951. Array <TextAtom*> atoms;
  41952. void initialiseAtoms (const String& textToParse,
  41953. const juce_wchar passwordCharacter)
  41954. {
  41955. String::CharPointerType text (textToParse.getCharPointer());
  41956. while (! text.isEmpty())
  41957. {
  41958. int numChars = 0;
  41959. String::CharPointerType start (text);
  41960. // create a whitespace atom unless it starts with non-ws
  41961. if (text.isWhitespace() && *text != '\r' && *text != '\n')
  41962. {
  41963. do
  41964. {
  41965. ++text;
  41966. ++numChars;
  41967. }
  41968. while (text.isWhitespace() && *text != '\r' && *text != '\n');
  41969. }
  41970. else
  41971. {
  41972. if (*text == '\r')
  41973. {
  41974. ++text;
  41975. ++numChars;
  41976. if (*text == '\n')
  41977. {
  41978. ++start;
  41979. ++text;
  41980. }
  41981. }
  41982. else if (*text == '\n')
  41983. {
  41984. ++text;
  41985. ++numChars;
  41986. }
  41987. else
  41988. {
  41989. while (! (text.isEmpty() || text.isWhitespace()))
  41990. {
  41991. ++text;
  41992. ++numChars;
  41993. }
  41994. }
  41995. }
  41996. TextAtom* const atom = new TextAtom();
  41997. atom->atomText = String (start, numChars);
  41998. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  41999. atom->numChars = (uint16) numChars;
  42000. atoms.add (atom);
  42001. }
  42002. }
  42003. UniformTextSection& operator= (const UniformTextSection& other);
  42004. JUCE_LEAK_DETECTOR (UniformTextSection);
  42005. };
  42006. class TextEditor::Iterator
  42007. {
  42008. public:
  42009. Iterator (const Array <UniformTextSection*>& sections_,
  42010. const float wordWrapWidth_,
  42011. const juce_wchar passwordCharacter_)
  42012. : indexInText (0),
  42013. lineY (0),
  42014. lineHeight (0),
  42015. maxDescent (0),
  42016. atomX (0),
  42017. atomRight (0),
  42018. atom (0),
  42019. currentSection (0),
  42020. sections (sections_),
  42021. sectionIndex (0),
  42022. atomIndex (0),
  42023. wordWrapWidth (wordWrapWidth_),
  42024. passwordCharacter (passwordCharacter_)
  42025. {
  42026. jassert (wordWrapWidth_ > 0);
  42027. if (sections.size() > 0)
  42028. {
  42029. currentSection = sections.getUnchecked (sectionIndex);
  42030. if (currentSection != 0)
  42031. beginNewLine();
  42032. }
  42033. }
  42034. Iterator (const Iterator& other)
  42035. : indexInText (other.indexInText),
  42036. lineY (other.lineY),
  42037. lineHeight (other.lineHeight),
  42038. maxDescent (other.maxDescent),
  42039. atomX (other.atomX),
  42040. atomRight (other.atomRight),
  42041. atom (other.atom),
  42042. currentSection (other.currentSection),
  42043. sections (other.sections),
  42044. sectionIndex (other.sectionIndex),
  42045. atomIndex (other.atomIndex),
  42046. wordWrapWidth (other.wordWrapWidth),
  42047. passwordCharacter (other.passwordCharacter),
  42048. tempAtom (other.tempAtom)
  42049. {
  42050. }
  42051. bool next()
  42052. {
  42053. if (atom == &tempAtom)
  42054. {
  42055. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42056. if (numRemaining > 0)
  42057. {
  42058. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42059. atomX = 0;
  42060. if (tempAtom.numChars > 0)
  42061. lineY += lineHeight;
  42062. indexInText += tempAtom.numChars;
  42063. GlyphArrangement g;
  42064. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42065. int split;
  42066. for (split = 0; split < g.getNumGlyphs(); ++split)
  42067. if (shouldWrap (g.getGlyph (split).getRight()))
  42068. break;
  42069. if (split > 0 && split <= numRemaining)
  42070. {
  42071. tempAtom.numChars = (uint16) split;
  42072. tempAtom.width = g.getGlyph (split - 1).getRight();
  42073. atomRight = atomX + tempAtom.width;
  42074. return true;
  42075. }
  42076. }
  42077. }
  42078. bool forceNewLine = false;
  42079. if (sectionIndex >= sections.size())
  42080. {
  42081. moveToEndOfLastAtom();
  42082. return false;
  42083. }
  42084. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42085. {
  42086. if (atomIndex >= currentSection->getNumAtoms())
  42087. {
  42088. if (++sectionIndex >= sections.size())
  42089. {
  42090. moveToEndOfLastAtom();
  42091. return false;
  42092. }
  42093. atomIndex = 0;
  42094. currentSection = sections.getUnchecked (sectionIndex);
  42095. }
  42096. else
  42097. {
  42098. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42099. if (! lastAtom->isWhitespace())
  42100. {
  42101. // handle the case where the last atom in a section is actually part of the same
  42102. // word as the first atom of the next section...
  42103. float right = atomRight + lastAtom->width;
  42104. float lineHeight2 = lineHeight;
  42105. float maxDescent2 = maxDescent;
  42106. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42107. {
  42108. const UniformTextSection* const s = sections.getUnchecked (section);
  42109. if (s->getNumAtoms() == 0)
  42110. break;
  42111. const TextAtom* const nextAtom = s->getAtom (0);
  42112. if (nextAtom->isWhitespace())
  42113. break;
  42114. right += nextAtom->width;
  42115. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42116. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42117. if (shouldWrap (right))
  42118. {
  42119. lineHeight = lineHeight2;
  42120. maxDescent = maxDescent2;
  42121. forceNewLine = true;
  42122. break;
  42123. }
  42124. if (s->getNumAtoms() > 1)
  42125. break;
  42126. }
  42127. }
  42128. }
  42129. }
  42130. if (atom != 0)
  42131. {
  42132. atomX = atomRight;
  42133. indexInText += atom->numChars;
  42134. if (atom->isNewLine())
  42135. beginNewLine();
  42136. }
  42137. atom = currentSection->getAtom (atomIndex);
  42138. atomRight = atomX + atom->width;
  42139. ++atomIndex;
  42140. if (shouldWrap (atomRight) || forceNewLine)
  42141. {
  42142. if (atom->isWhitespace())
  42143. {
  42144. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42145. atomRight = jmin (atomRight, wordWrapWidth);
  42146. }
  42147. else
  42148. {
  42149. atomRight = atom->width;
  42150. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42151. {
  42152. tempAtom = *atom;
  42153. tempAtom.width = 0;
  42154. tempAtom.numChars = 0;
  42155. atom = &tempAtom;
  42156. if (atomX > 0)
  42157. beginNewLine();
  42158. return next();
  42159. }
  42160. beginNewLine();
  42161. return true;
  42162. }
  42163. }
  42164. return true;
  42165. }
  42166. void beginNewLine()
  42167. {
  42168. atomX = 0;
  42169. lineY += lineHeight;
  42170. int tempSectionIndex = sectionIndex;
  42171. int tempAtomIndex = atomIndex;
  42172. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42173. lineHeight = section->font.getHeight();
  42174. maxDescent = section->font.getDescent();
  42175. float x = (atom != 0) ? atom->width : 0;
  42176. while (! shouldWrap (x))
  42177. {
  42178. if (tempSectionIndex >= sections.size())
  42179. break;
  42180. bool checkSize = false;
  42181. if (tempAtomIndex >= section->getNumAtoms())
  42182. {
  42183. if (++tempSectionIndex >= sections.size())
  42184. break;
  42185. tempAtomIndex = 0;
  42186. section = sections.getUnchecked (tempSectionIndex);
  42187. checkSize = true;
  42188. }
  42189. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42190. if (nextAtom == 0)
  42191. break;
  42192. x += nextAtom->width;
  42193. if (shouldWrap (x) || nextAtom->isNewLine())
  42194. break;
  42195. if (checkSize)
  42196. {
  42197. lineHeight = jmax (lineHeight, section->font.getHeight());
  42198. maxDescent = jmax (maxDescent, section->font.getDescent());
  42199. }
  42200. ++tempAtomIndex;
  42201. }
  42202. }
  42203. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42204. {
  42205. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42206. {
  42207. if (lastSection != currentSection)
  42208. {
  42209. lastSection = currentSection;
  42210. g.setColour (currentSection->colour);
  42211. g.setFont (currentSection->font);
  42212. }
  42213. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42214. GlyphArrangement ga;
  42215. ga.addLineOfText (currentSection->font,
  42216. atom->getTrimmedText (passwordCharacter),
  42217. atomX,
  42218. (float) roundToInt (lineY + lineHeight - maxDescent));
  42219. ga.draw (g);
  42220. }
  42221. }
  42222. void drawSelection (Graphics& g,
  42223. const Range<int>& selection) const
  42224. {
  42225. const int startX = roundToInt (indexToX (selection.getStart()));
  42226. const int endX = roundToInt (indexToX (selection.getEnd()));
  42227. const int y = roundToInt (lineY);
  42228. const int nextY = roundToInt (lineY + lineHeight);
  42229. g.fillRect (startX, y, endX - startX, nextY - y);
  42230. }
  42231. void drawSelectedText (Graphics& g,
  42232. const Range<int>& selection,
  42233. const Colour& selectedTextColour) const
  42234. {
  42235. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42236. {
  42237. GlyphArrangement ga;
  42238. ga.addLineOfText (currentSection->font,
  42239. atom->getTrimmedText (passwordCharacter),
  42240. atomX,
  42241. (float) roundToInt (lineY + lineHeight - maxDescent));
  42242. if (selection.getEnd() < indexInText + atom->numChars)
  42243. {
  42244. GlyphArrangement ga2 (ga);
  42245. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42246. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42247. g.setColour (currentSection->colour);
  42248. ga2.draw (g);
  42249. }
  42250. if (selection.getStart() > indexInText)
  42251. {
  42252. GlyphArrangement ga2 (ga);
  42253. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42254. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42255. g.setColour (currentSection->colour);
  42256. ga2.draw (g);
  42257. }
  42258. g.setColour (selectedTextColour);
  42259. ga.draw (g);
  42260. }
  42261. }
  42262. float indexToX (const int indexToFind) const
  42263. {
  42264. if (indexToFind <= indexInText)
  42265. return atomX;
  42266. if (indexToFind >= indexInText + atom->numChars)
  42267. return atomRight;
  42268. GlyphArrangement g;
  42269. g.addLineOfText (currentSection->font,
  42270. atom->getText (passwordCharacter),
  42271. atomX, 0.0f);
  42272. if (indexToFind - indexInText >= g.getNumGlyphs())
  42273. return atomRight;
  42274. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42275. }
  42276. int xToIndex (const float xToFind) const
  42277. {
  42278. if (xToFind <= atomX || atom->isNewLine())
  42279. return indexInText;
  42280. if (xToFind >= atomRight)
  42281. return indexInText + atom->numChars;
  42282. GlyphArrangement g;
  42283. g.addLineOfText (currentSection->font,
  42284. atom->getText (passwordCharacter),
  42285. atomX, 0.0f);
  42286. int j;
  42287. for (j = 0; j < g.getNumGlyphs(); ++j)
  42288. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42289. break;
  42290. return indexInText + j;
  42291. }
  42292. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42293. {
  42294. while (next())
  42295. {
  42296. if (indexInText + atom->numChars > index)
  42297. {
  42298. cx = indexToX (index);
  42299. cy = lineY;
  42300. lineHeight_ = lineHeight;
  42301. return true;
  42302. }
  42303. }
  42304. cx = atomX;
  42305. cy = lineY;
  42306. lineHeight_ = lineHeight;
  42307. return false;
  42308. }
  42309. int indexInText;
  42310. float lineY, lineHeight, maxDescent;
  42311. float atomX, atomRight;
  42312. const TextAtom* atom;
  42313. const UniformTextSection* currentSection;
  42314. private:
  42315. const Array <UniformTextSection*>& sections;
  42316. int sectionIndex, atomIndex;
  42317. const float wordWrapWidth;
  42318. const juce_wchar passwordCharacter;
  42319. TextAtom tempAtom;
  42320. Iterator& operator= (const Iterator&);
  42321. void moveToEndOfLastAtom()
  42322. {
  42323. if (atom != 0)
  42324. {
  42325. atomX = atomRight;
  42326. if (atom->isNewLine())
  42327. {
  42328. atomX = 0.0f;
  42329. lineY += lineHeight;
  42330. }
  42331. }
  42332. }
  42333. bool shouldWrap (const float x) const
  42334. {
  42335. return (x - 0.0001f) >= wordWrapWidth;
  42336. }
  42337. JUCE_LEAK_DETECTOR (Iterator);
  42338. };
  42339. class TextEditor::InsertAction : public UndoableAction
  42340. {
  42341. public:
  42342. InsertAction (TextEditor& owner_,
  42343. const String& text_,
  42344. const int insertIndex_,
  42345. const Font& font_,
  42346. const Colour& colour_,
  42347. const int oldCaretPos_,
  42348. const int newCaretPos_)
  42349. : owner (owner_),
  42350. text (text_),
  42351. insertIndex (insertIndex_),
  42352. oldCaretPos (oldCaretPos_),
  42353. newCaretPos (newCaretPos_),
  42354. font (font_),
  42355. colour (colour_)
  42356. {
  42357. }
  42358. bool perform()
  42359. {
  42360. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42361. return true;
  42362. }
  42363. bool undo()
  42364. {
  42365. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42366. return true;
  42367. }
  42368. int getSizeInUnits()
  42369. {
  42370. return text.length() + 16;
  42371. }
  42372. private:
  42373. TextEditor& owner;
  42374. const String text;
  42375. const int insertIndex, oldCaretPos, newCaretPos;
  42376. const Font font;
  42377. const Colour colour;
  42378. JUCE_DECLARE_NON_COPYABLE (InsertAction);
  42379. };
  42380. class TextEditor::RemoveAction : public UndoableAction
  42381. {
  42382. public:
  42383. RemoveAction (TextEditor& owner_,
  42384. const Range<int> range_,
  42385. const int oldCaretPos_,
  42386. const int newCaretPos_,
  42387. const Array <UniformTextSection*>& removedSections_)
  42388. : owner (owner_),
  42389. range (range_),
  42390. oldCaretPos (oldCaretPos_),
  42391. newCaretPos (newCaretPos_),
  42392. removedSections (removedSections_)
  42393. {
  42394. }
  42395. ~RemoveAction()
  42396. {
  42397. for (int i = removedSections.size(); --i >= 0;)
  42398. {
  42399. UniformTextSection* const section = removedSections.getUnchecked (i);
  42400. section->clear();
  42401. delete section;
  42402. }
  42403. }
  42404. bool perform()
  42405. {
  42406. owner.remove (range, 0, newCaretPos);
  42407. return true;
  42408. }
  42409. bool undo()
  42410. {
  42411. owner.reinsert (range.getStart(), removedSections);
  42412. owner.moveCursorTo (oldCaretPos, false);
  42413. return true;
  42414. }
  42415. int getSizeInUnits()
  42416. {
  42417. int n = 0;
  42418. for (int i = removedSections.size(); --i >= 0;)
  42419. n += removedSections.getUnchecked (i)->getTotalLength();
  42420. return n + 16;
  42421. }
  42422. private:
  42423. TextEditor& owner;
  42424. const Range<int> range;
  42425. const int oldCaretPos, newCaretPos;
  42426. Array <UniformTextSection*> removedSections;
  42427. JUCE_DECLARE_NON_COPYABLE (RemoveAction);
  42428. };
  42429. class TextEditor::TextHolderComponent : public Component,
  42430. public Timer,
  42431. public ValueListener
  42432. {
  42433. public:
  42434. TextHolderComponent (TextEditor& owner_)
  42435. : owner (owner_)
  42436. {
  42437. setWantsKeyboardFocus (false);
  42438. setInterceptsMouseClicks (false, true);
  42439. owner.getTextValue().addListener (this);
  42440. }
  42441. ~TextHolderComponent()
  42442. {
  42443. owner.getTextValue().removeListener (this);
  42444. }
  42445. void paint (Graphics& g)
  42446. {
  42447. owner.drawContent (g);
  42448. }
  42449. void timerCallback()
  42450. {
  42451. owner.timerCallbackInt();
  42452. }
  42453. const MouseCursor getMouseCursor()
  42454. {
  42455. return owner.getMouseCursor();
  42456. }
  42457. void valueChanged (Value&)
  42458. {
  42459. owner.textWasChangedByValue();
  42460. }
  42461. private:
  42462. TextEditor& owner;
  42463. JUCE_DECLARE_NON_COPYABLE (TextHolderComponent);
  42464. };
  42465. class TextEditorViewport : public Viewport
  42466. {
  42467. public:
  42468. TextEditorViewport (TextEditor& owner_)
  42469. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42470. {
  42471. }
  42472. void visibleAreaChanged (const Rectangle<int>&)
  42473. {
  42474. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42475. // appear and disappear, causing the wrap width to change.
  42476. {
  42477. const float wordWrapWidth = owner.getWordWrapWidth();
  42478. if (wordWrapWidth != lastWordWrapWidth)
  42479. {
  42480. lastWordWrapWidth = wordWrapWidth;
  42481. rentrant = true;
  42482. owner.updateTextHolderSize();
  42483. rentrant = false;
  42484. }
  42485. }
  42486. }
  42487. private:
  42488. TextEditor& owner;
  42489. float lastWordWrapWidth;
  42490. bool rentrant;
  42491. JUCE_DECLARE_NON_COPYABLE (TextEditorViewport);
  42492. };
  42493. namespace TextEditorDefs
  42494. {
  42495. const int flashSpeedIntervalMs = 380;
  42496. const int textChangeMessageId = 0x10003001;
  42497. const int returnKeyMessageId = 0x10003002;
  42498. const int escapeKeyMessageId = 0x10003003;
  42499. const int focusLossMessageId = 0x10003004;
  42500. const int maxActionsPerTransaction = 100;
  42501. int getCharacterCategory (const juce_wchar character)
  42502. {
  42503. return CharacterFunctions::isLetterOrDigit (character)
  42504. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42505. }
  42506. }
  42507. TextEditor::TextEditor (const String& name,
  42508. const juce_wchar passwordCharacter_)
  42509. : Component (name),
  42510. borderSize (1, 1, 1, 3),
  42511. readOnly (false),
  42512. multiline (false),
  42513. wordWrap (false),
  42514. returnKeyStartsNewLine (false),
  42515. caretVisible (true),
  42516. popupMenuEnabled (true),
  42517. selectAllTextWhenFocused (false),
  42518. scrollbarVisible (true),
  42519. wasFocused (false),
  42520. caretFlashState (true),
  42521. keepCursorOnScreen (true),
  42522. tabKeyUsed (false),
  42523. menuActive (false),
  42524. valueTextNeedsUpdating (false),
  42525. cursorX (0),
  42526. cursorY (0),
  42527. cursorHeight (0),
  42528. maxTextLength (0),
  42529. leftIndent (4),
  42530. topIndent (4),
  42531. lastTransactionTime (0),
  42532. currentFont (14.0f),
  42533. totalNumChars (0),
  42534. caretPosition (0),
  42535. passwordCharacter (passwordCharacter_),
  42536. dragType (notDragging)
  42537. {
  42538. setOpaque (true);
  42539. addAndMakeVisible (viewport = new TextEditorViewport (*this));
  42540. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42541. viewport->setWantsKeyboardFocus (false);
  42542. viewport->setScrollBarsShown (false, false);
  42543. setMouseCursor (MouseCursor::IBeamCursor);
  42544. setWantsKeyboardFocus (true);
  42545. }
  42546. TextEditor::~TextEditor()
  42547. {
  42548. textValue.referTo (Value());
  42549. clearInternal (0);
  42550. viewport = 0;
  42551. textHolder = 0;
  42552. }
  42553. void TextEditor::newTransaction()
  42554. {
  42555. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42556. undoManager.beginNewTransaction();
  42557. }
  42558. void TextEditor::doUndoRedo (const bool isRedo)
  42559. {
  42560. if (! isReadOnly())
  42561. {
  42562. if (isRedo ? undoManager.redo()
  42563. : undoManager.undo())
  42564. {
  42565. scrollToMakeSureCursorIsVisible();
  42566. repaint();
  42567. textChanged();
  42568. }
  42569. }
  42570. }
  42571. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42572. const bool shouldWordWrap)
  42573. {
  42574. if (multiline != shouldBeMultiLine
  42575. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42576. {
  42577. multiline = shouldBeMultiLine;
  42578. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42579. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42580. scrollbarVisible && multiline);
  42581. viewport->setViewPosition (0, 0);
  42582. resized();
  42583. scrollToMakeSureCursorIsVisible();
  42584. }
  42585. }
  42586. bool TextEditor::isMultiLine() const
  42587. {
  42588. return multiline;
  42589. }
  42590. void TextEditor::setScrollbarsShown (bool shown)
  42591. {
  42592. if (scrollbarVisible != shown)
  42593. {
  42594. scrollbarVisible = shown;
  42595. shown = shown && isMultiLine();
  42596. viewport->setScrollBarsShown (shown, shown);
  42597. }
  42598. }
  42599. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  42600. {
  42601. if (readOnly != shouldBeReadOnly)
  42602. {
  42603. readOnly = shouldBeReadOnly;
  42604. enablementChanged();
  42605. }
  42606. }
  42607. bool TextEditor::isReadOnly() const
  42608. {
  42609. return readOnly || ! isEnabled();
  42610. }
  42611. bool TextEditor::isTextInputActive() const
  42612. {
  42613. return ! isReadOnly();
  42614. }
  42615. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  42616. {
  42617. returnKeyStartsNewLine = shouldStartNewLine;
  42618. }
  42619. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  42620. {
  42621. tabKeyUsed = shouldTabKeyBeUsed;
  42622. }
  42623. void TextEditor::setPopupMenuEnabled (const bool b)
  42624. {
  42625. popupMenuEnabled = b;
  42626. }
  42627. void TextEditor::setSelectAllWhenFocused (const bool b)
  42628. {
  42629. selectAllTextWhenFocused = b;
  42630. }
  42631. const Font TextEditor::getFont() const
  42632. {
  42633. return currentFont;
  42634. }
  42635. void TextEditor::setFont (const Font& newFont)
  42636. {
  42637. currentFont = newFont;
  42638. scrollToMakeSureCursorIsVisible();
  42639. }
  42640. void TextEditor::applyFontToAllText (const Font& newFont)
  42641. {
  42642. currentFont = newFont;
  42643. const Colour overallColour (findColour (textColourId));
  42644. for (int i = sections.size(); --i >= 0;)
  42645. {
  42646. UniformTextSection* const uts = sections.getUnchecked (i);
  42647. uts->setFont (newFont, passwordCharacter);
  42648. uts->colour = overallColour;
  42649. }
  42650. coalesceSimilarSections();
  42651. updateTextHolderSize();
  42652. scrollToMakeSureCursorIsVisible();
  42653. repaint();
  42654. }
  42655. void TextEditor::colourChanged()
  42656. {
  42657. setOpaque (findColour (backgroundColourId).isOpaque());
  42658. repaint();
  42659. }
  42660. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  42661. {
  42662. caretVisible = shouldCaretBeVisible;
  42663. if (shouldCaretBeVisible)
  42664. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42665. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  42666. : MouseCursor::NormalCursor);
  42667. }
  42668. void TextEditor::setInputRestrictions (const int maxLen,
  42669. const String& chars)
  42670. {
  42671. maxTextLength = jmax (0, maxLen);
  42672. allowedCharacters = chars;
  42673. }
  42674. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  42675. {
  42676. textToShowWhenEmpty = text;
  42677. colourForTextWhenEmpty = colourToUse;
  42678. }
  42679. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  42680. {
  42681. if (passwordCharacter != newPasswordCharacter)
  42682. {
  42683. passwordCharacter = newPasswordCharacter;
  42684. resized();
  42685. repaint();
  42686. }
  42687. }
  42688. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  42689. {
  42690. viewport->setScrollBarThickness (newThicknessPixels);
  42691. }
  42692. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  42693. {
  42694. viewport->setScrollBarButtonVisibility (buttonsVisible);
  42695. }
  42696. void TextEditor::clear()
  42697. {
  42698. clearInternal (0);
  42699. updateTextHolderSize();
  42700. undoManager.clearUndoHistory();
  42701. }
  42702. void TextEditor::setText (const String& newText,
  42703. const bool sendTextChangeMessage)
  42704. {
  42705. const int newLength = newText.length();
  42706. if (newLength != getTotalNumChars() || getText() != newText)
  42707. {
  42708. const int oldCursorPos = caretPosition;
  42709. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  42710. clearInternal (0);
  42711. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  42712. // if you're adding text with line-feeds to a single-line text editor, it
  42713. // ain't gonna look right!
  42714. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  42715. if (cursorWasAtEnd && ! isMultiLine())
  42716. moveCursorTo (getTotalNumChars(), false);
  42717. else
  42718. moveCursorTo (oldCursorPos, false);
  42719. if (sendTextChangeMessage)
  42720. textChanged();
  42721. updateTextHolderSize();
  42722. scrollToMakeSureCursorIsVisible();
  42723. undoManager.clearUndoHistory();
  42724. repaint();
  42725. }
  42726. }
  42727. Value& TextEditor::getTextValue()
  42728. {
  42729. if (valueTextNeedsUpdating)
  42730. {
  42731. valueTextNeedsUpdating = false;
  42732. textValue = getText();
  42733. }
  42734. return textValue;
  42735. }
  42736. void TextEditor::textWasChangedByValue()
  42737. {
  42738. if (textValue.getValueSource().getReferenceCount() > 1)
  42739. setText (textValue.getValue());
  42740. }
  42741. void TextEditor::textChanged()
  42742. {
  42743. updateTextHolderSize();
  42744. postCommandMessage (TextEditorDefs::textChangeMessageId);
  42745. if (textValue.getValueSource().getReferenceCount() > 1)
  42746. {
  42747. valueTextNeedsUpdating = false;
  42748. textValue = getText();
  42749. }
  42750. }
  42751. void TextEditor::returnPressed()
  42752. {
  42753. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  42754. }
  42755. void TextEditor::escapePressed()
  42756. {
  42757. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  42758. }
  42759. void TextEditor::addListener (TextEditorListener* const newListener)
  42760. {
  42761. listeners.add (newListener);
  42762. }
  42763. void TextEditor::removeListener (TextEditorListener* const listenerToRemove)
  42764. {
  42765. listeners.remove (listenerToRemove);
  42766. }
  42767. void TextEditor::timerCallbackInt()
  42768. {
  42769. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  42770. if (caretFlashState != newState)
  42771. {
  42772. caretFlashState = newState;
  42773. if (caretFlashState)
  42774. wasFocused = true;
  42775. if (caretVisible
  42776. && hasKeyboardFocus (false)
  42777. && ! isReadOnly())
  42778. {
  42779. repaintCaret();
  42780. }
  42781. }
  42782. const unsigned int now = Time::getApproximateMillisecondCounter();
  42783. if (now > lastTransactionTime + 200)
  42784. newTransaction();
  42785. }
  42786. void TextEditor::repaintCaret()
  42787. {
  42788. if (! findColour (caretColourId).isTransparent())
  42789. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  42790. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  42791. 4,
  42792. roundToInt (cursorHeight) + 2);
  42793. }
  42794. void TextEditor::repaintText (const Range<int>& range)
  42795. {
  42796. if (! range.isEmpty())
  42797. {
  42798. float x = 0, y = 0, lh = currentFont.getHeight();
  42799. const float wordWrapWidth = getWordWrapWidth();
  42800. if (wordWrapWidth > 0)
  42801. {
  42802. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42803. i.getCharPosition (range.getStart(), x, y, lh);
  42804. const int y1 = (int) y;
  42805. int y2;
  42806. if (range.getEnd() >= getTotalNumChars())
  42807. {
  42808. y2 = textHolder->getHeight();
  42809. }
  42810. else
  42811. {
  42812. i.getCharPosition (range.getEnd(), x, y, lh);
  42813. y2 = (int) (y + lh * 2.0f);
  42814. }
  42815. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  42816. }
  42817. }
  42818. }
  42819. void TextEditor::moveCaret (int newCaretPos)
  42820. {
  42821. if (newCaretPos < 0)
  42822. newCaretPos = 0;
  42823. else if (newCaretPos > getTotalNumChars())
  42824. newCaretPos = getTotalNumChars();
  42825. if (newCaretPos != getCaretPosition())
  42826. {
  42827. repaintCaret();
  42828. caretFlashState = true;
  42829. caretPosition = newCaretPos;
  42830. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  42831. scrollToMakeSureCursorIsVisible();
  42832. repaintCaret();
  42833. }
  42834. }
  42835. void TextEditor::setCaretPosition (const int newIndex)
  42836. {
  42837. moveCursorTo (newIndex, false);
  42838. }
  42839. int TextEditor::getCaretPosition() const
  42840. {
  42841. return caretPosition;
  42842. }
  42843. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  42844. const int desiredCaretY)
  42845. {
  42846. updateCaretPosition();
  42847. int vx = roundToInt (cursorX) - desiredCaretX;
  42848. int vy = roundToInt (cursorY) - desiredCaretY;
  42849. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  42850. {
  42851. vx += desiredCaretX - proportionOfWidth (0.2f);
  42852. }
  42853. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42854. {
  42855. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42856. }
  42857. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  42858. if (! isMultiLine())
  42859. {
  42860. vy = viewport->getViewPositionY();
  42861. }
  42862. else
  42863. {
  42864. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  42865. const int curH = roundToInt (cursorHeight);
  42866. if (desiredCaretY < 0)
  42867. {
  42868. vy = jmax (0, desiredCaretY + vy);
  42869. }
  42870. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42871. {
  42872. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42873. }
  42874. }
  42875. viewport->setViewPosition (vx, vy);
  42876. }
  42877. const Rectangle<int> TextEditor::getCaretRectangle()
  42878. {
  42879. updateCaretPosition();
  42880. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  42881. roundToInt (cursorY) - viewport->getY(),
  42882. 1, roundToInt (cursorHeight));
  42883. }
  42884. float TextEditor::getWordWrapWidth() const
  42885. {
  42886. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  42887. : 1.0e10f;
  42888. }
  42889. void TextEditor::updateTextHolderSize()
  42890. {
  42891. const float wordWrapWidth = getWordWrapWidth();
  42892. if (wordWrapWidth > 0)
  42893. {
  42894. float maxWidth = 0.0f;
  42895. Iterator i (sections, wordWrapWidth, passwordCharacter);
  42896. while (i.next())
  42897. maxWidth = jmax (maxWidth, i.atomRight);
  42898. const int w = leftIndent + roundToInt (maxWidth);
  42899. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  42900. currentFont.getHeight()));
  42901. textHolder->setSize (w + 1, h + 1);
  42902. }
  42903. }
  42904. int TextEditor::getTextWidth() const
  42905. {
  42906. return textHolder->getWidth();
  42907. }
  42908. int TextEditor::getTextHeight() const
  42909. {
  42910. return textHolder->getHeight();
  42911. }
  42912. void TextEditor::setIndents (const int newLeftIndent,
  42913. const int newTopIndent)
  42914. {
  42915. leftIndent = newLeftIndent;
  42916. topIndent = newTopIndent;
  42917. }
  42918. void TextEditor::setBorder (const BorderSize<int>& border)
  42919. {
  42920. borderSize = border;
  42921. resized();
  42922. }
  42923. const BorderSize<int> TextEditor::getBorder() const
  42924. {
  42925. return borderSize;
  42926. }
  42927. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  42928. {
  42929. keepCursorOnScreen = shouldScrollToShowCursor;
  42930. }
  42931. void TextEditor::updateCaretPosition()
  42932. {
  42933. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  42934. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  42935. }
  42936. void TextEditor::scrollToMakeSureCursorIsVisible()
  42937. {
  42938. updateCaretPosition();
  42939. if (keepCursorOnScreen)
  42940. {
  42941. int x = viewport->getViewPositionX();
  42942. int y = viewport->getViewPositionY();
  42943. const int relativeCursorX = roundToInt (cursorX) - x;
  42944. const int relativeCursorY = roundToInt (cursorY) - y;
  42945. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  42946. {
  42947. x += relativeCursorX - proportionOfWidth (0.2f);
  42948. }
  42949. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  42950. {
  42951. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  42952. }
  42953. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  42954. if (! isMultiLine())
  42955. {
  42956. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  42957. }
  42958. else
  42959. {
  42960. const int curH = roundToInt (cursorHeight);
  42961. if (relativeCursorY < 0)
  42962. {
  42963. y = jmax (0, relativeCursorY + y);
  42964. }
  42965. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  42966. {
  42967. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  42968. }
  42969. }
  42970. viewport->setViewPosition (x, y);
  42971. }
  42972. }
  42973. void TextEditor::moveCursorTo (const int newPosition,
  42974. const bool isSelecting)
  42975. {
  42976. if (isSelecting)
  42977. {
  42978. moveCaret (newPosition);
  42979. const Range<int> oldSelection (selection);
  42980. if (dragType == notDragging)
  42981. {
  42982. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  42983. dragType = draggingSelectionStart;
  42984. else
  42985. dragType = draggingSelectionEnd;
  42986. }
  42987. if (dragType == draggingSelectionStart)
  42988. {
  42989. if (getCaretPosition() >= selection.getEnd())
  42990. dragType = draggingSelectionEnd;
  42991. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  42992. }
  42993. else
  42994. {
  42995. if (getCaretPosition() < selection.getStart())
  42996. dragType = draggingSelectionStart;
  42997. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  42998. }
  42999. repaintText (selection.getUnionWith (oldSelection));
  43000. }
  43001. else
  43002. {
  43003. dragType = notDragging;
  43004. repaintText (selection);
  43005. moveCaret (newPosition);
  43006. selection = Range<int>::emptyRange (getCaretPosition());
  43007. }
  43008. }
  43009. int TextEditor::getTextIndexAt (const int x,
  43010. const int y)
  43011. {
  43012. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43013. (float) (y + viewport->getViewPositionY() - topIndent));
  43014. }
  43015. void TextEditor::insertTextAtCaret (const String& newText_)
  43016. {
  43017. String newText (newText_);
  43018. if (allowedCharacters.isNotEmpty())
  43019. newText = newText.retainCharacters (allowedCharacters);
  43020. if (! isMultiLine())
  43021. newText = newText.replaceCharacters ("\r\n", " ");
  43022. else
  43023. newText = newText.replace ("\r\n", "\n");
  43024. const int newCaretPos = selection.getStart() + newText.length();
  43025. const int insertIndex = selection.getStart();
  43026. remove (selection, getUndoManager(),
  43027. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43028. if (maxTextLength > 0)
  43029. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43030. if (newText.isNotEmpty())
  43031. insert (newText,
  43032. insertIndex,
  43033. currentFont,
  43034. findColour (textColourId),
  43035. getUndoManager(),
  43036. newCaretPos);
  43037. textChanged();
  43038. }
  43039. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43040. {
  43041. moveCursorTo (newSelection.getStart(), false);
  43042. moveCursorTo (newSelection.getEnd(), true);
  43043. }
  43044. void TextEditor::copy()
  43045. {
  43046. if (passwordCharacter == 0)
  43047. {
  43048. const String selectedText (getHighlightedText());
  43049. if (selectedText.isNotEmpty())
  43050. SystemClipboard::copyTextToClipboard (selectedText);
  43051. }
  43052. }
  43053. void TextEditor::paste()
  43054. {
  43055. if (! isReadOnly())
  43056. {
  43057. const String clip (SystemClipboard::getTextFromClipboard());
  43058. if (clip.isNotEmpty())
  43059. insertTextAtCaret (clip);
  43060. }
  43061. }
  43062. void TextEditor::cut()
  43063. {
  43064. if (! isReadOnly())
  43065. {
  43066. moveCaret (selection.getEnd());
  43067. insertTextAtCaret (String::empty);
  43068. }
  43069. }
  43070. void TextEditor::drawContent (Graphics& g)
  43071. {
  43072. const float wordWrapWidth = getWordWrapWidth();
  43073. if (wordWrapWidth > 0)
  43074. {
  43075. g.setOrigin (leftIndent, topIndent);
  43076. const Rectangle<int> clip (g.getClipBounds());
  43077. Colour selectedTextColour;
  43078. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43079. while (i.lineY + 200.0 < clip.getY() && i.next())
  43080. {}
  43081. if (! selection.isEmpty())
  43082. {
  43083. g.setColour (findColour (highlightColourId)
  43084. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43085. selectedTextColour = findColour (highlightedTextColourId);
  43086. Iterator i2 (i);
  43087. while (i2.next() && i2.lineY < clip.getBottom())
  43088. {
  43089. if (i2.lineY + i2.lineHeight >= clip.getY()
  43090. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43091. {
  43092. i2.drawSelection (g, selection);
  43093. }
  43094. }
  43095. }
  43096. const UniformTextSection* lastSection = 0;
  43097. while (i.next() && i.lineY < clip.getBottom())
  43098. {
  43099. if (i.lineY + i.lineHeight >= clip.getY())
  43100. {
  43101. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43102. {
  43103. i.drawSelectedText (g, selection, selectedTextColour);
  43104. lastSection = 0;
  43105. }
  43106. else
  43107. {
  43108. i.draw (g, lastSection);
  43109. }
  43110. }
  43111. }
  43112. }
  43113. }
  43114. void TextEditor::paint (Graphics& g)
  43115. {
  43116. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43117. }
  43118. void TextEditor::paintOverChildren (Graphics& g)
  43119. {
  43120. if (caretFlashState
  43121. && hasKeyboardFocus (false)
  43122. && caretVisible
  43123. && ! isReadOnly())
  43124. {
  43125. g.setColour (findColour (caretColourId));
  43126. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43127. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43128. 2.0f, cursorHeight);
  43129. }
  43130. if (textToShowWhenEmpty.isNotEmpty()
  43131. && (! hasKeyboardFocus (false))
  43132. && getTotalNumChars() == 0)
  43133. {
  43134. g.setColour (colourForTextWhenEmpty);
  43135. g.setFont (getFont());
  43136. if (isMultiLine())
  43137. {
  43138. g.drawText (textToShowWhenEmpty,
  43139. 0, 0, getWidth(), getHeight(),
  43140. Justification::centred, true);
  43141. }
  43142. else
  43143. {
  43144. g.drawText (textToShowWhenEmpty,
  43145. leftIndent, topIndent,
  43146. viewport->getWidth() - leftIndent,
  43147. viewport->getHeight() - topIndent,
  43148. Justification::centredLeft, true);
  43149. }
  43150. }
  43151. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43152. }
  43153. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43154. {
  43155. public:
  43156. TextEditorMenuPerformer (TextEditor* const editor_)
  43157. : editor (editor_)
  43158. {
  43159. }
  43160. void modalStateFinished (int returnValue)
  43161. {
  43162. if (editor != 0 && returnValue != 0)
  43163. editor->performPopupMenuAction (returnValue);
  43164. }
  43165. private:
  43166. Component::SafePointer<TextEditor> editor;
  43167. JUCE_DECLARE_NON_COPYABLE (TextEditorMenuPerformer);
  43168. };
  43169. void TextEditor::mouseDown (const MouseEvent& e)
  43170. {
  43171. beginDragAutoRepeat (100);
  43172. newTransaction();
  43173. if (wasFocused || ! selectAllTextWhenFocused)
  43174. {
  43175. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43176. {
  43177. moveCursorTo (getTextIndexAt (e.x, e.y),
  43178. e.mods.isShiftDown());
  43179. }
  43180. else
  43181. {
  43182. PopupMenu m;
  43183. m.setLookAndFeel (&getLookAndFeel());
  43184. addPopupMenuItems (m, &e);
  43185. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43186. }
  43187. }
  43188. }
  43189. void TextEditor::mouseDrag (const MouseEvent& e)
  43190. {
  43191. if (wasFocused || ! selectAllTextWhenFocused)
  43192. {
  43193. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43194. {
  43195. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43196. }
  43197. }
  43198. }
  43199. void TextEditor::mouseUp (const MouseEvent& e)
  43200. {
  43201. newTransaction();
  43202. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43203. if (wasFocused || ! selectAllTextWhenFocused)
  43204. {
  43205. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43206. {
  43207. moveCaret (getTextIndexAt (e.x, e.y));
  43208. }
  43209. }
  43210. wasFocused = true;
  43211. }
  43212. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43213. {
  43214. int tokenEnd = getTextIndexAt (e.x, e.y);
  43215. int tokenStart = tokenEnd;
  43216. if (e.getNumberOfClicks() > 3)
  43217. {
  43218. tokenStart = 0;
  43219. tokenEnd = getTotalNumChars();
  43220. }
  43221. else
  43222. {
  43223. const String t (getText());
  43224. const int totalLength = getTotalNumChars();
  43225. while (tokenEnd < totalLength)
  43226. {
  43227. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43228. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43229. ++tokenEnd;
  43230. else
  43231. break;
  43232. }
  43233. tokenStart = tokenEnd;
  43234. while (tokenStart > 0)
  43235. {
  43236. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43237. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43238. --tokenStart;
  43239. else
  43240. break;
  43241. }
  43242. if (e.getNumberOfClicks() > 2)
  43243. {
  43244. while (tokenEnd < totalLength)
  43245. {
  43246. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43247. ++tokenEnd;
  43248. else
  43249. break;
  43250. }
  43251. while (tokenStart > 0)
  43252. {
  43253. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43254. --tokenStart;
  43255. else
  43256. break;
  43257. }
  43258. }
  43259. }
  43260. moveCursorTo (tokenEnd, false);
  43261. moveCursorTo (tokenStart, true);
  43262. }
  43263. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43264. {
  43265. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43266. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43267. }
  43268. bool TextEditor::keyPressed (const KeyPress& key)
  43269. {
  43270. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43271. return false;
  43272. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43273. if (key.isKeyCode (KeyPress::leftKey)
  43274. || key.isKeyCode (KeyPress::upKey))
  43275. {
  43276. newTransaction();
  43277. int newPos;
  43278. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43279. newPos = indexAtPosition (cursorX, cursorY - 1);
  43280. else if (moveInWholeWordSteps)
  43281. newPos = findWordBreakBefore (getCaretPosition());
  43282. else
  43283. newPos = getCaretPosition() - 1;
  43284. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43285. }
  43286. else if (key.isKeyCode (KeyPress::rightKey)
  43287. || key.isKeyCode (KeyPress::downKey))
  43288. {
  43289. newTransaction();
  43290. int newPos;
  43291. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43292. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43293. else if (moveInWholeWordSteps)
  43294. newPos = findWordBreakAfter (getCaretPosition());
  43295. else
  43296. newPos = getCaretPosition() + 1;
  43297. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43298. }
  43299. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43300. {
  43301. newTransaction();
  43302. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43303. key.getModifiers().isShiftDown());
  43304. }
  43305. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43306. {
  43307. newTransaction();
  43308. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43309. key.getModifiers().isShiftDown());
  43310. }
  43311. else if (key.isKeyCode (KeyPress::homeKey))
  43312. {
  43313. newTransaction();
  43314. if (isMultiLine() && ! moveInWholeWordSteps)
  43315. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43316. key.getModifiers().isShiftDown());
  43317. else
  43318. moveCursorTo (0, key.getModifiers().isShiftDown());
  43319. }
  43320. else if (key.isKeyCode (KeyPress::endKey))
  43321. {
  43322. newTransaction();
  43323. if (isMultiLine() && ! moveInWholeWordSteps)
  43324. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43325. key.getModifiers().isShiftDown());
  43326. else
  43327. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43328. }
  43329. else if (key.isKeyCode (KeyPress::backspaceKey))
  43330. {
  43331. if (moveInWholeWordSteps)
  43332. {
  43333. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43334. }
  43335. else
  43336. {
  43337. if (selection.isEmpty() && selection.getStart() > 0)
  43338. selection.setStart (selection.getEnd() - 1);
  43339. }
  43340. cut();
  43341. }
  43342. else if (key.isKeyCode (KeyPress::deleteKey))
  43343. {
  43344. if (key.getModifiers().isShiftDown())
  43345. copy();
  43346. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43347. selection.setEnd (selection.getStart() + 1);
  43348. cut();
  43349. }
  43350. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43351. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43352. {
  43353. newTransaction();
  43354. copy();
  43355. }
  43356. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43357. {
  43358. newTransaction();
  43359. copy();
  43360. cut();
  43361. }
  43362. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43363. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43364. {
  43365. newTransaction();
  43366. paste();
  43367. }
  43368. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43369. {
  43370. newTransaction();
  43371. doUndoRedo (false);
  43372. }
  43373. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43374. {
  43375. newTransaction();
  43376. doUndoRedo (true);
  43377. }
  43378. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43379. {
  43380. newTransaction();
  43381. moveCursorTo (getTotalNumChars(), false);
  43382. moveCursorTo (0, true);
  43383. }
  43384. else if (key == KeyPress::returnKey)
  43385. {
  43386. newTransaction();
  43387. if (returnKeyStartsNewLine)
  43388. insertTextAtCaret ("\n");
  43389. else
  43390. returnPressed();
  43391. }
  43392. else if (key.isKeyCode (KeyPress::escapeKey))
  43393. {
  43394. newTransaction();
  43395. moveCursorTo (getCaretPosition(), false);
  43396. escapePressed();
  43397. }
  43398. else if (key.getTextCharacter() >= ' '
  43399. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43400. {
  43401. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43402. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43403. }
  43404. else
  43405. {
  43406. return false;
  43407. }
  43408. return true;
  43409. }
  43410. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43411. {
  43412. if (! isKeyDown)
  43413. return false;
  43414. #if JUCE_WINDOWS
  43415. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43416. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43417. #endif
  43418. // (overridden to avoid forwarding key events to the parent)
  43419. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43420. }
  43421. const int baseMenuItemID = 0x7fff0000;
  43422. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43423. {
  43424. const bool writable = ! isReadOnly();
  43425. if (passwordCharacter == 0)
  43426. {
  43427. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43428. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43429. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43430. }
  43431. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43432. m.addSeparator();
  43433. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43434. m.addSeparator();
  43435. if (getUndoManager() != 0)
  43436. {
  43437. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43438. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43439. }
  43440. }
  43441. void TextEditor::performPopupMenuAction (const int menuItemID)
  43442. {
  43443. switch (menuItemID)
  43444. {
  43445. case baseMenuItemID + 1:
  43446. copy();
  43447. cut();
  43448. break;
  43449. case baseMenuItemID + 2:
  43450. copy();
  43451. break;
  43452. case baseMenuItemID + 3:
  43453. paste();
  43454. break;
  43455. case baseMenuItemID + 4:
  43456. cut();
  43457. break;
  43458. case baseMenuItemID + 5:
  43459. moveCursorTo (getTotalNumChars(), false);
  43460. moveCursorTo (0, true);
  43461. break;
  43462. case baseMenuItemID + 6:
  43463. doUndoRedo (false);
  43464. break;
  43465. case baseMenuItemID + 7:
  43466. doUndoRedo (true);
  43467. break;
  43468. default:
  43469. break;
  43470. }
  43471. }
  43472. void TextEditor::focusGained (FocusChangeType)
  43473. {
  43474. newTransaction();
  43475. caretFlashState = true;
  43476. if (selectAllTextWhenFocused)
  43477. {
  43478. moveCursorTo (0, false);
  43479. moveCursorTo (getTotalNumChars(), true);
  43480. }
  43481. repaint();
  43482. if (caretVisible)
  43483. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43484. ComponentPeer* const peer = getPeer();
  43485. if (peer != 0 && ! isReadOnly())
  43486. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43487. }
  43488. void TextEditor::focusLost (FocusChangeType)
  43489. {
  43490. newTransaction();
  43491. wasFocused = false;
  43492. textHolder->stopTimer();
  43493. caretFlashState = false;
  43494. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43495. repaint();
  43496. }
  43497. void TextEditor::resized()
  43498. {
  43499. viewport->setBoundsInset (borderSize);
  43500. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43501. updateTextHolderSize();
  43502. if (! isMultiLine())
  43503. {
  43504. scrollToMakeSureCursorIsVisible();
  43505. }
  43506. else
  43507. {
  43508. updateCaretPosition();
  43509. }
  43510. }
  43511. void TextEditor::handleCommandMessage (const int commandId)
  43512. {
  43513. Component::BailOutChecker checker (this);
  43514. switch (commandId)
  43515. {
  43516. case TextEditorDefs::textChangeMessageId:
  43517. listeners.callChecked (checker, &TextEditorListener::textEditorTextChanged, (TextEditor&) *this);
  43518. break;
  43519. case TextEditorDefs::returnKeyMessageId:
  43520. listeners.callChecked (checker, &TextEditorListener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43521. break;
  43522. case TextEditorDefs::escapeKeyMessageId:
  43523. listeners.callChecked (checker, &TextEditorListener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43524. break;
  43525. case TextEditorDefs::focusLossMessageId:
  43526. listeners.callChecked (checker, &TextEditorListener::textEditorFocusLost, (TextEditor&) *this);
  43527. break;
  43528. default:
  43529. jassertfalse;
  43530. break;
  43531. }
  43532. }
  43533. void TextEditor::enablementChanged()
  43534. {
  43535. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43536. : MouseCursor::IBeamCursor);
  43537. repaint();
  43538. }
  43539. UndoManager* TextEditor::getUndoManager() throw()
  43540. {
  43541. return isReadOnly() ? 0 : &undoManager;
  43542. }
  43543. void TextEditor::clearInternal (UndoManager* const um)
  43544. {
  43545. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43546. }
  43547. void TextEditor::insert (const String& text,
  43548. const int insertIndex,
  43549. const Font& font,
  43550. const Colour& colour,
  43551. UndoManager* const um,
  43552. const int caretPositionToMoveTo)
  43553. {
  43554. if (text.isNotEmpty())
  43555. {
  43556. if (um != 0)
  43557. {
  43558. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43559. newTransaction();
  43560. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43561. caretPosition, caretPositionToMoveTo));
  43562. }
  43563. else
  43564. {
  43565. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43566. // a line gets moved due to word wrap
  43567. int index = 0;
  43568. int nextIndex = 0;
  43569. for (int i = 0; i < sections.size(); ++i)
  43570. {
  43571. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43572. if (insertIndex == index)
  43573. {
  43574. sections.insert (i, new UniformTextSection (text,
  43575. font, colour,
  43576. passwordCharacter));
  43577. break;
  43578. }
  43579. else if (insertIndex > index && insertIndex < nextIndex)
  43580. {
  43581. splitSection (i, insertIndex - index);
  43582. sections.insert (i + 1, new UniformTextSection (text,
  43583. font, colour,
  43584. passwordCharacter));
  43585. break;
  43586. }
  43587. index = nextIndex;
  43588. }
  43589. if (nextIndex == insertIndex)
  43590. sections.add (new UniformTextSection (text,
  43591. font, colour,
  43592. passwordCharacter));
  43593. coalesceSimilarSections();
  43594. totalNumChars = -1;
  43595. valueTextNeedsUpdating = true;
  43596. moveCursorTo (caretPositionToMoveTo, false);
  43597. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  43598. }
  43599. }
  43600. }
  43601. void TextEditor::reinsert (const int insertIndex,
  43602. const Array <UniformTextSection*>& sectionsToInsert)
  43603. {
  43604. int index = 0;
  43605. int nextIndex = 0;
  43606. for (int i = 0; i < sections.size(); ++i)
  43607. {
  43608. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43609. if (insertIndex == index)
  43610. {
  43611. for (int j = sectionsToInsert.size(); --j >= 0;)
  43612. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43613. break;
  43614. }
  43615. else if (insertIndex > index && insertIndex < nextIndex)
  43616. {
  43617. splitSection (i, insertIndex - index);
  43618. for (int j = sectionsToInsert.size(); --j >= 0;)
  43619. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43620. break;
  43621. }
  43622. index = nextIndex;
  43623. }
  43624. if (nextIndex == insertIndex)
  43625. {
  43626. for (int j = 0; j < sectionsToInsert.size(); ++j)
  43627. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  43628. }
  43629. coalesceSimilarSections();
  43630. totalNumChars = -1;
  43631. valueTextNeedsUpdating = true;
  43632. }
  43633. void TextEditor::remove (const Range<int>& range,
  43634. UndoManager* const um,
  43635. const int caretPositionToMoveTo)
  43636. {
  43637. if (! range.isEmpty())
  43638. {
  43639. int index = 0;
  43640. for (int i = 0; i < sections.size(); ++i)
  43641. {
  43642. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  43643. if (range.getStart() > index && range.getStart() < nextIndex)
  43644. {
  43645. splitSection (i, range.getStart() - index);
  43646. --i;
  43647. }
  43648. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  43649. {
  43650. splitSection (i, range.getEnd() - index);
  43651. --i;
  43652. }
  43653. else
  43654. {
  43655. index = nextIndex;
  43656. if (index > range.getEnd())
  43657. break;
  43658. }
  43659. }
  43660. index = 0;
  43661. if (um != 0)
  43662. {
  43663. Array <UniformTextSection*> removedSections;
  43664. for (int i = 0; i < sections.size(); ++i)
  43665. {
  43666. if (range.getEnd() <= range.getStart())
  43667. break;
  43668. UniformTextSection* const section = sections.getUnchecked (i);
  43669. const int nextIndex = index + section->getTotalLength();
  43670. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  43671. removedSections.add (new UniformTextSection (*section));
  43672. index = nextIndex;
  43673. }
  43674. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43675. newTransaction();
  43676. um->perform (new RemoveAction (*this, range, caretPosition,
  43677. caretPositionToMoveTo, removedSections));
  43678. }
  43679. else
  43680. {
  43681. Range<int> remainingRange (range);
  43682. for (int i = 0; i < sections.size(); ++i)
  43683. {
  43684. UniformTextSection* const section = sections.getUnchecked (i);
  43685. const int nextIndex = index + section->getTotalLength();
  43686. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  43687. {
  43688. sections.remove(i);
  43689. section->clear();
  43690. delete section;
  43691. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  43692. if (remainingRange.isEmpty())
  43693. break;
  43694. --i;
  43695. }
  43696. else
  43697. {
  43698. index = nextIndex;
  43699. }
  43700. }
  43701. coalesceSimilarSections();
  43702. totalNumChars = -1;
  43703. valueTextNeedsUpdating = true;
  43704. moveCursorTo (caretPositionToMoveTo, false);
  43705. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  43706. }
  43707. }
  43708. }
  43709. const String TextEditor::getText() const
  43710. {
  43711. String t;
  43712. t.preallocateStorage (getTotalNumChars());
  43713. String::Concatenator concatenator (t);
  43714. for (int i = 0; i < sections.size(); ++i)
  43715. sections.getUnchecked (i)->appendAllText (concatenator);
  43716. return t;
  43717. }
  43718. const String TextEditor::getTextInRange (const Range<int>& range) const
  43719. {
  43720. String t;
  43721. if (! range.isEmpty())
  43722. {
  43723. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  43724. String::Concatenator concatenator (t);
  43725. int index = 0;
  43726. for (int i = 0; i < sections.size(); ++i)
  43727. {
  43728. const UniformTextSection* const s = sections.getUnchecked (i);
  43729. const int nextIndex = index + s->getTotalLength();
  43730. if (range.getStart() < nextIndex)
  43731. {
  43732. if (range.getEnd() <= index)
  43733. break;
  43734. s->appendSubstring (concatenator, range - index);
  43735. }
  43736. index = nextIndex;
  43737. }
  43738. }
  43739. return t;
  43740. }
  43741. const String TextEditor::getHighlightedText() const
  43742. {
  43743. return getTextInRange (selection);
  43744. }
  43745. int TextEditor::getTotalNumChars() const
  43746. {
  43747. if (totalNumChars < 0)
  43748. {
  43749. totalNumChars = 0;
  43750. for (int i = sections.size(); --i >= 0;)
  43751. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  43752. }
  43753. return totalNumChars;
  43754. }
  43755. bool TextEditor::isEmpty() const
  43756. {
  43757. return getTotalNumChars() == 0;
  43758. }
  43759. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  43760. {
  43761. const float wordWrapWidth = getWordWrapWidth();
  43762. if (wordWrapWidth > 0 && sections.size() > 0)
  43763. {
  43764. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43765. i.getCharPosition (index, cx, cy, lineHeight);
  43766. }
  43767. else
  43768. {
  43769. cx = cy = 0;
  43770. lineHeight = currentFont.getHeight();
  43771. }
  43772. }
  43773. int TextEditor::indexAtPosition (const float x, const float y)
  43774. {
  43775. const float wordWrapWidth = getWordWrapWidth();
  43776. if (wordWrapWidth > 0)
  43777. {
  43778. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43779. while (i.next())
  43780. {
  43781. if (i.lineY + i.lineHeight > y)
  43782. {
  43783. if (i.lineY > y)
  43784. return jmax (0, i.indexInText - 1);
  43785. if (i.atomX >= x)
  43786. return i.indexInText;
  43787. if (x < i.atomRight)
  43788. return i.xToIndex (x);
  43789. }
  43790. }
  43791. }
  43792. return getTotalNumChars();
  43793. }
  43794. int TextEditor::findWordBreakAfter (const int position) const
  43795. {
  43796. const String t (getTextInRange (Range<int> (position, position + 512)));
  43797. const int totalLength = t.length();
  43798. int i = 0;
  43799. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43800. ++i;
  43801. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  43802. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  43803. ++i;
  43804. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  43805. ++i;
  43806. return position + i;
  43807. }
  43808. int TextEditor::findWordBreakBefore (const int position) const
  43809. {
  43810. if (position <= 0)
  43811. return 0;
  43812. const int startOfBuffer = jmax (0, position - 512);
  43813. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  43814. int i = position - startOfBuffer;
  43815. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  43816. --i;
  43817. if (i > 0)
  43818. {
  43819. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  43820. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  43821. --i;
  43822. }
  43823. jassert (startOfBuffer + i >= 0);
  43824. return startOfBuffer + i;
  43825. }
  43826. void TextEditor::splitSection (const int sectionIndex,
  43827. const int charToSplitAt)
  43828. {
  43829. jassert (sections[sectionIndex] != 0);
  43830. sections.insert (sectionIndex + 1,
  43831. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  43832. }
  43833. void TextEditor::coalesceSimilarSections()
  43834. {
  43835. for (int i = 0; i < sections.size() - 1; ++i)
  43836. {
  43837. UniformTextSection* const s1 = sections.getUnchecked (i);
  43838. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  43839. if (s1->font == s2->font
  43840. && s1->colour == s2->colour)
  43841. {
  43842. s1->append (*s2, passwordCharacter);
  43843. sections.remove (i + 1);
  43844. delete s2;
  43845. --i;
  43846. }
  43847. }
  43848. }
  43849. void TextEditor::Listener::textEditorTextChanged (TextEditor&) {}
  43850. void TextEditor::Listener::textEditorReturnKeyPressed (TextEditor&) {}
  43851. void TextEditor::Listener::textEditorEscapeKeyPressed (TextEditor&) {}
  43852. void TextEditor::Listener::textEditorFocusLost (TextEditor&) {}
  43853. END_JUCE_NAMESPACE
  43854. /*** End of inlined file: juce_TextEditor.cpp ***/
  43855. /*** Start of inlined file: juce_Toolbar.cpp ***/
  43856. BEGIN_JUCE_NAMESPACE
  43857. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  43858. class ToolbarSpacerComp : public ToolbarItemComponent
  43859. {
  43860. public:
  43861. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  43862. : ToolbarItemComponent (itemId_, String::empty, false),
  43863. fixedSize (fixedSize_),
  43864. drawBar (drawBar_)
  43865. {
  43866. }
  43867. ~ToolbarSpacerComp()
  43868. {
  43869. }
  43870. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  43871. int& preferredSize, int& minSize, int& maxSize)
  43872. {
  43873. if (fixedSize <= 0)
  43874. {
  43875. preferredSize = toolbarThickness * 2;
  43876. minSize = 4;
  43877. maxSize = 32768;
  43878. }
  43879. else
  43880. {
  43881. maxSize = roundToInt (toolbarThickness * fixedSize);
  43882. minSize = drawBar ? maxSize : jmin (4, maxSize);
  43883. preferredSize = maxSize;
  43884. if (getEditingMode() == editableOnPalette)
  43885. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  43886. }
  43887. return true;
  43888. }
  43889. void paintButtonArea (Graphics&, int, int, bool, bool)
  43890. {
  43891. }
  43892. void contentAreaChanged (const Rectangle<int>&)
  43893. {
  43894. }
  43895. int getResizeOrder() const throw()
  43896. {
  43897. return fixedSize <= 0 ? 0 : 1;
  43898. }
  43899. void paint (Graphics& g)
  43900. {
  43901. const int w = getWidth();
  43902. const int h = getHeight();
  43903. if (drawBar)
  43904. {
  43905. g.setColour (findColour (Toolbar::separatorColourId, true));
  43906. const float thickness = 0.2f;
  43907. if (isToolbarVertical())
  43908. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  43909. else
  43910. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  43911. }
  43912. if (getEditingMode() != normalMode && ! drawBar)
  43913. {
  43914. g.setColour (findColour (Toolbar::separatorColourId, true));
  43915. const int indentX = jmin (2, (w - 3) / 2);
  43916. const int indentY = jmin (2, (h - 3) / 2);
  43917. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  43918. if (fixedSize <= 0)
  43919. {
  43920. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  43921. if (isToolbarVertical())
  43922. {
  43923. x1 = w * 0.5f;
  43924. y1 = h * 0.4f;
  43925. x2 = x1;
  43926. y2 = indentX * 2.0f;
  43927. x3 = x1;
  43928. y3 = h * 0.6f;
  43929. x4 = x1;
  43930. y4 = h - y2;
  43931. hw = w * 0.15f;
  43932. hl = w * 0.2f;
  43933. }
  43934. else
  43935. {
  43936. x1 = w * 0.4f;
  43937. y1 = h * 0.5f;
  43938. x2 = indentX * 2.0f;
  43939. y2 = y1;
  43940. x3 = w * 0.6f;
  43941. y3 = y1;
  43942. x4 = w - x2;
  43943. y4 = y1;
  43944. hw = h * 0.15f;
  43945. hl = h * 0.2f;
  43946. }
  43947. Path p;
  43948. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  43949. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  43950. g.fillPath (p);
  43951. }
  43952. }
  43953. }
  43954. private:
  43955. const float fixedSize;
  43956. const bool drawBar;
  43957. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ToolbarSpacerComp);
  43958. };
  43959. class Toolbar::MissingItemsComponent : public PopupMenu::CustomComponent
  43960. {
  43961. public:
  43962. MissingItemsComponent (Toolbar& owner_, const int height_)
  43963. : PopupMenu::CustomComponent (true),
  43964. owner (&owner_),
  43965. height (height_)
  43966. {
  43967. for (int i = owner_.items.size(); --i >= 0;)
  43968. {
  43969. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  43970. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  43971. {
  43972. oldIndexes.insert (0, i);
  43973. addAndMakeVisible (tc, 0);
  43974. }
  43975. }
  43976. layout (400);
  43977. }
  43978. ~MissingItemsComponent()
  43979. {
  43980. if (owner != 0)
  43981. {
  43982. for (int i = 0; i < getNumChildComponents(); ++i)
  43983. {
  43984. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  43985. if (tc != 0)
  43986. {
  43987. tc->setVisible (false);
  43988. const int index = oldIndexes.remove (i);
  43989. owner->addChildComponent (tc, index);
  43990. --i;
  43991. }
  43992. }
  43993. owner->resized();
  43994. }
  43995. }
  43996. void layout (const int preferredWidth)
  43997. {
  43998. const int indent = 8;
  43999. int x = indent;
  44000. int y = indent;
  44001. int maxX = 0;
  44002. for (int i = 0; i < getNumChildComponents(); ++i)
  44003. {
  44004. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44005. if (tc != 0)
  44006. {
  44007. int preferredSize = 1, minSize = 1, maxSize = 1;
  44008. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44009. {
  44010. if (x + preferredSize > preferredWidth && x > indent)
  44011. {
  44012. x = indent;
  44013. y += height;
  44014. }
  44015. tc->setBounds (x, y, preferredSize, height);
  44016. x += preferredSize;
  44017. maxX = jmax (maxX, x);
  44018. }
  44019. }
  44020. }
  44021. setSize (maxX + 8, y + height + 8);
  44022. }
  44023. void getIdealSize (int& idealWidth, int& idealHeight)
  44024. {
  44025. idealWidth = getWidth();
  44026. idealHeight = getHeight();
  44027. }
  44028. private:
  44029. Component::SafePointer<Toolbar> owner;
  44030. const int height;
  44031. Array <int> oldIndexes;
  44032. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MissingItemsComponent);
  44033. };
  44034. Toolbar::Toolbar()
  44035. : vertical (false),
  44036. isEditingActive (false),
  44037. toolbarStyle (Toolbar::iconsOnly)
  44038. {
  44039. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44040. missingItemsButton->setAlwaysOnTop (true);
  44041. missingItemsButton->addListener (this);
  44042. }
  44043. Toolbar::~Toolbar()
  44044. {
  44045. items.clear();
  44046. }
  44047. void Toolbar::setVertical (const bool shouldBeVertical)
  44048. {
  44049. if (vertical != shouldBeVertical)
  44050. {
  44051. vertical = shouldBeVertical;
  44052. resized();
  44053. }
  44054. }
  44055. void Toolbar::clear()
  44056. {
  44057. items.clear();
  44058. resized();
  44059. }
  44060. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44061. {
  44062. if (itemId == ToolbarItemFactory::separatorBarId)
  44063. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44064. else if (itemId == ToolbarItemFactory::spacerId)
  44065. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44066. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44067. return new ToolbarSpacerComp (itemId, 0, false);
  44068. return factory.createItem (itemId);
  44069. }
  44070. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44071. const int itemId,
  44072. const int insertIndex)
  44073. {
  44074. // An ID can't be zero - this might indicate a mistake somewhere?
  44075. jassert (itemId != 0);
  44076. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44077. if (tc != 0)
  44078. {
  44079. #if JUCE_DEBUG
  44080. Array <int> allowedIds;
  44081. factory.getAllToolbarItemIds (allowedIds);
  44082. // If your factory can create an item for a given ID, it must also return
  44083. // that ID from its getAllToolbarItemIds() method!
  44084. jassert (allowedIds.contains (itemId));
  44085. #endif
  44086. items.insert (insertIndex, tc);
  44087. addAndMakeVisible (tc, insertIndex);
  44088. }
  44089. }
  44090. void Toolbar::addItem (ToolbarItemFactory& factory,
  44091. const int itemId,
  44092. const int insertIndex)
  44093. {
  44094. addItemInternal (factory, itemId, insertIndex);
  44095. resized();
  44096. }
  44097. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44098. {
  44099. Array <int> ids;
  44100. factoryToUse.getDefaultItemSet (ids);
  44101. clear();
  44102. for (int i = 0; i < ids.size(); ++i)
  44103. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44104. resized();
  44105. }
  44106. void Toolbar::removeToolbarItem (const int itemIndex)
  44107. {
  44108. items.remove (itemIndex);
  44109. resized();
  44110. }
  44111. int Toolbar::getNumItems() const throw()
  44112. {
  44113. return items.size();
  44114. }
  44115. int Toolbar::getItemId (const int itemIndex) const throw()
  44116. {
  44117. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44118. return tc != 0 ? tc->getItemId() : 0;
  44119. }
  44120. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44121. {
  44122. return items [itemIndex];
  44123. }
  44124. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44125. {
  44126. for (;;)
  44127. {
  44128. index += delta;
  44129. ToolbarItemComponent* const tc = getItemComponent (index);
  44130. if (tc == 0)
  44131. break;
  44132. if (tc->isActive)
  44133. return tc;
  44134. }
  44135. return 0;
  44136. }
  44137. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44138. {
  44139. if (toolbarStyle != newStyle)
  44140. {
  44141. toolbarStyle = newStyle;
  44142. updateAllItemPositions (false);
  44143. }
  44144. }
  44145. const String Toolbar::toString() const
  44146. {
  44147. String s ("TB:");
  44148. for (int i = 0; i < getNumItems(); ++i)
  44149. s << getItemId(i) << ' ';
  44150. return s.trimEnd();
  44151. }
  44152. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44153. const String& savedVersion)
  44154. {
  44155. if (! savedVersion.startsWith ("TB:"))
  44156. return false;
  44157. StringArray tokens;
  44158. tokens.addTokens (savedVersion.substring (3), false);
  44159. clear();
  44160. for (int i = 0; i < tokens.size(); ++i)
  44161. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44162. resized();
  44163. return true;
  44164. }
  44165. void Toolbar::paint (Graphics& g)
  44166. {
  44167. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44168. }
  44169. int Toolbar::getThickness() const throw()
  44170. {
  44171. return vertical ? getWidth() : getHeight();
  44172. }
  44173. int Toolbar::getLength() const throw()
  44174. {
  44175. return vertical ? getHeight() : getWidth();
  44176. }
  44177. void Toolbar::setEditingActive (const bool active)
  44178. {
  44179. if (isEditingActive != active)
  44180. {
  44181. isEditingActive = active;
  44182. updateAllItemPositions (false);
  44183. }
  44184. }
  44185. void Toolbar::resized()
  44186. {
  44187. updateAllItemPositions (false);
  44188. }
  44189. void Toolbar::updateAllItemPositions (const bool animate)
  44190. {
  44191. if (getWidth() > 0 && getHeight() > 0)
  44192. {
  44193. StretchableObjectResizer resizer;
  44194. int i;
  44195. for (i = 0; i < items.size(); ++i)
  44196. {
  44197. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44198. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44199. : ToolbarItemComponent::normalMode);
  44200. tc->setStyle (toolbarStyle);
  44201. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44202. int preferredSize = 1, minSize = 1, maxSize = 1;
  44203. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44204. preferredSize, minSize, maxSize))
  44205. {
  44206. tc->isActive = true;
  44207. resizer.addItem (preferredSize, minSize, maxSize,
  44208. spacer != 0 ? spacer->getResizeOrder() : 2);
  44209. }
  44210. else
  44211. {
  44212. tc->isActive = false;
  44213. tc->setVisible (false);
  44214. }
  44215. }
  44216. resizer.resizeToFit (getLength());
  44217. int totalLength = 0;
  44218. for (i = 0; i < resizer.getNumItems(); ++i)
  44219. totalLength += (int) resizer.getItemSize (i);
  44220. const bool itemsOffTheEnd = totalLength > getLength();
  44221. const int extrasButtonSize = getThickness() / 2;
  44222. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44223. missingItemsButton->setVisible (itemsOffTheEnd);
  44224. missingItemsButton->setEnabled (! isEditingActive);
  44225. if (vertical)
  44226. missingItemsButton->setCentrePosition (getWidth() / 2,
  44227. getHeight() - 4 - extrasButtonSize / 2);
  44228. else
  44229. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44230. getHeight() / 2);
  44231. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44232. : missingItemsButton->getX()) - 4
  44233. : getLength();
  44234. int pos = 0, activeIndex = 0;
  44235. for (i = 0; i < items.size(); ++i)
  44236. {
  44237. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44238. if (tc->isActive)
  44239. {
  44240. const int size = (int) resizer.getItemSize (activeIndex++);
  44241. Rectangle<int> newBounds;
  44242. if (vertical)
  44243. newBounds.setBounds (0, pos, getWidth(), size);
  44244. else
  44245. newBounds.setBounds (pos, 0, size, getHeight());
  44246. if (animate)
  44247. {
  44248. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44249. }
  44250. else
  44251. {
  44252. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44253. tc->setBounds (newBounds);
  44254. }
  44255. pos += size;
  44256. tc->setVisible (pos <= maxLength
  44257. && ((! tc->isBeingDragged)
  44258. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44259. }
  44260. }
  44261. }
  44262. }
  44263. void Toolbar::buttonClicked (Button*)
  44264. {
  44265. jassert (missingItemsButton->isShowing());
  44266. if (missingItemsButton->isShowing())
  44267. {
  44268. PopupMenu m;
  44269. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44270. m.showAt (missingItemsButton);
  44271. }
  44272. }
  44273. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44274. Component* /*sourceComponent*/)
  44275. {
  44276. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44277. }
  44278. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44279. {
  44280. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44281. if (tc != 0)
  44282. {
  44283. if (! items.contains (tc))
  44284. {
  44285. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44286. {
  44287. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44288. if (palette != 0)
  44289. palette->replaceComponent (tc);
  44290. }
  44291. else
  44292. {
  44293. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44294. }
  44295. items.add (tc);
  44296. addChildComponent (tc);
  44297. updateAllItemPositions (true);
  44298. }
  44299. for (int i = getNumItems(); --i >= 0;)
  44300. {
  44301. const int currentIndex = items.indexOf (tc);
  44302. int newIndex = currentIndex;
  44303. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44304. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44305. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44306. .getComponentDestination (getChildComponent (newIndex)));
  44307. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44308. if (prev != 0)
  44309. {
  44310. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44311. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44312. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44313. {
  44314. newIndex = getIndexOfChildComponent (prev);
  44315. }
  44316. }
  44317. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44318. if (next != 0)
  44319. {
  44320. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44321. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44322. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44323. {
  44324. newIndex = getIndexOfChildComponent (next) + 1;
  44325. }
  44326. }
  44327. if (newIndex == currentIndex)
  44328. break;
  44329. items.removeObject (tc, false);
  44330. removeChildComponent (tc);
  44331. addChildComponent (tc, newIndex);
  44332. items.insert (newIndex, tc);
  44333. updateAllItemPositions (true);
  44334. }
  44335. }
  44336. }
  44337. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44338. {
  44339. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44340. if (tc != 0 && isParentOf (tc))
  44341. {
  44342. items.removeObject (tc, false);
  44343. removeChildComponent (tc);
  44344. updateAllItemPositions (true);
  44345. }
  44346. }
  44347. void Toolbar::itemDropped (const String&, Component* sourceComponent, int, int)
  44348. {
  44349. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44350. if (tc != 0)
  44351. tc->setState (Button::buttonNormal);
  44352. }
  44353. void Toolbar::mouseDown (const MouseEvent&)
  44354. {
  44355. }
  44356. class ToolbarCustomisationDialog : public DialogWindow
  44357. {
  44358. public:
  44359. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44360. Toolbar* const toolbar_,
  44361. const int optionFlags)
  44362. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44363. toolbar (toolbar_)
  44364. {
  44365. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44366. setResizable (true, true);
  44367. setResizeLimits (400, 300, 1500, 1000);
  44368. positionNearBar();
  44369. }
  44370. ~ToolbarCustomisationDialog()
  44371. {
  44372. setContentComponent (0, true);
  44373. }
  44374. void closeButtonPressed()
  44375. {
  44376. setVisible (false);
  44377. }
  44378. bool canModalEventBeSentToComponent (const Component* comp)
  44379. {
  44380. return toolbar->isParentOf (comp);
  44381. }
  44382. void positionNearBar()
  44383. {
  44384. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44385. const int tbx = toolbar->getScreenX();
  44386. const int tby = toolbar->getScreenY();
  44387. const int gap = 8;
  44388. int x, y;
  44389. if (toolbar->isVertical())
  44390. {
  44391. y = tby;
  44392. if (tbx > screenSize.getCentreX())
  44393. x = tbx - getWidth() - gap;
  44394. else
  44395. x = tbx + toolbar->getWidth() + gap;
  44396. }
  44397. else
  44398. {
  44399. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44400. if (tby > screenSize.getCentreY())
  44401. y = tby - getHeight() - gap;
  44402. else
  44403. y = tby + toolbar->getHeight() + gap;
  44404. }
  44405. setTopLeftPosition (x, y);
  44406. }
  44407. private:
  44408. Toolbar* const toolbar;
  44409. class CustomiserPanel : public Component,
  44410. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44411. private ButtonListener
  44412. {
  44413. public:
  44414. CustomiserPanel (ToolbarItemFactory& factory_,
  44415. Toolbar* const toolbar_,
  44416. const int optionFlags)
  44417. : factory (factory_),
  44418. toolbar (toolbar_),
  44419. palette (factory_, toolbar_),
  44420. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44421. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44422. defaultButton (TRANS ("Restore to default set of items"))
  44423. {
  44424. addAndMakeVisible (&palette);
  44425. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44426. | Toolbar::allowIconsWithTextChoice
  44427. | Toolbar::allowTextOnlyChoice)) != 0)
  44428. {
  44429. addAndMakeVisible (&styleBox);
  44430. styleBox.setEditableText (false);
  44431. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44432. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44433. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44434. int selectedStyle = 0;
  44435. switch (toolbar_->getStyle())
  44436. {
  44437. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44438. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44439. case Toolbar::textOnly: selectedStyle = 3; break;
  44440. }
  44441. styleBox.setSelectedId (selectedStyle);
  44442. styleBox.addListener (this);
  44443. }
  44444. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44445. {
  44446. addAndMakeVisible (&defaultButton);
  44447. defaultButton.addListener (this);
  44448. }
  44449. addAndMakeVisible (&instructions);
  44450. instructions.setFont (Font (13.0f));
  44451. setSize (500, 300);
  44452. }
  44453. void comboBoxChanged (ComboBox*)
  44454. {
  44455. switch (styleBox.getSelectedId())
  44456. {
  44457. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44458. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44459. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44460. }
  44461. palette.resized(); // to make it update the styles
  44462. }
  44463. void buttonClicked (Button*)
  44464. {
  44465. toolbar->addDefaultItems (factory);
  44466. }
  44467. void paint (Graphics& g)
  44468. {
  44469. Colour background;
  44470. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44471. if (dw != 0)
  44472. background = dw->getBackgroundColour();
  44473. g.setColour (background.contrasting().withAlpha (0.3f));
  44474. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44475. }
  44476. void resized()
  44477. {
  44478. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44479. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44480. defaultButton.changeWidthToFitText (22);
  44481. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44482. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44483. }
  44484. private:
  44485. ToolbarItemFactory& factory;
  44486. Toolbar* const toolbar;
  44487. ToolbarItemPalette palette;
  44488. Label instructions;
  44489. ComboBox styleBox;
  44490. TextButton defaultButton;
  44491. };
  44492. };
  44493. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44494. {
  44495. setEditingActive (true);
  44496. #if JUCE_DEBUG
  44497. WeakReference<Component> checker (this);
  44498. #endif
  44499. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44500. dw.runModalLoop();
  44501. #if JUCE_DEBUG
  44502. jassert (checker != 0); // Don't delete the toolbar while it's being customised!
  44503. #endif
  44504. setEditingActive (false);
  44505. }
  44506. END_JUCE_NAMESPACE
  44507. /*** End of inlined file: juce_Toolbar.cpp ***/
  44508. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44509. BEGIN_JUCE_NAMESPACE
  44510. ToolbarItemFactory::ToolbarItemFactory()
  44511. {
  44512. }
  44513. ToolbarItemFactory::~ToolbarItemFactory()
  44514. {
  44515. }
  44516. class ItemDragAndDropOverlayComponent : public Component
  44517. {
  44518. public:
  44519. ItemDragAndDropOverlayComponent()
  44520. : isDragging (false)
  44521. {
  44522. setAlwaysOnTop (true);
  44523. setRepaintsOnMouseActivity (true);
  44524. setMouseCursor (MouseCursor::DraggingHandCursor);
  44525. }
  44526. void paint (Graphics& g)
  44527. {
  44528. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44529. if (isMouseOverOrDragging()
  44530. && tc != 0
  44531. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44532. {
  44533. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44534. g.drawRect (0, 0, getWidth(), getHeight(),
  44535. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44536. }
  44537. }
  44538. void mouseDown (const MouseEvent& e)
  44539. {
  44540. isDragging = false;
  44541. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44542. if (tc != 0)
  44543. {
  44544. tc->dragOffsetX = e.x;
  44545. tc->dragOffsetY = e.y;
  44546. }
  44547. }
  44548. void mouseDrag (const MouseEvent& e)
  44549. {
  44550. if (! (isDragging || e.mouseWasClicked()))
  44551. {
  44552. isDragging = true;
  44553. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  44554. if (dnd != 0)
  44555. {
  44556. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  44557. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44558. if (tc != 0)
  44559. {
  44560. tc->isBeingDragged = true;
  44561. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44562. tc->setVisible (false);
  44563. }
  44564. }
  44565. }
  44566. }
  44567. void mouseUp (const MouseEvent&)
  44568. {
  44569. isDragging = false;
  44570. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44571. if (tc != 0)
  44572. {
  44573. tc->isBeingDragged = false;
  44574. Toolbar* const tb = tc->getToolbar();
  44575. if (tb != 0)
  44576. tb->updateAllItemPositions (true);
  44577. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44578. delete tc;
  44579. }
  44580. }
  44581. void parentSizeChanged()
  44582. {
  44583. setBounds (0, 0, getParentWidth(), getParentHeight());
  44584. }
  44585. private:
  44586. bool isDragging;
  44587. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemDragAndDropOverlayComponent);
  44588. };
  44589. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  44590. const String& labelText,
  44591. const bool isBeingUsedAsAButton_)
  44592. : Button (labelText),
  44593. itemId (itemId_),
  44594. mode (normalMode),
  44595. toolbarStyle (Toolbar::iconsOnly),
  44596. dragOffsetX (0),
  44597. dragOffsetY (0),
  44598. isActive (true),
  44599. isBeingDragged (false),
  44600. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  44601. {
  44602. // Your item ID can't be 0!
  44603. jassert (itemId_ != 0);
  44604. }
  44605. ToolbarItemComponent::~ToolbarItemComponent()
  44606. {
  44607. overlayComp = 0;
  44608. }
  44609. Toolbar* ToolbarItemComponent::getToolbar() const
  44610. {
  44611. return dynamic_cast <Toolbar*> (getParentComponent());
  44612. }
  44613. bool ToolbarItemComponent::isToolbarVertical() const
  44614. {
  44615. const Toolbar* const t = getToolbar();
  44616. return t != 0 && t->isVertical();
  44617. }
  44618. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  44619. {
  44620. if (toolbarStyle != newStyle)
  44621. {
  44622. toolbarStyle = newStyle;
  44623. repaint();
  44624. resized();
  44625. }
  44626. }
  44627. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  44628. {
  44629. if (isBeingUsedAsAButton)
  44630. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  44631. over, down, *this);
  44632. if (toolbarStyle != Toolbar::iconsOnly)
  44633. {
  44634. const int indent = contentArea.getX();
  44635. int y = indent;
  44636. int h = getHeight() - indent * 2;
  44637. if (toolbarStyle == Toolbar::iconsWithText)
  44638. {
  44639. y = contentArea.getBottom() + indent / 2;
  44640. h -= contentArea.getHeight();
  44641. }
  44642. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  44643. getButtonText(), *this);
  44644. }
  44645. if (! contentArea.isEmpty())
  44646. {
  44647. Graphics::ScopedSaveState ss (g);
  44648. g.reduceClipRegion (contentArea);
  44649. g.setOrigin (contentArea.getX(), contentArea.getY());
  44650. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  44651. }
  44652. }
  44653. void ToolbarItemComponent::resized()
  44654. {
  44655. if (toolbarStyle != Toolbar::textOnly)
  44656. {
  44657. const int indent = jmin (proportionOfWidth (0.08f),
  44658. proportionOfHeight (0.08f));
  44659. contentArea = Rectangle<int> (indent, indent,
  44660. getWidth() - indent * 2,
  44661. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  44662. : (getHeight() - indent * 2));
  44663. }
  44664. else
  44665. {
  44666. contentArea = Rectangle<int>();
  44667. }
  44668. contentAreaChanged (contentArea);
  44669. }
  44670. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  44671. {
  44672. if (mode != newMode)
  44673. {
  44674. mode = newMode;
  44675. repaint();
  44676. if (mode == normalMode)
  44677. {
  44678. overlayComp = 0;
  44679. }
  44680. else if (overlayComp == 0)
  44681. {
  44682. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  44683. overlayComp->parentSizeChanged();
  44684. }
  44685. resized();
  44686. }
  44687. }
  44688. END_JUCE_NAMESPACE
  44689. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  44690. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  44691. BEGIN_JUCE_NAMESPACE
  44692. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  44693. Toolbar* const toolbar_)
  44694. : factory (factory_),
  44695. toolbar (toolbar_)
  44696. {
  44697. Component* const itemHolder = new Component();
  44698. viewport.setViewedComponent (itemHolder);
  44699. Array <int> allIds;
  44700. factory.getAllToolbarItemIds (allIds);
  44701. for (int i = 0; i < allIds.size(); ++i)
  44702. addComponent (allIds.getUnchecked (i), -1);
  44703. addAndMakeVisible (&viewport);
  44704. }
  44705. ToolbarItemPalette::~ToolbarItemPalette()
  44706. {
  44707. }
  44708. void ToolbarItemPalette::addComponent (const int itemId, const int index)
  44709. {
  44710. ToolbarItemComponent* const tc = Toolbar::createItem (factory, itemId);
  44711. jassert (tc != 0);
  44712. if (tc != 0)
  44713. {
  44714. items.insert (index, tc);
  44715. viewport.getViewedComponent()->addAndMakeVisible (tc, index);
  44716. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  44717. }
  44718. }
  44719. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  44720. {
  44721. const int index = items.indexOf (comp);
  44722. jassert (index >= 0);
  44723. items.removeObject (comp, false);
  44724. addComponent (comp->getItemId(), index);
  44725. resized();
  44726. }
  44727. void ToolbarItemPalette::resized()
  44728. {
  44729. viewport.setBoundsInset (BorderSize<int> (1));
  44730. Component* const itemHolder = viewport.getViewedComponent();
  44731. const int indent = 8;
  44732. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  44733. const int height = toolbar->getThickness();
  44734. int x = indent;
  44735. int y = indent;
  44736. int maxX = 0;
  44737. for (int i = 0; i < items.size(); ++i)
  44738. {
  44739. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44740. tc->setStyle (toolbar->getStyle());
  44741. int preferredSize = 1, minSize = 1, maxSize = 1;
  44742. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44743. {
  44744. if (x + preferredSize > preferredWidth && x > indent)
  44745. {
  44746. x = indent;
  44747. y += height;
  44748. }
  44749. tc->setBounds (x, y, preferredSize, height);
  44750. x += preferredSize + 8;
  44751. maxX = jmax (maxX, x);
  44752. }
  44753. }
  44754. itemHolder->setSize (maxX, y + height + 8);
  44755. }
  44756. END_JUCE_NAMESPACE
  44757. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  44758. /*** Start of inlined file: juce_TreeView.cpp ***/
  44759. BEGIN_JUCE_NAMESPACE
  44760. class TreeViewContentComponent : public Component,
  44761. public TooltipClient
  44762. {
  44763. public:
  44764. TreeViewContentComponent (TreeView& owner_)
  44765. : owner (owner_),
  44766. buttonUnderMouse (0),
  44767. isDragging (false)
  44768. {
  44769. }
  44770. void mouseDown (const MouseEvent& e)
  44771. {
  44772. updateButtonUnderMouse (e);
  44773. isDragging = false;
  44774. needSelectionOnMouseUp = false;
  44775. Rectangle<int> pos;
  44776. TreeViewItem* const item = findItemAt (e.y, pos);
  44777. if (item == 0)
  44778. return;
  44779. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  44780. // as selection clicks)
  44781. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  44782. {
  44783. if (e.x >= pos.getX() - owner.getIndentSize())
  44784. item->setOpen (! item->isOpen());
  44785. // (clicks to the left of an open/close button are ignored)
  44786. }
  44787. else
  44788. {
  44789. // mouse-down inside the body of the item..
  44790. if (! owner.isMultiSelectEnabled())
  44791. item->setSelected (true, true);
  44792. else if (item->isSelected())
  44793. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  44794. else
  44795. selectBasedOnModifiers (item, e.mods);
  44796. if (e.x >= pos.getX())
  44797. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44798. }
  44799. }
  44800. void mouseUp (const MouseEvent& e)
  44801. {
  44802. updateButtonUnderMouse (e);
  44803. if (needSelectionOnMouseUp && e.mouseWasClicked())
  44804. {
  44805. Rectangle<int> pos;
  44806. TreeViewItem* const item = findItemAt (e.y, pos);
  44807. if (item != 0)
  44808. selectBasedOnModifiers (item, e.mods);
  44809. }
  44810. }
  44811. void mouseDoubleClick (const MouseEvent& e)
  44812. {
  44813. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  44814. {
  44815. Rectangle<int> pos;
  44816. TreeViewItem* const item = findItemAt (e.y, pos);
  44817. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  44818. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  44819. }
  44820. }
  44821. void mouseDrag (const MouseEvent& e)
  44822. {
  44823. if (isEnabled()
  44824. && ! (isDragging || e.mouseWasClicked()
  44825. || e.getDistanceFromDragStart() < 5
  44826. || e.mods.isPopupMenu()))
  44827. {
  44828. isDragging = true;
  44829. Rectangle<int> pos;
  44830. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  44831. if (item != 0 && e.getMouseDownX() >= pos.getX())
  44832. {
  44833. const String dragDescription (item->getDragSourceDescription());
  44834. if (dragDescription.isNotEmpty())
  44835. {
  44836. DragAndDropContainer* const dragContainer
  44837. = DragAndDropContainer::findParentDragContainerFor (this);
  44838. if (dragContainer != 0)
  44839. {
  44840. pos.setSize (pos.getWidth(), item->itemHeight);
  44841. Image dragImage (Component::createComponentSnapshot (pos, true));
  44842. dragImage.multiplyAllAlphas (0.6f);
  44843. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  44844. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  44845. }
  44846. else
  44847. {
  44848. // to be able to do a drag-and-drop operation, the treeview needs to
  44849. // be inside a component which is also a DragAndDropContainer.
  44850. jassertfalse;
  44851. }
  44852. }
  44853. }
  44854. }
  44855. }
  44856. void mouseMove (const MouseEvent& e)
  44857. {
  44858. updateButtonUnderMouse (e);
  44859. }
  44860. void mouseExit (const MouseEvent& e)
  44861. {
  44862. updateButtonUnderMouse (e);
  44863. }
  44864. void paint (Graphics& g)
  44865. {
  44866. if (owner.rootItem != 0)
  44867. {
  44868. owner.handleAsyncUpdate();
  44869. if (! owner.rootItemVisible)
  44870. g.setOrigin (0, -owner.rootItem->itemHeight);
  44871. owner.rootItem->paintRecursively (g, getWidth());
  44872. }
  44873. }
  44874. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  44875. {
  44876. if (owner.rootItem != 0)
  44877. {
  44878. owner.handleAsyncUpdate();
  44879. if (! owner.rootItemVisible)
  44880. y += owner.rootItem->itemHeight;
  44881. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  44882. if (ti != 0)
  44883. itemPosition = ti->getItemPosition (false);
  44884. return ti;
  44885. }
  44886. return 0;
  44887. }
  44888. void updateComponents()
  44889. {
  44890. const int visibleTop = -getY();
  44891. const int visibleBottom = visibleTop + getParentHeight();
  44892. {
  44893. for (int i = items.size(); --i >= 0;)
  44894. items.getUnchecked(i)->shouldKeep = false;
  44895. }
  44896. {
  44897. TreeViewItem* item = owner.rootItem;
  44898. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  44899. while (item != 0 && y < visibleBottom)
  44900. {
  44901. y += item->itemHeight;
  44902. if (y >= visibleTop)
  44903. {
  44904. RowItem* const ri = findItem (item->uid);
  44905. if (ri != 0)
  44906. {
  44907. ri->shouldKeep = true;
  44908. }
  44909. else
  44910. {
  44911. Component* const comp = item->createItemComponent();
  44912. if (comp != 0)
  44913. {
  44914. items.add (new RowItem (item, comp, item->uid));
  44915. addAndMakeVisible (comp);
  44916. }
  44917. }
  44918. }
  44919. item = item->getNextVisibleItem (true);
  44920. }
  44921. }
  44922. for (int i = items.size(); --i >= 0;)
  44923. {
  44924. RowItem* const ri = items.getUnchecked(i);
  44925. bool keep = false;
  44926. if (isParentOf (ri->component))
  44927. {
  44928. if (ri->shouldKeep)
  44929. {
  44930. Rectangle<int> pos (ri->item->getItemPosition (false));
  44931. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  44932. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  44933. {
  44934. keep = true;
  44935. ri->component->setBounds (pos);
  44936. }
  44937. }
  44938. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  44939. {
  44940. keep = true;
  44941. ri->component->setSize (0, 0);
  44942. }
  44943. }
  44944. if (! keep)
  44945. items.remove (i);
  44946. }
  44947. }
  44948. void updateButtonUnderMouse (const MouseEvent& e)
  44949. {
  44950. TreeViewItem* newItem = 0;
  44951. if (owner.openCloseButtonsVisible)
  44952. {
  44953. Rectangle<int> pos;
  44954. TreeViewItem* item = findItemAt (e.y, pos);
  44955. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  44956. {
  44957. newItem = item;
  44958. if (! newItem->mightContainSubItems())
  44959. newItem = 0;
  44960. }
  44961. }
  44962. if (buttonUnderMouse != newItem)
  44963. {
  44964. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  44965. {
  44966. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44967. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44968. }
  44969. buttonUnderMouse = newItem;
  44970. if (buttonUnderMouse != 0)
  44971. {
  44972. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  44973. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  44974. }
  44975. }
  44976. }
  44977. bool isMouseOverButton (TreeViewItem* const item) const throw()
  44978. {
  44979. return item == buttonUnderMouse;
  44980. }
  44981. void resized()
  44982. {
  44983. owner.itemsChanged();
  44984. }
  44985. const String getTooltip()
  44986. {
  44987. Rectangle<int> pos;
  44988. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  44989. if (item != 0)
  44990. return item->getTooltip();
  44991. return owner.getTooltip();
  44992. }
  44993. private:
  44994. TreeView& owner;
  44995. struct RowItem
  44996. {
  44997. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  44998. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  44999. {
  45000. }
  45001. ~RowItem()
  45002. {
  45003. delete component.get();
  45004. }
  45005. WeakReference<Component> component;
  45006. TreeViewItem* item;
  45007. int uid;
  45008. bool shouldKeep;
  45009. };
  45010. OwnedArray <RowItem> items;
  45011. TreeViewItem* buttonUnderMouse;
  45012. bool isDragging, needSelectionOnMouseUp;
  45013. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45014. {
  45015. TreeViewItem* firstSelected = 0;
  45016. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45017. {
  45018. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45019. jassert (lastSelected != 0);
  45020. int rowStart = firstSelected->getRowNumberInTree();
  45021. int rowEnd = lastSelected->getRowNumberInTree();
  45022. if (rowStart > rowEnd)
  45023. swapVariables (rowStart, rowEnd);
  45024. int ourRow = item->getRowNumberInTree();
  45025. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45026. if (ourRow > otherEnd)
  45027. swapVariables (ourRow, otherEnd);
  45028. for (int i = ourRow; i <= otherEnd; ++i)
  45029. owner.getItemOnRow (i)->setSelected (true, false);
  45030. }
  45031. else
  45032. {
  45033. const bool cmd = modifiers.isCommandDown();
  45034. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45035. }
  45036. }
  45037. bool containsItem (TreeViewItem* const item) const throw()
  45038. {
  45039. for (int i = items.size(); --i >= 0;)
  45040. if (items.getUnchecked(i)->item == item)
  45041. return true;
  45042. return false;
  45043. }
  45044. RowItem* findItem (const int uid) const throw()
  45045. {
  45046. for (int i = items.size(); --i >= 0;)
  45047. {
  45048. RowItem* const ri = items.getUnchecked(i);
  45049. if (ri->uid == uid)
  45050. return ri;
  45051. }
  45052. return 0;
  45053. }
  45054. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45055. {
  45056. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45057. {
  45058. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45059. if (source->isDragging())
  45060. {
  45061. Component* const underMouse = source->getComponentUnderMouse();
  45062. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45063. return true;
  45064. }
  45065. }
  45066. return false;
  45067. }
  45068. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewContentComponent);
  45069. };
  45070. class TreeView::TreeViewport : public Viewport
  45071. {
  45072. public:
  45073. TreeViewport() throw() : lastX (-1) {}
  45074. void updateComponents (const bool triggerResize = false)
  45075. {
  45076. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45077. if (tvc != 0)
  45078. {
  45079. if (triggerResize)
  45080. tvc->resized();
  45081. else
  45082. tvc->updateComponents();
  45083. }
  45084. repaint();
  45085. }
  45086. void visibleAreaChanged (const Rectangle<int>& newVisibleArea)
  45087. {
  45088. const bool hasScrolledSideways = (newVisibleArea.getX() != lastX);
  45089. lastX = newVisibleArea.getX();
  45090. updateComponents (hasScrolledSideways);
  45091. }
  45092. private:
  45093. int lastX;
  45094. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TreeViewport);
  45095. };
  45096. TreeView::TreeView (const String& componentName)
  45097. : Component (componentName),
  45098. rootItem (0),
  45099. indentSize (24),
  45100. defaultOpenness (false),
  45101. needsRecalculating (true),
  45102. rootItemVisible (true),
  45103. multiSelectEnabled (false),
  45104. openCloseButtonsVisible (true)
  45105. {
  45106. addAndMakeVisible (viewport = new TreeViewport());
  45107. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45108. viewport->setWantsKeyboardFocus (false);
  45109. setWantsKeyboardFocus (true);
  45110. }
  45111. TreeView::~TreeView()
  45112. {
  45113. if (rootItem != 0)
  45114. rootItem->setOwnerView (0);
  45115. }
  45116. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45117. {
  45118. if (rootItem != newRootItem)
  45119. {
  45120. if (newRootItem != 0)
  45121. {
  45122. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45123. if (newRootItem->ownerView != 0)
  45124. newRootItem->ownerView->setRootItem (0);
  45125. }
  45126. if (rootItem != 0)
  45127. rootItem->setOwnerView (0);
  45128. rootItem = newRootItem;
  45129. if (newRootItem != 0)
  45130. newRootItem->setOwnerView (this);
  45131. needsRecalculating = true;
  45132. handleAsyncUpdate();
  45133. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45134. {
  45135. rootItem->setOpen (false); // force a re-open
  45136. rootItem->setOpen (true);
  45137. }
  45138. }
  45139. }
  45140. void TreeView::deleteRootItem()
  45141. {
  45142. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45143. setRootItem (0);
  45144. }
  45145. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45146. {
  45147. rootItemVisible = shouldBeVisible;
  45148. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45149. {
  45150. rootItem->setOpen (false); // force a re-open
  45151. rootItem->setOpen (true);
  45152. }
  45153. itemsChanged();
  45154. }
  45155. void TreeView::colourChanged()
  45156. {
  45157. setOpaque (findColour (backgroundColourId).isOpaque());
  45158. repaint();
  45159. }
  45160. void TreeView::setIndentSize (const int newIndentSize)
  45161. {
  45162. if (indentSize != newIndentSize)
  45163. {
  45164. indentSize = newIndentSize;
  45165. resized();
  45166. }
  45167. }
  45168. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45169. {
  45170. if (defaultOpenness != isOpenByDefault)
  45171. {
  45172. defaultOpenness = isOpenByDefault;
  45173. itemsChanged();
  45174. }
  45175. }
  45176. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45177. {
  45178. multiSelectEnabled = canMultiSelect;
  45179. }
  45180. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45181. {
  45182. if (openCloseButtonsVisible != shouldBeVisible)
  45183. {
  45184. openCloseButtonsVisible = shouldBeVisible;
  45185. itemsChanged();
  45186. }
  45187. }
  45188. Viewport* TreeView::getViewport() const throw()
  45189. {
  45190. return viewport;
  45191. }
  45192. void TreeView::clearSelectedItems()
  45193. {
  45194. if (rootItem != 0)
  45195. rootItem->deselectAllRecursively();
  45196. }
  45197. int TreeView::getNumSelectedItems (int maximumDepthToSearchTo) const throw()
  45198. {
  45199. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively (maximumDepthToSearchTo) : 0;
  45200. }
  45201. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45202. {
  45203. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45204. }
  45205. int TreeView::getNumRowsInTree() const
  45206. {
  45207. if (rootItem != 0)
  45208. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45209. return 0;
  45210. }
  45211. TreeViewItem* TreeView::getItemOnRow (int index) const
  45212. {
  45213. if (! rootItemVisible)
  45214. ++index;
  45215. if (rootItem != 0 && index >= 0)
  45216. return rootItem->getItemOnRow (index);
  45217. return 0;
  45218. }
  45219. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45220. {
  45221. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45222. Rectangle<int> pos;
  45223. return tc->findItemAt (tc->getLocalPoint (this, Point<int> (0, y)).getY(), pos);
  45224. }
  45225. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45226. {
  45227. if (rootItem == 0)
  45228. return 0;
  45229. return rootItem->findItemFromIdentifierString (identifierString);
  45230. }
  45231. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45232. {
  45233. XmlElement* e = 0;
  45234. if (rootItem != 0)
  45235. {
  45236. e = rootItem->getOpennessState();
  45237. if (e != 0 && alsoIncludeScrollPosition)
  45238. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45239. }
  45240. return e;
  45241. }
  45242. void TreeView::restoreOpennessState (const XmlElement& newState)
  45243. {
  45244. if (rootItem != 0)
  45245. {
  45246. rootItem->restoreOpennessState (newState);
  45247. if (newState.hasAttribute ("scrollPos"))
  45248. viewport->setViewPosition (viewport->getViewPositionX(),
  45249. newState.getIntAttribute ("scrollPos"));
  45250. }
  45251. }
  45252. void TreeView::paint (Graphics& g)
  45253. {
  45254. g.fillAll (findColour (backgroundColourId));
  45255. }
  45256. void TreeView::resized()
  45257. {
  45258. viewport->setBounds (getLocalBounds());
  45259. itemsChanged();
  45260. handleAsyncUpdate();
  45261. }
  45262. void TreeView::enablementChanged()
  45263. {
  45264. repaint();
  45265. }
  45266. void TreeView::moveSelectedRow (int delta)
  45267. {
  45268. if (delta == 0)
  45269. return;
  45270. int rowSelected = 0;
  45271. TreeViewItem* const firstSelected = getSelectedItem (0);
  45272. if (firstSelected != 0)
  45273. rowSelected = firstSelected->getRowNumberInTree();
  45274. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45275. for (;;)
  45276. {
  45277. TreeViewItem* item = getItemOnRow (rowSelected);
  45278. if (item != 0)
  45279. {
  45280. if (! item->canBeSelected())
  45281. {
  45282. // if the row we want to highlight doesn't allow it, try skipping
  45283. // to the next item..
  45284. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45285. rowSelected + (delta < 0 ? -1 : 1));
  45286. if (rowSelected != nextRowToTry)
  45287. {
  45288. rowSelected = nextRowToTry;
  45289. continue;
  45290. }
  45291. else
  45292. {
  45293. break;
  45294. }
  45295. }
  45296. item->setSelected (true, true);
  45297. scrollToKeepItemVisible (item);
  45298. }
  45299. break;
  45300. }
  45301. }
  45302. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45303. {
  45304. if (item != 0 && item->ownerView == this)
  45305. {
  45306. handleAsyncUpdate();
  45307. item = item->getDeepestOpenParentItem();
  45308. int y = item->y;
  45309. int viewTop = viewport->getViewPositionY();
  45310. if (y < viewTop)
  45311. {
  45312. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45313. }
  45314. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45315. {
  45316. viewport->setViewPosition (viewport->getViewPositionX(),
  45317. (y + item->itemHeight) - viewport->getViewHeight());
  45318. }
  45319. }
  45320. }
  45321. bool TreeView::keyPressed (const KeyPress& key)
  45322. {
  45323. if (key.isKeyCode (KeyPress::upKey))
  45324. {
  45325. moveSelectedRow (-1);
  45326. }
  45327. else if (key.isKeyCode (KeyPress::downKey))
  45328. {
  45329. moveSelectedRow (1);
  45330. }
  45331. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45332. {
  45333. if (rootItem != 0)
  45334. {
  45335. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45336. if (key.isKeyCode (KeyPress::pageUpKey))
  45337. rowsOnScreen = -rowsOnScreen;
  45338. moveSelectedRow (rowsOnScreen);
  45339. }
  45340. }
  45341. else if (key.isKeyCode (KeyPress::homeKey))
  45342. {
  45343. moveSelectedRow (-0x3fffffff);
  45344. }
  45345. else if (key.isKeyCode (KeyPress::endKey))
  45346. {
  45347. moveSelectedRow (0x3fffffff);
  45348. }
  45349. else if (key.isKeyCode (KeyPress::returnKey))
  45350. {
  45351. TreeViewItem* const firstSelected = getSelectedItem (0);
  45352. if (firstSelected != 0)
  45353. firstSelected->setOpen (! firstSelected->isOpen());
  45354. }
  45355. else if (key.isKeyCode (KeyPress::leftKey))
  45356. {
  45357. TreeViewItem* const firstSelected = getSelectedItem (0);
  45358. if (firstSelected != 0)
  45359. {
  45360. if (firstSelected->isOpen())
  45361. {
  45362. firstSelected->setOpen (false);
  45363. }
  45364. else
  45365. {
  45366. TreeViewItem* parent = firstSelected->parentItem;
  45367. if ((! rootItemVisible) && parent == rootItem)
  45368. parent = 0;
  45369. if (parent != 0)
  45370. {
  45371. parent->setSelected (true, true);
  45372. scrollToKeepItemVisible (parent);
  45373. }
  45374. }
  45375. }
  45376. }
  45377. else if (key.isKeyCode (KeyPress::rightKey))
  45378. {
  45379. TreeViewItem* const firstSelected = getSelectedItem (0);
  45380. if (firstSelected != 0)
  45381. {
  45382. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45383. moveSelectedRow (1);
  45384. else
  45385. firstSelected->setOpen (true);
  45386. }
  45387. }
  45388. else
  45389. {
  45390. return false;
  45391. }
  45392. return true;
  45393. }
  45394. void TreeView::itemsChanged() throw()
  45395. {
  45396. needsRecalculating = true;
  45397. repaint();
  45398. triggerAsyncUpdate();
  45399. }
  45400. void TreeView::handleAsyncUpdate()
  45401. {
  45402. if (needsRecalculating)
  45403. {
  45404. needsRecalculating = false;
  45405. const ScopedLock sl (nodeAlterationLock);
  45406. if (rootItem != 0)
  45407. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45408. viewport->updateComponents();
  45409. if (rootItem != 0)
  45410. {
  45411. viewport->getViewedComponent()
  45412. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45413. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45414. }
  45415. else
  45416. {
  45417. viewport->getViewedComponent()->setSize (0, 0);
  45418. }
  45419. }
  45420. }
  45421. class TreeView::InsertPointHighlight : public Component
  45422. {
  45423. public:
  45424. InsertPointHighlight()
  45425. : lastItem (0)
  45426. {
  45427. setSize (100, 12);
  45428. setAlwaysOnTop (true);
  45429. setInterceptsMouseClicks (false, false);
  45430. }
  45431. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45432. {
  45433. lastItem = item;
  45434. lastIndex = insertIndex;
  45435. const int offset = getHeight() / 2;
  45436. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45437. }
  45438. void paint (Graphics& g)
  45439. {
  45440. Path p;
  45441. const float h = (float) getHeight();
  45442. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45443. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45444. p.lineTo ((float) getWidth(), h / 2.0f);
  45445. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45446. g.strokePath (p, PathStrokeType (2.0f));
  45447. }
  45448. TreeViewItem* lastItem;
  45449. int lastIndex;
  45450. private:
  45451. JUCE_DECLARE_NON_COPYABLE (InsertPointHighlight);
  45452. };
  45453. class TreeView::TargetGroupHighlight : public Component
  45454. {
  45455. public:
  45456. TargetGroupHighlight()
  45457. {
  45458. setAlwaysOnTop (true);
  45459. setInterceptsMouseClicks (false, false);
  45460. }
  45461. void setTargetPosition (TreeViewItem* const item) throw()
  45462. {
  45463. Rectangle<int> r (item->getItemPosition (true));
  45464. r.setHeight (item->getItemHeight());
  45465. setBounds (r);
  45466. }
  45467. void paint (Graphics& g)
  45468. {
  45469. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45470. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45471. }
  45472. private:
  45473. JUCE_DECLARE_NON_COPYABLE (TargetGroupHighlight);
  45474. };
  45475. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45476. {
  45477. beginDragAutoRepeat (100);
  45478. if (dragInsertPointHighlight == 0)
  45479. {
  45480. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45481. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45482. }
  45483. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45484. dragTargetGroupHighlight->setTargetPosition (item);
  45485. }
  45486. void TreeView::hideDragHighlight() throw()
  45487. {
  45488. dragInsertPointHighlight = 0;
  45489. dragTargetGroupHighlight = 0;
  45490. }
  45491. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45492. const StringArray& files, const String& sourceDescription,
  45493. Component* sourceComponent) const throw()
  45494. {
  45495. insertIndex = 0;
  45496. TreeViewItem* item = getItemAt (y);
  45497. if (item == 0)
  45498. return 0;
  45499. Rectangle<int> itemPos (item->getItemPosition (true));
  45500. insertIndex = item->getIndexInParent();
  45501. const int oldY = y;
  45502. y = itemPos.getY();
  45503. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45504. {
  45505. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45506. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45507. {
  45508. // Check if we're trying to drag into an empty group item..
  45509. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45510. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45511. {
  45512. insertIndex = 0;
  45513. x = itemPos.getX() + getIndentSize();
  45514. y = itemPos.getBottom();
  45515. return item;
  45516. }
  45517. }
  45518. }
  45519. if (oldY > itemPos.getCentreY())
  45520. {
  45521. y += item->getItemHeight();
  45522. while (item->isLastOfSiblings() && item->parentItem != 0
  45523. && item->parentItem->parentItem != 0)
  45524. {
  45525. if (x > itemPos.getX())
  45526. break;
  45527. item = item->parentItem;
  45528. itemPos = item->getItemPosition (true);
  45529. insertIndex = item->getIndexInParent();
  45530. }
  45531. ++insertIndex;
  45532. }
  45533. x = itemPos.getX();
  45534. return item->parentItem;
  45535. }
  45536. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45537. {
  45538. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  45539. int insertIndex;
  45540. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45541. if (item != 0)
  45542. {
  45543. if (scrolled || dragInsertPointHighlight == 0
  45544. || dragInsertPointHighlight->lastItem != item
  45545. || dragInsertPointHighlight->lastIndex != insertIndex)
  45546. {
  45547. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45548. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45549. showDragHighlight (item, insertIndex, x, y);
  45550. else
  45551. hideDragHighlight();
  45552. }
  45553. }
  45554. else
  45555. {
  45556. hideDragHighlight();
  45557. }
  45558. }
  45559. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  45560. {
  45561. hideDragHighlight();
  45562. int insertIndex;
  45563. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  45564. if (item != 0)
  45565. {
  45566. if (files.size() > 0)
  45567. {
  45568. if (item->isInterestedInFileDrag (files))
  45569. item->filesDropped (files, insertIndex);
  45570. }
  45571. else
  45572. {
  45573. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45574. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  45575. }
  45576. }
  45577. }
  45578. bool TreeView::isInterestedInFileDrag (const StringArray&)
  45579. {
  45580. return true;
  45581. }
  45582. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  45583. {
  45584. fileDragMove (files, x, y);
  45585. }
  45586. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  45587. {
  45588. handleDrag (files, String::empty, 0, x, y);
  45589. }
  45590. void TreeView::fileDragExit (const StringArray&)
  45591. {
  45592. hideDragHighlight();
  45593. }
  45594. void TreeView::filesDropped (const StringArray& files, int x, int y)
  45595. {
  45596. handleDrop (files, String::empty, 0, x, y);
  45597. }
  45598. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45599. {
  45600. return true;
  45601. }
  45602. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45603. {
  45604. itemDragMove (sourceDescription, sourceComponent, x, y);
  45605. }
  45606. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45607. {
  45608. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  45609. }
  45610. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45611. {
  45612. hideDragHighlight();
  45613. }
  45614. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  45615. {
  45616. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  45617. }
  45618. enum TreeViewOpenness
  45619. {
  45620. opennessDefault = 0,
  45621. opennessClosed = 1,
  45622. opennessOpen = 2
  45623. };
  45624. TreeViewItem::TreeViewItem()
  45625. : ownerView (0),
  45626. parentItem (0),
  45627. y (0),
  45628. itemHeight (0),
  45629. totalHeight (0),
  45630. selected (false),
  45631. redrawNeeded (true),
  45632. drawLinesInside (true),
  45633. drawsInLeftMargin (false),
  45634. openness (opennessDefault)
  45635. {
  45636. static int nextUID = 0;
  45637. uid = nextUID++;
  45638. }
  45639. TreeViewItem::~TreeViewItem()
  45640. {
  45641. }
  45642. const String TreeViewItem::getUniqueName() const
  45643. {
  45644. return String::empty;
  45645. }
  45646. void TreeViewItem::itemOpennessChanged (bool)
  45647. {
  45648. }
  45649. int TreeViewItem::getNumSubItems() const throw()
  45650. {
  45651. return subItems.size();
  45652. }
  45653. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  45654. {
  45655. return subItems [index];
  45656. }
  45657. void TreeViewItem::clearSubItems()
  45658. {
  45659. if (subItems.size() > 0)
  45660. {
  45661. if (ownerView != 0)
  45662. {
  45663. const ScopedLock sl (ownerView->nodeAlterationLock);
  45664. subItems.clear();
  45665. treeHasChanged();
  45666. }
  45667. else
  45668. {
  45669. subItems.clear();
  45670. }
  45671. }
  45672. }
  45673. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  45674. {
  45675. if (newItem != 0)
  45676. {
  45677. newItem->parentItem = this;
  45678. newItem->setOwnerView (ownerView);
  45679. newItem->y = 0;
  45680. newItem->itemHeight = newItem->getItemHeight();
  45681. newItem->totalHeight = 0;
  45682. newItem->itemWidth = newItem->getItemWidth();
  45683. newItem->totalWidth = 0;
  45684. if (ownerView != 0)
  45685. {
  45686. const ScopedLock sl (ownerView->nodeAlterationLock);
  45687. subItems.insert (insertPosition, newItem);
  45688. treeHasChanged();
  45689. if (newItem->isOpen())
  45690. newItem->itemOpennessChanged (true);
  45691. }
  45692. else
  45693. {
  45694. subItems.insert (insertPosition, newItem);
  45695. if (newItem->isOpen())
  45696. newItem->itemOpennessChanged (true);
  45697. }
  45698. }
  45699. }
  45700. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  45701. {
  45702. if (ownerView != 0)
  45703. {
  45704. const ScopedLock sl (ownerView->nodeAlterationLock);
  45705. if (isPositiveAndBelow (index, subItems.size()))
  45706. {
  45707. subItems.remove (index, deleteItem);
  45708. treeHasChanged();
  45709. }
  45710. }
  45711. else
  45712. {
  45713. subItems.remove (index, deleteItem);
  45714. }
  45715. }
  45716. bool TreeViewItem::isOpen() const throw()
  45717. {
  45718. if (openness == opennessDefault)
  45719. return ownerView != 0 && ownerView->defaultOpenness;
  45720. else
  45721. return openness == opennessOpen;
  45722. }
  45723. void TreeViewItem::setOpen (const bool shouldBeOpen)
  45724. {
  45725. if (isOpen() != shouldBeOpen)
  45726. {
  45727. openness = shouldBeOpen ? opennessOpen
  45728. : opennessClosed;
  45729. treeHasChanged();
  45730. itemOpennessChanged (isOpen());
  45731. }
  45732. }
  45733. bool TreeViewItem::isSelected() const throw()
  45734. {
  45735. return selected;
  45736. }
  45737. void TreeViewItem::deselectAllRecursively()
  45738. {
  45739. setSelected (false, false);
  45740. for (int i = 0; i < subItems.size(); ++i)
  45741. subItems.getUnchecked(i)->deselectAllRecursively();
  45742. }
  45743. void TreeViewItem::setSelected (const bool shouldBeSelected,
  45744. const bool deselectOtherItemsFirst)
  45745. {
  45746. if (shouldBeSelected && ! canBeSelected())
  45747. return;
  45748. if (deselectOtherItemsFirst)
  45749. getTopLevelItem()->deselectAllRecursively();
  45750. if (shouldBeSelected != selected)
  45751. {
  45752. selected = shouldBeSelected;
  45753. if (ownerView != 0)
  45754. ownerView->repaint();
  45755. itemSelectionChanged (shouldBeSelected);
  45756. }
  45757. }
  45758. void TreeViewItem::paintItem (Graphics&, int, int)
  45759. {
  45760. }
  45761. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  45762. {
  45763. ownerView->getLookAndFeel()
  45764. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  45765. }
  45766. void TreeViewItem::itemClicked (const MouseEvent&)
  45767. {
  45768. }
  45769. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  45770. {
  45771. if (mightContainSubItems())
  45772. setOpen (! isOpen());
  45773. }
  45774. void TreeViewItem::itemSelectionChanged (bool)
  45775. {
  45776. }
  45777. const String TreeViewItem::getTooltip()
  45778. {
  45779. return String::empty;
  45780. }
  45781. const String TreeViewItem::getDragSourceDescription()
  45782. {
  45783. return String::empty;
  45784. }
  45785. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  45786. {
  45787. return false;
  45788. }
  45789. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  45790. {
  45791. }
  45792. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  45793. {
  45794. return false;
  45795. }
  45796. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  45797. {
  45798. }
  45799. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  45800. {
  45801. const int indentX = getIndentX();
  45802. int width = itemWidth;
  45803. if (ownerView != 0 && width < 0)
  45804. width = ownerView->viewport->getViewWidth() - indentX;
  45805. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  45806. if (relativeToTreeViewTopLeft)
  45807. r -= ownerView->viewport->getViewPosition();
  45808. return r;
  45809. }
  45810. void TreeViewItem::treeHasChanged() const throw()
  45811. {
  45812. if (ownerView != 0)
  45813. ownerView->itemsChanged();
  45814. }
  45815. void TreeViewItem::repaintItem() const
  45816. {
  45817. if (ownerView != 0 && areAllParentsOpen())
  45818. {
  45819. Rectangle<int> r (getItemPosition (true));
  45820. r.setLeft (0);
  45821. ownerView->viewport->repaint (r);
  45822. }
  45823. }
  45824. bool TreeViewItem::areAllParentsOpen() const throw()
  45825. {
  45826. return parentItem == 0
  45827. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  45828. }
  45829. void TreeViewItem::updatePositions (int newY)
  45830. {
  45831. y = newY;
  45832. itemHeight = getItemHeight();
  45833. totalHeight = itemHeight;
  45834. itemWidth = getItemWidth();
  45835. totalWidth = jmax (itemWidth, 0) + getIndentX();
  45836. if (isOpen())
  45837. {
  45838. newY += totalHeight;
  45839. for (int i = 0; i < subItems.size(); ++i)
  45840. {
  45841. TreeViewItem* const ti = subItems.getUnchecked(i);
  45842. ti->updatePositions (newY);
  45843. newY += ti->totalHeight;
  45844. totalHeight += ti->totalHeight;
  45845. totalWidth = jmax (totalWidth, ti->totalWidth);
  45846. }
  45847. }
  45848. }
  45849. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  45850. {
  45851. TreeViewItem* result = this;
  45852. TreeViewItem* item = this;
  45853. while (item->parentItem != 0)
  45854. {
  45855. item = item->parentItem;
  45856. if (! item->isOpen())
  45857. result = item;
  45858. }
  45859. return result;
  45860. }
  45861. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  45862. {
  45863. ownerView = newOwner;
  45864. for (int i = subItems.size(); --i >= 0;)
  45865. subItems.getUnchecked(i)->setOwnerView (newOwner);
  45866. }
  45867. int TreeViewItem::getIndentX() const throw()
  45868. {
  45869. const int indentWidth = ownerView->getIndentSize();
  45870. int x = ownerView->rootItemVisible ? indentWidth : 0;
  45871. if (! ownerView->openCloseButtonsVisible)
  45872. x -= indentWidth;
  45873. TreeViewItem* p = parentItem;
  45874. while (p != 0)
  45875. {
  45876. x += indentWidth;
  45877. p = p->parentItem;
  45878. }
  45879. return x;
  45880. }
  45881. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  45882. {
  45883. drawsInLeftMargin = canDrawInLeftMargin;
  45884. }
  45885. void TreeViewItem::paintRecursively (Graphics& g, int width)
  45886. {
  45887. jassert (ownerView != 0);
  45888. if (ownerView == 0)
  45889. return;
  45890. const int indent = getIndentX();
  45891. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  45892. {
  45893. Graphics::ScopedSaveState ss (g);
  45894. g.setOrigin (indent, 0);
  45895. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  45896. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  45897. paintItem (g, itemW, itemHeight);
  45898. }
  45899. g.setColour (ownerView->findColour (TreeView::linesColourId));
  45900. const float halfH = itemHeight * 0.5f;
  45901. int depth = 0;
  45902. TreeViewItem* p = parentItem;
  45903. while (p != 0)
  45904. {
  45905. ++depth;
  45906. p = p->parentItem;
  45907. }
  45908. if (! ownerView->rootItemVisible)
  45909. --depth;
  45910. const int indentWidth = ownerView->getIndentSize();
  45911. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  45912. {
  45913. float x = (depth + 0.5f) * indentWidth;
  45914. if (depth >= 0)
  45915. {
  45916. if (parentItem != 0 && parentItem->drawLinesInside)
  45917. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  45918. if ((parentItem != 0 && parentItem->drawLinesInside)
  45919. || (parentItem == 0 && drawLinesInside))
  45920. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  45921. }
  45922. p = parentItem;
  45923. int d = depth;
  45924. while (p != 0 && --d >= 0)
  45925. {
  45926. x -= (float) indentWidth;
  45927. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  45928. && ! p->isLastOfSiblings())
  45929. {
  45930. g.drawLine (x, 0, x, (float) itemHeight);
  45931. }
  45932. p = p->parentItem;
  45933. }
  45934. if (mightContainSubItems())
  45935. {
  45936. Graphics::ScopedSaveState ss (g);
  45937. g.setOrigin (depth * indentWidth, 0);
  45938. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  45939. paintOpenCloseButton (g, indentWidth, itemHeight,
  45940. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  45941. ->isMouseOverButton (this));
  45942. }
  45943. }
  45944. if (isOpen())
  45945. {
  45946. const Rectangle<int> clip (g.getClipBounds());
  45947. for (int i = 0; i < subItems.size(); ++i)
  45948. {
  45949. TreeViewItem* const ti = subItems.getUnchecked(i);
  45950. const int relY = ti->y - y;
  45951. if (relY >= clip.getBottom())
  45952. break;
  45953. if (relY + ti->totalHeight >= clip.getY())
  45954. {
  45955. Graphics::ScopedSaveState ss (g);
  45956. g.setOrigin (0, relY);
  45957. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  45958. ti->paintRecursively (g, width);
  45959. }
  45960. }
  45961. }
  45962. }
  45963. bool TreeViewItem::isLastOfSiblings() const throw()
  45964. {
  45965. return parentItem == 0
  45966. || parentItem->subItems.getLast() == this;
  45967. }
  45968. int TreeViewItem::getIndexInParent() const throw()
  45969. {
  45970. return parentItem == 0 ? 0
  45971. : parentItem->subItems.indexOf (this);
  45972. }
  45973. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  45974. {
  45975. return parentItem == 0 ? this
  45976. : parentItem->getTopLevelItem();
  45977. }
  45978. int TreeViewItem::getNumRows() const throw()
  45979. {
  45980. int num = 1;
  45981. if (isOpen())
  45982. {
  45983. for (int i = subItems.size(); --i >= 0;)
  45984. num += subItems.getUnchecked(i)->getNumRows();
  45985. }
  45986. return num;
  45987. }
  45988. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  45989. {
  45990. if (index == 0)
  45991. return this;
  45992. if (index > 0 && isOpen())
  45993. {
  45994. --index;
  45995. for (int i = 0; i < subItems.size(); ++i)
  45996. {
  45997. TreeViewItem* const item = subItems.getUnchecked(i);
  45998. if (index == 0)
  45999. return item;
  46000. const int numRows = item->getNumRows();
  46001. if (numRows > index)
  46002. return item->getItemOnRow (index);
  46003. index -= numRows;
  46004. }
  46005. }
  46006. return 0;
  46007. }
  46008. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46009. {
  46010. if (isPositiveAndBelow (targetY, totalHeight))
  46011. {
  46012. const int h = itemHeight;
  46013. if (targetY < h)
  46014. return this;
  46015. if (isOpen())
  46016. {
  46017. targetY -= h;
  46018. for (int i = 0; i < subItems.size(); ++i)
  46019. {
  46020. TreeViewItem* const ti = subItems.getUnchecked(i);
  46021. if (targetY < ti->totalHeight)
  46022. return ti->findItemRecursively (targetY);
  46023. targetY -= ti->totalHeight;
  46024. }
  46025. }
  46026. }
  46027. return 0;
  46028. }
  46029. int TreeViewItem::countSelectedItemsRecursively (int depth) const throw()
  46030. {
  46031. int total = isSelected() ? 1 : 0;
  46032. if (depth != 0)
  46033. for (int i = subItems.size(); --i >= 0;)
  46034. total += subItems.getUnchecked(i)->countSelectedItemsRecursively (depth - 1);
  46035. return total;
  46036. }
  46037. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46038. {
  46039. if (isSelected())
  46040. {
  46041. if (index == 0)
  46042. return this;
  46043. --index;
  46044. }
  46045. if (index >= 0)
  46046. {
  46047. for (int i = 0; i < subItems.size(); ++i)
  46048. {
  46049. TreeViewItem* const item = subItems.getUnchecked(i);
  46050. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46051. if (found != 0)
  46052. return found;
  46053. index -= item->countSelectedItemsRecursively (-1);
  46054. }
  46055. }
  46056. return 0;
  46057. }
  46058. int TreeViewItem::getRowNumberInTree() const throw()
  46059. {
  46060. if (parentItem != 0 && ownerView != 0)
  46061. {
  46062. int n = 1 + parentItem->getRowNumberInTree();
  46063. int ourIndex = parentItem->subItems.indexOf (this);
  46064. jassert (ourIndex >= 0);
  46065. while (--ourIndex >= 0)
  46066. n += parentItem->subItems [ourIndex]->getNumRows();
  46067. if (parentItem->parentItem == 0
  46068. && ! ownerView->rootItemVisible)
  46069. --n;
  46070. return n;
  46071. }
  46072. else
  46073. {
  46074. return 0;
  46075. }
  46076. }
  46077. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46078. {
  46079. drawLinesInside = drawLines;
  46080. }
  46081. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46082. {
  46083. if (recurse && isOpen() && subItems.size() > 0)
  46084. return subItems [0];
  46085. if (parentItem != 0)
  46086. {
  46087. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46088. if (nextIndex >= parentItem->subItems.size())
  46089. return parentItem->getNextVisibleItem (false);
  46090. return parentItem->subItems [nextIndex];
  46091. }
  46092. return 0;
  46093. }
  46094. const String TreeViewItem::getItemIdentifierString() const
  46095. {
  46096. String s;
  46097. if (parentItem != 0)
  46098. s = parentItem->getItemIdentifierString();
  46099. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46100. }
  46101. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46102. {
  46103. const String thisId (getUniqueName());
  46104. if (thisId == identifierString)
  46105. return this;
  46106. if (identifierString.startsWith (thisId + "/"))
  46107. {
  46108. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46109. bool wasOpen = isOpen();
  46110. setOpen (true);
  46111. for (int i = subItems.size(); --i >= 0;)
  46112. {
  46113. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46114. if (item != 0)
  46115. return item;
  46116. }
  46117. setOpen (wasOpen);
  46118. }
  46119. return 0;
  46120. }
  46121. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46122. {
  46123. if (e.hasTagName ("CLOSED"))
  46124. {
  46125. setOpen (false);
  46126. }
  46127. else if (e.hasTagName ("OPEN"))
  46128. {
  46129. setOpen (true);
  46130. forEachXmlChildElement (e, n)
  46131. {
  46132. const String id (n->getStringAttribute ("id"));
  46133. for (int i = 0; i < subItems.size(); ++i)
  46134. {
  46135. TreeViewItem* const ti = subItems.getUnchecked(i);
  46136. if (ti->getUniqueName() == id)
  46137. {
  46138. ti->restoreOpennessState (*n);
  46139. break;
  46140. }
  46141. }
  46142. }
  46143. }
  46144. }
  46145. XmlElement* TreeViewItem::getOpennessState() const throw()
  46146. {
  46147. const String name (getUniqueName());
  46148. if (name.isNotEmpty())
  46149. {
  46150. XmlElement* e;
  46151. if (isOpen())
  46152. {
  46153. e = new XmlElement ("OPEN");
  46154. for (int i = 0; i < subItems.size(); ++i)
  46155. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46156. }
  46157. else
  46158. {
  46159. e = new XmlElement ("CLOSED");
  46160. }
  46161. e->setAttribute ("id", name);
  46162. return e;
  46163. }
  46164. else
  46165. {
  46166. // trying to save the openness for an element that has no name - this won't
  46167. // work because it needs the names to identify what to open.
  46168. jassertfalse;
  46169. }
  46170. return 0;
  46171. }
  46172. TreeViewItem::OpennessRestorer::OpennessRestorer (TreeViewItem& treeViewItem_)
  46173. : treeViewItem (treeViewItem_),
  46174. oldOpenness (treeViewItem_.getOpennessState())
  46175. {
  46176. }
  46177. TreeViewItem::OpennessRestorer::~OpennessRestorer()
  46178. {
  46179. if (oldOpenness != 0)
  46180. treeViewItem.restoreOpennessState (*oldOpenness);
  46181. }
  46182. END_JUCE_NAMESPACE
  46183. /*** End of inlined file: juce_TreeView.cpp ***/
  46184. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46185. BEGIN_JUCE_NAMESPACE
  46186. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46187. : fileList (listToShow)
  46188. {
  46189. }
  46190. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46191. {
  46192. }
  46193. FileBrowserListener::~FileBrowserListener()
  46194. {
  46195. }
  46196. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46197. {
  46198. listeners.add (listener);
  46199. }
  46200. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46201. {
  46202. listeners.remove (listener);
  46203. }
  46204. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46205. {
  46206. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46207. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46208. }
  46209. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46210. {
  46211. if (fileList.getDirectory().exists())
  46212. {
  46213. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46214. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46215. }
  46216. }
  46217. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46218. {
  46219. if (fileList.getDirectory().exists())
  46220. {
  46221. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46222. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46223. }
  46224. }
  46225. END_JUCE_NAMESPACE
  46226. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46227. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46228. BEGIN_JUCE_NAMESPACE
  46229. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46230. TimeSliceThread& thread_)
  46231. : fileFilter (fileFilter_),
  46232. thread (thread_),
  46233. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46234. fileFindHandle (0),
  46235. shouldStop (true)
  46236. {
  46237. }
  46238. DirectoryContentsList::~DirectoryContentsList()
  46239. {
  46240. clear();
  46241. }
  46242. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46243. {
  46244. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46245. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46246. }
  46247. bool DirectoryContentsList::ignoresHiddenFiles() const
  46248. {
  46249. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46250. }
  46251. const File& DirectoryContentsList::getDirectory() const
  46252. {
  46253. return root;
  46254. }
  46255. void DirectoryContentsList::setDirectory (const File& directory,
  46256. const bool includeDirectories,
  46257. const bool includeFiles)
  46258. {
  46259. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46260. if (directory != root)
  46261. {
  46262. clear();
  46263. root = directory;
  46264. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46265. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46266. }
  46267. int newFlags = fileTypeFlags;
  46268. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46269. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46270. setTypeFlags (newFlags);
  46271. }
  46272. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46273. {
  46274. if (fileTypeFlags != newFlags)
  46275. {
  46276. fileTypeFlags = newFlags;
  46277. refresh();
  46278. }
  46279. }
  46280. void DirectoryContentsList::clear()
  46281. {
  46282. shouldStop = true;
  46283. thread.removeTimeSliceClient (this);
  46284. fileFindHandle = 0;
  46285. if (files.size() > 0)
  46286. {
  46287. files.clear();
  46288. changed();
  46289. }
  46290. }
  46291. void DirectoryContentsList::refresh()
  46292. {
  46293. clear();
  46294. if (root.isDirectory())
  46295. {
  46296. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46297. shouldStop = false;
  46298. thread.addTimeSliceClient (this);
  46299. }
  46300. }
  46301. int DirectoryContentsList::getNumFiles() const
  46302. {
  46303. return files.size();
  46304. }
  46305. bool DirectoryContentsList::getFileInfo (const int index,
  46306. FileInfo& result) const
  46307. {
  46308. const ScopedLock sl (fileListLock);
  46309. const FileInfo* const info = files [index];
  46310. if (info != 0)
  46311. {
  46312. result = *info;
  46313. return true;
  46314. }
  46315. return false;
  46316. }
  46317. const File DirectoryContentsList::getFile (const int index) const
  46318. {
  46319. const ScopedLock sl (fileListLock);
  46320. const FileInfo* const info = files [index];
  46321. if (info != 0)
  46322. return root.getChildFile (info->filename);
  46323. return File::nonexistent;
  46324. }
  46325. bool DirectoryContentsList::isStillLoading() const
  46326. {
  46327. return fileFindHandle != 0;
  46328. }
  46329. void DirectoryContentsList::changed()
  46330. {
  46331. sendChangeMessage();
  46332. }
  46333. int DirectoryContentsList::useTimeSlice()
  46334. {
  46335. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46336. bool hasChanged = false;
  46337. for (int i = 100; --i >= 0;)
  46338. {
  46339. if (! checkNextFile (hasChanged))
  46340. {
  46341. if (hasChanged)
  46342. changed();
  46343. return 500;
  46344. }
  46345. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46346. break;
  46347. }
  46348. if (hasChanged)
  46349. changed();
  46350. return 0;
  46351. }
  46352. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46353. {
  46354. if (fileFindHandle != 0)
  46355. {
  46356. bool fileFoundIsDir, isHidden, isReadOnly;
  46357. int64 fileSize;
  46358. Time modTime, creationTime;
  46359. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46360. &modTime, &creationTime, &isReadOnly))
  46361. {
  46362. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46363. fileSize, modTime, creationTime, isReadOnly))
  46364. {
  46365. hasChanged = true;
  46366. }
  46367. return true;
  46368. }
  46369. else
  46370. {
  46371. fileFindHandle = 0;
  46372. }
  46373. }
  46374. return false;
  46375. }
  46376. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46377. const DirectoryContentsList::FileInfo* const second)
  46378. {
  46379. #if JUCE_WINDOWS
  46380. if (first->isDirectory != second->isDirectory)
  46381. return first->isDirectory ? -1 : 1;
  46382. #endif
  46383. return first->filename.compareIgnoreCase (second->filename);
  46384. }
  46385. bool DirectoryContentsList::addFile (const File& file,
  46386. const bool isDir,
  46387. const int64 fileSize,
  46388. const Time& modTime,
  46389. const Time& creationTime,
  46390. const bool isReadOnly)
  46391. {
  46392. if (fileFilter == 0
  46393. || ((! isDir) && fileFilter->isFileSuitable (file))
  46394. || (isDir && fileFilter->isDirectorySuitable (file)))
  46395. {
  46396. ScopedPointer <FileInfo> info (new FileInfo());
  46397. info->filename = file.getFileName();
  46398. info->fileSize = fileSize;
  46399. info->modificationTime = modTime;
  46400. info->creationTime = creationTime;
  46401. info->isDirectory = isDir;
  46402. info->isReadOnly = isReadOnly;
  46403. const ScopedLock sl (fileListLock);
  46404. for (int i = files.size(); --i >= 0;)
  46405. if (files.getUnchecked(i)->filename == info->filename)
  46406. return false;
  46407. files.addSorted (*this, info.release());
  46408. return true;
  46409. }
  46410. return false;
  46411. }
  46412. END_JUCE_NAMESPACE
  46413. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46414. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46415. BEGIN_JUCE_NAMESPACE
  46416. FileBrowserComponent::FileBrowserComponent (int flags_,
  46417. const File& initialFileOrDirectory,
  46418. const FileFilter* fileFilter_,
  46419. FilePreviewComponent* previewComp_)
  46420. : FileFilter (String::empty),
  46421. fileFilter (fileFilter_),
  46422. flags (flags_),
  46423. previewComp (previewComp_),
  46424. currentPathBox ("path"),
  46425. fileLabel ("f", TRANS ("file:")),
  46426. thread ("Juce FileBrowser")
  46427. {
  46428. // You need to specify one or other of the open/save flags..
  46429. jassert ((flags & (saveMode | openMode)) != 0);
  46430. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46431. // You need to specify at least one of these flags..
  46432. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46433. String filename;
  46434. if (initialFileOrDirectory == File::nonexistent)
  46435. {
  46436. currentRoot = File::getCurrentWorkingDirectory();
  46437. }
  46438. else if (initialFileOrDirectory.isDirectory())
  46439. {
  46440. currentRoot = initialFileOrDirectory;
  46441. }
  46442. else
  46443. {
  46444. chosenFiles.add (initialFileOrDirectory);
  46445. currentRoot = initialFileOrDirectory.getParentDirectory();
  46446. filename = initialFileOrDirectory.getFileName();
  46447. }
  46448. fileList = new DirectoryContentsList (this, thread);
  46449. if ((flags & useTreeView) != 0)
  46450. {
  46451. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46452. fileListComponent = tree;
  46453. if ((flags & canSelectMultipleItems) != 0)
  46454. tree->setMultiSelectEnabled (true);
  46455. addAndMakeVisible (tree);
  46456. }
  46457. else
  46458. {
  46459. FileListComponent* const list = new FileListComponent (*fileList);
  46460. fileListComponent = list;
  46461. list->setOutlineThickness (1);
  46462. if ((flags & canSelectMultipleItems) != 0)
  46463. list->setMultipleSelectionEnabled (true);
  46464. addAndMakeVisible (list);
  46465. }
  46466. fileListComponent->addListener (this);
  46467. addAndMakeVisible (&currentPathBox);
  46468. currentPathBox.setEditableText (true);
  46469. StringArray rootNames, rootPaths;
  46470. getRoots (rootNames, rootPaths);
  46471. for (int i = 0; i < rootNames.size(); ++i)
  46472. {
  46473. if (rootNames[i].isEmpty())
  46474. currentPathBox.addSeparator();
  46475. else
  46476. currentPathBox.addItem (rootNames[i], i + 1);
  46477. }
  46478. currentPathBox.addSeparator();
  46479. currentPathBox.addListener (this);
  46480. addAndMakeVisible (&filenameBox);
  46481. filenameBox.setMultiLine (false);
  46482. filenameBox.setSelectAllWhenFocused (true);
  46483. filenameBox.setText (filename, false);
  46484. filenameBox.addListener (this);
  46485. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46486. addAndMakeVisible (&fileLabel);
  46487. fileLabel.attachToComponent (&filenameBox, true);
  46488. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46489. goUpButton->addListener (this);
  46490. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46491. if (previewComp != 0)
  46492. addAndMakeVisible (previewComp);
  46493. setRoot (currentRoot);
  46494. thread.startThread (4);
  46495. }
  46496. FileBrowserComponent::~FileBrowserComponent()
  46497. {
  46498. fileListComponent = 0;
  46499. fileList = 0;
  46500. thread.stopThread (10000);
  46501. }
  46502. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46503. {
  46504. listeners.add (newListener);
  46505. }
  46506. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46507. {
  46508. listeners.remove (listener);
  46509. }
  46510. bool FileBrowserComponent::isSaveMode() const throw()
  46511. {
  46512. return (flags & saveMode) != 0;
  46513. }
  46514. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46515. {
  46516. if (chosenFiles.size() == 0 && currentFileIsValid())
  46517. return 1;
  46518. return chosenFiles.size();
  46519. }
  46520. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46521. {
  46522. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  46523. return currentRoot;
  46524. if (! filenameBox.isReadOnly())
  46525. return currentRoot.getChildFile (filenameBox.getText());
  46526. return chosenFiles[index];
  46527. }
  46528. bool FileBrowserComponent::currentFileIsValid() const
  46529. {
  46530. if (isSaveMode())
  46531. return ! getSelectedFile (0).isDirectory();
  46532. else
  46533. return getSelectedFile (0).exists();
  46534. }
  46535. const File FileBrowserComponent::getHighlightedFile() const throw()
  46536. {
  46537. return fileListComponent->getSelectedFile (0);
  46538. }
  46539. void FileBrowserComponent::deselectAllFiles()
  46540. {
  46541. fileListComponent->deselectAllFiles();
  46542. }
  46543. bool FileBrowserComponent::isFileSuitable (const File& file) const
  46544. {
  46545. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  46546. }
  46547. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  46548. {
  46549. return true;
  46550. }
  46551. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  46552. {
  46553. if (f.isDirectory())
  46554. return (flags & canSelectDirectories) != 0
  46555. && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  46556. return (flags & canSelectFiles) != 0 && f.exists()
  46557. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  46558. }
  46559. const File FileBrowserComponent::getRoot() const
  46560. {
  46561. return currentRoot;
  46562. }
  46563. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  46564. {
  46565. if (currentRoot != newRootDirectory)
  46566. {
  46567. fileListComponent->scrollToTop();
  46568. String path (newRootDirectory.getFullPathName());
  46569. if (path.isEmpty())
  46570. path = File::separatorString;
  46571. StringArray rootNames, rootPaths;
  46572. getRoots (rootNames, rootPaths);
  46573. if (! rootPaths.contains (path, true))
  46574. {
  46575. bool alreadyListed = false;
  46576. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  46577. {
  46578. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  46579. {
  46580. alreadyListed = true;
  46581. break;
  46582. }
  46583. }
  46584. if (! alreadyListed)
  46585. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  46586. }
  46587. }
  46588. currentRoot = newRootDirectory;
  46589. fileList->setDirectory (currentRoot, true, true);
  46590. String currentRootName (currentRoot.getFullPathName());
  46591. if (currentRootName.isEmpty())
  46592. currentRootName = File::separatorString;
  46593. currentPathBox.setText (currentRootName, true);
  46594. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  46595. && currentRoot.getParentDirectory() != currentRoot);
  46596. }
  46597. void FileBrowserComponent::goUp()
  46598. {
  46599. setRoot (getRoot().getParentDirectory());
  46600. }
  46601. void FileBrowserComponent::refresh()
  46602. {
  46603. fileList->refresh();
  46604. }
  46605. void FileBrowserComponent::setFileFilter (const FileFilter* const newFileFilter)
  46606. {
  46607. if (fileFilter != newFileFilter)
  46608. {
  46609. fileFilter = newFileFilter;
  46610. refresh();
  46611. }
  46612. }
  46613. const String FileBrowserComponent::getActionVerb() const
  46614. {
  46615. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  46616. }
  46617. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  46618. {
  46619. return previewComp;
  46620. }
  46621. void FileBrowserComponent::resized()
  46622. {
  46623. getLookAndFeel()
  46624. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  46625. &currentPathBox, &filenameBox, goUpButton);
  46626. }
  46627. void FileBrowserComponent::sendListenerChangeMessage()
  46628. {
  46629. Component::BailOutChecker checker (this);
  46630. if (previewComp != 0)
  46631. previewComp->selectedFileChanged (getSelectedFile (0));
  46632. // You shouldn't delete the browser when the file gets changed!
  46633. jassert (! checker.shouldBailOut());
  46634. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46635. }
  46636. void FileBrowserComponent::selectionChanged()
  46637. {
  46638. StringArray newFilenames;
  46639. bool resetChosenFiles = true;
  46640. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  46641. {
  46642. const File f (fileListComponent->getSelectedFile (i));
  46643. if (isFileOrDirSuitable (f))
  46644. {
  46645. if (resetChosenFiles)
  46646. {
  46647. chosenFiles.clear();
  46648. resetChosenFiles = false;
  46649. }
  46650. chosenFiles.add (f);
  46651. newFilenames.add (f.getRelativePathFrom (getRoot()));
  46652. }
  46653. }
  46654. if (newFilenames.size() > 0)
  46655. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  46656. sendListenerChangeMessage();
  46657. }
  46658. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  46659. {
  46660. Component::BailOutChecker checker (this);
  46661. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  46662. }
  46663. void FileBrowserComponent::fileDoubleClicked (const File& f)
  46664. {
  46665. if (f.isDirectory())
  46666. {
  46667. setRoot (f);
  46668. if ((flags & canSelectDirectories) != 0)
  46669. filenameBox.setText (String::empty);
  46670. }
  46671. else
  46672. {
  46673. Component::BailOutChecker checker (this);
  46674. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  46675. }
  46676. }
  46677. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  46678. {
  46679. (void) key;
  46680. #if JUCE_LINUX || JUCE_WINDOWS
  46681. if (key.getModifiers().isCommandDown()
  46682. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  46683. {
  46684. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  46685. fileList->refresh();
  46686. return true;
  46687. }
  46688. #endif
  46689. return false;
  46690. }
  46691. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  46692. {
  46693. sendListenerChangeMessage();
  46694. }
  46695. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  46696. {
  46697. if (filenameBox.getText().containsChar (File::separator))
  46698. {
  46699. const File f (currentRoot.getChildFile (filenameBox.getText()));
  46700. if (f.isDirectory())
  46701. {
  46702. setRoot (f);
  46703. chosenFiles.clear();
  46704. filenameBox.setText (String::empty);
  46705. }
  46706. else
  46707. {
  46708. setRoot (f.getParentDirectory());
  46709. chosenFiles.clear();
  46710. chosenFiles.add (f);
  46711. filenameBox.setText (f.getFileName());
  46712. }
  46713. }
  46714. else
  46715. {
  46716. fileDoubleClicked (getSelectedFile (0));
  46717. }
  46718. }
  46719. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  46720. {
  46721. }
  46722. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  46723. {
  46724. if (! isSaveMode())
  46725. selectionChanged();
  46726. }
  46727. void FileBrowserComponent::buttonClicked (Button*)
  46728. {
  46729. goUp();
  46730. }
  46731. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  46732. {
  46733. const String newText (currentPathBox.getText().trim().unquoted());
  46734. if (newText.isNotEmpty())
  46735. {
  46736. const int index = currentPathBox.getSelectedId() - 1;
  46737. StringArray rootNames, rootPaths;
  46738. getRoots (rootNames, rootPaths);
  46739. if (rootPaths [index].isNotEmpty())
  46740. {
  46741. setRoot (File (rootPaths [index]));
  46742. }
  46743. else
  46744. {
  46745. File f (newText);
  46746. for (;;)
  46747. {
  46748. if (f.isDirectory())
  46749. {
  46750. setRoot (f);
  46751. break;
  46752. }
  46753. if (f.getParentDirectory() == f)
  46754. break;
  46755. f = f.getParentDirectory();
  46756. }
  46757. }
  46758. }
  46759. }
  46760. void FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  46761. {
  46762. #if JUCE_WINDOWS
  46763. Array<File> roots;
  46764. File::findFileSystemRoots (roots);
  46765. rootPaths.clear();
  46766. for (int i = 0; i < roots.size(); ++i)
  46767. {
  46768. const File& drive = roots.getReference(i);
  46769. String name (drive.getFullPathName());
  46770. rootPaths.add (name);
  46771. if (drive.isOnHardDisk())
  46772. {
  46773. String volume (drive.getVolumeLabel());
  46774. if (volume.isEmpty())
  46775. volume = TRANS("Hard Drive");
  46776. name << " [" << volume << ']';
  46777. }
  46778. else if (drive.isOnCDRomDrive())
  46779. {
  46780. name << TRANS(" [CD/DVD drive]");
  46781. }
  46782. rootNames.add (name);
  46783. }
  46784. rootPaths.add (String::empty);
  46785. rootNames.add (String::empty);
  46786. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46787. rootNames.add ("Documents");
  46788. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46789. rootNames.add ("Desktop");
  46790. #endif
  46791. #if JUCE_MAC
  46792. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46793. rootNames.add ("Home folder");
  46794. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  46795. rootNames.add ("Documents");
  46796. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46797. rootNames.add ("Desktop");
  46798. rootPaths.add (String::empty);
  46799. rootNames.add (String::empty);
  46800. Array <File> volumes;
  46801. File vol ("/Volumes");
  46802. vol.findChildFiles (volumes, File::findDirectories, false);
  46803. for (int i = 0; i < volumes.size(); ++i)
  46804. {
  46805. const File& volume = volumes.getReference(i);
  46806. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  46807. {
  46808. rootPaths.add (volume.getFullPathName());
  46809. rootNames.add (volume.getFileName());
  46810. }
  46811. }
  46812. #endif
  46813. #if JUCE_LINUX
  46814. rootPaths.add ("/");
  46815. rootNames.add ("/");
  46816. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  46817. rootNames.add ("Home folder");
  46818. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  46819. rootNames.add ("Desktop");
  46820. #endif
  46821. }
  46822. END_JUCE_NAMESPACE
  46823. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  46824. /*** Start of inlined file: juce_FileChooser.cpp ***/
  46825. BEGIN_JUCE_NAMESPACE
  46826. FileChooser::FileChooser (const String& chooserBoxTitle,
  46827. const File& currentFileOrDirectory,
  46828. const String& fileFilters,
  46829. const bool useNativeDialogBox_)
  46830. : title (chooserBoxTitle),
  46831. filters (fileFilters),
  46832. startingFile (currentFileOrDirectory),
  46833. useNativeDialogBox (useNativeDialogBox_)
  46834. {
  46835. #if JUCE_LINUX
  46836. useNativeDialogBox = false;
  46837. #endif
  46838. if (! fileFilters.containsNonWhitespaceChars())
  46839. filters = "*";
  46840. }
  46841. FileChooser::~FileChooser()
  46842. {
  46843. }
  46844. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  46845. {
  46846. return showDialog (false, true, false, false, false, previewComponent);
  46847. }
  46848. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  46849. {
  46850. return showDialog (false, true, false, false, true, previewComponent);
  46851. }
  46852. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  46853. {
  46854. return showDialog (true, true, false, false, true, previewComponent);
  46855. }
  46856. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  46857. {
  46858. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  46859. }
  46860. bool FileChooser::browseForDirectory()
  46861. {
  46862. return showDialog (true, false, false, false, false, 0);
  46863. }
  46864. const File FileChooser::getResult() const
  46865. {
  46866. // if you've used a multiple-file select, you should use the getResults() method
  46867. // to retrieve all the files that were chosen.
  46868. jassert (results.size() <= 1);
  46869. return results.getFirst();
  46870. }
  46871. const Array<File>& FileChooser::getResults() const
  46872. {
  46873. return results;
  46874. }
  46875. bool FileChooser::showDialog (const bool selectsDirectories,
  46876. const bool selectsFiles,
  46877. const bool isSave,
  46878. const bool warnAboutOverwritingExistingFiles,
  46879. const bool selectMultipleFiles,
  46880. FilePreviewComponent* const previewComponent)
  46881. {
  46882. WeakReference<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  46883. results.clear();
  46884. // the preview component needs to be the right size before you pass it in here..
  46885. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  46886. && previewComponent->getHeight() > 10));
  46887. #if JUCE_WINDOWS
  46888. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  46889. #elif JUCE_MAC
  46890. if (useNativeDialogBox && (previewComponent == 0))
  46891. #else
  46892. if (false)
  46893. #endif
  46894. {
  46895. showPlatformDialog (results, title, startingFile, filters,
  46896. selectsDirectories, selectsFiles, isSave,
  46897. warnAboutOverwritingExistingFiles,
  46898. selectMultipleFiles,
  46899. previewComponent);
  46900. }
  46901. else
  46902. {
  46903. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  46904. selectsDirectories ? "*" : String::empty,
  46905. String::empty);
  46906. int flags = isSave ? FileBrowserComponent::saveMode
  46907. : FileBrowserComponent::openMode;
  46908. if (selectsFiles)
  46909. flags |= FileBrowserComponent::canSelectFiles;
  46910. if (selectsDirectories)
  46911. {
  46912. flags |= FileBrowserComponent::canSelectDirectories;
  46913. if (! isSave)
  46914. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  46915. }
  46916. if (selectMultipleFiles)
  46917. flags |= FileBrowserComponent::canSelectMultipleItems;
  46918. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  46919. FileChooserDialogBox box (title, String::empty,
  46920. browserComponent,
  46921. warnAboutOverwritingExistingFiles,
  46922. browserComponent.findColour (AlertWindow::backgroundColourId));
  46923. if (box.show())
  46924. {
  46925. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  46926. results.add (browserComponent.getSelectedFile (i));
  46927. }
  46928. }
  46929. if (previouslyFocused != 0)
  46930. previouslyFocused->grabKeyboardFocus();
  46931. return results.size() > 0;
  46932. }
  46933. FilePreviewComponent::FilePreviewComponent()
  46934. {
  46935. }
  46936. FilePreviewComponent::~FilePreviewComponent()
  46937. {
  46938. }
  46939. END_JUCE_NAMESPACE
  46940. /*** End of inlined file: juce_FileChooser.cpp ***/
  46941. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  46942. BEGIN_JUCE_NAMESPACE
  46943. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  46944. const String& instructions,
  46945. FileBrowserComponent& chooserComponent,
  46946. const bool warnAboutOverwritingExistingFiles_,
  46947. const Colour& backgroundColour)
  46948. : ResizableWindow (name, backgroundColour, true),
  46949. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  46950. {
  46951. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  46952. setResizable (true, true);
  46953. setResizeLimits (300, 300, 1200, 1000);
  46954. content->okButton.addListener (this);
  46955. content->cancelButton.addListener (this);
  46956. content->newFolderButton.addListener (this);
  46957. content->chooserComponent.addListener (this);
  46958. selectionChanged();
  46959. }
  46960. FileChooserDialogBox::~FileChooserDialogBox()
  46961. {
  46962. content->chooserComponent.removeListener (this);
  46963. }
  46964. bool FileChooserDialogBox::show (int w, int h)
  46965. {
  46966. return showAt (-1, -1, w, h);
  46967. }
  46968. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  46969. {
  46970. if (w <= 0)
  46971. {
  46972. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  46973. if (previewComp != 0)
  46974. w = 400 + previewComp->getWidth();
  46975. else
  46976. w = 600;
  46977. }
  46978. if (h <= 0)
  46979. h = 500;
  46980. if (x < 0 || y < 0)
  46981. centreWithSize (w, h);
  46982. else
  46983. setBounds (x, y, w, h);
  46984. const bool ok = (runModalLoop() != 0);
  46985. setVisible (false);
  46986. return ok;
  46987. }
  46988. void FileChooserDialogBox::buttonClicked (Button* button)
  46989. {
  46990. if (button == &(content->okButton))
  46991. {
  46992. okButtonPressed();
  46993. }
  46994. else if (button == &(content->cancelButton))
  46995. {
  46996. closeButtonPressed();
  46997. }
  46998. else if (button == &(content->newFolderButton))
  46999. {
  47000. createNewFolder();
  47001. }
  47002. }
  47003. void FileChooserDialogBox::closeButtonPressed()
  47004. {
  47005. setVisible (false);
  47006. }
  47007. void FileChooserDialogBox::selectionChanged()
  47008. {
  47009. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47010. content->newFolderButton.setVisible (content->chooserComponent.isSaveMode()
  47011. && content->chooserComponent.getRoot().isDirectory());
  47012. }
  47013. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47014. {
  47015. }
  47016. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47017. {
  47018. selectionChanged();
  47019. content->okButton.triggerClick();
  47020. }
  47021. void FileChooserDialogBox::okButtonPressed()
  47022. {
  47023. if ((! (warnAboutOverwritingExistingFiles
  47024. && content->chooserComponent.isSaveMode()
  47025. && content->chooserComponent.getSelectedFile(0).exists()))
  47026. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47027. TRANS("File already exists"),
  47028. TRANS("There's already a file called:")
  47029. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47030. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47031. TRANS("overwrite"),
  47032. TRANS("cancel")))
  47033. {
  47034. exitModalState (1);
  47035. }
  47036. }
  47037. void FileChooserDialogBox::createNewFolder()
  47038. {
  47039. File parent (content->chooserComponent.getRoot());
  47040. if (parent.isDirectory())
  47041. {
  47042. AlertWindow aw (TRANS("New Folder"),
  47043. TRANS("Please enter the name for the folder"),
  47044. AlertWindow::NoIcon, this);
  47045. aw.addTextEditor ("name", String::empty, String::empty, false);
  47046. aw.addButton (TRANS("ok"), 1, KeyPress::returnKey);
  47047. aw.addButton (TRANS("cancel"), KeyPress::escapeKey);
  47048. if (aw.runModalLoop() != 0)
  47049. {
  47050. aw.setVisible (false);
  47051. const String name (File::createLegalFileName (aw.getTextEditorContents ("name")));
  47052. if (! name.isEmpty())
  47053. {
  47054. if (! parent.getChildFile (name).createDirectory())
  47055. {
  47056. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  47057. TRANS ("New Folder"),
  47058. TRANS ("Couldn't create the folder!"));
  47059. }
  47060. content->chooserComponent.refresh();
  47061. }
  47062. }
  47063. }
  47064. }
  47065. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47066. : Component (name), instructions (instructions_),
  47067. chooserComponent (chooserComponent_),
  47068. okButton (chooserComponent_.getActionVerb()),
  47069. cancelButton (TRANS ("Cancel")),
  47070. newFolderButton (TRANS ("New Folder"))
  47071. {
  47072. addAndMakeVisible (&chooserComponent);
  47073. addAndMakeVisible (&okButton);
  47074. okButton.addShortcut (KeyPress::returnKey);
  47075. addAndMakeVisible (&cancelButton);
  47076. cancelButton.addShortcut (KeyPress::escapeKey);
  47077. addChildComponent (&newFolderButton);
  47078. setInterceptsMouseClicks (false, true);
  47079. }
  47080. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47081. {
  47082. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47083. text.draw (g);
  47084. }
  47085. void FileChooserDialogBox::ContentComponent::resized()
  47086. {
  47087. const int buttonHeight = 26;
  47088. Rectangle<int> area (getLocalBounds());
  47089. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47090. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47091. area.removeFromTop (roundToInt (bb.getBottom()) + 10);
  47092. chooserComponent.setBounds (area.removeFromTop (area.getHeight() - buttonHeight - 20));
  47093. Rectangle<int> buttonArea (area.reduced (16, 10));
  47094. okButton.changeWidthToFitText (buttonHeight);
  47095. okButton.setBounds (buttonArea.removeFromRight (okButton.getWidth() + 16));
  47096. buttonArea.removeFromRight (16);
  47097. cancelButton.changeWidthToFitText (buttonHeight);
  47098. cancelButton.setBounds (buttonArea.removeFromRight (cancelButton.getWidth()));
  47099. newFolderButton.changeWidthToFitText (buttonHeight);
  47100. newFolderButton.setBounds (buttonArea.removeFromLeft (newFolderButton.getWidth()));
  47101. }
  47102. END_JUCE_NAMESPACE
  47103. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47104. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47105. BEGIN_JUCE_NAMESPACE
  47106. FileFilter::FileFilter (const String& filterDescription)
  47107. : description (filterDescription)
  47108. {
  47109. }
  47110. FileFilter::~FileFilter()
  47111. {
  47112. }
  47113. const String& FileFilter::getDescription() const throw()
  47114. {
  47115. return description;
  47116. }
  47117. END_JUCE_NAMESPACE
  47118. /*** End of inlined file: juce_FileFilter.cpp ***/
  47119. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47120. BEGIN_JUCE_NAMESPACE
  47121. const Image juce_createIconForFile (const File& file);
  47122. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47123. : ListBox (String::empty, 0),
  47124. DirectoryContentsDisplayComponent (listToShow)
  47125. {
  47126. setModel (this);
  47127. fileList.addChangeListener (this);
  47128. }
  47129. FileListComponent::~FileListComponent()
  47130. {
  47131. fileList.removeChangeListener (this);
  47132. }
  47133. int FileListComponent::getNumSelectedFiles() const
  47134. {
  47135. return getNumSelectedRows();
  47136. }
  47137. const File FileListComponent::getSelectedFile (int index) const
  47138. {
  47139. return fileList.getFile (getSelectedRow (index));
  47140. }
  47141. void FileListComponent::deselectAllFiles()
  47142. {
  47143. deselectAllRows();
  47144. }
  47145. void FileListComponent::scrollToTop()
  47146. {
  47147. getVerticalScrollBar()->setCurrentRangeStart (0);
  47148. }
  47149. void FileListComponent::changeListenerCallback (ChangeBroadcaster*)
  47150. {
  47151. updateContent();
  47152. if (lastDirectory != fileList.getDirectory())
  47153. {
  47154. lastDirectory = fileList.getDirectory();
  47155. deselectAllRows();
  47156. }
  47157. }
  47158. class FileListItemComponent : public Component,
  47159. public TimeSliceClient,
  47160. public AsyncUpdater
  47161. {
  47162. public:
  47163. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47164. : owner (owner_), thread (thread_), index (0), highlighted (false)
  47165. {
  47166. }
  47167. ~FileListItemComponent()
  47168. {
  47169. thread.removeTimeSliceClient (this);
  47170. }
  47171. void paint (Graphics& g)
  47172. {
  47173. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47174. file.getFileName(),
  47175. &icon, fileSize, modTime,
  47176. isDirectory, highlighted,
  47177. index, owner);
  47178. }
  47179. void mouseDown (const MouseEvent& e)
  47180. {
  47181. owner.selectRowsBasedOnModifierKeys (index, e.mods, false);
  47182. owner.sendMouseClickMessage (file, e);
  47183. }
  47184. void mouseDoubleClick (const MouseEvent&)
  47185. {
  47186. owner.sendDoubleClickMessage (file);
  47187. }
  47188. void update (const File& root,
  47189. const DirectoryContentsList::FileInfo* const fileInfo,
  47190. const int index_,
  47191. const bool highlighted_)
  47192. {
  47193. thread.removeTimeSliceClient (this);
  47194. if (highlighted_ != highlighted || index_ != index)
  47195. {
  47196. index = index_;
  47197. highlighted = highlighted_;
  47198. repaint();
  47199. }
  47200. File newFile;
  47201. String newFileSize, newModTime;
  47202. if (fileInfo != 0)
  47203. {
  47204. newFile = root.getChildFile (fileInfo->filename);
  47205. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47206. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47207. }
  47208. if (newFile != file
  47209. || fileSize != newFileSize
  47210. || modTime != newModTime)
  47211. {
  47212. file = newFile;
  47213. fileSize = newFileSize;
  47214. modTime = newModTime;
  47215. icon = Image::null;
  47216. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47217. repaint();
  47218. }
  47219. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47220. {
  47221. updateIcon (true);
  47222. if (! icon.isValid())
  47223. thread.addTimeSliceClient (this);
  47224. }
  47225. }
  47226. int useTimeSlice()
  47227. {
  47228. updateIcon (false);
  47229. return -1;
  47230. }
  47231. void handleAsyncUpdate()
  47232. {
  47233. repaint();
  47234. }
  47235. private:
  47236. FileListComponent& owner;
  47237. TimeSliceThread& thread;
  47238. File file;
  47239. String fileSize, modTime;
  47240. Image icon;
  47241. int index;
  47242. bool highlighted, isDirectory;
  47243. void updateIcon (const bool onlyUpdateIfCached)
  47244. {
  47245. if (icon.isNull())
  47246. {
  47247. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47248. Image im (ImageCache::getFromHashCode (hashCode));
  47249. if (im.isNull() && ! onlyUpdateIfCached)
  47250. {
  47251. im = juce_createIconForFile (file);
  47252. if (im.isValid())
  47253. ImageCache::addImageToCache (im, hashCode);
  47254. }
  47255. if (im.isValid())
  47256. {
  47257. icon = im;
  47258. triggerAsyncUpdate();
  47259. }
  47260. }
  47261. }
  47262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListItemComponent);
  47263. };
  47264. int FileListComponent::getNumRows()
  47265. {
  47266. return fileList.getNumFiles();
  47267. }
  47268. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47269. {
  47270. }
  47271. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47272. {
  47273. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47274. if (comp == 0)
  47275. {
  47276. delete existingComponentToUpdate;
  47277. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47278. }
  47279. DirectoryContentsList::FileInfo fileInfo;
  47280. if (fileList.getFileInfo (row, fileInfo))
  47281. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47282. else
  47283. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47284. return comp;
  47285. }
  47286. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47287. {
  47288. sendSelectionChangeMessage();
  47289. }
  47290. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47291. {
  47292. }
  47293. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47294. {
  47295. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47296. }
  47297. END_JUCE_NAMESPACE
  47298. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47299. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47300. BEGIN_JUCE_NAMESPACE
  47301. FilenameComponent::FilenameComponent (const String& name,
  47302. const File& currentFile,
  47303. const bool canEditFilename,
  47304. const bool isDirectory,
  47305. const bool isForSaving,
  47306. const String& fileBrowserWildcard,
  47307. const String& enforcedSuffix_,
  47308. const String& textWhenNothingSelected)
  47309. : Component (name),
  47310. maxRecentFiles (30),
  47311. isDir (isDirectory),
  47312. isSaving (isForSaving),
  47313. isFileDragOver (false),
  47314. wildcard (fileBrowserWildcard),
  47315. enforcedSuffix (enforcedSuffix_)
  47316. {
  47317. addAndMakeVisible (&filenameBox);
  47318. filenameBox.setEditableText (canEditFilename);
  47319. filenameBox.addListener (this);
  47320. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47321. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47322. setBrowseButtonText ("...");
  47323. setCurrentFile (currentFile, true);
  47324. }
  47325. FilenameComponent::~FilenameComponent()
  47326. {
  47327. }
  47328. void FilenameComponent::paintOverChildren (Graphics& g)
  47329. {
  47330. if (isFileDragOver)
  47331. {
  47332. g.setColour (Colours::red.withAlpha (0.2f));
  47333. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47334. }
  47335. }
  47336. void FilenameComponent::resized()
  47337. {
  47338. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47339. }
  47340. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47341. {
  47342. browseButtonText = newBrowseButtonText;
  47343. lookAndFeelChanged();
  47344. }
  47345. void FilenameComponent::lookAndFeelChanged()
  47346. {
  47347. browseButton = 0;
  47348. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47349. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47350. resized();
  47351. browseButton->addListener (this);
  47352. }
  47353. void FilenameComponent::setTooltip (const String& newTooltip)
  47354. {
  47355. SettableTooltipClient::setTooltip (newTooltip);
  47356. filenameBox.setTooltip (newTooltip);
  47357. }
  47358. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47359. {
  47360. defaultBrowseFile = newDefaultDirectory;
  47361. }
  47362. void FilenameComponent::buttonClicked (Button*)
  47363. {
  47364. FileChooser fc (TRANS("Choose a new file"),
  47365. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47366. : getCurrentFile(),
  47367. wildcard);
  47368. if (isDir ? fc.browseForDirectory()
  47369. : (isSaving ? fc.browseForFileToSave (false)
  47370. : fc.browseForFileToOpen()))
  47371. {
  47372. setCurrentFile (fc.getResult(), true);
  47373. }
  47374. }
  47375. void FilenameComponent::comboBoxChanged (ComboBox*)
  47376. {
  47377. setCurrentFile (getCurrentFile(), true);
  47378. }
  47379. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47380. {
  47381. return true;
  47382. }
  47383. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47384. {
  47385. isFileDragOver = false;
  47386. repaint();
  47387. const File f (filenames[0]);
  47388. if (f.exists() && (f.isDirectory() == isDir))
  47389. setCurrentFile (f, true);
  47390. }
  47391. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47392. {
  47393. isFileDragOver = true;
  47394. repaint();
  47395. }
  47396. void FilenameComponent::fileDragExit (const StringArray&)
  47397. {
  47398. isFileDragOver = false;
  47399. repaint();
  47400. }
  47401. const File FilenameComponent::getCurrentFile() const
  47402. {
  47403. File f (filenameBox.getText());
  47404. if (enforcedSuffix.isNotEmpty())
  47405. f = f.withFileExtension (enforcedSuffix);
  47406. return f;
  47407. }
  47408. void FilenameComponent::setCurrentFile (File newFile,
  47409. const bool addToRecentlyUsedList,
  47410. const bool sendChangeNotification)
  47411. {
  47412. if (enforcedSuffix.isNotEmpty())
  47413. newFile = newFile.withFileExtension (enforcedSuffix);
  47414. if (newFile.getFullPathName() != lastFilename)
  47415. {
  47416. lastFilename = newFile.getFullPathName();
  47417. if (addToRecentlyUsedList)
  47418. addRecentlyUsedFile (newFile);
  47419. filenameBox.setText (lastFilename, true);
  47420. if (sendChangeNotification)
  47421. triggerAsyncUpdate();
  47422. }
  47423. }
  47424. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47425. {
  47426. filenameBox.setEditableText (shouldBeEditable);
  47427. }
  47428. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47429. {
  47430. StringArray names;
  47431. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47432. names.add (filenameBox.getItemText (i));
  47433. return names;
  47434. }
  47435. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47436. {
  47437. if (filenames != getRecentlyUsedFilenames())
  47438. {
  47439. filenameBox.clear();
  47440. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47441. filenameBox.addItem (filenames[i], i + 1);
  47442. }
  47443. }
  47444. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47445. {
  47446. maxRecentFiles = jmax (1, newMaximum);
  47447. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47448. }
  47449. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47450. {
  47451. StringArray files (getRecentlyUsedFilenames());
  47452. if (file.getFullPathName().isNotEmpty())
  47453. {
  47454. files.removeString (file.getFullPathName(), true);
  47455. files.insert (0, file.getFullPathName());
  47456. setRecentlyUsedFilenames (files);
  47457. }
  47458. }
  47459. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47460. {
  47461. listeners.add (listener);
  47462. }
  47463. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47464. {
  47465. listeners.remove (listener);
  47466. }
  47467. void FilenameComponent::handleAsyncUpdate()
  47468. {
  47469. Component::BailOutChecker checker (this);
  47470. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47471. }
  47472. END_JUCE_NAMESPACE
  47473. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47474. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47475. BEGIN_JUCE_NAMESPACE
  47476. FileSearchPathListComponent::FileSearchPathListComponent()
  47477. : addButton ("+"),
  47478. removeButton ("-"),
  47479. changeButton (TRANS ("change...")),
  47480. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47481. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47482. {
  47483. listBox.setModel (this);
  47484. addAndMakeVisible (&listBox);
  47485. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47486. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47487. listBox.setOutlineThickness (1);
  47488. addAndMakeVisible (&addButton);
  47489. addButton.addListener (this);
  47490. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47491. addAndMakeVisible (&removeButton);
  47492. removeButton.addListener (this);
  47493. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47494. addAndMakeVisible (&changeButton);
  47495. changeButton.addListener (this);
  47496. addAndMakeVisible (&upButton);
  47497. upButton.addListener (this);
  47498. {
  47499. Path arrowPath;
  47500. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47501. DrawablePath arrowImage;
  47502. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47503. arrowImage.setPath (arrowPath);
  47504. upButton.setImages (&arrowImage);
  47505. }
  47506. addAndMakeVisible (&downButton);
  47507. downButton.addListener (this);
  47508. {
  47509. Path arrowPath;
  47510. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47511. DrawablePath arrowImage;
  47512. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47513. arrowImage.setPath (arrowPath);
  47514. downButton.setImages (&arrowImage);
  47515. }
  47516. updateButtons();
  47517. }
  47518. FileSearchPathListComponent::~FileSearchPathListComponent()
  47519. {
  47520. }
  47521. void FileSearchPathListComponent::updateButtons()
  47522. {
  47523. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47524. removeButton.setEnabled (anythingSelected);
  47525. changeButton.setEnabled (anythingSelected);
  47526. upButton.setEnabled (anythingSelected);
  47527. downButton.setEnabled (anythingSelected);
  47528. }
  47529. void FileSearchPathListComponent::changed()
  47530. {
  47531. listBox.updateContent();
  47532. listBox.repaint();
  47533. updateButtons();
  47534. }
  47535. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47536. {
  47537. if (newPath.toString() != path.toString())
  47538. {
  47539. path = newPath;
  47540. changed();
  47541. }
  47542. }
  47543. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47544. {
  47545. defaultBrowseTarget = newDefaultDirectory;
  47546. }
  47547. int FileSearchPathListComponent::getNumRows()
  47548. {
  47549. return path.getNumPaths();
  47550. }
  47551. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47552. {
  47553. if (rowIsSelected)
  47554. g.fillAll (findColour (TextEditor::highlightColourId));
  47555. g.setColour (findColour (ListBox::textColourId));
  47556. Font f (height * 0.7f);
  47557. f.setHorizontalScale (0.9f);
  47558. g.setFont (f);
  47559. g.drawText (path [rowNumber].getFullPathName(),
  47560. 4, 0, width - 6, height,
  47561. Justification::centredLeft, true);
  47562. }
  47563. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47564. {
  47565. if (isPositiveAndBelow (row, path.getNumPaths()))
  47566. {
  47567. path.remove (row);
  47568. changed();
  47569. }
  47570. }
  47571. void FileSearchPathListComponent::returnKeyPressed (int row)
  47572. {
  47573. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47574. if (chooser.browseForDirectory())
  47575. {
  47576. path.remove (row);
  47577. path.add (chooser.getResult(), row);
  47578. changed();
  47579. }
  47580. }
  47581. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  47582. {
  47583. returnKeyPressed (row);
  47584. }
  47585. void FileSearchPathListComponent::selectedRowsChanged (int)
  47586. {
  47587. updateButtons();
  47588. }
  47589. void FileSearchPathListComponent::paint (Graphics& g)
  47590. {
  47591. g.fillAll (findColour (backgroundColourId));
  47592. }
  47593. void FileSearchPathListComponent::resized()
  47594. {
  47595. const int buttonH = 22;
  47596. const int buttonY = getHeight() - buttonH - 4;
  47597. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  47598. addButton.setBounds (2, buttonY, buttonH, buttonH);
  47599. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  47600. changeButton.changeWidthToFitText (buttonH);
  47601. downButton.setSize (buttonH * 2, buttonH);
  47602. upButton.setSize (buttonH * 2, buttonH);
  47603. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  47604. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  47605. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  47606. }
  47607. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  47608. {
  47609. return true;
  47610. }
  47611. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  47612. {
  47613. for (int i = filenames.size(); --i >= 0;)
  47614. {
  47615. const File f (filenames[i]);
  47616. if (f.isDirectory())
  47617. {
  47618. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  47619. path.add (f, row);
  47620. changed();
  47621. }
  47622. }
  47623. }
  47624. void FileSearchPathListComponent::buttonClicked (Button* button)
  47625. {
  47626. const int currentRow = listBox.getSelectedRow();
  47627. if (button == &removeButton)
  47628. {
  47629. deleteKeyPressed (currentRow);
  47630. }
  47631. else if (button == &addButton)
  47632. {
  47633. File start (defaultBrowseTarget);
  47634. if (start == File::nonexistent)
  47635. start = path [0];
  47636. if (start == File::nonexistent)
  47637. start = File::getCurrentWorkingDirectory();
  47638. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  47639. if (chooser.browseForDirectory())
  47640. {
  47641. path.add (chooser.getResult(), currentRow);
  47642. }
  47643. }
  47644. else if (button == &changeButton)
  47645. {
  47646. returnKeyPressed (currentRow);
  47647. }
  47648. else if (button == &upButton)
  47649. {
  47650. if (currentRow > 0 && currentRow < path.getNumPaths())
  47651. {
  47652. const File f (path[currentRow]);
  47653. path.remove (currentRow);
  47654. path.add (f, currentRow - 1);
  47655. listBox.selectRow (currentRow - 1);
  47656. }
  47657. }
  47658. else if (button == &downButton)
  47659. {
  47660. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  47661. {
  47662. const File f (path[currentRow]);
  47663. path.remove (currentRow);
  47664. path.add (f, currentRow + 1);
  47665. listBox.selectRow (currentRow + 1);
  47666. }
  47667. }
  47668. changed();
  47669. }
  47670. END_JUCE_NAMESPACE
  47671. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47672. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  47673. BEGIN_JUCE_NAMESPACE
  47674. const Image juce_createIconForFile (const File& file);
  47675. class FileListTreeItem : public TreeViewItem,
  47676. public TimeSliceClient,
  47677. public AsyncUpdater,
  47678. public ChangeListener
  47679. {
  47680. public:
  47681. FileListTreeItem (FileTreeComponent& owner_,
  47682. DirectoryContentsList* const parentContentsList_,
  47683. const int indexInContentsList_,
  47684. const File& file_,
  47685. TimeSliceThread& thread_)
  47686. : file (file_),
  47687. owner (owner_),
  47688. parentContentsList (parentContentsList_),
  47689. indexInContentsList (indexInContentsList_),
  47690. subContentsList (0),
  47691. canDeleteSubContentsList (false),
  47692. thread (thread_),
  47693. icon (0)
  47694. {
  47695. DirectoryContentsList::FileInfo fileInfo;
  47696. if (parentContentsList_ != 0
  47697. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  47698. {
  47699. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  47700. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  47701. isDirectory = fileInfo.isDirectory;
  47702. }
  47703. else
  47704. {
  47705. isDirectory = true;
  47706. }
  47707. }
  47708. ~FileListTreeItem()
  47709. {
  47710. thread.removeTimeSliceClient (this);
  47711. clearSubItems();
  47712. if (canDeleteSubContentsList)
  47713. delete subContentsList;
  47714. }
  47715. bool mightContainSubItems() { return isDirectory; }
  47716. const String getUniqueName() const { return file.getFullPathName(); }
  47717. int getItemHeight() const { return 22; }
  47718. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  47719. void itemOpennessChanged (bool isNowOpen)
  47720. {
  47721. if (isNowOpen)
  47722. {
  47723. clearSubItems();
  47724. isDirectory = file.isDirectory();
  47725. if (isDirectory)
  47726. {
  47727. if (subContentsList == 0)
  47728. {
  47729. jassert (parentContentsList != 0);
  47730. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  47731. l->setDirectory (file, true, true);
  47732. setSubContentsList (l);
  47733. canDeleteSubContentsList = true;
  47734. }
  47735. changeListenerCallback (0);
  47736. }
  47737. }
  47738. }
  47739. void setSubContentsList (DirectoryContentsList* newList)
  47740. {
  47741. jassert (subContentsList == 0);
  47742. subContentsList = newList;
  47743. newList->addChangeListener (this);
  47744. }
  47745. void changeListenerCallback (ChangeBroadcaster*)
  47746. {
  47747. clearSubItems();
  47748. if (isOpen() && subContentsList != 0)
  47749. {
  47750. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  47751. {
  47752. FileListTreeItem* const item
  47753. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  47754. addSubItem (item);
  47755. }
  47756. }
  47757. }
  47758. void paintItem (Graphics& g, int width, int height)
  47759. {
  47760. if (file != File::nonexistent)
  47761. {
  47762. updateIcon (true);
  47763. if (icon.isNull())
  47764. thread.addTimeSliceClient (this);
  47765. }
  47766. owner.getLookAndFeel()
  47767. .drawFileBrowserRow (g, width, height,
  47768. file.getFileName(),
  47769. &icon, fileSize, modTime,
  47770. isDirectory, isSelected(),
  47771. indexInContentsList, owner);
  47772. }
  47773. void itemClicked (const MouseEvent& e)
  47774. {
  47775. owner.sendMouseClickMessage (file, e);
  47776. }
  47777. void itemDoubleClicked (const MouseEvent& e)
  47778. {
  47779. TreeViewItem::itemDoubleClicked (e);
  47780. owner.sendDoubleClickMessage (file);
  47781. }
  47782. void itemSelectionChanged (bool)
  47783. {
  47784. owner.sendSelectionChangeMessage();
  47785. }
  47786. int useTimeSlice()
  47787. {
  47788. updateIcon (false);
  47789. return -1;
  47790. }
  47791. void handleAsyncUpdate()
  47792. {
  47793. owner.repaint();
  47794. }
  47795. const File file;
  47796. private:
  47797. FileTreeComponent& owner;
  47798. DirectoryContentsList* parentContentsList;
  47799. int indexInContentsList;
  47800. DirectoryContentsList* subContentsList;
  47801. bool isDirectory, canDeleteSubContentsList;
  47802. TimeSliceThread& thread;
  47803. Image icon;
  47804. String fileSize;
  47805. String modTime;
  47806. void updateIcon (const bool onlyUpdateIfCached)
  47807. {
  47808. if (icon.isNull())
  47809. {
  47810. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47811. Image im (ImageCache::getFromHashCode (hashCode));
  47812. if (im.isNull() && ! onlyUpdateIfCached)
  47813. {
  47814. im = juce_createIconForFile (file);
  47815. if (im.isValid())
  47816. ImageCache::addImageToCache (im, hashCode);
  47817. }
  47818. if (im.isValid())
  47819. {
  47820. icon = im;
  47821. triggerAsyncUpdate();
  47822. }
  47823. }
  47824. }
  47825. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem);
  47826. };
  47827. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  47828. : DirectoryContentsDisplayComponent (listToShow)
  47829. {
  47830. FileListTreeItem* const root
  47831. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  47832. listToShow.getTimeSliceThread());
  47833. root->setSubContentsList (&listToShow);
  47834. setRootItemVisible (false);
  47835. setRootItem (root);
  47836. }
  47837. FileTreeComponent::~FileTreeComponent()
  47838. {
  47839. deleteRootItem();
  47840. }
  47841. const File FileTreeComponent::getSelectedFile (const int index) const
  47842. {
  47843. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  47844. return item != 0 ? item->file
  47845. : File::nonexistent;
  47846. }
  47847. void FileTreeComponent::deselectAllFiles()
  47848. {
  47849. clearSelectedItems();
  47850. }
  47851. void FileTreeComponent::scrollToTop()
  47852. {
  47853. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  47854. }
  47855. void FileTreeComponent::setDragAndDropDescription (const String& description)
  47856. {
  47857. dragAndDropDescription = description;
  47858. }
  47859. END_JUCE_NAMESPACE
  47860. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  47861. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  47862. BEGIN_JUCE_NAMESPACE
  47863. ImagePreviewComponent::ImagePreviewComponent()
  47864. {
  47865. }
  47866. ImagePreviewComponent::~ImagePreviewComponent()
  47867. {
  47868. }
  47869. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  47870. {
  47871. const int availableW = proportionOfWidth (0.97f);
  47872. const int availableH = getHeight() - 13 * 4;
  47873. const double scale = jmin (1.0,
  47874. availableW / (double) w,
  47875. availableH / (double) h);
  47876. w = roundToInt (scale * w);
  47877. h = roundToInt (scale * h);
  47878. }
  47879. void ImagePreviewComponent::selectedFileChanged (const File& file)
  47880. {
  47881. if (fileToLoad != file)
  47882. {
  47883. fileToLoad = file;
  47884. startTimer (100);
  47885. }
  47886. }
  47887. void ImagePreviewComponent::timerCallback()
  47888. {
  47889. stopTimer();
  47890. currentThumbnail = Image::null;
  47891. currentDetails = String::empty;
  47892. repaint();
  47893. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  47894. if (in != 0)
  47895. {
  47896. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  47897. if (format != 0)
  47898. {
  47899. currentThumbnail = format->decodeImage (*in);
  47900. if (currentThumbnail.isValid())
  47901. {
  47902. int w = currentThumbnail.getWidth();
  47903. int h = currentThumbnail.getHeight();
  47904. currentDetails
  47905. << fileToLoad.getFileName() << "\n"
  47906. << format->getFormatName() << "\n"
  47907. << w << " x " << h << " pixels\n"
  47908. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  47909. getThumbSize (w, h);
  47910. currentThumbnail = currentThumbnail.rescaled (w, h);
  47911. }
  47912. }
  47913. }
  47914. }
  47915. void ImagePreviewComponent::paint (Graphics& g)
  47916. {
  47917. if (currentThumbnail.isValid())
  47918. {
  47919. g.setFont (13.0f);
  47920. int w = currentThumbnail.getWidth();
  47921. int h = currentThumbnail.getHeight();
  47922. getThumbSize (w, h);
  47923. const int numLines = 4;
  47924. const int totalH = 13 * numLines + h + 4;
  47925. const int y = (getHeight() - totalH) / 2;
  47926. g.drawImageWithin (currentThumbnail,
  47927. (getWidth() - w) / 2, y, w, h,
  47928. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  47929. false);
  47930. g.drawFittedText (currentDetails,
  47931. 0, y + h + 4, getWidth(), 100,
  47932. Justification::centredTop, numLines);
  47933. }
  47934. }
  47935. END_JUCE_NAMESPACE
  47936. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  47937. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  47938. BEGIN_JUCE_NAMESPACE
  47939. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  47940. const String& directoryWildcardPatterns,
  47941. const String& description_)
  47942. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  47943. : (description_ + " (" + fileWildcardPatterns + ")"))
  47944. {
  47945. parse (fileWildcardPatterns, fileWildcards);
  47946. parse (directoryWildcardPatterns, directoryWildcards);
  47947. }
  47948. WildcardFileFilter::~WildcardFileFilter()
  47949. {
  47950. }
  47951. bool WildcardFileFilter::isFileSuitable (const File& file) const
  47952. {
  47953. return match (file, fileWildcards);
  47954. }
  47955. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  47956. {
  47957. return match (file, directoryWildcards);
  47958. }
  47959. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  47960. {
  47961. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  47962. result.trim();
  47963. result.removeEmptyStrings();
  47964. // special case for *.*, because people use it to mean "any file", but it
  47965. // would actually ignore files with no extension.
  47966. for (int i = result.size(); --i >= 0;)
  47967. if (result[i] == "*.*")
  47968. result.set (i, "*");
  47969. }
  47970. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  47971. {
  47972. const String filename (file.getFileName());
  47973. for (int i = wildcards.size(); --i >= 0;)
  47974. if (filename.matchesWildcard (wildcards[i], true))
  47975. return true;
  47976. return false;
  47977. }
  47978. END_JUCE_NAMESPACE
  47979. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  47980. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  47981. BEGIN_JUCE_NAMESPACE
  47982. KeyboardFocusTraverser::KeyboardFocusTraverser()
  47983. {
  47984. }
  47985. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  47986. {
  47987. }
  47988. namespace KeyboardFocusHelpers
  47989. {
  47990. // This will sort a set of components, so that they are ordered in terms of
  47991. // left-to-right and then top-to-bottom.
  47992. class ScreenPositionComparator
  47993. {
  47994. public:
  47995. ScreenPositionComparator() {}
  47996. static int compareElements (const Component* const first, const Component* const second)
  47997. {
  47998. int explicitOrder1 = first->getExplicitFocusOrder();
  47999. if (explicitOrder1 <= 0)
  48000. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48001. int explicitOrder2 = second->getExplicitFocusOrder();
  48002. if (explicitOrder2 <= 0)
  48003. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48004. if (explicitOrder1 != explicitOrder2)
  48005. return explicitOrder1 - explicitOrder2;
  48006. const int diff = first->getY() - second->getY();
  48007. return (diff == 0) ? first->getX() - second->getX()
  48008. : diff;
  48009. }
  48010. };
  48011. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48012. {
  48013. if (parent->getNumChildComponents() > 0)
  48014. {
  48015. Array <Component*> localComps;
  48016. ScreenPositionComparator comparator;
  48017. int i;
  48018. for (i = parent->getNumChildComponents(); --i >= 0;)
  48019. {
  48020. Component* const c = parent->getChildComponent (i);
  48021. if (c->isVisible() && c->isEnabled())
  48022. localComps.addSorted (comparator, c);
  48023. }
  48024. for (i = 0; i < localComps.size(); ++i)
  48025. {
  48026. Component* const c = localComps.getUnchecked (i);
  48027. if (c->getWantsKeyboardFocus())
  48028. comps.add (c);
  48029. if (! c->isFocusContainer())
  48030. findAllFocusableComponents (c, comps);
  48031. }
  48032. }
  48033. }
  48034. }
  48035. namespace KeyboardFocusHelpers
  48036. {
  48037. Component* getIncrementedComponent (Component* const current, const int delta)
  48038. {
  48039. Component* focusContainer = current->getParentComponent();
  48040. if (focusContainer != 0)
  48041. {
  48042. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48043. focusContainer = focusContainer->getParentComponent();
  48044. if (focusContainer != 0)
  48045. {
  48046. Array <Component*> comps;
  48047. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48048. if (comps.size() > 0)
  48049. {
  48050. const int index = comps.indexOf (current);
  48051. return comps [(index + comps.size() + delta) % comps.size()];
  48052. }
  48053. }
  48054. }
  48055. return 0;
  48056. }
  48057. }
  48058. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48059. {
  48060. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48061. }
  48062. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48063. {
  48064. return KeyboardFocusHelpers::getIncrementedComponent (current, -1);
  48065. }
  48066. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48067. {
  48068. Array <Component*> comps;
  48069. if (parentComponent != 0)
  48070. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48071. return comps.getFirst();
  48072. }
  48073. END_JUCE_NAMESPACE
  48074. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48075. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48076. BEGIN_JUCE_NAMESPACE
  48077. bool KeyListener::keyStateChanged (const bool, Component*)
  48078. {
  48079. return false;
  48080. }
  48081. END_JUCE_NAMESPACE
  48082. /*** End of inlined file: juce_KeyListener.cpp ***/
  48083. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48084. BEGIN_JUCE_NAMESPACE
  48085. // N.B. these two includes are put here deliberately to avoid problems with
  48086. // old GCCs failing on long include paths
  48087. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  48088. {
  48089. public:
  48090. ChangeKeyButton (KeyMappingEditorComponent& owner_,
  48091. const CommandID commandID_,
  48092. const String& keyName,
  48093. const int keyNum_)
  48094. : Button (keyName),
  48095. owner (owner_),
  48096. commandID (commandID_),
  48097. keyNum (keyNum_)
  48098. {
  48099. setWantsKeyboardFocus (false);
  48100. setTriggeredOnMouseDown (keyNum >= 0);
  48101. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48102. : TRANS("click to change this key-mapping"));
  48103. }
  48104. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48105. {
  48106. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48107. keyNum >= 0 ? getName() : String::empty);
  48108. }
  48109. void clicked()
  48110. {
  48111. if (keyNum >= 0)
  48112. {
  48113. // existing key clicked..
  48114. PopupMenu m;
  48115. m.addItem (1, TRANS("change this key-mapping"));
  48116. m.addSeparator();
  48117. m.addItem (2, TRANS("remove this key-mapping"));
  48118. switch (m.show())
  48119. {
  48120. case 1: assignNewKey(); break;
  48121. case 2: owner.getMappings().removeKeyPress (commandID, keyNum); break;
  48122. default: break;
  48123. }
  48124. }
  48125. else
  48126. {
  48127. assignNewKey(); // + button pressed..
  48128. }
  48129. }
  48130. void fitToContent (const int h) throw()
  48131. {
  48132. if (keyNum < 0)
  48133. {
  48134. setSize (h, h);
  48135. }
  48136. else
  48137. {
  48138. Font f (h * 0.6f);
  48139. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48140. }
  48141. }
  48142. class KeyEntryWindow : public AlertWindow
  48143. {
  48144. public:
  48145. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48146. : AlertWindow (TRANS("New key-mapping"),
  48147. TRANS("Please press a key combination now..."),
  48148. AlertWindow::NoIcon),
  48149. owner (owner_)
  48150. {
  48151. addButton (TRANS("Ok"), 1);
  48152. addButton (TRANS("Cancel"), 0);
  48153. // (avoid return + escape keys getting processed by the buttons..)
  48154. for (int i = getNumChildComponents(); --i >= 0;)
  48155. getChildComponent (i)->setWantsKeyboardFocus (false);
  48156. setWantsKeyboardFocus (true);
  48157. grabKeyboardFocus();
  48158. }
  48159. bool keyPressed (const KeyPress& key)
  48160. {
  48161. lastPress = key;
  48162. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48163. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (key);
  48164. if (previousCommand != 0)
  48165. message << "\n\n" << TRANS("(Currently assigned to \"")
  48166. << owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand) << "\")";
  48167. setMessage (message);
  48168. return true;
  48169. }
  48170. bool keyStateChanged (bool)
  48171. {
  48172. return true;
  48173. }
  48174. KeyPress lastPress;
  48175. private:
  48176. KeyMappingEditorComponent& owner;
  48177. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow);
  48178. };
  48179. void assignNewKey()
  48180. {
  48181. KeyEntryWindow entryWindow (owner);
  48182. if (entryWindow.runModalLoop() != 0)
  48183. {
  48184. entryWindow.setVisible (false);
  48185. if (entryWindow.lastPress.isValid())
  48186. {
  48187. const CommandID previousCommand = owner.getMappings().findCommandForKeyPress (entryWindow.lastPress);
  48188. if (previousCommand == 0
  48189. || AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48190. TRANS("Change key-mapping"),
  48191. TRANS("This key is already assigned to the command \"")
  48192. + owner.getMappings().getCommandManager()->getNameOfCommand (previousCommand)
  48193. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48194. TRANS("Re-assign"),
  48195. TRANS("Cancel")))
  48196. {
  48197. owner.getMappings().removeKeyPress (entryWindow.lastPress);
  48198. if (keyNum >= 0)
  48199. owner.getMappings().removeKeyPress (commandID, keyNum);
  48200. owner.getMappings().addKeyPress (commandID, entryWindow.lastPress, keyNum);
  48201. }
  48202. }
  48203. }
  48204. }
  48205. private:
  48206. KeyMappingEditorComponent& owner;
  48207. const CommandID commandID;
  48208. const int keyNum;
  48209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton);
  48210. };
  48211. class KeyMappingEditorComponent::ItemComponent : public Component
  48212. {
  48213. public:
  48214. ItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48215. : owner (owner_), commandID (commandID_)
  48216. {
  48217. setInterceptsMouseClicks (false, true);
  48218. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48219. const Array <KeyPress> keyPresses (owner.getMappings().getKeyPressesAssignedToCommand (commandID));
  48220. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48221. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  48222. addKeyPressButton (String::empty, -1, isReadOnly);
  48223. }
  48224. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  48225. {
  48226. ChangeKeyButton* const b = new ChangeKeyButton (owner, commandID, desc, index);
  48227. keyChangeButtons.add (b);
  48228. b->setEnabled (! isReadOnly);
  48229. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  48230. addChildComponent (b);
  48231. }
  48232. void paint (Graphics& g)
  48233. {
  48234. g.setFont (getHeight() * 0.7f);
  48235. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48236. g.drawFittedText (owner.getMappings().getCommandManager()->getNameOfCommand (commandID),
  48237. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48238. Justification::centredLeft, true);
  48239. }
  48240. void resized()
  48241. {
  48242. int x = getWidth() - 4;
  48243. for (int i = keyChangeButtons.size(); --i >= 0;)
  48244. {
  48245. ChangeKeyButton* const b = keyChangeButtons.getUnchecked(i);
  48246. b->fitToContent (getHeight() - 2);
  48247. b->setTopRightPosition (x, 1);
  48248. x = b->getX() - 5;
  48249. }
  48250. }
  48251. private:
  48252. KeyMappingEditorComponent& owner;
  48253. OwnedArray<ChangeKeyButton> keyChangeButtons;
  48254. const CommandID commandID;
  48255. enum { maxNumAssignments = 3 };
  48256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  48257. };
  48258. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  48259. {
  48260. public:
  48261. MappingItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48262. : owner (owner_), commandID (commandID_)
  48263. {
  48264. }
  48265. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48266. bool mightContainSubItems() { return false; }
  48267. int getItemHeight() const { return 20; }
  48268. Component* createItemComponent()
  48269. {
  48270. return new ItemComponent (owner, commandID);
  48271. }
  48272. private:
  48273. KeyMappingEditorComponent& owner;
  48274. const CommandID commandID;
  48275. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem);
  48276. };
  48277. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  48278. {
  48279. public:
  48280. CategoryItem (KeyMappingEditorComponent& owner_, const String& name)
  48281. : owner (owner_), categoryName (name)
  48282. {
  48283. }
  48284. const String getUniqueName() const { return categoryName + "_cat"; }
  48285. bool mightContainSubItems() { return true; }
  48286. int getItemHeight() const { return 28; }
  48287. void paintItem (Graphics& g, int width, int height)
  48288. {
  48289. g.setFont (height * 0.6f, Font::bold);
  48290. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48291. g.drawText (categoryName,
  48292. 2, 0, width - 2, height,
  48293. Justification::centredLeft, true);
  48294. }
  48295. void itemOpennessChanged (bool isNowOpen)
  48296. {
  48297. if (isNowOpen)
  48298. {
  48299. if (getNumSubItems() == 0)
  48300. {
  48301. Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categoryName));
  48302. for (int i = 0; i < commands.size(); ++i)
  48303. {
  48304. if (owner.shouldCommandBeIncluded (commands[i]))
  48305. addSubItem (new MappingItem (owner, commands[i]));
  48306. }
  48307. }
  48308. }
  48309. else
  48310. {
  48311. clearSubItems();
  48312. }
  48313. }
  48314. private:
  48315. KeyMappingEditorComponent& owner;
  48316. String categoryName;
  48317. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem);
  48318. };
  48319. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  48320. public ChangeListener,
  48321. public ButtonListener
  48322. {
  48323. public:
  48324. TopLevelItem (KeyMappingEditorComponent& owner_)
  48325. : owner (owner_)
  48326. {
  48327. setLinesDrawnForSubItems (false);
  48328. owner.getMappings().addChangeListener (this);
  48329. }
  48330. ~TopLevelItem()
  48331. {
  48332. owner.getMappings().removeChangeListener (this);
  48333. }
  48334. bool mightContainSubItems() { return true; }
  48335. const String getUniqueName() const { return "keys"; }
  48336. void changeListenerCallback (ChangeBroadcaster*)
  48337. {
  48338. const OpennessRestorer openness (*this);
  48339. clearSubItems();
  48340. const StringArray categories (owner.getMappings().getCommandManager()->getCommandCategories());
  48341. for (int i = 0; i < categories.size(); ++i)
  48342. {
  48343. const Array <CommandID> commands (owner.getMappings().getCommandManager()->getCommandsInCategory (categories[i]));
  48344. int count = 0;
  48345. for (int j = 0; j < commands.size(); ++j)
  48346. if (owner.shouldCommandBeIncluded (commands[j]))
  48347. ++count;
  48348. if (count > 0)
  48349. addSubItem (new CategoryItem (owner, categories[i]));
  48350. }
  48351. }
  48352. void buttonClicked (Button*)
  48353. {
  48354. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48355. TRANS("Reset to defaults"),
  48356. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48357. TRANS("Reset")))
  48358. {
  48359. owner.getMappings().resetToDefaultMappings();
  48360. }
  48361. }
  48362. private:
  48363. KeyMappingEditorComponent& owner;
  48364. };
  48365. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  48366. const bool showResetToDefaultButton)
  48367. : mappings (mappingManager),
  48368. resetButton (TRANS ("reset to defaults"))
  48369. {
  48370. treeItem = new TopLevelItem (*this);
  48371. if (showResetToDefaultButton)
  48372. {
  48373. addAndMakeVisible (&resetButton);
  48374. resetButton.addListener (treeItem);
  48375. }
  48376. addAndMakeVisible (&tree);
  48377. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48378. tree.setRootItemVisible (false);
  48379. tree.setDefaultOpenness (true);
  48380. tree.setRootItem (treeItem);
  48381. }
  48382. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48383. {
  48384. tree.setRootItem (0);
  48385. }
  48386. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48387. const Colour& textColour)
  48388. {
  48389. setColour (backgroundColourId, mainBackground);
  48390. setColour (textColourId, textColour);
  48391. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48392. }
  48393. void KeyMappingEditorComponent::parentHierarchyChanged()
  48394. {
  48395. treeItem->changeListenerCallback (0);
  48396. }
  48397. void KeyMappingEditorComponent::resized()
  48398. {
  48399. int h = getHeight();
  48400. if (resetButton.isVisible())
  48401. {
  48402. const int buttonHeight = 20;
  48403. h -= buttonHeight + 8;
  48404. int x = getWidth() - 8;
  48405. resetButton.changeWidthToFitText (buttonHeight);
  48406. resetButton.setTopRightPosition (x, h + 6);
  48407. }
  48408. tree.setBounds (0, 0, getWidth(), h);
  48409. }
  48410. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48411. {
  48412. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48413. return ci != 0 && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  48414. }
  48415. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48416. {
  48417. const ApplicationCommandInfo* const ci = mappings.getCommandManager()->getCommandForID (commandID);
  48418. return ci != 0 && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  48419. }
  48420. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48421. {
  48422. return key.getTextDescription();
  48423. }
  48424. END_JUCE_NAMESPACE
  48425. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48426. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48427. BEGIN_JUCE_NAMESPACE
  48428. KeyPress::KeyPress() throw()
  48429. : keyCode (0),
  48430. mods (0),
  48431. textCharacter (0)
  48432. {
  48433. }
  48434. KeyPress::KeyPress (const int keyCode_,
  48435. const ModifierKeys& mods_,
  48436. const juce_wchar textCharacter_) throw()
  48437. : keyCode (keyCode_),
  48438. mods (mods_),
  48439. textCharacter (textCharacter_)
  48440. {
  48441. }
  48442. KeyPress::KeyPress (const int keyCode_) throw()
  48443. : keyCode (keyCode_),
  48444. textCharacter (0)
  48445. {
  48446. }
  48447. KeyPress::KeyPress (const KeyPress& other) throw()
  48448. : keyCode (other.keyCode),
  48449. mods (other.mods),
  48450. textCharacter (other.textCharacter)
  48451. {
  48452. }
  48453. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48454. {
  48455. keyCode = other.keyCode;
  48456. mods = other.mods;
  48457. textCharacter = other.textCharacter;
  48458. return *this;
  48459. }
  48460. bool KeyPress::operator== (const KeyPress& other) const throw()
  48461. {
  48462. return mods.getRawFlags() == other.mods.getRawFlags()
  48463. && (textCharacter == other.textCharacter
  48464. || textCharacter == 0
  48465. || other.textCharacter == 0)
  48466. && (keyCode == other.keyCode
  48467. || (keyCode < 256
  48468. && other.keyCode < 256
  48469. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48470. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48471. }
  48472. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48473. {
  48474. return ! operator== (other);
  48475. }
  48476. bool KeyPress::isCurrentlyDown() const
  48477. {
  48478. return isKeyCurrentlyDown (keyCode)
  48479. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48480. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48481. }
  48482. namespace KeyPressHelpers
  48483. {
  48484. struct KeyNameAndCode
  48485. {
  48486. const char* name;
  48487. int code;
  48488. };
  48489. const KeyNameAndCode translations[] =
  48490. {
  48491. { "spacebar", KeyPress::spaceKey },
  48492. { "return", KeyPress::returnKey },
  48493. { "escape", KeyPress::escapeKey },
  48494. { "backspace", KeyPress::backspaceKey },
  48495. { "cursor left", KeyPress::leftKey },
  48496. { "cursor right", KeyPress::rightKey },
  48497. { "cursor up", KeyPress::upKey },
  48498. { "cursor down", KeyPress::downKey },
  48499. { "page up", KeyPress::pageUpKey },
  48500. { "page down", KeyPress::pageDownKey },
  48501. { "home", KeyPress::homeKey },
  48502. { "end", KeyPress::endKey },
  48503. { "delete", KeyPress::deleteKey },
  48504. { "insert", KeyPress::insertKey },
  48505. { "tab", KeyPress::tabKey },
  48506. { "play", KeyPress::playKey },
  48507. { "stop", KeyPress::stopKey },
  48508. { "fast forward", KeyPress::fastForwardKey },
  48509. { "rewind", KeyPress::rewindKey }
  48510. };
  48511. const String numberPadPrefix() { return "numpad "; }
  48512. }
  48513. const KeyPress KeyPress::createFromDescription (const String& desc)
  48514. {
  48515. int modifiers = 0;
  48516. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48517. || desc.containsWholeWordIgnoreCase ("control")
  48518. || desc.containsWholeWordIgnoreCase ("ctl"))
  48519. modifiers |= ModifierKeys::ctrlModifier;
  48520. if (desc.containsWholeWordIgnoreCase ("shift")
  48521. || desc.containsWholeWordIgnoreCase ("shft"))
  48522. modifiers |= ModifierKeys::shiftModifier;
  48523. if (desc.containsWholeWordIgnoreCase ("alt")
  48524. || desc.containsWholeWordIgnoreCase ("option"))
  48525. modifiers |= ModifierKeys::altModifier;
  48526. if (desc.containsWholeWordIgnoreCase ("command")
  48527. || desc.containsWholeWordIgnoreCase ("cmd"))
  48528. modifiers |= ModifierKeys::commandModifier;
  48529. int key = 0;
  48530. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48531. {
  48532. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48533. {
  48534. key = KeyPressHelpers::translations[i].code;
  48535. break;
  48536. }
  48537. }
  48538. if (key == 0)
  48539. {
  48540. // see if it's a numpad key..
  48541. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  48542. {
  48543. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  48544. if (lastChar >= '0' && lastChar <= '9')
  48545. key = numberPad0 + lastChar - '0';
  48546. else if (lastChar == '+')
  48547. key = numberPadAdd;
  48548. else if (lastChar == '-')
  48549. key = numberPadSubtract;
  48550. else if (lastChar == '*')
  48551. key = numberPadMultiply;
  48552. else if (lastChar == '/')
  48553. key = numberPadDivide;
  48554. else if (lastChar == '.')
  48555. key = numberPadDecimalPoint;
  48556. else if (lastChar == '=')
  48557. key = numberPadEquals;
  48558. else if (desc.endsWith ("separator"))
  48559. key = numberPadSeparator;
  48560. else if (desc.endsWith ("delete"))
  48561. key = numberPadDelete;
  48562. }
  48563. if (key == 0)
  48564. {
  48565. // see if it's a function key..
  48566. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  48567. for (int i = 1; i <= 12; ++i)
  48568. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  48569. key = F1Key + i - 1;
  48570. if (key == 0)
  48571. {
  48572. // give up and use the hex code..
  48573. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  48574. .toLowerCase()
  48575. .retainCharacters ("0123456789abcdef")
  48576. .getHexValue32();
  48577. if (hexCode > 0)
  48578. key = hexCode;
  48579. else
  48580. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  48581. }
  48582. }
  48583. }
  48584. return KeyPress (key, ModifierKeys (modifiers), 0);
  48585. }
  48586. const String KeyPress::getTextDescription() const
  48587. {
  48588. String desc;
  48589. if (keyCode > 0)
  48590. {
  48591. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  48592. // want to store it as being a slash, not shift+whatever.
  48593. if (textCharacter == '/')
  48594. return "/";
  48595. if (mods.isCtrlDown())
  48596. desc << "ctrl + ";
  48597. if (mods.isShiftDown())
  48598. desc << "shift + ";
  48599. #if JUCE_MAC
  48600. // only do this on the mac, because on Windows ctrl and command are the same,
  48601. // and this would get confusing
  48602. if (mods.isCommandDown())
  48603. desc << "command + ";
  48604. if (mods.isAltDown())
  48605. desc << "option + ";
  48606. #else
  48607. if (mods.isAltDown())
  48608. desc << "alt + ";
  48609. #endif
  48610. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48611. if (keyCode == KeyPressHelpers::translations[i].code)
  48612. return desc + KeyPressHelpers::translations[i].name;
  48613. if (keyCode >= F1Key && keyCode <= F16Key)
  48614. desc << 'F' << (1 + keyCode - F1Key);
  48615. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  48616. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  48617. else if (keyCode >= 33 && keyCode < 176)
  48618. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  48619. else if (keyCode == numberPadAdd)
  48620. desc << KeyPressHelpers::numberPadPrefix() << '+';
  48621. else if (keyCode == numberPadSubtract)
  48622. desc << KeyPressHelpers::numberPadPrefix() << '-';
  48623. else if (keyCode == numberPadMultiply)
  48624. desc << KeyPressHelpers::numberPadPrefix() << '*';
  48625. else if (keyCode == numberPadDivide)
  48626. desc << KeyPressHelpers::numberPadPrefix() << '/';
  48627. else if (keyCode == numberPadSeparator)
  48628. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  48629. else if (keyCode == numberPadDecimalPoint)
  48630. desc << KeyPressHelpers::numberPadPrefix() << '.';
  48631. else if (keyCode == numberPadDelete)
  48632. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  48633. else
  48634. desc << '#' << String::toHexString (keyCode);
  48635. }
  48636. return desc;
  48637. }
  48638. END_JUCE_NAMESPACE
  48639. /*** End of inlined file: juce_KeyPress.cpp ***/
  48640. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  48641. BEGIN_JUCE_NAMESPACE
  48642. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  48643. : commandManager (commandManager_)
  48644. {
  48645. // A manager is needed to get the descriptions of commands, and will be called when
  48646. // a command is invoked. So you can't leave this null..
  48647. jassert (commandManager_ != 0);
  48648. Desktop::getInstance().addFocusChangeListener (this);
  48649. }
  48650. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  48651. : commandManager (other.commandManager)
  48652. {
  48653. Desktop::getInstance().addFocusChangeListener (this);
  48654. }
  48655. KeyPressMappingSet::~KeyPressMappingSet()
  48656. {
  48657. Desktop::getInstance().removeFocusChangeListener (this);
  48658. }
  48659. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  48660. {
  48661. for (int i = 0; i < mappings.size(); ++i)
  48662. if (mappings.getUnchecked(i)->commandID == commandID)
  48663. return mappings.getUnchecked (i)->keypresses;
  48664. return Array <KeyPress> ();
  48665. }
  48666. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  48667. const KeyPress& newKeyPress,
  48668. int insertIndex)
  48669. {
  48670. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  48671. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  48672. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  48673. && ! newKeyPress.getModifiers().isShiftDown()));
  48674. if (findCommandForKeyPress (newKeyPress) != commandID)
  48675. {
  48676. removeKeyPress (newKeyPress);
  48677. if (newKeyPress.isValid())
  48678. {
  48679. for (int i = mappings.size(); --i >= 0;)
  48680. {
  48681. if (mappings.getUnchecked(i)->commandID == commandID)
  48682. {
  48683. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  48684. sendChangeMessage();
  48685. return;
  48686. }
  48687. }
  48688. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48689. if (ci != 0)
  48690. {
  48691. CommandMapping* const cm = new CommandMapping();
  48692. cm->commandID = commandID;
  48693. cm->keypresses.add (newKeyPress);
  48694. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  48695. mappings.add (cm);
  48696. sendChangeMessage();
  48697. }
  48698. }
  48699. }
  48700. }
  48701. void KeyPressMappingSet::resetToDefaultMappings()
  48702. {
  48703. mappings.clear();
  48704. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  48705. {
  48706. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  48707. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48708. {
  48709. addKeyPress (ci->commandID,
  48710. ci->defaultKeypresses.getReference (j));
  48711. }
  48712. }
  48713. sendChangeMessage();
  48714. }
  48715. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  48716. {
  48717. clearAllKeyPresses (commandID);
  48718. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48719. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  48720. {
  48721. addKeyPress (ci->commandID,
  48722. ci->defaultKeypresses.getReference (j));
  48723. }
  48724. }
  48725. void KeyPressMappingSet::clearAllKeyPresses()
  48726. {
  48727. if (mappings.size() > 0)
  48728. {
  48729. sendChangeMessage();
  48730. mappings.clear();
  48731. }
  48732. }
  48733. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  48734. {
  48735. for (int i = mappings.size(); --i >= 0;)
  48736. {
  48737. if (mappings.getUnchecked(i)->commandID == commandID)
  48738. {
  48739. mappings.remove (i);
  48740. sendChangeMessage();
  48741. }
  48742. }
  48743. }
  48744. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  48745. {
  48746. if (keypress.isValid())
  48747. {
  48748. for (int i = mappings.size(); --i >= 0;)
  48749. {
  48750. CommandMapping* const cm = mappings.getUnchecked(i);
  48751. for (int j = cm->keypresses.size(); --j >= 0;)
  48752. {
  48753. if (keypress == cm->keypresses [j])
  48754. {
  48755. cm->keypresses.remove (j);
  48756. sendChangeMessage();
  48757. }
  48758. }
  48759. }
  48760. }
  48761. }
  48762. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  48763. {
  48764. for (int i = mappings.size(); --i >= 0;)
  48765. {
  48766. if (mappings.getUnchecked(i)->commandID == commandID)
  48767. {
  48768. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  48769. sendChangeMessage();
  48770. break;
  48771. }
  48772. }
  48773. }
  48774. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  48775. {
  48776. for (int i = 0; i < mappings.size(); ++i)
  48777. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  48778. return mappings.getUnchecked(i)->commandID;
  48779. return 0;
  48780. }
  48781. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  48782. {
  48783. for (int i = mappings.size(); --i >= 0;)
  48784. if (mappings.getUnchecked(i)->commandID == commandID)
  48785. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  48786. return false;
  48787. }
  48788. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  48789. const KeyPress& key,
  48790. const bool isKeyDown,
  48791. const int millisecsSinceKeyPressed,
  48792. Component* const originatingComponent) const
  48793. {
  48794. ApplicationCommandTarget::InvocationInfo info (commandID);
  48795. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  48796. info.isKeyDown = isKeyDown;
  48797. info.keyPress = key;
  48798. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  48799. info.originatingComponent = originatingComponent;
  48800. commandManager->invoke (info, false);
  48801. }
  48802. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  48803. {
  48804. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  48805. {
  48806. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  48807. {
  48808. // if the XML was created as a set of differences from the default mappings,
  48809. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  48810. resetToDefaultMappings();
  48811. }
  48812. else
  48813. {
  48814. // if the XML was created calling createXml (false), then we need to clear all
  48815. // the keys and treat the xml as describing the entire set of mappings.
  48816. clearAllKeyPresses();
  48817. }
  48818. forEachXmlChildElement (xmlVersion, map)
  48819. {
  48820. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  48821. if (commandId != 0)
  48822. {
  48823. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  48824. if (map->hasTagName ("MAPPING"))
  48825. {
  48826. addKeyPress (commandId, key);
  48827. }
  48828. else if (map->hasTagName ("UNMAPPING"))
  48829. {
  48830. if (containsMapping (commandId, key))
  48831. removeKeyPress (key);
  48832. }
  48833. }
  48834. }
  48835. return true;
  48836. }
  48837. return false;
  48838. }
  48839. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  48840. {
  48841. ScopedPointer <KeyPressMappingSet> defaultSet;
  48842. if (saveDifferencesFromDefaultSet)
  48843. {
  48844. defaultSet = new KeyPressMappingSet (commandManager);
  48845. defaultSet->resetToDefaultMappings();
  48846. }
  48847. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  48848. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  48849. int i;
  48850. for (i = 0; i < mappings.size(); ++i)
  48851. {
  48852. const CommandMapping* const cm = mappings.getUnchecked(i);
  48853. for (int j = 0; j < cm->keypresses.size(); ++j)
  48854. {
  48855. if (defaultSet == 0
  48856. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48857. {
  48858. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  48859. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48860. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48861. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48862. }
  48863. }
  48864. }
  48865. if (defaultSet != 0)
  48866. {
  48867. for (i = 0; i < defaultSet->mappings.size(); ++i)
  48868. {
  48869. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  48870. for (int j = 0; j < cm->keypresses.size(); ++j)
  48871. {
  48872. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  48873. {
  48874. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  48875. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  48876. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  48877. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  48878. }
  48879. }
  48880. }
  48881. }
  48882. return doc;
  48883. }
  48884. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  48885. Component* originatingComponent)
  48886. {
  48887. bool used = false;
  48888. const CommandID commandID = findCommandForKeyPress (key);
  48889. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  48890. if (ci != 0
  48891. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  48892. {
  48893. ApplicationCommandInfo info (0);
  48894. if (commandManager->getTargetForCommand (commandID, info) != 0
  48895. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  48896. {
  48897. invokeCommand (commandID, key, true, 0, originatingComponent);
  48898. used = true;
  48899. }
  48900. else
  48901. {
  48902. if (originatingComponent != 0)
  48903. originatingComponent->getLookAndFeel().playAlertSound();
  48904. }
  48905. }
  48906. return used;
  48907. }
  48908. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  48909. {
  48910. bool used = false;
  48911. const uint32 now = Time::getMillisecondCounter();
  48912. for (int i = mappings.size(); --i >= 0;)
  48913. {
  48914. CommandMapping* const cm = mappings.getUnchecked(i);
  48915. if (cm->wantsKeyUpDownCallbacks)
  48916. {
  48917. for (int j = cm->keypresses.size(); --j >= 0;)
  48918. {
  48919. const KeyPress key (cm->keypresses.getReference (j));
  48920. const bool isDown = key.isCurrentlyDown();
  48921. int keyPressEntryIndex = 0;
  48922. bool wasDown = false;
  48923. for (int k = keysDown.size(); --k >= 0;)
  48924. {
  48925. if (key == keysDown.getUnchecked(k)->key)
  48926. {
  48927. keyPressEntryIndex = k;
  48928. wasDown = true;
  48929. used = true;
  48930. break;
  48931. }
  48932. }
  48933. if (isDown != wasDown)
  48934. {
  48935. int millisecs = 0;
  48936. if (isDown)
  48937. {
  48938. KeyPressTime* const k = new KeyPressTime();
  48939. k->key = key;
  48940. k->timeWhenPressed = now;
  48941. keysDown.add (k);
  48942. }
  48943. else
  48944. {
  48945. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  48946. if (now > pressTime)
  48947. millisecs = now - pressTime;
  48948. keysDown.remove (keyPressEntryIndex);
  48949. }
  48950. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  48951. used = true;
  48952. }
  48953. }
  48954. }
  48955. }
  48956. return used;
  48957. }
  48958. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  48959. {
  48960. if (focusedComponent != 0)
  48961. focusedComponent->keyStateChanged (false);
  48962. }
  48963. END_JUCE_NAMESPACE
  48964. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  48965. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  48966. BEGIN_JUCE_NAMESPACE
  48967. ModifierKeys::ModifierKeys (const int flags_) throw()
  48968. : flags (flags_)
  48969. {
  48970. }
  48971. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  48972. : flags (other.flags)
  48973. {
  48974. }
  48975. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  48976. {
  48977. flags = other.flags;
  48978. return *this;
  48979. }
  48980. ModifierKeys ModifierKeys::currentModifiers;
  48981. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  48982. {
  48983. return currentModifiers;
  48984. }
  48985. int ModifierKeys::getNumMouseButtonsDown() const throw()
  48986. {
  48987. int num = 0;
  48988. if (isLeftButtonDown()) ++num;
  48989. if (isRightButtonDown()) ++num;
  48990. if (isMiddleButtonDown()) ++num;
  48991. return num;
  48992. }
  48993. END_JUCE_NAMESPACE
  48994. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  48995. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  48996. BEGIN_JUCE_NAMESPACE
  48997. class ComponentAnimator::AnimationTask
  48998. {
  48999. public:
  49000. AnimationTask (Component* const comp)
  49001. : component (comp)
  49002. {
  49003. }
  49004. void reset (const Rectangle<int>& finalBounds,
  49005. float finalAlpha,
  49006. int millisecondsToSpendMoving,
  49007. bool useProxyComponent,
  49008. double startSpeed_, double endSpeed_)
  49009. {
  49010. msElapsed = 0;
  49011. msTotal = jmax (1, millisecondsToSpendMoving);
  49012. lastProgress = 0;
  49013. destination = finalBounds;
  49014. destAlpha = finalAlpha;
  49015. isMoving = (finalBounds != component->getBounds());
  49016. isChangingAlpha = (finalAlpha != component->getAlpha());
  49017. left = component->getX();
  49018. top = component->getY();
  49019. right = component->getRight();
  49020. bottom = component->getBottom();
  49021. alpha = component->getAlpha();
  49022. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49023. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49024. midSpeed = invTotalDistance;
  49025. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49026. if (useProxyComponent)
  49027. proxy = new ProxyComponent (*component);
  49028. else
  49029. proxy = 0;
  49030. component->setVisible (! useProxyComponent);
  49031. }
  49032. bool useTimeslice (const int elapsed)
  49033. {
  49034. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49035. : static_cast <Component*> (component);
  49036. if (c != 0)
  49037. {
  49038. msElapsed += elapsed;
  49039. double newProgress = msElapsed / (double) msTotal;
  49040. if (newProgress >= 0 && newProgress < 1.0)
  49041. {
  49042. newProgress = timeToDistance (newProgress);
  49043. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49044. jassert (newProgress >= lastProgress);
  49045. lastProgress = newProgress;
  49046. if (delta < 1.0)
  49047. {
  49048. bool stillBusy = false;
  49049. if (isMoving)
  49050. {
  49051. left += (destination.getX() - left) * delta;
  49052. top += (destination.getY() - top) * delta;
  49053. right += (destination.getRight() - right) * delta;
  49054. bottom += (destination.getBottom() - bottom) * delta;
  49055. const Rectangle<int> newBounds (roundToInt (left),
  49056. roundToInt (top),
  49057. roundToInt (right - left),
  49058. roundToInt (bottom - top));
  49059. if (newBounds != destination)
  49060. {
  49061. c->setBounds (newBounds);
  49062. stillBusy = true;
  49063. }
  49064. }
  49065. if (isChangingAlpha)
  49066. {
  49067. alpha += (destAlpha - alpha) * delta;
  49068. c->setAlpha ((float) alpha);
  49069. stillBusy = true;
  49070. }
  49071. if (stillBusy)
  49072. return true;
  49073. }
  49074. }
  49075. }
  49076. moveToFinalDestination();
  49077. return false;
  49078. }
  49079. void moveToFinalDestination()
  49080. {
  49081. if (component != 0)
  49082. {
  49083. component->setAlpha ((float) destAlpha);
  49084. component->setBounds (destination);
  49085. }
  49086. }
  49087. class ProxyComponent : public Component
  49088. {
  49089. public:
  49090. ProxyComponent (Component& component)
  49091. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49092. {
  49093. setBounds (component.getBounds());
  49094. setAlpha (component.getAlpha());
  49095. setInterceptsMouseClicks (false, false);
  49096. Component* const parent = component.getParentComponent();
  49097. if (parent != 0)
  49098. parent->addAndMakeVisible (this);
  49099. else if (component.isOnDesktop() && component.getPeer() != 0)
  49100. addToDesktop (component.getPeer()->getStyleFlags());
  49101. else
  49102. jassertfalse; // seem to be trying to animate a component that's not visible..
  49103. setVisible (true);
  49104. toBehind (&component);
  49105. }
  49106. void paint (Graphics& g)
  49107. {
  49108. g.setOpacity (1.0f);
  49109. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49110. 0, 0, image.getWidth(), image.getHeight());
  49111. }
  49112. private:
  49113. Image image;
  49114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProxyComponent);
  49115. };
  49116. WeakReference<Component> component;
  49117. ScopedPointer<Component> proxy;
  49118. Rectangle<int> destination;
  49119. double destAlpha;
  49120. int msElapsed, msTotal;
  49121. double startSpeed, midSpeed, endSpeed, lastProgress;
  49122. double left, top, right, bottom, alpha;
  49123. bool isMoving, isChangingAlpha;
  49124. private:
  49125. double timeToDistance (const double time) const throw()
  49126. {
  49127. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49128. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49129. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49130. }
  49131. };
  49132. ComponentAnimator::ComponentAnimator()
  49133. : lastTime (0)
  49134. {
  49135. }
  49136. ComponentAnimator::~ComponentAnimator()
  49137. {
  49138. }
  49139. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49140. {
  49141. for (int i = tasks.size(); --i >= 0;)
  49142. if (component == tasks.getUnchecked(i)->component.get())
  49143. return tasks.getUnchecked(i);
  49144. return 0;
  49145. }
  49146. void ComponentAnimator::animateComponent (Component* const component,
  49147. const Rectangle<int>& finalBounds,
  49148. const float finalAlpha,
  49149. const int millisecondsToSpendMoving,
  49150. const bool useProxyComponent,
  49151. const double startSpeed,
  49152. const double endSpeed)
  49153. {
  49154. // the speeds must be 0 or greater!
  49155. jassert (startSpeed >= 0 && endSpeed >= 0)
  49156. if (component != 0)
  49157. {
  49158. AnimationTask* at = findTaskFor (component);
  49159. if (at == 0)
  49160. {
  49161. at = new AnimationTask (component);
  49162. tasks.add (at);
  49163. sendChangeMessage();
  49164. }
  49165. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49166. useProxyComponent, startSpeed, endSpeed);
  49167. if (! isTimerRunning())
  49168. {
  49169. lastTime = Time::getMillisecondCounter();
  49170. startTimer (1000 / 50);
  49171. }
  49172. }
  49173. }
  49174. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49175. {
  49176. if (component != 0)
  49177. {
  49178. if (component->isShowing() && millisecondsToTake > 0)
  49179. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49180. component->setVisible (false);
  49181. }
  49182. }
  49183. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49184. {
  49185. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49186. {
  49187. component->setAlpha (0.0f);
  49188. component->setVisible (true);
  49189. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49190. }
  49191. }
  49192. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49193. {
  49194. if (tasks.size() > 0)
  49195. {
  49196. if (moveComponentsToTheirFinalPositions)
  49197. for (int i = tasks.size(); --i >= 0;)
  49198. tasks.getUnchecked(i)->moveToFinalDestination();
  49199. tasks.clear();
  49200. sendChangeMessage();
  49201. }
  49202. }
  49203. void ComponentAnimator::cancelAnimation (Component* const component,
  49204. const bool moveComponentToItsFinalPosition)
  49205. {
  49206. AnimationTask* const at = findTaskFor (component);
  49207. if (at != 0)
  49208. {
  49209. if (moveComponentToItsFinalPosition)
  49210. at->moveToFinalDestination();
  49211. tasks.removeObject (at);
  49212. sendChangeMessage();
  49213. }
  49214. }
  49215. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49216. {
  49217. jassert (component != 0);
  49218. AnimationTask* const at = findTaskFor (component);
  49219. if (at != 0)
  49220. return at->destination;
  49221. return component->getBounds();
  49222. }
  49223. bool ComponentAnimator::isAnimating (Component* component) const
  49224. {
  49225. return findTaskFor (component) != 0;
  49226. }
  49227. void ComponentAnimator::timerCallback()
  49228. {
  49229. const uint32 timeNow = Time::getMillisecondCounter();
  49230. if (lastTime == 0 || lastTime == timeNow)
  49231. lastTime = timeNow;
  49232. const int elapsed = timeNow - lastTime;
  49233. for (int i = tasks.size(); --i >= 0;)
  49234. {
  49235. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49236. {
  49237. tasks.remove (i);
  49238. sendChangeMessage();
  49239. }
  49240. }
  49241. lastTime = timeNow;
  49242. if (tasks.size() == 0)
  49243. stopTimer();
  49244. }
  49245. END_JUCE_NAMESPACE
  49246. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49247. /*** Start of inlined file: juce_ComponentBuilder.cpp ***/
  49248. BEGIN_JUCE_NAMESPACE
  49249. namespace ComponentBuilderHelpers
  49250. {
  49251. const String getStateId (const ValueTree& state)
  49252. {
  49253. return state [ComponentBuilder::idProperty].toString();
  49254. }
  49255. Component* findComponentWithID (OwnedArray<Component>& components, const String& compId)
  49256. {
  49257. jassert (compId.isNotEmpty());
  49258. for (int i = components.size(); --i >= 0;)
  49259. {
  49260. Component* const c = components.getUnchecked (i);
  49261. if (c->getComponentID() == compId)
  49262. return components.removeAndReturn (i);
  49263. }
  49264. return 0;
  49265. }
  49266. Component* findComponentWithID (Component* const c, const String& compId)
  49267. {
  49268. jassert (compId.isNotEmpty());
  49269. if (c->getComponentID() == compId)
  49270. return c;
  49271. for (int i = c->getNumChildComponents(); --i >= 0;)
  49272. {
  49273. Component* const child = findComponentWithID (c->getChildComponent (i), compId);
  49274. if (child != 0)
  49275. return child;
  49276. }
  49277. return 0;
  49278. }
  49279. Component* createNewComponent (ComponentBuilder::TypeHandler& type,
  49280. const ValueTree& state, Component* parent)
  49281. {
  49282. Component* const c = type.addNewComponentFromState (state, parent);
  49283. jassert (c != 0 && c->getParentComponent() == parent);
  49284. c->setComponentID (getStateId (state));
  49285. return c;
  49286. }
  49287. void updateComponent (ComponentBuilder& builder, const ValueTree& state)
  49288. {
  49289. Component* topLevelComp = builder.getManagedComponent();
  49290. if (topLevelComp != 0)
  49291. {
  49292. ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
  49293. const String uid (getStateId (state));
  49294. if (type == 0 || uid.isEmpty())
  49295. {
  49296. // ..handle the case where a child of the actual state node has changed.
  49297. if (state.getParent().isValid())
  49298. updateComponent (builder, state.getParent());
  49299. }
  49300. else
  49301. {
  49302. Component* const changedComp = findComponentWithID (topLevelComp, uid);
  49303. if (changedComp != 0)
  49304. type->updateComponentFromState (changedComp, state);
  49305. }
  49306. }
  49307. }
  49308. }
  49309. const Identifier ComponentBuilder::idProperty ("id");
  49310. ComponentBuilder::ComponentBuilder (const ValueTree& state_)
  49311. : state (state_), imageProvider (0)
  49312. {
  49313. state.addListener (this);
  49314. }
  49315. ComponentBuilder::~ComponentBuilder()
  49316. {
  49317. state.removeListener (this);
  49318. #if JUCE_DEBUG
  49319. // Don't delete the managed component!! The builder owns that component, and will delete
  49320. // it automatically when it gets deleted.
  49321. jassert (componentRef.get() == static_cast <Component*> (component));
  49322. #endif
  49323. }
  49324. Component* ComponentBuilder::getManagedComponent()
  49325. {
  49326. if (component == 0)
  49327. {
  49328. component = createComponent();
  49329. #if JUCE_DEBUG
  49330. componentRef = component;
  49331. #endif
  49332. }
  49333. return component;
  49334. }
  49335. Component* ComponentBuilder::createComponent()
  49336. {
  49337. jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
  49338. TypeHandler* const type = getHandlerForState (state);
  49339. jassert (type != 0); // trying to create a component from an unknown type of ValueTree
  49340. return type != 0 ? ComponentBuilderHelpers::createNewComponent (*type, state, 0) : 0;
  49341. }
  49342. void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
  49343. {
  49344. jassert (type != 0);
  49345. // Don't try to move your types around! Once a type has been added to a builder, the
  49346. // builder owns it, and you should leave it alone!
  49347. jassert (type->builder == 0);
  49348. types.add (type);
  49349. type->builder = this;
  49350. }
  49351. ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
  49352. {
  49353. const Identifier targetType (s.getType());
  49354. for (int i = 0; i < types.size(); ++i)
  49355. {
  49356. TypeHandler* const t = types.getUnchecked(i);
  49357. if (t->getType() == targetType)
  49358. return t;
  49359. }
  49360. return 0;
  49361. }
  49362. int ComponentBuilder::getNumHandlers() const throw()
  49363. {
  49364. return types.size();
  49365. }
  49366. ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const throw()
  49367. {
  49368. return types [index];
  49369. }
  49370. void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) throw()
  49371. {
  49372. imageProvider = newImageProvider;
  49373. }
  49374. ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const throw()
  49375. {
  49376. return imageProvider;
  49377. }
  49378. void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
  49379. {
  49380. ComponentBuilderHelpers::updateComponent (*this, tree);
  49381. }
  49382. void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
  49383. {
  49384. ComponentBuilderHelpers::updateComponent (*this, tree);
  49385. }
  49386. void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&)
  49387. {
  49388. ComponentBuilderHelpers::updateComponent (*this, tree);
  49389. }
  49390. void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree)
  49391. {
  49392. ComponentBuilderHelpers::updateComponent (*this, tree);
  49393. }
  49394. void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
  49395. {
  49396. ComponentBuilderHelpers::updateComponent (*this, tree);
  49397. }
  49398. ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType_)
  49399. : builder (0), valueTreeType (valueTreeType_)
  49400. {
  49401. }
  49402. ComponentBuilder::TypeHandler::~TypeHandler()
  49403. {
  49404. }
  49405. ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const throw()
  49406. {
  49407. // A type handler needs to be registered with a ComponentBuilder before using it!
  49408. jassert (builder != 0);
  49409. return builder;
  49410. }
  49411. void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
  49412. {
  49413. using namespace ComponentBuilderHelpers;
  49414. const int numExistingChildComps = parent.getNumChildComponents();
  49415. Array <Component*> componentsInOrder;
  49416. componentsInOrder.ensureStorageAllocated (numExistingChildComps);
  49417. {
  49418. OwnedArray<Component> existingComponents;
  49419. existingComponents.ensureStorageAllocated (numExistingChildComps);
  49420. int i;
  49421. for (i = 0; i < numExistingChildComps; ++i)
  49422. existingComponents.add (parent.getChildComponent (i));
  49423. const int newNumChildren = children.getNumChildren();
  49424. for (i = 0; i < newNumChildren; ++i)
  49425. {
  49426. const ValueTree childState (children.getChild (i));
  49427. ComponentBuilder::TypeHandler* const type = getHandlerForState (childState);
  49428. jassert (type != 0);
  49429. if (type != 0)
  49430. {
  49431. Component* c = findComponentWithID (existingComponents, getStateId (childState));
  49432. if (c == 0)
  49433. c = createNewComponent (*type, childState, &parent);
  49434. componentsInOrder.add (c);
  49435. }
  49436. }
  49437. // (remaining unused items in existingComponents get deleted here as it goes out of scope)
  49438. }
  49439. // Make sure the z-order is correct..
  49440. if (componentsInOrder.size() > 0)
  49441. {
  49442. componentsInOrder.getLast()->toFront (false);
  49443. for (int i = componentsInOrder.size() - 1; --i >= 0;)
  49444. componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
  49445. }
  49446. }
  49447. END_JUCE_NAMESPACE
  49448. /*** End of inlined file: juce_ComponentBuilder.cpp ***/
  49449. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49450. BEGIN_JUCE_NAMESPACE
  49451. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49452. : minW (0),
  49453. maxW (0x3fffffff),
  49454. minH (0),
  49455. maxH (0x3fffffff),
  49456. minOffTop (0),
  49457. minOffLeft (0),
  49458. minOffBottom (0),
  49459. minOffRight (0),
  49460. aspectRatio (0.0)
  49461. {
  49462. }
  49463. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49464. {
  49465. }
  49466. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49467. {
  49468. minW = minimumWidth;
  49469. }
  49470. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49471. {
  49472. maxW = maximumWidth;
  49473. }
  49474. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49475. {
  49476. minH = minimumHeight;
  49477. }
  49478. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49479. {
  49480. maxH = maximumHeight;
  49481. }
  49482. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49483. {
  49484. jassert (maxW >= minimumWidth);
  49485. jassert (maxH >= minimumHeight);
  49486. jassert (minimumWidth > 0 && minimumHeight > 0);
  49487. minW = minimumWidth;
  49488. minH = minimumHeight;
  49489. if (minW > maxW)
  49490. maxW = minW;
  49491. if (minH > maxH)
  49492. maxH = minH;
  49493. }
  49494. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49495. {
  49496. jassert (maximumWidth >= minW);
  49497. jassert (maximumHeight >= minH);
  49498. jassert (maximumWidth > 0 && maximumHeight > 0);
  49499. maxW = jmax (minW, maximumWidth);
  49500. maxH = jmax (minH, maximumHeight);
  49501. }
  49502. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49503. const int minimumHeight,
  49504. const int maximumWidth,
  49505. const int maximumHeight) throw()
  49506. {
  49507. jassert (maximumWidth >= minimumWidth);
  49508. jassert (maximumHeight >= minimumHeight);
  49509. jassert (maximumWidth > 0 && maximumHeight > 0);
  49510. jassert (minimumWidth > 0 && minimumHeight > 0);
  49511. minW = jmax (0, minimumWidth);
  49512. minH = jmax (0, minimumHeight);
  49513. maxW = jmax (minW, maximumWidth);
  49514. maxH = jmax (minH, maximumHeight);
  49515. }
  49516. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49517. const int minimumWhenOffTheLeft,
  49518. const int minimumWhenOffTheBottom,
  49519. const int minimumWhenOffTheRight) throw()
  49520. {
  49521. minOffTop = minimumWhenOffTheTop;
  49522. minOffLeft = minimumWhenOffTheLeft;
  49523. minOffBottom = minimumWhenOffTheBottom;
  49524. minOffRight = minimumWhenOffTheRight;
  49525. }
  49526. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49527. {
  49528. aspectRatio = jmax (0.0, widthOverHeight);
  49529. }
  49530. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49531. {
  49532. return aspectRatio;
  49533. }
  49534. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49535. const Rectangle<int>& targetBounds,
  49536. const bool isStretchingTop,
  49537. const bool isStretchingLeft,
  49538. const bool isStretchingBottom,
  49539. const bool isStretchingRight)
  49540. {
  49541. jassert (component != 0);
  49542. Rectangle<int> limits, bounds (targetBounds);
  49543. BorderSize<int> border;
  49544. Component* const parent = component->getParentComponent();
  49545. if (parent == 0)
  49546. {
  49547. ComponentPeer* peer = component->getPeer();
  49548. if (peer != 0)
  49549. border = peer->getFrameSize();
  49550. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49551. }
  49552. else
  49553. {
  49554. limits.setSize (parent->getWidth(), parent->getHeight());
  49555. }
  49556. border.addTo (bounds);
  49557. checkBounds (bounds,
  49558. border.addedTo (component->getBounds()), limits,
  49559. isStretchingTop, isStretchingLeft,
  49560. isStretchingBottom, isStretchingRight);
  49561. border.subtractFrom (bounds);
  49562. applyBoundsToComponent (component, bounds);
  49563. }
  49564. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49565. {
  49566. setBoundsForComponent (component, component->getBounds(),
  49567. false, false, false, false);
  49568. }
  49569. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49570. const Rectangle<int>& bounds)
  49571. {
  49572. component->setBounds (bounds);
  49573. }
  49574. void ComponentBoundsConstrainer::resizeStart()
  49575. {
  49576. }
  49577. void ComponentBoundsConstrainer::resizeEnd()
  49578. {
  49579. }
  49580. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49581. const Rectangle<int>& old,
  49582. const Rectangle<int>& limits,
  49583. const bool isStretchingTop,
  49584. const bool isStretchingLeft,
  49585. const bool isStretchingBottom,
  49586. const bool isStretchingRight)
  49587. {
  49588. // constrain the size if it's being stretched..
  49589. if (isStretchingLeft)
  49590. bounds.setLeft (jlimit (old.getRight() - maxW, old.getRight() - minW, bounds.getX()));
  49591. if (isStretchingRight)
  49592. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49593. if (isStretchingTop)
  49594. bounds.setTop (jlimit (old.getBottom() - maxH, old.getBottom() - minH, bounds.getY()));
  49595. if (isStretchingBottom)
  49596. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49597. if (bounds.isEmpty())
  49598. return;
  49599. if (minOffTop > 0)
  49600. {
  49601. const int limit = limits.getY() + jmin (minOffTop - bounds.getHeight(), 0);
  49602. if (bounds.getY() < limit)
  49603. {
  49604. if (isStretchingTop)
  49605. bounds.setTop (limits.getY());
  49606. else
  49607. bounds.setY (limit);
  49608. }
  49609. }
  49610. if (minOffLeft > 0)
  49611. {
  49612. const int limit = limits.getX() + jmin (minOffLeft - bounds.getWidth(), 0);
  49613. if (bounds.getX() < limit)
  49614. {
  49615. if (isStretchingLeft)
  49616. bounds.setLeft (limits.getX());
  49617. else
  49618. bounds.setX (limit);
  49619. }
  49620. }
  49621. if (minOffBottom > 0)
  49622. {
  49623. const int limit = limits.getBottom() - jmin (minOffBottom, bounds.getHeight());
  49624. if (bounds.getY() > limit)
  49625. {
  49626. if (isStretchingBottom)
  49627. bounds.setBottom (limits.getBottom());
  49628. else
  49629. bounds.setY (limit);
  49630. }
  49631. }
  49632. if (minOffRight > 0)
  49633. {
  49634. const int limit = limits.getRight() - jmin (minOffRight, bounds.getWidth());
  49635. if (bounds.getX() > limit)
  49636. {
  49637. if (isStretchingRight)
  49638. bounds.setRight (limits.getRight());
  49639. else
  49640. bounds.setX (limit);
  49641. }
  49642. }
  49643. // constrain the aspect ratio if one has been specified..
  49644. if (aspectRatio > 0.0)
  49645. {
  49646. bool adjustWidth;
  49647. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49648. {
  49649. adjustWidth = true;
  49650. }
  49651. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49652. {
  49653. adjustWidth = false;
  49654. }
  49655. else
  49656. {
  49657. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49658. const double newRatio = std::abs (bounds.getWidth() / (double) bounds.getHeight());
  49659. adjustWidth = (oldRatio > newRatio);
  49660. }
  49661. if (adjustWidth)
  49662. {
  49663. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49664. if (bounds.getWidth() > maxW || bounds.getWidth() < minW)
  49665. {
  49666. bounds.setWidth (jlimit (minW, maxW, bounds.getWidth()));
  49667. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49668. }
  49669. }
  49670. else
  49671. {
  49672. bounds.setHeight (roundToInt (bounds.getWidth() / aspectRatio));
  49673. if (bounds.getHeight() > maxH || bounds.getHeight() < minH)
  49674. {
  49675. bounds.setHeight (jlimit (minH, maxH, bounds.getHeight()));
  49676. bounds.setWidth (roundToInt (bounds.getHeight() * aspectRatio));
  49677. }
  49678. }
  49679. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49680. {
  49681. bounds.setX (old.getX() + (old.getWidth() - bounds.getWidth()) / 2);
  49682. }
  49683. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49684. {
  49685. bounds.setY (old.getY() + (old.getHeight() - bounds.getHeight()) / 2);
  49686. }
  49687. else
  49688. {
  49689. if (isStretchingLeft)
  49690. bounds.setX (old.getRight() - bounds.getWidth());
  49691. if (isStretchingTop)
  49692. bounds.setY (old.getBottom() - bounds.getHeight());
  49693. }
  49694. }
  49695. jassert (! bounds.isEmpty());
  49696. }
  49697. END_JUCE_NAMESPACE
  49698. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49699. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49700. BEGIN_JUCE_NAMESPACE
  49701. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49702. : component (component_),
  49703. lastPeer (0),
  49704. reentrant (false),
  49705. wasShowing (component_->isShowing())
  49706. {
  49707. jassert (component != 0); // can't use this with a null pointer..
  49708. component->addComponentListener (this);
  49709. registerWithParentComps();
  49710. }
  49711. ComponentMovementWatcher::~ComponentMovementWatcher()
  49712. {
  49713. if (component != 0)
  49714. component->removeComponentListener (this);
  49715. unregister();
  49716. }
  49717. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49718. {
  49719. if (component != 0 && ! reentrant)
  49720. {
  49721. const ScopedValueSetter<bool> setter (reentrant, true);
  49722. ComponentPeer* const peer = component->getPeer();
  49723. if (peer != lastPeer)
  49724. {
  49725. componentPeerChanged();
  49726. if (component == 0)
  49727. return;
  49728. lastPeer = peer;
  49729. }
  49730. unregister();
  49731. registerWithParentComps();
  49732. componentMovedOrResized (*component, true, true);
  49733. if (component != 0)
  49734. componentVisibilityChanged (*component);
  49735. }
  49736. }
  49737. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49738. {
  49739. if (component != 0)
  49740. {
  49741. if (wasMoved)
  49742. {
  49743. const Point<int> pos (component->getTopLevelComponent()->getLocalPoint (component, Point<int>()));
  49744. wasMoved = lastBounds.getPosition() != pos;
  49745. lastBounds.setPosition (pos);
  49746. }
  49747. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49748. lastBounds.setSize (component->getWidth(), component->getHeight());
  49749. if (wasMoved || wasResized)
  49750. componentMovedOrResized (wasMoved, wasResized);
  49751. }
  49752. }
  49753. void ComponentMovementWatcher::componentBeingDeleted (Component& comp)
  49754. {
  49755. registeredParentComps.removeValue (&comp);
  49756. if (component == &comp)
  49757. unregister();
  49758. }
  49759. void ComponentMovementWatcher::componentVisibilityChanged (Component&)
  49760. {
  49761. if (component != 0)
  49762. {
  49763. const bool isShowingNow = component->isShowing();
  49764. if (wasShowing != isShowingNow)
  49765. {
  49766. wasShowing = isShowingNow;
  49767. componentVisibilityChanged();
  49768. }
  49769. }
  49770. }
  49771. void ComponentMovementWatcher::registerWithParentComps()
  49772. {
  49773. Component* p = component->getParentComponent();
  49774. while (p != 0)
  49775. {
  49776. p->addComponentListener (this);
  49777. registeredParentComps.add (p);
  49778. p = p->getParentComponent();
  49779. }
  49780. }
  49781. void ComponentMovementWatcher::unregister()
  49782. {
  49783. for (int i = registeredParentComps.size(); --i >= 0;)
  49784. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49785. registeredParentComps.clear();
  49786. }
  49787. END_JUCE_NAMESPACE
  49788. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49789. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49790. BEGIN_JUCE_NAMESPACE
  49791. GroupComponent::GroupComponent (const String& componentName,
  49792. const String& labelText)
  49793. : Component (componentName),
  49794. text (labelText),
  49795. justification (Justification::left)
  49796. {
  49797. setInterceptsMouseClicks (false, true);
  49798. }
  49799. GroupComponent::~GroupComponent()
  49800. {
  49801. }
  49802. void GroupComponent::setText (const String& newText)
  49803. {
  49804. if (text != newText)
  49805. {
  49806. text = newText;
  49807. repaint();
  49808. }
  49809. }
  49810. const String GroupComponent::getText() const
  49811. {
  49812. return text;
  49813. }
  49814. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49815. {
  49816. if (justification != newJustification)
  49817. {
  49818. justification = newJustification;
  49819. repaint();
  49820. }
  49821. }
  49822. void GroupComponent::paint (Graphics& g)
  49823. {
  49824. getLookAndFeel()
  49825. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49826. text, justification,
  49827. *this);
  49828. }
  49829. void GroupComponent::enablementChanged()
  49830. {
  49831. repaint();
  49832. }
  49833. void GroupComponent::colourChanged()
  49834. {
  49835. repaint();
  49836. }
  49837. END_JUCE_NAMESPACE
  49838. /*** End of inlined file: juce_GroupComponent.cpp ***/
  49839. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  49840. BEGIN_JUCE_NAMESPACE
  49841. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  49842. : DocumentWindow (String::empty, backgroundColour,
  49843. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  49844. {
  49845. }
  49846. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  49847. {
  49848. }
  49849. void MultiDocumentPanelWindow::maximiseButtonPressed()
  49850. {
  49851. MultiDocumentPanel* const owner = getOwner();
  49852. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49853. if (owner != 0)
  49854. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  49855. }
  49856. void MultiDocumentPanelWindow::closeButtonPressed()
  49857. {
  49858. MultiDocumentPanel* const owner = getOwner();
  49859. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  49860. if (owner != 0)
  49861. owner->closeDocument (getContentComponent(), true);
  49862. }
  49863. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  49864. {
  49865. DocumentWindow::activeWindowStatusChanged();
  49866. updateOrder();
  49867. }
  49868. void MultiDocumentPanelWindow::broughtToFront()
  49869. {
  49870. DocumentWindow::broughtToFront();
  49871. updateOrder();
  49872. }
  49873. void MultiDocumentPanelWindow::updateOrder()
  49874. {
  49875. MultiDocumentPanel* const owner = getOwner();
  49876. if (owner != 0)
  49877. owner->updateOrder();
  49878. }
  49879. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  49880. {
  49881. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49882. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49883. }
  49884. class MDITabbedComponentInternal : public TabbedComponent
  49885. {
  49886. public:
  49887. MDITabbedComponentInternal()
  49888. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  49889. {
  49890. }
  49891. ~MDITabbedComponentInternal()
  49892. {
  49893. }
  49894. void currentTabChanged (int, const String&)
  49895. {
  49896. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  49897. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  49898. if (owner != 0)
  49899. owner->updateOrder();
  49900. }
  49901. };
  49902. MultiDocumentPanel::MultiDocumentPanel()
  49903. : mode (MaximisedWindowsWithTabs),
  49904. backgroundColour (Colours::lightblue),
  49905. maximumNumDocuments (0),
  49906. numDocsBeforeTabsUsed (0)
  49907. {
  49908. setOpaque (true);
  49909. }
  49910. MultiDocumentPanel::~MultiDocumentPanel()
  49911. {
  49912. closeAllDocuments (false);
  49913. }
  49914. namespace MultiDocHelpers
  49915. {
  49916. bool shouldDeleteComp (Component* const c)
  49917. {
  49918. return c->getProperties() ["mdiDocumentDelete_"];
  49919. }
  49920. }
  49921. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  49922. {
  49923. while (components.size() > 0)
  49924. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  49925. return false;
  49926. return true;
  49927. }
  49928. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  49929. {
  49930. return new MultiDocumentPanelWindow (backgroundColour);
  49931. }
  49932. void MultiDocumentPanel::addWindow (Component* component)
  49933. {
  49934. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  49935. dw->setResizable (true, false);
  49936. dw->setContentComponent (component, false, true);
  49937. dw->setName (component->getName());
  49938. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  49939. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  49940. int x = 4;
  49941. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  49942. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  49943. x += 16;
  49944. dw->setTopLeftPosition (x, x);
  49945. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  49946. if (pos.toString().isNotEmpty())
  49947. dw->restoreWindowStateFromString (pos.toString());
  49948. addAndMakeVisible (dw);
  49949. dw->toFront (true);
  49950. }
  49951. bool MultiDocumentPanel::addDocument (Component* const component,
  49952. const Colour& docColour,
  49953. const bool deleteWhenRemoved)
  49954. {
  49955. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  49956. // with a frame-within-a-frame! Just pass in the bare content component.
  49957. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  49958. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  49959. return false;
  49960. components.add (component);
  49961. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  49962. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  49963. component->addComponentListener (this);
  49964. if (mode == FloatingWindows)
  49965. {
  49966. if (isFullscreenWhenOneDocument())
  49967. {
  49968. if (components.size() == 1)
  49969. {
  49970. addAndMakeVisible (component);
  49971. }
  49972. else
  49973. {
  49974. if (components.size() == 2)
  49975. addWindow (components.getFirst());
  49976. addWindow (component);
  49977. }
  49978. }
  49979. else
  49980. {
  49981. addWindow (component);
  49982. }
  49983. }
  49984. else
  49985. {
  49986. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  49987. {
  49988. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  49989. Array <Component*> temp (components);
  49990. for (int i = 0; i < temp.size(); ++i)
  49991. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  49992. resized();
  49993. }
  49994. else
  49995. {
  49996. if (tabComponent != 0)
  49997. tabComponent->addTab (component->getName(), docColour, component, false);
  49998. else
  49999. addAndMakeVisible (component);
  50000. }
  50001. setActiveDocument (component);
  50002. }
  50003. resized();
  50004. activeDocumentChanged();
  50005. return true;
  50006. }
  50007. bool MultiDocumentPanel::closeDocument (Component* component,
  50008. const bool checkItsOkToCloseFirst)
  50009. {
  50010. if (components.contains (component))
  50011. {
  50012. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50013. return false;
  50014. component->removeComponentListener (this);
  50015. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50016. component->getProperties().remove ("mdiDocumentDelete_");
  50017. component->getProperties().remove ("mdiDocumentBkg_");
  50018. if (mode == FloatingWindows)
  50019. {
  50020. for (int i = getNumChildComponents(); --i >= 0;)
  50021. {
  50022. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50023. if (dw != 0 && dw->getContentComponent() == component)
  50024. {
  50025. dw->setContentComponent (0, false);
  50026. delete dw;
  50027. break;
  50028. }
  50029. }
  50030. if (shouldDelete)
  50031. delete component;
  50032. components.removeValue (component);
  50033. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50034. {
  50035. for (int i = getNumChildComponents(); --i >= 0;)
  50036. {
  50037. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50038. if (dw != 0)
  50039. {
  50040. dw->setContentComponent (0, false);
  50041. delete dw;
  50042. }
  50043. }
  50044. addAndMakeVisible (components.getFirst());
  50045. }
  50046. }
  50047. else
  50048. {
  50049. jassert (components.indexOf (component) >= 0);
  50050. if (tabComponent != 0)
  50051. {
  50052. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50053. if (tabComponent->getTabContentComponent (i) == component)
  50054. tabComponent->removeTab (i);
  50055. }
  50056. else
  50057. {
  50058. removeChildComponent (component);
  50059. }
  50060. if (shouldDelete)
  50061. delete component;
  50062. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50063. tabComponent = 0;
  50064. components.removeValue (component);
  50065. if (components.size() > 0 && tabComponent == 0)
  50066. addAndMakeVisible (components.getFirst());
  50067. }
  50068. resized();
  50069. activeDocumentChanged();
  50070. }
  50071. else
  50072. {
  50073. jassertfalse;
  50074. }
  50075. return true;
  50076. }
  50077. int MultiDocumentPanel::getNumDocuments() const throw()
  50078. {
  50079. return components.size();
  50080. }
  50081. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50082. {
  50083. return components [index];
  50084. }
  50085. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50086. {
  50087. if (mode == FloatingWindows)
  50088. {
  50089. for (int i = getNumChildComponents(); --i >= 0;)
  50090. {
  50091. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50092. if (dw != 0 && dw->isActiveWindow())
  50093. return dw->getContentComponent();
  50094. }
  50095. }
  50096. return components.getLast();
  50097. }
  50098. void MultiDocumentPanel::setActiveDocument (Component* component)
  50099. {
  50100. if (mode == FloatingWindows)
  50101. {
  50102. component = getContainerComp (component);
  50103. if (component != 0)
  50104. component->toFront (true);
  50105. }
  50106. else if (tabComponent != 0)
  50107. {
  50108. jassert (components.indexOf (component) >= 0);
  50109. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50110. {
  50111. if (tabComponent->getTabContentComponent (i) == component)
  50112. {
  50113. tabComponent->setCurrentTabIndex (i);
  50114. break;
  50115. }
  50116. }
  50117. }
  50118. else
  50119. {
  50120. component->grabKeyboardFocus();
  50121. }
  50122. }
  50123. void MultiDocumentPanel::activeDocumentChanged()
  50124. {
  50125. }
  50126. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50127. {
  50128. maximumNumDocuments = newNumber;
  50129. }
  50130. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50131. {
  50132. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50133. }
  50134. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50135. {
  50136. return numDocsBeforeTabsUsed != 0;
  50137. }
  50138. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50139. {
  50140. if (mode != newLayoutMode)
  50141. {
  50142. mode = newLayoutMode;
  50143. if (mode == FloatingWindows)
  50144. {
  50145. tabComponent = 0;
  50146. }
  50147. else
  50148. {
  50149. for (int i = getNumChildComponents(); --i >= 0;)
  50150. {
  50151. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50152. if (dw != 0)
  50153. {
  50154. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50155. dw->setContentComponent (0, false);
  50156. delete dw;
  50157. }
  50158. }
  50159. }
  50160. resized();
  50161. const Array <Component*> tempComps (components);
  50162. components.clear();
  50163. for (int i = 0; i < tempComps.size(); ++i)
  50164. {
  50165. Component* const c = tempComps.getUnchecked(i);
  50166. addDocument (c,
  50167. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50168. MultiDocHelpers::shouldDeleteComp (c));
  50169. }
  50170. }
  50171. }
  50172. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50173. {
  50174. if (backgroundColour != newBackgroundColour)
  50175. {
  50176. backgroundColour = newBackgroundColour;
  50177. setOpaque (newBackgroundColour.isOpaque());
  50178. repaint();
  50179. }
  50180. }
  50181. void MultiDocumentPanel::paint (Graphics& g)
  50182. {
  50183. g.fillAll (backgroundColour);
  50184. }
  50185. void MultiDocumentPanel::resized()
  50186. {
  50187. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50188. {
  50189. for (int i = getNumChildComponents(); --i >= 0;)
  50190. getChildComponent (i)->setBounds (getLocalBounds());
  50191. }
  50192. setWantsKeyboardFocus (components.size() == 0);
  50193. }
  50194. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50195. {
  50196. if (mode == FloatingWindows)
  50197. {
  50198. for (int i = 0; i < getNumChildComponents(); ++i)
  50199. {
  50200. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50201. if (dw != 0 && dw->getContentComponent() == c)
  50202. {
  50203. c = dw;
  50204. break;
  50205. }
  50206. }
  50207. }
  50208. return c;
  50209. }
  50210. void MultiDocumentPanel::componentNameChanged (Component&)
  50211. {
  50212. if (mode == FloatingWindows)
  50213. {
  50214. for (int i = 0; i < getNumChildComponents(); ++i)
  50215. {
  50216. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50217. if (dw != 0)
  50218. dw->setName (dw->getContentComponent()->getName());
  50219. }
  50220. }
  50221. else if (tabComponent != 0)
  50222. {
  50223. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50224. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50225. }
  50226. }
  50227. void MultiDocumentPanel::updateOrder()
  50228. {
  50229. const Array <Component*> oldList (components);
  50230. if (mode == FloatingWindows)
  50231. {
  50232. components.clear();
  50233. for (int i = 0; i < getNumChildComponents(); ++i)
  50234. {
  50235. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50236. if (dw != 0)
  50237. components.add (dw->getContentComponent());
  50238. }
  50239. }
  50240. else
  50241. {
  50242. if (tabComponent != 0)
  50243. {
  50244. Component* const current = tabComponent->getCurrentContentComponent();
  50245. if (current != 0)
  50246. {
  50247. components.removeValue (current);
  50248. components.add (current);
  50249. }
  50250. }
  50251. }
  50252. if (components != oldList)
  50253. activeDocumentChanged();
  50254. }
  50255. END_JUCE_NAMESPACE
  50256. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50257. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50258. BEGIN_JUCE_NAMESPACE
  50259. ResizableBorderComponent::Zone::Zone (const int zoneFlags) throw()
  50260. : zone (zoneFlags)
  50261. {}
  50262. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw()
  50263. : zone (other.zone)
  50264. {}
  50265. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw()
  50266. {
  50267. zone = other.zone;
  50268. return *this;
  50269. }
  50270. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50271. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50272. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50273. const BorderSize<int>& border,
  50274. const Point<int>& position)
  50275. {
  50276. int z = 0;
  50277. if (totalSize.contains (position)
  50278. && ! border.subtractedFrom (totalSize).contains (position))
  50279. {
  50280. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50281. if (position.getX() < jmax (border.getLeft(), minW) && border.getLeft() > 0)
  50282. z |= left;
  50283. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW) && border.getRight() > 0)
  50284. z |= right;
  50285. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50286. if (position.getY() < jmax (border.getTop(), minH) && border.getTop() > 0)
  50287. z |= top;
  50288. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH) && border.getBottom() > 0)
  50289. z |= bottom;
  50290. }
  50291. return Zone (z);
  50292. }
  50293. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50294. {
  50295. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50296. switch (zone)
  50297. {
  50298. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50299. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50300. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50301. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50302. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50303. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50304. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50305. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50306. default: break;
  50307. }
  50308. return mc;
  50309. }
  50310. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50311. ComponentBoundsConstrainer* const constrainer_)
  50312. : component (componentToResize),
  50313. constrainer (constrainer_),
  50314. borderSize (5),
  50315. mouseZone (0)
  50316. {
  50317. }
  50318. ResizableBorderComponent::~ResizableBorderComponent()
  50319. {
  50320. }
  50321. void ResizableBorderComponent::paint (Graphics& g)
  50322. {
  50323. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50324. }
  50325. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50326. {
  50327. updateMouseZone (e);
  50328. }
  50329. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50330. {
  50331. updateMouseZone (e);
  50332. }
  50333. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50334. {
  50335. if (component == 0)
  50336. {
  50337. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50338. return;
  50339. }
  50340. updateMouseZone (e);
  50341. originalBounds = component->getBounds();
  50342. if (constrainer != 0)
  50343. constrainer->resizeStart();
  50344. }
  50345. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50346. {
  50347. if (component == 0)
  50348. {
  50349. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50350. return;
  50351. }
  50352. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50353. if (constrainer != 0)
  50354. constrainer->setBoundsForComponent (component, bounds,
  50355. mouseZone.isDraggingTopEdge(),
  50356. mouseZone.isDraggingLeftEdge(),
  50357. mouseZone.isDraggingBottomEdge(),
  50358. mouseZone.isDraggingRightEdge());
  50359. else
  50360. component->setBounds (bounds);
  50361. }
  50362. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50363. {
  50364. if (constrainer != 0)
  50365. constrainer->resizeEnd();
  50366. }
  50367. bool ResizableBorderComponent::hitTest (int x, int y)
  50368. {
  50369. return x < borderSize.getLeft()
  50370. || x >= getWidth() - borderSize.getRight()
  50371. || y < borderSize.getTop()
  50372. || y >= getHeight() - borderSize.getBottom();
  50373. }
  50374. void ResizableBorderComponent::setBorderThickness (const BorderSize<int>& newBorderSize)
  50375. {
  50376. if (borderSize != newBorderSize)
  50377. {
  50378. borderSize = newBorderSize;
  50379. repaint();
  50380. }
  50381. }
  50382. const BorderSize<int> ResizableBorderComponent::getBorderThickness() const
  50383. {
  50384. return borderSize;
  50385. }
  50386. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50387. {
  50388. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50389. if (mouseZone != newZone)
  50390. {
  50391. mouseZone = newZone;
  50392. setMouseCursor (newZone.getMouseCursor());
  50393. }
  50394. }
  50395. END_JUCE_NAMESPACE
  50396. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50397. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50398. BEGIN_JUCE_NAMESPACE
  50399. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50400. ComponentBoundsConstrainer* const constrainer_)
  50401. : component (componentToResize),
  50402. constrainer (constrainer_)
  50403. {
  50404. setRepaintsOnMouseActivity (true);
  50405. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50406. }
  50407. ResizableCornerComponent::~ResizableCornerComponent()
  50408. {
  50409. }
  50410. void ResizableCornerComponent::paint (Graphics& g)
  50411. {
  50412. getLookAndFeel()
  50413. .drawCornerResizer (g, getWidth(), getHeight(),
  50414. isMouseOverOrDragging(),
  50415. isMouseButtonDown());
  50416. }
  50417. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50418. {
  50419. if (component == 0)
  50420. {
  50421. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50422. return;
  50423. }
  50424. originalBounds = component->getBounds();
  50425. if (constrainer != 0)
  50426. constrainer->resizeStart();
  50427. }
  50428. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50429. {
  50430. if (component == 0)
  50431. {
  50432. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50433. return;
  50434. }
  50435. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50436. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50437. if (constrainer != 0)
  50438. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50439. else
  50440. component->setBounds (r);
  50441. }
  50442. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50443. {
  50444. if (constrainer != 0)
  50445. constrainer->resizeStart();
  50446. }
  50447. bool ResizableCornerComponent::hitTest (int x, int y)
  50448. {
  50449. if (getWidth() <= 0)
  50450. return false;
  50451. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50452. return y >= yAtX - getHeight() / 4;
  50453. }
  50454. END_JUCE_NAMESPACE
  50455. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50456. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50457. BEGIN_JUCE_NAMESPACE
  50458. class ScrollBar::ScrollbarButton : public Button
  50459. {
  50460. public:
  50461. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50462. : Button (String::empty),
  50463. direction (direction_),
  50464. owner (owner_)
  50465. {
  50466. setWantsKeyboardFocus (false);
  50467. }
  50468. void paintButton (Graphics& g, bool over, bool down)
  50469. {
  50470. getLookAndFeel()
  50471. .drawScrollbarButton (g, owner,
  50472. getWidth(), getHeight(),
  50473. direction,
  50474. owner.isVertical(),
  50475. over, down);
  50476. }
  50477. void clicked()
  50478. {
  50479. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50480. }
  50481. int direction;
  50482. private:
  50483. ScrollBar& owner;
  50484. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton);
  50485. };
  50486. ScrollBar::ScrollBar (const bool vertical_,
  50487. const bool buttonsAreVisible)
  50488. : totalRange (0.0, 1.0),
  50489. visibleRange (0.0, 0.1),
  50490. singleStepSize (0.1),
  50491. thumbAreaStart (0),
  50492. thumbAreaSize (0),
  50493. thumbStart (0),
  50494. thumbSize (0),
  50495. initialDelayInMillisecs (100),
  50496. repeatDelayInMillisecs (50),
  50497. minimumDelayInMillisecs (10),
  50498. vertical (vertical_),
  50499. isDraggingThumb (false),
  50500. autohides (true)
  50501. {
  50502. setButtonVisibility (buttonsAreVisible);
  50503. setRepaintsOnMouseActivity (true);
  50504. setFocusContainer (true);
  50505. }
  50506. ScrollBar::~ScrollBar()
  50507. {
  50508. upButton = 0;
  50509. downButton = 0;
  50510. }
  50511. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50512. {
  50513. if (totalRange != newRangeLimit)
  50514. {
  50515. totalRange = newRangeLimit;
  50516. setCurrentRange (visibleRange);
  50517. updateThumbPosition();
  50518. }
  50519. }
  50520. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50521. {
  50522. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50523. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50524. }
  50525. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50526. {
  50527. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50528. if (visibleRange != constrainedRange)
  50529. {
  50530. visibleRange = constrainedRange;
  50531. updateThumbPosition();
  50532. triggerAsyncUpdate();
  50533. }
  50534. }
  50535. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50536. {
  50537. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50538. }
  50539. void ScrollBar::setCurrentRangeStart (const double newStart)
  50540. {
  50541. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50542. }
  50543. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50544. {
  50545. singleStepSize = newSingleStepSize;
  50546. }
  50547. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50548. {
  50549. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50550. }
  50551. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50552. {
  50553. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50554. }
  50555. void ScrollBar::scrollToTop()
  50556. {
  50557. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50558. }
  50559. void ScrollBar::scrollToBottom()
  50560. {
  50561. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50562. }
  50563. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50564. const int repeatDelayInMillisecs_,
  50565. const int minimumDelayInMillisecs_)
  50566. {
  50567. initialDelayInMillisecs = initialDelayInMillisecs_;
  50568. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50569. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50570. if (upButton != 0)
  50571. {
  50572. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50573. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50574. }
  50575. }
  50576. void ScrollBar::addListener (Listener* const listener)
  50577. {
  50578. listeners.add (listener);
  50579. }
  50580. void ScrollBar::removeListener (Listener* const listener)
  50581. {
  50582. listeners.remove (listener);
  50583. }
  50584. void ScrollBar::handleAsyncUpdate()
  50585. {
  50586. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50587. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50588. }
  50589. void ScrollBar::updateThumbPosition()
  50590. {
  50591. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50592. : thumbAreaSize);
  50593. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50594. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50595. if (newThumbSize > thumbAreaSize)
  50596. newThumbSize = thumbAreaSize;
  50597. int newThumbStart = thumbAreaStart;
  50598. if (totalRange.getLength() > visibleRange.getLength())
  50599. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50600. / (totalRange.getLength() - visibleRange.getLength()));
  50601. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50602. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50603. {
  50604. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50605. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50606. if (vertical)
  50607. repaint (0, repaintStart, getWidth(), repaintSize);
  50608. else
  50609. repaint (repaintStart, 0, repaintSize, getHeight());
  50610. thumbStart = newThumbStart;
  50611. thumbSize = newThumbSize;
  50612. }
  50613. }
  50614. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50615. {
  50616. if (vertical != shouldBeVertical)
  50617. {
  50618. vertical = shouldBeVertical;
  50619. if (upButton != 0)
  50620. {
  50621. upButton->direction = vertical ? 0 : 3;
  50622. downButton->direction = vertical ? 2 : 1;
  50623. }
  50624. updateThumbPosition();
  50625. }
  50626. }
  50627. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50628. {
  50629. upButton = 0;
  50630. downButton = 0;
  50631. if (buttonsAreVisible)
  50632. {
  50633. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50634. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50635. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50636. }
  50637. updateThumbPosition();
  50638. }
  50639. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50640. {
  50641. autohides = shouldHideWhenFullRange;
  50642. updateThumbPosition();
  50643. }
  50644. bool ScrollBar::autoHides() const throw()
  50645. {
  50646. return autohides;
  50647. }
  50648. void ScrollBar::paint (Graphics& g)
  50649. {
  50650. if (thumbAreaSize > 0)
  50651. {
  50652. LookAndFeel& lf = getLookAndFeel();
  50653. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50654. ? thumbSize : 0;
  50655. if (vertical)
  50656. {
  50657. lf.drawScrollbar (g, *this,
  50658. 0, thumbAreaStart,
  50659. getWidth(), thumbAreaSize,
  50660. vertical,
  50661. thumbStart, thumb,
  50662. isMouseOver(), isMouseButtonDown());
  50663. }
  50664. else
  50665. {
  50666. lf.drawScrollbar (g, *this,
  50667. thumbAreaStart, 0,
  50668. thumbAreaSize, getHeight(),
  50669. vertical,
  50670. thumbStart, thumb,
  50671. isMouseOver(), isMouseButtonDown());
  50672. }
  50673. }
  50674. }
  50675. void ScrollBar::lookAndFeelChanged()
  50676. {
  50677. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50678. }
  50679. void ScrollBar::resized()
  50680. {
  50681. const int length = ((vertical) ? getHeight() : getWidth());
  50682. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50683. : 0;
  50684. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50685. {
  50686. thumbAreaStart = length >> 1;
  50687. thumbAreaSize = 0;
  50688. }
  50689. else
  50690. {
  50691. thumbAreaStart = buttonSize;
  50692. thumbAreaSize = length - (buttonSize << 1);
  50693. }
  50694. if (upButton != 0)
  50695. {
  50696. if (vertical)
  50697. {
  50698. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50699. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50700. }
  50701. else
  50702. {
  50703. upButton->setBounds (0, 0, buttonSize, getHeight());
  50704. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50705. }
  50706. }
  50707. updateThumbPosition();
  50708. }
  50709. void ScrollBar::mouseDown (const MouseEvent& e)
  50710. {
  50711. isDraggingThumb = false;
  50712. lastMousePos = vertical ? e.y : e.x;
  50713. dragStartMousePos = lastMousePos;
  50714. dragStartRange = visibleRange.getStart();
  50715. if (dragStartMousePos < thumbStart)
  50716. {
  50717. moveScrollbarInPages (-1);
  50718. startTimer (400);
  50719. }
  50720. else if (dragStartMousePos >= thumbStart + thumbSize)
  50721. {
  50722. moveScrollbarInPages (1);
  50723. startTimer (400);
  50724. }
  50725. else
  50726. {
  50727. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50728. && (thumbAreaSize > thumbSize);
  50729. }
  50730. }
  50731. void ScrollBar::mouseDrag (const MouseEvent& e)
  50732. {
  50733. const int mousePos = vertical ? e.y : e.x;
  50734. if (isDraggingThumb && lastMousePos != mousePos)
  50735. {
  50736. const int deltaPixels = mousePos - dragStartMousePos;
  50737. setCurrentRangeStart (dragStartRange
  50738. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50739. / (thumbAreaSize - thumbSize));
  50740. }
  50741. lastMousePos = mousePos;
  50742. }
  50743. void ScrollBar::mouseUp (const MouseEvent&)
  50744. {
  50745. isDraggingThumb = false;
  50746. stopTimer();
  50747. repaint();
  50748. }
  50749. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50750. float wheelIncrementX,
  50751. float wheelIncrementY)
  50752. {
  50753. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50754. if (increment < 0)
  50755. increment = jmin (increment * 10.0f, -1.0f);
  50756. else if (increment > 0)
  50757. increment = jmax (increment * 10.0f, 1.0f);
  50758. setCurrentRange (visibleRange - singleStepSize * increment);
  50759. }
  50760. void ScrollBar::timerCallback()
  50761. {
  50762. if (isMouseButtonDown())
  50763. {
  50764. startTimer (40);
  50765. if (lastMousePos < thumbStart)
  50766. setCurrentRange (visibleRange - visibleRange.getLength());
  50767. else if (lastMousePos > thumbStart + thumbSize)
  50768. setCurrentRangeStart (visibleRange.getEnd());
  50769. }
  50770. else
  50771. {
  50772. stopTimer();
  50773. }
  50774. }
  50775. bool ScrollBar::keyPressed (const KeyPress& key)
  50776. {
  50777. if (! isVisible())
  50778. return false;
  50779. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50780. moveScrollbarInSteps (-1);
  50781. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50782. moveScrollbarInSteps (1);
  50783. else if (key.isKeyCode (KeyPress::pageUpKey))
  50784. moveScrollbarInPages (-1);
  50785. else if (key.isKeyCode (KeyPress::pageDownKey))
  50786. moveScrollbarInPages (1);
  50787. else if (key.isKeyCode (KeyPress::homeKey))
  50788. scrollToTop();
  50789. else if (key.isKeyCode (KeyPress::endKey))
  50790. scrollToBottom();
  50791. else
  50792. return false;
  50793. return true;
  50794. }
  50795. END_JUCE_NAMESPACE
  50796. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50797. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50798. BEGIN_JUCE_NAMESPACE
  50799. StretchableLayoutManager::StretchableLayoutManager()
  50800. : totalSize (0)
  50801. {
  50802. }
  50803. StretchableLayoutManager::~StretchableLayoutManager()
  50804. {
  50805. }
  50806. void StretchableLayoutManager::clearAllItems()
  50807. {
  50808. items.clear();
  50809. totalSize = 0;
  50810. }
  50811. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  50812. const double minimumSize,
  50813. const double maximumSize,
  50814. const double preferredSize)
  50815. {
  50816. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  50817. if (layout == 0)
  50818. {
  50819. layout = new ItemLayoutProperties();
  50820. layout->itemIndex = itemIndex;
  50821. int i;
  50822. for (i = 0; i < items.size(); ++i)
  50823. if (items.getUnchecked (i)->itemIndex > itemIndex)
  50824. break;
  50825. items.insert (i, layout);
  50826. }
  50827. layout->minSize = minimumSize;
  50828. layout->maxSize = maximumSize;
  50829. layout->preferredSize = preferredSize;
  50830. layout->currentSize = 0;
  50831. }
  50832. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  50833. double& minimumSize,
  50834. double& maximumSize,
  50835. double& preferredSize) const
  50836. {
  50837. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50838. if (layout != 0)
  50839. {
  50840. minimumSize = layout->minSize;
  50841. maximumSize = layout->maxSize;
  50842. preferredSize = layout->preferredSize;
  50843. return true;
  50844. }
  50845. return false;
  50846. }
  50847. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  50848. {
  50849. totalSize = newTotalSize;
  50850. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  50851. }
  50852. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  50853. {
  50854. int pos = 0;
  50855. for (int i = 0; i < itemIndex; ++i)
  50856. {
  50857. const ItemLayoutProperties* const layout = getInfoFor (i);
  50858. if (layout != 0)
  50859. pos += layout->currentSize;
  50860. }
  50861. return pos;
  50862. }
  50863. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  50864. {
  50865. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50866. if (layout != 0)
  50867. return layout->currentSize;
  50868. return 0;
  50869. }
  50870. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  50871. {
  50872. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  50873. if (layout != 0)
  50874. return -layout->currentSize / (double) totalSize;
  50875. return 0;
  50876. }
  50877. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  50878. int newPosition)
  50879. {
  50880. for (int i = items.size(); --i >= 0;)
  50881. {
  50882. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  50883. if (layout->itemIndex == itemIndex)
  50884. {
  50885. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  50886. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  50887. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  50888. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  50889. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  50890. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  50891. endPos += layout->currentSize;
  50892. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  50893. updatePrefSizesToMatchCurrentPositions();
  50894. break;
  50895. }
  50896. }
  50897. }
  50898. void StretchableLayoutManager::layOutComponents (Component** const components,
  50899. int numComponents,
  50900. int x, int y, int w, int h,
  50901. const bool vertically,
  50902. const bool resizeOtherDimension)
  50903. {
  50904. setTotalSize (vertically ? h : w);
  50905. int pos = vertically ? y : x;
  50906. for (int i = 0; i < numComponents; ++i)
  50907. {
  50908. const ItemLayoutProperties* const layout = getInfoFor (i);
  50909. if (layout != 0)
  50910. {
  50911. Component* const c = components[i];
  50912. if (c != 0)
  50913. {
  50914. if (i == numComponents - 1)
  50915. {
  50916. // if it's the last item, crop it to exactly fit the available space..
  50917. if (resizeOtherDimension)
  50918. {
  50919. if (vertically)
  50920. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  50921. else
  50922. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  50923. }
  50924. else
  50925. {
  50926. if (vertically)
  50927. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  50928. else
  50929. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  50930. }
  50931. }
  50932. else
  50933. {
  50934. if (resizeOtherDimension)
  50935. {
  50936. if (vertically)
  50937. c->setBounds (x, pos, w, layout->currentSize);
  50938. else
  50939. c->setBounds (pos, y, layout->currentSize, h);
  50940. }
  50941. else
  50942. {
  50943. if (vertically)
  50944. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  50945. else
  50946. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  50947. }
  50948. }
  50949. }
  50950. pos += layout->currentSize;
  50951. }
  50952. }
  50953. }
  50954. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  50955. {
  50956. for (int i = items.size(); --i >= 0;)
  50957. if (items.getUnchecked(i)->itemIndex == itemIndex)
  50958. return items.getUnchecked(i);
  50959. return 0;
  50960. }
  50961. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  50962. const int endIndex,
  50963. const int availableSpace,
  50964. int startPos)
  50965. {
  50966. // calculate the total sizes
  50967. int i;
  50968. double totalIdealSize = 0.0;
  50969. int totalMinimums = 0;
  50970. for (i = startIndex; i < endIndex; ++i)
  50971. {
  50972. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50973. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  50974. totalMinimums += layout->currentSize;
  50975. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  50976. }
  50977. if (totalIdealSize <= 0)
  50978. totalIdealSize = 1.0;
  50979. // now calc the best sizes..
  50980. int extraSpace = availableSpace - totalMinimums;
  50981. while (extraSpace > 0)
  50982. {
  50983. int numWantingMoreSpace = 0;
  50984. int numHavingTakenExtraSpace = 0;
  50985. // first figure out how many comps want a slice of the extra space..
  50986. for (i = startIndex; i < endIndex; ++i)
  50987. {
  50988. ItemLayoutProperties* const layout = items.getUnchecked (i);
  50989. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  50990. const int bestSize = jlimit (layout->currentSize,
  50991. jmax (layout->currentSize,
  50992. sizeToRealSize (layout->maxSize, totalSize)),
  50993. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  50994. if (bestSize > layout->currentSize)
  50995. ++numWantingMoreSpace;
  50996. }
  50997. // ..share out the extra space..
  50998. for (i = startIndex; i < endIndex; ++i)
  50999. {
  51000. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51001. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51002. int bestSize = jlimit (layout->currentSize,
  51003. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51004. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51005. const int extraWanted = bestSize - layout->currentSize;
  51006. if (extraWanted > 0)
  51007. {
  51008. const int extraAllowed = jmin (extraWanted,
  51009. extraSpace / jmax (1, numWantingMoreSpace));
  51010. if (extraAllowed > 0)
  51011. {
  51012. ++numHavingTakenExtraSpace;
  51013. --numWantingMoreSpace;
  51014. layout->currentSize += extraAllowed;
  51015. extraSpace -= extraAllowed;
  51016. }
  51017. }
  51018. }
  51019. if (numHavingTakenExtraSpace <= 0)
  51020. break;
  51021. }
  51022. // ..and calculate the end position
  51023. for (i = startIndex; i < endIndex; ++i)
  51024. {
  51025. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51026. startPos += layout->currentSize;
  51027. }
  51028. return startPos;
  51029. }
  51030. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51031. const int endIndex) const
  51032. {
  51033. int totalMinimums = 0;
  51034. for (int i = startIndex; i < endIndex; ++i)
  51035. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51036. return totalMinimums;
  51037. }
  51038. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51039. {
  51040. int totalMaximums = 0;
  51041. for (int i = startIndex; i < endIndex; ++i)
  51042. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51043. return totalMaximums;
  51044. }
  51045. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51046. {
  51047. for (int i = 0; i < items.size(); ++i)
  51048. {
  51049. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51050. layout->preferredSize
  51051. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51052. : getItemCurrentAbsoluteSize (i);
  51053. }
  51054. }
  51055. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51056. {
  51057. if (size < 0)
  51058. size *= -totalSpace;
  51059. return roundToInt (size);
  51060. }
  51061. END_JUCE_NAMESPACE
  51062. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51063. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51064. BEGIN_JUCE_NAMESPACE
  51065. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51066. const int itemIndex_,
  51067. const bool isVertical_)
  51068. : layout (layout_),
  51069. itemIndex (itemIndex_),
  51070. isVertical (isVertical_)
  51071. {
  51072. setRepaintsOnMouseActivity (true);
  51073. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51074. : MouseCursor::UpDownResizeCursor));
  51075. }
  51076. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51077. {
  51078. }
  51079. void StretchableLayoutResizerBar::paint (Graphics& g)
  51080. {
  51081. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51082. getWidth(), getHeight(),
  51083. isVertical,
  51084. isMouseOver(),
  51085. isMouseButtonDown());
  51086. }
  51087. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51088. {
  51089. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51090. }
  51091. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51092. {
  51093. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51094. : e.getDistanceFromDragStartY());
  51095. if (layout->getItemCurrentPosition (itemIndex) != desiredPos)
  51096. {
  51097. layout->setItemPosition (itemIndex, desiredPos);
  51098. hasBeenMoved();
  51099. }
  51100. }
  51101. void StretchableLayoutResizerBar::hasBeenMoved()
  51102. {
  51103. if (getParentComponent() != 0)
  51104. getParentComponent()->resized();
  51105. }
  51106. END_JUCE_NAMESPACE
  51107. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51108. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51109. BEGIN_JUCE_NAMESPACE
  51110. StretchableObjectResizer::StretchableObjectResizer()
  51111. {
  51112. }
  51113. StretchableObjectResizer::~StretchableObjectResizer()
  51114. {
  51115. }
  51116. void StretchableObjectResizer::addItem (const double size,
  51117. const double minSize, const double maxSize,
  51118. const int order)
  51119. {
  51120. // the order must be >= 0 but less than the maximum integer value.
  51121. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51122. Item* const item = new Item();
  51123. item->size = size;
  51124. item->minSize = minSize;
  51125. item->maxSize = maxSize;
  51126. item->order = order;
  51127. items.add (item);
  51128. }
  51129. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51130. {
  51131. const Item* const it = items [index];
  51132. return it != 0 ? it->size : 0;
  51133. }
  51134. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51135. {
  51136. int order = 0;
  51137. for (;;)
  51138. {
  51139. double currentSize = 0;
  51140. double minSize = 0;
  51141. double maxSize = 0;
  51142. int nextHighestOrder = std::numeric_limits<int>::max();
  51143. for (int i = 0; i < items.size(); ++i)
  51144. {
  51145. const Item* const it = items.getUnchecked(i);
  51146. currentSize += it->size;
  51147. if (it->order <= order)
  51148. {
  51149. minSize += it->minSize;
  51150. maxSize += it->maxSize;
  51151. }
  51152. else
  51153. {
  51154. minSize += it->size;
  51155. maxSize += it->size;
  51156. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51157. }
  51158. }
  51159. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51160. if (thisIterationTarget >= currentSize)
  51161. {
  51162. const double availableExtraSpace = maxSize - currentSize;
  51163. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51164. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51165. for (int i = 0; i < items.size(); ++i)
  51166. {
  51167. Item* const it = items.getUnchecked(i);
  51168. if (it->order <= order)
  51169. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51170. }
  51171. }
  51172. else
  51173. {
  51174. const double amountOfSlack = currentSize - minSize;
  51175. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51176. const double scale = targetAmountOfSlack / amountOfSlack;
  51177. for (int i = 0; i < items.size(); ++i)
  51178. {
  51179. Item* const it = items.getUnchecked(i);
  51180. if (it->order <= order)
  51181. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51182. }
  51183. }
  51184. if (nextHighestOrder < std::numeric_limits<int>::max())
  51185. order = nextHighestOrder;
  51186. else
  51187. break;
  51188. }
  51189. }
  51190. END_JUCE_NAMESPACE
  51191. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51192. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51193. BEGIN_JUCE_NAMESPACE
  51194. TabBarButton::TabBarButton (const String& name, TabbedButtonBar& owner_)
  51195. : Button (name),
  51196. owner (owner_),
  51197. overlapPixels (0)
  51198. {
  51199. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51200. setComponentEffect (&shadow);
  51201. setWantsKeyboardFocus (false);
  51202. }
  51203. TabBarButton::~TabBarButton()
  51204. {
  51205. }
  51206. int TabBarButton::getIndex() const
  51207. {
  51208. return owner.indexOfTabButton (this);
  51209. }
  51210. void TabBarButton::paintButton (Graphics& g,
  51211. bool isMouseOverButton,
  51212. bool isButtonDown)
  51213. {
  51214. const Rectangle<int> area (getActiveArea());
  51215. g.setOrigin (area.getX(), area.getY());
  51216. getLookAndFeel()
  51217. .drawTabButton (g, area.getWidth(), area.getHeight(),
  51218. owner.getTabBackgroundColour (getIndex()),
  51219. getIndex(), getButtonText(), *this,
  51220. owner.getOrientation(),
  51221. isMouseOverButton, isButtonDown,
  51222. getToggleState());
  51223. }
  51224. void TabBarButton::clicked (const ModifierKeys& mods)
  51225. {
  51226. if (mods.isPopupMenu())
  51227. owner.popupMenuClickOnTab (getIndex(), getButtonText());
  51228. else
  51229. owner.setCurrentTabIndex (getIndex());
  51230. }
  51231. bool TabBarButton::hitTest (int mx, int my)
  51232. {
  51233. const Rectangle<int> area (getActiveArea());
  51234. if (owner.getOrientation() == TabbedButtonBar::TabsAtLeft
  51235. || owner.getOrientation() == TabbedButtonBar::TabsAtRight)
  51236. {
  51237. if (isPositiveAndBelow (mx, getWidth())
  51238. && my >= area.getY() + overlapPixels
  51239. && my < area.getBottom() - overlapPixels)
  51240. return true;
  51241. }
  51242. else
  51243. {
  51244. if (mx >= area.getX() + overlapPixels && mx < area.getRight() - overlapPixels
  51245. && isPositiveAndBelow (my, getHeight()))
  51246. return true;
  51247. }
  51248. Path p;
  51249. getLookAndFeel()
  51250. .createTabButtonShape (p, area.getWidth(), area.getHeight(), getIndex(), getButtonText(), *this,
  51251. owner.getOrientation(), false, false, getToggleState());
  51252. return p.contains ((float) (mx - area.getX()),
  51253. (float) (my - area.getY()));
  51254. }
  51255. int TabBarButton::getBestTabLength (const int depth)
  51256. {
  51257. return jlimit (depth * 2,
  51258. depth * 7,
  51259. getLookAndFeel().getTabButtonBestWidth (getIndex(), getButtonText(), depth, *this));
  51260. }
  51261. const Rectangle<int> TabBarButton::getActiveArea()
  51262. {
  51263. Rectangle<int> r (getLocalBounds());
  51264. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51265. if (owner.getOrientation() != TabbedButtonBar::TabsAtLeft) r.removeFromRight (spaceAroundImage);
  51266. if (owner.getOrientation() != TabbedButtonBar::TabsAtRight) r.removeFromLeft (spaceAroundImage);
  51267. if (owner.getOrientation() != TabbedButtonBar::TabsAtBottom) r.removeFromTop (spaceAroundImage);
  51268. if (owner.getOrientation() != TabbedButtonBar::TabsAtTop) r.removeFromBottom (spaceAroundImage);
  51269. return r;
  51270. }
  51271. class TabbedButtonBar::BehindFrontTabComp : public Component,
  51272. public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  51273. {
  51274. public:
  51275. BehindFrontTabComp (TabbedButtonBar& owner_)
  51276. : owner (owner_)
  51277. {
  51278. setInterceptsMouseClicks (false, false);
  51279. }
  51280. void paint (Graphics& g)
  51281. {
  51282. getLookAndFeel().drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51283. owner, owner.getOrientation());
  51284. }
  51285. void enablementChanged()
  51286. {
  51287. repaint();
  51288. }
  51289. void buttonClicked (Button*)
  51290. {
  51291. owner.showExtraItemsMenu();
  51292. }
  51293. private:
  51294. TabbedButtonBar& owner;
  51295. JUCE_DECLARE_NON_COPYABLE (BehindFrontTabComp);
  51296. };
  51297. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51298. : orientation (orientation_),
  51299. minimumScale (0.7),
  51300. currentTabIndex (-1)
  51301. {
  51302. setInterceptsMouseClicks (false, true);
  51303. addAndMakeVisible (behindFrontTab = new BehindFrontTabComp (*this));
  51304. setFocusContainer (true);
  51305. }
  51306. TabbedButtonBar::~TabbedButtonBar()
  51307. {
  51308. tabs.clear();
  51309. extraTabsButton = 0;
  51310. }
  51311. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51312. {
  51313. orientation = newOrientation;
  51314. for (int i = getNumChildComponents(); --i >= 0;)
  51315. getChildComponent (i)->resized();
  51316. resized();
  51317. }
  51318. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int /*index*/)
  51319. {
  51320. return new TabBarButton (name, *this);
  51321. }
  51322. void TabbedButtonBar::setMinimumTabScaleFactor (double newMinimumScale)
  51323. {
  51324. minimumScale = newMinimumScale;
  51325. resized();
  51326. }
  51327. void TabbedButtonBar::clearTabs()
  51328. {
  51329. tabs.clear();
  51330. extraTabsButton = 0;
  51331. setCurrentTabIndex (-1);
  51332. }
  51333. void TabbedButtonBar::addTab (const String& tabName,
  51334. const Colour& tabBackgroundColour,
  51335. int insertIndex)
  51336. {
  51337. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51338. if (tabName.isNotEmpty())
  51339. {
  51340. if (! isPositiveAndBelow (insertIndex, tabs.size()))
  51341. insertIndex = tabs.size();
  51342. TabInfo* newTab = new TabInfo();
  51343. newTab->name = tabName;
  51344. newTab->colour = tabBackgroundColour;
  51345. newTab->component = createTabButton (tabName, insertIndex);
  51346. jassert (newTab->component != 0);
  51347. tabs.insert (insertIndex, newTab);
  51348. addAndMakeVisible (newTab->component, insertIndex);
  51349. resized();
  51350. if (currentTabIndex < 0)
  51351. setCurrentTabIndex (0);
  51352. }
  51353. }
  51354. void TabbedButtonBar::setTabName (const int tabIndex, const String& newName)
  51355. {
  51356. TabInfo* const tab = tabs [tabIndex];
  51357. if (tab != 0 && tab->name != newName)
  51358. {
  51359. tab->name = newName;
  51360. tab->component->setButtonText (newName);
  51361. resized();
  51362. }
  51363. }
  51364. void TabbedButtonBar::removeTab (const int tabIndex)
  51365. {
  51366. if (tabs [tabIndex] != 0)
  51367. {
  51368. const int oldTabIndex = currentTabIndex;
  51369. if (currentTabIndex == tabIndex)
  51370. currentTabIndex = -1;
  51371. tabs.remove (tabIndex);
  51372. resized();
  51373. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51374. }
  51375. }
  51376. void TabbedButtonBar::moveTab (const int currentIndex, const int newIndex)
  51377. {
  51378. tabs.move (currentIndex, newIndex);
  51379. resized();
  51380. }
  51381. int TabbedButtonBar::getNumTabs() const
  51382. {
  51383. return tabs.size();
  51384. }
  51385. const String TabbedButtonBar::getCurrentTabName() const
  51386. {
  51387. TabInfo* tab = tabs [currentTabIndex];
  51388. return tab == 0 ? String::empty : tab->name;
  51389. }
  51390. const StringArray TabbedButtonBar::getTabNames() const
  51391. {
  51392. StringArray names;
  51393. for (int i = 0; i < tabs.size(); ++i)
  51394. names.add (tabs.getUnchecked(i)->name);
  51395. return names;
  51396. }
  51397. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51398. {
  51399. if (currentTabIndex != newIndex)
  51400. {
  51401. if (! isPositiveAndBelow (newIndex, tabs.size()))
  51402. newIndex = -1;
  51403. currentTabIndex = newIndex;
  51404. for (int i = 0; i < tabs.size(); ++i)
  51405. {
  51406. TabBarButton* tb = tabs.getUnchecked(i)->component;
  51407. tb->setToggleState (i == newIndex, false);
  51408. }
  51409. resized();
  51410. if (sendChangeMessage_)
  51411. sendChangeMessage();
  51412. currentTabChanged (newIndex, getCurrentTabName());
  51413. }
  51414. }
  51415. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51416. {
  51417. TabInfo* const tab = tabs[index];
  51418. return tab == 0 ? 0 : static_cast <TabBarButton*> (tab->component);
  51419. }
  51420. int TabbedButtonBar::indexOfTabButton (const TabBarButton* button) const
  51421. {
  51422. for (int i = tabs.size(); --i >= 0;)
  51423. if (tabs.getUnchecked(i)->component == button)
  51424. return i;
  51425. return -1;
  51426. }
  51427. void TabbedButtonBar::lookAndFeelChanged()
  51428. {
  51429. extraTabsButton = 0;
  51430. resized();
  51431. }
  51432. void TabbedButtonBar::resized()
  51433. {
  51434. int depth = getWidth();
  51435. int length = getHeight();
  51436. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51437. swapVariables (depth, length);
  51438. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51439. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51440. int i, totalLength = overlap;
  51441. int numVisibleButtons = tabs.size();
  51442. for (i = 0; i < tabs.size(); ++i)
  51443. {
  51444. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51445. totalLength += tb->getBestTabLength (depth) - overlap;
  51446. tb->overlapPixels = overlap / 2;
  51447. }
  51448. double scale = 1.0;
  51449. if (totalLength > length)
  51450. scale = jmax (minimumScale, length / (double) totalLength);
  51451. const bool isTooBig = totalLength * scale > length;
  51452. int tabsButtonPos = 0;
  51453. if (isTooBig)
  51454. {
  51455. if (extraTabsButton == 0)
  51456. {
  51457. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51458. extraTabsButton->addListener (behindFrontTab);
  51459. extraTabsButton->setAlwaysOnTop (true);
  51460. extraTabsButton->setTriggeredOnMouseDown (true);
  51461. }
  51462. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51463. extraTabsButton->setSize (buttonSize, buttonSize);
  51464. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51465. {
  51466. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51467. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51468. }
  51469. else
  51470. {
  51471. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51472. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51473. }
  51474. totalLength = 0;
  51475. for (i = 0; i < tabs.size(); ++i)
  51476. {
  51477. TabBarButton* const tb = tabs.getUnchecked(i)->component;
  51478. const int newLength = totalLength + tb->getBestTabLength (depth);
  51479. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51480. {
  51481. totalLength += overlap;
  51482. break;
  51483. }
  51484. numVisibleButtons = i + 1;
  51485. totalLength = newLength - overlap;
  51486. }
  51487. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51488. }
  51489. else
  51490. {
  51491. extraTabsButton = 0;
  51492. }
  51493. int pos = 0;
  51494. TabBarButton* frontTab = 0;
  51495. for (i = 0; i < tabs.size(); ++i)
  51496. {
  51497. TabBarButton* const tb = getTabButton (i);
  51498. if (tb != 0)
  51499. {
  51500. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51501. if (i < numVisibleButtons)
  51502. {
  51503. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51504. tb->setBounds (pos, 0, bestLength, getHeight());
  51505. else
  51506. tb->setBounds (0, pos, getWidth(), bestLength);
  51507. tb->toBack();
  51508. if (i == currentTabIndex)
  51509. frontTab = tb;
  51510. tb->setVisible (true);
  51511. }
  51512. else
  51513. {
  51514. tb->setVisible (false);
  51515. }
  51516. pos += bestLength - overlap;
  51517. }
  51518. }
  51519. behindFrontTab->setBounds (getLocalBounds());
  51520. if (frontTab != 0)
  51521. {
  51522. frontTab->toFront (false);
  51523. behindFrontTab->toBehind (frontTab);
  51524. }
  51525. }
  51526. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51527. {
  51528. TabInfo* const tab = tabs [tabIndex];
  51529. return tab == 0 ? Colours::white : tab->colour;
  51530. }
  51531. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51532. {
  51533. TabInfo* const tab = tabs [tabIndex];
  51534. if (tab != 0 && tab->colour != newColour)
  51535. {
  51536. tab->colour = newColour;
  51537. repaint();
  51538. }
  51539. }
  51540. void TabbedButtonBar::showExtraItemsMenu()
  51541. {
  51542. PopupMenu m;
  51543. for (int i = 0; i < tabs.size(); ++i)
  51544. {
  51545. const TabInfo* const tab = tabs.getUnchecked(i);
  51546. if (! tab->component->isVisible())
  51547. m.addItem (i + 1, tab->name, true, i == currentTabIndex);
  51548. }
  51549. const int res = m.showAt (extraTabsButton);
  51550. if (res != 0)
  51551. setCurrentTabIndex (res - 1);
  51552. }
  51553. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51554. {
  51555. }
  51556. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51557. {
  51558. }
  51559. END_JUCE_NAMESPACE
  51560. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51561. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51562. BEGIN_JUCE_NAMESPACE
  51563. namespace TabbedComponentHelpers
  51564. {
  51565. const Identifier deleteComponentId ("deleteByTabComp_");
  51566. void deleteIfNecessary (Component* const comp)
  51567. {
  51568. if (comp != 0 && (bool) comp->getProperties() [deleteComponentId])
  51569. delete comp;
  51570. }
  51571. const Rectangle<int> getTabArea (Rectangle<int>& content, BorderSize<int>& outline,
  51572. const TabbedButtonBar::Orientation orientation, const int tabDepth)
  51573. {
  51574. switch (orientation)
  51575. {
  51576. case TabbedButtonBar::TabsAtTop: outline.setTop (0); return content.removeFromTop (tabDepth);
  51577. case TabbedButtonBar::TabsAtBottom: outline.setBottom (0); return content.removeFromBottom (tabDepth);
  51578. case TabbedButtonBar::TabsAtLeft: outline.setLeft (0); return content.removeFromLeft (tabDepth);
  51579. case TabbedButtonBar::TabsAtRight: outline.setRight (0); return content.removeFromRight (tabDepth);
  51580. default: jassertfalse; break;
  51581. }
  51582. return Rectangle<int>();
  51583. }
  51584. }
  51585. class TabbedComponent::ButtonBar : public TabbedButtonBar
  51586. {
  51587. public:
  51588. ButtonBar (TabbedComponent& owner_, const TabbedButtonBar::Orientation orientation_)
  51589. : TabbedButtonBar (orientation_),
  51590. owner (owner_)
  51591. {
  51592. }
  51593. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51594. {
  51595. owner.changeCallback (newCurrentTabIndex, newTabName);
  51596. }
  51597. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51598. {
  51599. owner.popupMenuClickOnTab (tabIndex, tabName);
  51600. }
  51601. const Colour getTabBackgroundColour (const int tabIndex)
  51602. {
  51603. return owner.tabs->getTabBackgroundColour (tabIndex);
  51604. }
  51605. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51606. {
  51607. return owner.createTabButton (tabName, tabIndex);
  51608. }
  51609. private:
  51610. TabbedComponent& owner;
  51611. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonBar);
  51612. };
  51613. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51614. : tabDepth (30),
  51615. outlineThickness (1),
  51616. edgeIndent (0)
  51617. {
  51618. addAndMakeVisible (tabs = new ButtonBar (*this, orientation));
  51619. }
  51620. TabbedComponent::~TabbedComponent()
  51621. {
  51622. clearTabs();
  51623. tabs = 0;
  51624. }
  51625. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51626. {
  51627. tabs->setOrientation (orientation);
  51628. resized();
  51629. }
  51630. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51631. {
  51632. return tabs->getOrientation();
  51633. }
  51634. void TabbedComponent::setTabBarDepth (const int newDepth)
  51635. {
  51636. if (tabDepth != newDepth)
  51637. {
  51638. tabDepth = newDepth;
  51639. resized();
  51640. }
  51641. }
  51642. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int /*tabIndex*/)
  51643. {
  51644. return new TabBarButton (tabName, *tabs);
  51645. }
  51646. void TabbedComponent::clearTabs()
  51647. {
  51648. if (panelComponent != 0)
  51649. {
  51650. panelComponent->setVisible (false);
  51651. removeChildComponent (panelComponent);
  51652. panelComponent = 0;
  51653. }
  51654. tabs->clearTabs();
  51655. for (int i = contentComponents.size(); --i >= 0;)
  51656. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (i));
  51657. contentComponents.clear();
  51658. }
  51659. void TabbedComponent::addTab (const String& tabName,
  51660. const Colour& tabBackgroundColour,
  51661. Component* const contentComponent,
  51662. const bool deleteComponentWhenNotNeeded,
  51663. const int insertIndex)
  51664. {
  51665. contentComponents.insert (insertIndex, WeakReference<Component> (contentComponent));
  51666. if (deleteComponentWhenNotNeeded && contentComponent != 0)
  51667. contentComponent->getProperties().set (TabbedComponentHelpers::deleteComponentId, true);
  51668. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51669. }
  51670. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51671. {
  51672. tabs->setTabName (tabIndex, newName);
  51673. }
  51674. void TabbedComponent::removeTab (const int tabIndex)
  51675. {
  51676. if (isPositiveAndBelow (tabIndex, contentComponents.size()))
  51677. {
  51678. TabbedComponentHelpers::deleteIfNecessary (contentComponents.getReference (tabIndex));
  51679. contentComponents.remove (tabIndex);
  51680. tabs->removeTab (tabIndex);
  51681. }
  51682. }
  51683. int TabbedComponent::getNumTabs() const
  51684. {
  51685. return tabs->getNumTabs();
  51686. }
  51687. const StringArray TabbedComponent::getTabNames() const
  51688. {
  51689. return tabs->getTabNames();
  51690. }
  51691. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51692. {
  51693. return contentComponents [tabIndex];
  51694. }
  51695. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51696. {
  51697. return tabs->getTabBackgroundColour (tabIndex);
  51698. }
  51699. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51700. {
  51701. tabs->setTabBackgroundColour (tabIndex, newColour);
  51702. if (getCurrentTabIndex() == tabIndex)
  51703. repaint();
  51704. }
  51705. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51706. {
  51707. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51708. }
  51709. int TabbedComponent::getCurrentTabIndex() const
  51710. {
  51711. return tabs->getCurrentTabIndex();
  51712. }
  51713. const String TabbedComponent::getCurrentTabName() const
  51714. {
  51715. return tabs->getCurrentTabName();
  51716. }
  51717. void TabbedComponent::setOutline (const int thickness)
  51718. {
  51719. outlineThickness = thickness;
  51720. resized();
  51721. repaint();
  51722. }
  51723. void TabbedComponent::setIndent (const int indentThickness)
  51724. {
  51725. edgeIndent = indentThickness;
  51726. resized();
  51727. repaint();
  51728. }
  51729. void TabbedComponent::paint (Graphics& g)
  51730. {
  51731. g.fillAll (findColour (backgroundColourId));
  51732. Rectangle<int> content (getLocalBounds());
  51733. BorderSize<int> outline (outlineThickness);
  51734. TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth);
  51735. g.reduceClipRegion (content);
  51736. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51737. if (outlineThickness > 0)
  51738. {
  51739. RectangleList rl (content);
  51740. rl.subtract (outline.subtractedFrom (content));
  51741. g.reduceClipRegion (rl);
  51742. g.fillAll (findColour (outlineColourId));
  51743. }
  51744. }
  51745. void TabbedComponent::resized()
  51746. {
  51747. Rectangle<int> content (getLocalBounds());
  51748. BorderSize<int> outline (outlineThickness);
  51749. tabs->setBounds (TabbedComponentHelpers::getTabArea (content, outline, getOrientation(), tabDepth));
  51750. content = BorderSize<int> (edgeIndent).subtractedFrom (outline.subtractedFrom (content));
  51751. for (int i = contentComponents.size(); --i >= 0;)
  51752. if (contentComponents.getReference (i) != 0)
  51753. contentComponents.getReference (i)->setBounds (content);
  51754. }
  51755. void TabbedComponent::lookAndFeelChanged()
  51756. {
  51757. for (int i = contentComponents.size(); --i >= 0;)
  51758. if (contentComponents.getReference (i) != 0)
  51759. contentComponents.getReference (i)->lookAndFeelChanged();
  51760. }
  51761. void TabbedComponent::changeCallback (const int newCurrentTabIndex, const String& newTabName)
  51762. {
  51763. if (panelComponent != 0)
  51764. {
  51765. panelComponent->setVisible (false);
  51766. removeChildComponent (panelComponent);
  51767. panelComponent = 0;
  51768. }
  51769. if (getCurrentTabIndex() >= 0)
  51770. {
  51771. panelComponent = getTabContentComponent (getCurrentTabIndex());
  51772. if (panelComponent != 0)
  51773. {
  51774. // do these ops as two stages instead of addAndMakeVisible() so that the
  51775. // component has always got a parent when it gets the visibilityChanged() callback
  51776. addChildComponent (panelComponent);
  51777. panelComponent->setVisible (true);
  51778. panelComponent->toFront (true);
  51779. }
  51780. repaint();
  51781. }
  51782. resized();
  51783. currentTabChanged (newCurrentTabIndex, newTabName);
  51784. }
  51785. void TabbedComponent::currentTabChanged (const int, const String&) {}
  51786. void TabbedComponent::popupMenuClickOnTab (const int, const String&) {}
  51787. END_JUCE_NAMESPACE
  51788. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  51789. /*** Start of inlined file: juce_Viewport.cpp ***/
  51790. BEGIN_JUCE_NAMESPACE
  51791. Viewport::Viewport (const String& componentName)
  51792. : Component (componentName),
  51793. scrollBarThickness (0),
  51794. singleStepX (16),
  51795. singleStepY (16),
  51796. showHScrollbar (true),
  51797. showVScrollbar (true),
  51798. verticalScrollBar (true),
  51799. horizontalScrollBar (false)
  51800. {
  51801. // content holder is used to clip the contents so they don't overlap the scrollbars
  51802. addAndMakeVisible (&contentHolder);
  51803. contentHolder.setInterceptsMouseClicks (false, true);
  51804. addChildComponent (&verticalScrollBar);
  51805. addChildComponent (&horizontalScrollBar);
  51806. verticalScrollBar.addListener (this);
  51807. horizontalScrollBar.addListener (this);
  51808. setInterceptsMouseClicks (false, true);
  51809. setWantsKeyboardFocus (true);
  51810. }
  51811. Viewport::~Viewport()
  51812. {
  51813. deleteContentComp();
  51814. }
  51815. void Viewport::visibleAreaChanged (const Rectangle<int>&)
  51816. {
  51817. }
  51818. void Viewport::deleteContentComp()
  51819. {
  51820. // This sets the content comp to a null pointer before deleting the old one, in case
  51821. // anything tries to use the old one while it's in mid-deletion..
  51822. ScopedPointer<Component> oldCompDeleter (contentComp);
  51823. contentComp = 0;
  51824. }
  51825. void Viewport::setViewedComponent (Component* const newViewedComponent)
  51826. {
  51827. if (contentComp.get() != newViewedComponent)
  51828. {
  51829. deleteContentComp();
  51830. contentComp = newViewedComponent;
  51831. if (contentComp != 0)
  51832. {
  51833. contentHolder.addAndMakeVisible (contentComp);
  51834. setViewPosition (0, 0);
  51835. contentComp->addComponentListener (this);
  51836. }
  51837. updateVisibleArea();
  51838. }
  51839. }
  51840. int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); }
  51841. int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); }
  51842. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  51843. {
  51844. if (contentComp != 0)
  51845. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  51846. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  51847. }
  51848. void Viewport::setViewPosition (const Point<int>& newPosition)
  51849. {
  51850. setViewPosition (newPosition.getX(), newPosition.getY());
  51851. }
  51852. void Viewport::setViewPositionProportionately (const double x, const double y)
  51853. {
  51854. if (contentComp != 0)
  51855. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  51856. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  51857. }
  51858. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  51859. {
  51860. if (contentComp != 0)
  51861. {
  51862. int dx = 0, dy = 0;
  51863. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  51864. {
  51865. if (mouseX < activeBorderThickness)
  51866. dx = activeBorderThickness - mouseX;
  51867. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  51868. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  51869. if (dx < 0)
  51870. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  51871. else
  51872. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  51873. }
  51874. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  51875. {
  51876. if (mouseY < activeBorderThickness)
  51877. dy = activeBorderThickness - mouseY;
  51878. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  51879. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  51880. if (dy < 0)
  51881. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  51882. else
  51883. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  51884. }
  51885. if (dx != 0 || dy != 0)
  51886. {
  51887. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  51888. contentComp->getY() + dy);
  51889. return true;
  51890. }
  51891. }
  51892. return false;
  51893. }
  51894. void Viewport::componentMovedOrResized (Component&, bool, bool)
  51895. {
  51896. updateVisibleArea();
  51897. }
  51898. void Viewport::resized()
  51899. {
  51900. updateVisibleArea();
  51901. }
  51902. void Viewport::updateVisibleArea()
  51903. {
  51904. const int scrollbarWidth = getScrollBarThickness();
  51905. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  51906. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  51907. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  51908. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  51909. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  51910. Rectangle<int> contentArea (getLocalBounds());
  51911. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  51912. {
  51913. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  51914. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  51915. if (vBarVisible)
  51916. contentArea.setWidth (getWidth() - scrollbarWidth);
  51917. if (hBarVisible)
  51918. contentArea.setHeight (getHeight() - scrollbarWidth);
  51919. if (! contentArea.contains (contentComp->getBounds()))
  51920. {
  51921. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  51922. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  51923. }
  51924. }
  51925. if (vBarVisible)
  51926. contentArea.setWidth (getWidth() - scrollbarWidth);
  51927. if (hBarVisible)
  51928. contentArea.setHeight (getHeight() - scrollbarWidth);
  51929. contentHolder.setBounds (contentArea);
  51930. Rectangle<int> contentBounds;
  51931. if (contentComp != 0)
  51932. contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds());
  51933. Point<int> visibleOrigin (-contentBounds.getPosition());
  51934. if (hBarVisible)
  51935. {
  51936. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  51937. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  51938. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  51939. horizontalScrollBar.setSingleStepSize (singleStepX);
  51940. horizontalScrollBar.cancelPendingUpdate();
  51941. }
  51942. else if (canShowHBar)
  51943. {
  51944. visibleOrigin.setX (0);
  51945. }
  51946. if (vBarVisible)
  51947. {
  51948. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  51949. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  51950. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  51951. verticalScrollBar.setSingleStepSize (singleStepY);
  51952. verticalScrollBar.cancelPendingUpdate();
  51953. }
  51954. else if (canShowVBar)
  51955. {
  51956. visibleOrigin.setY (0);
  51957. }
  51958. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  51959. horizontalScrollBar.setVisible (hBarVisible);
  51960. verticalScrollBar.setVisible (vBarVisible);
  51961. setViewPosition (visibleOrigin);
  51962. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  51963. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  51964. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  51965. if (lastVisibleArea != visibleArea)
  51966. {
  51967. lastVisibleArea = visibleArea;
  51968. visibleAreaChanged (visibleArea);
  51969. }
  51970. horizontalScrollBar.handleUpdateNowIfNeeded();
  51971. verticalScrollBar.handleUpdateNowIfNeeded();
  51972. }
  51973. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  51974. {
  51975. if (singleStepX != stepX || singleStepY != stepY)
  51976. {
  51977. singleStepX = stepX;
  51978. singleStepY = stepY;
  51979. updateVisibleArea();
  51980. }
  51981. }
  51982. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  51983. const bool showHorizontalScrollbarIfNeeded)
  51984. {
  51985. if (showVScrollbar != showVerticalScrollbarIfNeeded
  51986. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  51987. {
  51988. showVScrollbar = showVerticalScrollbarIfNeeded;
  51989. showHScrollbar = showHorizontalScrollbarIfNeeded;
  51990. updateVisibleArea();
  51991. }
  51992. }
  51993. void Viewport::setScrollBarThickness (const int thickness)
  51994. {
  51995. if (scrollBarThickness != thickness)
  51996. {
  51997. scrollBarThickness = thickness;
  51998. updateVisibleArea();
  51999. }
  52000. }
  52001. int Viewport::getScrollBarThickness() const
  52002. {
  52003. return scrollBarThickness > 0 ? scrollBarThickness
  52004. : getLookAndFeel().getDefaultScrollbarWidth();
  52005. }
  52006. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52007. {
  52008. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52009. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52010. }
  52011. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52012. {
  52013. const int newRangeStartInt = roundToInt (newRangeStart);
  52014. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52015. {
  52016. setViewPosition (newRangeStartInt, getViewPositionY());
  52017. }
  52018. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52019. {
  52020. setViewPosition (getViewPositionX(), newRangeStartInt);
  52021. }
  52022. }
  52023. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52024. {
  52025. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52026. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52027. }
  52028. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52029. {
  52030. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52031. {
  52032. const bool hasVertBar = verticalScrollBar.isVisible();
  52033. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52034. if (hasHorzBar || hasVertBar)
  52035. {
  52036. if (wheelIncrementX != 0)
  52037. {
  52038. wheelIncrementX *= 14.0f * singleStepX;
  52039. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52040. : jmax (wheelIncrementX, 1.0f);
  52041. }
  52042. if (wheelIncrementY != 0)
  52043. {
  52044. wheelIncrementY *= 14.0f * singleStepY;
  52045. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52046. : jmax (wheelIncrementY, 1.0f);
  52047. }
  52048. Point<int> pos (getViewPosition());
  52049. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52050. {
  52051. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52052. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52053. }
  52054. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52055. {
  52056. if (wheelIncrementX == 0 && ! hasVertBar)
  52057. wheelIncrementX = wheelIncrementY;
  52058. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52059. }
  52060. else if (hasVertBar && wheelIncrementY != 0)
  52061. {
  52062. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52063. }
  52064. if (pos != getViewPosition())
  52065. {
  52066. setViewPosition (pos);
  52067. return true;
  52068. }
  52069. }
  52070. }
  52071. return false;
  52072. }
  52073. bool Viewport::keyPressed (const KeyPress& key)
  52074. {
  52075. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52076. || key.isKeyCode (KeyPress::downKey)
  52077. || key.isKeyCode (KeyPress::pageUpKey)
  52078. || key.isKeyCode (KeyPress::pageDownKey)
  52079. || key.isKeyCode (KeyPress::homeKey)
  52080. || key.isKeyCode (KeyPress::endKey);
  52081. if (verticalScrollBar.isVisible() && isUpDownKey)
  52082. return verticalScrollBar.keyPressed (key);
  52083. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52084. || key.isKeyCode (KeyPress::rightKey);
  52085. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52086. return horizontalScrollBar.keyPressed (key);
  52087. return false;
  52088. }
  52089. END_JUCE_NAMESPACE
  52090. /*** End of inlined file: juce_Viewport.cpp ***/
  52091. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52092. BEGIN_JUCE_NAMESPACE
  52093. namespace LookAndFeelHelpers
  52094. {
  52095. void createRoundedPath (Path& p,
  52096. const float x, const float y,
  52097. const float w, const float h,
  52098. const float cs,
  52099. const bool curveTopLeft, const bool curveTopRight,
  52100. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52101. {
  52102. const float cs2 = 2.0f * cs;
  52103. if (curveTopLeft)
  52104. {
  52105. p.startNewSubPath (x, y + cs);
  52106. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52107. }
  52108. else
  52109. {
  52110. p.startNewSubPath (x, y);
  52111. }
  52112. if (curveTopRight)
  52113. {
  52114. p.lineTo (x + w - cs, y);
  52115. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52116. }
  52117. else
  52118. {
  52119. p.lineTo (x + w, y);
  52120. }
  52121. if (curveBottomRight)
  52122. {
  52123. p.lineTo (x + w, y + h - cs);
  52124. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52125. }
  52126. else
  52127. {
  52128. p.lineTo (x + w, y + h);
  52129. }
  52130. if (curveBottomLeft)
  52131. {
  52132. p.lineTo (x + cs, y + h);
  52133. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52134. }
  52135. else
  52136. {
  52137. p.lineTo (x, y + h);
  52138. }
  52139. p.closeSubPath();
  52140. }
  52141. const Colour createBaseColour (const Colour& buttonColour,
  52142. const bool hasKeyboardFocus,
  52143. const bool isMouseOverButton,
  52144. const bool isButtonDown) throw()
  52145. {
  52146. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52147. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52148. if (isButtonDown)
  52149. return baseColour.contrasting (0.2f);
  52150. else if (isMouseOverButton)
  52151. return baseColour.contrasting (0.1f);
  52152. return baseColour;
  52153. }
  52154. const TextLayout layoutTooltipText (const String& text) throw()
  52155. {
  52156. const float tooltipFontSize = 12.0f;
  52157. const int maxToolTipWidth = 400;
  52158. const Font f (tooltipFontSize, Font::bold);
  52159. TextLayout tl (text, f);
  52160. tl.layout (maxToolTipWidth, Justification::left, true);
  52161. return tl;
  52162. }
  52163. LookAndFeel* defaultLF = 0;
  52164. LookAndFeel* currentDefaultLF = 0;
  52165. }
  52166. LookAndFeel::LookAndFeel()
  52167. {
  52168. /* if this fails it means you're trying to create a LookAndFeel object before
  52169. the static Colours have been initialised. That ain't gonna work. It probably
  52170. means that you're using a static LookAndFeel object and that your compiler has
  52171. decided to intialise it before the Colours class.
  52172. */
  52173. jassert (Colours::white == Colour (0xffffffff));
  52174. // set up the standard set of colours..
  52175. const int textButtonColour = 0xffbbbbff;
  52176. const int textHighlightColour = 0x401111ee;
  52177. const int standardOutlineColour = 0xb2808080;
  52178. static const int standardColours[] =
  52179. {
  52180. TextButton::buttonColourId, textButtonColour,
  52181. TextButton::buttonOnColourId, 0xff4444ff,
  52182. TextButton::textColourOnId, 0xff000000,
  52183. TextButton::textColourOffId, 0xff000000,
  52184. ComboBox::buttonColourId, 0xffbbbbff,
  52185. ComboBox::outlineColourId, standardOutlineColour,
  52186. ToggleButton::textColourId, 0xff000000,
  52187. TextEditor::backgroundColourId, 0xffffffff,
  52188. TextEditor::textColourId, 0xff000000,
  52189. TextEditor::highlightColourId, textHighlightColour,
  52190. TextEditor::highlightedTextColourId, 0xff000000,
  52191. TextEditor::caretColourId, 0xff000000,
  52192. TextEditor::outlineColourId, 0x00000000,
  52193. TextEditor::focusedOutlineColourId, textButtonColour,
  52194. TextEditor::shadowColourId, 0x38000000,
  52195. Label::backgroundColourId, 0x00000000,
  52196. Label::textColourId, 0xff000000,
  52197. Label::outlineColourId, 0x00000000,
  52198. ScrollBar::backgroundColourId, 0x00000000,
  52199. ScrollBar::thumbColourId, 0xffffffff,
  52200. TreeView::linesColourId, 0x4c000000,
  52201. TreeView::backgroundColourId, 0x00000000,
  52202. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52203. PopupMenu::backgroundColourId, 0xffffffff,
  52204. PopupMenu::textColourId, 0xff000000,
  52205. PopupMenu::headerTextColourId, 0xff000000,
  52206. PopupMenu::highlightedTextColourId, 0xffffffff,
  52207. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52208. ComboBox::textColourId, 0xff000000,
  52209. ComboBox::backgroundColourId, 0xffffffff,
  52210. ComboBox::arrowColourId, 0x99000000,
  52211. ListBox::backgroundColourId, 0xffffffff,
  52212. ListBox::outlineColourId, standardOutlineColour,
  52213. ListBox::textColourId, 0xff000000,
  52214. Slider::backgroundColourId, 0x00000000,
  52215. Slider::thumbColourId, textButtonColour,
  52216. Slider::trackColourId, 0x7fffffff,
  52217. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52218. Slider::rotarySliderOutlineColourId, 0x66000000,
  52219. Slider::textBoxTextColourId, 0xff000000,
  52220. Slider::textBoxBackgroundColourId, 0xffffffff,
  52221. Slider::textBoxHighlightColourId, textHighlightColour,
  52222. Slider::textBoxOutlineColourId, standardOutlineColour,
  52223. ResizableWindow::backgroundColourId, 0xff777777,
  52224. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52225. AlertWindow::backgroundColourId, 0xffededed,
  52226. AlertWindow::textColourId, 0xff000000,
  52227. AlertWindow::outlineColourId, 0xff666666,
  52228. ProgressBar::backgroundColourId, 0xffeeeeee,
  52229. ProgressBar::foregroundColourId, 0xffaaaaee,
  52230. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52231. TooltipWindow::textColourId, 0xff000000,
  52232. TooltipWindow::outlineColourId, 0x4c000000,
  52233. TabbedComponent::backgroundColourId, 0x00000000,
  52234. TabbedComponent::outlineColourId, 0xff777777,
  52235. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52236. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52237. Toolbar::backgroundColourId, 0xfff6f8f9,
  52238. Toolbar::separatorColourId, 0x4c000000,
  52239. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52240. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52241. Toolbar::labelTextColourId, 0xff000000,
  52242. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52243. HyperlinkButton::textColourId, 0xcc1111ee,
  52244. GroupComponent::outlineColourId, 0x66000000,
  52245. GroupComponent::textColourId, 0xff000000,
  52246. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52247. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52248. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52249. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52250. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52251. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52252. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52253. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52254. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52255. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52256. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52257. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52258. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52259. CodeEditorComponent::caretColourId, 0xff000000,
  52260. CodeEditorComponent::highlightColourId, textHighlightColour,
  52261. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52262. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52263. ColourSelector::labelTextColourId, 0xff000000,
  52264. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52265. KeyMappingEditorComponent::textColourId, 0xff000000,
  52266. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52267. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52268. DrawableButton::textColourId, 0xff000000,
  52269. };
  52270. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52271. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52272. static String defaultSansName, defaultSerifName, defaultFixedName, defaultFallback;
  52273. if (defaultSansName.isEmpty())
  52274. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName, defaultFallback);
  52275. defaultSans = defaultSansName;
  52276. defaultSerif = defaultSerifName;
  52277. defaultFixed = defaultFixedName;
  52278. Font::setFallbackFontName (defaultFallback);
  52279. }
  52280. LookAndFeel::~LookAndFeel()
  52281. {
  52282. if (this == LookAndFeelHelpers::currentDefaultLF)
  52283. setDefaultLookAndFeel (0);
  52284. }
  52285. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52286. {
  52287. const int index = colourIds.indexOf (colourId);
  52288. if (index >= 0)
  52289. return colours [index];
  52290. jassertfalse;
  52291. return Colours::black;
  52292. }
  52293. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52294. {
  52295. const int index = colourIds.indexOf (colourId);
  52296. if (index >= 0)
  52297. {
  52298. colours.set (index, colour);
  52299. }
  52300. else
  52301. {
  52302. colourIds.add (colourId);
  52303. colours.add (colour);
  52304. }
  52305. }
  52306. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52307. {
  52308. return colourIds.contains (colourId);
  52309. }
  52310. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52311. {
  52312. // if this happens, your app hasn't initialised itself properly.. if you're
  52313. // trying to hack your own main() function, have a look at
  52314. // JUCEApplication::initialiseForGUI()
  52315. jassert (LookAndFeelHelpers::currentDefaultLF != 0);
  52316. return *LookAndFeelHelpers::currentDefaultLF;
  52317. }
  52318. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52319. {
  52320. using namespace LookAndFeelHelpers;
  52321. if (newDefaultLookAndFeel == 0)
  52322. {
  52323. if (defaultLF == 0)
  52324. defaultLF = new LookAndFeel();
  52325. newDefaultLookAndFeel = defaultLF;
  52326. }
  52327. LookAndFeelHelpers::currentDefaultLF = newDefaultLookAndFeel;
  52328. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52329. {
  52330. Component* const c = Desktop::getInstance().getComponent (i);
  52331. if (c != 0)
  52332. c->sendLookAndFeelChange();
  52333. }
  52334. }
  52335. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52336. {
  52337. using namespace LookAndFeelHelpers;
  52338. if (currentDefaultLF == defaultLF)
  52339. currentDefaultLF = 0;
  52340. deleteAndZero (defaultLF);
  52341. }
  52342. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52343. {
  52344. String faceName (font.getTypefaceName());
  52345. if (faceName == Font::getDefaultSansSerifFontName())
  52346. faceName = defaultSans;
  52347. else if (faceName == Font::getDefaultSerifFontName())
  52348. faceName = defaultSerif;
  52349. else if (faceName == Font::getDefaultMonospacedFontName())
  52350. faceName = defaultFixed;
  52351. Font f (font);
  52352. f.setTypefaceName (faceName);
  52353. return Typeface::createSystemTypefaceFor (f);
  52354. }
  52355. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52356. {
  52357. defaultSans = newName;
  52358. }
  52359. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52360. {
  52361. return component.getMouseCursor();
  52362. }
  52363. void LookAndFeel::drawButtonBackground (Graphics& g,
  52364. Button& button,
  52365. const Colour& backgroundColour,
  52366. bool isMouseOverButton,
  52367. bool isButtonDown)
  52368. {
  52369. const int width = button.getWidth();
  52370. const int height = button.getHeight();
  52371. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52372. const float halfThickness = outlineThickness * 0.5f;
  52373. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52374. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52375. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52376. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52377. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52378. button.hasKeyboardFocus (true),
  52379. isMouseOverButton, isButtonDown)
  52380. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52381. drawGlassLozenge (g,
  52382. indentL,
  52383. indentT,
  52384. width - indentL - indentR,
  52385. height - indentT - indentB,
  52386. baseColour, outlineThickness, -1.0f,
  52387. button.isConnectedOnLeft(),
  52388. button.isConnectedOnRight(),
  52389. button.isConnectedOnTop(),
  52390. button.isConnectedOnBottom());
  52391. }
  52392. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52393. {
  52394. return button.getFont();
  52395. }
  52396. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52397. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52398. {
  52399. Font font (getFontForTextButton (button));
  52400. g.setFont (font);
  52401. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52402. : TextButton::textColourOffId)
  52403. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52404. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52405. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52406. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52407. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52408. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52409. g.drawFittedText (button.getButtonText(),
  52410. leftIndent,
  52411. yIndent,
  52412. button.getWidth() - leftIndent - rightIndent,
  52413. button.getHeight() - yIndent * 2,
  52414. Justification::centred, 2);
  52415. }
  52416. void LookAndFeel::drawTickBox (Graphics& g,
  52417. Component& component,
  52418. float x, float y, float w, float h,
  52419. const bool ticked,
  52420. const bool isEnabled,
  52421. const bool isMouseOverButton,
  52422. const bool isButtonDown)
  52423. {
  52424. const float boxSize = w * 0.7f;
  52425. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52426. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52427. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52428. true, isMouseOverButton, isButtonDown),
  52429. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52430. if (ticked)
  52431. {
  52432. Path tick;
  52433. tick.startNewSubPath (1.5f, 3.0f);
  52434. tick.lineTo (3.0f, 6.0f);
  52435. tick.lineTo (6.0f, 0.0f);
  52436. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52437. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52438. .translated (x, y));
  52439. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52440. }
  52441. }
  52442. void LookAndFeel::drawToggleButton (Graphics& g,
  52443. ToggleButton& button,
  52444. bool isMouseOverButton,
  52445. bool isButtonDown)
  52446. {
  52447. if (button.hasKeyboardFocus (true))
  52448. {
  52449. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52450. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52451. }
  52452. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52453. const float tickWidth = fontSize * 1.1f;
  52454. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52455. tickWidth, tickWidth,
  52456. button.getToggleState(),
  52457. button.isEnabled(),
  52458. isMouseOverButton,
  52459. isButtonDown);
  52460. g.setColour (button.findColour (ToggleButton::textColourId));
  52461. g.setFont (fontSize);
  52462. if (! button.isEnabled())
  52463. g.setOpacity (0.5f);
  52464. const int textX = (int) tickWidth + 5;
  52465. g.drawFittedText (button.getButtonText(),
  52466. textX, 0,
  52467. button.getWidth() - textX - 2, button.getHeight(),
  52468. Justification::centredLeft, 10);
  52469. }
  52470. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52471. {
  52472. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52473. const int tickWidth = jmin (24, button.getHeight());
  52474. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52475. button.getHeight());
  52476. }
  52477. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52478. const String& message,
  52479. const String& button1,
  52480. const String& button2,
  52481. const String& button3,
  52482. AlertWindow::AlertIconType iconType,
  52483. int numButtons,
  52484. Component* associatedComponent)
  52485. {
  52486. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52487. if (numButtons == 1)
  52488. {
  52489. aw->addButton (button1, 0,
  52490. KeyPress (KeyPress::escapeKey, 0, 0),
  52491. KeyPress (KeyPress::returnKey, 0, 0));
  52492. }
  52493. else
  52494. {
  52495. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52496. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52497. if (button1ShortCut == button2ShortCut)
  52498. button2ShortCut = KeyPress();
  52499. if (numButtons == 2)
  52500. {
  52501. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52502. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52503. }
  52504. else if (numButtons == 3)
  52505. {
  52506. aw->addButton (button1, 1, button1ShortCut);
  52507. aw->addButton (button2, 2, button2ShortCut);
  52508. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52509. }
  52510. }
  52511. return aw;
  52512. }
  52513. void LookAndFeel::drawAlertBox (Graphics& g,
  52514. AlertWindow& alert,
  52515. const Rectangle<int>& textArea,
  52516. TextLayout& textLayout)
  52517. {
  52518. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52519. int iconSpaceUsed = 0;
  52520. Justification alignment (Justification::horizontallyCentred);
  52521. const int iconWidth = 80;
  52522. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52523. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52524. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52525. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52526. iconSize, iconSize);
  52527. if (alert.getAlertType() != AlertWindow::NoIcon)
  52528. {
  52529. Path icon;
  52530. uint32 colour;
  52531. char character;
  52532. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52533. {
  52534. colour = 0x55ff5555;
  52535. character = '!';
  52536. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52537. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52538. (float) iconRect.getX(), (float) iconRect.getBottom());
  52539. icon = icon.createPathWithRoundedCorners (5.0f);
  52540. }
  52541. else
  52542. {
  52543. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52544. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52545. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52546. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52547. }
  52548. GlyphArrangement ga;
  52549. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52550. String::charToString (character),
  52551. (float) iconRect.getX(), (float) iconRect.getY(),
  52552. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52553. Justification::centred, false);
  52554. ga.createPath (icon);
  52555. icon.setUsingNonZeroWinding (false);
  52556. g.setColour (Colour (colour));
  52557. g.fillPath (icon);
  52558. iconSpaceUsed = iconWidth;
  52559. alignment = Justification::left;
  52560. }
  52561. g.setColour (alert.findColour (AlertWindow::textColourId));
  52562. textLayout.drawWithin (g,
  52563. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52564. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52565. alignment.getFlags() | Justification::top);
  52566. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52567. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52568. }
  52569. int LookAndFeel::getAlertBoxWindowFlags()
  52570. {
  52571. return ComponentPeer::windowAppearsOnTaskbar
  52572. | ComponentPeer::windowHasDropShadow;
  52573. }
  52574. int LookAndFeel::getAlertWindowButtonHeight()
  52575. {
  52576. return 28;
  52577. }
  52578. const Font LookAndFeel::getAlertWindowMessageFont()
  52579. {
  52580. return Font (15.0f);
  52581. }
  52582. const Font LookAndFeel::getAlertWindowFont()
  52583. {
  52584. return Font (12.0f);
  52585. }
  52586. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52587. int width, int height,
  52588. double progress, const String& textToShow)
  52589. {
  52590. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52591. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52592. g.fillAll (background);
  52593. if (progress >= 0.0f && progress < 1.0f)
  52594. {
  52595. drawGlassLozenge (g, 1.0f, 1.0f,
  52596. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52597. (float) (height - 2),
  52598. foreground,
  52599. 0.5f, 0.0f,
  52600. true, true, true, true);
  52601. }
  52602. else
  52603. {
  52604. // spinning bar..
  52605. g.setColour (foreground);
  52606. const int stripeWidth = height * 2;
  52607. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52608. Path p;
  52609. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52610. p.addQuadrilateral (x, 0.0f,
  52611. x + stripeWidth * 0.5f, 0.0f,
  52612. x, (float) height,
  52613. x - stripeWidth * 0.5f, (float) height);
  52614. Image im (Image::ARGB, width, height, true);
  52615. {
  52616. Graphics g2 (im);
  52617. drawGlassLozenge (g2, 1.0f, 1.0f,
  52618. (float) (width - 2),
  52619. (float) (height - 2),
  52620. foreground,
  52621. 0.5f, 0.0f,
  52622. true, true, true, true);
  52623. }
  52624. g.setTiledImageFill (im, 0, 0, 0.85f);
  52625. g.fillPath (p);
  52626. }
  52627. if (textToShow.isNotEmpty())
  52628. {
  52629. g.setColour (Colour::contrasting (background, foreground));
  52630. g.setFont (height * 0.6f);
  52631. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52632. }
  52633. }
  52634. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52635. {
  52636. const float radius = jmin (w, h) * 0.4f;
  52637. const float thickness = radius * 0.15f;
  52638. Path p;
  52639. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52640. radius * 0.6f, thickness,
  52641. thickness * 0.5f);
  52642. const float cx = x + w * 0.5f;
  52643. const float cy = y + h * 0.5f;
  52644. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52645. for (int i = 0; i < 12; ++i)
  52646. {
  52647. const int n = (i + 12 - animationIndex) % 12;
  52648. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52649. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52650. .translated (cx, cy));
  52651. }
  52652. }
  52653. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52654. ScrollBar& scrollbar,
  52655. int width, int height,
  52656. int buttonDirection,
  52657. bool /*isScrollbarVertical*/,
  52658. bool /*isMouseOverButton*/,
  52659. bool isButtonDown)
  52660. {
  52661. Path p;
  52662. if (buttonDirection == 0)
  52663. p.addTriangle (width * 0.5f, height * 0.2f,
  52664. width * 0.1f, height * 0.7f,
  52665. width * 0.9f, height * 0.7f);
  52666. else if (buttonDirection == 1)
  52667. p.addTriangle (width * 0.8f, height * 0.5f,
  52668. width * 0.3f, height * 0.1f,
  52669. width * 0.3f, height * 0.9f);
  52670. else if (buttonDirection == 2)
  52671. p.addTriangle (width * 0.5f, height * 0.8f,
  52672. width * 0.1f, height * 0.3f,
  52673. width * 0.9f, height * 0.3f);
  52674. else if (buttonDirection == 3)
  52675. p.addTriangle (width * 0.2f, height * 0.5f,
  52676. width * 0.7f, height * 0.1f,
  52677. width * 0.7f, height * 0.9f);
  52678. if (isButtonDown)
  52679. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52680. else
  52681. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52682. g.fillPath (p);
  52683. g.setColour (Colour (0x80000000));
  52684. g.strokePath (p, PathStrokeType (0.5f));
  52685. }
  52686. void LookAndFeel::drawScrollbar (Graphics& g,
  52687. ScrollBar& scrollbar,
  52688. int x, int y,
  52689. int width, int height,
  52690. bool isScrollbarVertical,
  52691. int thumbStartPosition,
  52692. int thumbSize,
  52693. bool /*isMouseOver*/,
  52694. bool /*isMouseDown*/)
  52695. {
  52696. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52697. Path slotPath, thumbPath;
  52698. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52699. const float slotIndentx2 = slotIndent * 2.0f;
  52700. const float thumbIndent = slotIndent + 1.0f;
  52701. const float thumbIndentx2 = thumbIndent * 2.0f;
  52702. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52703. if (isScrollbarVertical)
  52704. {
  52705. slotPath.addRoundedRectangle (x + slotIndent,
  52706. y + slotIndent,
  52707. width - slotIndentx2,
  52708. height - slotIndentx2,
  52709. (width - slotIndentx2) * 0.5f);
  52710. if (thumbSize > 0)
  52711. thumbPath.addRoundedRectangle (x + thumbIndent,
  52712. thumbStartPosition + thumbIndent,
  52713. width - thumbIndentx2,
  52714. thumbSize - thumbIndentx2,
  52715. (width - thumbIndentx2) * 0.5f);
  52716. gx1 = (float) x;
  52717. gx2 = x + width * 0.7f;
  52718. }
  52719. else
  52720. {
  52721. slotPath.addRoundedRectangle (x + slotIndent,
  52722. y + slotIndent,
  52723. width - slotIndentx2,
  52724. height - slotIndentx2,
  52725. (height - slotIndentx2) * 0.5f);
  52726. if (thumbSize > 0)
  52727. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52728. y + thumbIndent,
  52729. thumbSize - thumbIndentx2,
  52730. height - thumbIndentx2,
  52731. (height - thumbIndentx2) * 0.5f);
  52732. gy1 = (float) y;
  52733. gy2 = y + height * 0.7f;
  52734. }
  52735. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52736. Colour trackColour1, trackColour2;
  52737. if (scrollbar.isColourSpecified (ScrollBar::trackColourId))
  52738. {
  52739. trackColour1 = trackColour2 = scrollbar.findColour (ScrollBar::trackColourId);
  52740. }
  52741. else
  52742. {
  52743. trackColour1 = thumbColour.overlaidWith (Colour (0x44000000));
  52744. trackColour2 = thumbColour.overlaidWith (Colour (0x19000000));
  52745. }
  52746. g.setGradientFill (ColourGradient (trackColour1, gx1, gy1,
  52747. trackColour2, gx2, gy2, false));
  52748. g.fillPath (slotPath);
  52749. if (isScrollbarVertical)
  52750. {
  52751. gx1 = x + width * 0.6f;
  52752. gx2 = (float) x + width;
  52753. }
  52754. else
  52755. {
  52756. gy1 = y + height * 0.6f;
  52757. gy2 = (float) y + height;
  52758. }
  52759. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52760. Colour (0x19000000), gx2, gy2, false));
  52761. g.fillPath (slotPath);
  52762. g.setColour (thumbColour);
  52763. g.fillPath (thumbPath);
  52764. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52765. Colours::transparentBlack, gx2, gy2, false));
  52766. g.saveState();
  52767. if (isScrollbarVertical)
  52768. g.reduceClipRegion (x + width / 2, y, width, height);
  52769. else
  52770. g.reduceClipRegion (x, y + height / 2, width, height);
  52771. g.fillPath (thumbPath);
  52772. g.restoreState();
  52773. g.setColour (Colour (0x4c000000));
  52774. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52775. }
  52776. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52777. {
  52778. return 0;
  52779. }
  52780. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52781. {
  52782. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52783. }
  52784. int LookAndFeel::getDefaultScrollbarWidth()
  52785. {
  52786. return 18;
  52787. }
  52788. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52789. {
  52790. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52791. : scrollbar.getHeight());
  52792. }
  52793. const Path LookAndFeel::getTickShape (const float height)
  52794. {
  52795. static const unsigned char tickShapeData[] =
  52796. {
  52797. 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,
  52798. 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,
  52799. 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,
  52800. 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,
  52801. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52802. };
  52803. Path p;
  52804. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52805. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52806. return p;
  52807. }
  52808. const Path LookAndFeel::getCrossShape (const float height)
  52809. {
  52810. static const unsigned char crossShapeData[] =
  52811. {
  52812. 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,
  52813. 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,
  52814. 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,
  52815. 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,
  52816. 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,
  52817. 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,
  52818. 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
  52819. };
  52820. Path p;
  52821. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52822. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52823. return p;
  52824. }
  52825. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52826. {
  52827. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  52828. x += (w - boxSize) >> 1;
  52829. y += (h - boxSize) >> 1;
  52830. w = boxSize;
  52831. h = boxSize;
  52832. g.setColour (Colour (0xe5ffffff));
  52833. g.fillRect (x, y, w, h);
  52834. g.setColour (Colour (0x80000000));
  52835. g.drawRect (x, y, w, h);
  52836. const float size = boxSize / 2 + 1.0f;
  52837. const float centre = (float) (boxSize / 2);
  52838. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  52839. if (isPlus)
  52840. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  52841. }
  52842. void LookAndFeel::drawBubble (Graphics& g,
  52843. float tipX, float tipY,
  52844. float boxX, float boxY,
  52845. float boxW, float boxH)
  52846. {
  52847. int side = 0;
  52848. if (tipX < boxX)
  52849. side = 1;
  52850. else if (tipX > boxX + boxW)
  52851. side = 3;
  52852. else if (tipY > boxY + boxH)
  52853. side = 2;
  52854. const float indent = 2.0f;
  52855. Path p;
  52856. p.addBubble (boxX + indent,
  52857. boxY + indent,
  52858. boxW - indent * 2.0f,
  52859. boxH - indent * 2.0f,
  52860. 5.0f,
  52861. tipX, tipY,
  52862. side,
  52863. 0.5f,
  52864. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  52865. //xxx need to take comp as param for colour
  52866. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  52867. g.fillPath (p);
  52868. //xxx as above
  52869. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  52870. g.strokePath (p, PathStrokeType (1.33f));
  52871. }
  52872. const Font LookAndFeel::getPopupMenuFont()
  52873. {
  52874. return Font (17.0f);
  52875. }
  52876. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  52877. const bool isSeparator,
  52878. int standardMenuItemHeight,
  52879. int& idealWidth,
  52880. int& idealHeight)
  52881. {
  52882. if (isSeparator)
  52883. {
  52884. idealWidth = 50;
  52885. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  52886. }
  52887. else
  52888. {
  52889. Font font (getPopupMenuFont());
  52890. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  52891. font.setHeight (standardMenuItemHeight / 1.3f);
  52892. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  52893. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  52894. }
  52895. }
  52896. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  52897. {
  52898. const Colour background (findColour (PopupMenu::backgroundColourId));
  52899. g.fillAll (background);
  52900. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  52901. for (int i = 0; i < height; i += 3)
  52902. g.fillRect (0, i, width, 1);
  52903. #if ! JUCE_MAC
  52904. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  52905. g.drawRect (0, 0, width, height);
  52906. #endif
  52907. }
  52908. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  52909. int width, int height,
  52910. bool isScrollUpArrow)
  52911. {
  52912. const Colour background (findColour (PopupMenu::backgroundColourId));
  52913. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  52914. background.withAlpha (0.0f),
  52915. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  52916. false));
  52917. g.fillRect (1, 1, width - 2, height - 2);
  52918. const float hw = width * 0.5f;
  52919. const float arrowW = height * 0.3f;
  52920. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  52921. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  52922. Path p;
  52923. p.addTriangle (hw - arrowW, y1,
  52924. hw + arrowW, y1,
  52925. hw, y2);
  52926. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  52927. g.fillPath (p);
  52928. }
  52929. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  52930. int width, int height,
  52931. const bool isSeparator,
  52932. const bool isActive,
  52933. const bool isHighlighted,
  52934. const bool isTicked,
  52935. const bool hasSubMenu,
  52936. const String& text,
  52937. const String& shortcutKeyText,
  52938. Image* image,
  52939. const Colour* const textColourToUse)
  52940. {
  52941. const float halfH = height * 0.5f;
  52942. if (isSeparator)
  52943. {
  52944. const float separatorIndent = 5.5f;
  52945. g.setColour (Colour (0x33000000));
  52946. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  52947. g.setColour (Colour (0x66ffffff));
  52948. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  52949. }
  52950. else
  52951. {
  52952. Colour textColour (findColour (PopupMenu::textColourId));
  52953. if (textColourToUse != 0)
  52954. textColour = *textColourToUse;
  52955. if (isHighlighted)
  52956. {
  52957. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  52958. g.fillRect (1, 1, width - 2, height - 2);
  52959. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  52960. }
  52961. else
  52962. {
  52963. g.setColour (textColour);
  52964. }
  52965. if (! isActive)
  52966. g.setOpacity (0.3f);
  52967. Font font (getPopupMenuFont());
  52968. if (font.getHeight() > height / 1.3f)
  52969. font.setHeight (height / 1.3f);
  52970. g.setFont (font);
  52971. const int leftBorder = (height * 5) / 4;
  52972. const int rightBorder = 4;
  52973. if (image != 0)
  52974. {
  52975. g.drawImageWithin (*image,
  52976. 2, 1, leftBorder - 4, height - 2,
  52977. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  52978. }
  52979. else if (isTicked)
  52980. {
  52981. const Path tick (getTickShape (1.0f));
  52982. const float th = font.getAscent();
  52983. const float ty = halfH - th * 0.5f;
  52984. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  52985. th, true));
  52986. }
  52987. g.drawFittedText (text,
  52988. leftBorder, 0,
  52989. width - (leftBorder + rightBorder), height,
  52990. Justification::centredLeft, 1);
  52991. if (shortcutKeyText.isNotEmpty())
  52992. {
  52993. Font f2 (font);
  52994. f2.setHeight (f2.getHeight() * 0.75f);
  52995. f2.setHorizontalScale (0.95f);
  52996. g.setFont (f2);
  52997. g.drawText (shortcutKeyText,
  52998. leftBorder,
  52999. 0,
  53000. width - (leftBorder + rightBorder + 4),
  53001. height,
  53002. Justification::centredRight,
  53003. true);
  53004. }
  53005. if (hasSubMenu)
  53006. {
  53007. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53008. const float x = width - height * 0.6f;
  53009. Path p;
  53010. p.addTriangle (x, halfH - arrowH * 0.5f,
  53011. x, halfH + arrowH * 0.5f,
  53012. x + arrowH * 0.6f, halfH);
  53013. g.fillPath (p);
  53014. }
  53015. }
  53016. }
  53017. int LookAndFeel::getMenuWindowFlags()
  53018. {
  53019. return ComponentPeer::windowHasDropShadow;
  53020. }
  53021. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53022. bool, MenuBarComponent& menuBar)
  53023. {
  53024. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53025. if (menuBar.isEnabled())
  53026. {
  53027. drawShinyButtonShape (g,
  53028. -4.0f, 0.0f,
  53029. width + 8.0f, (float) height,
  53030. 0.0f,
  53031. baseColour,
  53032. 0.4f,
  53033. true, true, true, true);
  53034. }
  53035. else
  53036. {
  53037. g.fillAll (baseColour);
  53038. }
  53039. }
  53040. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53041. {
  53042. return Font (menuBar.getHeight() * 0.7f);
  53043. }
  53044. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53045. {
  53046. return getMenuBarFont (menuBar, itemIndex, itemText)
  53047. .getStringWidth (itemText) + menuBar.getHeight();
  53048. }
  53049. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53050. int width, int height,
  53051. int itemIndex,
  53052. const String& itemText,
  53053. bool isMouseOverItem,
  53054. bool isMenuOpen,
  53055. bool /*isMouseOverBar*/,
  53056. MenuBarComponent& menuBar)
  53057. {
  53058. if (! menuBar.isEnabled())
  53059. {
  53060. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53061. .withMultipliedAlpha (0.5f));
  53062. }
  53063. else if (isMenuOpen || isMouseOverItem)
  53064. {
  53065. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53066. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53067. }
  53068. else
  53069. {
  53070. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53071. }
  53072. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53073. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53074. }
  53075. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53076. TextEditor& textEditor)
  53077. {
  53078. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53079. }
  53080. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53081. {
  53082. if (textEditor.isEnabled())
  53083. {
  53084. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53085. {
  53086. const int border = 2;
  53087. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53088. g.drawRect (0, 0, width, height, border);
  53089. g.setOpacity (1.0f);
  53090. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53091. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53092. }
  53093. else
  53094. {
  53095. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53096. g.drawRect (0, 0, width, height);
  53097. g.setOpacity (1.0f);
  53098. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53099. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53100. }
  53101. }
  53102. }
  53103. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53104. const bool isButtonDown,
  53105. int buttonX, int buttonY,
  53106. int buttonW, int buttonH,
  53107. ComboBox& box)
  53108. {
  53109. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53110. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53111. {
  53112. g.setColour (box.findColour (TextButton::buttonColourId));
  53113. g.drawRect (0, 0, width, height, 2);
  53114. }
  53115. else
  53116. {
  53117. g.setColour (box.findColour (ComboBox::outlineColourId));
  53118. g.drawRect (0, 0, width, height);
  53119. }
  53120. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53121. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53122. box.hasKeyboardFocus (true),
  53123. false, isButtonDown)
  53124. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53125. drawGlassLozenge (g,
  53126. buttonX + outlineThickness, buttonY + outlineThickness,
  53127. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53128. baseColour, outlineThickness, -1.0f,
  53129. true, true, true, true);
  53130. if (box.isEnabled())
  53131. {
  53132. const float arrowX = 0.3f;
  53133. const float arrowH = 0.2f;
  53134. Path p;
  53135. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53136. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53137. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53138. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53139. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53140. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53141. g.setColour (box.findColour (ComboBox::arrowColourId));
  53142. g.fillPath (p);
  53143. }
  53144. }
  53145. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53146. {
  53147. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53148. }
  53149. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53150. {
  53151. return new Label (String::empty, String::empty);
  53152. }
  53153. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53154. {
  53155. label.setBounds (1, 1,
  53156. box.getWidth() + 3 - box.getHeight(),
  53157. box.getHeight() - 2);
  53158. label.setFont (getComboBoxFont (box));
  53159. }
  53160. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53161. {
  53162. g.fillAll (label.findColour (Label::backgroundColourId));
  53163. if (! label.isBeingEdited())
  53164. {
  53165. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53166. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53167. g.setFont (label.getFont());
  53168. g.drawFittedText (label.getText(),
  53169. label.getHorizontalBorderSize(),
  53170. label.getVerticalBorderSize(),
  53171. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53172. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53173. label.getJustificationType(),
  53174. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53175. label.getMinimumHorizontalScale());
  53176. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53177. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53178. }
  53179. else if (label.isEnabled())
  53180. {
  53181. g.setColour (label.findColour (Label::outlineColourId));
  53182. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53183. }
  53184. }
  53185. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53186. int x, int y,
  53187. int width, int height,
  53188. float /*sliderPos*/,
  53189. float /*minSliderPos*/,
  53190. float /*maxSliderPos*/,
  53191. const Slider::SliderStyle /*style*/,
  53192. Slider& slider)
  53193. {
  53194. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53195. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53196. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53197. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53198. Path indent;
  53199. if (slider.isHorizontal())
  53200. {
  53201. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53202. const float ih = sliderRadius;
  53203. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53204. gradCol2, 0.0f, iy + ih, false));
  53205. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53206. width + sliderRadius, ih,
  53207. 5.0f);
  53208. g.fillPath (indent);
  53209. }
  53210. else
  53211. {
  53212. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53213. const float iw = sliderRadius;
  53214. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53215. gradCol2, ix + iw, 0.0f, false));
  53216. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53217. iw, height + sliderRadius,
  53218. 5.0f);
  53219. g.fillPath (indent);
  53220. }
  53221. g.setColour (Colour (0x4c000000));
  53222. g.strokePath (indent, PathStrokeType (0.5f));
  53223. }
  53224. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53225. int x, int y,
  53226. int width, int height,
  53227. float sliderPos,
  53228. float minSliderPos,
  53229. float maxSliderPos,
  53230. const Slider::SliderStyle style,
  53231. Slider& slider)
  53232. {
  53233. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53234. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53235. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53236. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53237. slider.isMouseButtonDown() && slider.isEnabled()));
  53238. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53239. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53240. {
  53241. float kx, ky;
  53242. if (style == Slider::LinearVertical)
  53243. {
  53244. kx = x + width * 0.5f;
  53245. ky = sliderPos;
  53246. }
  53247. else
  53248. {
  53249. kx = sliderPos;
  53250. ky = y + height * 0.5f;
  53251. }
  53252. drawGlassSphere (g,
  53253. kx - sliderRadius,
  53254. ky - sliderRadius,
  53255. sliderRadius * 2.0f,
  53256. knobColour, outlineThickness);
  53257. }
  53258. else
  53259. {
  53260. if (style == Slider::ThreeValueVertical)
  53261. {
  53262. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53263. sliderPos - sliderRadius,
  53264. sliderRadius * 2.0f,
  53265. knobColour, outlineThickness);
  53266. }
  53267. else if (style == Slider::ThreeValueHorizontal)
  53268. {
  53269. drawGlassSphere (g,sliderPos - sliderRadius,
  53270. y + height * 0.5f - sliderRadius,
  53271. sliderRadius * 2.0f,
  53272. knobColour, outlineThickness);
  53273. }
  53274. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53275. {
  53276. const float sr = jmin (sliderRadius, width * 0.4f);
  53277. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53278. minSliderPos - sliderRadius,
  53279. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53280. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53281. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53282. }
  53283. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53284. {
  53285. const float sr = jmin (sliderRadius, height * 0.4f);
  53286. drawGlassPointer (g, minSliderPos - sr,
  53287. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53288. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53289. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53290. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53291. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53292. }
  53293. }
  53294. }
  53295. void LookAndFeel::drawLinearSlider (Graphics& g,
  53296. int x, int y,
  53297. int width, int height,
  53298. float sliderPos,
  53299. float minSliderPos,
  53300. float maxSliderPos,
  53301. const Slider::SliderStyle style,
  53302. Slider& slider)
  53303. {
  53304. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53305. if (style == Slider::LinearBar)
  53306. {
  53307. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53308. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53309. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53310. false, isMouseOver,
  53311. isMouseOver || slider.isMouseButtonDown()));
  53312. drawShinyButtonShape (g,
  53313. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53314. baseColour,
  53315. slider.isEnabled() ? 0.9f : 0.3f,
  53316. true, true, true, true);
  53317. }
  53318. else
  53319. {
  53320. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53321. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53322. }
  53323. }
  53324. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53325. {
  53326. return jmin (7,
  53327. slider.getHeight() / 2,
  53328. slider.getWidth() / 2) + 2;
  53329. }
  53330. void LookAndFeel::drawRotarySlider (Graphics& g,
  53331. int x, int y,
  53332. int width, int height,
  53333. float sliderPos,
  53334. const float rotaryStartAngle,
  53335. const float rotaryEndAngle,
  53336. Slider& slider)
  53337. {
  53338. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53339. const float centreX = x + width * 0.5f;
  53340. const float centreY = y + height * 0.5f;
  53341. const float rx = centreX - radius;
  53342. const float ry = centreY - radius;
  53343. const float rw = radius * 2.0f;
  53344. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53345. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53346. if (radius > 12.0f)
  53347. {
  53348. if (slider.isEnabled())
  53349. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53350. else
  53351. g.setColour (Colour (0x80808080));
  53352. const float thickness = 0.7f;
  53353. {
  53354. Path filledArc;
  53355. filledArc.addPieSegment (rx, ry, rw, rw,
  53356. rotaryStartAngle,
  53357. angle,
  53358. thickness);
  53359. g.fillPath (filledArc);
  53360. }
  53361. if (thickness > 0)
  53362. {
  53363. const float innerRadius = radius * 0.2f;
  53364. Path p;
  53365. p.addTriangle (-innerRadius, 0.0f,
  53366. 0.0f, -radius * thickness * 1.1f,
  53367. innerRadius, 0.0f);
  53368. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53369. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53370. }
  53371. if (slider.isEnabled())
  53372. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53373. else
  53374. g.setColour (Colour (0x80808080));
  53375. Path outlineArc;
  53376. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53377. outlineArc.closeSubPath();
  53378. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53379. }
  53380. else
  53381. {
  53382. if (slider.isEnabled())
  53383. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53384. else
  53385. g.setColour (Colour (0x80808080));
  53386. Path p;
  53387. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53388. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53389. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53390. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53391. }
  53392. }
  53393. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53394. {
  53395. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53396. }
  53397. class SliderLabelComp : public Label
  53398. {
  53399. public:
  53400. SliderLabelComp() : Label (String::empty, String::empty) {}
  53401. ~SliderLabelComp() {}
  53402. void mouseWheelMove (const MouseEvent&, float, float) {}
  53403. };
  53404. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53405. {
  53406. Label* const l = new SliderLabelComp();
  53407. l->setJustificationType (Justification::centred);
  53408. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53409. l->setColour (Label::backgroundColourId,
  53410. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53411. : slider.findColour (Slider::textBoxBackgroundColourId));
  53412. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53413. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53414. l->setColour (TextEditor::backgroundColourId,
  53415. slider.findColour (Slider::textBoxBackgroundColourId)
  53416. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53417. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53418. return l;
  53419. }
  53420. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53421. {
  53422. return 0;
  53423. }
  53424. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53425. {
  53426. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53427. width = tl.getWidth() + 14;
  53428. height = tl.getHeight() + 6;
  53429. }
  53430. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53431. {
  53432. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53433. const Colour textCol (findColour (TooltipWindow::textColourId));
  53434. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53435. g.setColour (findColour (TooltipWindow::outlineColourId));
  53436. g.drawRect (0, 0, width, height, 1);
  53437. #endif
  53438. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53439. g.setColour (findColour (TooltipWindow::textColourId));
  53440. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53441. }
  53442. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53443. {
  53444. return new TextButton (text, TRANS("click to browse for a different file"));
  53445. }
  53446. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53447. ComboBox* filenameBox,
  53448. Button* browseButton)
  53449. {
  53450. browseButton->setSize (80, filenameComp.getHeight());
  53451. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53452. if (tb != 0)
  53453. tb->changeWidthToFitText();
  53454. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53455. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53456. }
  53457. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53458. int imageX, int imageY, int imageW, int imageH,
  53459. const Colour& overlayColour,
  53460. float imageOpacity,
  53461. ImageButton& button)
  53462. {
  53463. if (! button.isEnabled())
  53464. imageOpacity *= 0.3f;
  53465. if (! overlayColour.isOpaque())
  53466. {
  53467. g.setOpacity (imageOpacity);
  53468. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53469. 0, 0, image->getWidth(), image->getHeight(), false);
  53470. }
  53471. if (! overlayColour.isTransparent())
  53472. {
  53473. g.setColour (overlayColour);
  53474. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53475. 0, 0, image->getWidth(), image->getHeight(), true);
  53476. }
  53477. }
  53478. void LookAndFeel::drawCornerResizer (Graphics& g,
  53479. int w, int h,
  53480. bool /*isMouseOver*/,
  53481. bool /*isMouseDragging*/)
  53482. {
  53483. const float lineThickness = jmin (w, h) * 0.075f;
  53484. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53485. {
  53486. g.setColour (Colours::lightgrey);
  53487. g.drawLine (w * i,
  53488. h + 1.0f,
  53489. w + 1.0f,
  53490. h * i,
  53491. lineThickness);
  53492. g.setColour (Colours::darkgrey);
  53493. g.drawLine (w * i + lineThickness,
  53494. h + 1.0f,
  53495. w + 1.0f,
  53496. h * i + lineThickness,
  53497. lineThickness);
  53498. }
  53499. }
  53500. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize<int>& border)
  53501. {
  53502. if (! border.isEmpty())
  53503. {
  53504. const Rectangle<int> fullSize (0, 0, w, h);
  53505. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53506. g.saveState();
  53507. g.excludeClipRegion (centreArea);
  53508. g.setColour (Colour (0x50000000));
  53509. g.drawRect (fullSize);
  53510. g.setColour (Colour (0x19000000));
  53511. g.drawRect (centreArea.expanded (1, 1));
  53512. g.restoreState();
  53513. }
  53514. }
  53515. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53516. const BorderSize<int>& /*border*/, ResizableWindow& window)
  53517. {
  53518. g.fillAll (window.getBackgroundColour());
  53519. }
  53520. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53521. const BorderSize<int>& /*border*/, ResizableWindow&)
  53522. {
  53523. }
  53524. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53525. Graphics& g, int w, int h,
  53526. int titleSpaceX, int titleSpaceW,
  53527. const Image* icon,
  53528. bool drawTitleTextOnLeft)
  53529. {
  53530. const bool isActive = window.isActiveWindow();
  53531. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53532. 0.0f, 0.0f,
  53533. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53534. 0.0f, (float) h, false));
  53535. g.fillAll();
  53536. Font font (h * 0.65f, Font::bold);
  53537. g.setFont (font);
  53538. int textW = font.getStringWidth (window.getName());
  53539. int iconW = 0;
  53540. int iconH = 0;
  53541. if (icon != 0)
  53542. {
  53543. iconH = (int) font.getHeight();
  53544. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53545. }
  53546. textW = jmin (titleSpaceW, textW + iconW);
  53547. int textX = drawTitleTextOnLeft ? titleSpaceX
  53548. : jmax (titleSpaceX, (w - textW) / 2);
  53549. if (textX + textW > titleSpaceX + titleSpaceW)
  53550. textX = titleSpaceX + titleSpaceW - textW;
  53551. if (icon != 0)
  53552. {
  53553. g.setOpacity (isActive ? 1.0f : 0.6f);
  53554. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53555. RectanglePlacement::centred, false);
  53556. textX += iconW;
  53557. textW -= iconW;
  53558. }
  53559. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53560. g.setColour (findColour (DocumentWindow::textColourId));
  53561. else
  53562. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53563. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53564. }
  53565. class GlassWindowButton : public Button
  53566. {
  53567. public:
  53568. GlassWindowButton (const String& name, const Colour& col,
  53569. const Path& normalShape_,
  53570. const Path& toggledShape_) throw()
  53571. : Button (name),
  53572. colour (col),
  53573. normalShape (normalShape_),
  53574. toggledShape (toggledShape_)
  53575. {
  53576. }
  53577. ~GlassWindowButton()
  53578. {
  53579. }
  53580. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53581. {
  53582. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53583. if (! isEnabled())
  53584. alpha *= 0.5f;
  53585. float x = 0, y = 0, diam;
  53586. if (getWidth() < getHeight())
  53587. {
  53588. diam = (float) getWidth();
  53589. y = (getHeight() - getWidth()) * 0.5f;
  53590. }
  53591. else
  53592. {
  53593. diam = (float) getHeight();
  53594. y = (getWidth() - getHeight()) * 0.5f;
  53595. }
  53596. x += diam * 0.05f;
  53597. y += diam * 0.05f;
  53598. diam *= 0.9f;
  53599. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53600. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53601. g.fillEllipse (x, y, diam, diam);
  53602. x += 2.0f;
  53603. y += 2.0f;
  53604. diam -= 4.0f;
  53605. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53606. Path& p = getToggleState() ? toggledShape : normalShape;
  53607. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53608. diam * 0.4f, diam * 0.4f, true));
  53609. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53610. g.fillPath (p, t);
  53611. }
  53612. private:
  53613. Colour colour;
  53614. Path normalShape, toggledShape;
  53615. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlassWindowButton);
  53616. };
  53617. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53618. {
  53619. Path shape;
  53620. const float crossThickness = 0.25f;
  53621. if (buttonType == DocumentWindow::closeButton)
  53622. {
  53623. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53624. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53625. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53626. }
  53627. else if (buttonType == DocumentWindow::minimiseButton)
  53628. {
  53629. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53630. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53631. }
  53632. else if (buttonType == DocumentWindow::maximiseButton)
  53633. {
  53634. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53635. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53636. Path fullscreenShape;
  53637. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53638. fullscreenShape.lineTo (0.0f, 100.0f);
  53639. fullscreenShape.lineTo (0.0f, 0.0f);
  53640. fullscreenShape.lineTo (100.0f, 0.0f);
  53641. fullscreenShape.lineTo (100.0f, 45.0f);
  53642. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53643. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53644. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53645. }
  53646. jassertfalse;
  53647. return 0;
  53648. }
  53649. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53650. int titleBarX,
  53651. int titleBarY,
  53652. int titleBarW,
  53653. int titleBarH,
  53654. Button* minimiseButton,
  53655. Button* maximiseButton,
  53656. Button* closeButton,
  53657. bool positionTitleBarButtonsOnLeft)
  53658. {
  53659. const int buttonW = titleBarH - titleBarH / 8;
  53660. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53661. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53662. if (closeButton != 0)
  53663. {
  53664. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53665. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53666. }
  53667. if (positionTitleBarButtonsOnLeft)
  53668. swapVariables (minimiseButton, maximiseButton);
  53669. if (maximiseButton != 0)
  53670. {
  53671. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53672. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53673. }
  53674. if (minimiseButton != 0)
  53675. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53676. }
  53677. int LookAndFeel::getDefaultMenuBarHeight()
  53678. {
  53679. return 24;
  53680. }
  53681. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53682. {
  53683. return new DropShadower (0.4f, 1, 5, 10);
  53684. }
  53685. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53686. int w, int h,
  53687. bool /*isVerticalBar*/,
  53688. bool isMouseOver,
  53689. bool isMouseDragging)
  53690. {
  53691. float alpha = 0.5f;
  53692. if (isMouseOver || isMouseDragging)
  53693. {
  53694. g.fillAll (Colour (0x190000ff));
  53695. alpha = 1.0f;
  53696. }
  53697. const float cx = w * 0.5f;
  53698. const float cy = h * 0.5f;
  53699. const float cr = jmin (w, h) * 0.4f;
  53700. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53701. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53702. true));
  53703. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53704. }
  53705. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53706. const String& text,
  53707. const Justification& position,
  53708. GroupComponent& group)
  53709. {
  53710. const float textH = 15.0f;
  53711. const float indent = 3.0f;
  53712. const float textEdgeGap = 4.0f;
  53713. float cs = 5.0f;
  53714. Font f (textH);
  53715. Path p;
  53716. float x = indent;
  53717. float y = f.getAscent() - 3.0f;
  53718. float w = jmax (0.0f, width - x * 2.0f);
  53719. float h = jmax (0.0f, height - y - indent);
  53720. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53721. const float cs2 = 2.0f * cs;
  53722. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53723. float textX = cs + textEdgeGap;
  53724. if (position.testFlags (Justification::horizontallyCentred))
  53725. textX = cs + (w - cs2 - textW) * 0.5f;
  53726. else if (position.testFlags (Justification::right))
  53727. textX = w - cs - textW - textEdgeGap;
  53728. p.startNewSubPath (x + textX + textW, y);
  53729. p.lineTo (x + w - cs, y);
  53730. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53731. p.lineTo (x + w, y + h - cs);
  53732. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53733. p.lineTo (x + cs, y + h);
  53734. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53735. p.lineTo (x, y + cs);
  53736. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53737. p.lineTo (x + textX, y);
  53738. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53739. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53740. .withMultipliedAlpha (alpha));
  53741. g.strokePath (p, PathStrokeType (2.0f));
  53742. g.setColour (group.findColour (GroupComponent::textColourId)
  53743. .withMultipliedAlpha (alpha));
  53744. g.setFont (f);
  53745. g.drawText (text,
  53746. roundToInt (x + textX), 0,
  53747. roundToInt (textW),
  53748. roundToInt (textH),
  53749. Justification::centred, true);
  53750. }
  53751. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53752. {
  53753. return 1 + tabDepth / 3;
  53754. }
  53755. int LookAndFeel::getTabButtonSpaceAroundImage()
  53756. {
  53757. return 4;
  53758. }
  53759. void LookAndFeel::createTabButtonShape (Path& p,
  53760. int width, int height,
  53761. int /*tabIndex*/,
  53762. const String& /*text*/,
  53763. Button& /*button*/,
  53764. TabbedButtonBar::Orientation orientation,
  53765. const bool /*isMouseOver*/,
  53766. const bool /*isMouseDown*/,
  53767. const bool /*isFrontTab*/)
  53768. {
  53769. const float w = (float) width;
  53770. const float h = (float) height;
  53771. float length = w;
  53772. float depth = h;
  53773. if (orientation == TabbedButtonBar::TabsAtLeft
  53774. || orientation == TabbedButtonBar::TabsAtRight)
  53775. {
  53776. swapVariables (length, depth);
  53777. }
  53778. const float indent = (float) getTabButtonOverlap ((int) depth);
  53779. const float overhang = 4.0f;
  53780. if (orientation == TabbedButtonBar::TabsAtLeft)
  53781. {
  53782. p.startNewSubPath (w, 0.0f);
  53783. p.lineTo (0.0f, indent);
  53784. p.lineTo (0.0f, h - indent);
  53785. p.lineTo (w, h);
  53786. p.lineTo (w + overhang, h + overhang);
  53787. p.lineTo (w + overhang, -overhang);
  53788. }
  53789. else if (orientation == TabbedButtonBar::TabsAtRight)
  53790. {
  53791. p.startNewSubPath (0.0f, 0.0f);
  53792. p.lineTo (w, indent);
  53793. p.lineTo (w, h - indent);
  53794. p.lineTo (0.0f, h);
  53795. p.lineTo (-overhang, h + overhang);
  53796. p.lineTo (-overhang, -overhang);
  53797. }
  53798. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53799. {
  53800. p.startNewSubPath (0.0f, 0.0f);
  53801. p.lineTo (indent, h);
  53802. p.lineTo (w - indent, h);
  53803. p.lineTo (w, 0.0f);
  53804. p.lineTo (w + overhang, -overhang);
  53805. p.lineTo (-overhang, -overhang);
  53806. }
  53807. else
  53808. {
  53809. p.startNewSubPath (0.0f, h);
  53810. p.lineTo (indent, 0.0f);
  53811. p.lineTo (w - indent, 0.0f);
  53812. p.lineTo (w, h);
  53813. p.lineTo (w + overhang, h + overhang);
  53814. p.lineTo (-overhang, h + overhang);
  53815. }
  53816. p.closeSubPath();
  53817. p = p.createPathWithRoundedCorners (3.0f);
  53818. }
  53819. void LookAndFeel::fillTabButtonShape (Graphics& g,
  53820. const Path& path,
  53821. const Colour& preferredColour,
  53822. int /*tabIndex*/,
  53823. const String& /*text*/,
  53824. Button& button,
  53825. TabbedButtonBar::Orientation /*orientation*/,
  53826. const bool /*isMouseOver*/,
  53827. const bool /*isMouseDown*/,
  53828. const bool isFrontTab)
  53829. {
  53830. g.setColour (isFrontTab ? preferredColour
  53831. : preferredColour.withMultipliedAlpha (0.9f));
  53832. g.fillPath (path);
  53833. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  53834. : TabbedButtonBar::tabOutlineColourId, false)
  53835. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  53836. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  53837. }
  53838. void LookAndFeel::drawTabButtonText (Graphics& g,
  53839. int x, int y, int w, int h,
  53840. const Colour& preferredBackgroundColour,
  53841. int /*tabIndex*/,
  53842. const String& text,
  53843. Button& button,
  53844. TabbedButtonBar::Orientation orientation,
  53845. const bool isMouseOver,
  53846. const bool isMouseDown,
  53847. const bool isFrontTab)
  53848. {
  53849. int length = w;
  53850. int depth = h;
  53851. if (orientation == TabbedButtonBar::TabsAtLeft
  53852. || orientation == TabbedButtonBar::TabsAtRight)
  53853. {
  53854. swapVariables (length, depth);
  53855. }
  53856. Font font (depth * 0.6f);
  53857. font.setUnderline (button.hasKeyboardFocus (false));
  53858. GlyphArrangement textLayout;
  53859. textLayout.addFittedText (font, text.trim(),
  53860. 0.0f, 0.0f, (float) length, (float) depth,
  53861. Justification::centred,
  53862. jmax (1, depth / 12));
  53863. AffineTransform transform;
  53864. if (orientation == TabbedButtonBar::TabsAtLeft)
  53865. {
  53866. transform = transform.rotated (float_Pi * -0.5f)
  53867. .translated ((float) x, (float) (y + h));
  53868. }
  53869. else if (orientation == TabbedButtonBar::TabsAtRight)
  53870. {
  53871. transform = transform.rotated (float_Pi * 0.5f)
  53872. .translated ((float) (x + w), (float) y);
  53873. }
  53874. else
  53875. {
  53876. transform = transform.translated ((float) x, (float) y);
  53877. }
  53878. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  53879. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  53880. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  53881. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  53882. else
  53883. g.setColour (preferredBackgroundColour.contrasting());
  53884. if (! (isMouseOver || isMouseDown))
  53885. g.setOpacity (0.8f);
  53886. if (! button.isEnabled())
  53887. g.setOpacity (0.3f);
  53888. textLayout.draw (g, transform);
  53889. }
  53890. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  53891. const String& text,
  53892. int tabDepth,
  53893. Button&)
  53894. {
  53895. Font f (tabDepth * 0.6f);
  53896. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  53897. }
  53898. void LookAndFeel::drawTabButton (Graphics& g,
  53899. int w, int h,
  53900. const Colour& preferredColour,
  53901. int tabIndex,
  53902. const String& text,
  53903. Button& button,
  53904. TabbedButtonBar::Orientation orientation,
  53905. const bool isMouseOver,
  53906. const bool isMouseDown,
  53907. const bool isFrontTab)
  53908. {
  53909. int length = w;
  53910. int depth = h;
  53911. if (orientation == TabbedButtonBar::TabsAtLeft
  53912. || orientation == TabbedButtonBar::TabsAtRight)
  53913. {
  53914. swapVariables (length, depth);
  53915. }
  53916. Path tabShape;
  53917. createTabButtonShape (tabShape, w, h,
  53918. tabIndex, text, button, orientation,
  53919. isMouseOver, isMouseDown, isFrontTab);
  53920. fillTabButtonShape (g, tabShape, preferredColour,
  53921. tabIndex, text, button, orientation,
  53922. isMouseOver, isMouseDown, isFrontTab);
  53923. const int indent = getTabButtonOverlap (depth);
  53924. int x = 0, y = 0;
  53925. if (orientation == TabbedButtonBar::TabsAtLeft
  53926. || orientation == TabbedButtonBar::TabsAtRight)
  53927. {
  53928. y += indent;
  53929. h -= indent * 2;
  53930. }
  53931. else
  53932. {
  53933. x += indent;
  53934. w -= indent * 2;
  53935. }
  53936. drawTabButtonText (g, x, y, w, h, preferredColour,
  53937. tabIndex, text, button, orientation,
  53938. isMouseOver, isMouseDown, isFrontTab);
  53939. }
  53940. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  53941. int w, int h,
  53942. TabbedButtonBar& tabBar,
  53943. TabbedButtonBar::Orientation orientation)
  53944. {
  53945. const float shadowSize = 0.2f;
  53946. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53947. Rectangle<int> shadowRect;
  53948. if (orientation == TabbedButtonBar::TabsAtLeft)
  53949. {
  53950. x1 = (float) w;
  53951. x2 = w * (1.0f - shadowSize);
  53952. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  53953. }
  53954. else if (orientation == TabbedButtonBar::TabsAtRight)
  53955. {
  53956. x2 = w * shadowSize;
  53957. shadowRect.setBounds (0, 0, (int) x2, h);
  53958. }
  53959. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53960. {
  53961. y2 = h * shadowSize;
  53962. shadowRect.setBounds (0, 0, w, (int) y2);
  53963. }
  53964. else
  53965. {
  53966. y1 = (float) h;
  53967. y2 = h * (1.0f - shadowSize);
  53968. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  53969. }
  53970. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  53971. Colours::transparentBlack, x2, y2, false));
  53972. shadowRect.expand (2, 2);
  53973. g.fillRect (shadowRect);
  53974. g.setColour (Colour (0x80000000));
  53975. if (orientation == TabbedButtonBar::TabsAtLeft)
  53976. {
  53977. g.fillRect (w - 1, 0, 1, h);
  53978. }
  53979. else if (orientation == TabbedButtonBar::TabsAtRight)
  53980. {
  53981. g.fillRect (0, 0, 1, h);
  53982. }
  53983. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53984. {
  53985. g.fillRect (0, 0, w, 1);
  53986. }
  53987. else
  53988. {
  53989. g.fillRect (0, h - 1, w, 1);
  53990. }
  53991. }
  53992. Button* LookAndFeel::createTabBarExtrasButton()
  53993. {
  53994. const float thickness = 7.0f;
  53995. const float indent = 22.0f;
  53996. Path p;
  53997. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  53998. DrawablePath ellipse;
  53999. ellipse.setPath (p);
  54000. ellipse.setFill (Colour (0x99ffffff));
  54001. p.clear();
  54002. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54003. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54004. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54005. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54006. p.setUsingNonZeroWinding (false);
  54007. DrawablePath dp;
  54008. dp.setPath (p);
  54009. dp.setFill (Colour (0x59000000));
  54010. DrawableComposite normalImage;
  54011. normalImage.addAndMakeVisible (ellipse.createCopy());
  54012. normalImage.addAndMakeVisible (dp.createCopy());
  54013. dp.setFill (Colour (0xcc000000));
  54014. DrawableComposite overImage;
  54015. overImage.addAndMakeVisible (ellipse.createCopy());
  54016. overImage.addAndMakeVisible (dp.createCopy());
  54017. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54018. db->setImages (&normalImage, &overImage, 0);
  54019. return db;
  54020. }
  54021. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54022. {
  54023. g.fillAll (Colours::white);
  54024. const int w = header.getWidth();
  54025. const int h = header.getHeight();
  54026. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54027. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54028. false));
  54029. g.fillRect (0, h / 2, w, h);
  54030. g.setColour (Colour (0x33000000));
  54031. g.fillRect (0, h - 1, w, 1);
  54032. for (int i = header.getNumColumns (true); --i >= 0;)
  54033. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54034. }
  54035. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54036. int width, int height,
  54037. bool isMouseOver, bool isMouseDown,
  54038. int columnFlags)
  54039. {
  54040. if (isMouseDown)
  54041. g.fillAll (Colour (0x8899aadd));
  54042. else if (isMouseOver)
  54043. g.fillAll (Colour (0x5599aadd));
  54044. int rightOfText = width - 4;
  54045. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54046. {
  54047. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54048. const float bottom = height - top;
  54049. const float w = height * 0.5f;
  54050. const float x = rightOfText - (w * 1.25f);
  54051. rightOfText = (int) x;
  54052. Path sortArrow;
  54053. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54054. g.setColour (Colour (0x99000000));
  54055. g.fillPath (sortArrow);
  54056. }
  54057. g.setColour (Colours::black);
  54058. g.setFont (height * 0.5f, Font::bold);
  54059. const int textX = 4;
  54060. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54061. }
  54062. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54063. {
  54064. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54065. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54066. background.darker (0.1f),
  54067. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54068. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54069. false));
  54070. g.fillAll();
  54071. }
  54072. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54073. {
  54074. return createTabBarExtrasButton();
  54075. }
  54076. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54077. bool isMouseOver, bool isMouseDown,
  54078. ToolbarItemComponent& component)
  54079. {
  54080. if (isMouseDown)
  54081. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54082. else if (isMouseOver)
  54083. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54084. }
  54085. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54086. const String& text, ToolbarItemComponent& component)
  54087. {
  54088. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54089. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54090. const float fontHeight = jmin (14.0f, height * 0.85f);
  54091. g.setFont (fontHeight);
  54092. g.drawFittedText (text,
  54093. x, y, width, height,
  54094. Justification::centred,
  54095. jmax (1, height / (int) fontHeight));
  54096. }
  54097. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54098. bool isOpen, int width, int height)
  54099. {
  54100. const int buttonSize = (height * 3) / 4;
  54101. const int buttonIndent = (height - buttonSize) / 2;
  54102. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54103. const int textX = buttonIndent * 2 + buttonSize + 2;
  54104. g.setColour (Colours::black);
  54105. g.setFont (height * 0.7f, Font::bold);
  54106. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54107. }
  54108. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54109. PropertyComponent&)
  54110. {
  54111. g.setColour (Colour (0x66ffffff));
  54112. g.fillRect (0, 0, width, height - 1);
  54113. }
  54114. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54115. PropertyComponent& component)
  54116. {
  54117. g.setColour (Colours::black);
  54118. if (! component.isEnabled())
  54119. g.setOpacity (0.6f);
  54120. g.setFont (jmin (height, 24) * 0.65f);
  54121. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54122. g.drawFittedText (component.getName(),
  54123. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54124. Justification::centredLeft, 2);
  54125. }
  54126. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54127. {
  54128. return Rectangle<int> (component.getWidth() / 3, 1,
  54129. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54130. }
  54131. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54132. {
  54133. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54134. {
  54135. Graphics g2 (content);
  54136. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54137. g2.fillPath (path);
  54138. g2.setColour (Colours::white.withAlpha (0.8f));
  54139. g2.strokePath (path, PathStrokeType (2.0f));
  54140. }
  54141. DropShadowEffect shadow;
  54142. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54143. shadow.applyEffect (content, g, 1.0f);
  54144. }
  54145. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54146. const String& instructions,
  54147. GlyphArrangement& text,
  54148. int width)
  54149. {
  54150. text.clear();
  54151. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54152. 8.0f, 22.0f, width - 16.0f,
  54153. Justification::centred);
  54154. text.addJustifiedText (Font (14.0f), instructions,
  54155. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54156. Justification::centred);
  54157. }
  54158. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54159. const String& filename, Image* icon,
  54160. const String& fileSizeDescription,
  54161. const String& fileTimeDescription,
  54162. const bool isDirectory,
  54163. const bool isItemSelected,
  54164. const int /*itemIndex*/,
  54165. DirectoryContentsDisplayComponent&)
  54166. {
  54167. if (isItemSelected)
  54168. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54169. const int x = 32;
  54170. g.setColour (Colours::black);
  54171. if (icon != 0 && icon->isValid())
  54172. {
  54173. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54174. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54175. false);
  54176. }
  54177. else
  54178. {
  54179. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54180. : getDefaultDocumentFileImage();
  54181. if (d != 0)
  54182. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54183. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54184. }
  54185. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54186. g.setFont (height * 0.7f);
  54187. if (width > 450 && ! isDirectory)
  54188. {
  54189. const int sizeX = roundToInt (width * 0.7f);
  54190. const int dateX = roundToInt (width * 0.8f);
  54191. g.drawFittedText (filename,
  54192. x, 0, sizeX - x, height,
  54193. Justification::centredLeft, 1);
  54194. g.setFont (height * 0.5f);
  54195. g.setColour (Colours::darkgrey);
  54196. if (! isDirectory)
  54197. {
  54198. g.drawFittedText (fileSizeDescription,
  54199. sizeX, 0, dateX - sizeX - 8, height,
  54200. Justification::centredRight, 1);
  54201. g.drawFittedText (fileTimeDescription,
  54202. dateX, 0, width - 8 - dateX, height,
  54203. Justification::centredRight, 1);
  54204. }
  54205. }
  54206. else
  54207. {
  54208. g.drawFittedText (filename,
  54209. x, 0, width - x, height,
  54210. Justification::centredLeft, 1);
  54211. }
  54212. }
  54213. Button* LookAndFeel::createFileBrowserGoUpButton()
  54214. {
  54215. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54216. Path arrowPath;
  54217. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54218. DrawablePath arrowImage;
  54219. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54220. arrowImage.setPath (arrowPath);
  54221. goUpButton->setImages (&arrowImage);
  54222. return goUpButton;
  54223. }
  54224. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54225. DirectoryContentsDisplayComponent* fileListComponent,
  54226. FilePreviewComponent* previewComp,
  54227. ComboBox* currentPathBox,
  54228. TextEditor* filenameBox,
  54229. Button* goUpButton)
  54230. {
  54231. const int x = 8;
  54232. int w = browserComp.getWidth() - x - x;
  54233. if (previewComp != 0)
  54234. {
  54235. const int previewWidth = w / 3;
  54236. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54237. w -= previewWidth + 4;
  54238. }
  54239. int y = 4;
  54240. const int controlsHeight = 22;
  54241. const int bottomSectionHeight = controlsHeight + 8;
  54242. const int upButtonWidth = 50;
  54243. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54244. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54245. y += controlsHeight + 4;
  54246. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54247. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54248. y = listAsComp->getBottom() + 4;
  54249. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54250. }
  54251. // Pulls a drawable out of compressed valuetree data..
  54252. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54253. {
  54254. MemoryInputStream m (data, numBytes, false);
  54255. GZIPDecompressorInputStream gz (m);
  54256. ValueTree drawable (ValueTree::readFromStream (gz));
  54257. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54258. }
  54259. const Drawable* LookAndFeel::getDefaultFolderImage()
  54260. {
  54261. if (folderImage == 0)
  54262. {
  54263. static const unsigned char drawableData[] =
  54264. { 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,
  54265. 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,
  54266. 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,
  54267. 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,
  54268. 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,
  54269. 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,
  54270. 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,
  54271. 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,
  54272. 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,
  54273. 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,
  54274. 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,
  54275. 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,
  54276. 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,
  54277. 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,
  54278. 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 };
  54279. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54280. }
  54281. return folderImage;
  54282. }
  54283. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54284. {
  54285. if (documentImage == 0)
  54286. {
  54287. static const unsigned char drawableData[] =
  54288. { 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,
  54289. 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,
  54290. 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,
  54291. 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,
  54292. 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,
  54293. 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,
  54294. 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,
  54295. 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,
  54296. 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,
  54297. 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,
  54298. 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,
  54299. 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,
  54300. 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,
  54301. 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,
  54302. 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,
  54303. 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,
  54304. 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,
  54305. 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,
  54306. 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,
  54307. 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,
  54308. 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,
  54309. 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,
  54310. 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 };
  54311. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54312. }
  54313. return documentImage;
  54314. }
  54315. void LookAndFeel::playAlertSound()
  54316. {
  54317. PlatformUtilities::beep();
  54318. }
  54319. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54320. {
  54321. g.setColour (Colours::white.withAlpha (0.7f));
  54322. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54323. g.setColour (Colours::black.withAlpha (0.2f));
  54324. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54325. const int totalBlocks = 7;
  54326. const int numBlocks = roundToInt (totalBlocks * level);
  54327. const float w = (width - 6.0f) / (float) totalBlocks;
  54328. for (int i = 0; i < totalBlocks; ++i)
  54329. {
  54330. if (i >= numBlocks)
  54331. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54332. else
  54333. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54334. : Colours::red);
  54335. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54336. }
  54337. }
  54338. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54339. {
  54340. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54341. if (keyDescription.isNotEmpty())
  54342. {
  54343. if (button.isEnabled())
  54344. {
  54345. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54346. g.fillAll (textColour.withAlpha (alpha));
  54347. g.setOpacity (0.3f);
  54348. g.drawBevel (0, 0, width, height, 2);
  54349. }
  54350. g.setColour (textColour);
  54351. g.setFont (height * 0.6f);
  54352. g.drawFittedText (keyDescription,
  54353. 3, 0, width - 6, height,
  54354. Justification::centred, 1);
  54355. }
  54356. else
  54357. {
  54358. const float thickness = 7.0f;
  54359. const float indent = 22.0f;
  54360. Path p;
  54361. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54362. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54363. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54364. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54365. p.setUsingNonZeroWinding (false);
  54366. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54367. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54368. }
  54369. if (button.hasKeyboardFocus (false))
  54370. {
  54371. g.setColour (textColour.withAlpha (0.4f));
  54372. g.drawRect (0, 0, width, height);
  54373. }
  54374. }
  54375. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54376. float x, float y, float w, float h,
  54377. float maxCornerSize,
  54378. const Colour& baseColour,
  54379. const float strokeWidth,
  54380. const bool flatOnLeft,
  54381. const bool flatOnRight,
  54382. const bool flatOnTop,
  54383. const bool flatOnBottom) throw()
  54384. {
  54385. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54386. return;
  54387. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54388. Path outline;
  54389. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54390. ! (flatOnLeft || flatOnTop),
  54391. ! (flatOnRight || flatOnTop),
  54392. ! (flatOnLeft || flatOnBottom),
  54393. ! (flatOnRight || flatOnBottom));
  54394. ColourGradient cg (baseColour, 0.0f, y,
  54395. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54396. false);
  54397. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54398. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54399. g.setGradientFill (cg);
  54400. g.fillPath (outline);
  54401. g.setColour (Colour (0x80000000));
  54402. g.strokePath (outline, PathStrokeType (strokeWidth));
  54403. }
  54404. void LookAndFeel::drawGlassSphere (Graphics& g,
  54405. const float x, const float y,
  54406. const float diameter,
  54407. const Colour& colour,
  54408. const float outlineThickness) throw()
  54409. {
  54410. if (diameter <= outlineThickness)
  54411. return;
  54412. Path p;
  54413. p.addEllipse (x, y, diameter, diameter);
  54414. {
  54415. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54416. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54417. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54418. g.setGradientFill (cg);
  54419. g.fillPath (p);
  54420. }
  54421. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54422. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54423. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54424. ColourGradient cg (Colours::transparentBlack,
  54425. x + diameter * 0.5f, y + diameter * 0.5f,
  54426. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54427. x, y + diameter * 0.5f, true);
  54428. cg.addColour (0.7, Colours::transparentBlack);
  54429. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54430. g.setGradientFill (cg);
  54431. g.fillPath (p);
  54432. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54433. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54434. }
  54435. void LookAndFeel::drawGlassPointer (Graphics& g,
  54436. const float x, const float y,
  54437. const float diameter,
  54438. const Colour& colour, const float outlineThickness,
  54439. const int direction) throw()
  54440. {
  54441. if (diameter <= outlineThickness)
  54442. return;
  54443. Path p;
  54444. p.startNewSubPath (x + diameter * 0.5f, y);
  54445. p.lineTo (x + diameter, y + diameter * 0.6f);
  54446. p.lineTo (x + diameter, y + diameter);
  54447. p.lineTo (x, y + diameter);
  54448. p.lineTo (x, y + diameter * 0.6f);
  54449. p.closeSubPath();
  54450. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54451. {
  54452. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54453. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54454. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54455. g.setGradientFill (cg);
  54456. g.fillPath (p);
  54457. }
  54458. ColourGradient cg (Colours::transparentBlack,
  54459. x + diameter * 0.5f, y + diameter * 0.5f,
  54460. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54461. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54462. cg.addColour (0.5, Colours::transparentBlack);
  54463. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54464. g.setGradientFill (cg);
  54465. g.fillPath (p);
  54466. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54467. g.strokePath (p, PathStrokeType (outlineThickness));
  54468. }
  54469. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54470. const float x, const float y,
  54471. const float width, const float height,
  54472. const Colour& colour,
  54473. const float outlineThickness,
  54474. const float cornerSize,
  54475. const bool flatOnLeft,
  54476. const bool flatOnRight,
  54477. const bool flatOnTop,
  54478. const bool flatOnBottom) throw()
  54479. {
  54480. if (width <= outlineThickness || height <= outlineThickness)
  54481. return;
  54482. const int intX = (int) x;
  54483. const int intY = (int) y;
  54484. const int intW = (int) width;
  54485. const int intH = (int) height;
  54486. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54487. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54488. const int intEdge = (int) edgeBlurRadius;
  54489. Path outline;
  54490. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54491. ! (flatOnLeft || flatOnTop),
  54492. ! (flatOnRight || flatOnTop),
  54493. ! (flatOnLeft || flatOnBottom),
  54494. ! (flatOnRight || flatOnBottom));
  54495. {
  54496. ColourGradient cg (colour.darker (0.2f), 0, y,
  54497. colour.darker (0.2f), 0, y + height, false);
  54498. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54499. cg.addColour (0.4, colour);
  54500. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54501. g.setGradientFill (cg);
  54502. g.fillPath (outline);
  54503. }
  54504. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54505. colour.darker (0.2f), x, y + height * 0.5f, true);
  54506. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54507. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54508. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54509. {
  54510. g.saveState();
  54511. g.setGradientFill (cg);
  54512. g.reduceClipRegion (intX, intY, intEdge, intH);
  54513. g.fillPath (outline);
  54514. g.restoreState();
  54515. }
  54516. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54517. {
  54518. cg.point1.setX (x + width - edgeBlurRadius);
  54519. cg.point2.setX (x + width);
  54520. g.saveState();
  54521. g.setGradientFill (cg);
  54522. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54523. g.fillPath (outline);
  54524. g.restoreState();
  54525. }
  54526. {
  54527. const float leftIndent = flatOnTop || flatOnLeft ? 0.0f : cs * 0.4f;
  54528. const float rightIndent = flatOnTop || flatOnRight ? 0.0f : cs * 0.4f;
  54529. Path highlight;
  54530. LookAndFeelHelpers::createRoundedPath (highlight,
  54531. x + leftIndent,
  54532. y + cs * 0.1f,
  54533. width - (leftIndent + rightIndent),
  54534. height * 0.4f, cs * 0.4f,
  54535. ! (flatOnLeft || flatOnTop),
  54536. ! (flatOnRight || flatOnTop),
  54537. ! (flatOnLeft || flatOnBottom),
  54538. ! (flatOnRight || flatOnBottom));
  54539. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54540. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54541. g.fillPath (highlight);
  54542. }
  54543. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54544. g.strokePath (outline, PathStrokeType (outlineThickness));
  54545. }
  54546. END_JUCE_NAMESPACE
  54547. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54548. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54549. BEGIN_JUCE_NAMESPACE
  54550. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54551. {
  54552. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54553. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54554. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54555. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54556. setColour (Slider::thumbColourId, Colours::white);
  54557. setColour (Slider::trackColourId, Colour (0x7f000000));
  54558. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54559. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54560. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54561. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54562. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54563. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54564. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54565. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54566. }
  54567. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54568. {
  54569. }
  54570. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54571. Button& button,
  54572. const Colour& backgroundColour,
  54573. bool isMouseOverButton,
  54574. bool isButtonDown)
  54575. {
  54576. const int width = button.getWidth();
  54577. const int height = button.getHeight();
  54578. const float indent = 2.0f;
  54579. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54580. roundToInt (height * 0.4f));
  54581. Path p;
  54582. p.addRoundedRectangle (indent, indent,
  54583. width - indent * 2.0f,
  54584. height - indent * 2.0f,
  54585. (float) cornerSize);
  54586. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54587. if (isMouseOverButton)
  54588. {
  54589. if (isButtonDown)
  54590. bc = bc.brighter();
  54591. else if (bc.getBrightness() > 0.5f)
  54592. bc = bc.darker (0.1f);
  54593. else
  54594. bc = bc.brighter (0.1f);
  54595. }
  54596. g.setColour (bc);
  54597. g.fillPath (p);
  54598. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54599. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54600. }
  54601. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54602. Component& /*component*/,
  54603. float x, float y, float w, float h,
  54604. const bool ticked,
  54605. const bool isEnabled,
  54606. const bool /*isMouseOverButton*/,
  54607. const bool isButtonDown)
  54608. {
  54609. Path box;
  54610. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54611. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54612. : Colours::lightgrey.withAlpha (0.1f));
  54613. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54614. g.fillPath (box, trans);
  54615. g.setColour (Colours::black.withAlpha (0.6f));
  54616. g.strokePath (box, PathStrokeType (0.9f), trans);
  54617. if (ticked)
  54618. {
  54619. Path tick;
  54620. tick.startNewSubPath (1.5f, 3.0f);
  54621. tick.lineTo (3.0f, 6.0f);
  54622. tick.lineTo (6.0f, 0.0f);
  54623. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54624. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54625. }
  54626. }
  54627. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54628. ToggleButton& button,
  54629. bool isMouseOverButton,
  54630. bool isButtonDown)
  54631. {
  54632. if (button.hasKeyboardFocus (true))
  54633. {
  54634. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54635. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54636. }
  54637. const int tickWidth = jmin (20, button.getHeight() - 4);
  54638. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54639. (float) tickWidth, (float) tickWidth,
  54640. button.getToggleState(),
  54641. button.isEnabled(),
  54642. isMouseOverButton,
  54643. isButtonDown);
  54644. g.setColour (button.findColour (ToggleButton::textColourId));
  54645. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54646. if (! button.isEnabled())
  54647. g.setOpacity (0.5f);
  54648. const int textX = tickWidth + 5;
  54649. g.drawFittedText (button.getButtonText(),
  54650. textX, 4,
  54651. button.getWidth() - textX - 2, button.getHeight() - 8,
  54652. Justification::centredLeft, 10);
  54653. }
  54654. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54655. int width, int height,
  54656. double progress, const String& textToShow)
  54657. {
  54658. if (progress < 0 || progress >= 1.0)
  54659. {
  54660. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54661. }
  54662. else
  54663. {
  54664. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54665. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54666. g.fillAll (background);
  54667. g.setColour (foreground);
  54668. g.fillRect (1, 1,
  54669. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54670. height - 2);
  54671. if (textToShow.isNotEmpty())
  54672. {
  54673. g.setColour (Colour::contrasting (background, foreground));
  54674. g.setFont (height * 0.6f);
  54675. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54676. }
  54677. }
  54678. }
  54679. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54680. ScrollBar& bar,
  54681. int width, int height,
  54682. int buttonDirection,
  54683. bool isScrollbarVertical,
  54684. bool isMouseOverButton,
  54685. bool isButtonDown)
  54686. {
  54687. if (isScrollbarVertical)
  54688. width -= 2;
  54689. else
  54690. height -= 2;
  54691. Path p;
  54692. if (buttonDirection == 0)
  54693. p.addTriangle (width * 0.5f, height * 0.2f,
  54694. width * 0.1f, height * 0.7f,
  54695. width * 0.9f, height * 0.7f);
  54696. else if (buttonDirection == 1)
  54697. p.addTriangle (width * 0.8f, height * 0.5f,
  54698. width * 0.3f, height * 0.1f,
  54699. width * 0.3f, height * 0.9f);
  54700. else if (buttonDirection == 2)
  54701. p.addTriangle (width * 0.5f, height * 0.8f,
  54702. width * 0.1f, height * 0.3f,
  54703. width * 0.9f, height * 0.3f);
  54704. else if (buttonDirection == 3)
  54705. p.addTriangle (width * 0.2f, height * 0.5f,
  54706. width * 0.7f, height * 0.1f,
  54707. width * 0.7f, height * 0.9f);
  54708. if (isButtonDown)
  54709. g.setColour (Colours::white);
  54710. else if (isMouseOverButton)
  54711. g.setColour (Colours::white.withAlpha (0.7f));
  54712. else
  54713. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54714. g.fillPath (p);
  54715. g.setColour (Colours::black.withAlpha (0.5f));
  54716. g.strokePath (p, PathStrokeType (0.5f));
  54717. }
  54718. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54719. ScrollBar& bar,
  54720. int x, int y,
  54721. int width, int height,
  54722. bool isScrollbarVertical,
  54723. int thumbStartPosition,
  54724. int thumbSize,
  54725. bool isMouseOver,
  54726. bool isMouseDown)
  54727. {
  54728. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54729. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54730. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54731. if (thumbSize > 0.0f)
  54732. {
  54733. Rectangle<int> thumb;
  54734. if (isScrollbarVertical)
  54735. {
  54736. width -= 2;
  54737. g.fillRect (x + roundToInt (width * 0.35f), y,
  54738. roundToInt (width * 0.3f), height);
  54739. thumb.setBounds (x + 1, thumbStartPosition,
  54740. width - 2, thumbSize);
  54741. }
  54742. else
  54743. {
  54744. height -= 2;
  54745. g.fillRect (x, y + roundToInt (height * 0.35f),
  54746. width, roundToInt (height * 0.3f));
  54747. thumb.setBounds (thumbStartPosition, y + 1,
  54748. thumbSize, height - 2);
  54749. }
  54750. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54751. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54752. g.fillRect (thumb);
  54753. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54754. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54755. if (thumbSize > 16)
  54756. {
  54757. for (int i = 3; --i >= 0;)
  54758. {
  54759. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54760. g.setColour (Colours::black.withAlpha (0.15f));
  54761. if (isScrollbarVertical)
  54762. {
  54763. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  54764. g.setColour (Colours::white.withAlpha (0.15f));
  54765. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  54766. }
  54767. else
  54768. {
  54769. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  54770. g.setColour (Colours::white.withAlpha (0.15f));
  54771. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  54772. }
  54773. }
  54774. }
  54775. }
  54776. }
  54777. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  54778. {
  54779. return &scrollbarShadow;
  54780. }
  54781. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  54782. {
  54783. g.fillAll (findColour (PopupMenu::backgroundColourId));
  54784. g.setColour (Colours::black.withAlpha (0.6f));
  54785. g.drawRect (0, 0, width, height);
  54786. }
  54787. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  54788. bool, MenuBarComponent& menuBar)
  54789. {
  54790. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  54791. }
  54792. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  54793. {
  54794. if (textEditor.isEnabled())
  54795. {
  54796. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  54797. g.drawRect (0, 0, width, height);
  54798. }
  54799. }
  54800. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  54801. const bool isButtonDown,
  54802. int buttonX, int buttonY,
  54803. int buttonW, int buttonH,
  54804. ComboBox& box)
  54805. {
  54806. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  54807. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  54808. : ComboBox::backgroundColourId));
  54809. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  54810. g.setColour (box.findColour (ComboBox::outlineColourId));
  54811. g.drawRect (0, 0, width, height);
  54812. const float arrowX = 0.2f;
  54813. const float arrowH = 0.3f;
  54814. if (box.isEnabled())
  54815. {
  54816. Path p;
  54817. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  54818. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  54819. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  54820. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  54821. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  54822. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  54823. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  54824. : ComboBox::buttonColourId));
  54825. g.fillPath (p);
  54826. }
  54827. }
  54828. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  54829. {
  54830. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  54831. f.setHorizontalScale (0.9f);
  54832. return f;
  54833. }
  54834. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  54835. {
  54836. Path p;
  54837. p.addTriangle (x1, y1, x2, y2, x3, y3);
  54838. g.setColour (fill);
  54839. g.fillPath (p);
  54840. g.setColour (outline);
  54841. g.strokePath (p, PathStrokeType (0.3f));
  54842. }
  54843. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  54844. int x, int y,
  54845. int w, int h,
  54846. float sliderPos,
  54847. float minSliderPos,
  54848. float maxSliderPos,
  54849. const Slider::SliderStyle style,
  54850. Slider& slider)
  54851. {
  54852. g.fillAll (slider.findColour (Slider::backgroundColourId));
  54853. if (style == Slider::LinearBar)
  54854. {
  54855. g.setColour (slider.findColour (Slider::thumbColourId));
  54856. g.fillRect (x, y, (int) sliderPos - x, h);
  54857. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  54858. g.drawRect (x, y, (int) sliderPos - x, h);
  54859. }
  54860. else
  54861. {
  54862. g.setColour (slider.findColour (Slider::trackColourId)
  54863. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  54864. if (slider.isHorizontal())
  54865. {
  54866. g.fillRect (x, y + roundToInt (h * 0.6f),
  54867. w, roundToInt (h * 0.2f));
  54868. }
  54869. else
  54870. {
  54871. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  54872. jmin (4, roundToInt (w * 0.2f)), h);
  54873. }
  54874. float alpha = 0.35f;
  54875. if (slider.isEnabled())
  54876. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  54877. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  54878. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  54879. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  54880. {
  54881. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  54882. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  54883. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  54884. fill, outline);
  54885. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  54886. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  54887. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  54888. fill, outline);
  54889. }
  54890. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  54891. {
  54892. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54893. minSliderPos - 7.0f, y + h * 0.9f ,
  54894. minSliderPos, y + h * 0.9f,
  54895. fill, outline);
  54896. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  54897. maxSliderPos, y + h * 0.9f,
  54898. maxSliderPos + 7.0f, y + h * 0.9f,
  54899. fill, outline);
  54900. }
  54901. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  54902. {
  54903. drawTriangle (g, sliderPos, y + h * 0.9f,
  54904. sliderPos - 7.0f, y + h * 0.2f,
  54905. sliderPos + 7.0f, y + h * 0.2f,
  54906. fill, outline);
  54907. }
  54908. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  54909. {
  54910. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  54911. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  54912. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  54913. fill, outline);
  54914. }
  54915. }
  54916. }
  54917. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  54918. {
  54919. if (isIncrement)
  54920. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  54921. else
  54922. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  54923. }
  54924. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  54925. {
  54926. return &scrollbarShadow;
  54927. }
  54928. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  54929. {
  54930. return 8;
  54931. }
  54932. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  54933. int w, int h,
  54934. bool isMouseOver,
  54935. bool isMouseDragging)
  54936. {
  54937. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  54938. : Colours::darkgrey);
  54939. const float lineThickness = jmin (w, h) * 0.1f;
  54940. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  54941. {
  54942. g.drawLine (w * i,
  54943. h + 1.0f,
  54944. w + 1.0f,
  54945. h * i,
  54946. lineThickness);
  54947. }
  54948. }
  54949. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  54950. {
  54951. Path shape;
  54952. if (buttonType == DocumentWindow::closeButton)
  54953. {
  54954. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  54955. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  54956. ShapeButton* const b = new ShapeButton ("close",
  54957. Colour (0x7fff3333),
  54958. Colour (0xd7ff3333),
  54959. Colour (0xf7ff3333));
  54960. b->setShape (shape, true, true, true);
  54961. return b;
  54962. }
  54963. else if (buttonType == DocumentWindow::minimiseButton)
  54964. {
  54965. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54966. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  54967. DrawablePath dp;
  54968. dp.setPath (shape);
  54969. dp.setFill (Colours::black.withAlpha (0.3f));
  54970. b->setImages (&dp);
  54971. return b;
  54972. }
  54973. else if (buttonType == DocumentWindow::maximiseButton)
  54974. {
  54975. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  54976. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  54977. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  54978. DrawablePath dp;
  54979. dp.setPath (shape);
  54980. dp.setFill (Colours::black.withAlpha (0.3f));
  54981. b->setImages (&dp);
  54982. return b;
  54983. }
  54984. jassertfalse;
  54985. return 0;
  54986. }
  54987. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54988. int titleBarX,
  54989. int titleBarY,
  54990. int titleBarW,
  54991. int titleBarH,
  54992. Button* minimiseButton,
  54993. Button* maximiseButton,
  54994. Button* closeButton,
  54995. bool positionTitleBarButtonsOnLeft)
  54996. {
  54997. titleBarY += titleBarH / 8;
  54998. titleBarH -= titleBarH / 4;
  54999. const int buttonW = titleBarH;
  55000. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55001. : titleBarX + titleBarW - buttonW - 4;
  55002. if (closeButton != 0)
  55003. {
  55004. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55005. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55006. : -(buttonW + buttonW / 5);
  55007. }
  55008. if (positionTitleBarButtonsOnLeft)
  55009. swapVariables (minimiseButton, maximiseButton);
  55010. if (maximiseButton != 0)
  55011. {
  55012. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55013. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55014. }
  55015. if (minimiseButton != 0)
  55016. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55017. }
  55018. END_JUCE_NAMESPACE
  55019. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55020. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55021. BEGIN_JUCE_NAMESPACE
  55022. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55023. : model (0),
  55024. itemUnderMouse (-1),
  55025. currentPopupIndex (-1),
  55026. topLevelIndexClicked (0),
  55027. lastMouseX (0),
  55028. lastMouseY (0)
  55029. {
  55030. setRepaintsOnMouseActivity (true);
  55031. setWantsKeyboardFocus (false);
  55032. setMouseClickGrabsKeyboardFocus (false);
  55033. setModel (model_);
  55034. }
  55035. MenuBarComponent::~MenuBarComponent()
  55036. {
  55037. setModel (0);
  55038. Desktop::getInstance().removeGlobalMouseListener (this);
  55039. }
  55040. MenuBarModel* MenuBarComponent::getModel() const throw()
  55041. {
  55042. return model;
  55043. }
  55044. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55045. {
  55046. if (model != newModel)
  55047. {
  55048. if (model != 0)
  55049. model->removeListener (this);
  55050. model = newModel;
  55051. if (model != 0)
  55052. model->addListener (this);
  55053. repaint();
  55054. menuBarItemsChanged (0);
  55055. }
  55056. }
  55057. void MenuBarComponent::paint (Graphics& g)
  55058. {
  55059. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55060. getLookAndFeel().drawMenuBarBackground (g,
  55061. getWidth(),
  55062. getHeight(),
  55063. isMouseOverBar,
  55064. *this);
  55065. if (model != 0)
  55066. {
  55067. for (int i = 0; i < menuNames.size(); ++i)
  55068. {
  55069. Graphics::ScopedSaveState ss (g);
  55070. g.setOrigin (xPositions [i], 0);
  55071. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55072. getLookAndFeel().drawMenuBarItem (g,
  55073. xPositions[i + 1] - xPositions[i],
  55074. getHeight(),
  55075. i,
  55076. menuNames[i],
  55077. i == itemUnderMouse,
  55078. i == currentPopupIndex,
  55079. isMouseOverBar,
  55080. *this);
  55081. }
  55082. }
  55083. }
  55084. void MenuBarComponent::resized()
  55085. {
  55086. xPositions.clear();
  55087. int x = 0;
  55088. xPositions.add (x);
  55089. for (int i = 0; i < menuNames.size(); ++i)
  55090. {
  55091. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55092. xPositions.add (x);
  55093. }
  55094. }
  55095. int MenuBarComponent::getItemAt (const int x, const int y)
  55096. {
  55097. for (int i = 0; i < xPositions.size(); ++i)
  55098. if (x >= xPositions[i] && x < xPositions[i + 1])
  55099. return reallyContains (Point<int> (x, y), true) ? i : -1;
  55100. return -1;
  55101. }
  55102. void MenuBarComponent::repaintMenuItem (int index)
  55103. {
  55104. if (isPositiveAndBelow (index, xPositions.size()))
  55105. {
  55106. const int x1 = xPositions [index];
  55107. const int x2 = xPositions [index + 1];
  55108. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55109. }
  55110. }
  55111. void MenuBarComponent::setItemUnderMouse (const int index)
  55112. {
  55113. if (itemUnderMouse != index)
  55114. {
  55115. repaintMenuItem (itemUnderMouse);
  55116. itemUnderMouse = index;
  55117. repaintMenuItem (itemUnderMouse);
  55118. }
  55119. }
  55120. void MenuBarComponent::setOpenItem (int index)
  55121. {
  55122. if (currentPopupIndex != index)
  55123. {
  55124. repaintMenuItem (currentPopupIndex);
  55125. currentPopupIndex = index;
  55126. repaintMenuItem (currentPopupIndex);
  55127. if (index >= 0)
  55128. Desktop::getInstance().addGlobalMouseListener (this);
  55129. else
  55130. Desktop::getInstance().removeGlobalMouseListener (this);
  55131. }
  55132. }
  55133. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55134. {
  55135. setItemUnderMouse (getItemAt (x, y));
  55136. }
  55137. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55138. {
  55139. public:
  55140. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55141. : bar (bar_), topLevelIndex (topLevelIndex_)
  55142. {
  55143. }
  55144. void modalStateFinished (int returnValue)
  55145. {
  55146. if (bar != 0)
  55147. bar->menuDismissed (topLevelIndex, returnValue);
  55148. }
  55149. private:
  55150. Component::SafePointer<MenuBarComponent> bar;
  55151. const int topLevelIndex;
  55152. JUCE_DECLARE_NON_COPYABLE (AsyncCallback);
  55153. };
  55154. void MenuBarComponent::showMenu (int index)
  55155. {
  55156. if (index != currentPopupIndex)
  55157. {
  55158. PopupMenu::dismissAllActiveMenus();
  55159. menuBarItemsChanged (0);
  55160. setOpenItem (index);
  55161. setItemUnderMouse (index);
  55162. if (index >= 0)
  55163. {
  55164. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55165. menuNames [itemUnderMouse]));
  55166. if (m.lookAndFeel == 0)
  55167. m.setLookAndFeel (&getLookAndFeel());
  55168. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55169. m.showMenu (localAreaToGlobal (itemPos),
  55170. 0, itemPos.getWidth(), 0, 0, this,
  55171. new AsyncCallback (this, index));
  55172. }
  55173. }
  55174. }
  55175. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55176. {
  55177. topLevelIndexClicked = topLevelIndex;
  55178. postCommandMessage (itemId);
  55179. }
  55180. void MenuBarComponent::handleCommandMessage (int commandId)
  55181. {
  55182. const Point<int> mousePos (getMouseXYRelative());
  55183. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55184. if (currentPopupIndex == topLevelIndexClicked)
  55185. setOpenItem (-1);
  55186. if (commandId != 0 && model != 0)
  55187. model->menuItemSelected (commandId, topLevelIndexClicked);
  55188. }
  55189. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55190. {
  55191. if (e.eventComponent == this)
  55192. updateItemUnderMouse (e.x, e.y);
  55193. }
  55194. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55195. {
  55196. if (e.eventComponent == this)
  55197. updateItemUnderMouse (e.x, e.y);
  55198. }
  55199. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55200. {
  55201. if (currentPopupIndex < 0)
  55202. {
  55203. const MouseEvent e2 (e.getEventRelativeTo (this));
  55204. updateItemUnderMouse (e2.x, e2.y);
  55205. currentPopupIndex = -2;
  55206. showMenu (itemUnderMouse);
  55207. }
  55208. }
  55209. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55210. {
  55211. const MouseEvent e2 (e.getEventRelativeTo (this));
  55212. const int item = getItemAt (e2.x, e2.y);
  55213. if (item >= 0)
  55214. showMenu (item);
  55215. }
  55216. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55217. {
  55218. const MouseEvent e2 (e.getEventRelativeTo (this));
  55219. updateItemUnderMouse (e2.x, e2.y);
  55220. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55221. {
  55222. setOpenItem (-1);
  55223. PopupMenu::dismissAllActiveMenus();
  55224. }
  55225. }
  55226. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55227. {
  55228. const MouseEvent e2 (e.getEventRelativeTo (this));
  55229. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55230. {
  55231. if (currentPopupIndex >= 0)
  55232. {
  55233. const int item = getItemAt (e2.x, e2.y);
  55234. if (item >= 0)
  55235. showMenu (item);
  55236. }
  55237. else
  55238. {
  55239. updateItemUnderMouse (e2.x, e2.y);
  55240. }
  55241. lastMouseX = e2.x;
  55242. lastMouseY = e2.y;
  55243. }
  55244. }
  55245. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55246. {
  55247. bool used = false;
  55248. const int numMenus = menuNames.size();
  55249. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55250. if (key.isKeyCode (KeyPress::leftKey))
  55251. {
  55252. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55253. used = true;
  55254. }
  55255. else if (key.isKeyCode (KeyPress::rightKey))
  55256. {
  55257. showMenu ((currentIndex + 1) % numMenus);
  55258. used = true;
  55259. }
  55260. return used;
  55261. }
  55262. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55263. {
  55264. StringArray newNames;
  55265. if (model != 0)
  55266. newNames = model->getMenuBarNames();
  55267. if (newNames != menuNames)
  55268. {
  55269. menuNames = newNames;
  55270. repaint();
  55271. resized();
  55272. }
  55273. }
  55274. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55275. const ApplicationCommandTarget::InvocationInfo& info)
  55276. {
  55277. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55278. return;
  55279. for (int i = 0; i < menuNames.size(); ++i)
  55280. {
  55281. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55282. if (menu.containsCommandItem (info.commandID))
  55283. {
  55284. setItemUnderMouse (i);
  55285. startTimer (200);
  55286. break;
  55287. }
  55288. }
  55289. }
  55290. void MenuBarComponent::timerCallback()
  55291. {
  55292. stopTimer();
  55293. const Point<int> mousePos (getMouseXYRelative());
  55294. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55295. }
  55296. END_JUCE_NAMESPACE
  55297. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55298. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55299. BEGIN_JUCE_NAMESPACE
  55300. MenuBarModel::MenuBarModel() throw()
  55301. : manager (0)
  55302. {
  55303. }
  55304. MenuBarModel::~MenuBarModel()
  55305. {
  55306. setApplicationCommandManagerToWatch (0);
  55307. }
  55308. void MenuBarModel::menuItemsChanged()
  55309. {
  55310. triggerAsyncUpdate();
  55311. }
  55312. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55313. {
  55314. if (manager != newManager)
  55315. {
  55316. if (manager != 0)
  55317. manager->removeListener (this);
  55318. manager = newManager;
  55319. if (manager != 0)
  55320. manager->addListener (this);
  55321. }
  55322. }
  55323. void MenuBarModel::addListener (Listener* const newListener) throw()
  55324. {
  55325. listeners.add (newListener);
  55326. }
  55327. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55328. {
  55329. // Trying to remove a listener that isn't on the list!
  55330. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55331. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55332. jassert (listeners.contains (listenerToRemove));
  55333. listeners.remove (listenerToRemove);
  55334. }
  55335. void MenuBarModel::handleAsyncUpdate()
  55336. {
  55337. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55338. }
  55339. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55340. {
  55341. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55342. }
  55343. void MenuBarModel::applicationCommandListChanged()
  55344. {
  55345. menuItemsChanged();
  55346. }
  55347. END_JUCE_NAMESPACE
  55348. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55349. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55350. BEGIN_JUCE_NAMESPACE
  55351. class PopupMenu::Item
  55352. {
  55353. public:
  55354. Item()
  55355. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55356. usesColour (false), customComp (0), commandManager (0)
  55357. {
  55358. }
  55359. Item (const int itemId_,
  55360. const String& text_,
  55361. const bool active_,
  55362. const bool isTicked_,
  55363. const Image& im,
  55364. const Colour& textColour_,
  55365. const bool usesColour_,
  55366. CustomComponent* const customComp_,
  55367. const PopupMenu* const subMenu_,
  55368. ApplicationCommandManager* const commandManager_)
  55369. : itemId (itemId_), text (text_), textColour (textColour_),
  55370. active (active_), isSeparator (false), isTicked (isTicked_),
  55371. usesColour (usesColour_), image (im), customComp (customComp_),
  55372. commandManager (commandManager_)
  55373. {
  55374. if (subMenu_ != 0)
  55375. subMenu = new PopupMenu (*subMenu_);
  55376. if (commandManager_ != 0 && itemId_ != 0)
  55377. {
  55378. String shortcutKey;
  55379. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55380. ->getKeyPressesAssignedToCommand (itemId_));
  55381. for (int i = 0; i < keyPresses.size(); ++i)
  55382. {
  55383. const String key (keyPresses.getReference(i).getTextDescription());
  55384. if (shortcutKey.isNotEmpty())
  55385. shortcutKey << ", ";
  55386. if (key.length() == 1)
  55387. shortcutKey << "shortcut: '" << key << '\'';
  55388. else
  55389. shortcutKey << key;
  55390. }
  55391. shortcutKey = shortcutKey.trim();
  55392. if (shortcutKey.isNotEmpty())
  55393. text << "<end>" << shortcutKey;
  55394. }
  55395. }
  55396. Item (const Item& other)
  55397. : itemId (other.itemId),
  55398. text (other.text),
  55399. textColour (other.textColour),
  55400. active (other.active),
  55401. isSeparator (other.isSeparator),
  55402. isTicked (other.isTicked),
  55403. usesColour (other.usesColour),
  55404. image (other.image),
  55405. customComp (other.customComp),
  55406. commandManager (other.commandManager)
  55407. {
  55408. if (other.subMenu != 0)
  55409. subMenu = new PopupMenu (*(other.subMenu));
  55410. }
  55411. bool canBeTriggered() const throw() { return active && ! (isSeparator || (subMenu != 0)); }
  55412. bool hasActiveSubMenu() const throw() { return active && (subMenu != 0); }
  55413. const int itemId;
  55414. String text;
  55415. const Colour textColour;
  55416. const bool active, isSeparator, isTicked, usesColour;
  55417. Image image;
  55418. ReferenceCountedObjectPtr <CustomComponent> customComp;
  55419. ScopedPointer <PopupMenu> subMenu;
  55420. ApplicationCommandManager* const commandManager;
  55421. private:
  55422. Item& operator= (const Item&);
  55423. JUCE_LEAK_DETECTOR (Item);
  55424. };
  55425. class PopupMenu::ItemComponent : public Component
  55426. {
  55427. public:
  55428. ItemComponent (const PopupMenu::Item& itemInfo_, int standardItemHeight, Component* const parent)
  55429. : itemInfo (itemInfo_),
  55430. isHighlighted (false)
  55431. {
  55432. if (itemInfo.customComp != 0)
  55433. addAndMakeVisible (itemInfo.customComp);
  55434. parent->addAndMakeVisible (this);
  55435. int itemW = 80;
  55436. int itemH = 16;
  55437. getIdealSize (itemW, itemH, standardItemHeight);
  55438. setSize (itemW, jlimit (2, 600, itemH));
  55439. addMouseListener (parent, false);
  55440. }
  55441. ~ItemComponent()
  55442. {
  55443. if (itemInfo.customComp != 0)
  55444. removeChildComponent (itemInfo.customComp);
  55445. }
  55446. void getIdealSize (int& idealWidth, int& idealHeight, const int standardItemHeight)
  55447. {
  55448. if (itemInfo.customComp != 0)
  55449. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55450. else
  55451. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55452. itemInfo.isSeparator,
  55453. standardItemHeight,
  55454. idealWidth, idealHeight);
  55455. }
  55456. void paint (Graphics& g)
  55457. {
  55458. if (itemInfo.customComp == 0)
  55459. {
  55460. String mainText (itemInfo.text);
  55461. String endText;
  55462. const int endIndex = mainText.indexOf ("<end>");
  55463. if (endIndex >= 0)
  55464. {
  55465. endText = mainText.substring (endIndex + 5).trim();
  55466. mainText = mainText.substring (0, endIndex);
  55467. }
  55468. getLookAndFeel()
  55469. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55470. itemInfo.isSeparator,
  55471. itemInfo.active,
  55472. isHighlighted,
  55473. itemInfo.isTicked,
  55474. itemInfo.subMenu != 0,
  55475. mainText, endText,
  55476. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55477. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55478. }
  55479. }
  55480. void resized()
  55481. {
  55482. if (getNumChildComponents() > 0)
  55483. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55484. }
  55485. void setHighlighted (bool shouldBeHighlighted)
  55486. {
  55487. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55488. if (isHighlighted != shouldBeHighlighted)
  55489. {
  55490. isHighlighted = shouldBeHighlighted;
  55491. if (itemInfo.customComp != 0)
  55492. itemInfo.customComp->setHighlighted (shouldBeHighlighted);
  55493. repaint();
  55494. }
  55495. }
  55496. PopupMenu::Item itemInfo;
  55497. private:
  55498. bool isHighlighted;
  55499. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent);
  55500. };
  55501. namespace PopupMenuSettings
  55502. {
  55503. const int scrollZone = 24;
  55504. const int borderSize = 2;
  55505. const int timerInterval = 50;
  55506. const int dismissCommandId = 0x6287345f;
  55507. }
  55508. class PopupMenu::Window : public Component,
  55509. private Timer
  55510. {
  55511. public:
  55512. Window (const PopupMenu& menu, Window* const owner_, const Rectangle<int>& target,
  55513. const bool alignToRectangle, const int itemIdThatMustBeVisible,
  55514. const int minimumWidth_, const int maximumNumColumns_,
  55515. const int standardItemHeight_, const bool dismissOnMouseUp_,
  55516. ApplicationCommandManager** const managerOfChosenCommand_,
  55517. Component* const componentAttachedTo_)
  55518. : Component ("menu"),
  55519. owner (owner_),
  55520. activeSubMenu (0),
  55521. managerOfChosenCommand (managerOfChosenCommand_),
  55522. componentAttachedTo (componentAttachedTo_),
  55523. componentAttachedToOriginal (componentAttachedTo_),
  55524. minimumWidth (minimumWidth_),
  55525. maximumNumColumns (maximumNumColumns_),
  55526. standardItemHeight (standardItemHeight_),
  55527. isOver (false),
  55528. hasBeenOver (false),
  55529. isDown (false),
  55530. needsToScroll (false),
  55531. dismissOnMouseUp (dismissOnMouseUp_),
  55532. hideOnExit (false),
  55533. disableMouseMoves (false),
  55534. hasAnyJuceCompHadFocus (false),
  55535. numColumns (0),
  55536. contentHeight (0),
  55537. childYOffset (0),
  55538. menuCreationTime (Time::getMillisecondCounter()),
  55539. lastMouseMoveTime (0),
  55540. timeEnteredCurrentChildComp (0),
  55541. scrollAcceleration (1.0)
  55542. {
  55543. lastFocused = lastScroll = menuCreationTime;
  55544. setWantsKeyboardFocus (false);
  55545. setMouseClickGrabsKeyboardFocus (false);
  55546. setAlwaysOnTop (true);
  55547. setLookAndFeel (menu.lookAndFeel);
  55548. setOpaque (getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55549. for (int i = 0; i < menu.items.size(); ++i)
  55550. items.add (new PopupMenu::ItemComponent (*menu.items.getUnchecked(i), standardItemHeight, this));
  55551. calculateWindowPos (target, alignToRectangle);
  55552. setTopLeftPosition (windowPos.getX(), windowPos.getY());
  55553. updateYPositions();
  55554. if (itemIdThatMustBeVisible != 0)
  55555. {
  55556. const int y = target.getY() - windowPos.getY();
  55557. ensureItemIsVisible (itemIdThatMustBeVisible,
  55558. isPositiveAndBelow (y, windowPos.getHeight()) ? y : -1);
  55559. }
  55560. resizeToBestWindowPos();
  55561. addToDesktop (ComponentPeer::windowIsTemporary | getLookAndFeel().getMenuWindowFlags());
  55562. getActiveWindows().add (this);
  55563. Desktop::getInstance().addGlobalMouseListener (this);
  55564. }
  55565. ~Window()
  55566. {
  55567. getActiveWindows().removeValue (this);
  55568. Desktop::getInstance().removeGlobalMouseListener (this);
  55569. activeSubMenu = 0;
  55570. items.clear();
  55571. }
  55572. static Window* create (const PopupMenu& menu,
  55573. bool dismissOnMouseUp,
  55574. Window* const owner_,
  55575. const Rectangle<int>& target,
  55576. int minimumWidth,
  55577. int maximumNumColumns,
  55578. int standardItemHeight,
  55579. bool alignToRectangle,
  55580. int itemIdThatMustBeVisible,
  55581. ApplicationCommandManager** managerOfChosenCommand,
  55582. Component* componentAttachedTo)
  55583. {
  55584. if (menu.items.size() > 0)
  55585. return new Window (menu, owner_, target, alignToRectangle, itemIdThatMustBeVisible,
  55586. minimumWidth, maximumNumColumns, standardItemHeight, dismissOnMouseUp,
  55587. managerOfChosenCommand, componentAttachedTo);
  55588. return 0;
  55589. }
  55590. void paint (Graphics& g)
  55591. {
  55592. if (isOpaque())
  55593. g.fillAll (Colours::white);
  55594. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55595. }
  55596. void paintOverChildren (Graphics& g)
  55597. {
  55598. if (isScrolling())
  55599. {
  55600. LookAndFeel& lf = getLookAndFeel();
  55601. if (isScrollZoneActive (false))
  55602. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55603. if (isScrollZoneActive (true))
  55604. {
  55605. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55606. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55607. }
  55608. }
  55609. }
  55610. bool isScrollZoneActive (bool bottomOne) const
  55611. {
  55612. return isScrolling()
  55613. && (bottomOne ? childYOffset < contentHeight - windowPos.getHeight()
  55614. : childYOffset > 0);
  55615. }
  55616. // hide this and all sub-comps
  55617. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  55618. {
  55619. if (isVisible())
  55620. {
  55621. activeSubMenu = 0;
  55622. currentChild = 0;
  55623. exitModalState (item != 0 ? item->itemId : 0);
  55624. if (makeInvisible)
  55625. setVisible (false);
  55626. if (item != 0
  55627. && item->commandManager != 0
  55628. && item->itemId != 0)
  55629. {
  55630. *managerOfChosenCommand = item->commandManager;
  55631. }
  55632. }
  55633. }
  55634. void dismissMenu (const PopupMenu::Item* const item)
  55635. {
  55636. if (owner != 0)
  55637. {
  55638. owner->dismissMenu (item);
  55639. }
  55640. else
  55641. {
  55642. if (item != 0)
  55643. {
  55644. // need a copy of this on the stack as the one passed in will get deleted during this call
  55645. const PopupMenu::Item mi (*item);
  55646. hide (&mi, false);
  55647. }
  55648. else
  55649. {
  55650. hide (0, false);
  55651. }
  55652. }
  55653. }
  55654. void mouseMove (const MouseEvent&) { timerCallback(); }
  55655. void mouseDown (const MouseEvent&) { timerCallback(); }
  55656. void mouseDrag (const MouseEvent&) { timerCallback(); }
  55657. void mouseUp (const MouseEvent&) { timerCallback(); }
  55658. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55659. {
  55660. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55661. lastMouse = Point<int> (-1, -1);
  55662. }
  55663. bool keyPressed (const KeyPress& key)
  55664. {
  55665. if (key.isKeyCode (KeyPress::downKey))
  55666. {
  55667. selectNextItem (1);
  55668. }
  55669. else if (key.isKeyCode (KeyPress::upKey))
  55670. {
  55671. selectNextItem (-1);
  55672. }
  55673. else if (key.isKeyCode (KeyPress::leftKey))
  55674. {
  55675. if (owner != 0)
  55676. {
  55677. Component::SafePointer<Window> parentWindow (owner);
  55678. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55679. hide (0, true);
  55680. if (parentWindow != 0)
  55681. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55682. disableTimerUntilMouseMoves();
  55683. }
  55684. else if (componentAttachedTo != 0)
  55685. {
  55686. componentAttachedTo->keyPressed (key);
  55687. }
  55688. }
  55689. else if (key.isKeyCode (KeyPress::rightKey))
  55690. {
  55691. disableTimerUntilMouseMoves();
  55692. if (showSubMenuFor (currentChild))
  55693. {
  55694. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55695. activeSubMenu->selectNextItem (1);
  55696. }
  55697. else if (componentAttachedTo != 0)
  55698. {
  55699. componentAttachedTo->keyPressed (key);
  55700. }
  55701. }
  55702. else if (key.isKeyCode (KeyPress::returnKey))
  55703. {
  55704. triggerCurrentlyHighlightedItem();
  55705. }
  55706. else if (key.isKeyCode (KeyPress::escapeKey))
  55707. {
  55708. dismissMenu (0);
  55709. }
  55710. else
  55711. {
  55712. return false;
  55713. }
  55714. return true;
  55715. }
  55716. void inputAttemptWhenModal()
  55717. {
  55718. WeakReference<Component> deletionChecker (this);
  55719. timerCallback();
  55720. if (deletionChecker != 0 && ! isOverAnyMenu())
  55721. {
  55722. if (componentAttachedTo != 0)
  55723. {
  55724. // we want to dismiss the menu, but if we do it synchronously, then
  55725. // the mouse-click will be allowed to pass through. That's good, except
  55726. // when the user clicks on the button that orginally popped the menu up,
  55727. // as they'll expect the menu to go away, and in fact it'll just
  55728. // come back. So only dismiss synchronously if they're not on the original
  55729. // comp that we're attached to.
  55730. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  55731. if (componentAttachedTo->reallyContains (mousePos, true))
  55732. {
  55733. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  55734. return;
  55735. }
  55736. }
  55737. dismissMenu (0);
  55738. }
  55739. }
  55740. void handleCommandMessage (int commandId)
  55741. {
  55742. Component::handleCommandMessage (commandId);
  55743. if (commandId == PopupMenuSettings::dismissCommandId)
  55744. dismissMenu (0);
  55745. }
  55746. void timerCallback()
  55747. {
  55748. if (! isVisible())
  55749. return;
  55750. if (componentAttachedTo != componentAttachedToOriginal)
  55751. {
  55752. dismissMenu (0);
  55753. return;
  55754. }
  55755. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  55756. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  55757. return;
  55758. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  55759. // move rather than a real timer callback
  55760. const Point<int> globalMousePos (Desktop::getMousePosition());
  55761. const Point<int> localMousePos (getLocalPoint (0, globalMousePos));
  55762. const uint32 now = Time::getMillisecondCounter();
  55763. if (now > timeEnteredCurrentChildComp + 100
  55764. && reallyContains (localMousePos, true)
  55765. && currentChild != 0
  55766. && (! disableMouseMoves)
  55767. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  55768. {
  55769. showSubMenuFor (currentChild);
  55770. }
  55771. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  55772. {
  55773. highlightItemUnderMouse (globalMousePos, localMousePos);
  55774. }
  55775. bool overScrollArea = false;
  55776. if (isScrolling()
  55777. && (isOver || (isDown && isPositiveAndBelow (localMousePos.getX(), getWidth())))
  55778. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  55779. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  55780. {
  55781. if (now > lastScroll + 20)
  55782. {
  55783. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  55784. int amount = 0;
  55785. for (int i = 0; i < items.size() && amount == 0; ++i)
  55786. amount = ((int) scrollAcceleration) * items.getUnchecked(i)->getHeight();
  55787. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  55788. lastScroll = now;
  55789. }
  55790. overScrollArea = true;
  55791. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  55792. }
  55793. else
  55794. {
  55795. scrollAcceleration = 1.0;
  55796. }
  55797. const bool wasDown = isDown;
  55798. bool isOverAny = isOverAnyMenu();
  55799. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  55800. {
  55801. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55802. isOverAny = isOverAnyMenu();
  55803. }
  55804. if (hideOnExit && hasBeenOver && ! isOverAny)
  55805. {
  55806. hide (0, true);
  55807. }
  55808. else
  55809. {
  55810. isDown = hasBeenOver
  55811. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  55812. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  55813. bool anyFocused = Process::isForegroundProcess();
  55814. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  55815. {
  55816. // because no component at all may have focus, our test here will
  55817. // only be triggered when something has focus and then loses it.
  55818. anyFocused = ! hasAnyJuceCompHadFocus;
  55819. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  55820. {
  55821. if (ComponentPeer::getPeer (i)->isFocused())
  55822. {
  55823. anyFocused = true;
  55824. hasAnyJuceCompHadFocus = true;
  55825. break;
  55826. }
  55827. }
  55828. }
  55829. if (! anyFocused)
  55830. {
  55831. if (now > lastFocused + 10)
  55832. {
  55833. wasHiddenBecauseOfAppChange() = true;
  55834. dismissMenu (0);
  55835. return; // may have been deleted by the previous call..
  55836. }
  55837. }
  55838. else if (wasDown && now > menuCreationTime + 250
  55839. && ! (isDown || overScrollArea))
  55840. {
  55841. isOver = reallyContains (localMousePos, true);
  55842. if (isOver)
  55843. {
  55844. triggerCurrentlyHighlightedItem();
  55845. }
  55846. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  55847. {
  55848. dismissMenu (0);
  55849. }
  55850. return; // may have been deleted by the previous calls..
  55851. }
  55852. else
  55853. {
  55854. lastFocused = now;
  55855. }
  55856. }
  55857. }
  55858. static Array<Window*>& getActiveWindows()
  55859. {
  55860. static Array<Window*> activeMenuWindows;
  55861. return activeMenuWindows;
  55862. }
  55863. static bool& wasHiddenBecauseOfAppChange() throw()
  55864. {
  55865. static bool b = false;
  55866. return b;
  55867. }
  55868. private:
  55869. Window* owner;
  55870. OwnedArray <PopupMenu::ItemComponent> items;
  55871. Component::SafePointer<PopupMenu::ItemComponent> currentChild;
  55872. ScopedPointer <Window> activeSubMenu;
  55873. ApplicationCommandManager** managerOfChosenCommand;
  55874. WeakReference<Component> componentAttachedTo;
  55875. Component* componentAttachedToOriginal;
  55876. Rectangle<int> windowPos;
  55877. Point<int> lastMouse;
  55878. int minimumWidth, maximumNumColumns, standardItemHeight;
  55879. bool isOver, hasBeenOver, isDown, needsToScroll;
  55880. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  55881. int numColumns, contentHeight, childYOffset;
  55882. Array <int> columnWidths;
  55883. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  55884. double scrollAcceleration;
  55885. bool overlaps (const Rectangle<int>& r) const
  55886. {
  55887. return r.intersects (getBounds())
  55888. || (owner != 0 && owner->overlaps (r));
  55889. }
  55890. bool isOverAnyMenu() const
  55891. {
  55892. return (owner != 0) ? owner->isOverAnyMenu()
  55893. : isOverChildren();
  55894. }
  55895. bool isOverChildren() const
  55896. {
  55897. return isVisible()
  55898. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  55899. }
  55900. void updateMouseOverStatus (const Point<int>& globalMousePos)
  55901. {
  55902. const Point<int> relPos (getLocalPoint (0, globalMousePos));
  55903. isOver = reallyContains (relPos, true);
  55904. if (activeSubMenu != 0)
  55905. activeSubMenu->updateMouseOverStatus (globalMousePos);
  55906. }
  55907. bool treeContains (const Window* const window) const throw()
  55908. {
  55909. const Window* mw = this;
  55910. while (mw->owner != 0)
  55911. mw = mw->owner;
  55912. while (mw != 0)
  55913. {
  55914. if (mw == window)
  55915. return true;
  55916. mw = mw->activeSubMenu;
  55917. }
  55918. return false;
  55919. }
  55920. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  55921. {
  55922. const Rectangle<int> mon (Desktop::getInstance()
  55923. .getMonitorAreaContaining (target.getCentre(),
  55924. #if JUCE_MAC
  55925. true));
  55926. #else
  55927. false)); // on windows, don't stop the menu overlapping the taskbar
  55928. #endif
  55929. int x, y, widthToUse, heightToUse;
  55930. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  55931. if (alignToRectangle)
  55932. {
  55933. x = target.getX();
  55934. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  55935. const int spaceOver = target.getY() - mon.getY();
  55936. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  55937. y = target.getBottom();
  55938. else
  55939. y = target.getY() - heightToUse;
  55940. }
  55941. else
  55942. {
  55943. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  55944. if (owner != 0)
  55945. {
  55946. if (owner->owner != 0)
  55947. {
  55948. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  55949. > owner->owner->getX() + owner->owner->getWidth() / 2);
  55950. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  55951. tendTowardsRight = true;
  55952. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  55953. tendTowardsRight = false;
  55954. }
  55955. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  55956. {
  55957. tendTowardsRight = true;
  55958. }
  55959. }
  55960. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  55961. target.getX() - mon.getX()) - 32;
  55962. if (biggestSpace < widthToUse)
  55963. {
  55964. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  55965. if (numColumns > 1)
  55966. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  55967. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  55968. }
  55969. if (tendTowardsRight)
  55970. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  55971. else
  55972. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  55973. y = target.getY();
  55974. if (target.getCentreY() > mon.getCentreY())
  55975. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  55976. }
  55977. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  55978. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  55979. windowPos.setBounds (x, y, widthToUse, heightToUse);
  55980. // sets this flag if it's big enough to obscure any of its parent menus
  55981. hideOnExit = (owner != 0)
  55982. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  55983. }
  55984. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  55985. {
  55986. numColumns = 0;
  55987. contentHeight = 0;
  55988. const int maxMenuH = getParentHeight() - 24;
  55989. int totalW;
  55990. do
  55991. {
  55992. ++numColumns;
  55993. totalW = workOutBestSize (maxMenuW);
  55994. if (totalW > maxMenuW)
  55995. {
  55996. numColumns = jmax (1, numColumns - 1);
  55997. totalW = workOutBestSize (maxMenuW); // to update col widths
  55998. break;
  55999. }
  56000. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56001. {
  56002. break;
  56003. }
  56004. } while (numColumns < maximumNumColumns);
  56005. const int actualH = jmin (contentHeight, maxMenuH);
  56006. needsToScroll = contentHeight > actualH;
  56007. width = updateYPositions();
  56008. height = actualH + PopupMenuSettings::borderSize * 2;
  56009. }
  56010. int workOutBestSize (const int maxMenuW)
  56011. {
  56012. int totalW = 0;
  56013. contentHeight = 0;
  56014. int childNum = 0;
  56015. for (int col = 0; col < numColumns; ++col)
  56016. {
  56017. int i, colW = 50, colH = 0;
  56018. const int numChildren = jmin (items.size() - childNum,
  56019. (items.size() + numColumns - 1) / numColumns);
  56020. for (i = numChildren; --i >= 0;)
  56021. {
  56022. colW = jmax (colW, items.getUnchecked (childNum + i)->getWidth());
  56023. colH += items.getUnchecked (childNum + i)->getHeight();
  56024. }
  56025. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56026. columnWidths.set (col, colW);
  56027. totalW += colW;
  56028. contentHeight = jmax (contentHeight, colH);
  56029. childNum += numChildren;
  56030. }
  56031. if (totalW < minimumWidth)
  56032. {
  56033. totalW = minimumWidth;
  56034. for (int col = 0; col < numColumns; ++col)
  56035. columnWidths.set (0, totalW / numColumns);
  56036. }
  56037. return totalW;
  56038. }
  56039. void ensureItemIsVisible (const int itemId, int wantedY)
  56040. {
  56041. jassert (itemId != 0)
  56042. for (int i = items.size(); --i >= 0;)
  56043. {
  56044. PopupMenu::ItemComponent* const m = items.getUnchecked(i);
  56045. if (m != 0
  56046. && m->itemInfo.itemId == itemId
  56047. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56048. {
  56049. const int currentY = m->getY();
  56050. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56051. {
  56052. if (wantedY < 0)
  56053. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56054. jmax (PopupMenuSettings::scrollZone,
  56055. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56056. currentY);
  56057. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56058. int deltaY = wantedY - currentY;
  56059. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56060. jmin (windowPos.getHeight(), mon.getHeight()));
  56061. const int newY = jlimit (mon.getY(),
  56062. mon.getBottom() - windowPos.getHeight(),
  56063. windowPos.getY() + deltaY);
  56064. deltaY -= newY - windowPos.getY();
  56065. childYOffset -= deltaY;
  56066. windowPos.setPosition (windowPos.getX(), newY);
  56067. updateYPositions();
  56068. }
  56069. break;
  56070. }
  56071. }
  56072. }
  56073. void resizeToBestWindowPos()
  56074. {
  56075. Rectangle<int> r (windowPos);
  56076. if (childYOffset < 0)
  56077. {
  56078. r.setBounds (r.getX(), r.getY() - childYOffset,
  56079. r.getWidth(), r.getHeight() + childYOffset);
  56080. }
  56081. else if (childYOffset > 0)
  56082. {
  56083. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56084. if (spaceAtBottom > 0)
  56085. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56086. }
  56087. setBounds (r);
  56088. updateYPositions();
  56089. }
  56090. void alterChildYPos (const int delta)
  56091. {
  56092. if (isScrolling())
  56093. {
  56094. childYOffset += delta;
  56095. if (delta < 0)
  56096. {
  56097. childYOffset = jmax (childYOffset, 0);
  56098. }
  56099. else if (delta > 0)
  56100. {
  56101. childYOffset = jmin (childYOffset,
  56102. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56103. }
  56104. updateYPositions();
  56105. }
  56106. else
  56107. {
  56108. childYOffset = 0;
  56109. }
  56110. resizeToBestWindowPos();
  56111. repaint();
  56112. }
  56113. int updateYPositions()
  56114. {
  56115. int x = 0;
  56116. int childNum = 0;
  56117. for (int col = 0; col < numColumns; ++col)
  56118. {
  56119. const int numChildren = jmin (items.size() - childNum,
  56120. (items.size() + numColumns - 1) / numColumns);
  56121. const int colW = columnWidths [col];
  56122. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56123. for (int i = 0; i < numChildren; ++i)
  56124. {
  56125. Component* const c = items.getUnchecked (childNum + i);
  56126. c->setBounds (x, y, colW, c->getHeight());
  56127. y += c->getHeight();
  56128. }
  56129. x += colW;
  56130. childNum += numChildren;
  56131. }
  56132. return x;
  56133. }
  56134. bool isScrolling() const throw()
  56135. {
  56136. return childYOffset != 0 || needsToScroll;
  56137. }
  56138. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56139. {
  56140. if (currentChild != 0)
  56141. currentChild->setHighlighted (false);
  56142. currentChild = child;
  56143. if (currentChild != 0)
  56144. {
  56145. currentChild->setHighlighted (true);
  56146. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56147. }
  56148. }
  56149. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56150. {
  56151. activeSubMenu = 0;
  56152. if (childComp != 0 && childComp->itemInfo.hasActiveSubMenu())
  56153. {
  56154. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56155. dismissOnMouseUp,
  56156. this,
  56157. childComp->getScreenBounds(),
  56158. 0, maximumNumColumns,
  56159. standardItemHeight,
  56160. false, 0, managerOfChosenCommand,
  56161. componentAttachedTo);
  56162. if (activeSubMenu != 0)
  56163. {
  56164. activeSubMenu->setVisible (true);
  56165. activeSubMenu->enterModalState (false);
  56166. activeSubMenu->toFront (false);
  56167. return true;
  56168. }
  56169. }
  56170. return false;
  56171. }
  56172. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56173. {
  56174. isOver = reallyContains (localMousePos, true);
  56175. if (isOver)
  56176. hasBeenOver = true;
  56177. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56178. {
  56179. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56180. if (disableMouseMoves && isOver)
  56181. disableMouseMoves = false;
  56182. }
  56183. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56184. return;
  56185. bool isMovingTowardsMenu = false;
  56186. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56187. {
  56188. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56189. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56190. // extends from the last mouse pos to the submenu's rectangle..
  56191. float subX = (float) activeSubMenu->getScreenX();
  56192. if (activeSubMenu->getX() > getX())
  56193. {
  56194. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56195. }
  56196. else
  56197. {
  56198. lastMouse += Point<int> (2, 0);
  56199. subX += activeSubMenu->getWidth();
  56200. }
  56201. Path areaTowardsSubMenu;
  56202. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(), (float) lastMouse.getY(),
  56203. subX, (float) activeSubMenu->getScreenY(),
  56204. subX, (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56205. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56206. }
  56207. lastMouse = globalMousePos;
  56208. if (! isMovingTowardsMenu)
  56209. {
  56210. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56211. if (c == this)
  56212. c = 0;
  56213. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56214. if (mic == 0 && c != 0)
  56215. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56216. if (mic != currentChild
  56217. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56218. {
  56219. if (isOver && (c != 0) && (activeSubMenu != 0))
  56220. activeSubMenu->hide (0, true);
  56221. if (! isOver)
  56222. mic = 0;
  56223. setCurrentlyHighlightedChild (mic);
  56224. }
  56225. }
  56226. }
  56227. void triggerCurrentlyHighlightedItem()
  56228. {
  56229. if (currentChild != 0
  56230. && currentChild->itemInfo.canBeTriggered()
  56231. && (currentChild->itemInfo.customComp == 0
  56232. || currentChild->itemInfo.customComp->isTriggeredAutomatically()))
  56233. {
  56234. dismissMenu (&currentChild->itemInfo);
  56235. }
  56236. }
  56237. void selectNextItem (const int delta)
  56238. {
  56239. disableTimerUntilMouseMoves();
  56240. PopupMenu::ItemComponent* mic = 0;
  56241. bool wasLastOne = (currentChild == 0);
  56242. const int numItems = items.size();
  56243. for (int i = 0; i < numItems + 1; ++i)
  56244. {
  56245. int index = (delta > 0) ? i : (numItems - 1 - i);
  56246. index = (index + numItems) % numItems;
  56247. mic = items.getUnchecked (index);
  56248. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56249. && wasLastOne)
  56250. break;
  56251. if (mic == currentChild)
  56252. wasLastOne = true;
  56253. }
  56254. setCurrentlyHighlightedChild (mic);
  56255. }
  56256. void disableTimerUntilMouseMoves()
  56257. {
  56258. disableMouseMoves = true;
  56259. if (owner != 0)
  56260. owner->disableTimerUntilMouseMoves();
  56261. }
  56262. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Window);
  56263. };
  56264. PopupMenu::PopupMenu()
  56265. : lookAndFeel (0),
  56266. separatorPending (false)
  56267. {
  56268. }
  56269. PopupMenu::PopupMenu (const PopupMenu& other)
  56270. : lookAndFeel (other.lookAndFeel),
  56271. separatorPending (false)
  56272. {
  56273. items.addCopiesOf (other.items);
  56274. }
  56275. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56276. {
  56277. if (this != &other)
  56278. {
  56279. lookAndFeel = other.lookAndFeel;
  56280. clear();
  56281. items.addCopiesOf (other.items);
  56282. }
  56283. return *this;
  56284. }
  56285. PopupMenu::~PopupMenu()
  56286. {
  56287. clear();
  56288. }
  56289. void PopupMenu::clear()
  56290. {
  56291. items.clear();
  56292. separatorPending = false;
  56293. }
  56294. void PopupMenu::addSeparatorIfPending()
  56295. {
  56296. if (separatorPending)
  56297. {
  56298. separatorPending = false;
  56299. if (items.size() > 0)
  56300. items.add (new Item());
  56301. }
  56302. }
  56303. void PopupMenu::addItem (const int itemResultId, const String& itemText,
  56304. const bool isActive, const bool isTicked, const Image& iconToUse)
  56305. {
  56306. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56307. // didn't pick anything, so you shouldn't use it as the id
  56308. // for an item..
  56309. addSeparatorIfPending();
  56310. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56311. Colours::black, false, 0, 0, 0));
  56312. }
  56313. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56314. const int commandID,
  56315. const String& displayName)
  56316. {
  56317. jassert (commandManager != 0 && commandID != 0);
  56318. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56319. if (registeredInfo != 0)
  56320. {
  56321. ApplicationCommandInfo info (*registeredInfo);
  56322. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56323. addSeparatorIfPending();
  56324. items.add (new Item (commandID,
  56325. displayName.isNotEmpty() ? displayName
  56326. : info.shortName,
  56327. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56328. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56329. Image::null,
  56330. Colours::black,
  56331. false,
  56332. 0, 0,
  56333. commandManager));
  56334. }
  56335. }
  56336. void PopupMenu::addColouredItem (const int itemResultId,
  56337. const String& itemText,
  56338. const Colour& itemTextColour,
  56339. const bool isActive,
  56340. const bool isTicked,
  56341. const Image& iconToUse)
  56342. {
  56343. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56344. // didn't pick anything, so you shouldn't use it as the id
  56345. // for an item..
  56346. addSeparatorIfPending();
  56347. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56348. itemTextColour, true, 0, 0, 0));
  56349. }
  56350. void PopupMenu::addCustomItem (const int itemResultId, CustomComponent* const customComponent)
  56351. {
  56352. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56353. // didn't pick anything, so you shouldn't use it as the id
  56354. // for an item..
  56355. addSeparatorIfPending();
  56356. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56357. Colours::black, false, customComponent, 0, 0));
  56358. }
  56359. class NormalComponentWrapper : public PopupMenu::CustomComponent
  56360. {
  56361. public:
  56362. NormalComponentWrapper (Component* const comp, const int w, const int h,
  56363. const bool triggerMenuItemAutomaticallyWhenClicked)
  56364. : PopupMenu::CustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56365. width (w), height (h)
  56366. {
  56367. addAndMakeVisible (comp);
  56368. }
  56369. void getIdealSize (int& idealWidth, int& idealHeight)
  56370. {
  56371. idealWidth = width;
  56372. idealHeight = height;
  56373. }
  56374. void resized()
  56375. {
  56376. if (getChildComponent(0) != 0)
  56377. getChildComponent(0)->setBounds (getLocalBounds());
  56378. }
  56379. private:
  56380. const int width, height;
  56381. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NormalComponentWrapper);
  56382. };
  56383. void PopupMenu::addCustomItem (const int itemResultId,
  56384. Component* customComponent,
  56385. int idealWidth, int idealHeight,
  56386. const bool triggerMenuItemAutomaticallyWhenClicked)
  56387. {
  56388. addCustomItem (itemResultId,
  56389. new NormalComponentWrapper (customComponent, idealWidth, idealHeight,
  56390. triggerMenuItemAutomaticallyWhenClicked));
  56391. }
  56392. void PopupMenu::addSubMenu (const String& subMenuName,
  56393. const PopupMenu& subMenu,
  56394. const bool isActive,
  56395. const Image& iconToUse,
  56396. const bool isTicked)
  56397. {
  56398. addSeparatorIfPending();
  56399. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56400. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56401. }
  56402. void PopupMenu::addSeparator()
  56403. {
  56404. separatorPending = true;
  56405. }
  56406. class HeaderItemComponent : public PopupMenu::CustomComponent
  56407. {
  56408. public:
  56409. HeaderItemComponent (const String& name)
  56410. : PopupMenu::CustomComponent (false)
  56411. {
  56412. setName (name);
  56413. }
  56414. void paint (Graphics& g)
  56415. {
  56416. Font f (getLookAndFeel().getPopupMenuFont());
  56417. f.setBold (true);
  56418. g.setFont (f);
  56419. g.setColour (findColour (PopupMenu::headerTextColourId));
  56420. g.drawFittedText (getName(),
  56421. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56422. Justification::bottomLeft, 1);
  56423. }
  56424. void getIdealSize (int& idealWidth, int& idealHeight)
  56425. {
  56426. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56427. idealHeight += idealHeight / 2;
  56428. idealWidth += idealWidth / 4;
  56429. }
  56430. private:
  56431. JUCE_LEAK_DETECTOR (HeaderItemComponent);
  56432. };
  56433. void PopupMenu::addSectionHeader (const String& title)
  56434. {
  56435. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56436. }
  56437. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56438. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56439. {
  56440. public:
  56441. PopupMenuCompletionCallback()
  56442. : managerOfChosenCommand (0)
  56443. {
  56444. }
  56445. void modalStateFinished (int result)
  56446. {
  56447. if (managerOfChosenCommand != 0 && result != 0)
  56448. {
  56449. ApplicationCommandTarget::InvocationInfo info (result);
  56450. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56451. managerOfChosenCommand->invoke (info, true);
  56452. }
  56453. // (this would be the place to fade out the component, if that's what's required)
  56454. component = 0;
  56455. }
  56456. ApplicationCommandManager* managerOfChosenCommand;
  56457. ScopedPointer<Component> component;
  56458. private:
  56459. JUCE_DECLARE_NON_COPYABLE (PopupMenuCompletionCallback);
  56460. };
  56461. int PopupMenu::showMenu (const Rectangle<int>& target,
  56462. const int itemIdThatMustBeVisible,
  56463. const int minimumWidth,
  56464. const int maximumNumColumns,
  56465. const int standardItemHeight,
  56466. Component* const componentAttachedTo,
  56467. ModalComponentManager::Callback* userCallback)
  56468. {
  56469. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56470. WeakReference<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56471. WeakReference<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56472. Window::wasHiddenBecauseOfAppChange() = false;
  56473. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56474. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56475. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56476. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56477. standardItemHeight, ! target.isEmpty(), itemIdThatMustBeVisible,
  56478. &callback->managerOfChosenCommand, componentAttachedTo);
  56479. if (callback->component == 0)
  56480. return 0;
  56481. callback->component->enterModalState (false, userCallbackDeleter.release());
  56482. callback->component->toFront (false); // need to do this after making it modal, or it could
  56483. // be stuck behind other comps that are already modal..
  56484. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56485. callbackDeleter.release();
  56486. if (userCallback != 0)
  56487. return 0;
  56488. const int result = callback->component->runModalLoop();
  56489. if (! Window::wasHiddenBecauseOfAppChange())
  56490. {
  56491. if (prevTopLevel != 0)
  56492. prevTopLevel->toFront (true);
  56493. if (prevFocused != 0)
  56494. prevFocused->grabKeyboardFocus();
  56495. }
  56496. return result;
  56497. }
  56498. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56499. const int minimumWidth, const int maximumNumColumns,
  56500. const int standardItemHeight,
  56501. ModalComponentManager::Callback* callback)
  56502. {
  56503. return showMenu (Rectangle<int>().withPosition (Desktop::getMousePosition()),
  56504. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56505. standardItemHeight, 0, callback);
  56506. }
  56507. int PopupMenu::showAt (const Rectangle<int>& screenAreaToAttachTo,
  56508. const int itemIdThatMustBeVisible,
  56509. const int minimumWidth, const int maximumNumColumns,
  56510. const int standardItemHeight,
  56511. ModalComponentManager::Callback* callback)
  56512. {
  56513. return showMenu (screenAreaToAttachTo,
  56514. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56515. standardItemHeight, 0, callback);
  56516. }
  56517. int PopupMenu::showAt (Component* componentToAttachTo,
  56518. const int itemIdThatMustBeVisible,
  56519. const int minimumWidth, const int maximumNumColumns,
  56520. const int standardItemHeight,
  56521. ModalComponentManager::Callback* callback)
  56522. {
  56523. if (componentToAttachTo != 0)
  56524. {
  56525. return showMenu (componentToAttachTo->getScreenBounds(),
  56526. itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56527. standardItemHeight, componentToAttachTo, callback);
  56528. }
  56529. else
  56530. {
  56531. return show (itemIdThatMustBeVisible, minimumWidth, maximumNumColumns,
  56532. standardItemHeight, callback);
  56533. }
  56534. }
  56535. bool JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56536. {
  56537. const int numWindows = Window::getActiveWindows().size();
  56538. for (int i = numWindows; --i >= 0;)
  56539. {
  56540. Window* const pmw = Window::getActiveWindows()[i];
  56541. if (pmw != 0)
  56542. pmw->dismissMenu (0);
  56543. }
  56544. return numWindows > 0;
  56545. }
  56546. int PopupMenu::getNumItems() const throw()
  56547. {
  56548. int num = 0;
  56549. for (int i = items.size(); --i >= 0;)
  56550. if (! (items.getUnchecked(i))->isSeparator)
  56551. ++num;
  56552. return num;
  56553. }
  56554. bool PopupMenu::containsCommandItem (const int commandID) const
  56555. {
  56556. for (int i = items.size(); --i >= 0;)
  56557. {
  56558. const Item* mi = items.getUnchecked (i);
  56559. if ((mi->itemId == commandID && mi->commandManager != 0)
  56560. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56561. {
  56562. return true;
  56563. }
  56564. }
  56565. return false;
  56566. }
  56567. bool PopupMenu::containsAnyActiveItems() const throw()
  56568. {
  56569. for (int i = items.size(); --i >= 0;)
  56570. {
  56571. const Item* const mi = items.getUnchecked (i);
  56572. if (mi->subMenu != 0)
  56573. {
  56574. if (mi->subMenu->containsAnyActiveItems())
  56575. return true;
  56576. }
  56577. else if (mi->active)
  56578. {
  56579. return true;
  56580. }
  56581. }
  56582. return false;
  56583. }
  56584. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56585. {
  56586. lookAndFeel = newLookAndFeel;
  56587. }
  56588. PopupMenu::CustomComponent::CustomComponent (const bool isTriggeredAutomatically_)
  56589. : isHighlighted (false),
  56590. triggeredAutomatically (isTriggeredAutomatically_)
  56591. {
  56592. }
  56593. PopupMenu::CustomComponent::~CustomComponent()
  56594. {
  56595. }
  56596. void PopupMenu::CustomComponent::setHighlighted (bool shouldBeHighlighted)
  56597. {
  56598. isHighlighted = shouldBeHighlighted;
  56599. repaint();
  56600. }
  56601. void PopupMenu::CustomComponent::triggerMenuItem()
  56602. {
  56603. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56604. if (mic != 0)
  56605. {
  56606. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56607. if (pmw != 0)
  56608. {
  56609. pmw->dismissMenu (&mic->itemInfo);
  56610. }
  56611. else
  56612. {
  56613. // something must have gone wrong with the component hierarchy if this happens..
  56614. jassertfalse;
  56615. }
  56616. }
  56617. else
  56618. {
  56619. // why isn't this component inside a menu? Not much point triggering the item if
  56620. // there's no menu.
  56621. jassertfalse;
  56622. }
  56623. }
  56624. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56625. : subMenu (0),
  56626. itemId (0),
  56627. isSeparator (false),
  56628. isTicked (false),
  56629. isEnabled (false),
  56630. isCustomComponent (false),
  56631. isSectionHeader (false),
  56632. customColour (0),
  56633. customImage (0),
  56634. menu (menu_),
  56635. index (0)
  56636. {
  56637. }
  56638. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56639. {
  56640. }
  56641. bool PopupMenu::MenuItemIterator::next()
  56642. {
  56643. if (index >= menu.items.size())
  56644. return false;
  56645. const Item* const item = menu.items.getUnchecked (index);
  56646. ++index;
  56647. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56648. subMenu = item->subMenu;
  56649. itemId = item->itemId;
  56650. isSeparator = item->isSeparator;
  56651. isTicked = item->isTicked;
  56652. isEnabled = item->active;
  56653. isSectionHeader = dynamic_cast <HeaderItemComponent*> (static_cast <CustomComponent*> (item->customComp)) != 0;
  56654. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56655. customColour = item->usesColour ? &(item->textColour) : 0;
  56656. customImage = item->image;
  56657. commandManager = item->commandManager;
  56658. return true;
  56659. }
  56660. END_JUCE_NAMESPACE
  56661. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56662. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56663. BEGIN_JUCE_NAMESPACE
  56664. ComponentDragger::ComponentDragger()
  56665. {
  56666. }
  56667. ComponentDragger::~ComponentDragger()
  56668. {
  56669. }
  56670. void ComponentDragger::startDraggingComponent (Component* const componentToDrag, const MouseEvent& e)
  56671. {
  56672. jassert (componentToDrag != 0);
  56673. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56674. if (componentToDrag != 0)
  56675. mouseDownWithinTarget = e.getEventRelativeTo (componentToDrag).getMouseDownPosition();
  56676. }
  56677. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e,
  56678. ComponentBoundsConstrainer* const constrainer)
  56679. {
  56680. jassert (componentToDrag != 0);
  56681. jassert (e.mods.isAnyMouseButtonDown()); // The event has to be a drag event!
  56682. if (componentToDrag != 0)
  56683. {
  56684. Rectangle<int> bounds (componentToDrag->getBounds());
  56685. // If the component is a window, multiple mouse events can get queued while it's in the same position,
  56686. // so their coordinates become wrong after the first one moves the window, so in that case, we'll use
  56687. // the current mouse position instead of the one that the event contains...
  56688. if (componentToDrag->isOnDesktop())
  56689. bounds += componentToDrag->getMouseXYRelative() - mouseDownWithinTarget;
  56690. else
  56691. bounds += e.getEventRelativeTo (componentToDrag).getPosition() - mouseDownWithinTarget;
  56692. if (constrainer != 0)
  56693. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  56694. else
  56695. componentToDrag->setBounds (bounds);
  56696. }
  56697. }
  56698. END_JUCE_NAMESPACE
  56699. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  56700. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  56701. BEGIN_JUCE_NAMESPACE
  56702. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  56703. bool juce_performDragDropText (const String& text, bool& shouldStop);
  56704. class DragImageComponent : public Component,
  56705. public Timer
  56706. {
  56707. public:
  56708. DragImageComponent (const Image& im,
  56709. const String& desc,
  56710. Component* const sourceComponent,
  56711. Component* const mouseDragSource_,
  56712. DragAndDropContainer* const o,
  56713. const Point<int>& imageOffset_)
  56714. : image (im),
  56715. source (sourceComponent),
  56716. mouseDragSource (mouseDragSource_),
  56717. owner (o),
  56718. dragDesc (desc),
  56719. imageOffset (imageOffset_),
  56720. hasCheckedForExternalDrag (false),
  56721. drawImage (true)
  56722. {
  56723. setSize (im.getWidth(), im.getHeight());
  56724. if (mouseDragSource == 0)
  56725. mouseDragSource = source;
  56726. mouseDragSource->addMouseListener (this, false);
  56727. startTimer (200);
  56728. setInterceptsMouseClicks (false, false);
  56729. setAlwaysOnTop (true);
  56730. }
  56731. ~DragImageComponent()
  56732. {
  56733. if (owner->dragImageComponent == this)
  56734. owner->dragImageComponent.release();
  56735. if (mouseDragSource != 0)
  56736. {
  56737. mouseDragSource->removeMouseListener (this);
  56738. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  56739. getCurrentlyOver()->itemDragExit (dragDesc, source);
  56740. }
  56741. }
  56742. void paint (Graphics& g)
  56743. {
  56744. if (isOpaque())
  56745. g.fillAll (Colours::white);
  56746. if (drawImage)
  56747. {
  56748. g.setOpacity (1.0f);
  56749. g.drawImageAt (image, 0, 0);
  56750. }
  56751. }
  56752. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  56753. {
  56754. Component* hit = getParentComponent();
  56755. if (hit == 0)
  56756. {
  56757. hit = Desktop::getInstance().findComponentAt (screenPos);
  56758. }
  56759. else
  56760. {
  56761. const Point<int> relPos (hit->getLocalPoint (0, screenPos));
  56762. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  56763. }
  56764. // (note: use a local copy of the dragDesc member in case the callback runs
  56765. // a modal loop and deletes this object before the method completes)
  56766. const String dragDescLocal (dragDesc);
  56767. while (hit != 0)
  56768. {
  56769. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  56770. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56771. {
  56772. relativePos = hit->getLocalPoint (0, screenPos);
  56773. return ddt;
  56774. }
  56775. hit = hit->getParentComponent();
  56776. }
  56777. return 0;
  56778. }
  56779. void mouseUp (const MouseEvent& e)
  56780. {
  56781. if (e.originalComponent != this)
  56782. {
  56783. if (mouseDragSource != 0)
  56784. mouseDragSource->removeMouseListener (this);
  56785. bool dropAccepted = false;
  56786. DragAndDropTarget* ddt = 0;
  56787. Point<int> relPos;
  56788. if (isVisible())
  56789. {
  56790. setVisible (false);
  56791. ddt = findTarget (e.getScreenPosition(), relPos);
  56792. // fade this component and remove it - it'll be deleted later by the timer callback
  56793. dropAccepted = ddt != 0;
  56794. setVisible (true);
  56795. if (dropAccepted || source == 0)
  56796. {
  56797. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  56798. }
  56799. else
  56800. {
  56801. const Point<int> target (source->localPointToGlobal (source->getLocalBounds().getCentre()));
  56802. const Point<int> ourCentre (localPointToGlobal (getLocalBounds().getCentre()));
  56803. Desktop::getInstance().getAnimator().animateComponent (this,
  56804. getBounds() + (target - ourCentre),
  56805. 0.0f, 120,
  56806. true, 1.0, 1.0);
  56807. }
  56808. }
  56809. if (getParentComponent() != 0)
  56810. getParentComponent()->removeChildComponent (this);
  56811. if (dropAccepted && ddt != 0)
  56812. {
  56813. // (note: use a local copy of the dragDesc member in case the callback runs
  56814. // a modal loop and deletes this object before the method completes)
  56815. const String dragDescLocal (dragDesc);
  56816. currentlyOverComp = 0;
  56817. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  56818. }
  56819. // careful - this object could now be deleted..
  56820. }
  56821. }
  56822. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  56823. {
  56824. // (note: use a local copy of the dragDesc member in case the callback runs
  56825. // a modal loop and deletes this object before it returns)
  56826. const String dragDescLocal (dragDesc);
  56827. Point<int> newPos (screenPos + imageOffset);
  56828. if (getParentComponent() != 0)
  56829. newPos = getParentComponent()->getLocalPoint (0, newPos);
  56830. //if (newX != getX() || newY != getY())
  56831. {
  56832. setTopLeftPosition (newPos.getX(), newPos.getY());
  56833. Point<int> relPos;
  56834. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  56835. Component* ddtComp = dynamic_cast <Component*> (ddt);
  56836. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  56837. if (ddtComp != currentlyOverComp)
  56838. {
  56839. if (currentlyOverComp != 0 && source != 0
  56840. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  56841. {
  56842. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  56843. }
  56844. currentlyOverComp = ddtComp;
  56845. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  56846. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  56847. }
  56848. DragAndDropTarget* target = getCurrentlyOver();
  56849. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  56850. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  56851. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  56852. {
  56853. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  56854. {
  56855. hasCheckedForExternalDrag = true;
  56856. StringArray files;
  56857. bool canMoveFiles = false;
  56858. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  56859. && files.size() > 0)
  56860. {
  56861. WeakReference<Component> cdw (this);
  56862. setVisible (false);
  56863. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  56864. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  56865. if (cdw != 0)
  56866. delete this;
  56867. return;
  56868. }
  56869. }
  56870. }
  56871. }
  56872. }
  56873. void mouseDrag (const MouseEvent& e)
  56874. {
  56875. if (e.originalComponent != this)
  56876. updateLocation (true, e.getScreenPosition());
  56877. }
  56878. void timerCallback()
  56879. {
  56880. if (source == 0)
  56881. {
  56882. delete this;
  56883. }
  56884. else if (! isMouseButtonDownAnywhere())
  56885. {
  56886. if (mouseDragSource != 0)
  56887. mouseDragSource->removeMouseListener (this);
  56888. delete this;
  56889. }
  56890. }
  56891. private:
  56892. Image image;
  56893. WeakReference<Component> source;
  56894. WeakReference<Component> mouseDragSource;
  56895. DragAndDropContainer* const owner;
  56896. WeakReference<Component> currentlyOverComp;
  56897. DragAndDropTarget* getCurrentlyOver()
  56898. {
  56899. return dynamic_cast <DragAndDropTarget*> (currentlyOverComp.get());
  56900. }
  56901. String dragDesc;
  56902. const Point<int> imageOffset;
  56903. bool hasCheckedForExternalDrag, drawImage;
  56904. JUCE_DECLARE_NON_COPYABLE (DragImageComponent);
  56905. };
  56906. DragAndDropContainer::DragAndDropContainer()
  56907. {
  56908. }
  56909. DragAndDropContainer::~DragAndDropContainer()
  56910. {
  56911. dragImageComponent = 0;
  56912. }
  56913. void DragAndDropContainer::startDragging (const String& sourceDescription,
  56914. Component* sourceComponent,
  56915. const Image& dragImage_,
  56916. const bool allowDraggingToExternalWindows,
  56917. const Point<int>* imageOffsetFromMouse)
  56918. {
  56919. Image dragImage (dragImage_);
  56920. if (dragImageComponent == 0)
  56921. {
  56922. Component* const thisComp = dynamic_cast <Component*> (this);
  56923. if (thisComp == 0)
  56924. {
  56925. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  56926. return;
  56927. }
  56928. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  56929. if (draggingSource == 0 || ! draggingSource->isDragging())
  56930. {
  56931. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  56932. return;
  56933. }
  56934. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  56935. Point<int> imageOffset;
  56936. if (dragImage.isNull())
  56937. {
  56938. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  56939. .convertedToFormat (Image::ARGB);
  56940. dragImage.multiplyAllAlphas (0.6f);
  56941. const int lo = 150;
  56942. const int hi = 400;
  56943. Point<int> relPos (sourceComponent->getLocalPoint (0, lastMouseDown));
  56944. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  56945. for (int y = dragImage.getHeight(); --y >= 0;)
  56946. {
  56947. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  56948. for (int x = dragImage.getWidth(); --x >= 0;)
  56949. {
  56950. const int dx = x - clipped.getX();
  56951. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  56952. if (distance > lo)
  56953. {
  56954. const float alpha = (distance > hi) ? 0
  56955. : (hi - distance) / (float) (hi - lo)
  56956. + Random::getSystemRandom().nextFloat() * 0.008f;
  56957. dragImage.multiplyAlphaAt (x, y, alpha);
  56958. }
  56959. }
  56960. }
  56961. imageOffset = -clipped;
  56962. }
  56963. else
  56964. {
  56965. if (imageOffsetFromMouse == 0)
  56966. imageOffset = -dragImage.getBounds().getCentre();
  56967. else
  56968. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  56969. }
  56970. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  56971. draggingSource->getComponentUnderMouse(), this, imageOffset);
  56972. currentDragDesc = sourceDescription;
  56973. if (allowDraggingToExternalWindows)
  56974. {
  56975. if (! Desktop::canUseSemiTransparentWindows())
  56976. dragImageComponent->setOpaque (true);
  56977. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56978. | ComponentPeer::windowIsTemporary
  56979. | ComponentPeer::windowIgnoresKeyPresses);
  56980. }
  56981. else
  56982. thisComp->addChildComponent (dragImageComponent);
  56983. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  56984. dragImageComponent->setVisible (true);
  56985. }
  56986. }
  56987. bool DragAndDropContainer::isDragAndDropActive() const
  56988. {
  56989. return dragImageComponent != 0;
  56990. }
  56991. const String DragAndDropContainer::getCurrentDragDescription() const
  56992. {
  56993. return (dragImageComponent != 0) ? currentDragDesc
  56994. : String::empty;
  56995. }
  56996. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  56997. {
  56998. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  56999. }
  57000. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57001. {
  57002. return false;
  57003. }
  57004. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57005. {
  57006. }
  57007. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57008. {
  57009. }
  57010. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57011. {
  57012. }
  57013. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57014. {
  57015. return true;
  57016. }
  57017. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57018. {
  57019. }
  57020. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57021. {
  57022. }
  57023. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57024. {
  57025. }
  57026. END_JUCE_NAMESPACE
  57027. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57028. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57029. BEGIN_JUCE_NAMESPACE
  57030. class MouseCursor::SharedCursorHandle
  57031. {
  57032. public:
  57033. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57034. : handle (createStandardMouseCursor (type)),
  57035. refCount (1),
  57036. standardType (type),
  57037. isStandard (true)
  57038. {
  57039. }
  57040. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57041. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57042. refCount (1),
  57043. standardType (MouseCursor::NormalCursor),
  57044. isStandard (false)
  57045. {
  57046. }
  57047. ~SharedCursorHandle()
  57048. {
  57049. deleteMouseCursor (handle, isStandard);
  57050. }
  57051. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57052. {
  57053. const ScopedLock sl (getLock());
  57054. for (int i = 0; i < getCursors().size(); ++i)
  57055. {
  57056. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57057. if (sc->standardType == type)
  57058. return sc->retain();
  57059. }
  57060. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57061. getCursors().add (sc);
  57062. return sc;
  57063. }
  57064. SharedCursorHandle* retain() throw()
  57065. {
  57066. ++refCount;
  57067. return this;
  57068. }
  57069. void release()
  57070. {
  57071. if (--refCount == 0)
  57072. {
  57073. if (isStandard)
  57074. {
  57075. const ScopedLock sl (getLock());
  57076. getCursors().removeValue (this);
  57077. }
  57078. delete this;
  57079. }
  57080. }
  57081. void* getHandle() const throw() { return handle; }
  57082. private:
  57083. void* const handle;
  57084. Atomic <int> refCount;
  57085. const MouseCursor::StandardCursorType standardType;
  57086. const bool isStandard;
  57087. static CriticalSection& getLock()
  57088. {
  57089. static CriticalSection lock;
  57090. return lock;
  57091. }
  57092. static Array <SharedCursorHandle*>& getCursors()
  57093. {
  57094. static Array <SharedCursorHandle*> cursors;
  57095. return cursors;
  57096. }
  57097. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SharedCursorHandle);
  57098. };
  57099. MouseCursor::MouseCursor()
  57100. : cursorHandle (0)
  57101. {
  57102. }
  57103. MouseCursor::MouseCursor (const StandardCursorType type)
  57104. : cursorHandle (type != MouseCursor::NormalCursor ? SharedCursorHandle::createStandard (type) : 0)
  57105. {
  57106. }
  57107. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57108. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57109. {
  57110. }
  57111. MouseCursor::MouseCursor (const MouseCursor& other)
  57112. : cursorHandle (other.cursorHandle == 0 ? 0 : other.cursorHandle->retain())
  57113. {
  57114. }
  57115. MouseCursor::~MouseCursor()
  57116. {
  57117. if (cursorHandle != 0)
  57118. cursorHandle->release();
  57119. }
  57120. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57121. {
  57122. if (other.cursorHandle != 0)
  57123. other.cursorHandle->retain();
  57124. if (cursorHandle != 0)
  57125. cursorHandle->release();
  57126. cursorHandle = other.cursorHandle;
  57127. return *this;
  57128. }
  57129. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57130. {
  57131. return getHandle() == other.getHandle();
  57132. }
  57133. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57134. {
  57135. return getHandle() != other.getHandle();
  57136. }
  57137. void* MouseCursor::getHandle() const throw()
  57138. {
  57139. return cursorHandle != 0 ? cursorHandle->getHandle() : 0;
  57140. }
  57141. void MouseCursor::showWaitCursor()
  57142. {
  57143. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57144. }
  57145. void MouseCursor::hideWaitCursor()
  57146. {
  57147. Desktop::getInstance().getMainMouseSource().revealCursor();
  57148. }
  57149. END_JUCE_NAMESPACE
  57150. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57151. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57152. BEGIN_JUCE_NAMESPACE
  57153. MouseEvent::MouseEvent (MouseInputSource& source_,
  57154. const Point<int>& position,
  57155. const ModifierKeys& mods_,
  57156. Component* const eventComponent_,
  57157. Component* const originator,
  57158. const Time& eventTime_,
  57159. const Point<int> mouseDownPos_,
  57160. const Time& mouseDownTime_,
  57161. const int numberOfClicks_,
  57162. const bool mouseWasDragged) throw()
  57163. : x (position.getX()),
  57164. y (position.getY()),
  57165. mods (mods_),
  57166. eventComponent (eventComponent_),
  57167. originalComponent (originator),
  57168. eventTime (eventTime_),
  57169. source (source_),
  57170. mouseDownPos (mouseDownPos_),
  57171. mouseDownTime (mouseDownTime_),
  57172. numberOfClicks (numberOfClicks_),
  57173. wasMovedSinceMouseDown (mouseWasDragged)
  57174. {
  57175. }
  57176. MouseEvent::~MouseEvent() throw()
  57177. {
  57178. }
  57179. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57180. {
  57181. if (otherComponent == 0)
  57182. {
  57183. jassertfalse;
  57184. return *this;
  57185. }
  57186. return MouseEvent (source, otherComponent->getLocalPoint (eventComponent, getPosition()),
  57187. mods, otherComponent, originalComponent, eventTime,
  57188. otherComponent->getLocalPoint (eventComponent, mouseDownPos),
  57189. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57190. }
  57191. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57192. {
  57193. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57194. eventTime, mouseDownPos, mouseDownTime,
  57195. numberOfClicks, wasMovedSinceMouseDown);
  57196. }
  57197. bool MouseEvent::mouseWasClicked() const throw()
  57198. {
  57199. return ! wasMovedSinceMouseDown;
  57200. }
  57201. int MouseEvent::getMouseDownX() const throw()
  57202. {
  57203. return mouseDownPos.getX();
  57204. }
  57205. int MouseEvent::getMouseDownY() const throw()
  57206. {
  57207. return mouseDownPos.getY();
  57208. }
  57209. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57210. {
  57211. return mouseDownPos;
  57212. }
  57213. int MouseEvent::getDistanceFromDragStartX() const throw()
  57214. {
  57215. return x - mouseDownPos.getX();
  57216. }
  57217. int MouseEvent::getDistanceFromDragStartY() const throw()
  57218. {
  57219. return y - mouseDownPos.getY();
  57220. }
  57221. int MouseEvent::getDistanceFromDragStart() const throw()
  57222. {
  57223. return mouseDownPos.getDistanceFrom (getPosition());
  57224. }
  57225. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57226. {
  57227. return getPosition() - mouseDownPos;
  57228. }
  57229. int MouseEvent::getLengthOfMousePress() const throw()
  57230. {
  57231. if (mouseDownTime.toMilliseconds() > 0)
  57232. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57233. return 0;
  57234. }
  57235. const Point<int> MouseEvent::getPosition() const throw()
  57236. {
  57237. return Point<int> (x, y);
  57238. }
  57239. int MouseEvent::getScreenX() const
  57240. {
  57241. return getScreenPosition().getX();
  57242. }
  57243. int MouseEvent::getScreenY() const
  57244. {
  57245. return getScreenPosition().getY();
  57246. }
  57247. const Point<int> MouseEvent::getScreenPosition() const
  57248. {
  57249. return eventComponent->localPointToGlobal (Point<int> (x, y));
  57250. }
  57251. int MouseEvent::getMouseDownScreenX() const
  57252. {
  57253. return getMouseDownScreenPosition().getX();
  57254. }
  57255. int MouseEvent::getMouseDownScreenY() const
  57256. {
  57257. return getMouseDownScreenPosition().getY();
  57258. }
  57259. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57260. {
  57261. return eventComponent->localPointToGlobal (mouseDownPos);
  57262. }
  57263. int MouseEvent::doubleClickTimeOutMs = 400;
  57264. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57265. {
  57266. doubleClickTimeOutMs = newTime;
  57267. }
  57268. int MouseEvent::getDoubleClickTimeout() throw()
  57269. {
  57270. return doubleClickTimeOutMs;
  57271. }
  57272. END_JUCE_NAMESPACE
  57273. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57274. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57275. BEGIN_JUCE_NAMESPACE
  57276. class MouseInputSourceInternal : public AsyncUpdater
  57277. {
  57278. public:
  57279. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57280. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57281. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57282. mouseEventCounter (0)
  57283. {
  57284. }
  57285. bool isDragging() const throw()
  57286. {
  57287. return buttonState.isAnyMouseButtonDown();
  57288. }
  57289. Component* getComponentUnderMouse() const
  57290. {
  57291. return static_cast <Component*> (componentUnderMouse);
  57292. }
  57293. const ModifierKeys getCurrentModifiers() const
  57294. {
  57295. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57296. }
  57297. ComponentPeer* getPeer()
  57298. {
  57299. if (! ComponentPeer::isValidPeer (lastPeer))
  57300. lastPeer = 0;
  57301. return lastPeer;
  57302. }
  57303. Component* findComponentAt (const Point<int>& screenPos)
  57304. {
  57305. ComponentPeer* const peer = getPeer();
  57306. if (peer != 0)
  57307. {
  57308. Component* const comp = peer->getComponent();
  57309. const Point<int> relativePos (comp->getLocalPoint (0, screenPos));
  57310. // (the contains() call is needed to test for overlapping desktop windows)
  57311. if (comp->contains (relativePos))
  57312. return comp->getComponentAt (relativePos);
  57313. }
  57314. return 0;
  57315. }
  57316. const Point<int> getScreenPosition() const
  57317. {
  57318. // This needs to return the live position if possible, but it mustn't update the lastScreenPos
  57319. // value, because that can cause continuity problems.
  57320. return unboundedMouseOffset + (isMouseDevice ? MouseInputSource::getCurrentMousePosition()
  57321. : lastScreenPos);
  57322. }
  57323. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const Time& time)
  57324. {
  57325. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57326. comp->internalMouseEnter (source, comp->getLocalPoint (0, screenPos), time);
  57327. }
  57328. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const Time& time)
  57329. {
  57330. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57331. comp->internalMouseExit (source, comp->getLocalPoint (0, screenPos), time);
  57332. }
  57333. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const Time& time)
  57334. {
  57335. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57336. comp->internalMouseMove (source, comp->getLocalPoint (0, screenPos), time);
  57337. }
  57338. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const Time& time)
  57339. {
  57340. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57341. comp->internalMouseDown (source, comp->getLocalPoint (0, screenPos), time);
  57342. }
  57343. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const Time& time)
  57344. {
  57345. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57346. comp->internalMouseDrag (source, comp->getLocalPoint (0, screenPos), time);
  57347. }
  57348. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const Time& time)
  57349. {
  57350. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57351. comp->internalMouseUp (source, comp->getLocalPoint (0, screenPos), time, getCurrentModifiers());
  57352. }
  57353. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const Time& time, float x, float y)
  57354. {
  57355. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->getLocalPoint (0, screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57356. comp->internalMouseWheel (source, comp->getLocalPoint (0, screenPos), time, x, y);
  57357. }
  57358. // (returns true if the button change caused a modal event loop)
  57359. bool setButtons (const Point<int>& screenPos, const Time& time, const ModifierKeys& newButtonState)
  57360. {
  57361. if (buttonState == newButtonState)
  57362. return false;
  57363. setScreenPos (screenPos, time, false);
  57364. // (ignore secondary clicks when there's already a button down)
  57365. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57366. {
  57367. buttonState = newButtonState;
  57368. return false;
  57369. }
  57370. const int lastCounter = mouseEventCounter;
  57371. if (buttonState.isAnyMouseButtonDown())
  57372. {
  57373. Component* const current = getComponentUnderMouse();
  57374. if (current != 0)
  57375. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57376. enableUnboundedMouseMovement (false, false);
  57377. }
  57378. buttonState = newButtonState;
  57379. if (buttonState.isAnyMouseButtonDown())
  57380. {
  57381. Desktop::getInstance().incrementMouseClickCounter();
  57382. Component* const current = getComponentUnderMouse();
  57383. if (current != 0)
  57384. {
  57385. registerMouseDown (screenPos, time, current, buttonState);
  57386. sendMouseDown (current, screenPos, time);
  57387. }
  57388. }
  57389. return lastCounter != mouseEventCounter;
  57390. }
  57391. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const Time& time)
  57392. {
  57393. Component* current = getComponentUnderMouse();
  57394. if (newComponent != current)
  57395. {
  57396. WeakReference<Component> safeNewComp (newComponent);
  57397. const ModifierKeys originalButtonState (buttonState);
  57398. if (current != 0)
  57399. {
  57400. setButtons (screenPos, time, ModifierKeys());
  57401. sendMouseExit (current, screenPos, time);
  57402. buttonState = originalButtonState;
  57403. }
  57404. componentUnderMouse = safeNewComp;
  57405. current = getComponentUnderMouse();
  57406. if (current != 0)
  57407. sendMouseEnter (current, screenPos, time);
  57408. revealCursor (false);
  57409. setButtons (screenPos, time, originalButtonState);
  57410. }
  57411. }
  57412. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const Time& time)
  57413. {
  57414. ModifierKeys::updateCurrentModifiers();
  57415. if (newPeer != lastPeer)
  57416. {
  57417. setComponentUnderMouse (0, screenPos, time);
  57418. lastPeer = newPeer;
  57419. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57420. }
  57421. }
  57422. void setScreenPos (const Point<int>& newScreenPos, const Time& time, const bool forceUpdate)
  57423. {
  57424. if (! isDragging())
  57425. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57426. if (newScreenPos != lastScreenPos || forceUpdate)
  57427. {
  57428. cancelPendingUpdate();
  57429. lastScreenPos = newScreenPos;
  57430. Component* const current = getComponentUnderMouse();
  57431. if (current != 0)
  57432. {
  57433. if (isDragging())
  57434. {
  57435. registerMouseDrag (newScreenPos);
  57436. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57437. if (isUnboundedMouseModeOn)
  57438. handleUnboundedDrag (current);
  57439. }
  57440. else
  57441. {
  57442. sendMouseMove (current, newScreenPos, time);
  57443. }
  57444. }
  57445. revealCursor (false);
  57446. }
  57447. }
  57448. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const Time& time, const ModifierKeys& newMods)
  57449. {
  57450. jassert (newPeer != 0);
  57451. lastTime = time;
  57452. ++mouseEventCounter;
  57453. const Point<int> screenPos (newPeer->localToGlobal (positionWithinPeer));
  57454. if (isDragging() && newMods.isAnyMouseButtonDown())
  57455. {
  57456. setScreenPos (screenPos, time, false);
  57457. }
  57458. else
  57459. {
  57460. setPeer (newPeer, screenPos, time);
  57461. ComponentPeer* peer = getPeer();
  57462. if (peer != 0)
  57463. {
  57464. if (setButtons (screenPos, time, newMods))
  57465. return; // some modal events have been dispatched, so the current event is now out-of-date
  57466. peer = getPeer();
  57467. if (peer != 0)
  57468. setScreenPos (screenPos, time, false);
  57469. }
  57470. }
  57471. }
  57472. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const Time& time, float x, float y)
  57473. {
  57474. jassert (peer != 0);
  57475. lastTime = time;
  57476. ++mouseEventCounter;
  57477. const Point<int> screenPos (peer->localToGlobal (positionWithinPeer));
  57478. setPeer (peer, screenPos, time);
  57479. setScreenPos (screenPos, time, false);
  57480. triggerFakeMove();
  57481. if (! isDragging())
  57482. {
  57483. Component* current = getComponentUnderMouse();
  57484. if (current != 0)
  57485. sendMouseWheel (current, screenPos, time, x, y);
  57486. }
  57487. }
  57488. const Time getLastMouseDownTime() const throw()
  57489. {
  57490. return Time (mouseDowns[0].time);
  57491. }
  57492. const Point<int> getLastMouseDownPosition() const throw()
  57493. {
  57494. return mouseDowns[0].position;
  57495. }
  57496. int getNumberOfMultipleClicks() const throw()
  57497. {
  57498. int numClicks = 0;
  57499. if (mouseDowns[0].time != Time())
  57500. {
  57501. if (! mouseMovedSignificantlySincePressed)
  57502. ++numClicks;
  57503. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57504. {
  57505. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[i], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57506. ++numClicks;
  57507. else
  57508. break;
  57509. }
  57510. }
  57511. return numClicks;
  57512. }
  57513. bool hasMouseMovedSignificantlySincePressed() const throw()
  57514. {
  57515. return mouseMovedSignificantlySincePressed
  57516. || lastTime > mouseDowns[0].time + RelativeTime::milliseconds (300);
  57517. }
  57518. void triggerFakeMove()
  57519. {
  57520. triggerAsyncUpdate();
  57521. }
  57522. void handleAsyncUpdate()
  57523. {
  57524. setScreenPos (lastScreenPos, jmax (lastTime, Time::getCurrentTime()), true);
  57525. }
  57526. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57527. {
  57528. enable = enable && isDragging();
  57529. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57530. if (enable != isUnboundedMouseModeOn)
  57531. {
  57532. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57533. {
  57534. // when released, return the mouse to within the component's bounds
  57535. Component* current = getComponentUnderMouse();
  57536. if (current != 0)
  57537. Desktop::setMousePosition (current->getScreenBounds()
  57538. .getConstrainedPoint (lastScreenPos));
  57539. }
  57540. isUnboundedMouseModeOn = enable;
  57541. unboundedMouseOffset = Point<int>();
  57542. revealCursor (true);
  57543. }
  57544. }
  57545. void handleUnboundedDrag (Component* current)
  57546. {
  57547. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57548. if (! screenArea.contains (lastScreenPos))
  57549. {
  57550. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57551. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57552. Desktop::setMousePosition (componentCentre);
  57553. }
  57554. else if (isCursorVisibleUntilOffscreen
  57555. && (! unboundedMouseOffset.isOrigin())
  57556. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57557. {
  57558. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57559. unboundedMouseOffset = Point<int>();
  57560. }
  57561. }
  57562. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57563. {
  57564. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57565. {
  57566. cursor = MouseCursor::NoCursor;
  57567. forcedUpdate = true;
  57568. }
  57569. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57570. {
  57571. currentCursorHandle = cursor.getHandle();
  57572. cursor.showInWindow (getPeer());
  57573. }
  57574. }
  57575. void hideCursor()
  57576. {
  57577. showMouseCursor (MouseCursor::NoCursor, true);
  57578. }
  57579. void revealCursor (bool forcedUpdate)
  57580. {
  57581. MouseCursor mc (MouseCursor::NormalCursor);
  57582. Component* current = getComponentUnderMouse();
  57583. if (current != 0)
  57584. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57585. showMouseCursor (mc, forcedUpdate);
  57586. }
  57587. const int index;
  57588. const bool isMouseDevice;
  57589. Point<int> lastScreenPos;
  57590. ModifierKeys buttonState;
  57591. private:
  57592. MouseInputSource& source;
  57593. WeakReference<Component> componentUnderMouse;
  57594. ComponentPeer* lastPeer;
  57595. Point<int> unboundedMouseOffset;
  57596. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57597. void* currentCursorHandle;
  57598. int mouseEventCounter;
  57599. struct RecentMouseDown
  57600. {
  57601. RecentMouseDown() : component (0)
  57602. {
  57603. }
  57604. Point<int> position;
  57605. Time time;
  57606. Component* component;
  57607. ModifierKeys buttons;
  57608. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, const int maxTimeBetweenMs) const
  57609. {
  57610. return time - other.time < RelativeTime::milliseconds (maxTimeBetweenMs)
  57611. && abs (position.getX() - other.position.getX()) < 8
  57612. && abs (position.getY() - other.position.getY()) < 8
  57613. && buttons == other.buttons;;
  57614. }
  57615. };
  57616. RecentMouseDown mouseDowns[4];
  57617. bool mouseMovedSignificantlySincePressed;
  57618. Time lastTime;
  57619. void registerMouseDown (const Point<int>& screenPos, const Time& time,
  57620. Component* const component, const ModifierKeys& modifiers) throw()
  57621. {
  57622. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57623. mouseDowns[i] = mouseDowns[i - 1];
  57624. mouseDowns[0].position = screenPos;
  57625. mouseDowns[0].time = time;
  57626. mouseDowns[0].component = component;
  57627. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  57628. mouseMovedSignificantlySincePressed = false;
  57629. }
  57630. void registerMouseDrag (const Point<int>& screenPos) throw()
  57631. {
  57632. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57633. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57634. }
  57635. JUCE_DECLARE_NON_COPYABLE (MouseInputSourceInternal);
  57636. };
  57637. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57638. {
  57639. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57640. }
  57641. MouseInputSource::~MouseInputSource()
  57642. {
  57643. }
  57644. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57645. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57646. bool MouseInputSource::canHover() const { return isMouse(); }
  57647. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57648. int MouseInputSource::getIndex() const { return pimpl->index; }
  57649. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57650. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57651. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57652. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57653. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57654. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57655. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57656. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57657. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57658. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57659. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57660. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57661. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57662. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57663. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57664. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57665. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57666. {
  57667. pimpl->handleEvent (peer, positionWithinPeer, Time (time), mods.withOnlyMouseButtons());
  57668. }
  57669. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57670. {
  57671. pimpl->handleWheel (peer, positionWithinPeer, Time (time), x, y);
  57672. }
  57673. END_JUCE_NAMESPACE
  57674. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57675. /*** Start of inlined file: juce_MouseListener.cpp ***/
  57676. BEGIN_JUCE_NAMESPACE
  57677. void MouseListener::mouseEnter (const MouseEvent&)
  57678. {
  57679. }
  57680. void MouseListener::mouseExit (const MouseEvent&)
  57681. {
  57682. }
  57683. void MouseListener::mouseDown (const MouseEvent&)
  57684. {
  57685. }
  57686. void MouseListener::mouseUp (const MouseEvent&)
  57687. {
  57688. }
  57689. void MouseListener::mouseDrag (const MouseEvent&)
  57690. {
  57691. }
  57692. void MouseListener::mouseMove (const MouseEvent&)
  57693. {
  57694. }
  57695. void MouseListener::mouseDoubleClick (const MouseEvent&)
  57696. {
  57697. }
  57698. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  57699. {
  57700. }
  57701. END_JUCE_NAMESPACE
  57702. /*** End of inlined file: juce_MouseListener.cpp ***/
  57703. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57704. BEGIN_JUCE_NAMESPACE
  57705. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  57706. const String& buttonTextWhenTrue,
  57707. const String& buttonTextWhenFalse)
  57708. : PropertyComponent (name),
  57709. onText (buttonTextWhenTrue),
  57710. offText (buttonTextWhenFalse)
  57711. {
  57712. addAndMakeVisible (&button);
  57713. button.setClickingTogglesState (false);
  57714. button.addListener (this);
  57715. }
  57716. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  57717. const String& name,
  57718. const String& buttonText)
  57719. : PropertyComponent (name),
  57720. onText (buttonText),
  57721. offText (buttonText)
  57722. {
  57723. addAndMakeVisible (&button);
  57724. button.setClickingTogglesState (false);
  57725. button.setButtonText (buttonText);
  57726. button.getToggleStateValue().referTo (valueToControl);
  57727. button.setClickingTogglesState (true);
  57728. }
  57729. BooleanPropertyComponent::~BooleanPropertyComponent()
  57730. {
  57731. }
  57732. void BooleanPropertyComponent::setState (const bool newState)
  57733. {
  57734. button.setToggleState (newState, true);
  57735. }
  57736. bool BooleanPropertyComponent::getState() const
  57737. {
  57738. return button.getToggleState();
  57739. }
  57740. void BooleanPropertyComponent::paint (Graphics& g)
  57741. {
  57742. PropertyComponent::paint (g);
  57743. g.setColour (Colours::white);
  57744. g.fillRect (button.getBounds());
  57745. g.setColour (findColour (ComboBox::outlineColourId));
  57746. g.drawRect (button.getBounds());
  57747. }
  57748. void BooleanPropertyComponent::refresh()
  57749. {
  57750. button.setToggleState (getState(), false);
  57751. button.setButtonText (button.getToggleState() ? onText : offText);
  57752. }
  57753. void BooleanPropertyComponent::buttonClicked (Button*)
  57754. {
  57755. setState (! getState());
  57756. }
  57757. END_JUCE_NAMESPACE
  57758. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  57759. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57760. BEGIN_JUCE_NAMESPACE
  57761. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  57762. const bool triggerOnMouseDown)
  57763. : PropertyComponent (name)
  57764. {
  57765. addAndMakeVisible (&button);
  57766. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  57767. button.addListener (this);
  57768. }
  57769. ButtonPropertyComponent::~ButtonPropertyComponent()
  57770. {
  57771. }
  57772. void ButtonPropertyComponent::refresh()
  57773. {
  57774. button.setButtonText (getButtonText());
  57775. }
  57776. void ButtonPropertyComponent::buttonClicked (Button*)
  57777. {
  57778. buttonClicked();
  57779. }
  57780. END_JUCE_NAMESPACE
  57781. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  57782. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57783. BEGIN_JUCE_NAMESPACE
  57784. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  57785. public ValueListener
  57786. {
  57787. public:
  57788. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  57789. : sourceValue (sourceValue_),
  57790. mappings (mappings_)
  57791. {
  57792. sourceValue.addListener (this);
  57793. }
  57794. ~RemapperValueSource() {}
  57795. const var getValue() const
  57796. {
  57797. return mappings.indexOf (sourceValue.getValue()) + 1;
  57798. }
  57799. void setValue (const var& newValue)
  57800. {
  57801. const var remappedVal (mappings [(int) newValue - 1]);
  57802. if (remappedVal != sourceValue)
  57803. sourceValue = remappedVal;
  57804. }
  57805. void valueChanged (Value&)
  57806. {
  57807. sendChangeMessage (true);
  57808. }
  57809. protected:
  57810. Value sourceValue;
  57811. Array<var> mappings;
  57812. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RemapperValueSource);
  57813. };
  57814. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  57815. : PropertyComponent (name),
  57816. isCustomClass (true)
  57817. {
  57818. }
  57819. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  57820. const String& name,
  57821. const StringArray& choices_,
  57822. const Array <var>& correspondingValues)
  57823. : PropertyComponent (name),
  57824. choices (choices_),
  57825. isCustomClass (false)
  57826. {
  57827. // The array of corresponding values must contain one value for each of the items in
  57828. // the choices array!
  57829. jassert (correspondingValues.size() == choices.size());
  57830. createComboBox();
  57831. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  57832. }
  57833. ChoicePropertyComponent::~ChoicePropertyComponent()
  57834. {
  57835. }
  57836. void ChoicePropertyComponent::createComboBox()
  57837. {
  57838. addAndMakeVisible (&comboBox);
  57839. for (int i = 0; i < choices.size(); ++i)
  57840. {
  57841. if (choices[i].isNotEmpty())
  57842. comboBox.addItem (choices[i], i + 1);
  57843. else
  57844. comboBox.addSeparator();
  57845. }
  57846. comboBox.setEditableText (false);
  57847. }
  57848. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  57849. {
  57850. jassertfalse; // you need to override this method in your subclass!
  57851. }
  57852. int ChoicePropertyComponent::getIndex() const
  57853. {
  57854. jassertfalse; // you need to override this method in your subclass!
  57855. return -1;
  57856. }
  57857. const StringArray& ChoicePropertyComponent::getChoices() const
  57858. {
  57859. return choices;
  57860. }
  57861. void ChoicePropertyComponent::refresh()
  57862. {
  57863. if (isCustomClass)
  57864. {
  57865. if (! comboBox.isVisible())
  57866. {
  57867. createComboBox();
  57868. comboBox.addListener (this);
  57869. }
  57870. comboBox.setSelectedId (getIndex() + 1, true);
  57871. }
  57872. }
  57873. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  57874. {
  57875. if (isCustomClass)
  57876. {
  57877. const int newIndex = comboBox.getSelectedId() - 1;
  57878. if (newIndex != getIndex())
  57879. setIndex (newIndex);
  57880. }
  57881. }
  57882. END_JUCE_NAMESPACE
  57883. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  57884. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  57885. BEGIN_JUCE_NAMESPACE
  57886. PropertyComponent::PropertyComponent (const String& name,
  57887. const int preferredHeight_)
  57888. : Component (name),
  57889. preferredHeight (preferredHeight_)
  57890. {
  57891. jassert (name.isNotEmpty());
  57892. }
  57893. PropertyComponent::~PropertyComponent()
  57894. {
  57895. }
  57896. void PropertyComponent::paint (Graphics& g)
  57897. {
  57898. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  57899. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  57900. }
  57901. void PropertyComponent::resized()
  57902. {
  57903. if (getNumChildComponents() > 0)
  57904. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  57905. }
  57906. void PropertyComponent::enablementChanged()
  57907. {
  57908. repaint();
  57909. }
  57910. END_JUCE_NAMESPACE
  57911. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  57912. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  57913. BEGIN_JUCE_NAMESPACE
  57914. class PropertySectionComponent : public Component
  57915. {
  57916. public:
  57917. PropertySectionComponent (const String& sectionTitle,
  57918. const Array <PropertyComponent*>& newProperties,
  57919. const bool sectionIsOpen_)
  57920. : Component (sectionTitle),
  57921. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  57922. sectionIsOpen (sectionIsOpen_)
  57923. {
  57924. propertyComps.addArray (newProperties);
  57925. for (int i = propertyComps.size(); --i >= 0;)
  57926. {
  57927. addAndMakeVisible (propertyComps.getUnchecked(i));
  57928. propertyComps.getUnchecked(i)->refresh();
  57929. }
  57930. }
  57931. ~PropertySectionComponent()
  57932. {
  57933. propertyComps.clear();
  57934. }
  57935. void paint (Graphics& g)
  57936. {
  57937. if (titleHeight > 0)
  57938. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  57939. }
  57940. void resized()
  57941. {
  57942. int y = titleHeight;
  57943. for (int i = 0; i < propertyComps.size(); ++i)
  57944. {
  57945. PropertyComponent* const pec = propertyComps.getUnchecked (i);
  57946. pec->setBounds (1, y, getWidth() - 2, pec->getPreferredHeight());
  57947. y = pec->getBottom();
  57948. }
  57949. }
  57950. int getPreferredHeight() const
  57951. {
  57952. int y = titleHeight;
  57953. if (isOpen())
  57954. {
  57955. for (int i = propertyComps.size(); --i >= 0;)
  57956. y += propertyComps.getUnchecked(i)->getPreferredHeight();
  57957. }
  57958. return y;
  57959. }
  57960. void setOpen (const bool open)
  57961. {
  57962. if (sectionIsOpen != open)
  57963. {
  57964. sectionIsOpen = open;
  57965. for (int i = propertyComps.size(); --i >= 0;)
  57966. propertyComps.getUnchecked(i)->setVisible (open);
  57967. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  57968. if (pp != 0)
  57969. pp->resized();
  57970. }
  57971. }
  57972. bool isOpen() const
  57973. {
  57974. return sectionIsOpen;
  57975. }
  57976. void refreshAll() const
  57977. {
  57978. for (int i = propertyComps.size(); --i >= 0;)
  57979. propertyComps.getUnchecked (i)->refresh();
  57980. }
  57981. void mouseUp (const MouseEvent& e)
  57982. {
  57983. if (e.getMouseDownX() < titleHeight
  57984. && e.x < titleHeight
  57985. && e.y < titleHeight
  57986. && e.getNumberOfClicks() != 2)
  57987. {
  57988. setOpen (! isOpen());
  57989. }
  57990. }
  57991. void mouseDoubleClick (const MouseEvent& e)
  57992. {
  57993. if (e.y < titleHeight)
  57994. setOpen (! isOpen());
  57995. }
  57996. private:
  57997. OwnedArray <PropertyComponent> propertyComps;
  57998. int titleHeight;
  57999. bool sectionIsOpen;
  58000. JUCE_DECLARE_NON_COPYABLE (PropertySectionComponent);
  58001. };
  58002. class PropertyPanel::PropertyHolderComponent : public Component
  58003. {
  58004. public:
  58005. PropertyHolderComponent() {}
  58006. void paint (Graphics&) {}
  58007. void updateLayout (int width)
  58008. {
  58009. int y = 0;
  58010. for (int i = 0; i < sections.size(); ++i)
  58011. {
  58012. PropertySectionComponent* const section = sections.getUnchecked(i);
  58013. section->setBounds (0, y, width, section->getPreferredHeight());
  58014. y = section->getBottom();
  58015. }
  58016. setSize (width, y);
  58017. repaint();
  58018. }
  58019. void refreshAll() const
  58020. {
  58021. for (int i = 0; i < sections.size(); ++i)
  58022. sections.getUnchecked(i)->refreshAll();
  58023. }
  58024. void clear()
  58025. {
  58026. sections.clear();
  58027. }
  58028. void addSection (PropertySectionComponent* newSection)
  58029. {
  58030. sections.add (newSection);
  58031. addAndMakeVisible (newSection, 0);
  58032. }
  58033. int getNumSections() const throw() { return sections.size(); }
  58034. PropertySectionComponent* getSection (const int index) const { return sections [index]; }
  58035. private:
  58036. OwnedArray<PropertySectionComponent> sections;
  58037. JUCE_DECLARE_NON_COPYABLE (PropertyHolderComponent);
  58038. };
  58039. PropertyPanel::PropertyPanel()
  58040. {
  58041. messageWhenEmpty = TRANS("(nothing selected)");
  58042. addAndMakeVisible (&viewport);
  58043. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58044. viewport.setFocusContainer (true);
  58045. }
  58046. PropertyPanel::~PropertyPanel()
  58047. {
  58048. clear();
  58049. }
  58050. void PropertyPanel::paint (Graphics& g)
  58051. {
  58052. if (propertyHolderComponent->getNumSections() == 0)
  58053. {
  58054. g.setColour (Colours::black.withAlpha (0.5f));
  58055. g.setFont (14.0f);
  58056. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58057. Justification::centred, true);
  58058. }
  58059. }
  58060. void PropertyPanel::resized()
  58061. {
  58062. viewport.setBounds (getLocalBounds());
  58063. updatePropHolderLayout();
  58064. }
  58065. void PropertyPanel::clear()
  58066. {
  58067. if (propertyHolderComponent->getNumSections() > 0)
  58068. {
  58069. propertyHolderComponent->clear();
  58070. repaint();
  58071. }
  58072. }
  58073. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58074. {
  58075. if (propertyHolderComponent->getNumSections() == 0)
  58076. repaint();
  58077. propertyHolderComponent->addSection (new PropertySectionComponent (String::empty, newProperties, true));
  58078. updatePropHolderLayout();
  58079. }
  58080. void PropertyPanel::addSection (const String& sectionTitle,
  58081. const Array <PropertyComponent*>& newProperties,
  58082. const bool shouldBeOpen)
  58083. {
  58084. jassert (sectionTitle.isNotEmpty());
  58085. if (propertyHolderComponent->getNumSections() == 0)
  58086. repaint();
  58087. propertyHolderComponent->addSection (new PropertySectionComponent (sectionTitle, newProperties, shouldBeOpen));
  58088. updatePropHolderLayout();
  58089. }
  58090. void PropertyPanel::updatePropHolderLayout() const
  58091. {
  58092. const int maxWidth = viewport.getMaximumVisibleWidth();
  58093. propertyHolderComponent->updateLayout (maxWidth);
  58094. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58095. if (maxWidth != newMaxWidth)
  58096. {
  58097. // need to do this twice because of scrollbars changing the size, etc.
  58098. propertyHolderComponent->updateLayout (newMaxWidth);
  58099. }
  58100. }
  58101. void PropertyPanel::refreshAll() const
  58102. {
  58103. propertyHolderComponent->refreshAll();
  58104. }
  58105. const StringArray PropertyPanel::getSectionNames() const
  58106. {
  58107. StringArray s;
  58108. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58109. {
  58110. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58111. if (section->getName().isNotEmpty())
  58112. s.add (section->getName());
  58113. }
  58114. return s;
  58115. }
  58116. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58117. {
  58118. int index = 0;
  58119. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58120. {
  58121. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58122. if (section->getName().isNotEmpty())
  58123. {
  58124. if (index == sectionIndex)
  58125. return section->isOpen();
  58126. ++index;
  58127. }
  58128. }
  58129. return false;
  58130. }
  58131. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58132. {
  58133. int index = 0;
  58134. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58135. {
  58136. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58137. if (section->getName().isNotEmpty())
  58138. {
  58139. if (index == sectionIndex)
  58140. {
  58141. section->setOpen (shouldBeOpen);
  58142. break;
  58143. }
  58144. ++index;
  58145. }
  58146. }
  58147. }
  58148. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58149. {
  58150. int index = 0;
  58151. for (int i = 0; i < propertyHolderComponent->getNumSections(); ++i)
  58152. {
  58153. PropertySectionComponent* const section = propertyHolderComponent->getSection (i);
  58154. if (section->getName().isNotEmpty())
  58155. {
  58156. if (index == sectionIndex)
  58157. {
  58158. section->setEnabled (shouldBeEnabled);
  58159. break;
  58160. }
  58161. ++index;
  58162. }
  58163. }
  58164. }
  58165. XmlElement* PropertyPanel::getOpennessState() const
  58166. {
  58167. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58168. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58169. const StringArray sections (getSectionNames());
  58170. for (int i = 0; i < sections.size(); ++i)
  58171. {
  58172. if (sections[i].isNotEmpty())
  58173. {
  58174. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58175. e->setAttribute ("name", sections[i]);
  58176. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58177. }
  58178. }
  58179. return xml;
  58180. }
  58181. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58182. {
  58183. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58184. {
  58185. const StringArray sections (getSectionNames());
  58186. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58187. {
  58188. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58189. e->getBoolAttribute ("open"));
  58190. }
  58191. viewport.setViewPosition (viewport.getViewPositionX(),
  58192. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58193. }
  58194. }
  58195. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58196. {
  58197. if (messageWhenEmpty != newMessage)
  58198. {
  58199. messageWhenEmpty = newMessage;
  58200. repaint();
  58201. }
  58202. }
  58203. const String& PropertyPanel::getMessageWhenEmpty() const
  58204. {
  58205. return messageWhenEmpty;
  58206. }
  58207. END_JUCE_NAMESPACE
  58208. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58209. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58210. BEGIN_JUCE_NAMESPACE
  58211. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58212. const double rangeMin,
  58213. const double rangeMax,
  58214. const double interval,
  58215. const double skewFactor)
  58216. : PropertyComponent (name)
  58217. {
  58218. addAndMakeVisible (&slider);
  58219. slider.setRange (rangeMin, rangeMax, interval);
  58220. slider.setSkewFactor (skewFactor);
  58221. slider.setSliderStyle (Slider::LinearBar);
  58222. slider.addListener (this);
  58223. }
  58224. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58225. const String& name,
  58226. const double rangeMin,
  58227. const double rangeMax,
  58228. const double interval,
  58229. const double skewFactor)
  58230. : PropertyComponent (name)
  58231. {
  58232. addAndMakeVisible (&slider);
  58233. slider.setRange (rangeMin, rangeMax, interval);
  58234. slider.setSkewFactor (skewFactor);
  58235. slider.setSliderStyle (Slider::LinearBar);
  58236. slider.getValueObject().referTo (valueToControl);
  58237. }
  58238. SliderPropertyComponent::~SliderPropertyComponent()
  58239. {
  58240. }
  58241. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58242. {
  58243. }
  58244. double SliderPropertyComponent::getValue() const
  58245. {
  58246. return slider.getValue();
  58247. }
  58248. void SliderPropertyComponent::refresh()
  58249. {
  58250. slider.setValue (getValue(), false);
  58251. }
  58252. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58253. {
  58254. if (getValue() != slider.getValue())
  58255. setValue (slider.getValue());
  58256. }
  58257. END_JUCE_NAMESPACE
  58258. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58259. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58260. BEGIN_JUCE_NAMESPACE
  58261. class TextPropLabel : public Label
  58262. {
  58263. public:
  58264. TextPropLabel (TextPropertyComponent& owner_,
  58265. const int maxChars_, const bool isMultiline_)
  58266. : Label (String::empty, String::empty),
  58267. owner (owner_),
  58268. maxChars (maxChars_),
  58269. isMultiline (isMultiline_)
  58270. {
  58271. setEditable (true, true, false);
  58272. setColour (backgroundColourId, Colours::white);
  58273. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58274. }
  58275. TextEditor* createEditorComponent()
  58276. {
  58277. TextEditor* const textEditor = Label::createEditorComponent();
  58278. textEditor->setInputRestrictions (maxChars);
  58279. if (isMultiline)
  58280. {
  58281. textEditor->setMultiLine (true, true);
  58282. textEditor->setReturnKeyStartsNewLine (true);
  58283. }
  58284. return textEditor;
  58285. }
  58286. void textWasEdited()
  58287. {
  58288. owner.textWasEdited();
  58289. }
  58290. private:
  58291. TextPropertyComponent& owner;
  58292. int maxChars;
  58293. bool isMultiline;
  58294. };
  58295. TextPropertyComponent::TextPropertyComponent (const String& name,
  58296. const int maxNumChars,
  58297. const bool isMultiLine)
  58298. : PropertyComponent (name)
  58299. {
  58300. createEditor (maxNumChars, isMultiLine);
  58301. }
  58302. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58303. const String& name,
  58304. const int maxNumChars,
  58305. const bool isMultiLine)
  58306. : PropertyComponent (name)
  58307. {
  58308. createEditor (maxNumChars, isMultiLine);
  58309. textEditor->getTextValue().referTo (valueToControl);
  58310. }
  58311. TextPropertyComponent::~TextPropertyComponent()
  58312. {
  58313. }
  58314. void TextPropertyComponent::setText (const String& newText)
  58315. {
  58316. textEditor->setText (newText, true);
  58317. }
  58318. const String TextPropertyComponent::getText() const
  58319. {
  58320. return textEditor->getText();
  58321. }
  58322. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58323. {
  58324. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58325. if (isMultiLine)
  58326. {
  58327. textEditor->setJustificationType (Justification::topLeft);
  58328. preferredHeight = 120;
  58329. }
  58330. }
  58331. void TextPropertyComponent::refresh()
  58332. {
  58333. textEditor->setText (getText(), false);
  58334. }
  58335. void TextPropertyComponent::textWasEdited()
  58336. {
  58337. const String newText (textEditor->getText());
  58338. if (getText() != newText)
  58339. setText (newText);
  58340. }
  58341. END_JUCE_NAMESPACE
  58342. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58343. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58344. BEGIN_JUCE_NAMESPACE
  58345. class SimpleDeviceManagerInputLevelMeter : public Component,
  58346. public Timer
  58347. {
  58348. public:
  58349. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58350. : manager (manager_),
  58351. level (0)
  58352. {
  58353. startTimer (50);
  58354. manager->enableInputLevelMeasurement (true);
  58355. }
  58356. ~SimpleDeviceManagerInputLevelMeter()
  58357. {
  58358. manager->enableInputLevelMeasurement (false);
  58359. }
  58360. void timerCallback()
  58361. {
  58362. const float newLevel = (float) manager->getCurrentInputLevel();
  58363. if (std::abs (level - newLevel) > 0.005f)
  58364. {
  58365. level = newLevel;
  58366. repaint();
  58367. }
  58368. }
  58369. void paint (Graphics& g)
  58370. {
  58371. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58372. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58373. }
  58374. private:
  58375. AudioDeviceManager* const manager;
  58376. float level;
  58377. JUCE_DECLARE_NON_COPYABLE (SimpleDeviceManagerInputLevelMeter);
  58378. };
  58379. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58380. public ListBoxModel
  58381. {
  58382. public:
  58383. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58384. const String& noItemsMessage_,
  58385. const int minNumber_,
  58386. const int maxNumber_)
  58387. : ListBox (String::empty, 0),
  58388. deviceManager (deviceManager_),
  58389. noItemsMessage (noItemsMessage_),
  58390. minNumber (minNumber_),
  58391. maxNumber (maxNumber_)
  58392. {
  58393. items = MidiInput::getDevices();
  58394. setModel (this);
  58395. setOutlineThickness (1);
  58396. }
  58397. ~MidiInputSelectorComponentListBox()
  58398. {
  58399. }
  58400. int getNumRows()
  58401. {
  58402. return items.size();
  58403. }
  58404. void paintListBoxItem (int row,
  58405. Graphics& g,
  58406. int width, int height,
  58407. bool rowIsSelected)
  58408. {
  58409. if (isPositiveAndBelow (row, items.size()))
  58410. {
  58411. if (rowIsSelected)
  58412. g.fillAll (findColour (TextEditor::highlightColourId)
  58413. .withMultipliedAlpha (0.3f));
  58414. const String item (items [row]);
  58415. bool enabled = deviceManager.isMidiInputEnabled (item);
  58416. const int x = getTickX();
  58417. const float tickW = height * 0.75f;
  58418. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58419. enabled, true, true, false);
  58420. g.setFont (height * 0.6f);
  58421. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58422. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58423. }
  58424. }
  58425. void listBoxItemClicked (int row, const MouseEvent& e)
  58426. {
  58427. selectRow (row);
  58428. if (e.x < getTickX())
  58429. flipEnablement (row);
  58430. }
  58431. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58432. {
  58433. flipEnablement (row);
  58434. }
  58435. void returnKeyPressed (int row)
  58436. {
  58437. flipEnablement (row);
  58438. }
  58439. void paint (Graphics& g)
  58440. {
  58441. ListBox::paint (g);
  58442. if (items.size() == 0)
  58443. {
  58444. g.setColour (Colours::grey);
  58445. g.setFont (13.0f);
  58446. g.drawText (noItemsMessage,
  58447. 0, 0, getWidth(), getHeight() / 2,
  58448. Justification::centred, true);
  58449. }
  58450. }
  58451. int getBestHeight (const int preferredHeight)
  58452. {
  58453. const int extra = getOutlineThickness() * 2;
  58454. return jmax (getRowHeight() * 2 + extra,
  58455. jmin (getRowHeight() * getNumRows() + extra,
  58456. preferredHeight));
  58457. }
  58458. private:
  58459. AudioDeviceManager& deviceManager;
  58460. const String noItemsMessage;
  58461. StringArray items;
  58462. int minNumber, maxNumber;
  58463. void flipEnablement (const int row)
  58464. {
  58465. if (isPositiveAndBelow (row, items.size()))
  58466. {
  58467. const String item (items [row]);
  58468. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58469. }
  58470. }
  58471. int getTickX() const
  58472. {
  58473. return getRowHeight() + 5;
  58474. }
  58475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox);
  58476. };
  58477. class AudioDeviceSettingsPanel : public Component,
  58478. public ChangeListener,
  58479. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58480. public ButtonListener
  58481. {
  58482. public:
  58483. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58484. AudioIODeviceType::DeviceSetupDetails& setup_,
  58485. const bool hideAdvancedOptionsWithButton)
  58486. : type (type_),
  58487. setup (setup_)
  58488. {
  58489. if (hideAdvancedOptionsWithButton)
  58490. {
  58491. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58492. showAdvancedSettingsButton->addListener (this);
  58493. }
  58494. type->scanForDevices();
  58495. setup.manager->addChangeListener (this);
  58496. changeListenerCallback (0);
  58497. }
  58498. ~AudioDeviceSettingsPanel()
  58499. {
  58500. setup.manager->removeChangeListener (this);
  58501. }
  58502. void resized()
  58503. {
  58504. const int lx = proportionOfWidth (0.35f);
  58505. const int w = proportionOfWidth (0.4f);
  58506. const int h = 24;
  58507. const int space = 6;
  58508. const int dh = h + space;
  58509. int y = 0;
  58510. if (outputDeviceDropDown != 0)
  58511. {
  58512. outputDeviceDropDown->setBounds (lx, y, w, h);
  58513. if (testButton != 0)
  58514. testButton->setBounds (proportionOfWidth (0.77f),
  58515. outputDeviceDropDown->getY(),
  58516. proportionOfWidth (0.18f),
  58517. h);
  58518. y += dh;
  58519. }
  58520. if (inputDeviceDropDown != 0)
  58521. {
  58522. inputDeviceDropDown->setBounds (lx, y, w, h);
  58523. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58524. inputDeviceDropDown->getY(),
  58525. proportionOfWidth (0.18f),
  58526. h);
  58527. y += dh;
  58528. }
  58529. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58530. if (outputChanList != 0)
  58531. {
  58532. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58533. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58534. y += bh + space;
  58535. }
  58536. if (inputChanList != 0)
  58537. {
  58538. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58539. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58540. y += bh + space;
  58541. }
  58542. y += space * 2;
  58543. if (showAdvancedSettingsButton != 0)
  58544. {
  58545. showAdvancedSettingsButton->changeWidthToFitText (h);
  58546. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  58547. }
  58548. if (sampleRateDropDown != 0)
  58549. {
  58550. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  58551. || ! showAdvancedSettingsButton->isVisible());
  58552. sampleRateDropDown->setBounds (lx, y, w, h);
  58553. y += dh;
  58554. }
  58555. if (bufferSizeDropDown != 0)
  58556. {
  58557. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  58558. || ! showAdvancedSettingsButton->isVisible());
  58559. bufferSizeDropDown->setBounds (lx, y, w, h);
  58560. y += dh;
  58561. }
  58562. if (showUIButton != 0)
  58563. {
  58564. showUIButton->setVisible (showAdvancedSettingsButton == 0
  58565. || ! showAdvancedSettingsButton->isVisible());
  58566. showUIButton->changeWidthToFitText (h);
  58567. showUIButton->setTopLeftPosition (lx, y);
  58568. }
  58569. }
  58570. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  58571. {
  58572. if (comboBoxThatHasChanged == 0)
  58573. return;
  58574. AudioDeviceManager::AudioDeviceSetup config;
  58575. setup.manager->getAudioDeviceSetup (config);
  58576. String error;
  58577. if (comboBoxThatHasChanged == outputDeviceDropDown
  58578. || comboBoxThatHasChanged == inputDeviceDropDown)
  58579. {
  58580. if (outputDeviceDropDown != 0)
  58581. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58582. : outputDeviceDropDown->getText();
  58583. if (inputDeviceDropDown != 0)
  58584. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  58585. : inputDeviceDropDown->getText();
  58586. if (! type->hasSeparateInputsAndOutputs())
  58587. config.inputDeviceName = config.outputDeviceName;
  58588. if (comboBoxThatHasChanged == inputDeviceDropDown)
  58589. config.useDefaultInputChannels = true;
  58590. else
  58591. config.useDefaultOutputChannels = true;
  58592. error = setup.manager->setAudioDeviceSetup (config, true);
  58593. showCorrectDeviceName (inputDeviceDropDown, true);
  58594. showCorrectDeviceName (outputDeviceDropDown, false);
  58595. updateControlPanelButton();
  58596. resized();
  58597. }
  58598. else if (comboBoxThatHasChanged == sampleRateDropDown)
  58599. {
  58600. if (sampleRateDropDown->getSelectedId() > 0)
  58601. {
  58602. config.sampleRate = sampleRateDropDown->getSelectedId();
  58603. error = setup.manager->setAudioDeviceSetup (config, true);
  58604. }
  58605. }
  58606. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  58607. {
  58608. if (bufferSizeDropDown->getSelectedId() > 0)
  58609. {
  58610. config.bufferSize = bufferSizeDropDown->getSelectedId();
  58611. error = setup.manager->setAudioDeviceSetup (config, true);
  58612. }
  58613. }
  58614. if (error.isNotEmpty())
  58615. {
  58616. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  58617. "Error when trying to open audio device!",
  58618. error);
  58619. }
  58620. }
  58621. void buttonClicked (Button* button)
  58622. {
  58623. if (button == showAdvancedSettingsButton)
  58624. {
  58625. showAdvancedSettingsButton->setVisible (false);
  58626. resized();
  58627. }
  58628. else if (button == showUIButton)
  58629. {
  58630. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  58631. if (device != 0 && device->showControlPanel())
  58632. {
  58633. setup.manager->closeAudioDevice();
  58634. setup.manager->restartLastAudioDevice();
  58635. getTopLevelComponent()->toFront (true);
  58636. }
  58637. }
  58638. else if (button == testButton && testButton != 0)
  58639. {
  58640. setup.manager->playTestSound();
  58641. }
  58642. }
  58643. void updateControlPanelButton()
  58644. {
  58645. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58646. showUIButton = 0;
  58647. if (currentDevice != 0 && currentDevice->hasControlPanel())
  58648. {
  58649. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  58650. TRANS ("opens the device's own control panel")));
  58651. showUIButton->addListener (this);
  58652. }
  58653. resized();
  58654. }
  58655. void changeListenerCallback (ChangeBroadcaster*)
  58656. {
  58657. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58658. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  58659. {
  58660. if (outputDeviceDropDown == 0)
  58661. {
  58662. outputDeviceDropDown = new ComboBox (String::empty);
  58663. outputDeviceDropDown->addListener (this);
  58664. addAndMakeVisible (outputDeviceDropDown);
  58665. outputDeviceLabel = new Label (String::empty,
  58666. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  58667. : TRANS ("device:"));
  58668. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  58669. if (setup.maxNumOutputChannels > 0)
  58670. {
  58671. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  58672. testButton->addListener (this);
  58673. }
  58674. }
  58675. addNamesToDeviceBox (*outputDeviceDropDown, false);
  58676. }
  58677. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  58678. {
  58679. if (inputDeviceDropDown == 0)
  58680. {
  58681. inputDeviceDropDown = new ComboBox (String::empty);
  58682. inputDeviceDropDown->addListener (this);
  58683. addAndMakeVisible (inputDeviceDropDown);
  58684. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  58685. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  58686. addAndMakeVisible (inputLevelMeter
  58687. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  58688. }
  58689. addNamesToDeviceBox (*inputDeviceDropDown, true);
  58690. }
  58691. updateControlPanelButton();
  58692. showCorrectDeviceName (inputDeviceDropDown, true);
  58693. showCorrectDeviceName (outputDeviceDropDown, false);
  58694. if (currentDevice != 0)
  58695. {
  58696. if (setup.maxNumOutputChannels > 0
  58697. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  58698. {
  58699. if (outputChanList == 0)
  58700. {
  58701. addAndMakeVisible (outputChanList
  58702. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  58703. TRANS ("(no audio output channels found)")));
  58704. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  58705. outputChanLabel->attachToComponent (outputChanList, true);
  58706. }
  58707. outputChanList->refresh();
  58708. }
  58709. else
  58710. {
  58711. outputChanLabel = 0;
  58712. outputChanList = 0;
  58713. }
  58714. if (setup.maxNumInputChannels > 0
  58715. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  58716. {
  58717. if (inputChanList == 0)
  58718. {
  58719. addAndMakeVisible (inputChanList
  58720. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  58721. TRANS ("(no audio input channels found)")));
  58722. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  58723. inputChanLabel->attachToComponent (inputChanList, true);
  58724. }
  58725. inputChanList->refresh();
  58726. }
  58727. else
  58728. {
  58729. inputChanLabel = 0;
  58730. inputChanList = 0;
  58731. }
  58732. // sample rate..
  58733. {
  58734. if (sampleRateDropDown == 0)
  58735. {
  58736. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  58737. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  58738. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  58739. }
  58740. else
  58741. {
  58742. sampleRateDropDown->clear();
  58743. sampleRateDropDown->removeListener (this);
  58744. }
  58745. const int numRates = currentDevice->getNumSampleRates();
  58746. for (int i = 0; i < numRates; ++i)
  58747. {
  58748. const int rate = roundToInt (currentDevice->getSampleRate (i));
  58749. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  58750. }
  58751. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  58752. sampleRateDropDown->addListener (this);
  58753. }
  58754. // buffer size
  58755. {
  58756. if (bufferSizeDropDown == 0)
  58757. {
  58758. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  58759. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  58760. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  58761. }
  58762. else
  58763. {
  58764. bufferSizeDropDown->clear();
  58765. bufferSizeDropDown->removeListener (this);
  58766. }
  58767. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  58768. double currentRate = currentDevice->getCurrentSampleRate();
  58769. if (currentRate == 0)
  58770. currentRate = 48000.0;
  58771. for (int i = 0; i < numBufferSizes; ++i)
  58772. {
  58773. const int bs = currentDevice->getBufferSizeSamples (i);
  58774. bufferSizeDropDown->addItem (String (bs)
  58775. + " samples ("
  58776. + String (bs * 1000.0 / currentRate, 1)
  58777. + " ms)",
  58778. bs);
  58779. }
  58780. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  58781. bufferSizeDropDown->addListener (this);
  58782. }
  58783. }
  58784. else
  58785. {
  58786. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  58787. sampleRateLabel = 0;
  58788. bufferSizeLabel = 0;
  58789. sampleRateDropDown = 0;
  58790. bufferSizeDropDown = 0;
  58791. if (outputDeviceDropDown != 0)
  58792. outputDeviceDropDown->setSelectedId (-1, true);
  58793. if (inputDeviceDropDown != 0)
  58794. inputDeviceDropDown->setSelectedId (-1, true);
  58795. }
  58796. resized();
  58797. setSize (getWidth(), getLowestY() + 4);
  58798. }
  58799. private:
  58800. AudioIODeviceType* const type;
  58801. const AudioIODeviceType::DeviceSetupDetails setup;
  58802. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  58803. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  58804. ScopedPointer<TextButton> testButton;
  58805. ScopedPointer<Component> inputLevelMeter;
  58806. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  58807. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  58808. {
  58809. if (box != 0)
  58810. {
  58811. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  58812. const int index = type->getIndexOfDevice (currentDevice, isInput);
  58813. box->setSelectedId (index + 1, true);
  58814. if (testButton != 0 && ! isInput)
  58815. testButton->setEnabled (index >= 0);
  58816. }
  58817. }
  58818. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  58819. {
  58820. const StringArray devs (type->getDeviceNames (isInputs));
  58821. combo.clear (true);
  58822. for (int i = 0; i < devs.size(); ++i)
  58823. combo.addItem (devs[i], i + 1);
  58824. combo.addItem (TRANS("<< none >>"), -1);
  58825. combo.setSelectedId (-1, true);
  58826. }
  58827. int getLowestY() const
  58828. {
  58829. int y = 0;
  58830. for (int i = getNumChildComponents(); --i >= 0;)
  58831. y = jmax (y, getChildComponent (i)->getBottom());
  58832. return y;
  58833. }
  58834. public:
  58835. class ChannelSelectorListBox : public ListBox,
  58836. public ListBoxModel
  58837. {
  58838. public:
  58839. enum BoxType
  58840. {
  58841. audioInputType,
  58842. audioOutputType
  58843. };
  58844. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  58845. const BoxType type_,
  58846. const String& noItemsMessage_)
  58847. : ListBox (String::empty, 0),
  58848. setup (setup_),
  58849. type (type_),
  58850. noItemsMessage (noItemsMessage_)
  58851. {
  58852. refresh();
  58853. setModel (this);
  58854. setOutlineThickness (1);
  58855. }
  58856. ~ChannelSelectorListBox()
  58857. {
  58858. }
  58859. void refresh()
  58860. {
  58861. items.clear();
  58862. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  58863. if (currentDevice != 0)
  58864. {
  58865. if (type == audioInputType)
  58866. items = currentDevice->getInputChannelNames();
  58867. else if (type == audioOutputType)
  58868. items = currentDevice->getOutputChannelNames();
  58869. if (setup.useStereoPairs)
  58870. {
  58871. StringArray pairs;
  58872. for (int i = 0; i < items.size(); i += 2)
  58873. {
  58874. const String name (items[i]);
  58875. const String name2 (items[i + 1]);
  58876. String commonBit;
  58877. for (int j = 0; j < name.length(); ++j)
  58878. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  58879. commonBit = name.substring (0, j);
  58880. // Make sure we only split the name at a space, because otherwise, things
  58881. // like "input 11" + "input 12" would become "input 11 + 2"
  58882. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  58883. commonBit = commonBit.dropLastCharacters (1);
  58884. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  58885. }
  58886. items = pairs;
  58887. }
  58888. }
  58889. updateContent();
  58890. repaint();
  58891. }
  58892. int getNumRows()
  58893. {
  58894. return items.size();
  58895. }
  58896. void paintListBoxItem (int row,
  58897. Graphics& g,
  58898. int width, int height,
  58899. bool rowIsSelected)
  58900. {
  58901. if (isPositiveAndBelow (row, items.size()))
  58902. {
  58903. if (rowIsSelected)
  58904. g.fillAll (findColour (TextEditor::highlightColourId)
  58905. .withMultipliedAlpha (0.3f));
  58906. const String item (items [row]);
  58907. bool enabled = false;
  58908. AudioDeviceManager::AudioDeviceSetup config;
  58909. setup.manager->getAudioDeviceSetup (config);
  58910. if (setup.useStereoPairs)
  58911. {
  58912. if (type == audioInputType)
  58913. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  58914. else if (type == audioOutputType)
  58915. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  58916. }
  58917. else
  58918. {
  58919. if (type == audioInputType)
  58920. enabled = config.inputChannels [row];
  58921. else if (type == audioOutputType)
  58922. enabled = config.outputChannels [row];
  58923. }
  58924. const int x = getTickX();
  58925. const float tickW = height * 0.75f;
  58926. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58927. enabled, true, true, false);
  58928. g.setFont (height * 0.6f);
  58929. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58930. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58931. }
  58932. }
  58933. void listBoxItemClicked (int row, const MouseEvent& e)
  58934. {
  58935. selectRow (row);
  58936. if (e.x < getTickX())
  58937. flipEnablement (row);
  58938. }
  58939. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58940. {
  58941. flipEnablement (row);
  58942. }
  58943. void returnKeyPressed (int row)
  58944. {
  58945. flipEnablement (row);
  58946. }
  58947. void paint (Graphics& g)
  58948. {
  58949. ListBox::paint (g);
  58950. if (items.size() == 0)
  58951. {
  58952. g.setColour (Colours::grey);
  58953. g.setFont (13.0f);
  58954. g.drawText (noItemsMessage,
  58955. 0, 0, getWidth(), getHeight() / 2,
  58956. Justification::centred, true);
  58957. }
  58958. }
  58959. int getBestHeight (int maxHeight)
  58960. {
  58961. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  58962. getNumRows())
  58963. + getOutlineThickness() * 2;
  58964. }
  58965. private:
  58966. const AudioIODeviceType::DeviceSetupDetails setup;
  58967. const BoxType type;
  58968. const String noItemsMessage;
  58969. StringArray items;
  58970. void flipEnablement (const int row)
  58971. {
  58972. jassert (type == audioInputType || type == audioOutputType);
  58973. if (isPositiveAndBelow (row, items.size()))
  58974. {
  58975. AudioDeviceManager::AudioDeviceSetup config;
  58976. setup.manager->getAudioDeviceSetup (config);
  58977. if (setup.useStereoPairs)
  58978. {
  58979. BigInteger bits;
  58980. BigInteger& original = (type == audioInputType ? config.inputChannels
  58981. : config.outputChannels);
  58982. int i;
  58983. for (i = 0; i < 256; i += 2)
  58984. bits.setBit (i / 2, original [i] || original [i + 1]);
  58985. if (type == audioInputType)
  58986. {
  58987. config.useDefaultInputChannels = false;
  58988. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  58989. }
  58990. else
  58991. {
  58992. config.useDefaultOutputChannels = false;
  58993. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  58994. }
  58995. for (i = 0; i < 256; ++i)
  58996. original.setBit (i, bits [i / 2]);
  58997. }
  58998. else
  58999. {
  59000. if (type == audioInputType)
  59001. {
  59002. config.useDefaultInputChannels = false;
  59003. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59004. }
  59005. else
  59006. {
  59007. config.useDefaultOutputChannels = false;
  59008. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59009. }
  59010. }
  59011. String error (setup.manager->setAudioDeviceSetup (config, true));
  59012. if (! error.isEmpty())
  59013. {
  59014. //xxx
  59015. }
  59016. }
  59017. }
  59018. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59019. {
  59020. const int numActive = chans.countNumberOfSetBits();
  59021. if (chans [index])
  59022. {
  59023. if (numActive > minNumber)
  59024. chans.setBit (index, false);
  59025. }
  59026. else
  59027. {
  59028. if (numActive >= maxNumber)
  59029. {
  59030. const int firstActiveChan = chans.findNextSetBit();
  59031. chans.setBit (index > firstActiveChan
  59032. ? firstActiveChan : chans.getHighestBit(),
  59033. false);
  59034. }
  59035. chans.setBit (index, true);
  59036. }
  59037. }
  59038. int getTickX() const
  59039. {
  59040. return getRowHeight() + 5;
  59041. }
  59042. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox);
  59043. };
  59044. private:
  59045. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59046. JUCE_DECLARE_NON_COPYABLE (AudioDeviceSettingsPanel);
  59047. };
  59048. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59049. const int minInputChannels_,
  59050. const int maxInputChannels_,
  59051. const int minOutputChannels_,
  59052. const int maxOutputChannels_,
  59053. const bool showMidiInputOptions,
  59054. const bool showMidiOutputSelector,
  59055. const bool showChannelsAsStereoPairs_,
  59056. const bool hideAdvancedOptionsWithButton_)
  59057. : deviceManager (deviceManager_),
  59058. deviceTypeDropDown (0),
  59059. deviceTypeDropDownLabel (0),
  59060. minOutputChannels (minOutputChannels_),
  59061. maxOutputChannels (maxOutputChannels_),
  59062. minInputChannels (minInputChannels_),
  59063. maxInputChannels (maxInputChannels_),
  59064. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59065. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59066. {
  59067. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59068. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59069. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59070. {
  59071. deviceTypeDropDown = new ComboBox (String::empty);
  59072. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59073. {
  59074. deviceTypeDropDown
  59075. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59076. i + 1);
  59077. }
  59078. addAndMakeVisible (deviceTypeDropDown);
  59079. deviceTypeDropDown->addListener (this);
  59080. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59081. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59082. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59083. }
  59084. if (showMidiInputOptions)
  59085. {
  59086. addAndMakeVisible (midiInputsList
  59087. = new MidiInputSelectorComponentListBox (deviceManager,
  59088. TRANS("(no midi inputs available)"),
  59089. 0, 0));
  59090. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59091. midiInputsLabel->setJustificationType (Justification::topRight);
  59092. midiInputsLabel->attachToComponent (midiInputsList, true);
  59093. }
  59094. else
  59095. {
  59096. midiInputsList = 0;
  59097. midiInputsLabel = 0;
  59098. }
  59099. if (showMidiOutputSelector)
  59100. {
  59101. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59102. midiOutputSelector->addListener (this);
  59103. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59104. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59105. }
  59106. else
  59107. {
  59108. midiOutputSelector = 0;
  59109. midiOutputLabel = 0;
  59110. }
  59111. deviceManager_.addChangeListener (this);
  59112. changeListenerCallback (0);
  59113. }
  59114. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59115. {
  59116. deviceManager.removeChangeListener (this);
  59117. }
  59118. void AudioDeviceSelectorComponent::resized()
  59119. {
  59120. const int lx = proportionOfWidth (0.35f);
  59121. const int w = proportionOfWidth (0.4f);
  59122. const int h = 24;
  59123. const int space = 6;
  59124. const int dh = h + space;
  59125. int y = 15;
  59126. if (deviceTypeDropDown != 0)
  59127. {
  59128. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59129. y += dh + space * 2;
  59130. }
  59131. if (audioDeviceSettingsComp != 0)
  59132. {
  59133. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59134. y += audioDeviceSettingsComp->getHeight() + space;
  59135. }
  59136. if (midiInputsList != 0)
  59137. {
  59138. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59139. midiInputsList->setBounds (lx, y, w, bh);
  59140. y += bh + space;
  59141. }
  59142. if (midiOutputSelector != 0)
  59143. midiOutputSelector->setBounds (lx, y, w, h);
  59144. }
  59145. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59146. {
  59147. if (child == audioDeviceSettingsComp)
  59148. resized();
  59149. }
  59150. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59151. {
  59152. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59153. if (device != 0 && device->hasControlPanel())
  59154. {
  59155. if (device->showControlPanel())
  59156. deviceManager.restartLastAudioDevice();
  59157. getTopLevelComponent()->toFront (true);
  59158. }
  59159. }
  59160. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59161. {
  59162. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59163. {
  59164. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59165. if (type != 0)
  59166. {
  59167. audioDeviceSettingsComp = 0;
  59168. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59169. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59170. }
  59171. }
  59172. else if (comboBoxThatHasChanged == midiOutputSelector)
  59173. {
  59174. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59175. }
  59176. }
  59177. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  59178. {
  59179. if (deviceTypeDropDown != 0)
  59180. {
  59181. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59182. }
  59183. if (audioDeviceSettingsComp == 0
  59184. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59185. {
  59186. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59187. audioDeviceSettingsComp = 0;
  59188. AudioIODeviceType* const type
  59189. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59190. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59191. if (type != 0)
  59192. {
  59193. AudioIODeviceType::DeviceSetupDetails details;
  59194. details.manager = &deviceManager;
  59195. details.minNumInputChannels = minInputChannels;
  59196. details.maxNumInputChannels = maxInputChannels;
  59197. details.minNumOutputChannels = minOutputChannels;
  59198. details.maxNumOutputChannels = maxOutputChannels;
  59199. details.useStereoPairs = showChannelsAsStereoPairs;
  59200. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59201. if (audioDeviceSettingsComp != 0)
  59202. {
  59203. addAndMakeVisible (audioDeviceSettingsComp);
  59204. audioDeviceSettingsComp->resized();
  59205. }
  59206. }
  59207. }
  59208. if (midiInputsList != 0)
  59209. {
  59210. midiInputsList->updateContent();
  59211. midiInputsList->repaint();
  59212. }
  59213. if (midiOutputSelector != 0)
  59214. {
  59215. midiOutputSelector->clear();
  59216. const StringArray midiOuts (MidiOutput::getDevices());
  59217. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59218. midiOutputSelector->addSeparator();
  59219. for (int i = 0; i < midiOuts.size(); ++i)
  59220. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59221. int current = -1;
  59222. if (deviceManager.getDefaultMidiOutput() != 0)
  59223. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59224. midiOutputSelector->setSelectedId (current, true);
  59225. }
  59226. resized();
  59227. }
  59228. END_JUCE_NAMESPACE
  59229. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59230. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59231. BEGIN_JUCE_NAMESPACE
  59232. BubbleComponent::BubbleComponent()
  59233. : side (0),
  59234. allowablePlacements (above | below | left | right),
  59235. arrowTipX (0.0f),
  59236. arrowTipY (0.0f)
  59237. {
  59238. setInterceptsMouseClicks (false, false);
  59239. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59240. setComponentEffect (&shadow);
  59241. }
  59242. BubbleComponent::~BubbleComponent()
  59243. {
  59244. }
  59245. void BubbleComponent::paint (Graphics& g)
  59246. {
  59247. int x = content.getX();
  59248. int y = content.getY();
  59249. int w = content.getWidth();
  59250. int h = content.getHeight();
  59251. int cw, ch;
  59252. getContentSize (cw, ch);
  59253. if (side == 3)
  59254. x += w - cw;
  59255. else if (side != 1)
  59256. x += (w - cw) / 2;
  59257. w = cw;
  59258. if (side == 2)
  59259. y += h - ch;
  59260. else if (side != 0)
  59261. y += (h - ch) / 2;
  59262. h = ch;
  59263. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59264. (float) x, (float) y,
  59265. (float) w, (float) h);
  59266. const int cx = x + (w - cw) / 2;
  59267. const int cy = y + (h - ch) / 2;
  59268. const int indent = 3;
  59269. g.setOrigin (cx + indent, cy + indent);
  59270. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59271. paintContent (g, cw - indent * 2, ch - indent * 2);
  59272. }
  59273. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59274. {
  59275. allowablePlacements = newPlacement;
  59276. }
  59277. void BubbleComponent::setPosition (Component* componentToPointTo)
  59278. {
  59279. jassert (componentToPointTo != 0);
  59280. Point<int> pos;
  59281. if (getParentComponent() != 0)
  59282. pos = getParentComponent()->getLocalPoint (componentToPointTo, pos);
  59283. else
  59284. pos = componentToPointTo->localPointToGlobal (pos);
  59285. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59286. }
  59287. void BubbleComponent::setPosition (const int arrowTipX_,
  59288. const int arrowTipY_)
  59289. {
  59290. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59291. }
  59292. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59293. {
  59294. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59295. : getParentMonitorArea());
  59296. int x = 0;
  59297. int y = 0;
  59298. int w = 150;
  59299. int h = 30;
  59300. getContentSize (w, h);
  59301. w += 30;
  59302. h += 30;
  59303. const float edgeIndent = 2.0f;
  59304. const int arrowLength = jmin (10, h / 3, w / 3);
  59305. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59306. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59307. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59308. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59309. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59310. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59311. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59312. {
  59313. spaceLeft = spaceRight = 0;
  59314. }
  59315. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59316. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59317. {
  59318. spaceAbove = spaceBelow = 0;
  59319. }
  59320. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59321. {
  59322. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59323. arrowTipX = w * 0.5f;
  59324. content.setSize (w, h - arrowLength);
  59325. if (spaceAbove >= spaceBelow)
  59326. {
  59327. // above
  59328. y = rectangleToPointTo.getY() - h;
  59329. content.setPosition (0, 0);
  59330. arrowTipY = h - edgeIndent;
  59331. side = 2;
  59332. }
  59333. else
  59334. {
  59335. // below
  59336. y = rectangleToPointTo.getBottom();
  59337. content.setPosition (0, arrowLength);
  59338. arrowTipY = edgeIndent;
  59339. side = 0;
  59340. }
  59341. }
  59342. else
  59343. {
  59344. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59345. arrowTipY = h * 0.5f;
  59346. content.setSize (w - arrowLength, h);
  59347. if (spaceLeft > spaceRight)
  59348. {
  59349. // on the left
  59350. x = rectangleToPointTo.getX() - w;
  59351. content.setPosition (0, 0);
  59352. arrowTipX = w - edgeIndent;
  59353. side = 3;
  59354. }
  59355. else
  59356. {
  59357. // on the right
  59358. x = rectangleToPointTo.getRight();
  59359. content.setPosition (arrowLength, 0);
  59360. arrowTipX = edgeIndent;
  59361. side = 1;
  59362. }
  59363. }
  59364. setBounds (x, y, w, h);
  59365. }
  59366. END_JUCE_NAMESPACE
  59367. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59368. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59369. BEGIN_JUCE_NAMESPACE
  59370. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59371. : fadeOutLength (fadeOutLengthMs),
  59372. deleteAfterUse (false)
  59373. {
  59374. }
  59375. BubbleMessageComponent::~BubbleMessageComponent()
  59376. {
  59377. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59378. }
  59379. void BubbleMessageComponent::showAt (int x, int y,
  59380. const String& text,
  59381. const int numMillisecondsBeforeRemoving,
  59382. const bool removeWhenMouseClicked,
  59383. const bool deleteSelfAfterUse)
  59384. {
  59385. textLayout.clear();
  59386. textLayout.setText (text, Font (14.0f));
  59387. textLayout.layout (256, Justification::centredLeft, true);
  59388. setPosition (x, y);
  59389. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59390. }
  59391. void BubbleMessageComponent::showAt (Component* const component,
  59392. const String& text,
  59393. const int numMillisecondsBeforeRemoving,
  59394. const bool removeWhenMouseClicked,
  59395. const bool deleteSelfAfterUse)
  59396. {
  59397. textLayout.clear();
  59398. textLayout.setText (text, Font (14.0f));
  59399. textLayout.layout (256, Justification::centredLeft, true);
  59400. setPosition (component);
  59401. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59402. }
  59403. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59404. const bool removeWhenMouseClicked,
  59405. const bool deleteSelfAfterUse)
  59406. {
  59407. setVisible (true);
  59408. deleteAfterUse = deleteSelfAfterUse;
  59409. if (numMillisecondsBeforeRemoving > 0)
  59410. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59411. else
  59412. expiryTime = 0;
  59413. startTimer (77);
  59414. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59415. if (! (removeWhenMouseClicked && isShowing()))
  59416. mouseClickCounter += 0xfffff;
  59417. repaint();
  59418. }
  59419. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59420. {
  59421. w = textLayout.getWidth() + 16;
  59422. h = textLayout.getHeight() + 16;
  59423. }
  59424. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59425. {
  59426. g.setColour (findColour (TooltipWindow::textColourId));
  59427. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59428. }
  59429. void BubbleMessageComponent::timerCallback()
  59430. {
  59431. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59432. {
  59433. stopTimer();
  59434. setVisible (false);
  59435. if (deleteAfterUse)
  59436. delete this;
  59437. }
  59438. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59439. {
  59440. stopTimer();
  59441. if (deleteAfterUse)
  59442. delete this;
  59443. else
  59444. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59445. }
  59446. }
  59447. END_JUCE_NAMESPACE
  59448. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59449. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59450. BEGIN_JUCE_NAMESPACE
  59451. class ColourComponentSlider : public Slider
  59452. {
  59453. public:
  59454. ColourComponentSlider (const String& name)
  59455. : Slider (name)
  59456. {
  59457. setRange (0.0, 255.0, 1.0);
  59458. }
  59459. const String getTextFromValue (double value)
  59460. {
  59461. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59462. }
  59463. double getValueFromText (const String& text)
  59464. {
  59465. return (double) text.getHexValue32();
  59466. }
  59467. private:
  59468. JUCE_DECLARE_NON_COPYABLE (ColourComponentSlider);
  59469. };
  59470. class ColourSpaceMarker : public Component
  59471. {
  59472. public:
  59473. ColourSpaceMarker()
  59474. {
  59475. setInterceptsMouseClicks (false, false);
  59476. }
  59477. void paint (Graphics& g)
  59478. {
  59479. g.setColour (Colour::greyLevel (0.1f));
  59480. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59481. g.setColour (Colour::greyLevel (0.9f));
  59482. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59483. }
  59484. private:
  59485. JUCE_DECLARE_NON_COPYABLE (ColourSpaceMarker);
  59486. };
  59487. class ColourSelector::ColourSpaceView : public Component
  59488. {
  59489. public:
  59490. ColourSpaceView (ColourSelector& owner_,
  59491. float& h_, float& s_, float& v_,
  59492. const int edgeSize)
  59493. : owner (owner_),
  59494. h (h_), s (s_), v (v_),
  59495. lastHue (0.0f),
  59496. edge (edgeSize)
  59497. {
  59498. addAndMakeVisible (&marker);
  59499. setMouseCursor (MouseCursor::CrosshairCursor);
  59500. }
  59501. void paint (Graphics& g)
  59502. {
  59503. if (colours.isNull())
  59504. {
  59505. const int width = getWidth() / 2;
  59506. const int height = getHeight() / 2;
  59507. colours = Image (Image::RGB, width, height, false);
  59508. Image::BitmapData pixels (colours, true);
  59509. for (int y = 0; y < height; ++y)
  59510. {
  59511. const float val = 1.0f - y / (float) height;
  59512. for (int x = 0; x < width; ++x)
  59513. {
  59514. const float sat = x / (float) width;
  59515. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59516. }
  59517. }
  59518. }
  59519. g.setOpacity (1.0f);
  59520. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  59521. 0, 0, colours.getWidth(), colours.getHeight());
  59522. }
  59523. void mouseDown (const MouseEvent& e)
  59524. {
  59525. mouseDrag (e);
  59526. }
  59527. void mouseDrag (const MouseEvent& e)
  59528. {
  59529. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  59530. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  59531. owner.setSV (sat, val);
  59532. }
  59533. void updateIfNeeded()
  59534. {
  59535. if (lastHue != h)
  59536. {
  59537. lastHue = h;
  59538. colours = Image::null;
  59539. repaint();
  59540. }
  59541. updateMarker();
  59542. }
  59543. void resized()
  59544. {
  59545. colours = Image::null;
  59546. updateMarker();
  59547. }
  59548. private:
  59549. ColourSelector& owner;
  59550. float& h;
  59551. float& s;
  59552. float& v;
  59553. float lastHue;
  59554. ColourSpaceMarker marker;
  59555. const int edge;
  59556. Image colours;
  59557. void updateMarker()
  59558. {
  59559. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  59560. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  59561. edge * 2, edge * 2);
  59562. }
  59563. JUCE_DECLARE_NON_COPYABLE (ColourSpaceView);
  59564. };
  59565. class HueSelectorMarker : public Component
  59566. {
  59567. public:
  59568. HueSelectorMarker()
  59569. {
  59570. setInterceptsMouseClicks (false, false);
  59571. }
  59572. void paint (Graphics& g)
  59573. {
  59574. Path p;
  59575. p.addTriangle (1.0f, 1.0f,
  59576. getWidth() * 0.3f, getHeight() * 0.5f,
  59577. 1.0f, getHeight() - 1.0f);
  59578. p.addTriangle (getWidth() - 1.0f, 1.0f,
  59579. getWidth() * 0.7f, getHeight() * 0.5f,
  59580. getWidth() - 1.0f, getHeight() - 1.0f);
  59581. g.setColour (Colours::white.withAlpha (0.75f));
  59582. g.fillPath (p);
  59583. g.setColour (Colours::black.withAlpha (0.75f));
  59584. g.strokePath (p, PathStrokeType (1.2f));
  59585. }
  59586. private:
  59587. JUCE_DECLARE_NON_COPYABLE (HueSelectorMarker);
  59588. };
  59589. class ColourSelector::HueSelectorComp : public Component
  59590. {
  59591. public:
  59592. HueSelectorComp (ColourSelector& owner_,
  59593. float& h_, float& s_, float& v_,
  59594. const int edgeSize)
  59595. : owner (owner_),
  59596. h (h_), s (s_), v (v_),
  59597. lastHue (0.0f),
  59598. edge (edgeSize)
  59599. {
  59600. addAndMakeVisible (&marker);
  59601. }
  59602. void paint (Graphics& g)
  59603. {
  59604. const float yScale = 1.0f / (getHeight() - edge * 2);
  59605. const Rectangle<int> clip (g.getClipBounds());
  59606. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  59607. {
  59608. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  59609. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  59610. }
  59611. }
  59612. void resized()
  59613. {
  59614. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  59615. getWidth(), edge * 2);
  59616. }
  59617. void mouseDown (const MouseEvent& e)
  59618. {
  59619. mouseDrag (e);
  59620. }
  59621. void mouseDrag (const MouseEvent& e)
  59622. {
  59623. owner.setHue ((e.y - edge) / (float) (getHeight() - edge * 2));
  59624. }
  59625. void updateIfNeeded()
  59626. {
  59627. resized();
  59628. }
  59629. private:
  59630. ColourSelector& owner;
  59631. float& h;
  59632. float& s;
  59633. float& v;
  59634. float lastHue;
  59635. HueSelectorMarker marker;
  59636. const int edge;
  59637. JUCE_DECLARE_NON_COPYABLE (HueSelectorComp);
  59638. };
  59639. class ColourSelector::SwatchComponent : public Component
  59640. {
  59641. public:
  59642. SwatchComponent (ColourSelector& owner_, int index_)
  59643. : owner (owner_), index (index_)
  59644. {
  59645. }
  59646. void paint (Graphics& g)
  59647. {
  59648. const Colour colour (owner.getSwatchColour (index));
  59649. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  59650. Colour (0xffdddddd).overlaidWith (colour),
  59651. Colour (0xffffffff).overlaidWith (colour));
  59652. }
  59653. void mouseDown (const MouseEvent&)
  59654. {
  59655. PopupMenu m;
  59656. m.addItem (1, TRANS("Use this swatch as the current colour"));
  59657. m.addSeparator();
  59658. m.addItem (2, TRANS("Set this swatch to the current colour"));
  59659. const int r = m.showAt (this);
  59660. if (r == 1)
  59661. {
  59662. owner.setCurrentColour (owner.getSwatchColour (index));
  59663. }
  59664. else if (r == 2)
  59665. {
  59666. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  59667. {
  59668. owner.setSwatchColour (index, owner.getCurrentColour());
  59669. repaint();
  59670. }
  59671. }
  59672. }
  59673. private:
  59674. ColourSelector& owner;
  59675. const int index;
  59676. JUCE_DECLARE_NON_COPYABLE (SwatchComponent);
  59677. };
  59678. ColourSelector::ColourSelector (const int flags_,
  59679. const int edgeGap_,
  59680. const int gapAroundColourSpaceComponent)
  59681. : colour (Colours::white),
  59682. flags (flags_),
  59683. edgeGap (edgeGap_)
  59684. {
  59685. // not much point having a selector with no components in it!
  59686. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  59687. updateHSV();
  59688. if ((flags & showSliders) != 0)
  59689. {
  59690. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  59691. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  59692. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  59693. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  59694. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  59695. for (int i = 4; --i >= 0;)
  59696. sliders[i]->addListener (this);
  59697. }
  59698. if ((flags & showColourspace) != 0)
  59699. {
  59700. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  59701. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  59702. }
  59703. update();
  59704. }
  59705. ColourSelector::~ColourSelector()
  59706. {
  59707. dispatchPendingMessages();
  59708. swatchComponents.clear();
  59709. }
  59710. const Colour ColourSelector::getCurrentColour() const
  59711. {
  59712. return ((flags & showAlphaChannel) != 0) ? colour
  59713. : colour.withAlpha ((uint8) 0xff);
  59714. }
  59715. void ColourSelector::setCurrentColour (const Colour& c)
  59716. {
  59717. if (c != colour)
  59718. {
  59719. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  59720. updateHSV();
  59721. update();
  59722. }
  59723. }
  59724. void ColourSelector::setHue (float newH)
  59725. {
  59726. newH = jlimit (0.0f, 1.0f, newH);
  59727. if (h != newH)
  59728. {
  59729. h = newH;
  59730. colour = Colour (h, s, v, colour.getFloatAlpha());
  59731. update();
  59732. }
  59733. }
  59734. void ColourSelector::setSV (float newS, float newV)
  59735. {
  59736. newS = jlimit (0.0f, 1.0f, newS);
  59737. newV = jlimit (0.0f, 1.0f, newV);
  59738. if (s != newS || v != newV)
  59739. {
  59740. s = newS;
  59741. v = newV;
  59742. colour = Colour (h, s, v, colour.getFloatAlpha());
  59743. update();
  59744. }
  59745. }
  59746. void ColourSelector::updateHSV()
  59747. {
  59748. colour.getHSB (h, s, v);
  59749. }
  59750. void ColourSelector::update()
  59751. {
  59752. if (sliders[0] != 0)
  59753. {
  59754. sliders[0]->setValue ((int) colour.getRed());
  59755. sliders[1]->setValue ((int) colour.getGreen());
  59756. sliders[2]->setValue ((int) colour.getBlue());
  59757. sliders[3]->setValue ((int) colour.getAlpha());
  59758. }
  59759. if (colourSpace != 0)
  59760. {
  59761. colourSpace->updateIfNeeded();
  59762. hueSelector->updateIfNeeded();
  59763. }
  59764. if ((flags & showColourAtTop) != 0)
  59765. repaint (previewArea);
  59766. sendChangeMessage();
  59767. }
  59768. void ColourSelector::paint (Graphics& g)
  59769. {
  59770. g.fillAll (findColour (backgroundColourId));
  59771. if ((flags & showColourAtTop) != 0)
  59772. {
  59773. const Colour currentColour (getCurrentColour());
  59774. g.fillCheckerBoard (previewArea, 10, 10,
  59775. Colour (0xffdddddd).overlaidWith (currentColour),
  59776. Colour (0xffffffff).overlaidWith (currentColour));
  59777. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  59778. g.setFont (14.0f, true);
  59779. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  59780. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  59781. Justification::centred, false);
  59782. }
  59783. if ((flags & showSliders) != 0)
  59784. {
  59785. g.setColour (findColour (labelTextColourId));
  59786. g.setFont (11.0f);
  59787. for (int i = 4; --i >= 0;)
  59788. {
  59789. if (sliders[i]->isVisible())
  59790. g.drawText (sliders[i]->getName() + ":",
  59791. 0, sliders[i]->getY(),
  59792. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  59793. Justification::centredRight, false);
  59794. }
  59795. }
  59796. }
  59797. void ColourSelector::resized()
  59798. {
  59799. const int swatchesPerRow = 8;
  59800. const int swatchHeight = 22;
  59801. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  59802. const int numSwatches = getNumSwatches();
  59803. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  59804. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  59805. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  59806. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  59807. int y = topSpace;
  59808. if ((flags & showColourspace) != 0)
  59809. {
  59810. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  59811. colourSpace->setBounds (edgeGap, y,
  59812. getWidth() - hueWidth - edgeGap - 4,
  59813. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  59814. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  59815. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  59816. colourSpace->getHeight());
  59817. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  59818. }
  59819. if ((flags & showSliders) != 0)
  59820. {
  59821. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  59822. for (int i = 0; i < numSliders; ++i)
  59823. {
  59824. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  59825. proportionOfWidth (0.72f), sliderHeight - 2);
  59826. y += sliderHeight;
  59827. }
  59828. }
  59829. if (numSwatches > 0)
  59830. {
  59831. const int startX = 8;
  59832. const int xGap = 4;
  59833. const int yGap = 4;
  59834. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  59835. y += edgeGap;
  59836. if (swatchComponents.size() != numSwatches)
  59837. {
  59838. swatchComponents.clear();
  59839. for (int i = 0; i < numSwatches; ++i)
  59840. {
  59841. SwatchComponent* const sc = new SwatchComponent (*this, i);
  59842. swatchComponents.add (sc);
  59843. addAndMakeVisible (sc);
  59844. }
  59845. }
  59846. int x = startX;
  59847. for (int i = 0; i < swatchComponents.size(); ++i)
  59848. {
  59849. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  59850. sc->setBounds (x + xGap / 2,
  59851. y + yGap / 2,
  59852. swatchWidth - xGap,
  59853. swatchHeight - yGap);
  59854. if (((i + 1) % swatchesPerRow) == 0)
  59855. {
  59856. x = startX;
  59857. y += swatchHeight;
  59858. }
  59859. else
  59860. {
  59861. x += swatchWidth;
  59862. }
  59863. }
  59864. }
  59865. }
  59866. void ColourSelector::sliderValueChanged (Slider*)
  59867. {
  59868. if (sliders[0] != 0)
  59869. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  59870. (uint8) sliders[1]->getValue(),
  59871. (uint8) sliders[2]->getValue(),
  59872. (uint8) sliders[3]->getValue()));
  59873. }
  59874. int ColourSelector::getNumSwatches() const
  59875. {
  59876. return 0;
  59877. }
  59878. const Colour ColourSelector::getSwatchColour (const int) const
  59879. {
  59880. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59881. return Colours::black;
  59882. }
  59883. void ColourSelector::setSwatchColour (const int, const Colour&) const
  59884. {
  59885. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  59886. }
  59887. END_JUCE_NAMESPACE
  59888. /*** End of inlined file: juce_ColourSelector.cpp ***/
  59889. /*** Start of inlined file: juce_DropShadower.cpp ***/
  59890. BEGIN_JUCE_NAMESPACE
  59891. class ShadowWindow : public Component
  59892. {
  59893. public:
  59894. ShadowWindow (Component& owner, const int type_, const Image shadowImageSections [12])
  59895. : topLeft (shadowImageSections [type_ * 3]),
  59896. bottomRight (shadowImageSections [type_ * 3 + 1]),
  59897. filler (shadowImageSections [type_ * 3 + 2]),
  59898. type (type_)
  59899. {
  59900. setInterceptsMouseClicks (false, false);
  59901. if (owner.isOnDesktop())
  59902. {
  59903. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  59904. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  59905. | ComponentPeer::windowIsTemporary
  59906. | ComponentPeer::windowIgnoresKeyPresses);
  59907. }
  59908. else if (owner.getParentComponent() != 0)
  59909. {
  59910. owner.getParentComponent()->addChildComponent (this);
  59911. }
  59912. }
  59913. void paint (Graphics& g)
  59914. {
  59915. g.setOpacity (1.0f);
  59916. if (type < 2)
  59917. {
  59918. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  59919. g.drawImage (topLeft,
  59920. 0, 0, topLeft.getWidth(), imH,
  59921. 0, 0, topLeft.getWidth(), imH);
  59922. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  59923. g.drawImage (bottomRight,
  59924. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  59925. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  59926. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59927. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  59928. }
  59929. else
  59930. {
  59931. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  59932. g.drawImage (topLeft,
  59933. 0, 0, imW, topLeft.getHeight(),
  59934. 0, 0, imW, topLeft.getHeight());
  59935. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  59936. g.drawImage (bottomRight,
  59937. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  59938. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  59939. g.setTiledImageFill (filler, 0, 0, 1.0f);
  59940. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  59941. }
  59942. }
  59943. void resized()
  59944. {
  59945. repaint(); // (needed for correct repainting)
  59946. }
  59947. private:
  59948. const Image topLeft, bottomRight, filler;
  59949. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  59950. JUCE_DECLARE_NON_COPYABLE (ShadowWindow);
  59951. };
  59952. DropShadower::DropShadower (const float alpha_,
  59953. const int xOffset_,
  59954. const int yOffset_,
  59955. const float blurRadius_)
  59956. : owner (0),
  59957. xOffset (xOffset_),
  59958. yOffset (yOffset_),
  59959. alpha (alpha_),
  59960. blurRadius (blurRadius_),
  59961. reentrant (false)
  59962. {
  59963. }
  59964. DropShadower::~DropShadower()
  59965. {
  59966. if (owner != 0)
  59967. owner->removeComponentListener (this);
  59968. reentrant = true;
  59969. shadowWindows.clear();
  59970. }
  59971. void DropShadower::setOwner (Component* componentToFollow)
  59972. {
  59973. if (componentToFollow != owner)
  59974. {
  59975. if (owner != 0)
  59976. owner->removeComponentListener (this);
  59977. // (the component can't be null)
  59978. jassert (componentToFollow != 0);
  59979. owner = componentToFollow;
  59980. jassert (owner != 0);
  59981. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  59982. owner->addComponentListener (this);
  59983. updateShadows();
  59984. }
  59985. }
  59986. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  59987. {
  59988. updateShadows();
  59989. }
  59990. void DropShadower::componentBroughtToFront (Component&)
  59991. {
  59992. bringShadowWindowsToFront();
  59993. }
  59994. void DropShadower::componentParentHierarchyChanged (Component&)
  59995. {
  59996. shadowWindows.clear();
  59997. updateShadows();
  59998. }
  59999. void DropShadower::componentVisibilityChanged (Component&)
  60000. {
  60001. updateShadows();
  60002. }
  60003. void DropShadower::updateShadows()
  60004. {
  60005. if (reentrant || owner == 0)
  60006. return;
  60007. ComponentPeer* const peer = owner->getPeer();
  60008. const bool isOwnerVisible = owner->isVisible() && (peer == 0 || ! peer->isMinimised());
  60009. const bool createShadowWindows = shadowWindows.size() == 0
  60010. && owner->getWidth() > 0
  60011. && owner->getHeight() > 0
  60012. && isOwnerVisible
  60013. && (Desktop::canUseSemiTransparentWindows()
  60014. || owner->getParentComponent() != 0);
  60015. {
  60016. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60017. const int shadowEdge = jmax (xOffset, yOffset) + (int) blurRadius;
  60018. if (createShadowWindows)
  60019. {
  60020. // keep a cached version of the image to save doing the gaussian too often
  60021. String imageId;
  60022. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60023. const int hash = imageId.hashCode();
  60024. Image bigIm (ImageCache::getFromHashCode (hash));
  60025. if (bigIm.isNull())
  60026. {
  60027. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60028. Graphics bigG (bigIm);
  60029. bigG.setColour (Colours::black.withAlpha (alpha));
  60030. bigG.fillRect (shadowEdge + xOffset,
  60031. shadowEdge + yOffset,
  60032. bigIm.getWidth() - (shadowEdge * 2),
  60033. bigIm.getHeight() - (shadowEdge * 2));
  60034. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60035. blurKernel.createGaussianBlur (blurRadius);
  60036. blurKernel.applyToImage (bigIm, bigIm,
  60037. Rectangle<int> (xOffset, yOffset,
  60038. bigIm.getWidth(), bigIm.getHeight()));
  60039. ImageCache::addImageToCache (bigIm, hash);
  60040. }
  60041. const int iw = bigIm.getWidth();
  60042. const int ih = bigIm.getHeight();
  60043. const int shadowEdge2 = shadowEdge * 2;
  60044. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60045. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60046. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60047. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60048. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60049. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60050. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60051. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60052. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60053. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60054. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60055. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60056. for (int i = 0; i < 4; ++i)
  60057. shadowWindows.add (new ShadowWindow (*owner, i, shadowImageSections));
  60058. }
  60059. if (shadowWindows.size() >= 4)
  60060. {
  60061. for (int i = shadowWindows.size(); --i >= 0;)
  60062. {
  60063. shadowWindows.getUnchecked(i)->setAlwaysOnTop (owner->isAlwaysOnTop());
  60064. shadowWindows.getUnchecked(i)->setVisible (isOwnerVisible);
  60065. }
  60066. const int x = owner->getX();
  60067. const int y = owner->getY() - shadowEdge;
  60068. const int w = owner->getWidth();
  60069. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60070. shadowWindows.getUnchecked(0)->setBounds (x - shadowEdge, y, shadowEdge, h);
  60071. shadowWindows.getUnchecked(1)->setBounds (x + w, y, shadowEdge, h);
  60072. shadowWindows.getUnchecked(2)->setBounds (x, y, w, shadowEdge);
  60073. shadowWindows.getUnchecked(3)->setBounds (x, owner->getBottom(), w, shadowEdge);
  60074. }
  60075. }
  60076. if (createShadowWindows)
  60077. bringShadowWindowsToFront();
  60078. }
  60079. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60080. const int sx, const int sy)
  60081. {
  60082. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60083. Graphics g (shadowImageSections[num]);
  60084. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60085. }
  60086. void DropShadower::bringShadowWindowsToFront()
  60087. {
  60088. if (! reentrant)
  60089. {
  60090. updateShadows();
  60091. const ScopedValueSetter<bool> setter (reentrant, true, false);
  60092. for (int i = shadowWindows.size(); --i >= 0;)
  60093. shadowWindows.getUnchecked(i)->toBehind (owner);
  60094. }
  60095. }
  60096. END_JUCE_NAMESPACE
  60097. /*** End of inlined file: juce_DropShadower.cpp ***/
  60098. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60099. BEGIN_JUCE_NAMESPACE
  60100. class MidiKeyboardUpDownButton : public Button
  60101. {
  60102. public:
  60103. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60104. : Button (String::empty),
  60105. owner (owner_),
  60106. delta (delta_)
  60107. {
  60108. setOpaque (true);
  60109. }
  60110. void clicked()
  60111. {
  60112. int note = owner.getLowestVisibleKey();
  60113. if (delta < 0)
  60114. note = (note - 1) / 12;
  60115. else
  60116. note = note / 12 + 1;
  60117. owner.setLowestVisibleKey (note * 12);
  60118. }
  60119. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  60120. {
  60121. owner.drawUpDownButton (g, getWidth(), getHeight(),
  60122. isMouseOverButton, isButtonDown,
  60123. delta > 0);
  60124. }
  60125. private:
  60126. MidiKeyboardComponent& owner;
  60127. const int delta;
  60128. JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
  60129. };
  60130. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60131. const Orientation orientation_)
  60132. : state (state_),
  60133. xOffset (0),
  60134. blackNoteLength (1),
  60135. keyWidth (16.0f),
  60136. orientation (orientation_),
  60137. midiChannel (1),
  60138. midiInChannelMask (0xffff),
  60139. velocity (1.0f),
  60140. noteUnderMouse (-1),
  60141. mouseDownNote (-1),
  60142. rangeStart (0),
  60143. rangeEnd (127),
  60144. firstKey (12 * 4),
  60145. canScroll (true),
  60146. mouseDragging (false),
  60147. useMousePositionForVelocity (true),
  60148. keyMappingOctave (6),
  60149. octaveNumForMiddleC (3)
  60150. {
  60151. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  60152. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  60153. // initialise with a default set of querty key-mappings..
  60154. const char* const keymap = "awsedftgyhujkolp;";
  60155. for (int i = String (keymap).length(); --i >= 0;)
  60156. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60157. setOpaque (true);
  60158. setWantsKeyboardFocus (true);
  60159. state.addListener (this);
  60160. }
  60161. MidiKeyboardComponent::~MidiKeyboardComponent()
  60162. {
  60163. state.removeListener (this);
  60164. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60165. }
  60166. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60167. {
  60168. keyWidth = widthInPixels;
  60169. resized();
  60170. }
  60171. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60172. {
  60173. if (orientation != newOrientation)
  60174. {
  60175. orientation = newOrientation;
  60176. resized();
  60177. }
  60178. }
  60179. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60180. const int highestNote)
  60181. {
  60182. jassert (lowestNote >= 0 && lowestNote <= 127);
  60183. jassert (highestNote >= 0 && highestNote <= 127);
  60184. jassert (lowestNote <= highestNote);
  60185. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60186. {
  60187. rangeStart = jlimit (0, 127, lowestNote);
  60188. rangeEnd = jlimit (0, 127, highestNote);
  60189. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60190. resized();
  60191. }
  60192. }
  60193. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60194. {
  60195. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60196. if (noteNumber != firstKey)
  60197. {
  60198. firstKey = noteNumber;
  60199. sendChangeMessage();
  60200. resized();
  60201. }
  60202. }
  60203. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  60204. {
  60205. if (canScroll != canScroll_)
  60206. {
  60207. canScroll = canScroll_;
  60208. resized();
  60209. }
  60210. }
  60211. void MidiKeyboardComponent::colourChanged()
  60212. {
  60213. repaint();
  60214. }
  60215. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  60216. {
  60217. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  60218. if (midiChannel != midiChannelNumber)
  60219. {
  60220. resetAnyKeysInUse();
  60221. midiChannel = jlimit (1, 16, midiChannelNumber);
  60222. }
  60223. }
  60224. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  60225. {
  60226. midiInChannelMask = midiChannelMask;
  60227. triggerAsyncUpdate();
  60228. }
  60229. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  60230. {
  60231. velocity = jlimit (0.0f, 1.0f, velocity_);
  60232. useMousePositionForVelocity = useMousePositionForVelocity_;
  60233. }
  60234. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  60235. {
  60236. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  60237. static const float blackNoteWidth = 0.7f;
  60238. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  60239. 1.0f, 2 - blackNoteWidth * 0.4f,
  60240. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  60241. 4.0f, 5 - blackNoteWidth * 0.5f,
  60242. 5.0f, 6 - blackNoteWidth * 0.3f,
  60243. 6.0f };
  60244. static const float widths[] = { 1.0f, blackNoteWidth,
  60245. 1.0f, blackNoteWidth,
  60246. 1.0f, 1.0f, blackNoteWidth,
  60247. 1.0f, blackNoteWidth,
  60248. 1.0f, blackNoteWidth,
  60249. 1.0f };
  60250. const int octave = midiNoteNumber / 12;
  60251. const int note = midiNoteNumber % 12;
  60252. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  60253. w = roundToInt (widths [note] * keyWidth_);
  60254. }
  60255. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  60256. {
  60257. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  60258. int rx, rw;
  60259. getKeyPosition (rangeStart, keyWidth, rx, rw);
  60260. x -= xOffset + rx;
  60261. }
  60262. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  60263. {
  60264. int x, y;
  60265. getKeyPos (midiNoteNumber, x, y);
  60266. return x;
  60267. }
  60268. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  60269. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  60270. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  60271. {
  60272. if (! reallyContains (pos, false))
  60273. return -1;
  60274. Point<int> p (pos);
  60275. if (orientation != horizontalKeyboard)
  60276. {
  60277. p = Point<int> (p.getY(), p.getX());
  60278. if (orientation == verticalKeyboardFacingLeft)
  60279. p = Point<int> (p.getX(), getWidth() - p.getY());
  60280. else
  60281. p = Point<int> (getHeight() - p.getX(), p.getY());
  60282. }
  60283. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  60284. }
  60285. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  60286. {
  60287. if (pos.getY() < blackNoteLength)
  60288. {
  60289. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60290. {
  60291. for (int i = 0; i < 5; ++i)
  60292. {
  60293. const int note = octaveStart + blackNotes [i];
  60294. if (note >= rangeStart && note <= rangeEnd)
  60295. {
  60296. int kx, kw;
  60297. getKeyPos (note, kx, kw);
  60298. kx += xOffset;
  60299. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60300. {
  60301. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  60302. return note;
  60303. }
  60304. }
  60305. }
  60306. }
  60307. }
  60308. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  60309. {
  60310. for (int i = 0; i < 7; ++i)
  60311. {
  60312. const int note = octaveStart + whiteNotes [i];
  60313. if (note >= rangeStart && note <= rangeEnd)
  60314. {
  60315. int kx, kw;
  60316. getKeyPos (note, kx, kw);
  60317. kx += xOffset;
  60318. if (pos.getX() >= kx && pos.getX() < kx + kw)
  60319. {
  60320. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  60321. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  60322. return note;
  60323. }
  60324. }
  60325. }
  60326. }
  60327. mousePositionVelocity = 0;
  60328. return -1;
  60329. }
  60330. void MidiKeyboardComponent::repaintNote (const int noteNum)
  60331. {
  60332. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60333. {
  60334. int x, w;
  60335. getKeyPos (noteNum, x, w);
  60336. if (orientation == horizontalKeyboard)
  60337. repaint (x, 0, w, getHeight());
  60338. else if (orientation == verticalKeyboardFacingLeft)
  60339. repaint (0, x, getWidth(), w);
  60340. else if (orientation == verticalKeyboardFacingRight)
  60341. repaint (0, getHeight() - x - w, getWidth(), w);
  60342. }
  60343. }
  60344. void MidiKeyboardComponent::paint (Graphics& g)
  60345. {
  60346. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  60347. const Colour lineColour (findColour (keySeparatorLineColourId));
  60348. const Colour textColour (findColour (textLabelColourId));
  60349. int x, w, octave;
  60350. for (octave = 0; octave < 128; octave += 12)
  60351. {
  60352. for (int white = 0; white < 7; ++white)
  60353. {
  60354. const int noteNum = octave + whiteNotes [white];
  60355. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60356. {
  60357. getKeyPos (noteNum, x, w);
  60358. if (orientation == horizontalKeyboard)
  60359. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  60360. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60361. noteUnderMouse == noteNum,
  60362. lineColour, textColour);
  60363. else if (orientation == verticalKeyboardFacingLeft)
  60364. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  60365. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60366. noteUnderMouse == noteNum,
  60367. lineColour, textColour);
  60368. else if (orientation == verticalKeyboardFacingRight)
  60369. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  60370. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60371. noteUnderMouse == noteNum,
  60372. lineColour, textColour);
  60373. }
  60374. }
  60375. }
  60376. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  60377. if (orientation == verticalKeyboardFacingLeft)
  60378. {
  60379. x1 = getWidth() - 1.0f;
  60380. x2 = getWidth() - 5.0f;
  60381. }
  60382. else if (orientation == verticalKeyboardFacingRight)
  60383. x2 = 5.0f;
  60384. else
  60385. y2 = 5.0f;
  60386. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  60387. Colours::transparentBlack, x2, y2, false));
  60388. getKeyPos (rangeEnd, x, w);
  60389. x += w;
  60390. if (orientation == verticalKeyboardFacingLeft)
  60391. g.fillRect (getWidth() - 5, 0, 5, x);
  60392. else if (orientation == verticalKeyboardFacingRight)
  60393. g.fillRect (0, 0, 5, x);
  60394. else
  60395. g.fillRect (0, 0, x, 5);
  60396. g.setColour (lineColour);
  60397. if (orientation == verticalKeyboardFacingLeft)
  60398. g.fillRect (0, 0, 1, x);
  60399. else if (orientation == verticalKeyboardFacingRight)
  60400. g.fillRect (getWidth() - 1, 0, 1, x);
  60401. else
  60402. g.fillRect (0, getHeight() - 1, x, 1);
  60403. const Colour blackNoteColour (findColour (blackNoteColourId));
  60404. for (octave = 0; octave < 128; octave += 12)
  60405. {
  60406. for (int black = 0; black < 5; ++black)
  60407. {
  60408. const int noteNum = octave + blackNotes [black];
  60409. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  60410. {
  60411. getKeyPos (noteNum, x, w);
  60412. if (orientation == horizontalKeyboard)
  60413. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  60414. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60415. noteUnderMouse == noteNum,
  60416. blackNoteColour);
  60417. else if (orientation == verticalKeyboardFacingLeft)
  60418. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  60419. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60420. noteUnderMouse == noteNum,
  60421. blackNoteColour);
  60422. else if (orientation == verticalKeyboardFacingRight)
  60423. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  60424. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  60425. noteUnderMouse == noteNum,
  60426. blackNoteColour);
  60427. }
  60428. }
  60429. }
  60430. }
  60431. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  60432. Graphics& g, int x, int y, int w, int h,
  60433. bool isDown, bool isOver,
  60434. const Colour& lineColour,
  60435. const Colour& textColour)
  60436. {
  60437. Colour c (Colours::transparentWhite);
  60438. if (isDown)
  60439. c = findColour (keyDownOverlayColourId);
  60440. if (isOver)
  60441. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60442. g.setColour (c);
  60443. g.fillRect (x, y, w, h);
  60444. const String text (getWhiteNoteText (midiNoteNumber));
  60445. if (! text.isEmpty())
  60446. {
  60447. g.setColour (textColour);
  60448. Font f (jmin (12.0f, keyWidth * 0.9f));
  60449. f.setHorizontalScale (0.8f);
  60450. g.setFont (f);
  60451. Justification justification (Justification::centredBottom);
  60452. if (orientation == verticalKeyboardFacingLeft)
  60453. justification = Justification::centredLeft;
  60454. else if (orientation == verticalKeyboardFacingRight)
  60455. justification = Justification::centredRight;
  60456. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  60457. }
  60458. g.setColour (lineColour);
  60459. if (orientation == horizontalKeyboard)
  60460. g.fillRect (x, y, 1, h);
  60461. else if (orientation == verticalKeyboardFacingLeft)
  60462. g.fillRect (x, y, w, 1);
  60463. else if (orientation == verticalKeyboardFacingRight)
  60464. g.fillRect (x, y + h - 1, w, 1);
  60465. if (midiNoteNumber == rangeEnd)
  60466. {
  60467. if (orientation == horizontalKeyboard)
  60468. g.fillRect (x + w, y, 1, h);
  60469. else if (orientation == verticalKeyboardFacingLeft)
  60470. g.fillRect (x, y + h, w, 1);
  60471. else if (orientation == verticalKeyboardFacingRight)
  60472. g.fillRect (x, y - 1, w, 1);
  60473. }
  60474. }
  60475. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  60476. Graphics& g, int x, int y, int w, int h,
  60477. bool isDown, bool isOver,
  60478. const Colour& noteFillColour)
  60479. {
  60480. Colour c (noteFillColour);
  60481. if (isDown)
  60482. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  60483. if (isOver)
  60484. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  60485. g.setColour (c);
  60486. g.fillRect (x, y, w, h);
  60487. if (isDown)
  60488. {
  60489. g.setColour (noteFillColour);
  60490. g.drawRect (x, y, w, h);
  60491. }
  60492. else
  60493. {
  60494. const int xIndent = jmax (1, jmin (w, h) / 8);
  60495. g.setColour (c.brighter());
  60496. if (orientation == horizontalKeyboard)
  60497. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  60498. else if (orientation == verticalKeyboardFacingLeft)
  60499. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  60500. else if (orientation == verticalKeyboardFacingRight)
  60501. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  60502. }
  60503. }
  60504. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  60505. {
  60506. octaveNumForMiddleC = octaveNumForMiddleC_;
  60507. repaint();
  60508. }
  60509. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  60510. {
  60511. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  60512. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  60513. return String::empty;
  60514. }
  60515. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  60516. const bool isMouseOver_,
  60517. const bool isButtonDown,
  60518. const bool movesOctavesUp)
  60519. {
  60520. g.fillAll (findColour (upDownButtonBackgroundColourId));
  60521. float angle;
  60522. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  60523. angle = movesOctavesUp ? 0.0f : 0.5f;
  60524. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  60525. angle = movesOctavesUp ? 0.25f : 0.75f;
  60526. else
  60527. angle = movesOctavesUp ? 0.75f : 0.25f;
  60528. Path path;
  60529. path.lineTo (0.0f, 1.0f);
  60530. path.lineTo (1.0f, 0.5f);
  60531. path.closeSubPath();
  60532. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  60533. g.setColour (findColour (upDownButtonArrowColourId)
  60534. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  60535. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  60536. w - 2.0f,
  60537. h - 2.0f,
  60538. true));
  60539. }
  60540. void MidiKeyboardComponent::resized()
  60541. {
  60542. int w = getWidth();
  60543. int h = getHeight();
  60544. if (w > 0 && h > 0)
  60545. {
  60546. if (orientation != horizontalKeyboard)
  60547. swapVariables (w, h);
  60548. blackNoteLength = roundToInt (h * 0.7f);
  60549. int kx2, kw2;
  60550. getKeyPos (rangeEnd, kx2, kw2);
  60551. kx2 += kw2;
  60552. if (firstKey != rangeStart)
  60553. {
  60554. int kx1, kw1;
  60555. getKeyPos (rangeStart, kx1, kw1);
  60556. if (kx2 - kx1 <= w)
  60557. {
  60558. firstKey = rangeStart;
  60559. sendChangeMessage();
  60560. repaint();
  60561. }
  60562. }
  60563. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  60564. scrollDown->setVisible (showScrollButtons);
  60565. scrollUp->setVisible (showScrollButtons);
  60566. xOffset = 0;
  60567. if (showScrollButtons)
  60568. {
  60569. const int scrollButtonW = jmin (12, w / 2);
  60570. if (orientation == horizontalKeyboard)
  60571. {
  60572. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  60573. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  60574. }
  60575. else if (orientation == verticalKeyboardFacingLeft)
  60576. {
  60577. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  60578. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60579. }
  60580. else if (orientation == verticalKeyboardFacingRight)
  60581. {
  60582. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  60583. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  60584. }
  60585. int endOfLastKey, kw;
  60586. getKeyPos (rangeEnd, endOfLastKey, kw);
  60587. endOfLastKey += kw;
  60588. float mousePositionVelocity;
  60589. const int spaceAvailable = w - scrollButtonW * 2;
  60590. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  60591. if (lastStartKey >= 0 && firstKey > lastStartKey)
  60592. {
  60593. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  60594. sendChangeMessage();
  60595. }
  60596. int newOffset = 0;
  60597. getKeyPos (firstKey, newOffset, kw);
  60598. xOffset = newOffset - scrollButtonW;
  60599. }
  60600. else
  60601. {
  60602. firstKey = rangeStart;
  60603. }
  60604. timerCallback();
  60605. repaint();
  60606. }
  60607. }
  60608. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  60609. {
  60610. triggerAsyncUpdate();
  60611. }
  60612. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  60613. {
  60614. triggerAsyncUpdate();
  60615. }
  60616. void MidiKeyboardComponent::handleAsyncUpdate()
  60617. {
  60618. for (int i = rangeStart; i <= rangeEnd; ++i)
  60619. {
  60620. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  60621. {
  60622. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  60623. repaintNote (i);
  60624. }
  60625. }
  60626. }
  60627. void MidiKeyboardComponent::resetAnyKeysInUse()
  60628. {
  60629. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  60630. {
  60631. state.allNotesOff (midiChannel);
  60632. keysPressed.clear();
  60633. mouseDownNote = -1;
  60634. }
  60635. }
  60636. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  60637. {
  60638. float mousePositionVelocity = 0.0f;
  60639. const int newNote = (mouseDragging || isMouseOver())
  60640. ? xyToNote (pos, mousePositionVelocity) : -1;
  60641. if (noteUnderMouse != newNote)
  60642. {
  60643. if (mouseDownNote >= 0)
  60644. {
  60645. state.noteOff (midiChannel, mouseDownNote);
  60646. mouseDownNote = -1;
  60647. }
  60648. if (mouseDragging && newNote >= 0)
  60649. {
  60650. if (! useMousePositionForVelocity)
  60651. mousePositionVelocity = 1.0f;
  60652. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  60653. mouseDownNote = newNote;
  60654. }
  60655. repaintNote (noteUnderMouse);
  60656. noteUnderMouse = newNote;
  60657. repaintNote (noteUnderMouse);
  60658. }
  60659. else if (mouseDownNote >= 0 && ! mouseDragging)
  60660. {
  60661. state.noteOff (midiChannel, mouseDownNote);
  60662. mouseDownNote = -1;
  60663. }
  60664. }
  60665. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  60666. {
  60667. updateNoteUnderMouse (e.getPosition());
  60668. stopTimer();
  60669. }
  60670. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  60671. {
  60672. float mousePositionVelocity;
  60673. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60674. if (newNote >= 0)
  60675. mouseDraggedToKey (newNote, e);
  60676. updateNoteUnderMouse (e.getPosition());
  60677. }
  60678. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  60679. {
  60680. return true;
  60681. }
  60682. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  60683. {
  60684. }
  60685. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  60686. {
  60687. float mousePositionVelocity;
  60688. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  60689. mouseDragging = false;
  60690. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  60691. {
  60692. repaintNote (noteUnderMouse);
  60693. noteUnderMouse = -1;
  60694. mouseDragging = true;
  60695. updateNoteUnderMouse (e.getPosition());
  60696. startTimer (500);
  60697. }
  60698. }
  60699. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  60700. {
  60701. mouseDragging = false;
  60702. updateNoteUnderMouse (e.getPosition());
  60703. stopTimer();
  60704. }
  60705. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  60706. {
  60707. updateNoteUnderMouse (e.getPosition());
  60708. }
  60709. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  60710. {
  60711. updateNoteUnderMouse (e.getPosition());
  60712. }
  60713. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  60714. {
  60715. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  60716. }
  60717. void MidiKeyboardComponent::timerCallback()
  60718. {
  60719. updateNoteUnderMouse (getMouseXYRelative());
  60720. }
  60721. void MidiKeyboardComponent::clearKeyMappings()
  60722. {
  60723. resetAnyKeysInUse();
  60724. keyPressNotes.clear();
  60725. keyPresses.clear();
  60726. }
  60727. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  60728. const int midiNoteOffsetFromC)
  60729. {
  60730. removeKeyPressForNote (midiNoteOffsetFromC);
  60731. keyPressNotes.add (midiNoteOffsetFromC);
  60732. keyPresses.add (key);
  60733. }
  60734. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  60735. {
  60736. for (int i = keyPressNotes.size(); --i >= 0;)
  60737. {
  60738. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  60739. {
  60740. keyPressNotes.remove (i);
  60741. keyPresses.remove (i);
  60742. }
  60743. }
  60744. }
  60745. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  60746. {
  60747. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  60748. keyMappingOctave = newOctaveNumber;
  60749. }
  60750. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  60751. {
  60752. bool keyPressUsed = false;
  60753. for (int i = keyPresses.size(); --i >= 0;)
  60754. {
  60755. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  60756. if (keyPresses.getReference(i).isCurrentlyDown())
  60757. {
  60758. if (! keysPressed [note])
  60759. {
  60760. keysPressed.setBit (note);
  60761. state.noteOn (midiChannel, note, velocity);
  60762. keyPressUsed = true;
  60763. }
  60764. }
  60765. else
  60766. {
  60767. if (keysPressed [note])
  60768. {
  60769. keysPressed.clearBit (note);
  60770. state.noteOff (midiChannel, note);
  60771. keyPressUsed = true;
  60772. }
  60773. }
  60774. }
  60775. return keyPressUsed;
  60776. }
  60777. void MidiKeyboardComponent::focusLost (FocusChangeType)
  60778. {
  60779. resetAnyKeysInUse();
  60780. }
  60781. END_JUCE_NAMESPACE
  60782. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60783. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  60784. #if JUCE_OPENGL
  60785. BEGIN_JUCE_NAMESPACE
  60786. extern void juce_glViewport (const int w, const int h);
  60787. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  60788. const int alphaBits_,
  60789. const int depthBufferBits_,
  60790. const int stencilBufferBits_)
  60791. : redBits (bitsPerRGBComponent),
  60792. greenBits (bitsPerRGBComponent),
  60793. blueBits (bitsPerRGBComponent),
  60794. alphaBits (alphaBits_),
  60795. depthBufferBits (depthBufferBits_),
  60796. stencilBufferBits (stencilBufferBits_),
  60797. accumulationBufferRedBits (0),
  60798. accumulationBufferGreenBits (0),
  60799. accumulationBufferBlueBits (0),
  60800. accumulationBufferAlphaBits (0),
  60801. fullSceneAntiAliasingNumSamples (0)
  60802. {
  60803. }
  60804. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  60805. : redBits (other.redBits),
  60806. greenBits (other.greenBits),
  60807. blueBits (other.blueBits),
  60808. alphaBits (other.alphaBits),
  60809. depthBufferBits (other.depthBufferBits),
  60810. stencilBufferBits (other.stencilBufferBits),
  60811. accumulationBufferRedBits (other.accumulationBufferRedBits),
  60812. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  60813. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  60814. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  60815. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  60816. {
  60817. }
  60818. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  60819. {
  60820. redBits = other.redBits;
  60821. greenBits = other.greenBits;
  60822. blueBits = other.blueBits;
  60823. alphaBits = other.alphaBits;
  60824. depthBufferBits = other.depthBufferBits;
  60825. stencilBufferBits = other.stencilBufferBits;
  60826. accumulationBufferRedBits = other.accumulationBufferRedBits;
  60827. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  60828. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  60829. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  60830. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  60831. return *this;
  60832. }
  60833. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  60834. {
  60835. return redBits == other.redBits
  60836. && greenBits == other.greenBits
  60837. && blueBits == other.blueBits
  60838. && alphaBits == other.alphaBits
  60839. && depthBufferBits == other.depthBufferBits
  60840. && stencilBufferBits == other.stencilBufferBits
  60841. && accumulationBufferRedBits == other.accumulationBufferRedBits
  60842. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  60843. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  60844. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  60845. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  60846. }
  60847. static Array<OpenGLContext*> knownContexts;
  60848. OpenGLContext::OpenGLContext() throw()
  60849. {
  60850. knownContexts.add (this);
  60851. }
  60852. OpenGLContext::~OpenGLContext()
  60853. {
  60854. knownContexts.removeValue (this);
  60855. }
  60856. OpenGLContext* OpenGLContext::getCurrentContext()
  60857. {
  60858. for (int i = knownContexts.size(); --i >= 0;)
  60859. {
  60860. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  60861. if (oglc->isActive())
  60862. return oglc;
  60863. }
  60864. return 0;
  60865. }
  60866. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  60867. {
  60868. public:
  60869. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  60870. : ComponentMovementWatcher (owner_),
  60871. owner (owner_)
  60872. {
  60873. }
  60874. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  60875. {
  60876. owner->updateContextPosition();
  60877. }
  60878. void componentPeerChanged()
  60879. {
  60880. const ScopedLock sl (owner->getContextLock());
  60881. owner->deleteContext();
  60882. }
  60883. void componentVisibilityChanged()
  60884. {
  60885. if (! owner->isShowing())
  60886. {
  60887. const ScopedLock sl (owner->getContextLock());
  60888. owner->deleteContext();
  60889. }
  60890. }
  60891. private:
  60892. OpenGLComponent* const owner;
  60893. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLComponentWatcher);
  60894. };
  60895. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  60896. : type (type_),
  60897. contextToShareListsWith (0),
  60898. needToUpdateViewport (true)
  60899. {
  60900. setOpaque (true);
  60901. componentWatcher = new OpenGLComponentWatcher (this);
  60902. }
  60903. OpenGLComponent::~OpenGLComponent()
  60904. {
  60905. deleteContext();
  60906. componentWatcher = 0;
  60907. }
  60908. void OpenGLComponent::deleteContext()
  60909. {
  60910. const ScopedLock sl (contextLock);
  60911. context = 0;
  60912. }
  60913. void OpenGLComponent::updateContextPosition()
  60914. {
  60915. needToUpdateViewport = true;
  60916. if (getWidth() > 0 && getHeight() > 0)
  60917. {
  60918. Component* const topComp = getTopLevelComponent();
  60919. if (topComp->getPeer() != 0)
  60920. {
  60921. const ScopedLock sl (contextLock);
  60922. if (context != 0)
  60923. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  60924. getScreenY() - topComp->getScreenY(),
  60925. getWidth(),
  60926. getHeight(),
  60927. topComp->getHeight());
  60928. }
  60929. }
  60930. }
  60931. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  60932. {
  60933. OpenGLPixelFormat pf;
  60934. const ScopedLock sl (contextLock);
  60935. if (context != 0)
  60936. pf = context->getPixelFormat();
  60937. return pf;
  60938. }
  60939. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  60940. {
  60941. if (! (preferredPixelFormat == formatToUse))
  60942. {
  60943. const ScopedLock sl (contextLock);
  60944. deleteContext();
  60945. preferredPixelFormat = formatToUse;
  60946. }
  60947. }
  60948. void OpenGLComponent::shareWith (OpenGLContext* c)
  60949. {
  60950. if (contextToShareListsWith != c)
  60951. {
  60952. const ScopedLock sl (contextLock);
  60953. deleteContext();
  60954. contextToShareListsWith = c;
  60955. }
  60956. }
  60957. bool OpenGLComponent::makeCurrentContextActive()
  60958. {
  60959. if (context == 0)
  60960. {
  60961. const ScopedLock sl (contextLock);
  60962. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  60963. {
  60964. context = createContext();
  60965. if (context != 0)
  60966. {
  60967. updateContextPosition();
  60968. if (context->makeActive())
  60969. newOpenGLContextCreated();
  60970. }
  60971. }
  60972. }
  60973. return context != 0 && context->makeActive();
  60974. }
  60975. void OpenGLComponent::makeCurrentContextInactive()
  60976. {
  60977. if (context != 0)
  60978. context->makeInactive();
  60979. }
  60980. bool OpenGLComponent::isActiveContext() const throw()
  60981. {
  60982. return context != 0 && context->isActive();
  60983. }
  60984. void OpenGLComponent::swapBuffers()
  60985. {
  60986. if (context != 0)
  60987. context->swapBuffers();
  60988. }
  60989. void OpenGLComponent::paint (Graphics&)
  60990. {
  60991. if (renderAndSwapBuffers())
  60992. {
  60993. ComponentPeer* const peer = getPeer();
  60994. if (peer != 0)
  60995. {
  60996. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  60997. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  60998. }
  60999. }
  61000. }
  61001. bool OpenGLComponent::renderAndSwapBuffers()
  61002. {
  61003. const ScopedLock sl (contextLock);
  61004. if (! makeCurrentContextActive())
  61005. return false;
  61006. if (needToUpdateViewport)
  61007. {
  61008. needToUpdateViewport = false;
  61009. juce_glViewport (getWidth(), getHeight());
  61010. }
  61011. renderOpenGL();
  61012. swapBuffers();
  61013. return true;
  61014. }
  61015. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61016. {
  61017. Component::internalRepaint (x, y, w, h);
  61018. if (context != 0)
  61019. context->repaint();
  61020. }
  61021. END_JUCE_NAMESPACE
  61022. #endif
  61023. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61024. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61025. BEGIN_JUCE_NAMESPACE
  61026. PreferencesPanel::PreferencesPanel()
  61027. : buttonSize (70)
  61028. {
  61029. }
  61030. PreferencesPanel::~PreferencesPanel()
  61031. {
  61032. }
  61033. void PreferencesPanel::addSettingsPage (const String& title,
  61034. const Drawable* icon,
  61035. const Drawable* overIcon,
  61036. const Drawable* downIcon)
  61037. {
  61038. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61039. buttons.add (button);
  61040. button->setImages (icon, overIcon, downIcon);
  61041. button->setRadioGroupId (1);
  61042. button->addListener (this);
  61043. button->setClickingTogglesState (true);
  61044. button->setWantsKeyboardFocus (false);
  61045. addAndMakeVisible (button);
  61046. resized();
  61047. if (currentPage == 0)
  61048. setCurrentPage (title);
  61049. }
  61050. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61051. {
  61052. DrawableImage icon, iconOver, iconDown;
  61053. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61054. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61055. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61056. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61057. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61058. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61059. }
  61060. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61061. {
  61062. setSize (dialogWidth, dialogHeight);
  61063. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61064. }
  61065. void PreferencesPanel::resized()
  61066. {
  61067. for (int i = 0; i < buttons.size(); ++i)
  61068. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61069. if (currentPage != 0)
  61070. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61071. }
  61072. void PreferencesPanel::paint (Graphics& g)
  61073. {
  61074. g.setColour (Colours::grey);
  61075. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61076. }
  61077. void PreferencesPanel::setCurrentPage (const String& pageName)
  61078. {
  61079. if (currentPageName != pageName)
  61080. {
  61081. currentPageName = pageName;
  61082. currentPage = 0;
  61083. currentPage = createComponentForPage (pageName);
  61084. if (currentPage != 0)
  61085. {
  61086. addAndMakeVisible (currentPage);
  61087. currentPage->toBack();
  61088. resized();
  61089. }
  61090. for (int i = 0; i < buttons.size(); ++i)
  61091. {
  61092. if (buttons.getUnchecked(i)->getName() == pageName)
  61093. {
  61094. buttons.getUnchecked(i)->setToggleState (true, false);
  61095. break;
  61096. }
  61097. }
  61098. }
  61099. }
  61100. void PreferencesPanel::buttonClicked (Button*)
  61101. {
  61102. for (int i = 0; i < buttons.size(); ++i)
  61103. {
  61104. if (buttons.getUnchecked(i)->getToggleState())
  61105. {
  61106. setCurrentPage (buttons.getUnchecked(i)->getName());
  61107. break;
  61108. }
  61109. }
  61110. }
  61111. END_JUCE_NAMESPACE
  61112. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61113. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61114. #if JUCE_WINDOWS || JUCE_LINUX
  61115. BEGIN_JUCE_NAMESPACE
  61116. SystemTrayIconComponent::SystemTrayIconComponent()
  61117. {
  61118. addToDesktop (0);
  61119. }
  61120. SystemTrayIconComponent::~SystemTrayIconComponent()
  61121. {
  61122. }
  61123. END_JUCE_NAMESPACE
  61124. #endif
  61125. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61126. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61127. BEGIN_JUCE_NAMESPACE
  61128. class AlertWindowTextEditor : public TextEditor
  61129. {
  61130. public:
  61131. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61132. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61133. {
  61134. setSelectAllWhenFocused (true);
  61135. }
  61136. void returnPressed()
  61137. {
  61138. // pass these up the component hierarchy to be trigger the buttons
  61139. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61140. }
  61141. void escapePressed()
  61142. {
  61143. // pass these up the component hierarchy to be trigger the buttons
  61144. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61145. }
  61146. private:
  61147. JUCE_DECLARE_NON_COPYABLE (AlertWindowTextEditor);
  61148. static juce_wchar getDefaultPasswordChar() throw()
  61149. {
  61150. #if JUCE_LINUX
  61151. return 0x2022;
  61152. #else
  61153. return 0x25cf;
  61154. #endif
  61155. }
  61156. };
  61157. AlertWindow::AlertWindow (const String& title,
  61158. const String& message,
  61159. AlertIconType iconType,
  61160. Component* associatedComponent_)
  61161. : TopLevelWindow (title, true),
  61162. alertIconType (iconType),
  61163. associatedComponent (associatedComponent_)
  61164. {
  61165. if (message.isEmpty())
  61166. text = " "; // to force an update if the message is empty
  61167. setMessage (message);
  61168. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  61169. {
  61170. Component* const c = Desktop::getInstance().getComponent (i);
  61171. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  61172. {
  61173. setAlwaysOnTop (true);
  61174. break;
  61175. }
  61176. }
  61177. if (! JUCEApplication::isStandaloneApp())
  61178. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61179. lookAndFeelChanged();
  61180. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  61181. }
  61182. AlertWindow::~AlertWindow()
  61183. {
  61184. removeAllChildren();
  61185. }
  61186. void AlertWindow::userTriedToCloseWindow()
  61187. {
  61188. exitModalState (0);
  61189. }
  61190. void AlertWindow::setMessage (const String& message)
  61191. {
  61192. const String newMessage (message.substring (0, 2048));
  61193. if (text != newMessage)
  61194. {
  61195. text = newMessage;
  61196. font = getLookAndFeel().getAlertWindowMessageFont();
  61197. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  61198. textLayout.setText (getName() + "\n\n", titleFont);
  61199. textLayout.appendText (text, font);
  61200. updateLayout (true);
  61201. repaint();
  61202. }
  61203. }
  61204. void AlertWindow::buttonClicked (Button* button)
  61205. {
  61206. if (button->getParentComponent() != 0)
  61207. button->getParentComponent()->exitModalState (button->getCommandID());
  61208. }
  61209. void AlertWindow::addButton (const String& name,
  61210. const int returnValue,
  61211. const KeyPress& shortcutKey1,
  61212. const KeyPress& shortcutKey2)
  61213. {
  61214. TextButton* const b = new TextButton (name, String::empty);
  61215. buttons.add (b);
  61216. b->setWantsKeyboardFocus (true);
  61217. b->setMouseClickGrabsKeyboardFocus (false);
  61218. b->setCommandToTrigger (0, returnValue, false);
  61219. b->addShortcut (shortcutKey1);
  61220. b->addShortcut (shortcutKey2);
  61221. b->addListener (this);
  61222. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  61223. addAndMakeVisible (b, 0);
  61224. updateLayout (false);
  61225. }
  61226. int AlertWindow::getNumButtons() const
  61227. {
  61228. return buttons.size();
  61229. }
  61230. void AlertWindow::triggerButtonClick (const String& buttonName)
  61231. {
  61232. for (int i = buttons.size(); --i >= 0;)
  61233. {
  61234. TextButton* const b = buttons.getUnchecked(i);
  61235. if (buttonName == b->getName())
  61236. {
  61237. b->triggerClick();
  61238. break;
  61239. }
  61240. }
  61241. }
  61242. void AlertWindow::addTextEditor (const String& name,
  61243. const String& initialContents,
  61244. const String& onScreenLabel,
  61245. const bool isPasswordBox)
  61246. {
  61247. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  61248. textBoxes.add (tc);
  61249. allComps.add (tc);
  61250. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  61251. tc->setFont (font);
  61252. tc->setText (initialContents);
  61253. tc->setCaretPosition (initialContents.length());
  61254. addAndMakeVisible (tc);
  61255. textboxNames.add (onScreenLabel);
  61256. updateLayout (false);
  61257. }
  61258. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  61259. {
  61260. for (int i = textBoxes.size(); --i >= 0;)
  61261. if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
  61262. return textBoxes.getUnchecked(i);
  61263. return 0;
  61264. }
  61265. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  61266. {
  61267. TextEditor* const t = getTextEditor (nameOfTextEditor);
  61268. return t != 0 ? t->getText() : String::empty;
  61269. }
  61270. void AlertWindow::addComboBox (const String& name,
  61271. const StringArray& items,
  61272. const String& onScreenLabel)
  61273. {
  61274. ComboBox* const cb = new ComboBox (name);
  61275. comboBoxes.add (cb);
  61276. allComps.add (cb);
  61277. for (int i = 0; i < items.size(); ++i)
  61278. cb->addItem (items[i], i + 1);
  61279. addAndMakeVisible (cb);
  61280. cb->setSelectedItemIndex (0);
  61281. comboBoxNames.add (onScreenLabel);
  61282. updateLayout (false);
  61283. }
  61284. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  61285. {
  61286. for (int i = comboBoxes.size(); --i >= 0;)
  61287. if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
  61288. return comboBoxes.getUnchecked(i);
  61289. return 0;
  61290. }
  61291. class AlertTextComp : public TextEditor
  61292. {
  61293. public:
  61294. AlertTextComp (const String& message,
  61295. const Font& font)
  61296. {
  61297. setReadOnly (true);
  61298. setMultiLine (true, true);
  61299. setCaretVisible (false);
  61300. setScrollbarsShown (true);
  61301. lookAndFeelChanged();
  61302. setWantsKeyboardFocus (false);
  61303. setFont (font);
  61304. setText (message, false);
  61305. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  61306. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  61307. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  61308. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  61309. }
  61310. ~AlertTextComp()
  61311. {
  61312. }
  61313. int getPreferredWidth() const throw() { return bestWidth; }
  61314. void updateLayout (const int width)
  61315. {
  61316. TextLayout text;
  61317. text.appendText (getText(), getFont());
  61318. text.layout (width - 8, Justification::topLeft, true);
  61319. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  61320. }
  61321. private:
  61322. int bestWidth;
  61323. JUCE_DECLARE_NON_COPYABLE (AlertTextComp);
  61324. };
  61325. void AlertWindow::addTextBlock (const String& textBlock)
  61326. {
  61327. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  61328. textBlocks.add (c);
  61329. allComps.add (c);
  61330. addAndMakeVisible (c);
  61331. updateLayout (false);
  61332. }
  61333. void AlertWindow::addProgressBarComponent (double& progressValue)
  61334. {
  61335. ProgressBar* const pb = new ProgressBar (progressValue);
  61336. progressBars.add (pb);
  61337. allComps.add (pb);
  61338. addAndMakeVisible (pb);
  61339. updateLayout (false);
  61340. }
  61341. void AlertWindow::addCustomComponent (Component* const component)
  61342. {
  61343. customComps.add (component);
  61344. allComps.add (component);
  61345. addAndMakeVisible (component);
  61346. updateLayout (false);
  61347. }
  61348. int AlertWindow::getNumCustomComponents() const
  61349. {
  61350. return customComps.size();
  61351. }
  61352. Component* AlertWindow::getCustomComponent (const int index) const
  61353. {
  61354. return customComps [index];
  61355. }
  61356. Component* AlertWindow::removeCustomComponent (const int index)
  61357. {
  61358. Component* const c = getCustomComponent (index);
  61359. if (c != 0)
  61360. {
  61361. customComps.removeValue (c);
  61362. allComps.removeValue (c);
  61363. removeChildComponent (c);
  61364. updateLayout (false);
  61365. }
  61366. return c;
  61367. }
  61368. void AlertWindow::paint (Graphics& g)
  61369. {
  61370. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  61371. g.setColour (findColour (textColourId));
  61372. g.setFont (getLookAndFeel().getAlertWindowFont());
  61373. int i;
  61374. for (i = textBoxes.size(); --i >= 0;)
  61375. {
  61376. const TextEditor* const te = textBoxes.getUnchecked(i);
  61377. g.drawFittedText (textboxNames[i],
  61378. te->getX(), te->getY() - 14,
  61379. te->getWidth(), 14,
  61380. Justification::centredLeft, 1);
  61381. }
  61382. for (i = comboBoxNames.size(); --i >= 0;)
  61383. {
  61384. const ComboBox* const cb = comboBoxes.getUnchecked(i);
  61385. g.drawFittedText (comboBoxNames[i],
  61386. cb->getX(), cb->getY() - 14,
  61387. cb->getWidth(), 14,
  61388. Justification::centredLeft, 1);
  61389. }
  61390. for (i = customComps.size(); --i >= 0;)
  61391. {
  61392. const Component* const c = customComps.getUnchecked(i);
  61393. g.drawFittedText (c->getName(),
  61394. c->getX(), c->getY() - 14,
  61395. c->getWidth(), 14,
  61396. Justification::centredLeft, 1);
  61397. }
  61398. }
  61399. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  61400. {
  61401. const int titleH = 24;
  61402. const int iconWidth = 80;
  61403. const int wid = jmax (font.getStringWidth (text),
  61404. font.getStringWidth (getName()));
  61405. const int sw = (int) std::sqrt (font.getHeight() * wid);
  61406. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  61407. const int edgeGap = 10;
  61408. const int labelHeight = 18;
  61409. int iconSpace;
  61410. if (alertIconType == NoIcon)
  61411. {
  61412. textLayout.layout (w, Justification::horizontallyCentred, true);
  61413. iconSpace = 0;
  61414. }
  61415. else
  61416. {
  61417. textLayout.layout (w, Justification::left, true);
  61418. iconSpace = iconWidth;
  61419. }
  61420. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  61421. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61422. const int textLayoutH = textLayout.getHeight();
  61423. const int textBottom = 16 + titleH + textLayoutH;
  61424. int h = textBottom;
  61425. int buttonW = 40;
  61426. int i;
  61427. for (i = 0; i < buttons.size(); ++i)
  61428. buttonW += 16 + buttons.getUnchecked(i)->getWidth();
  61429. w = jmax (buttonW, w);
  61430. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  61431. if (buttons.size() > 0)
  61432. h += 20 + buttons.getUnchecked(0)->getHeight();
  61433. for (i = customComps.size(); --i >= 0;)
  61434. {
  61435. Component* c = customComps.getUnchecked(i);
  61436. w = jmax (w, (c->getWidth() * 100) / 80);
  61437. h += 10 + c->getHeight();
  61438. if (c->getName().isNotEmpty())
  61439. h += labelHeight;
  61440. }
  61441. for (i = textBlocks.size(); --i >= 0;)
  61442. {
  61443. const AlertTextComp* const ac = static_cast <const AlertTextComp*> (textBlocks.getUnchecked(i));
  61444. w = jmax (w, ac->getPreferredWidth());
  61445. }
  61446. w = jmin (w, (int) (getParentWidth() * 0.7f));
  61447. for (i = textBlocks.size(); --i >= 0;)
  61448. {
  61449. AlertTextComp* const ac = static_cast <AlertTextComp*> (textBlocks.getUnchecked(i));
  61450. ac->updateLayout ((int) (w * 0.8f));
  61451. h += ac->getHeight() + 10;
  61452. }
  61453. h = jmin (getParentHeight() - 50, h);
  61454. if (onlyIncreaseSize)
  61455. {
  61456. w = jmax (w, getWidth());
  61457. h = jmax (h, getHeight());
  61458. }
  61459. if (! isVisible())
  61460. {
  61461. centreAroundComponent (associatedComponent, w, h);
  61462. }
  61463. else
  61464. {
  61465. const int cx = getX() + getWidth() / 2;
  61466. const int cy = getY() + getHeight() / 2;
  61467. setBounds (cx - w / 2,
  61468. cy - h / 2,
  61469. w, h);
  61470. }
  61471. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  61472. const int spacer = 16;
  61473. int totalWidth = -spacer;
  61474. for (i = buttons.size(); --i >= 0;)
  61475. totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;
  61476. int x = (w - totalWidth) / 2;
  61477. int y = (int) (getHeight() * 0.95f);
  61478. for (i = 0; i < buttons.size(); ++i)
  61479. {
  61480. TextButton* const c = buttons.getUnchecked(i);
  61481. int ny = proportionOfHeight (0.95f) - c->getHeight();
  61482. c->setTopLeftPosition (x, ny);
  61483. if (ny < y)
  61484. y = ny;
  61485. x += c->getWidth() + spacer;
  61486. c->toFront (false);
  61487. }
  61488. y = textBottom;
  61489. for (i = 0; i < allComps.size(); ++i)
  61490. {
  61491. Component* const c = allComps.getUnchecked(i);
  61492. h = 22;
  61493. const int comboIndex = comboBoxes.indexOf (dynamic_cast <ComboBox*> (c));
  61494. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  61495. y += labelHeight;
  61496. const int tbIndex = textBoxes.indexOf (dynamic_cast <TextEditor*> (c));
  61497. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  61498. y += labelHeight;
  61499. if (customComps.contains (c))
  61500. {
  61501. if (c->getName().isNotEmpty())
  61502. y += labelHeight;
  61503. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  61504. h = c->getHeight();
  61505. }
  61506. else if (textBlocks.contains (c))
  61507. {
  61508. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  61509. h = c->getHeight();
  61510. }
  61511. else
  61512. {
  61513. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  61514. }
  61515. y += h + 10;
  61516. }
  61517. setWantsKeyboardFocus (getNumChildComponents() == 0);
  61518. }
  61519. bool AlertWindow::containsAnyExtraComponents() const
  61520. {
  61521. return allComps.size() > 0;
  61522. }
  61523. void AlertWindow::mouseDown (const MouseEvent& e)
  61524. {
  61525. dragger.startDraggingComponent (this, e);
  61526. }
  61527. void AlertWindow::mouseDrag (const MouseEvent& e)
  61528. {
  61529. dragger.dragComponent (this, e, &constrainer);
  61530. }
  61531. bool AlertWindow::keyPressed (const KeyPress& key)
  61532. {
  61533. for (int i = buttons.size(); --i >= 0;)
  61534. {
  61535. TextButton* const b = buttons.getUnchecked(i);
  61536. if (b->isRegisteredForShortcut (key))
  61537. {
  61538. b->triggerClick();
  61539. return true;
  61540. }
  61541. }
  61542. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  61543. {
  61544. exitModalState (0);
  61545. return true;
  61546. }
  61547. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  61548. {
  61549. buttons.getUnchecked(0)->triggerClick();
  61550. return true;
  61551. }
  61552. return false;
  61553. }
  61554. void AlertWindow::lookAndFeelChanged()
  61555. {
  61556. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  61557. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  61558. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  61559. }
  61560. int AlertWindow::getDesktopWindowStyleFlags() const
  61561. {
  61562. return getLookAndFeel().getAlertBoxWindowFlags();
  61563. }
  61564. class AlertWindowInfo
  61565. {
  61566. public:
  61567. AlertWindowInfo (const String& title_, const String& message_, Component* component,
  61568. AlertWindow::AlertIconType iconType_, int numButtons_)
  61569. : title (title_), message (message_), iconType (iconType_),
  61570. numButtons (numButtons_), returnValue (0), associatedComponent (component)
  61571. {
  61572. }
  61573. String title, message, button1, button2, button3;
  61574. AlertWindow::AlertIconType iconType;
  61575. int numButtons, returnValue;
  61576. WeakReference<Component> associatedComponent;
  61577. int showModal() const
  61578. {
  61579. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  61580. return returnValue;
  61581. }
  61582. private:
  61583. void show()
  61584. {
  61585. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  61586. : LookAndFeel::getDefaultLookAndFeel();
  61587. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  61588. iconType, numButtons, associatedComponent));
  61589. jassert (alertBox != 0); // you have to return one of these!
  61590. returnValue = alertBox->runModalLoop();
  61591. }
  61592. static void* showCallback (void* userData)
  61593. {
  61594. static_cast <AlertWindowInfo*> (userData)->show();
  61595. return 0;
  61596. }
  61597. };
  61598. void AlertWindow::showMessageBox (AlertIconType iconType,
  61599. const String& title,
  61600. const String& message,
  61601. const String& buttonText,
  61602. Component* associatedComponent)
  61603. {
  61604. AlertWindowInfo info (title, message, associatedComponent, iconType, 1);
  61605. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  61606. info.showModal();
  61607. }
  61608. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  61609. const String& title,
  61610. const String& message,
  61611. const String& button1Text,
  61612. const String& button2Text,
  61613. Component* associatedComponent)
  61614. {
  61615. AlertWindowInfo info (title, message, associatedComponent, iconType, 2);
  61616. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  61617. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  61618. return info.showModal() != 0;
  61619. }
  61620. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  61621. const String& title,
  61622. const String& message,
  61623. const String& button1Text,
  61624. const String& button2Text,
  61625. const String& button3Text,
  61626. Component* associatedComponent)
  61627. {
  61628. AlertWindowInfo info (title, message, associatedComponent, iconType, 3);
  61629. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  61630. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  61631. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  61632. return info.showModal();
  61633. }
  61634. END_JUCE_NAMESPACE
  61635. /*** End of inlined file: juce_AlertWindow.cpp ***/
  61636. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  61637. BEGIN_JUCE_NAMESPACE
  61638. CallOutBox::CallOutBox (Component& contentComponent,
  61639. Component& componentToPointTo,
  61640. Component* const parentComponent)
  61641. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  61642. {
  61643. addAndMakeVisible (&content);
  61644. if (parentComponent != 0)
  61645. {
  61646. parentComponent->addChildComponent (this);
  61647. updatePosition (parentComponent->getLocalArea (&componentToPointTo, componentToPointTo.getLocalBounds()),
  61648. parentComponent->getLocalBounds());
  61649. setVisible (true);
  61650. }
  61651. else
  61652. {
  61653. if (! JUCEApplication::isStandaloneApp())
  61654. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  61655. updatePosition (componentToPointTo.getScreenBounds(),
  61656. componentToPointTo.getParentMonitorArea());
  61657. addToDesktop (ComponentPeer::windowIsTemporary);
  61658. }
  61659. }
  61660. CallOutBox::~CallOutBox()
  61661. {
  61662. }
  61663. void CallOutBox::setArrowSize (const float newSize)
  61664. {
  61665. arrowSize = newSize;
  61666. borderSpace = jmax (20, (int) arrowSize);
  61667. refreshPath();
  61668. }
  61669. void CallOutBox::paint (Graphics& g)
  61670. {
  61671. if (background.isNull())
  61672. {
  61673. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  61674. Graphics g2 (background);
  61675. getLookAndFeel().drawCallOutBoxBackground (*this, g2, outline);
  61676. }
  61677. g.setColour (Colours::black);
  61678. g.drawImageAt (background, 0, 0);
  61679. }
  61680. void CallOutBox::resized()
  61681. {
  61682. content.setTopLeftPosition (borderSpace, borderSpace);
  61683. refreshPath();
  61684. }
  61685. void CallOutBox::moved()
  61686. {
  61687. refreshPath();
  61688. }
  61689. void CallOutBox::childBoundsChanged (Component*)
  61690. {
  61691. updatePosition (targetArea, availableArea);
  61692. }
  61693. bool CallOutBox::hitTest (int x, int y)
  61694. {
  61695. return outline.contains ((float) x, (float) y);
  61696. }
  61697. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  61698. void CallOutBox::inputAttemptWhenModal()
  61699. {
  61700. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  61701. if (targetArea.contains (mousePos))
  61702. {
  61703. // if you click on the area that originally popped-up the callout, you expect it
  61704. // to get rid of the box, but deleting the box here allows the click to pass through and
  61705. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  61706. postCommandMessage (callOutBoxDismissCommandId);
  61707. }
  61708. else
  61709. {
  61710. exitModalState (0);
  61711. setVisible (false);
  61712. }
  61713. }
  61714. void CallOutBox::handleCommandMessage (int commandId)
  61715. {
  61716. Component::handleCommandMessage (commandId);
  61717. if (commandId == callOutBoxDismissCommandId)
  61718. {
  61719. exitModalState (0);
  61720. setVisible (false);
  61721. }
  61722. }
  61723. bool CallOutBox::keyPressed (const KeyPress& key)
  61724. {
  61725. if (key.isKeyCode (KeyPress::escapeKey))
  61726. {
  61727. inputAttemptWhenModal();
  61728. return true;
  61729. }
  61730. return false;
  61731. }
  61732. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  61733. {
  61734. targetArea = newAreaToPointTo;
  61735. availableArea = newAreaToFitIn;
  61736. Rectangle<int> bounds (0, 0,
  61737. content.getWidth() + borderSpace * 2,
  61738. content.getHeight() + borderSpace * 2);
  61739. const int hw = bounds.getWidth() / 2;
  61740. const int hh = bounds.getHeight() / 2;
  61741. const float hwReduced = (float) (hw - borderSpace * 3);
  61742. const float hhReduced = (float) (hh - borderSpace * 3);
  61743. const float arrowIndent = borderSpace - arrowSize;
  61744. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  61745. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  61746. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  61747. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  61748. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  61749. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  61750. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  61751. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  61752. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  61753. float nearest = 1.0e9f;
  61754. for (int i = 0; i < 4; ++i)
  61755. {
  61756. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  61757. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  61758. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  61759. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  61760. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  61761. distanceFromCentre *= 2.0f;
  61762. if (distanceFromCentre < nearest)
  61763. {
  61764. nearest = distanceFromCentre;
  61765. targetPoint = targets[i];
  61766. bounds.setPosition ((int) (centre.getX() - hw),
  61767. (int) (centre.getY() - hh));
  61768. }
  61769. }
  61770. setBounds (bounds);
  61771. }
  61772. void CallOutBox::refreshPath()
  61773. {
  61774. repaint();
  61775. background = Image::null;
  61776. outline.clear();
  61777. const float gap = 4.5f;
  61778. const float cornerSize = 9.0f;
  61779. const float cornerSize2 = 2.0f * cornerSize;
  61780. const float arrowBaseWidth = arrowSize * 0.7f;
  61781. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  61782. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  61783. outline.startNewSubPath (left + cornerSize, top);
  61784. if (targetY <= top)
  61785. {
  61786. outline.lineTo (targetX - arrowBaseWidth, top);
  61787. outline.lineTo (targetX, targetY);
  61788. outline.lineTo (targetX + arrowBaseWidth, top);
  61789. }
  61790. outline.lineTo (right - cornerSize, top);
  61791. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  61792. if (targetX >= right)
  61793. {
  61794. outline.lineTo (right, targetY - arrowBaseWidth);
  61795. outline.lineTo (targetX, targetY);
  61796. outline.lineTo (right, targetY + arrowBaseWidth);
  61797. }
  61798. outline.lineTo (right, bottom - cornerSize);
  61799. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  61800. if (targetY >= bottom)
  61801. {
  61802. outline.lineTo (targetX + arrowBaseWidth, bottom);
  61803. outline.lineTo (targetX, targetY);
  61804. outline.lineTo (targetX - arrowBaseWidth, bottom);
  61805. }
  61806. outline.lineTo (left + cornerSize, bottom);
  61807. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  61808. if (targetX <= left)
  61809. {
  61810. outline.lineTo (left, targetY + arrowBaseWidth);
  61811. outline.lineTo (targetX, targetY);
  61812. outline.lineTo (left, targetY - arrowBaseWidth);
  61813. }
  61814. outline.lineTo (left, top + cornerSize);
  61815. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  61816. outline.closeSubPath();
  61817. }
  61818. END_JUCE_NAMESPACE
  61819. /*** End of inlined file: juce_CallOutBox.cpp ***/
  61820. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  61821. BEGIN_JUCE_NAMESPACE
  61822. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  61823. static Array <ComponentPeer*> heavyweightPeers;
  61824. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  61825. : component (component_),
  61826. styleFlags (styleFlags_),
  61827. lastPaintTime (0),
  61828. constrainer (0),
  61829. lastDragAndDropCompUnderMouse (0),
  61830. fakeMouseMessageSent (false),
  61831. isWindowMinimised (false)
  61832. {
  61833. heavyweightPeers.add (this);
  61834. }
  61835. ComponentPeer::~ComponentPeer()
  61836. {
  61837. heavyweightPeers.removeValue (this);
  61838. Desktop::getInstance().triggerFocusCallback();
  61839. }
  61840. int ComponentPeer::getNumPeers() throw()
  61841. {
  61842. return heavyweightPeers.size();
  61843. }
  61844. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  61845. {
  61846. return heavyweightPeers [index];
  61847. }
  61848. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  61849. {
  61850. for (int i = heavyweightPeers.size(); --i >= 0;)
  61851. {
  61852. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  61853. if (peer->getComponent() == component)
  61854. return peer;
  61855. }
  61856. return 0;
  61857. }
  61858. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  61859. {
  61860. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  61861. }
  61862. void ComponentPeer::updateCurrentModifiers() throw()
  61863. {
  61864. ModifierKeys::updateCurrentModifiers();
  61865. }
  61866. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  61867. {
  61868. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61869. jassert (mouse != 0); // not enough sources!
  61870. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  61871. }
  61872. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  61873. {
  61874. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  61875. jassert (mouse != 0); // not enough sources!
  61876. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  61877. }
  61878. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  61879. {
  61880. Graphics g (&contextToPaintTo);
  61881. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61882. g.saveState();
  61883. #endif
  61884. JUCE_TRY
  61885. {
  61886. component->paintEntireComponent (g, true);
  61887. }
  61888. JUCE_CATCH_EXCEPTION
  61889. #if JUCE_ENABLE_REPAINT_DEBUGGING
  61890. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  61891. // clearly when things are being repainted.
  61892. g.restoreState();
  61893. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  61894. (uint8) Random::getSystemRandom().nextInt (255),
  61895. (uint8) Random::getSystemRandom().nextInt (255),
  61896. (uint8) 0x50));
  61897. #endif
  61898. /** If this fails, it's probably be because your CPU floating-point precision mode has
  61899. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  61900. mess up a lot of the calculations that the library needs to do.
  61901. */
  61902. jassert (roundToInt (10.1f) == 10);
  61903. }
  61904. bool ComponentPeer::handleKeyPress (const int keyCode,
  61905. const juce_wchar textCharacter)
  61906. {
  61907. updateCurrentModifiers();
  61908. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61909. ? Component::getCurrentlyFocusedComponent()
  61910. : component;
  61911. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61912. {
  61913. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61914. if (currentModalComp != 0)
  61915. target = currentModalComp;
  61916. }
  61917. const KeyPress keyInfo (keyCode,
  61918. ModifierKeys::getCurrentModifiers().getRawFlags()
  61919. & ModifierKeys::allKeyboardModifiers,
  61920. textCharacter);
  61921. bool keyWasUsed = false;
  61922. while (target != 0)
  61923. {
  61924. const WeakReference<Component> deletionChecker (target);
  61925. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61926. if (keyListeners != 0)
  61927. {
  61928. for (int i = keyListeners->size(); --i >= 0;)
  61929. {
  61930. keyWasUsed = keyListeners->getUnchecked(i)->keyPressed (keyInfo, target);
  61931. if (keyWasUsed || deletionChecker == 0)
  61932. return keyWasUsed;
  61933. i = jmin (i, keyListeners->size());
  61934. }
  61935. }
  61936. keyWasUsed = target->keyPressed (keyInfo);
  61937. if (keyWasUsed || deletionChecker == 0)
  61938. break;
  61939. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  61940. {
  61941. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  61942. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  61943. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  61944. break;
  61945. }
  61946. target = target->getParentComponent();
  61947. }
  61948. return keyWasUsed;
  61949. }
  61950. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  61951. {
  61952. updateCurrentModifiers();
  61953. Component* target = Component::getCurrentlyFocusedComponent() != 0
  61954. ? Component::getCurrentlyFocusedComponent()
  61955. : component;
  61956. if (target->isCurrentlyBlockedByAnotherModalComponent())
  61957. {
  61958. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  61959. if (currentModalComp != 0)
  61960. target = currentModalComp;
  61961. }
  61962. bool keyWasUsed = false;
  61963. while (target != 0)
  61964. {
  61965. const WeakReference<Component> deletionChecker (target);
  61966. keyWasUsed = target->keyStateChanged (isKeyDown);
  61967. if (keyWasUsed || deletionChecker == 0)
  61968. break;
  61969. const Array <KeyListener*>* const keyListeners = target->keyListeners;
  61970. if (keyListeners != 0)
  61971. {
  61972. for (int i = keyListeners->size(); --i >= 0;)
  61973. {
  61974. keyWasUsed = keyListeners->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  61975. if (keyWasUsed || deletionChecker == 0)
  61976. return keyWasUsed;
  61977. i = jmin (i, keyListeners->size());
  61978. }
  61979. }
  61980. target = target->getParentComponent();
  61981. }
  61982. return keyWasUsed;
  61983. }
  61984. void ComponentPeer::handleModifierKeysChange()
  61985. {
  61986. updateCurrentModifiers();
  61987. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  61988. if (target == 0)
  61989. target = Component::getCurrentlyFocusedComponent();
  61990. if (target == 0)
  61991. target = component;
  61992. if (target != 0)
  61993. target->internalModifierKeysChanged();
  61994. }
  61995. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  61996. {
  61997. Component* const c = Component::getCurrentlyFocusedComponent();
  61998. if (component->isParentOf (c))
  61999. {
  62000. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62001. if (ti != 0 && ti->isTextInputActive())
  62002. return ti;
  62003. }
  62004. return 0;
  62005. }
  62006. void ComponentPeer::handleBroughtToFront()
  62007. {
  62008. updateCurrentModifiers();
  62009. if (component != 0)
  62010. component->internalBroughtToFront();
  62011. }
  62012. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62013. {
  62014. constrainer = newConstrainer;
  62015. }
  62016. void ComponentPeer::handleMovedOrResized()
  62017. {
  62018. updateCurrentModifiers();
  62019. const bool nowMinimised = isMinimised();
  62020. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62021. {
  62022. const WeakReference<Component> deletionChecker (component);
  62023. const Rectangle<int> newBounds (getBounds());
  62024. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62025. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62026. if (wasMoved || wasResized)
  62027. {
  62028. component->bounds = newBounds;
  62029. if (wasResized)
  62030. component->repaint();
  62031. component->sendMovedResizedMessages (wasMoved, wasResized);
  62032. if (deletionChecker == 0)
  62033. return;
  62034. }
  62035. }
  62036. if (isWindowMinimised != nowMinimised)
  62037. {
  62038. isWindowMinimised = nowMinimised;
  62039. component->minimisationStateChanged (nowMinimised);
  62040. component->sendVisibilityChangeMessage();
  62041. }
  62042. if (! isFullScreen())
  62043. lastNonFullscreenBounds = component->getBounds();
  62044. }
  62045. void ComponentPeer::handleFocusGain()
  62046. {
  62047. updateCurrentModifiers();
  62048. if (component->isParentOf (lastFocusedComponent))
  62049. {
  62050. Component::currentlyFocusedComponent = lastFocusedComponent;
  62051. Desktop::getInstance().triggerFocusCallback();
  62052. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62053. }
  62054. else
  62055. {
  62056. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62057. component->grabKeyboardFocus();
  62058. else
  62059. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  62060. }
  62061. }
  62062. void ComponentPeer::handleFocusLoss()
  62063. {
  62064. updateCurrentModifiers();
  62065. if (component->hasKeyboardFocus (true))
  62066. {
  62067. lastFocusedComponent = Component::currentlyFocusedComponent;
  62068. if (lastFocusedComponent != 0)
  62069. {
  62070. Component::currentlyFocusedComponent = 0;
  62071. Desktop::getInstance().triggerFocusCallback();
  62072. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62073. }
  62074. }
  62075. }
  62076. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62077. {
  62078. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62079. ? static_cast <Component*> (lastFocusedComponent)
  62080. : component;
  62081. }
  62082. void ComponentPeer::handleScreenSizeChange()
  62083. {
  62084. updateCurrentModifiers();
  62085. component->parentSizeChanged();
  62086. handleMovedOrResized();
  62087. }
  62088. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62089. {
  62090. lastNonFullscreenBounds = newBounds;
  62091. }
  62092. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62093. {
  62094. return lastNonFullscreenBounds;
  62095. }
  62096. const Rectangle<int> ComponentPeer::localToGlobal (const Rectangle<int>& relativePosition)
  62097. {
  62098. return relativePosition.withPosition (localToGlobal (relativePosition.getPosition()));
  62099. }
  62100. const Rectangle<int> ComponentPeer::globalToLocal (const Rectangle<int>& screenPosition)
  62101. {
  62102. return screenPosition.withPosition (globalToLocal (screenPosition.getPosition()));
  62103. }
  62104. namespace ComponentPeerHelpers
  62105. {
  62106. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62107. const StringArray& files,
  62108. FileDragAndDropTarget* const lastOne)
  62109. {
  62110. while (c != 0)
  62111. {
  62112. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62113. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62114. return t;
  62115. c = c->getParentComponent();
  62116. }
  62117. return 0;
  62118. }
  62119. }
  62120. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62121. {
  62122. updateCurrentModifiers();
  62123. FileDragAndDropTarget* lastTarget
  62124. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62125. FileDragAndDropTarget* newTarget = 0;
  62126. Component* const compUnderMouse = component->getComponentAt (position);
  62127. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62128. {
  62129. lastDragAndDropCompUnderMouse = compUnderMouse;
  62130. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62131. if (newTarget != lastTarget)
  62132. {
  62133. if (lastTarget != 0)
  62134. lastTarget->fileDragExit (files);
  62135. dragAndDropTargetComponent = 0;
  62136. if (newTarget != 0)
  62137. {
  62138. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  62139. const Point<int> pos (dragAndDropTargetComponent->getLocalPoint (component, position));
  62140. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  62141. }
  62142. }
  62143. }
  62144. else
  62145. {
  62146. newTarget = lastTarget;
  62147. }
  62148. if (newTarget != 0)
  62149. {
  62150. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  62151. const Point<int> pos (targetComp->getLocalPoint (component, position));
  62152. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  62153. }
  62154. }
  62155. void ComponentPeer::handleFileDragExit (const StringArray& files)
  62156. {
  62157. handleFileDragMove (files, Point<int> (-1, -1));
  62158. jassert (dragAndDropTargetComponent == 0);
  62159. lastDragAndDropCompUnderMouse = 0;
  62160. }
  62161. // We'll use an async message to deliver the drop, because if the target decides
  62162. // to run a modal loop, it can gum-up the operating system..
  62163. class AsyncFileDropMessage : public CallbackMessage
  62164. {
  62165. public:
  62166. AsyncFileDropMessage (Component* target_, FileDragAndDropTarget* dropTarget_,
  62167. const Point<int>& position_, const StringArray& files_)
  62168. : target (target_), dropTarget (dropTarget_), position (position_), files (files_)
  62169. {
  62170. }
  62171. void messageCallback()
  62172. {
  62173. if (target != 0)
  62174. dropTarget->filesDropped (files, position.getX(), position.getY());
  62175. }
  62176. private:
  62177. WeakReference<Component> target;
  62178. FileDragAndDropTarget* const dropTarget;
  62179. const Point<int> position;
  62180. const StringArray files;
  62181. JUCE_DECLARE_NON_COPYABLE (AsyncFileDropMessage);
  62182. };
  62183. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  62184. {
  62185. handleFileDragMove (files, position);
  62186. if (dragAndDropTargetComponent != 0)
  62187. {
  62188. FileDragAndDropTarget* const target
  62189. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62190. dragAndDropTargetComponent = 0;
  62191. lastDragAndDropCompUnderMouse = 0;
  62192. if (target != 0)
  62193. {
  62194. Component* const targetComp = dynamic_cast <Component*> (target);
  62195. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62196. {
  62197. targetComp->internalModalInputAttempt();
  62198. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  62199. return;
  62200. }
  62201. (new AsyncFileDropMessage (targetComp, target, targetComp->getLocalPoint (component, position), files))->post();
  62202. }
  62203. }
  62204. }
  62205. void ComponentPeer::handleUserClosingWindow()
  62206. {
  62207. updateCurrentModifiers();
  62208. component->userTriedToCloseWindow();
  62209. }
  62210. void ComponentPeer::clearMaskedRegion()
  62211. {
  62212. maskedRegion.clear();
  62213. }
  62214. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  62215. {
  62216. maskedRegion.add (x, y, w, h);
  62217. }
  62218. const StringArray ComponentPeer::getAvailableRenderingEngines()
  62219. {
  62220. StringArray s;
  62221. s.add ("Software Renderer");
  62222. return s;
  62223. }
  62224. int ComponentPeer::getCurrentRenderingEngine() throw()
  62225. {
  62226. return 0;
  62227. }
  62228. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  62229. {
  62230. }
  62231. END_JUCE_NAMESPACE
  62232. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  62233. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  62234. BEGIN_JUCE_NAMESPACE
  62235. DialogWindow::DialogWindow (const String& name,
  62236. const Colour& backgroundColour_,
  62237. const bool escapeKeyTriggersCloseButton_,
  62238. const bool addToDesktop_)
  62239. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  62240. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  62241. {
  62242. }
  62243. DialogWindow::~DialogWindow()
  62244. {
  62245. }
  62246. void DialogWindow::resized()
  62247. {
  62248. DocumentWindow::resized();
  62249. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  62250. if (escapeKeyTriggersCloseButton
  62251. && getCloseButton() != 0
  62252. && ! getCloseButton()->isRegisteredForShortcut (esc))
  62253. {
  62254. getCloseButton()->addShortcut (esc);
  62255. }
  62256. }
  62257. // (Sadly, this can't be made a local class inside the showModalDialog function, because the
  62258. // VC compiler complains about the undefined copy constructor)
  62259. class TempDialogWindow : public DialogWindow
  62260. {
  62261. public:
  62262. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  62263. : DialogWindow (title, colour, escapeCloses, true)
  62264. {
  62265. if (! JUCEApplication::isStandaloneApp())
  62266. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62267. }
  62268. void closeButtonPressed()
  62269. {
  62270. setVisible (false);
  62271. }
  62272. private:
  62273. JUCE_DECLARE_NON_COPYABLE (TempDialogWindow);
  62274. };
  62275. int DialogWindow::showModalDialog (const String& dialogTitle,
  62276. Component* contentComponent,
  62277. Component* componentToCentreAround,
  62278. const Colour& colour,
  62279. const bool escapeKeyTriggersCloseButton,
  62280. const bool shouldBeResizable,
  62281. const bool useBottomRightCornerResizer)
  62282. {
  62283. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  62284. dw.setContentComponent (contentComponent, true, true);
  62285. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  62286. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62287. const int result = dw.runModalLoop();
  62288. dw.setContentComponent (0, false);
  62289. return result;
  62290. }
  62291. END_JUCE_NAMESPACE
  62292. /*** End of inlined file: juce_DialogWindow.cpp ***/
  62293. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  62294. BEGIN_JUCE_NAMESPACE
  62295. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  62296. {
  62297. public:
  62298. ButtonListenerProxy (DocumentWindow& owner_)
  62299. : owner (owner_)
  62300. {
  62301. }
  62302. void buttonClicked (Button* button)
  62303. {
  62304. if (button == owner.getMinimiseButton())
  62305. owner.minimiseButtonPressed();
  62306. else if (button == owner.getMaximiseButton())
  62307. owner.maximiseButtonPressed();
  62308. else if (button == owner.getCloseButton())
  62309. owner.closeButtonPressed();
  62310. }
  62311. private:
  62312. DocumentWindow& owner;
  62313. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonListenerProxy);
  62314. };
  62315. DocumentWindow::DocumentWindow (const String& title,
  62316. const Colour& backgroundColour,
  62317. const int requiredButtons_,
  62318. const bool addToDesktop_)
  62319. : ResizableWindow (title, backgroundColour, addToDesktop_),
  62320. titleBarHeight (26),
  62321. menuBarHeight (24),
  62322. requiredButtons (requiredButtons_),
  62323. #if JUCE_MAC
  62324. positionTitleBarButtonsOnLeft (true),
  62325. #else
  62326. positionTitleBarButtonsOnLeft (false),
  62327. #endif
  62328. drawTitleTextCentred (true),
  62329. menuBarModel (0)
  62330. {
  62331. setResizeLimits (128, 128, 32768, 32768);
  62332. lookAndFeelChanged();
  62333. }
  62334. DocumentWindow::~DocumentWindow()
  62335. {
  62336. // Don't delete or remove the resizer components yourself! They're managed by the
  62337. // DocumentWindow, and you should leave them alone! You may have deleted them
  62338. // accidentally by careless use of deleteAllChildren()..?
  62339. jassert (menuBar == 0 || getIndexOfChildComponent (menuBar) >= 0);
  62340. jassert (titleBarButtons[0] == 0 || getIndexOfChildComponent (titleBarButtons[0]) >= 0);
  62341. jassert (titleBarButtons[1] == 0 || getIndexOfChildComponent (titleBarButtons[1]) >= 0);
  62342. jassert (titleBarButtons[2] == 0 || getIndexOfChildComponent (titleBarButtons[2]) >= 0);
  62343. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62344. titleBarButtons[i] = 0;
  62345. menuBar = 0;
  62346. }
  62347. void DocumentWindow::repaintTitleBar()
  62348. {
  62349. repaint (getTitleBarArea());
  62350. }
  62351. void DocumentWindow::setName (const String& newName)
  62352. {
  62353. if (newName != getName())
  62354. {
  62355. Component::setName (newName);
  62356. repaintTitleBar();
  62357. }
  62358. }
  62359. void DocumentWindow::setIcon (const Image& imageToUse)
  62360. {
  62361. titleBarIcon = imageToUse;
  62362. repaintTitleBar();
  62363. }
  62364. void DocumentWindow::setTitleBarHeight (const int newHeight)
  62365. {
  62366. titleBarHeight = newHeight;
  62367. resized();
  62368. repaintTitleBar();
  62369. }
  62370. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  62371. const bool positionTitleBarButtonsOnLeft_)
  62372. {
  62373. requiredButtons = requiredButtons_;
  62374. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  62375. lookAndFeelChanged();
  62376. }
  62377. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  62378. {
  62379. drawTitleTextCentred = textShouldBeCentred;
  62380. repaintTitleBar();
  62381. }
  62382. void DocumentWindow::setMenuBar (MenuBarModel* newMenuBarModel, const int newMenuBarHeight)
  62383. {
  62384. if (menuBarModel != newMenuBarModel)
  62385. {
  62386. menuBar = 0;
  62387. menuBarModel = newMenuBarModel;
  62388. menuBarHeight = newMenuBarHeight > 0 ? newMenuBarHeight
  62389. : getLookAndFeel().getDefaultMenuBarHeight();
  62390. if (menuBarModel != 0)
  62391. setMenuBarComponent (new MenuBarComponent (menuBarModel));
  62392. resized();
  62393. }
  62394. }
  62395. Component* DocumentWindow::getMenuBarComponent() const throw()
  62396. {
  62397. return menuBar;
  62398. }
  62399. void DocumentWindow::setMenuBarComponent (Component* newMenuBarComponent)
  62400. {
  62401. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62402. Component::addAndMakeVisible (menuBar = newMenuBarComponent);
  62403. if (menuBar != 0)
  62404. menuBar->setEnabled (isActiveWindow());
  62405. resized();
  62406. }
  62407. void DocumentWindow::closeButtonPressed()
  62408. {
  62409. /* If you've got a close button, you have to override this method to get
  62410. rid of your window!
  62411. If the window is just a pop-up, you should override this method and make
  62412. it delete the window in whatever way is appropriate for your app. E.g. you
  62413. might just want to call "delete this".
  62414. If your app is centred around this window such that the whole app should quit when
  62415. the window is closed, then you will probably want to use this method as an opportunity
  62416. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  62417. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  62418. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  62419. or closing it via the taskbar icon on Windows).
  62420. */
  62421. jassertfalse;
  62422. }
  62423. void DocumentWindow::minimiseButtonPressed()
  62424. {
  62425. setMinimised (true);
  62426. }
  62427. void DocumentWindow::maximiseButtonPressed()
  62428. {
  62429. setFullScreen (! isFullScreen());
  62430. }
  62431. void DocumentWindow::paint (Graphics& g)
  62432. {
  62433. ResizableWindow::paint (g);
  62434. if (resizableBorder == 0)
  62435. {
  62436. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  62437. const BorderSize<int> border (getBorderThickness());
  62438. g.fillRect (0, 0, getWidth(), border.getTop());
  62439. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  62440. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  62441. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  62442. }
  62443. const Rectangle<int> titleBarArea (getTitleBarArea());
  62444. g.reduceClipRegion (titleBarArea);
  62445. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  62446. int titleSpaceX1 = 6;
  62447. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  62448. for (int i = 0; i < 3; ++i)
  62449. {
  62450. if (titleBarButtons[i] != 0)
  62451. {
  62452. if (positionTitleBarButtonsOnLeft)
  62453. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  62454. else
  62455. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  62456. }
  62457. }
  62458. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  62459. titleBarArea.getWidth(),
  62460. titleBarArea.getHeight(),
  62461. titleSpaceX1,
  62462. jmax (1, titleSpaceX2 - titleSpaceX1),
  62463. titleBarIcon.isValid() ? &titleBarIcon : 0,
  62464. ! drawTitleTextCentred);
  62465. }
  62466. void DocumentWindow::resized()
  62467. {
  62468. ResizableWindow::resized();
  62469. if (titleBarButtons[1] != 0)
  62470. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  62471. const Rectangle<int> titleBarArea (getTitleBarArea());
  62472. getLookAndFeel()
  62473. .positionDocumentWindowButtons (*this,
  62474. titleBarArea.getX(), titleBarArea.getY(),
  62475. titleBarArea.getWidth(), titleBarArea.getHeight(),
  62476. titleBarButtons[0],
  62477. titleBarButtons[1],
  62478. titleBarButtons[2],
  62479. positionTitleBarButtonsOnLeft);
  62480. if (menuBar != 0)
  62481. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  62482. titleBarArea.getWidth(), menuBarHeight);
  62483. }
  62484. const BorderSize<int> DocumentWindow::getBorderThickness()
  62485. {
  62486. return BorderSize<int> ((isFullScreen() || isUsingNativeTitleBar())
  62487. ? 0 : (resizableBorder != 0 ? 4 : 1));
  62488. }
  62489. const BorderSize<int> DocumentWindow::getContentComponentBorder()
  62490. {
  62491. BorderSize<int> border (getBorderThickness());
  62492. border.setTop (border.getTop()
  62493. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  62494. + (menuBar != 0 ? menuBarHeight : 0));
  62495. return border;
  62496. }
  62497. int DocumentWindow::getTitleBarHeight() const
  62498. {
  62499. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  62500. }
  62501. const Rectangle<int> DocumentWindow::getTitleBarArea()
  62502. {
  62503. const BorderSize<int> border (getBorderThickness());
  62504. return Rectangle<int> (border.getLeft(), border.getTop(),
  62505. getWidth() - border.getLeftAndRight(),
  62506. getTitleBarHeight());
  62507. }
  62508. Button* DocumentWindow::getCloseButton() const throw() { return titleBarButtons[2]; }
  62509. Button* DocumentWindow::getMinimiseButton() const throw() { return titleBarButtons[0]; }
  62510. Button* DocumentWindow::getMaximiseButton() const throw() { return titleBarButtons[1]; }
  62511. int DocumentWindow::getDesktopWindowStyleFlags() const
  62512. {
  62513. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  62514. if ((requiredButtons & minimiseButton) != 0)
  62515. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  62516. if ((requiredButtons & maximiseButton) != 0)
  62517. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  62518. if ((requiredButtons & closeButton) != 0)
  62519. styleFlags |= ComponentPeer::windowHasCloseButton;
  62520. return styleFlags;
  62521. }
  62522. void DocumentWindow::lookAndFeelChanged()
  62523. {
  62524. int i;
  62525. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  62526. titleBarButtons[i] = 0;
  62527. if (! isUsingNativeTitleBar())
  62528. {
  62529. LookAndFeel& lf = getLookAndFeel();
  62530. if ((requiredButtons & minimiseButton) != 0)
  62531. titleBarButtons[0] = lf.createDocumentWindowButton (minimiseButton);
  62532. if ((requiredButtons & maximiseButton) != 0)
  62533. titleBarButtons[1] = lf.createDocumentWindowButton (maximiseButton);
  62534. if ((requiredButtons & closeButton) != 0)
  62535. titleBarButtons[2] = lf.createDocumentWindowButton (closeButton);
  62536. for (i = 0; i < 3; ++i)
  62537. {
  62538. if (titleBarButtons[i] != 0)
  62539. {
  62540. if (buttonListener == 0)
  62541. buttonListener = new ButtonListenerProxy (*this);
  62542. titleBarButtons[i]->addListener (buttonListener);
  62543. titleBarButtons[i]->setWantsKeyboardFocus (false);
  62544. // (call the Component method directly to avoid the assertion in ResizableWindow)
  62545. Component::addAndMakeVisible (titleBarButtons[i]);
  62546. }
  62547. }
  62548. if (getCloseButton() != 0)
  62549. {
  62550. #if JUCE_MAC
  62551. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  62552. #else
  62553. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  62554. #endif
  62555. }
  62556. }
  62557. activeWindowStatusChanged();
  62558. ResizableWindow::lookAndFeelChanged();
  62559. }
  62560. void DocumentWindow::parentHierarchyChanged()
  62561. {
  62562. lookAndFeelChanged();
  62563. }
  62564. void DocumentWindow::activeWindowStatusChanged()
  62565. {
  62566. ResizableWindow::activeWindowStatusChanged();
  62567. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  62568. if (titleBarButtons[i] != 0)
  62569. titleBarButtons[i]->setEnabled (isActiveWindow());
  62570. if (menuBar != 0)
  62571. menuBar->setEnabled (isActiveWindow());
  62572. }
  62573. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  62574. {
  62575. if (getTitleBarArea().contains (e.x, e.y)
  62576. && getMaximiseButton() != 0)
  62577. {
  62578. getMaximiseButton()->triggerClick();
  62579. }
  62580. }
  62581. void DocumentWindow::userTriedToCloseWindow()
  62582. {
  62583. closeButtonPressed();
  62584. }
  62585. END_JUCE_NAMESPACE
  62586. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  62587. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  62588. BEGIN_JUCE_NAMESPACE
  62589. ResizableWindow::ResizableWindow (const String& name,
  62590. const bool addToDesktop_)
  62591. : TopLevelWindow (name, addToDesktop_),
  62592. resizeToFitContent (false),
  62593. fullscreen (false),
  62594. lastNonFullScreenPos (50, 50, 256, 256),
  62595. constrainer (0)
  62596. #if JUCE_DEBUG
  62597. , hasBeenResized (false)
  62598. #endif
  62599. {
  62600. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62601. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  62602. if (addToDesktop_)
  62603. Component::addToDesktop (getDesktopWindowStyleFlags());
  62604. }
  62605. ResizableWindow::ResizableWindow (const String& name,
  62606. const Colour& backgroundColour_,
  62607. const bool addToDesktop_)
  62608. : TopLevelWindow (name, addToDesktop_),
  62609. resizeToFitContent (false),
  62610. fullscreen (false),
  62611. lastNonFullScreenPos (50, 50, 256, 256),
  62612. constrainer (0)
  62613. #if JUCE_DEBUG
  62614. , hasBeenResized (false)
  62615. #endif
  62616. {
  62617. setBackgroundColour (backgroundColour_);
  62618. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  62619. if (addToDesktop_)
  62620. Component::addToDesktop (getDesktopWindowStyleFlags());
  62621. }
  62622. ResizableWindow::~ResizableWindow()
  62623. {
  62624. // Don't delete or remove the resizer components yourself! They're managed by the
  62625. // ResizableWindow, and you should leave them alone! You may have deleted them
  62626. // accidentally by careless use of deleteAllChildren()..?
  62627. jassert (resizableCorner == 0 || getIndexOfChildComponent (resizableCorner) >= 0);
  62628. jassert (resizableBorder == 0 || getIndexOfChildComponent (resizableBorder) >= 0);
  62629. resizableCorner = 0;
  62630. resizableBorder = 0;
  62631. contentComponent.deleteAndZero();
  62632. // have you been adding your own components directly to this window..? tut tut tut.
  62633. // Read the instructions for using a ResizableWindow!
  62634. jassert (getNumChildComponents() == 0);
  62635. }
  62636. int ResizableWindow::getDesktopWindowStyleFlags() const
  62637. {
  62638. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  62639. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  62640. styleFlags |= ComponentPeer::windowIsResizable;
  62641. return styleFlags;
  62642. }
  62643. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  62644. const bool deleteOldOne,
  62645. const bool resizeToFit)
  62646. {
  62647. resizeToFitContent = resizeToFit;
  62648. if (newContentComponent != static_cast <Component*> (contentComponent))
  62649. {
  62650. if (deleteOldOne)
  62651. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  62652. // external deletion of the content comp)
  62653. else
  62654. removeChildComponent (contentComponent);
  62655. contentComponent = newContentComponent;
  62656. Component::addAndMakeVisible (contentComponent);
  62657. }
  62658. if (resizeToFit)
  62659. childBoundsChanged (contentComponent);
  62660. resized(); // must always be called to position the new content comp
  62661. }
  62662. void ResizableWindow::setContentComponentSize (int width, int height)
  62663. {
  62664. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  62665. const BorderSize<int> border (getContentComponentBorder());
  62666. setSize (width + border.getLeftAndRight(),
  62667. height + border.getTopAndBottom());
  62668. }
  62669. const BorderSize<int> ResizableWindow::getBorderThickness()
  62670. {
  62671. return BorderSize<int> (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  62672. }
  62673. const BorderSize<int> ResizableWindow::getContentComponentBorder()
  62674. {
  62675. return getBorderThickness();
  62676. }
  62677. void ResizableWindow::moved()
  62678. {
  62679. updateLastPos();
  62680. }
  62681. void ResizableWindow::visibilityChanged()
  62682. {
  62683. TopLevelWindow::visibilityChanged();
  62684. updateLastPos();
  62685. }
  62686. void ResizableWindow::resized()
  62687. {
  62688. if (resizableBorder != 0)
  62689. {
  62690. #if JUCE_WINDOWS || JUCE_LINUX
  62691. // hide the resizable border if the OS already provides one..
  62692. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62693. #else
  62694. resizableBorder->setVisible (! isFullScreen());
  62695. #endif
  62696. resizableBorder->setBorderThickness (getBorderThickness());
  62697. resizableBorder->setSize (getWidth(), getHeight());
  62698. resizableBorder->toBack();
  62699. }
  62700. if (resizableCorner != 0)
  62701. {
  62702. #if JUCE_MAC
  62703. // hide the resizable border if the OS already provides one..
  62704. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  62705. #else
  62706. resizableCorner->setVisible (! isFullScreen());
  62707. #endif
  62708. const int resizerSize = 18;
  62709. resizableCorner->setBounds (getWidth() - resizerSize,
  62710. getHeight() - resizerSize,
  62711. resizerSize, resizerSize);
  62712. }
  62713. if (contentComponent != 0)
  62714. contentComponent->setBoundsInset (getContentComponentBorder());
  62715. updateLastPos();
  62716. #if JUCE_DEBUG
  62717. hasBeenResized = true;
  62718. #endif
  62719. }
  62720. void ResizableWindow::childBoundsChanged (Component* child)
  62721. {
  62722. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  62723. {
  62724. // not going to look very good if this component has a zero size..
  62725. jassert (child->getWidth() > 0);
  62726. jassert (child->getHeight() > 0);
  62727. const BorderSize<int> borders (getContentComponentBorder());
  62728. setSize (child->getWidth() + borders.getLeftAndRight(),
  62729. child->getHeight() + borders.getTopAndBottom());
  62730. }
  62731. }
  62732. void ResizableWindow::activeWindowStatusChanged()
  62733. {
  62734. const BorderSize<int> border (getContentComponentBorder());
  62735. Rectangle<int> area (getLocalBounds());
  62736. repaint (area.removeFromTop (border.getTop()));
  62737. repaint (area.removeFromLeft (border.getLeft()));
  62738. repaint (area.removeFromRight (border.getRight()));
  62739. repaint (area.removeFromBottom (border.getBottom()));
  62740. }
  62741. void ResizableWindow::setResizable (const bool shouldBeResizable,
  62742. const bool useBottomRightCornerResizer)
  62743. {
  62744. if (shouldBeResizable)
  62745. {
  62746. if (useBottomRightCornerResizer)
  62747. {
  62748. resizableBorder = 0;
  62749. if (resizableCorner == 0)
  62750. {
  62751. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  62752. resizableCorner->setAlwaysOnTop (true);
  62753. }
  62754. }
  62755. else
  62756. {
  62757. resizableCorner = 0;
  62758. if (resizableBorder == 0)
  62759. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  62760. }
  62761. }
  62762. else
  62763. {
  62764. resizableCorner = 0;
  62765. resizableBorder = 0;
  62766. }
  62767. if (isUsingNativeTitleBar())
  62768. recreateDesktopWindow();
  62769. childBoundsChanged (contentComponent);
  62770. resized();
  62771. }
  62772. bool ResizableWindow::isResizable() const throw()
  62773. {
  62774. return resizableCorner != 0
  62775. || resizableBorder != 0;
  62776. }
  62777. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  62778. const int newMinimumHeight,
  62779. const int newMaximumWidth,
  62780. const int newMaximumHeight) throw()
  62781. {
  62782. // if you've set up a custom constrainer then these settings won't have any effect..
  62783. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  62784. if (constrainer == 0)
  62785. setConstrainer (&defaultConstrainer);
  62786. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  62787. newMaximumWidth, newMaximumHeight);
  62788. setBoundsConstrained (getBounds());
  62789. }
  62790. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  62791. {
  62792. if (constrainer != newConstrainer)
  62793. {
  62794. constrainer = newConstrainer;
  62795. const bool useBottomRightCornerResizer = resizableCorner != 0;
  62796. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  62797. resizableCorner = 0;
  62798. resizableBorder = 0;
  62799. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  62800. ComponentPeer* const peer = getPeer();
  62801. if (peer != 0)
  62802. peer->setConstrainer (newConstrainer);
  62803. }
  62804. }
  62805. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  62806. {
  62807. if (constrainer != 0)
  62808. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  62809. else
  62810. setBounds (bounds);
  62811. }
  62812. void ResizableWindow::paint (Graphics& g)
  62813. {
  62814. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  62815. getBorderThickness(), *this);
  62816. if (! isFullScreen())
  62817. {
  62818. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  62819. getBorderThickness(), *this);
  62820. }
  62821. #if JUCE_DEBUG
  62822. /* If this fails, then you've probably written a subclass with a resized()
  62823. callback but forgotten to make it call its parent class's resized() method.
  62824. It's important when you override methods like resized(), moved(),
  62825. etc., that you make sure the base class methods also get called.
  62826. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  62827. because your content should all be inside the content component - and it's the
  62828. content component's resized() method that you should be using to do your
  62829. layout.
  62830. */
  62831. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  62832. #endif
  62833. }
  62834. void ResizableWindow::lookAndFeelChanged()
  62835. {
  62836. resized();
  62837. if (isOnDesktop())
  62838. {
  62839. Component::addToDesktop (getDesktopWindowStyleFlags());
  62840. ComponentPeer* const peer = getPeer();
  62841. if (peer != 0)
  62842. peer->setConstrainer (constrainer);
  62843. }
  62844. }
  62845. const Colour ResizableWindow::getBackgroundColour() const throw()
  62846. {
  62847. return findColour (backgroundColourId, false);
  62848. }
  62849. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  62850. {
  62851. Colour backgroundColour (newColour);
  62852. if (! Desktop::canUseSemiTransparentWindows())
  62853. backgroundColour = newColour.withAlpha (1.0f);
  62854. setColour (backgroundColourId, backgroundColour);
  62855. setOpaque (backgroundColour.isOpaque());
  62856. repaint();
  62857. }
  62858. bool ResizableWindow::isFullScreen() const
  62859. {
  62860. if (isOnDesktop())
  62861. {
  62862. ComponentPeer* const peer = getPeer();
  62863. return peer != 0 && peer->isFullScreen();
  62864. }
  62865. return fullscreen;
  62866. }
  62867. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  62868. {
  62869. if (shouldBeFullScreen != isFullScreen())
  62870. {
  62871. updateLastPos();
  62872. fullscreen = shouldBeFullScreen;
  62873. if (isOnDesktop())
  62874. {
  62875. ComponentPeer* const peer = getPeer();
  62876. if (peer != 0)
  62877. {
  62878. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  62879. const Rectangle<int> lastPos (lastNonFullScreenPos);
  62880. peer->setFullScreen (shouldBeFullScreen);
  62881. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  62882. setBounds (lastPos);
  62883. }
  62884. else
  62885. {
  62886. jassertfalse;
  62887. }
  62888. }
  62889. else
  62890. {
  62891. if (shouldBeFullScreen)
  62892. setBounds (0, 0, getParentWidth(), getParentHeight());
  62893. else
  62894. setBounds (lastNonFullScreenPos);
  62895. }
  62896. resized();
  62897. }
  62898. }
  62899. bool ResizableWindow::isMinimised() const
  62900. {
  62901. ComponentPeer* const peer = getPeer();
  62902. return (peer != 0) && peer->isMinimised();
  62903. }
  62904. void ResizableWindow::setMinimised (const bool shouldMinimise)
  62905. {
  62906. if (shouldMinimise != isMinimised())
  62907. {
  62908. ComponentPeer* const peer = getPeer();
  62909. if (peer != 0)
  62910. {
  62911. updateLastPos();
  62912. peer->setMinimised (shouldMinimise);
  62913. }
  62914. else
  62915. {
  62916. jassertfalse;
  62917. }
  62918. }
  62919. }
  62920. void ResizableWindow::updateLastPos()
  62921. {
  62922. if (isShowing() && ! (isFullScreen() || isMinimised()))
  62923. {
  62924. lastNonFullScreenPos = getBounds();
  62925. }
  62926. }
  62927. void ResizableWindow::parentSizeChanged()
  62928. {
  62929. if (isFullScreen() && getParentComponent() != 0)
  62930. {
  62931. setBounds (0, 0, getParentWidth(), getParentHeight());
  62932. }
  62933. }
  62934. const String ResizableWindow::getWindowStateAsString()
  62935. {
  62936. updateLastPos();
  62937. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  62938. }
  62939. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  62940. {
  62941. StringArray tokens;
  62942. tokens.addTokens (s, false);
  62943. tokens.removeEmptyStrings();
  62944. tokens.trim();
  62945. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  62946. const int firstCoord = fs ? 1 : 0;
  62947. if (tokens.size() != firstCoord + 4)
  62948. return false;
  62949. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  62950. tokens[firstCoord + 1].getIntValue(),
  62951. tokens[firstCoord + 2].getIntValue(),
  62952. tokens[firstCoord + 3].getIntValue());
  62953. if (newPos.isEmpty())
  62954. return false;
  62955. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  62956. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  62957. if (peer != 0)
  62958. peer->getFrameSize().addTo (newPos);
  62959. if (! screen.contains (newPos))
  62960. {
  62961. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  62962. jmin (newPos.getHeight(), screen.getHeight()));
  62963. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  62964. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  62965. }
  62966. if (peer != 0)
  62967. {
  62968. peer->getFrameSize().subtractFrom (newPos);
  62969. peer->setNonFullScreenBounds (newPos);
  62970. }
  62971. lastNonFullScreenPos = newPos;
  62972. setFullScreen (fs);
  62973. if (! fs)
  62974. setBoundsConstrained (newPos);
  62975. return true;
  62976. }
  62977. void ResizableWindow::mouseDown (const MouseEvent& e)
  62978. {
  62979. if (! isFullScreen())
  62980. dragger.startDraggingComponent (this, e);
  62981. }
  62982. void ResizableWindow::mouseDrag (const MouseEvent& e)
  62983. {
  62984. if (! isFullScreen())
  62985. dragger.dragComponent (this, e, constrainer);
  62986. }
  62987. #if JUCE_DEBUG
  62988. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  62989. {
  62990. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  62991. manages its child components automatically, and if you add your own it'll cause
  62992. trouble. Instead, use setContentComponent() to give it a component which
  62993. will be automatically resized and kept in the right place - then you can add
  62994. subcomponents to the content comp. See the notes for the ResizableWindow class
  62995. for more info.
  62996. If you really know what you're doing and want to avoid this assertion, just call
  62997. Component::addChildComponent directly.
  62998. */
  62999. jassertfalse;
  63000. Component::addChildComponent (child, zOrder);
  63001. }
  63002. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63003. {
  63004. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63005. manages its child components automatically, and if you add your own it'll cause
  63006. trouble. Instead, use setContentComponent() to give it a component which
  63007. will be automatically resized and kept in the right place - then you can add
  63008. subcomponents to the content comp. See the notes for the ResizableWindow class
  63009. for more info.
  63010. If you really know what you're doing and want to avoid this assertion, just call
  63011. Component::addAndMakeVisible directly.
  63012. */
  63013. jassertfalse;
  63014. Component::addAndMakeVisible (child, zOrder);
  63015. }
  63016. #endif
  63017. END_JUCE_NAMESPACE
  63018. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63019. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63020. BEGIN_JUCE_NAMESPACE
  63021. SplashScreen::SplashScreen()
  63022. {
  63023. setOpaque (true);
  63024. }
  63025. SplashScreen::~SplashScreen()
  63026. {
  63027. }
  63028. void SplashScreen::show (const String& title,
  63029. const Image& backgroundImage_,
  63030. const int minimumTimeToDisplayFor,
  63031. const bool useDropShadow,
  63032. const bool removeOnMouseClick)
  63033. {
  63034. backgroundImage = backgroundImage_;
  63035. jassert (backgroundImage_.isValid());
  63036. if (backgroundImage_.isValid())
  63037. {
  63038. setOpaque (! backgroundImage_.hasAlphaChannel());
  63039. show (title,
  63040. backgroundImage_.getWidth(),
  63041. backgroundImage_.getHeight(),
  63042. minimumTimeToDisplayFor,
  63043. useDropShadow,
  63044. removeOnMouseClick);
  63045. }
  63046. }
  63047. void SplashScreen::show (const String& title,
  63048. const int width,
  63049. const int height,
  63050. const int minimumTimeToDisplayFor,
  63051. const bool useDropShadow,
  63052. const bool removeOnMouseClick)
  63053. {
  63054. setName (title);
  63055. setAlwaysOnTop (true);
  63056. setVisible (true);
  63057. centreWithSize (width, height);
  63058. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63059. toFront (false);
  63060. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63061. repaint();
  63062. originalClickCounter = removeOnMouseClick
  63063. ? Desktop::getMouseButtonClickCounter()
  63064. : std::numeric_limits<int>::max();
  63065. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63066. startTimer (50);
  63067. }
  63068. void SplashScreen::paint (Graphics& g)
  63069. {
  63070. g.setOpacity (1.0f);
  63071. g.drawImage (backgroundImage,
  63072. 0, 0, getWidth(), getHeight(),
  63073. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63074. }
  63075. void SplashScreen::timerCallback()
  63076. {
  63077. if (Time::getCurrentTime() > earliestTimeToDelete
  63078. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63079. {
  63080. delete this;
  63081. }
  63082. }
  63083. END_JUCE_NAMESPACE
  63084. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63085. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63086. BEGIN_JUCE_NAMESPACE
  63087. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63088. const bool hasProgressBar,
  63089. const bool hasCancelButton,
  63090. const int timeOutMsWhenCancelling_,
  63091. const String& cancelButtonText)
  63092. : Thread ("Juce Progress Window"),
  63093. progress (0.0),
  63094. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63095. {
  63096. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63097. .createAlertWindow (title, String::empty, cancelButtonText,
  63098. String::empty, String::empty,
  63099. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63100. if (hasProgressBar)
  63101. alertWindow->addProgressBarComponent (progress);
  63102. }
  63103. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63104. {
  63105. stopThread (timeOutMsWhenCancelling);
  63106. }
  63107. bool ThreadWithProgressWindow::runThread (const int priority)
  63108. {
  63109. startThread (priority);
  63110. startTimer (100);
  63111. {
  63112. const ScopedLock sl (messageLock);
  63113. alertWindow->setMessage (message);
  63114. }
  63115. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63116. stopThread (timeOutMsWhenCancelling);
  63117. alertWindow->setVisible (false);
  63118. return finishedNaturally;
  63119. }
  63120. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63121. {
  63122. progress = newProgress;
  63123. }
  63124. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63125. {
  63126. const ScopedLock sl (messageLock);
  63127. message = newStatusMessage;
  63128. }
  63129. void ThreadWithProgressWindow::timerCallback()
  63130. {
  63131. if (! isThreadRunning())
  63132. {
  63133. // thread has finished normally..
  63134. alertWindow->exitModalState (1);
  63135. alertWindow->setVisible (false);
  63136. }
  63137. else
  63138. {
  63139. const ScopedLock sl (messageLock);
  63140. alertWindow->setMessage (message);
  63141. }
  63142. }
  63143. END_JUCE_NAMESPACE
  63144. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63145. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63146. BEGIN_JUCE_NAMESPACE
  63147. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63148. const int millisecondsBeforeTipAppears_)
  63149. : Component ("tooltip"),
  63150. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63151. mouseClicks (0),
  63152. lastHideTime (0),
  63153. lastComponentUnderMouse (0),
  63154. changedCompsSinceShown (true)
  63155. {
  63156. if (Desktop::getInstance().getMainMouseSource().canHover())
  63157. startTimer (123);
  63158. setAlwaysOnTop (true);
  63159. setOpaque (true);
  63160. if (parentComponent != 0)
  63161. parentComponent->addChildComponent (this);
  63162. }
  63163. TooltipWindow::~TooltipWindow()
  63164. {
  63165. hide();
  63166. }
  63167. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  63168. {
  63169. millisecondsBeforeTipAppears = newTimeMs;
  63170. }
  63171. void TooltipWindow::paint (Graphics& g)
  63172. {
  63173. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  63174. }
  63175. void TooltipWindow::mouseEnter (const MouseEvent&)
  63176. {
  63177. hide();
  63178. }
  63179. void TooltipWindow::showFor (const String& tip)
  63180. {
  63181. jassert (tip.isNotEmpty());
  63182. if (tipShowing != tip)
  63183. repaint();
  63184. tipShowing = tip;
  63185. Point<int> mousePos (Desktop::getMousePosition());
  63186. if (getParentComponent() != 0)
  63187. mousePos = getParentComponent()->getLocalPoint (0, mousePos);
  63188. int x, y, w, h;
  63189. getLookAndFeel().getTooltipSize (tip, w, h);
  63190. if (mousePos.getX() > getParentWidth() / 2)
  63191. x = mousePos.getX() - (w + 12);
  63192. else
  63193. x = mousePos.getX() + 24;
  63194. if (mousePos.getY() > getParentHeight() / 2)
  63195. y = mousePos.getY() - (h + 6);
  63196. else
  63197. y = mousePos.getY() + 6;
  63198. setBounds (x, y, w, h);
  63199. setVisible (true);
  63200. if (getParentComponent() == 0)
  63201. {
  63202. addToDesktop (ComponentPeer::windowHasDropShadow
  63203. | ComponentPeer::windowIsTemporary
  63204. | ComponentPeer::windowIgnoresKeyPresses);
  63205. }
  63206. toFront (false);
  63207. }
  63208. const String TooltipWindow::getTipFor (Component* const c)
  63209. {
  63210. if (c != 0
  63211. && Process::isForegroundProcess()
  63212. && ! Component::isMouseButtonDownAnywhere())
  63213. {
  63214. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  63215. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  63216. return ttc->getTooltip();
  63217. }
  63218. return String::empty;
  63219. }
  63220. void TooltipWindow::hide()
  63221. {
  63222. tipShowing = String::empty;
  63223. removeFromDesktop();
  63224. setVisible (false);
  63225. }
  63226. void TooltipWindow::timerCallback()
  63227. {
  63228. const unsigned int now = Time::getApproximateMillisecondCounter();
  63229. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  63230. const String newTip (getTipFor (newComp));
  63231. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  63232. lastComponentUnderMouse = newComp;
  63233. lastTipUnderMouse = newTip;
  63234. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  63235. const bool mouseWasClicked = clickCount > mouseClicks;
  63236. mouseClicks = clickCount;
  63237. const Point<int> mousePos (Desktop::getMousePosition());
  63238. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  63239. lastMousePos = mousePos;
  63240. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  63241. lastCompChangeTime = now;
  63242. if (isVisible() || now < lastHideTime + 500)
  63243. {
  63244. // if a tip is currently visible (or has just disappeared), update to a new one
  63245. // immediately if needed..
  63246. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  63247. {
  63248. if (isVisible())
  63249. {
  63250. lastHideTime = now;
  63251. hide();
  63252. }
  63253. }
  63254. else if (tipChanged)
  63255. {
  63256. showFor (newTip);
  63257. }
  63258. }
  63259. else
  63260. {
  63261. // if there isn't currently a tip, but one is needed, only let it
  63262. // appear after a timeout..
  63263. if (newTip.isNotEmpty()
  63264. && newTip != tipShowing
  63265. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  63266. {
  63267. showFor (newTip);
  63268. }
  63269. }
  63270. }
  63271. END_JUCE_NAMESPACE
  63272. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  63273. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  63274. BEGIN_JUCE_NAMESPACE
  63275. /** Keeps track of the active top level window.
  63276. */
  63277. class TopLevelWindowManager : public Timer,
  63278. public DeletedAtShutdown
  63279. {
  63280. public:
  63281. TopLevelWindowManager()
  63282. : currentActive (0)
  63283. {
  63284. }
  63285. ~TopLevelWindowManager()
  63286. {
  63287. clearSingletonInstance();
  63288. }
  63289. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  63290. void timerCallback()
  63291. {
  63292. startTimer (jmin (1731, getTimerInterval() * 2));
  63293. TopLevelWindow* active = 0;
  63294. if (Process::isForegroundProcess())
  63295. {
  63296. active = currentActive;
  63297. Component* const c = Component::getCurrentlyFocusedComponent();
  63298. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  63299. if (tlw == 0 && c != 0)
  63300. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  63301. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  63302. if (tlw != 0)
  63303. active = tlw;
  63304. }
  63305. if (active != currentActive)
  63306. {
  63307. currentActive = active;
  63308. for (int i = windows.size(); --i >= 0;)
  63309. {
  63310. TopLevelWindow* const tlw = windows.getUnchecked (i);
  63311. tlw->setWindowActive (isWindowActive (tlw));
  63312. i = jmin (i, windows.size() - 1);
  63313. }
  63314. Desktop::getInstance().triggerFocusCallback();
  63315. }
  63316. }
  63317. bool addWindow (TopLevelWindow* const w)
  63318. {
  63319. windows.add (w);
  63320. startTimer (10);
  63321. return isWindowActive (w);
  63322. }
  63323. void removeWindow (TopLevelWindow* const w)
  63324. {
  63325. startTimer (10);
  63326. if (currentActive == w)
  63327. currentActive = 0;
  63328. windows.removeValue (w);
  63329. if (windows.size() == 0)
  63330. deleteInstance();
  63331. }
  63332. Array <TopLevelWindow*> windows;
  63333. private:
  63334. TopLevelWindow* currentActive;
  63335. bool isWindowActive (TopLevelWindow* const tlw) const
  63336. {
  63337. return (tlw == currentActive
  63338. || tlw->isParentOf (currentActive)
  63339. || tlw->hasKeyboardFocus (true))
  63340. && tlw->isShowing();
  63341. }
  63342. JUCE_DECLARE_NON_COPYABLE (TopLevelWindowManager);
  63343. };
  63344. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  63345. void juce_CheckCurrentlyFocusedTopLevelWindow()
  63346. {
  63347. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  63348. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  63349. }
  63350. TopLevelWindow::TopLevelWindow (const String& name,
  63351. const bool addToDesktop_)
  63352. : Component (name),
  63353. useDropShadow (true),
  63354. useNativeTitleBar (false),
  63355. windowIsActive_ (false)
  63356. {
  63357. setOpaque (true);
  63358. if (addToDesktop_)
  63359. Component::addToDesktop (getDesktopWindowStyleFlags());
  63360. else
  63361. setDropShadowEnabled (true);
  63362. setWantsKeyboardFocus (true);
  63363. setBroughtToFrontOnMouseClick (true);
  63364. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  63365. }
  63366. TopLevelWindow::~TopLevelWindow()
  63367. {
  63368. shadower = 0;
  63369. TopLevelWindowManager::getInstance()->removeWindow (this);
  63370. }
  63371. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  63372. {
  63373. if (hasKeyboardFocus (true))
  63374. TopLevelWindowManager::getInstance()->timerCallback();
  63375. else
  63376. TopLevelWindowManager::getInstance()->startTimer (10);
  63377. }
  63378. void TopLevelWindow::setWindowActive (const bool isNowActive)
  63379. {
  63380. if (windowIsActive_ != isNowActive)
  63381. {
  63382. windowIsActive_ = isNowActive;
  63383. activeWindowStatusChanged();
  63384. }
  63385. }
  63386. void TopLevelWindow::activeWindowStatusChanged()
  63387. {
  63388. }
  63389. void TopLevelWindow::visibilityChanged()
  63390. {
  63391. if (isShowing()
  63392. && (getPeer()->getStyleFlags() & (ComponentPeer::windowIsTemporary
  63393. | ComponentPeer::windowIgnoresKeyPresses)) == 0)
  63394. {
  63395. toFront (true);
  63396. }
  63397. }
  63398. void TopLevelWindow::parentHierarchyChanged()
  63399. {
  63400. setDropShadowEnabled (useDropShadow);
  63401. }
  63402. int TopLevelWindow::getDesktopWindowStyleFlags() const
  63403. {
  63404. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  63405. if (useDropShadow)
  63406. styleFlags |= ComponentPeer::windowHasDropShadow;
  63407. if (useNativeTitleBar)
  63408. styleFlags |= ComponentPeer::windowHasTitleBar;
  63409. return styleFlags;
  63410. }
  63411. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  63412. {
  63413. useDropShadow = useShadow;
  63414. if (isOnDesktop())
  63415. {
  63416. shadower = 0;
  63417. Component::addToDesktop (getDesktopWindowStyleFlags());
  63418. }
  63419. else
  63420. {
  63421. if (useShadow && isOpaque())
  63422. {
  63423. if (shadower == 0)
  63424. {
  63425. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  63426. if (shadower != 0)
  63427. shadower->setOwner (this);
  63428. }
  63429. }
  63430. else
  63431. {
  63432. shadower = 0;
  63433. }
  63434. }
  63435. }
  63436. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  63437. {
  63438. if (useNativeTitleBar != useNativeTitleBar_)
  63439. {
  63440. useNativeTitleBar = useNativeTitleBar_;
  63441. recreateDesktopWindow();
  63442. sendLookAndFeelChange();
  63443. }
  63444. }
  63445. void TopLevelWindow::recreateDesktopWindow()
  63446. {
  63447. if (isOnDesktop())
  63448. {
  63449. Component::addToDesktop (getDesktopWindowStyleFlags());
  63450. toFront (true);
  63451. }
  63452. }
  63453. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  63454. {
  63455. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  63456. because this class needs to make sure its layout corresponds with settings like whether
  63457. it's got a native title bar or not.
  63458. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  63459. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  63460. method, then add or remove whatever flags are necessary from this value before returning it.
  63461. */
  63462. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  63463. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  63464. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  63465. if (windowStyleFlags != getDesktopWindowStyleFlags())
  63466. sendLookAndFeelChange();
  63467. }
  63468. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  63469. {
  63470. if (c == 0)
  63471. c = TopLevelWindow::getActiveTopLevelWindow();
  63472. if (c == 0)
  63473. {
  63474. centreWithSize (width, height);
  63475. }
  63476. else
  63477. {
  63478. Point<int> targetCentre (c->localPointToGlobal (c->getLocalBounds().getCentre()));
  63479. Rectangle<int> parentArea (c->getParentMonitorArea());
  63480. if (getParentComponent() != 0)
  63481. {
  63482. targetCentre = getParentComponent()->getLocalPoint (0, targetCentre);
  63483. parentArea = getParentComponent()->getLocalBounds();
  63484. }
  63485. parentArea.reduce (12, 12);
  63486. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), targetCentre.getX() - width / 2),
  63487. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), targetCentre.getY() - height / 2),
  63488. width, height);
  63489. }
  63490. }
  63491. int TopLevelWindow::getNumTopLevelWindows() throw()
  63492. {
  63493. return TopLevelWindowManager::getInstance()->windows.size();
  63494. }
  63495. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  63496. {
  63497. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  63498. }
  63499. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  63500. {
  63501. TopLevelWindow* best = 0;
  63502. int bestNumTWLParents = -1;
  63503. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  63504. {
  63505. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  63506. if (tlw->isActiveWindow())
  63507. {
  63508. int numTWLParents = 0;
  63509. const Component* c = tlw->getParentComponent();
  63510. while (c != 0)
  63511. {
  63512. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  63513. ++numTWLParents;
  63514. c = c->getParentComponent();
  63515. }
  63516. if (bestNumTWLParents < numTWLParents)
  63517. {
  63518. best = tlw;
  63519. bestNumTWLParents = numTWLParents;
  63520. }
  63521. }
  63522. }
  63523. return best;
  63524. }
  63525. END_JUCE_NAMESPACE
  63526. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  63527. /*** Start of inlined file: juce_MarkerList.cpp ***/
  63528. BEGIN_JUCE_NAMESPACE
  63529. MarkerList::MarkerList()
  63530. {
  63531. }
  63532. MarkerList::MarkerList (const MarkerList& other)
  63533. {
  63534. operator= (other);
  63535. }
  63536. MarkerList& MarkerList::operator= (const MarkerList& other)
  63537. {
  63538. if (other != *this)
  63539. {
  63540. markers.clear();
  63541. markers.addCopiesOf (other.markers);
  63542. markersHaveChanged();
  63543. }
  63544. return *this;
  63545. }
  63546. MarkerList::~MarkerList()
  63547. {
  63548. listeners.call (&MarkerList::Listener::markerListBeingDeleted, this);
  63549. }
  63550. bool MarkerList::operator== (const MarkerList& other) const throw()
  63551. {
  63552. if (other.markers.size() != markers.size())
  63553. return false;
  63554. for (int i = markers.size(); --i >= 0;)
  63555. {
  63556. const Marker* const m1 = markers.getUnchecked(i);
  63557. jassert (m1 != 0);
  63558. const Marker* const m2 = other.getMarker (m1->name);
  63559. if (m2 == 0 || *m1 != *m2)
  63560. return false;
  63561. }
  63562. return true;
  63563. }
  63564. bool MarkerList::operator!= (const MarkerList& other) const throw()
  63565. {
  63566. return ! operator== (other);
  63567. }
  63568. int MarkerList::getNumMarkers() const throw()
  63569. {
  63570. return markers.size();
  63571. }
  63572. const MarkerList::Marker* MarkerList::getMarker (const int index) const throw()
  63573. {
  63574. return markers [index];
  63575. }
  63576. const MarkerList::Marker* MarkerList::getMarker (const String& name) const throw()
  63577. {
  63578. for (int i = 0; i < markers.size(); ++i)
  63579. {
  63580. const Marker* const m = markers.getUnchecked(i);
  63581. if (m->name == name)
  63582. return m;
  63583. }
  63584. return 0;
  63585. }
  63586. void MarkerList::setMarker (const String& name, const RelativeCoordinate& position)
  63587. {
  63588. Marker* const m = const_cast <Marker*> (getMarker (name));
  63589. if (m != 0)
  63590. {
  63591. if (m->position != position)
  63592. {
  63593. m->position = position;
  63594. markersHaveChanged();
  63595. }
  63596. return;
  63597. }
  63598. markers.add (new Marker (name, position));
  63599. markersHaveChanged();
  63600. }
  63601. void MarkerList::removeMarker (const int index)
  63602. {
  63603. if (isPositiveAndBelow (index, markers.size()))
  63604. {
  63605. markers.remove (index);
  63606. markersHaveChanged();
  63607. }
  63608. }
  63609. void MarkerList::removeMarker (const String& name)
  63610. {
  63611. for (int i = 0; i < markers.size(); ++i)
  63612. {
  63613. const Marker* const m = markers.getUnchecked(i);
  63614. if (m->name == name)
  63615. {
  63616. markers.remove (i);
  63617. markersHaveChanged();
  63618. }
  63619. }
  63620. }
  63621. void MarkerList::markersHaveChanged()
  63622. {
  63623. listeners.call (&MarkerList::Listener::markersChanged, this);
  63624. }
  63625. void MarkerList::Listener::markerListBeingDeleted (MarkerList*)
  63626. {
  63627. }
  63628. void MarkerList::addListener (Listener* listener)
  63629. {
  63630. listeners.add (listener);
  63631. }
  63632. void MarkerList::removeListener (Listener* listener)
  63633. {
  63634. listeners.remove (listener);
  63635. }
  63636. MarkerList::Marker::Marker (const Marker& other)
  63637. : name (other.name), position (other.position)
  63638. {
  63639. }
  63640. MarkerList::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  63641. : name (name_), position (position_)
  63642. {
  63643. }
  63644. bool MarkerList::Marker::operator== (const Marker& other) const throw()
  63645. {
  63646. return name == other.name && position == other.position;
  63647. }
  63648. bool MarkerList::Marker::operator!= (const Marker& other) const throw()
  63649. {
  63650. return ! operator== (other);
  63651. }
  63652. const Identifier MarkerList::ValueTreeWrapper::markerTag ("Marker");
  63653. const Identifier MarkerList::ValueTreeWrapper::nameProperty ("name");
  63654. const Identifier MarkerList::ValueTreeWrapper::posProperty ("position");
  63655. MarkerList::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  63656. : state (state_)
  63657. {
  63658. }
  63659. int MarkerList::ValueTreeWrapper::getNumMarkers() const
  63660. {
  63661. return state.getNumChildren();
  63662. }
  63663. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (int index) const
  63664. {
  63665. return state.getChild (index);
  63666. }
  63667. const ValueTree MarkerList::ValueTreeWrapper::getMarkerState (const String& name) const
  63668. {
  63669. return state.getChildWithProperty (nameProperty, name);
  63670. }
  63671. bool MarkerList::ValueTreeWrapper::containsMarker (const ValueTree& marker) const
  63672. {
  63673. return marker.isAChildOf (state);
  63674. }
  63675. const MarkerList::Marker MarkerList::ValueTreeWrapper::getMarker (const ValueTree& marker) const
  63676. {
  63677. jassert (containsMarker (marker));
  63678. return MarkerList::Marker (marker [nameProperty], RelativeCoordinate (marker [posProperty].toString()));
  63679. }
  63680. void MarkerList::ValueTreeWrapper::setMarker (const MarkerList::Marker& m, UndoManager* undoManager)
  63681. {
  63682. ValueTree marker (state.getChildWithProperty (nameProperty, m.name));
  63683. if (marker.isValid())
  63684. {
  63685. marker.setProperty (posProperty, m.position.toString(), undoManager);
  63686. }
  63687. else
  63688. {
  63689. marker = ValueTree (markerTag);
  63690. marker.setProperty (nameProperty, m.name, 0);
  63691. marker.setProperty (posProperty, m.position.toString(), 0);
  63692. state.addChild (marker, -1, undoManager);
  63693. }
  63694. }
  63695. void MarkerList::ValueTreeWrapper::removeMarker (const ValueTree& marker, UndoManager* undoManager)
  63696. {
  63697. state.removeChild (marker, undoManager);
  63698. }
  63699. double MarkerList::getMarkerPosition (const Marker& marker, Component* parentComponent) const
  63700. {
  63701. if (parentComponent != 0)
  63702. {
  63703. RelativeCoordinatePositionerBase::ComponentScope scope (*parentComponent);
  63704. return marker.position.resolve (&scope);
  63705. }
  63706. else
  63707. {
  63708. return marker.position.resolve (0);
  63709. }
  63710. }
  63711. void MarkerList::ValueTreeWrapper::applyTo (MarkerList& markerList)
  63712. {
  63713. const int numMarkers = getNumMarkers();
  63714. StringArray updatedMarkers;
  63715. int i;
  63716. for (i = 0; i < numMarkers; ++i)
  63717. {
  63718. const ValueTree marker (state.getChild (i));
  63719. const String name (marker [nameProperty].toString());
  63720. markerList.setMarker (name, RelativeCoordinate (marker [posProperty].toString()));
  63721. updatedMarkers.add (name);
  63722. }
  63723. for (i = markerList.getNumMarkers(); --i >= 0;)
  63724. if (! updatedMarkers.contains (markerList.getMarker (i)->name))
  63725. markerList.removeMarker (i);
  63726. }
  63727. void MarkerList::ValueTreeWrapper::readFrom (const MarkerList& markerList, UndoManager* undoManager)
  63728. {
  63729. state.removeAllChildren (undoManager);
  63730. for (int i = 0; i < markerList.getNumMarkers(); ++i)
  63731. setMarker (*markerList.getMarker(i), undoManager);
  63732. }
  63733. END_JUCE_NAMESPACE
  63734. /*** End of inlined file: juce_MarkerList.cpp ***/
  63735. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  63736. BEGIN_JUCE_NAMESPACE
  63737. const String RelativeCoordinate::Strings::parent ("parent");
  63738. const String RelativeCoordinate::Strings::left ("left");
  63739. const String RelativeCoordinate::Strings::right ("right");
  63740. const String RelativeCoordinate::Strings::top ("top");
  63741. const String RelativeCoordinate::Strings::bottom ("bottom");
  63742. const String RelativeCoordinate::Strings::x ("x");
  63743. const String RelativeCoordinate::Strings::y ("y");
  63744. const String RelativeCoordinate::Strings::width ("width");
  63745. const String RelativeCoordinate::Strings::height ("height");
  63746. RelativeCoordinate::StandardStrings::Type RelativeCoordinate::StandardStrings::getTypeOf (const String& s) throw()
  63747. {
  63748. if (s == Strings::left) return left;
  63749. if (s == Strings::right) return right;
  63750. if (s == Strings::top) return top;
  63751. if (s == Strings::bottom) return bottom;
  63752. if (s == Strings::x) return x;
  63753. if (s == Strings::y) return y;
  63754. if (s == Strings::width) return width;
  63755. if (s == Strings::height) return height;
  63756. if (s == Strings::parent) return parent;
  63757. return unknown;
  63758. }
  63759. RelativeCoordinate::RelativeCoordinate()
  63760. {
  63761. }
  63762. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  63763. : term (term_)
  63764. {
  63765. }
  63766. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  63767. : term (other.term)
  63768. {
  63769. }
  63770. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  63771. {
  63772. term = other.term;
  63773. return *this;
  63774. }
  63775. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  63776. : term (absoluteDistanceFromOrigin)
  63777. {
  63778. }
  63779. RelativeCoordinate::RelativeCoordinate (const String& s)
  63780. {
  63781. try
  63782. {
  63783. term = Expression (s);
  63784. }
  63785. catch (...)
  63786. {}
  63787. }
  63788. RelativeCoordinate::~RelativeCoordinate()
  63789. {
  63790. }
  63791. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  63792. {
  63793. return term.toString() == other.term.toString();
  63794. }
  63795. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  63796. {
  63797. return ! operator== (other);
  63798. }
  63799. double RelativeCoordinate::resolve (const Expression::Scope* scope) const
  63800. {
  63801. try
  63802. {
  63803. if (scope != 0)
  63804. return term.evaluate (*scope);
  63805. else
  63806. return term.evaluate();
  63807. }
  63808. catch (...)
  63809. {}
  63810. return 0.0;
  63811. }
  63812. bool RelativeCoordinate::isRecursive (const Expression::Scope* scope) const
  63813. {
  63814. try
  63815. {
  63816. if (scope != 0)
  63817. term.evaluate (*scope);
  63818. else
  63819. term.evaluate();
  63820. }
  63821. catch (...)
  63822. {
  63823. return true;
  63824. }
  63825. return false;
  63826. }
  63827. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::Scope* scope)
  63828. {
  63829. try
  63830. {
  63831. if (scope != 0)
  63832. {
  63833. term = term.adjustedToGiveNewResult (newPos, *scope);
  63834. }
  63835. else
  63836. {
  63837. Expression::Scope defaultScope;
  63838. term = term.adjustedToGiveNewResult (newPos, defaultScope);
  63839. }
  63840. }
  63841. catch (...)
  63842. {}
  63843. }
  63844. bool RelativeCoordinate::isDynamic() const
  63845. {
  63846. return term.usesAnySymbols();
  63847. }
  63848. const String RelativeCoordinate::toString() const
  63849. {
  63850. return term.toString();
  63851. }
  63852. END_JUCE_NAMESPACE
  63853. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  63854. /*** Start of inlined file: juce_RelativePoint.cpp ***/
  63855. BEGIN_JUCE_NAMESPACE
  63856. namespace RelativePointHelpers
  63857. {
  63858. inline void skipComma (String::CharPointerType& s)
  63859. {
  63860. s = s.findEndOfWhitespace();
  63861. if (*s == ',')
  63862. ++s;
  63863. }
  63864. }
  63865. RelativePoint::RelativePoint()
  63866. {
  63867. }
  63868. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  63869. : x (absolutePoint.getX()), y (absolutePoint.getY())
  63870. {
  63871. }
  63872. RelativePoint::RelativePoint (const float x_, const float y_)
  63873. : x (x_), y (y_)
  63874. {
  63875. }
  63876. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  63877. : x (x_), y (y_)
  63878. {
  63879. }
  63880. RelativePoint::RelativePoint (const String& s)
  63881. {
  63882. String::CharPointerType text (s.getCharPointer());
  63883. x = RelativeCoordinate (Expression::parse (text));
  63884. RelativePointHelpers::skipComma (text);
  63885. y = RelativeCoordinate (Expression::parse (text));
  63886. }
  63887. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  63888. {
  63889. return x == other.x && y == other.y;
  63890. }
  63891. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  63892. {
  63893. return ! operator== (other);
  63894. }
  63895. const Point<float> RelativePoint::resolve (const Expression::Scope* scope) const
  63896. {
  63897. return Point<float> ((float) x.resolve (scope),
  63898. (float) y.resolve (scope));
  63899. }
  63900. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::Scope* scope)
  63901. {
  63902. x.moveToAbsolute (newPos.getX(), scope);
  63903. y.moveToAbsolute (newPos.getY(), scope);
  63904. }
  63905. const String RelativePoint::toString() const
  63906. {
  63907. return x.toString() + ", " + y.toString();
  63908. }
  63909. bool RelativePoint::isDynamic() const
  63910. {
  63911. return x.isDynamic() || y.isDynamic();
  63912. }
  63913. END_JUCE_NAMESPACE
  63914. /*** End of inlined file: juce_RelativePoint.cpp ***/
  63915. /*** Start of inlined file: juce_RelativeRectangle.cpp ***/
  63916. BEGIN_JUCE_NAMESPACE
  63917. namespace RelativeRectangleHelpers
  63918. {
  63919. inline void skipComma (String::CharPointerType& s)
  63920. {
  63921. s = s.findEndOfWhitespace();
  63922. if (*s == ',')
  63923. ++s;
  63924. }
  63925. bool dependsOnSymbolsOtherThanThis (const Expression& e)
  63926. {
  63927. if (e.getType() == Expression::operatorType && e.getSymbolOrFunction() == ".")
  63928. return true;
  63929. if (e.getType() == Expression::symbolType)
  63930. {
  63931. switch (RelativeCoordinate::StandardStrings::getTypeOf (e.getSymbolOrFunction()))
  63932. {
  63933. case RelativeCoordinate::StandardStrings::x:
  63934. case RelativeCoordinate::StandardStrings::y:
  63935. case RelativeCoordinate::StandardStrings::left:
  63936. case RelativeCoordinate::StandardStrings::right:
  63937. case RelativeCoordinate::StandardStrings::top:
  63938. case RelativeCoordinate::StandardStrings::bottom: return false;
  63939. default: break;
  63940. }
  63941. return true;
  63942. }
  63943. else
  63944. {
  63945. for (int i = e.getNumInputs(); --i >= 0;)
  63946. if (dependsOnSymbolsOtherThanThis (e.getInput(i)))
  63947. return true;
  63948. }
  63949. return false;
  63950. }
  63951. }
  63952. RelativeRectangle::RelativeRectangle()
  63953. {
  63954. }
  63955. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  63956. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  63957. : left (left_), right (right_), top (top_), bottom (bottom_)
  63958. {
  63959. }
  63960. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect)
  63961. : left (rect.getX()),
  63962. right (Expression::symbol (RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  63963. top (rect.getY()),
  63964. bottom (Expression::symbol (RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  63965. {
  63966. }
  63967. RelativeRectangle::RelativeRectangle (const String& s)
  63968. {
  63969. String::CharPointerType text (s.getCharPointer());
  63970. left = RelativeCoordinate (Expression::parse (text));
  63971. RelativeRectangleHelpers::skipComma (text);
  63972. top = RelativeCoordinate (Expression::parse (text));
  63973. RelativeRectangleHelpers::skipComma (text);
  63974. right = RelativeCoordinate (Expression::parse (text));
  63975. RelativeRectangleHelpers::skipComma (text);
  63976. bottom = RelativeCoordinate (Expression::parse (text));
  63977. }
  63978. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  63979. {
  63980. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  63981. }
  63982. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  63983. {
  63984. return ! operator== (other);
  63985. }
  63986. // An expression context that can evaluate expressions using "this"
  63987. class RelativeRectangleLocalScope : public Expression::Scope
  63988. {
  63989. public:
  63990. RelativeRectangleLocalScope (const RelativeRectangle& rect_) : rect (rect_) {}
  63991. const Expression getSymbolValue (const String& symbol) const
  63992. {
  63993. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  63994. {
  63995. case RelativeCoordinate::StandardStrings::x:
  63996. case RelativeCoordinate::StandardStrings::left: return rect.left.getExpression();
  63997. case RelativeCoordinate::StandardStrings::y:
  63998. case RelativeCoordinate::StandardStrings::top: return rect.top.getExpression();
  63999. case RelativeCoordinate::StandardStrings::right: return rect.right.getExpression();
  64000. case RelativeCoordinate::StandardStrings::bottom: return rect.bottom.getExpression();
  64001. default: break;
  64002. }
  64003. return Expression::Scope::getSymbolValue (symbol);
  64004. }
  64005. private:
  64006. const RelativeRectangle& rect;
  64007. JUCE_DECLARE_NON_COPYABLE (RelativeRectangleLocalScope);
  64008. };
  64009. const Rectangle<float> RelativeRectangle::resolve (const Expression::Scope* scope) const
  64010. {
  64011. if (scope == 0)
  64012. {
  64013. RelativeRectangleLocalScope scope (*this);
  64014. return resolve (&scope);
  64015. }
  64016. else
  64017. {
  64018. const double l = left.resolve (scope);
  64019. const double r = right.resolve (scope);
  64020. const double t = top.resolve (scope);
  64021. const double b = bottom.resolve (scope);
  64022. return Rectangle<float> ((float) l, (float) t, (float) jmax (0.0, r - l), (float) jmax (0.0, b - t));
  64023. }
  64024. }
  64025. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::Scope* scope)
  64026. {
  64027. left.moveToAbsolute (newPos.getX(), scope);
  64028. right.moveToAbsolute (newPos.getRight(), scope);
  64029. top.moveToAbsolute (newPos.getY(), scope);
  64030. bottom.moveToAbsolute (newPos.getBottom(), scope);
  64031. }
  64032. bool RelativeRectangle::isDynamic() const
  64033. {
  64034. using namespace RelativeRectangleHelpers;
  64035. return dependsOnSymbolsOtherThanThis (left.getExpression())
  64036. || dependsOnSymbolsOtherThanThis (right.getExpression())
  64037. || dependsOnSymbolsOtherThanThis (top.getExpression())
  64038. || dependsOnSymbolsOtherThanThis (bottom.getExpression());
  64039. }
  64040. const String RelativeRectangle::toString() const
  64041. {
  64042. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64043. }
  64044. void RelativeRectangle::renameSymbol (const Expression::Symbol& oldSymbol, const String& newName, const Expression::Scope& scope)
  64045. {
  64046. left = left.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64047. right = right.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64048. top = top.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64049. bottom = bottom.getExpression().withRenamedSymbol (oldSymbol, newName, scope);
  64050. }
  64051. class RelativeRectangleComponentPositioner : public RelativeCoordinatePositionerBase
  64052. {
  64053. public:
  64054. RelativeRectangleComponentPositioner (Component& component_, const RelativeRectangle& rectangle_)
  64055. : RelativeCoordinatePositionerBase (component_),
  64056. rectangle (rectangle_)
  64057. {
  64058. }
  64059. bool registerCoordinates()
  64060. {
  64061. bool ok = addCoordinate (rectangle.left);
  64062. ok = addCoordinate (rectangle.right) && ok;
  64063. ok = addCoordinate (rectangle.top) && ok;
  64064. ok = addCoordinate (rectangle.bottom) && ok;
  64065. return ok;
  64066. }
  64067. bool isUsingRectangle (const RelativeRectangle& other) const throw()
  64068. {
  64069. return rectangle == other;
  64070. }
  64071. void applyToComponentBounds()
  64072. {
  64073. for (int i = 4; --i >= 0;)
  64074. {
  64075. ComponentScope scope (getComponent());
  64076. const Rectangle<int> newBounds (rectangle.resolve (&scope).getSmallestIntegerContainer());
  64077. if (newBounds == getComponent().getBounds())
  64078. return;
  64079. getComponent().setBounds (newBounds);
  64080. }
  64081. jassertfalse; // must be a recursive reference!
  64082. }
  64083. private:
  64084. const RelativeRectangle rectangle;
  64085. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativeRectangleComponentPositioner);
  64086. };
  64087. void RelativeRectangle::applyToComponent (Component& component) const
  64088. {
  64089. if (isDynamic())
  64090. {
  64091. RelativeRectangleComponentPositioner* current = dynamic_cast <RelativeRectangleComponentPositioner*> (component.getPositioner());
  64092. if (current == 0 || ! current->isUsingRectangle (*this))
  64093. {
  64094. RelativeRectangleComponentPositioner* p = new RelativeRectangleComponentPositioner (component, *this);
  64095. component.setPositioner (p);
  64096. p->apply();
  64097. }
  64098. }
  64099. else
  64100. {
  64101. component.setPositioner (0);
  64102. component.setBounds (resolve (0).getSmallestIntegerContainer());
  64103. }
  64104. }
  64105. END_JUCE_NAMESPACE
  64106. /*** End of inlined file: juce_RelativeRectangle.cpp ***/
  64107. /*** Start of inlined file: juce_RelativePointPath.cpp ***/
  64108. BEGIN_JUCE_NAMESPACE
  64109. RelativePointPath::RelativePointPath()
  64110. : usesNonZeroWinding (true),
  64111. containsDynamicPoints (false)
  64112. {
  64113. }
  64114. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64115. : usesNonZeroWinding (true),
  64116. containsDynamicPoints (false)
  64117. {
  64118. for (int i = 0; i < other.elements.size(); ++i)
  64119. elements.add (other.elements.getUnchecked(i)->clone());
  64120. }
  64121. RelativePointPath::RelativePointPath (const Path& path)
  64122. : usesNonZeroWinding (path.isUsingNonZeroWinding()),
  64123. containsDynamicPoints (false)
  64124. {
  64125. for (Path::Iterator i (path); i.next();)
  64126. {
  64127. switch (i.elementType)
  64128. {
  64129. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64130. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64131. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64132. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64133. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64134. default: jassertfalse; break;
  64135. }
  64136. }
  64137. }
  64138. RelativePointPath::~RelativePointPath()
  64139. {
  64140. }
  64141. bool RelativePointPath::operator== (const RelativePointPath& other) const throw()
  64142. {
  64143. if (elements.size() != other.elements.size()
  64144. || usesNonZeroWinding != other.usesNonZeroWinding
  64145. || containsDynamicPoints != other.containsDynamicPoints)
  64146. return false;
  64147. for (int i = 0; i < elements.size(); ++i)
  64148. {
  64149. ElementBase* const e1 = elements.getUnchecked(i);
  64150. ElementBase* const e2 = other.elements.getUnchecked(i);
  64151. if (e1->type != e2->type)
  64152. return false;
  64153. int numPoints1, numPoints2;
  64154. const RelativePoint* const points1 = e1->getControlPoints (numPoints1);
  64155. const RelativePoint* const points2 = e2->getControlPoints (numPoints2);
  64156. jassert (numPoints1 == numPoints2);
  64157. for (int j = numPoints1; --j >= 0;)
  64158. if (points1[j] != points2[j])
  64159. return false;
  64160. }
  64161. return true;
  64162. }
  64163. bool RelativePointPath::operator!= (const RelativePointPath& other) const throw()
  64164. {
  64165. return ! operator== (other);
  64166. }
  64167. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64168. {
  64169. elements.swapWithArray (other.elements);
  64170. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64171. swapVariables (containsDynamicPoints, other.containsDynamicPoints);
  64172. }
  64173. void RelativePointPath::createPath (Path& path, Expression::Scope* scope) const
  64174. {
  64175. for (int i = 0; i < elements.size(); ++i)
  64176. elements.getUnchecked(i)->addToPath (path, scope);
  64177. }
  64178. bool RelativePointPath::containsAnyDynamicPoints() const
  64179. {
  64180. return containsDynamicPoints;
  64181. }
  64182. void RelativePointPath::addElement (ElementBase* newElement)
  64183. {
  64184. if (newElement != 0)
  64185. {
  64186. elements.add (newElement);
  64187. containsDynamicPoints = containsDynamicPoints || newElement->isDynamic();
  64188. }
  64189. }
  64190. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64191. {
  64192. }
  64193. bool RelativePointPath::ElementBase::isDynamic()
  64194. {
  64195. int numPoints;
  64196. const RelativePoint* const points = getControlPoints (numPoints);
  64197. for (int i = numPoints; --i >= 0;)
  64198. if (points[i].isDynamic())
  64199. return true;
  64200. return false;
  64201. }
  64202. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64203. : ElementBase (startSubPathElement), startPos (pos)
  64204. {
  64205. }
  64206. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64207. {
  64208. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64209. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64210. return v;
  64211. }
  64212. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::Scope* scope) const
  64213. {
  64214. path.startNewSubPath (startPos.resolve (scope));
  64215. }
  64216. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64217. {
  64218. numPoints = 1;
  64219. return &startPos;
  64220. }
  64221. RelativePointPath::ElementBase* RelativePointPath::StartSubPath::clone() const
  64222. {
  64223. return new StartSubPath (startPos);
  64224. }
  64225. RelativePointPath::CloseSubPath::CloseSubPath()
  64226. : ElementBase (closeSubPathElement)
  64227. {
  64228. }
  64229. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64230. {
  64231. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64232. }
  64233. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::Scope*) const
  64234. {
  64235. path.closeSubPath();
  64236. }
  64237. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64238. {
  64239. numPoints = 0;
  64240. return 0;
  64241. }
  64242. RelativePointPath::ElementBase* RelativePointPath::CloseSubPath::clone() const
  64243. {
  64244. return new CloseSubPath();
  64245. }
  64246. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64247. : ElementBase (lineToElement), endPoint (endPoint_)
  64248. {
  64249. }
  64250. const ValueTree RelativePointPath::LineTo::createTree() const
  64251. {
  64252. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64253. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64254. return v;
  64255. }
  64256. void RelativePointPath::LineTo::addToPath (Path& path, Expression::Scope* scope) const
  64257. {
  64258. path.lineTo (endPoint.resolve (scope));
  64259. }
  64260. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64261. {
  64262. numPoints = 1;
  64263. return &endPoint;
  64264. }
  64265. RelativePointPath::ElementBase* RelativePointPath::LineTo::clone() const
  64266. {
  64267. return new LineTo (endPoint);
  64268. }
  64269. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64270. : ElementBase (quadraticToElement)
  64271. {
  64272. controlPoints[0] = controlPoint;
  64273. controlPoints[1] = endPoint;
  64274. }
  64275. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64276. {
  64277. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64278. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64279. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64280. return v;
  64281. }
  64282. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::Scope* scope) const
  64283. {
  64284. path.quadraticTo (controlPoints[0].resolve (scope),
  64285. controlPoints[1].resolve (scope));
  64286. }
  64287. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64288. {
  64289. numPoints = 2;
  64290. return controlPoints;
  64291. }
  64292. RelativePointPath::ElementBase* RelativePointPath::QuadraticTo::clone() const
  64293. {
  64294. return new QuadraticTo (controlPoints[0], controlPoints[1]);
  64295. }
  64296. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64297. : ElementBase (cubicToElement)
  64298. {
  64299. controlPoints[0] = controlPoint1;
  64300. controlPoints[1] = controlPoint2;
  64301. controlPoints[2] = endPoint;
  64302. }
  64303. const ValueTree RelativePointPath::CubicTo::createTree() const
  64304. {
  64305. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64306. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64307. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64308. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64309. return v;
  64310. }
  64311. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::Scope* scope) const
  64312. {
  64313. path.cubicTo (controlPoints[0].resolve (scope),
  64314. controlPoints[1].resolve (scope),
  64315. controlPoints[2].resolve (scope));
  64316. }
  64317. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64318. {
  64319. numPoints = 3;
  64320. return controlPoints;
  64321. }
  64322. RelativePointPath::ElementBase* RelativePointPath::CubicTo::clone() const
  64323. {
  64324. return new CubicTo (controlPoints[0], controlPoints[1], controlPoints[2]);
  64325. }
  64326. END_JUCE_NAMESPACE
  64327. /*** End of inlined file: juce_RelativePointPath.cpp ***/
  64328. /*** Start of inlined file: juce_RelativeParallelogram.cpp ***/
  64329. BEGIN_JUCE_NAMESPACE
  64330. RelativeParallelogram::RelativeParallelogram()
  64331. {
  64332. }
  64333. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64334. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64335. {
  64336. }
  64337. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64338. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64339. {
  64340. }
  64341. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64342. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64343. {
  64344. }
  64345. RelativeParallelogram::~RelativeParallelogram()
  64346. {
  64347. }
  64348. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::Scope* const scope) const
  64349. {
  64350. points[0] = topLeft.resolve (scope);
  64351. points[1] = topRight.resolve (scope);
  64352. points[2] = bottomLeft.resolve (scope);
  64353. }
  64354. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::Scope* const scope) const
  64355. {
  64356. resolveThreePoints (points, scope);
  64357. points[3] = points[1] + (points[2] - points[0]);
  64358. }
  64359. const Rectangle<float> RelativeParallelogram::getBounds (Expression::Scope* const scope) const
  64360. {
  64361. Point<float> points[4];
  64362. resolveFourCorners (points, scope);
  64363. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64364. }
  64365. void RelativeParallelogram::getPath (Path& path, Expression::Scope* const scope) const
  64366. {
  64367. Point<float> points[4];
  64368. resolveFourCorners (points, scope);
  64369. path.startNewSubPath (points[0]);
  64370. path.lineTo (points[1]);
  64371. path.lineTo (points[3]);
  64372. path.lineTo (points[2]);
  64373. path.closeSubPath();
  64374. }
  64375. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::Scope* const scope)
  64376. {
  64377. Point<float> corners[3];
  64378. resolveThreePoints (corners, scope);
  64379. const Line<float> top (corners[0], corners[1]);
  64380. const Line<float> left (corners[0], corners[2]);
  64381. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64382. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64383. topRight.moveToAbsolute (newTopRight, scope);
  64384. bottomLeft.moveToAbsolute (newBottomLeft, scope);
  64385. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64386. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64387. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64388. }
  64389. bool RelativeParallelogram::isDynamic() const
  64390. {
  64391. return topLeft.isDynamic() || topRight.isDynamic() || bottomLeft.isDynamic();
  64392. }
  64393. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64394. {
  64395. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64396. }
  64397. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64398. {
  64399. return ! operator== (other);
  64400. }
  64401. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64402. {
  64403. const Point<float> tr (corners[1] - corners[0]);
  64404. const Point<float> bl (corners[2] - corners[0]);
  64405. target -= corners[0];
  64406. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64407. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64408. }
  64409. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64410. {
  64411. return corners[0]
  64412. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64413. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64414. }
  64415. const Rectangle<float> RelativeParallelogram::getBoundingBox (const Point<float>* const p) throw()
  64416. {
  64417. const Point<float> points[] = { p[0], p[1], p[2], p[1] + (p[2] - p[0]) };
  64418. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64419. }
  64420. END_JUCE_NAMESPACE
  64421. /*** End of inlined file: juce_RelativeParallelogram.cpp ***/
  64422. /*** Start of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64423. BEGIN_JUCE_NAMESPACE
  64424. RelativeCoordinatePositionerBase::ComponentScope::ComponentScope (Component& component_)
  64425. : component (component_)
  64426. {
  64427. }
  64428. const Expression RelativeCoordinatePositionerBase::ComponentScope::getSymbolValue (const String& symbol) const
  64429. {
  64430. switch (RelativeCoordinate::StandardStrings::getTypeOf (symbol))
  64431. {
  64432. case RelativeCoordinate::StandardStrings::x:
  64433. case RelativeCoordinate::StandardStrings::left: return Expression ((double) component.getX());
  64434. case RelativeCoordinate::StandardStrings::y:
  64435. case RelativeCoordinate::StandardStrings::top: return Expression ((double) component.getY());
  64436. case RelativeCoordinate::StandardStrings::width: return Expression ((double) component.getWidth());
  64437. case RelativeCoordinate::StandardStrings::height: return Expression ((double) component.getHeight());
  64438. case RelativeCoordinate::StandardStrings::right: return Expression ((double) component.getRight());
  64439. case RelativeCoordinate::StandardStrings::bottom: return Expression ((double) component.getBottom());
  64440. default: break;
  64441. }
  64442. MarkerList* list;
  64443. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64444. if (marker != 0)
  64445. return marker->position.getExpression();
  64446. return Expression::Scope::getSymbolValue (symbol);
  64447. }
  64448. void RelativeCoordinatePositionerBase::ComponentScope::visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64449. {
  64450. Component* targetComp = 0;
  64451. if (scopeName == RelativeCoordinate::Strings::parent)
  64452. targetComp = component.getParentComponent();
  64453. else
  64454. targetComp = findSiblingComponent (scopeName);
  64455. if (targetComp != 0)
  64456. visitor.visit (ComponentScope (*targetComp));
  64457. else
  64458. Expression::Scope::visitRelativeScope (scopeName, visitor);
  64459. }
  64460. const String RelativeCoordinatePositionerBase::ComponentScope::getScopeUID() const
  64461. {
  64462. return String::toHexString ((int) (pointer_sized_int) (void*) &component);
  64463. }
  64464. Component* RelativeCoordinatePositionerBase::ComponentScope::findSiblingComponent (const String& componentID) const
  64465. {
  64466. Component* const parent = component.getParentComponent();
  64467. if (parent != 0)
  64468. {
  64469. for (int i = parent->getNumChildComponents(); --i >= 0;)
  64470. {
  64471. Component* const c = parent->getChildComponent(i);
  64472. if (c->getComponentID() == componentID)
  64473. return c;
  64474. }
  64475. }
  64476. return 0;
  64477. }
  64478. const MarkerList::Marker* RelativeCoordinatePositionerBase::ComponentScope::findMarker (const String& name, MarkerList*& list) const
  64479. {
  64480. const MarkerList::Marker* marker = 0;
  64481. Component* const parent = component.getParentComponent();
  64482. if (parent != 0)
  64483. {
  64484. list = parent->getMarkers (true);
  64485. if (list != 0)
  64486. marker = list->getMarker (name);
  64487. if (marker == 0)
  64488. {
  64489. list = parent->getMarkers (false);
  64490. if (list != 0)
  64491. marker = list->getMarker (name);
  64492. }
  64493. }
  64494. return marker;
  64495. }
  64496. class RelativeCoordinatePositionerBase::DependencyFinderScope : public ComponentScope
  64497. {
  64498. public:
  64499. DependencyFinderScope (Component& component_, RelativeCoordinatePositionerBase& positioner_, bool& ok_)
  64500. : ComponentScope (component_), positioner (positioner_), ok (ok_)
  64501. {
  64502. }
  64503. const Expression getSymbolValue (const String& symbol) const
  64504. {
  64505. if (symbol == RelativeCoordinate::Strings::left || symbol == RelativeCoordinate::Strings::x
  64506. || symbol == RelativeCoordinate::Strings::width || symbol == RelativeCoordinate::Strings::right
  64507. || symbol == RelativeCoordinate::Strings::top || symbol == RelativeCoordinate::Strings::y
  64508. || symbol == RelativeCoordinate::Strings::height || symbol == RelativeCoordinate::Strings::bottom)
  64509. {
  64510. positioner.registerComponentListener (component);
  64511. }
  64512. else
  64513. {
  64514. MarkerList* list;
  64515. const MarkerList::Marker* const marker = findMarker (symbol, list);
  64516. if (marker != 0)
  64517. {
  64518. positioner.registerMarkerListListener (list);
  64519. }
  64520. else
  64521. {
  64522. // The marker we want doesn't exist, so watch all lists in case they change and the marker appears later..
  64523. positioner.registerMarkerListListener (component.getMarkers (true));
  64524. positioner.registerMarkerListListener (component.getMarkers (false));
  64525. ok = false;
  64526. }
  64527. }
  64528. return ComponentScope::getSymbolValue (symbol);
  64529. }
  64530. void visitRelativeScope (const String& scopeName, Visitor& visitor) const
  64531. {
  64532. Component* targetComp = 0;
  64533. if (scopeName == RelativeCoordinate::Strings::parent)
  64534. targetComp = component.getParentComponent();
  64535. else
  64536. targetComp = findSiblingComponent (scopeName);
  64537. if (targetComp != 0)
  64538. {
  64539. visitor.visit (DependencyFinderScope (*targetComp, positioner, ok));
  64540. }
  64541. else
  64542. {
  64543. // The named component doesn't exist, so we'll watch the parent for changes in case it appears later..
  64544. Component* const parent = component.getParentComponent();
  64545. if (parent != 0)
  64546. positioner.registerComponentListener (*parent);
  64547. positioner.registerComponentListener (component);
  64548. ok = false;
  64549. }
  64550. }
  64551. private:
  64552. RelativeCoordinatePositionerBase& positioner;
  64553. bool& ok;
  64554. JUCE_DECLARE_NON_COPYABLE (DependencyFinderScope);
  64555. };
  64556. RelativeCoordinatePositionerBase::RelativeCoordinatePositionerBase (Component& component_)
  64557. : Component::Positioner (component_), registeredOk (false)
  64558. {
  64559. }
  64560. RelativeCoordinatePositionerBase::~RelativeCoordinatePositionerBase()
  64561. {
  64562. unregisterListeners();
  64563. }
  64564. void RelativeCoordinatePositionerBase::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  64565. {
  64566. apply();
  64567. }
  64568. void RelativeCoordinatePositionerBase::componentParentHierarchyChanged (Component&)
  64569. {
  64570. apply();
  64571. }
  64572. void RelativeCoordinatePositionerBase::componentChildrenChanged (Component& changed)
  64573. {
  64574. if (getComponent().getParentComponent() == &changed && ! registeredOk)
  64575. apply();
  64576. }
  64577. void RelativeCoordinatePositionerBase::componentBeingDeleted (Component& component)
  64578. {
  64579. jassert (sourceComponents.contains (&component));
  64580. sourceComponents.removeValue (&component);
  64581. registeredOk = false;
  64582. }
  64583. void RelativeCoordinatePositionerBase::markersChanged (MarkerList*)
  64584. {
  64585. apply();
  64586. }
  64587. void RelativeCoordinatePositionerBase::markerListBeingDeleted (MarkerList* markerList)
  64588. {
  64589. jassert (sourceMarkerLists.contains (markerList));
  64590. sourceMarkerLists.removeValue (markerList);
  64591. }
  64592. void RelativeCoordinatePositionerBase::apply()
  64593. {
  64594. if (! registeredOk)
  64595. {
  64596. unregisterListeners();
  64597. registeredOk = registerCoordinates();
  64598. }
  64599. applyToComponentBounds();
  64600. }
  64601. bool RelativeCoordinatePositionerBase::addCoordinate (const RelativeCoordinate& coord)
  64602. {
  64603. bool ok = true;
  64604. DependencyFinderScope finderScope (getComponent(), *this, ok);
  64605. coord.getExpression().evaluate (finderScope);
  64606. return ok;
  64607. }
  64608. bool RelativeCoordinatePositionerBase::addPoint (const RelativePoint& point)
  64609. {
  64610. const bool ok = addCoordinate (point.x);
  64611. return addCoordinate (point.y) && ok;
  64612. }
  64613. void RelativeCoordinatePositionerBase::registerComponentListener (Component& comp)
  64614. {
  64615. if (! sourceComponents.contains (&comp))
  64616. {
  64617. comp.addComponentListener (this);
  64618. sourceComponents.add (&comp);
  64619. }
  64620. }
  64621. void RelativeCoordinatePositionerBase::registerMarkerListListener (MarkerList* const list)
  64622. {
  64623. if (list != 0 && ! sourceMarkerLists.contains (list))
  64624. {
  64625. list->addListener (this);
  64626. sourceMarkerLists.add (list);
  64627. }
  64628. }
  64629. void RelativeCoordinatePositionerBase::unregisterListeners()
  64630. {
  64631. int i;
  64632. for (i = sourceComponents.size(); --i >= 0;)
  64633. sourceComponents.getUnchecked(i)->removeComponentListener (this);
  64634. for (i = sourceMarkerLists.size(); --i >= 0;)
  64635. sourceMarkerLists.getUnchecked(i)->removeListener (this);
  64636. sourceComponents.clear();
  64637. sourceMarkerLists.clear();
  64638. }
  64639. END_JUCE_NAMESPACE
  64640. /*** End of inlined file: juce_RelativeCoordinatePositioner.cpp ***/
  64641. #endif
  64642. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64643. /*** Start of inlined file: juce_Colour.cpp ***/
  64644. BEGIN_JUCE_NAMESPACE
  64645. namespace ColourHelpers
  64646. {
  64647. uint8 floatAlphaToInt (const float alpha) throw()
  64648. {
  64649. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64650. }
  64651. void convertHSBtoRGB (float h, float s, float v,
  64652. uint8& r, uint8& g, uint8& b) throw()
  64653. {
  64654. v = jlimit (0.0f, 1.0f, v);
  64655. v *= 255.0f;
  64656. const uint8 intV = (uint8) roundToInt (v);
  64657. if (s <= 0)
  64658. {
  64659. r = intV;
  64660. g = intV;
  64661. b = intV;
  64662. }
  64663. else
  64664. {
  64665. s = jmin (1.0f, s);
  64666. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64667. const float f = h - std::floor (h);
  64668. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64669. if (h < 1.0f)
  64670. {
  64671. r = intV;
  64672. g = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64673. b = x;
  64674. }
  64675. else if (h < 2.0f)
  64676. {
  64677. r = (uint8) roundToInt (v * (1.0f - s * f));
  64678. g = intV;
  64679. b = x;
  64680. }
  64681. else if (h < 3.0f)
  64682. {
  64683. r = x;
  64684. g = intV;
  64685. b = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64686. }
  64687. else if (h < 4.0f)
  64688. {
  64689. r = x;
  64690. g = (uint8) roundToInt (v * (1.0f - s * f));
  64691. b = intV;
  64692. }
  64693. else if (h < 5.0f)
  64694. {
  64695. r = (uint8) roundToInt (v * (1.0f - (s * (1.0f - f))));
  64696. g = x;
  64697. b = intV;
  64698. }
  64699. else
  64700. {
  64701. r = intV;
  64702. g = x;
  64703. b = (uint8) roundToInt (v * (1.0f - s * f));
  64704. }
  64705. }
  64706. }
  64707. }
  64708. Colour::Colour() throw()
  64709. : argb (0)
  64710. {
  64711. }
  64712. Colour::Colour (const Colour& other) throw()
  64713. : argb (other.argb)
  64714. {
  64715. }
  64716. Colour& Colour::operator= (const Colour& other) throw()
  64717. {
  64718. argb = other.argb;
  64719. return *this;
  64720. }
  64721. bool Colour::operator== (const Colour& other) const throw()
  64722. {
  64723. return argb.getARGB() == other.argb.getARGB();
  64724. }
  64725. bool Colour::operator!= (const Colour& other) const throw()
  64726. {
  64727. return argb.getARGB() != other.argb.getARGB();
  64728. }
  64729. Colour::Colour (const uint32 argb_) throw()
  64730. : argb (argb_)
  64731. {
  64732. }
  64733. Colour::Colour (const uint8 red,
  64734. const uint8 green,
  64735. const uint8 blue) throw()
  64736. {
  64737. argb.setARGB (0xff, red, green, blue);
  64738. }
  64739. const Colour Colour::fromRGB (const uint8 red,
  64740. const uint8 green,
  64741. const uint8 blue) throw()
  64742. {
  64743. return Colour (red, green, blue);
  64744. }
  64745. Colour::Colour (const uint8 red,
  64746. const uint8 green,
  64747. const uint8 blue,
  64748. const uint8 alpha) throw()
  64749. {
  64750. argb.setARGB (alpha, red, green, blue);
  64751. }
  64752. const Colour Colour::fromRGBA (const uint8 red,
  64753. const uint8 green,
  64754. const uint8 blue,
  64755. const uint8 alpha) throw()
  64756. {
  64757. return Colour (red, green, blue, alpha);
  64758. }
  64759. Colour::Colour (const uint8 red,
  64760. const uint8 green,
  64761. const uint8 blue,
  64762. const float alpha) throw()
  64763. {
  64764. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  64765. }
  64766. const Colour Colour::fromRGBAFloat (const uint8 red,
  64767. const uint8 green,
  64768. const uint8 blue,
  64769. const float alpha) throw()
  64770. {
  64771. return Colour (red, green, blue, alpha);
  64772. }
  64773. Colour::Colour (const float hue,
  64774. const float saturation,
  64775. const float brightness,
  64776. const float alpha) throw()
  64777. {
  64778. uint8 r, g, b;
  64779. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64780. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  64781. }
  64782. const Colour Colour::fromHSV (const float hue,
  64783. const float saturation,
  64784. const float brightness,
  64785. const float alpha) throw()
  64786. {
  64787. return Colour (hue, saturation, brightness, alpha);
  64788. }
  64789. Colour::Colour (const float hue,
  64790. const float saturation,
  64791. const float brightness,
  64792. const uint8 alpha) throw()
  64793. {
  64794. uint8 r, g, b;
  64795. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  64796. argb.setARGB (alpha, r, g, b);
  64797. }
  64798. Colour::~Colour() throw()
  64799. {
  64800. }
  64801. const PixelARGB Colour::getPixelARGB() const throw()
  64802. {
  64803. PixelARGB p (argb);
  64804. p.premultiply();
  64805. return p;
  64806. }
  64807. uint32 Colour::getARGB() const throw()
  64808. {
  64809. return argb.getARGB();
  64810. }
  64811. bool Colour::isTransparent() const throw()
  64812. {
  64813. return getAlpha() == 0;
  64814. }
  64815. bool Colour::isOpaque() const throw()
  64816. {
  64817. return getAlpha() == 0xff;
  64818. }
  64819. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  64820. {
  64821. PixelARGB newCol (argb);
  64822. newCol.setAlpha (newAlpha);
  64823. return Colour (newCol.getARGB());
  64824. }
  64825. const Colour Colour::withAlpha (const float newAlpha) const throw()
  64826. {
  64827. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  64828. PixelARGB newCol (argb);
  64829. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  64830. return Colour (newCol.getARGB());
  64831. }
  64832. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  64833. {
  64834. jassert (alphaMultiplier >= 0);
  64835. PixelARGB newCol (argb);
  64836. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  64837. return Colour (newCol.getARGB());
  64838. }
  64839. const Colour Colour::overlaidWith (const Colour& src) const throw()
  64840. {
  64841. const int destAlpha = getAlpha();
  64842. if (destAlpha > 0)
  64843. {
  64844. const int invA = 0xff - (int) src.getAlpha();
  64845. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  64846. if (resA > 0)
  64847. {
  64848. const int da = (invA * destAlpha) / resA;
  64849. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  64850. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  64851. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  64852. (uint8) resA);
  64853. }
  64854. return *this;
  64855. }
  64856. else
  64857. {
  64858. return src;
  64859. }
  64860. }
  64861. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  64862. {
  64863. if (proportionOfOther <= 0)
  64864. return *this;
  64865. if (proportionOfOther >= 1.0f)
  64866. return other;
  64867. PixelARGB c1 (getPixelARGB());
  64868. const PixelARGB c2 (other.getPixelARGB());
  64869. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  64870. c1.unpremultiply();
  64871. return Colour (c1.getARGB());
  64872. }
  64873. float Colour::getFloatRed() const throw()
  64874. {
  64875. return getRed() / 255.0f;
  64876. }
  64877. float Colour::getFloatGreen() const throw()
  64878. {
  64879. return getGreen() / 255.0f;
  64880. }
  64881. float Colour::getFloatBlue() const throw()
  64882. {
  64883. return getBlue() / 255.0f;
  64884. }
  64885. float Colour::getFloatAlpha() const throw()
  64886. {
  64887. return getAlpha() / 255.0f;
  64888. }
  64889. void Colour::getHSB (float& h, float& s, float& v) const throw()
  64890. {
  64891. const int r = getRed();
  64892. const int g = getGreen();
  64893. const int b = getBlue();
  64894. const int hi = jmax (r, g, b);
  64895. const int lo = jmin (r, g, b);
  64896. if (hi != 0)
  64897. {
  64898. s = (hi - lo) / (float) hi;
  64899. if (s != 0)
  64900. {
  64901. const float invDiff = 1.0f / (hi - lo);
  64902. const float red = (hi - r) * invDiff;
  64903. const float green = (hi - g) * invDiff;
  64904. const float blue = (hi - b) * invDiff;
  64905. if (r == hi)
  64906. h = blue - green;
  64907. else if (g == hi)
  64908. h = 2.0f + red - blue;
  64909. else
  64910. h = 4.0f + green - red;
  64911. h *= 1.0f / 6.0f;
  64912. if (h < 0)
  64913. ++h;
  64914. }
  64915. else
  64916. {
  64917. h = 0;
  64918. }
  64919. }
  64920. else
  64921. {
  64922. s = 0;
  64923. h = 0;
  64924. }
  64925. v = hi / 255.0f;
  64926. }
  64927. float Colour::getHue() const throw()
  64928. {
  64929. float h, s, b;
  64930. getHSB (h, s, b);
  64931. return h;
  64932. }
  64933. const Colour Colour::withHue (const float hue) const throw()
  64934. {
  64935. float h, s, b;
  64936. getHSB (h, s, b);
  64937. return Colour (hue, s, b, getAlpha());
  64938. }
  64939. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  64940. {
  64941. float h, s, b;
  64942. getHSB (h, s, b);
  64943. return Colour (h + amountToRotate, s, b, getAlpha());
  64944. }
  64945. float Colour::getSaturation() const throw()
  64946. {
  64947. float h, s, b;
  64948. getHSB (h, s, b);
  64949. return s;
  64950. }
  64951. const Colour Colour::withSaturation (const float saturation) const throw()
  64952. {
  64953. float h, s, b;
  64954. getHSB (h, s, b);
  64955. return Colour (h, saturation, b, getAlpha());
  64956. }
  64957. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  64958. {
  64959. float h, s, b;
  64960. getHSB (h, s, b);
  64961. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  64962. }
  64963. float Colour::getBrightness() const throw()
  64964. {
  64965. float h, s, b;
  64966. getHSB (h, s, b);
  64967. return b;
  64968. }
  64969. const Colour Colour::withBrightness (const float brightness) const throw()
  64970. {
  64971. float h, s, b;
  64972. getHSB (h, s, b);
  64973. return Colour (h, s, brightness, getAlpha());
  64974. }
  64975. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  64976. {
  64977. float h, s, b;
  64978. getHSB (h, s, b);
  64979. b *= amount;
  64980. if (b > 1.0f)
  64981. b = 1.0f;
  64982. return Colour (h, s, b, getAlpha());
  64983. }
  64984. const Colour Colour::brighter (float amount) const throw()
  64985. {
  64986. amount = 1.0f / (1.0f + amount);
  64987. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  64988. (uint8) (255 - (amount * (255 - getGreen()))),
  64989. (uint8) (255 - (amount * (255 - getBlue()))),
  64990. getAlpha());
  64991. }
  64992. const Colour Colour::darker (float amount) const throw()
  64993. {
  64994. amount = 1.0f / (1.0f + amount);
  64995. return Colour ((uint8) (amount * getRed()),
  64996. (uint8) (amount * getGreen()),
  64997. (uint8) (amount * getBlue()),
  64998. getAlpha());
  64999. }
  65000. const Colour Colour::greyLevel (const float brightness) throw()
  65001. {
  65002. const uint8 level
  65003. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65004. return Colour (level, level, level);
  65005. }
  65006. const Colour Colour::contrasting (const float amount) const throw()
  65007. {
  65008. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65009. ? Colours::black
  65010. : Colours::white).withAlpha (amount));
  65011. }
  65012. const Colour Colour::contrasting (const Colour& colour1,
  65013. const Colour& colour2) throw()
  65014. {
  65015. const float b1 = colour1.getBrightness();
  65016. const float b2 = colour2.getBrightness();
  65017. float best = 0.0f;
  65018. float bestDist = 0.0f;
  65019. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65020. {
  65021. const float d1 = std::abs (i - b1);
  65022. const float d2 = std::abs (i - b2);
  65023. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65024. if (dist > bestDist)
  65025. {
  65026. best = i;
  65027. bestDist = dist;
  65028. }
  65029. }
  65030. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65031. .withBrightness (best);
  65032. }
  65033. const String Colour::toString() const
  65034. {
  65035. return String::toHexString ((int) argb.getARGB());
  65036. }
  65037. const Colour Colour::fromString (const String& encodedColourString)
  65038. {
  65039. return Colour ((uint32) encodedColourString.getHexValue32());
  65040. }
  65041. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65042. {
  65043. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65044. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65045. .toUpperCase();
  65046. }
  65047. END_JUCE_NAMESPACE
  65048. /*** End of inlined file: juce_Colour.cpp ***/
  65049. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65050. BEGIN_JUCE_NAMESPACE
  65051. ColourGradient::ColourGradient() throw()
  65052. {
  65053. #if JUCE_DEBUG
  65054. point1.setX (987654.0f);
  65055. #endif
  65056. }
  65057. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65058. const Colour& colour2, const float x2_, const float y2_,
  65059. const bool isRadial_)
  65060. : point1 (x1_, y1_),
  65061. point2 (x2_, y2_),
  65062. isRadial (isRadial_)
  65063. {
  65064. colours.add (ColourPoint (0.0, colour1));
  65065. colours.add (ColourPoint (1.0, colour2));
  65066. }
  65067. ColourGradient::~ColourGradient()
  65068. {
  65069. }
  65070. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65071. {
  65072. return point1 == other.point1 && point2 == other.point2
  65073. && isRadial == other.isRadial
  65074. && colours == other.colours;
  65075. }
  65076. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65077. {
  65078. return ! operator== (other);
  65079. }
  65080. void ColourGradient::clearColours()
  65081. {
  65082. colours.clear();
  65083. }
  65084. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65085. {
  65086. // must be within the two end-points
  65087. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65088. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65089. int i;
  65090. for (i = 0; i < colours.size(); ++i)
  65091. if (colours.getReference(i).position > pos)
  65092. break;
  65093. colours.insert (i, ColourPoint (pos, colour));
  65094. return i;
  65095. }
  65096. void ColourGradient::removeColour (int index)
  65097. {
  65098. jassert (index > 0 && index < colours.size() - 1);
  65099. colours.remove (index);
  65100. }
  65101. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65102. {
  65103. for (int i = 0; i < colours.size(); ++i)
  65104. {
  65105. Colour& c = colours.getReference(i).colour;
  65106. c = c.withMultipliedAlpha (multiplier);
  65107. }
  65108. }
  65109. int ColourGradient::getNumColours() const throw()
  65110. {
  65111. return colours.size();
  65112. }
  65113. double ColourGradient::getColourPosition (const int index) const throw()
  65114. {
  65115. if (isPositiveAndBelow (index, colours.size()))
  65116. return colours.getReference (index).position;
  65117. return 0;
  65118. }
  65119. const Colour ColourGradient::getColour (const int index) const throw()
  65120. {
  65121. if (isPositiveAndBelow (index, colours.size()))
  65122. return colours.getReference (index).colour;
  65123. return Colour();
  65124. }
  65125. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65126. {
  65127. if (isPositiveAndBelow (index, colours.size()))
  65128. colours.getReference (index).colour = newColour;
  65129. }
  65130. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65131. {
  65132. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65133. if (position <= 0 || colours.size() <= 1)
  65134. return colours.getReference(0).colour;
  65135. int i = colours.size() - 1;
  65136. while (position < colours.getReference(i).position)
  65137. --i;
  65138. const ColourPoint& p1 = colours.getReference (i);
  65139. if (i >= colours.size() - 1)
  65140. return p1.colour;
  65141. const ColourPoint& p2 = colours.getReference (i + 1);
  65142. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65143. }
  65144. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65145. {
  65146. #if JUCE_DEBUG
  65147. // trying to use the object without setting its co-ordinates? Have a careful read of
  65148. // the comments for the constructors.
  65149. jassert (point1.getX() != 987654.0f);
  65150. #endif
  65151. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65152. 3 * (int) point1.transformedBy (transform)
  65153. .getDistanceFrom (point2.transformedBy (transform)));
  65154. lookupTable.malloc (numEntries);
  65155. if (colours.size() >= 2)
  65156. {
  65157. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65158. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65159. int index = 0;
  65160. for (int j = 1; j < colours.size(); ++j)
  65161. {
  65162. const ColourPoint& p = colours.getReference (j);
  65163. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65164. const PixelARGB pix2 (p.colour.getPixelARGB());
  65165. for (int i = 0; i < numToDo; ++i)
  65166. {
  65167. jassert (index >= 0 && index < numEntries);
  65168. lookupTable[index] = pix1;
  65169. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65170. ++index;
  65171. }
  65172. pix1 = pix2;
  65173. }
  65174. while (index < numEntries)
  65175. lookupTable [index++] = pix1;
  65176. }
  65177. else
  65178. {
  65179. jassertfalse; // no colours specified!
  65180. }
  65181. return numEntries;
  65182. }
  65183. bool ColourGradient::isOpaque() const throw()
  65184. {
  65185. for (int i = 0; i < colours.size(); ++i)
  65186. if (! colours.getReference(i).colour.isOpaque())
  65187. return false;
  65188. return true;
  65189. }
  65190. bool ColourGradient::isInvisible() const throw()
  65191. {
  65192. for (int i = 0; i < colours.size(); ++i)
  65193. if (! colours.getReference(i).colour.isTransparent())
  65194. return false;
  65195. return true;
  65196. }
  65197. END_JUCE_NAMESPACE
  65198. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65199. /*** Start of inlined file: juce_Colours.cpp ***/
  65200. BEGIN_JUCE_NAMESPACE
  65201. const Colour Colours::transparentBlack (0);
  65202. const Colour Colours::transparentWhite (0x00ffffff);
  65203. const Colour Colours::aliceblue (0xfff0f8ff);
  65204. const Colour Colours::antiquewhite (0xfffaebd7);
  65205. const Colour Colours::aqua (0xff00ffff);
  65206. const Colour Colours::aquamarine (0xff7fffd4);
  65207. const Colour Colours::azure (0xfff0ffff);
  65208. const Colour Colours::beige (0xfff5f5dc);
  65209. const Colour Colours::bisque (0xffffe4c4);
  65210. const Colour Colours::black (0xff000000);
  65211. const Colour Colours::blanchedalmond (0xffffebcd);
  65212. const Colour Colours::blue (0xff0000ff);
  65213. const Colour Colours::blueviolet (0xff8a2be2);
  65214. const Colour Colours::brown (0xffa52a2a);
  65215. const Colour Colours::burlywood (0xffdeb887);
  65216. const Colour Colours::cadetblue (0xff5f9ea0);
  65217. const Colour Colours::chartreuse (0xff7fff00);
  65218. const Colour Colours::chocolate (0xffd2691e);
  65219. const Colour Colours::coral (0xffff7f50);
  65220. const Colour Colours::cornflowerblue (0xff6495ed);
  65221. const Colour Colours::cornsilk (0xfffff8dc);
  65222. const Colour Colours::crimson (0xffdc143c);
  65223. const Colour Colours::cyan (0xff00ffff);
  65224. const Colour Colours::darkblue (0xff00008b);
  65225. const Colour Colours::darkcyan (0xff008b8b);
  65226. const Colour Colours::darkgoldenrod (0xffb8860b);
  65227. const Colour Colours::darkgrey (0xff555555);
  65228. const Colour Colours::darkgreen (0xff006400);
  65229. const Colour Colours::darkkhaki (0xffbdb76b);
  65230. const Colour Colours::darkmagenta (0xff8b008b);
  65231. const Colour Colours::darkolivegreen (0xff556b2f);
  65232. const Colour Colours::darkorange (0xffff8c00);
  65233. const Colour Colours::darkorchid (0xff9932cc);
  65234. const Colour Colours::darkred (0xff8b0000);
  65235. const Colour Colours::darksalmon (0xffe9967a);
  65236. const Colour Colours::darkseagreen (0xff8fbc8f);
  65237. const Colour Colours::darkslateblue (0xff483d8b);
  65238. const Colour Colours::darkslategrey (0xff2f4f4f);
  65239. const Colour Colours::darkturquoise (0xff00ced1);
  65240. const Colour Colours::darkviolet (0xff9400d3);
  65241. const Colour Colours::deeppink (0xffff1493);
  65242. const Colour Colours::deepskyblue (0xff00bfff);
  65243. const Colour Colours::dimgrey (0xff696969);
  65244. const Colour Colours::dodgerblue (0xff1e90ff);
  65245. const Colour Colours::firebrick (0xffb22222);
  65246. const Colour Colours::floralwhite (0xfffffaf0);
  65247. const Colour Colours::forestgreen (0xff228b22);
  65248. const Colour Colours::fuchsia (0xffff00ff);
  65249. const Colour Colours::gainsboro (0xffdcdcdc);
  65250. const Colour Colours::gold (0xffffd700);
  65251. const Colour Colours::goldenrod (0xffdaa520);
  65252. const Colour Colours::grey (0xff808080);
  65253. const Colour Colours::green (0xff008000);
  65254. const Colour Colours::greenyellow (0xffadff2f);
  65255. const Colour Colours::honeydew (0xfff0fff0);
  65256. const Colour Colours::hotpink (0xffff69b4);
  65257. const Colour Colours::indianred (0xffcd5c5c);
  65258. const Colour Colours::indigo (0xff4b0082);
  65259. const Colour Colours::ivory (0xfffffff0);
  65260. const Colour Colours::khaki (0xfff0e68c);
  65261. const Colour Colours::lavender (0xffe6e6fa);
  65262. const Colour Colours::lavenderblush (0xfffff0f5);
  65263. const Colour Colours::lemonchiffon (0xfffffacd);
  65264. const Colour Colours::lightblue (0xffadd8e6);
  65265. const Colour Colours::lightcoral (0xfff08080);
  65266. const Colour Colours::lightcyan (0xffe0ffff);
  65267. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65268. const Colour Colours::lightgreen (0xff90ee90);
  65269. const Colour Colours::lightgrey (0xffd3d3d3);
  65270. const Colour Colours::lightpink (0xffffb6c1);
  65271. const Colour Colours::lightsalmon (0xffffa07a);
  65272. const Colour Colours::lightseagreen (0xff20b2aa);
  65273. const Colour Colours::lightskyblue (0xff87cefa);
  65274. const Colour Colours::lightslategrey (0xff778899);
  65275. const Colour Colours::lightsteelblue (0xffb0c4de);
  65276. const Colour Colours::lightyellow (0xffffffe0);
  65277. const Colour Colours::lime (0xff00ff00);
  65278. const Colour Colours::limegreen (0xff32cd32);
  65279. const Colour Colours::linen (0xfffaf0e6);
  65280. const Colour Colours::magenta (0xffff00ff);
  65281. const Colour Colours::maroon (0xff800000);
  65282. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65283. const Colour Colours::mediumblue (0xff0000cd);
  65284. const Colour Colours::mediumorchid (0xffba55d3);
  65285. const Colour Colours::mediumpurple (0xff9370db);
  65286. const Colour Colours::mediumseagreen (0xff3cb371);
  65287. const Colour Colours::mediumslateblue (0xff7b68ee);
  65288. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65289. const Colour Colours::mediumturquoise (0xff48d1cc);
  65290. const Colour Colours::mediumvioletred (0xffc71585);
  65291. const Colour Colours::midnightblue (0xff191970);
  65292. const Colour Colours::mintcream (0xfff5fffa);
  65293. const Colour Colours::mistyrose (0xffffe4e1);
  65294. const Colour Colours::navajowhite (0xffffdead);
  65295. const Colour Colours::navy (0xff000080);
  65296. const Colour Colours::oldlace (0xfffdf5e6);
  65297. const Colour Colours::olive (0xff808000);
  65298. const Colour Colours::olivedrab (0xff6b8e23);
  65299. const Colour Colours::orange (0xffffa500);
  65300. const Colour Colours::orangered (0xffff4500);
  65301. const Colour Colours::orchid (0xffda70d6);
  65302. const Colour Colours::palegoldenrod (0xffeee8aa);
  65303. const Colour Colours::palegreen (0xff98fb98);
  65304. const Colour Colours::paleturquoise (0xffafeeee);
  65305. const Colour Colours::palevioletred (0xffdb7093);
  65306. const Colour Colours::papayawhip (0xffffefd5);
  65307. const Colour Colours::peachpuff (0xffffdab9);
  65308. const Colour Colours::peru (0xffcd853f);
  65309. const Colour Colours::pink (0xffffc0cb);
  65310. const Colour Colours::plum (0xffdda0dd);
  65311. const Colour Colours::powderblue (0xffb0e0e6);
  65312. const Colour Colours::purple (0xff800080);
  65313. const Colour Colours::red (0xffff0000);
  65314. const Colour Colours::rosybrown (0xffbc8f8f);
  65315. const Colour Colours::royalblue (0xff4169e1);
  65316. const Colour Colours::saddlebrown (0xff8b4513);
  65317. const Colour Colours::salmon (0xfffa8072);
  65318. const Colour Colours::sandybrown (0xfff4a460);
  65319. const Colour Colours::seagreen (0xff2e8b57);
  65320. const Colour Colours::seashell (0xfffff5ee);
  65321. const Colour Colours::sienna (0xffa0522d);
  65322. const Colour Colours::silver (0xffc0c0c0);
  65323. const Colour Colours::skyblue (0xff87ceeb);
  65324. const Colour Colours::slateblue (0xff6a5acd);
  65325. const Colour Colours::slategrey (0xff708090);
  65326. const Colour Colours::snow (0xfffffafa);
  65327. const Colour Colours::springgreen (0xff00ff7f);
  65328. const Colour Colours::steelblue (0xff4682b4);
  65329. const Colour Colours::tan (0xffd2b48c);
  65330. const Colour Colours::teal (0xff008080);
  65331. const Colour Colours::thistle (0xffd8bfd8);
  65332. const Colour Colours::tomato (0xffff6347);
  65333. const Colour Colours::turquoise (0xff40e0d0);
  65334. const Colour Colours::violet (0xffee82ee);
  65335. const Colour Colours::wheat (0xfff5deb3);
  65336. const Colour Colours::white (0xffffffff);
  65337. const Colour Colours::whitesmoke (0xfff5f5f5);
  65338. const Colour Colours::yellow (0xffffff00);
  65339. const Colour Colours::yellowgreen (0xff9acd32);
  65340. const Colour Colours::findColourForName (const String& colourName,
  65341. const Colour& defaultColour)
  65342. {
  65343. static const int presets[] =
  65344. {
  65345. // (first value is the string's hashcode, second is ARGB)
  65346. 0x05978fff, 0xff000000, /* black */
  65347. 0x06bdcc29, 0xffffffff, /* white */
  65348. 0x002e305a, 0xff0000ff, /* blue */
  65349. 0x00308adf, 0xff808080, /* grey */
  65350. 0x05e0cf03, 0xff008000, /* green */
  65351. 0x0001b891, 0xffff0000, /* red */
  65352. 0xd43c6474, 0xffffff00, /* yellow */
  65353. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65354. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65355. 0x002dcebc, 0xff00ffff, /* aqua */
  65356. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65357. 0x0590228f, 0xfff0ffff, /* azure */
  65358. 0x05947fe4, 0xfff5f5dc, /* beige */
  65359. 0xad388e35, 0xffffe4c4, /* bisque */
  65360. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65361. 0x39129959, 0xff8a2be2, /* blueviolet */
  65362. 0x059a8136, 0xffa52a2a, /* brown */
  65363. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65364. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65365. 0x6b748956, 0xff7fff00, /* chartreuse */
  65366. 0x2903623c, 0xffd2691e, /* chocolate */
  65367. 0x05a74431, 0xffff7f50, /* coral */
  65368. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65369. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65370. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65371. 0x002ed323, 0xff00ffff, /* cyan */
  65372. 0x67cc74d0, 0xff00008b, /* darkblue */
  65373. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65374. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65375. 0x67cecf55, 0xff555555, /* darkgrey */
  65376. 0x920b194d, 0xff006400, /* darkgreen */
  65377. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65378. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65379. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65380. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65381. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65382. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65383. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65384. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65385. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65386. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65387. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65388. 0xc8769375, 0xff9400d3, /* darkviolet */
  65389. 0x25832862, 0xffff1493, /* deeppink */
  65390. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65391. 0x634c8b67, 0xff696969, /* dimgrey */
  65392. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65393. 0xef19e3cb, 0xffb22222, /* firebrick */
  65394. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65395. 0xd086fd06, 0xff228b22, /* forestgreen */
  65396. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65397. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65398. 0x00308060, 0xffffd700, /* gold */
  65399. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65400. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65401. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65402. 0x41892743, 0xffff69b4, /* hotpink */
  65403. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65404. 0xb969fed2, 0xff4b0082, /* indigo */
  65405. 0x05fef6a9, 0xfffffff0, /* ivory */
  65406. 0x06149302, 0xfff0e68c, /* khaki */
  65407. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65408. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65409. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65410. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65411. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65412. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65413. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65414. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65415. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65416. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65417. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65418. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65419. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65420. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65421. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65422. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65423. 0x0032afd5, 0xff00ff00, /* lime */
  65424. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65425. 0x06234efa, 0xfffaf0e6, /* linen */
  65426. 0x316858a9, 0xffff00ff, /* magenta */
  65427. 0xbf8ca470, 0xff800000, /* maroon */
  65428. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65429. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65430. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65431. 0x07556b71, 0xff9370db, /* mediumpurple */
  65432. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65433. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65434. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65435. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65436. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65437. 0x168eb32a, 0xff191970, /* midnightblue */
  65438. 0x4306b960, 0xfff5fffa, /* mintcream */
  65439. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65440. 0xe97218a6, 0xffffdead, /* navajowhite */
  65441. 0x00337bb6, 0xff000080, /* navy */
  65442. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65443. 0x064ee1db, 0xff808000, /* olive */
  65444. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65445. 0xc3de262e, 0xffffa500, /* orange */
  65446. 0x58bebba3, 0xffff4500, /* orangered */
  65447. 0xc3def8a3, 0xffda70d6, /* orchid */
  65448. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65449. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65450. 0x74022737, 0xffafeeee, /* paleturquoise */
  65451. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65452. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65453. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65454. 0x003472f8, 0xffcd853f, /* peru */
  65455. 0x00348176, 0xffffc0cb, /* pink */
  65456. 0x00348d94, 0xffdda0dd, /* plum */
  65457. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65458. 0xc5c507bc, 0xff800080, /* purple */
  65459. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65460. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65461. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65462. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65463. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65464. 0x34636c14, 0xff2e8b57, /* seagreen */
  65465. 0x3507fb41, 0xfffff5ee, /* seashell */
  65466. 0xca348772, 0xffa0522d, /* sienna */
  65467. 0xca37d30d, 0xffc0c0c0, /* silver */
  65468. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65469. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65470. 0x44ab37f8, 0xff708090, /* slategrey */
  65471. 0x0035f183, 0xfffffafa, /* snow */
  65472. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65473. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65474. 0x0001bfa1, 0xffd2b48c, /* tan */
  65475. 0x0036425c, 0xff008080, /* teal */
  65476. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65477. 0xcc41600a, 0xffff6347, /* tomato */
  65478. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65479. 0xcf57947f, 0xffee82ee, /* violet */
  65480. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65481. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65482. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65483. };
  65484. const int hash = colourName.trim().toLowerCase().hashCode();
  65485. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65486. if (presets [i] == hash)
  65487. return Colour (presets [i + 1]);
  65488. return defaultColour;
  65489. }
  65490. END_JUCE_NAMESPACE
  65491. /*** End of inlined file: juce_Colours.cpp ***/
  65492. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65493. BEGIN_JUCE_NAMESPACE
  65494. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65495. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65496. const Path& path, const AffineTransform& transform)
  65497. : bounds (bounds_),
  65498. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65499. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65500. needToCheckEmptinesss (true)
  65501. {
  65502. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65503. int* t = table;
  65504. for (int i = bounds.getHeight(); --i >= 0;)
  65505. {
  65506. *t = 0;
  65507. t += lineStrideElements;
  65508. }
  65509. const int topLimit = bounds.getY() << 8;
  65510. const int heightLimit = bounds.getHeight() << 8;
  65511. const int leftLimit = bounds.getX() << 8;
  65512. const int rightLimit = bounds.getRight() << 8;
  65513. PathFlatteningIterator iter (path, transform);
  65514. while (iter.next())
  65515. {
  65516. int y1 = roundToInt (iter.y1 * 256.0f);
  65517. int y2 = roundToInt (iter.y2 * 256.0f);
  65518. if (y1 != y2)
  65519. {
  65520. y1 -= topLimit;
  65521. y2 -= topLimit;
  65522. const int startY = y1;
  65523. int direction = -1;
  65524. if (y1 > y2)
  65525. {
  65526. swapVariables (y1, y2);
  65527. direction = 1;
  65528. }
  65529. if (y1 < 0)
  65530. y1 = 0;
  65531. if (y2 > heightLimit)
  65532. y2 = heightLimit;
  65533. if (y1 < y2)
  65534. {
  65535. const double startX = 256.0f * iter.x1;
  65536. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65537. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65538. do
  65539. {
  65540. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65541. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65542. if (x < leftLimit)
  65543. x = leftLimit;
  65544. else if (x >= rightLimit)
  65545. x = rightLimit - 1;
  65546. addEdgePoint (x, y1 >> 8, direction * step);
  65547. y1 += step;
  65548. }
  65549. while (y1 < y2);
  65550. }
  65551. }
  65552. }
  65553. sanitiseLevels (path.isUsingNonZeroWinding());
  65554. }
  65555. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65556. : bounds (rectangleToAdd),
  65557. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65558. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65559. needToCheckEmptinesss (true)
  65560. {
  65561. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65562. table[0] = 0;
  65563. const int x1 = rectangleToAdd.getX() << 8;
  65564. const int x2 = rectangleToAdd.getRight() << 8;
  65565. int* t = table;
  65566. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65567. {
  65568. t[0] = 2;
  65569. t[1] = x1;
  65570. t[2] = 255;
  65571. t[3] = x2;
  65572. t[4] = 0;
  65573. t += lineStrideElements;
  65574. }
  65575. }
  65576. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65577. : bounds (rectanglesToAdd.getBounds()),
  65578. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65579. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65580. needToCheckEmptinesss (true)
  65581. {
  65582. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65583. int* t = table;
  65584. for (int i = bounds.getHeight(); --i >= 0;)
  65585. {
  65586. *t = 0;
  65587. t += lineStrideElements;
  65588. }
  65589. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65590. {
  65591. const Rectangle<int>* const r = iter.getRectangle();
  65592. const int x1 = r->getX() << 8;
  65593. const int x2 = r->getRight() << 8;
  65594. int y = r->getY() - bounds.getY();
  65595. for (int j = r->getHeight(); --j >= 0;)
  65596. {
  65597. addEdgePoint (x1, y, 255);
  65598. addEdgePoint (x2, y, -255);
  65599. ++y;
  65600. }
  65601. }
  65602. sanitiseLevels (true);
  65603. }
  65604. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65605. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65606. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65607. 2 + (int) rectangleToAdd.getWidth(),
  65608. 2 + (int) rectangleToAdd.getHeight())),
  65609. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65610. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65611. needToCheckEmptinesss (true)
  65612. {
  65613. jassert (! rectangleToAdd.isEmpty());
  65614. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65615. table[0] = 0;
  65616. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65617. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65618. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65619. jassert (y1 < 256);
  65620. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65621. if (x2 <= x1 || y2 <= y1)
  65622. {
  65623. bounds.setHeight (0);
  65624. return;
  65625. }
  65626. int lineY = 0;
  65627. int* t = table;
  65628. if ((y1 >> 8) == (y2 >> 8))
  65629. {
  65630. t[0] = 2;
  65631. t[1] = x1;
  65632. t[2] = y2 - y1;
  65633. t[3] = x2;
  65634. t[4] = 0;
  65635. ++lineY;
  65636. t += lineStrideElements;
  65637. }
  65638. else
  65639. {
  65640. t[0] = 2;
  65641. t[1] = x1;
  65642. t[2] = 255 - (y1 & 255);
  65643. t[3] = x2;
  65644. t[4] = 0;
  65645. ++lineY;
  65646. t += lineStrideElements;
  65647. while (lineY < (y2 >> 8))
  65648. {
  65649. t[0] = 2;
  65650. t[1] = x1;
  65651. t[2] = 255;
  65652. t[3] = x2;
  65653. t[4] = 0;
  65654. ++lineY;
  65655. t += lineStrideElements;
  65656. }
  65657. jassert (lineY < bounds.getHeight());
  65658. t[0] = 2;
  65659. t[1] = x1;
  65660. t[2] = y2 & 255;
  65661. t[3] = x2;
  65662. t[4] = 0;
  65663. ++lineY;
  65664. t += lineStrideElements;
  65665. }
  65666. while (lineY < bounds.getHeight())
  65667. {
  65668. t[0] = 0;
  65669. t += lineStrideElements;
  65670. ++lineY;
  65671. }
  65672. }
  65673. EdgeTable::EdgeTable (const EdgeTable& other)
  65674. {
  65675. operator= (other);
  65676. }
  65677. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65678. {
  65679. bounds = other.bounds;
  65680. maxEdgesPerLine = other.maxEdgesPerLine;
  65681. lineStrideElements = other.lineStrideElements;
  65682. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65683. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65684. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65685. return *this;
  65686. }
  65687. EdgeTable::~EdgeTable()
  65688. {
  65689. }
  65690. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65691. {
  65692. while (--numLines >= 0)
  65693. {
  65694. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65695. src += srcLineStride;
  65696. dest += destLineStride;
  65697. }
  65698. }
  65699. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65700. {
  65701. // Convert the table from relative windings to absolute levels..
  65702. int* lineStart = table;
  65703. for (int i = bounds.getHeight(); --i >= 0;)
  65704. {
  65705. int* line = lineStart;
  65706. lineStart += lineStrideElements;
  65707. int num = *line;
  65708. if (num == 0)
  65709. continue;
  65710. int level = 0;
  65711. if (useNonZeroWinding)
  65712. {
  65713. while (--num > 0)
  65714. {
  65715. line += 2;
  65716. level += *line;
  65717. int corrected = abs (level);
  65718. if (corrected >> 8)
  65719. corrected = 255;
  65720. *line = corrected;
  65721. }
  65722. }
  65723. else
  65724. {
  65725. while (--num > 0)
  65726. {
  65727. line += 2;
  65728. level += *line;
  65729. int corrected = abs (level);
  65730. if (corrected >> 8)
  65731. {
  65732. corrected &= 511;
  65733. if (corrected >> 8)
  65734. corrected = 511 - corrected;
  65735. }
  65736. *line = corrected;
  65737. }
  65738. }
  65739. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65740. }
  65741. }
  65742. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine)
  65743. {
  65744. if (newNumEdgesPerLine != maxEdgesPerLine)
  65745. {
  65746. maxEdgesPerLine = newNumEdgesPerLine;
  65747. jassert (bounds.getHeight() > 0);
  65748. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  65749. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  65750. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  65751. table.swapWith (newTable);
  65752. lineStrideElements = newLineStrideElements;
  65753. }
  65754. }
  65755. void EdgeTable::optimiseTable()
  65756. {
  65757. int maxLineElements = 0;
  65758. for (int i = bounds.getHeight(); --i >= 0;)
  65759. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  65760. remapTableForNumEdges (maxLineElements);
  65761. }
  65762. void EdgeTable::addEdgePoint (const int x, const int y, const int winding)
  65763. {
  65764. jassert (y >= 0 && y < bounds.getHeight());
  65765. int* line = table + lineStrideElements * y;
  65766. const int numPoints = line[0];
  65767. int n = numPoints << 1;
  65768. if (n > 0)
  65769. {
  65770. while (n > 0)
  65771. {
  65772. const int cx = line [n - 1];
  65773. if (cx <= x)
  65774. {
  65775. if (cx == x)
  65776. {
  65777. line [n] += winding;
  65778. return;
  65779. }
  65780. break;
  65781. }
  65782. n -= 2;
  65783. }
  65784. if (numPoints >= maxEdgesPerLine)
  65785. {
  65786. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65787. jassert (numPoints < maxEdgesPerLine);
  65788. line = table + lineStrideElements * y;
  65789. }
  65790. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  65791. }
  65792. line [n + 1] = x;
  65793. line [n + 2] = winding;
  65794. line[0]++;
  65795. }
  65796. void EdgeTable::translate (float dx, const int dy) throw()
  65797. {
  65798. bounds.translate ((int) std::floor (dx), dy);
  65799. int* lineStart = table;
  65800. const int intDx = (int) (dx * 256.0f);
  65801. for (int i = bounds.getHeight(); --i >= 0;)
  65802. {
  65803. int* line = lineStart;
  65804. lineStart += lineStrideElements;
  65805. int num = *line++;
  65806. while (--num >= 0)
  65807. {
  65808. *line += intDx;
  65809. line += 2;
  65810. }
  65811. }
  65812. }
  65813. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine)
  65814. {
  65815. jassert (y >= 0 && y < bounds.getHeight());
  65816. int* dest = table + lineStrideElements * y;
  65817. if (dest[0] == 0)
  65818. return;
  65819. int otherNumPoints = *otherLine;
  65820. if (otherNumPoints == 0)
  65821. {
  65822. *dest = 0;
  65823. return;
  65824. }
  65825. const int right = bounds.getRight() << 8;
  65826. // optimise for the common case where our line lies entirely within a
  65827. // single pair of points, as happens when clipping to a simple rect.
  65828. if (otherNumPoints == 2 && otherLine[2] >= 255)
  65829. {
  65830. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  65831. return;
  65832. }
  65833. ++otherLine;
  65834. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  65835. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  65836. memcpy (temp, dest, lineSizeBytes);
  65837. const int* src1 = temp;
  65838. int srcNum1 = *src1++;
  65839. int x1 = *src1++;
  65840. const int* src2 = otherLine;
  65841. int srcNum2 = otherNumPoints;
  65842. int x2 = *src2++;
  65843. int destIndex = 0, destTotal = 0;
  65844. int level1 = 0, level2 = 0;
  65845. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  65846. while (srcNum1 > 0 && srcNum2 > 0)
  65847. {
  65848. int nextX;
  65849. if (x1 < x2)
  65850. {
  65851. nextX = x1;
  65852. level1 = *src1++;
  65853. x1 = *src1++;
  65854. --srcNum1;
  65855. }
  65856. else if (x1 == x2)
  65857. {
  65858. nextX = x1;
  65859. level1 = *src1++;
  65860. level2 = *src2++;
  65861. x1 = *src1++;
  65862. x2 = *src2++;
  65863. --srcNum1;
  65864. --srcNum2;
  65865. }
  65866. else
  65867. {
  65868. nextX = x2;
  65869. level2 = *src2++;
  65870. x2 = *src2++;
  65871. --srcNum2;
  65872. }
  65873. if (nextX > lastX)
  65874. {
  65875. if (nextX >= right)
  65876. break;
  65877. lastX = nextX;
  65878. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  65879. jassert (isPositiveAndBelow (nextLevel, (int) 256));
  65880. if (nextLevel != lastLevel)
  65881. {
  65882. if (destTotal >= maxEdgesPerLine)
  65883. {
  65884. dest[0] = destTotal;
  65885. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65886. dest = table + lineStrideElements * y;
  65887. }
  65888. ++destTotal;
  65889. lastLevel = nextLevel;
  65890. dest[++destIndex] = nextX;
  65891. dest[++destIndex] = nextLevel;
  65892. }
  65893. }
  65894. }
  65895. if (lastLevel > 0)
  65896. {
  65897. if (destTotal >= maxEdgesPerLine)
  65898. {
  65899. dest[0] = destTotal;
  65900. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  65901. dest = table + lineStrideElements * y;
  65902. }
  65903. ++destTotal;
  65904. dest[++destIndex] = right;
  65905. dest[++destIndex] = 0;
  65906. }
  65907. dest[0] = destTotal;
  65908. #if JUCE_DEBUG
  65909. int last = std::numeric_limits<int>::min();
  65910. for (int i = 0; i < dest[0]; ++i)
  65911. {
  65912. jassert (dest[i * 2 + 1] > last);
  65913. last = dest[i * 2 + 1];
  65914. }
  65915. jassert (dest [dest[0] * 2] == 0);
  65916. #endif
  65917. }
  65918. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  65919. {
  65920. int* lastItem = dest + (dest[0] * 2 - 1);
  65921. if (x2 < lastItem[0])
  65922. {
  65923. if (x2 <= dest[1])
  65924. {
  65925. dest[0] = 0;
  65926. return;
  65927. }
  65928. while (x2 < lastItem[-2])
  65929. {
  65930. --(dest[0]);
  65931. lastItem -= 2;
  65932. }
  65933. lastItem[0] = x2;
  65934. lastItem[1] = 0;
  65935. }
  65936. if (x1 > dest[1])
  65937. {
  65938. while (lastItem[0] > x1)
  65939. lastItem -= 2;
  65940. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  65941. if (itemsRemoved > 0)
  65942. {
  65943. dest[0] -= itemsRemoved;
  65944. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  65945. }
  65946. dest[1] = x1;
  65947. }
  65948. }
  65949. void EdgeTable::clipToRectangle (const Rectangle<int>& r)
  65950. {
  65951. const Rectangle<int> clipped (r.getIntersection (bounds));
  65952. if (clipped.isEmpty())
  65953. {
  65954. needToCheckEmptinesss = false;
  65955. bounds.setHeight (0);
  65956. }
  65957. else
  65958. {
  65959. const int top = clipped.getY() - bounds.getY();
  65960. const int bottom = clipped.getBottom() - bounds.getY();
  65961. if (bottom < bounds.getHeight())
  65962. bounds.setHeight (bottom);
  65963. if (clipped.getRight() < bounds.getRight())
  65964. bounds.setRight (clipped.getRight());
  65965. for (int i = top; --i >= 0;)
  65966. table [lineStrideElements * i] = 0;
  65967. if (clipped.getX() > bounds.getX())
  65968. {
  65969. const int x1 = clipped.getX() << 8;
  65970. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  65971. int* line = table + lineStrideElements * top;
  65972. for (int i = bottom - top; --i >= 0;)
  65973. {
  65974. if (line[0] != 0)
  65975. clipEdgeTableLineToRange (line, x1, x2);
  65976. line += lineStrideElements;
  65977. }
  65978. }
  65979. needToCheckEmptinesss = true;
  65980. }
  65981. }
  65982. void EdgeTable::excludeRectangle (const Rectangle<int>& r)
  65983. {
  65984. const Rectangle<int> clipped (r.getIntersection (bounds));
  65985. if (! clipped.isEmpty())
  65986. {
  65987. const int top = clipped.getY() - bounds.getY();
  65988. const int bottom = clipped.getBottom() - bounds.getY();
  65989. //XXX optimise here by shortening the table if it fills top or bottom
  65990. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  65991. clipped.getX() << 8, 0,
  65992. clipped.getRight() << 8, 255,
  65993. std::numeric_limits<int>::max(), 0 };
  65994. for (int i = top; i < bottom; ++i)
  65995. intersectWithEdgeTableLine (i, rectLine);
  65996. needToCheckEmptinesss = true;
  65997. }
  65998. }
  65999. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66000. {
  66001. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66002. if (clipped.isEmpty())
  66003. {
  66004. needToCheckEmptinesss = false;
  66005. bounds.setHeight (0);
  66006. }
  66007. else
  66008. {
  66009. const int top = clipped.getY() - bounds.getY();
  66010. const int bottom = clipped.getBottom() - bounds.getY();
  66011. if (bottom < bounds.getHeight())
  66012. bounds.setHeight (bottom);
  66013. if (clipped.getRight() < bounds.getRight())
  66014. bounds.setRight (clipped.getRight());
  66015. int i = 0;
  66016. for (i = top; --i >= 0;)
  66017. table [lineStrideElements * i] = 0;
  66018. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66019. for (i = top; i < bottom; ++i)
  66020. {
  66021. intersectWithEdgeTableLine (i, otherLine);
  66022. otherLine += other.lineStrideElements;
  66023. }
  66024. needToCheckEmptinesss = true;
  66025. }
  66026. }
  66027. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels)
  66028. {
  66029. y -= bounds.getY();
  66030. if (y < 0 || y >= bounds.getHeight())
  66031. return;
  66032. needToCheckEmptinesss = true;
  66033. if (numPixels <= 0)
  66034. {
  66035. table [lineStrideElements * y] = 0;
  66036. return;
  66037. }
  66038. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66039. int destIndex = 0, lastLevel = 0;
  66040. while (--numPixels >= 0)
  66041. {
  66042. const int alpha = *mask;
  66043. mask += maskStride;
  66044. if (alpha != lastLevel)
  66045. {
  66046. tempLine[++destIndex] = (x << 8);
  66047. tempLine[++destIndex] = alpha;
  66048. lastLevel = alpha;
  66049. }
  66050. ++x;
  66051. }
  66052. if (lastLevel > 0)
  66053. {
  66054. tempLine[++destIndex] = (x << 8);
  66055. tempLine[++destIndex] = 0;
  66056. }
  66057. tempLine[0] = destIndex >> 1;
  66058. intersectWithEdgeTableLine (y, tempLine);
  66059. }
  66060. bool EdgeTable::isEmpty() throw()
  66061. {
  66062. if (needToCheckEmptinesss)
  66063. {
  66064. needToCheckEmptinesss = false;
  66065. int* t = table;
  66066. for (int i = bounds.getHeight(); --i >= 0;)
  66067. {
  66068. if (t[0] > 1)
  66069. return false;
  66070. t += lineStrideElements;
  66071. }
  66072. bounds.setHeight (0);
  66073. }
  66074. return bounds.getHeight() == 0;
  66075. }
  66076. END_JUCE_NAMESPACE
  66077. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66078. /*** Start of inlined file: juce_FillType.cpp ***/
  66079. BEGIN_JUCE_NAMESPACE
  66080. FillType::FillType() throw()
  66081. : colour (0xff000000), image (0)
  66082. {
  66083. }
  66084. FillType::FillType (const Colour& colour_) throw()
  66085. : colour (colour_), image (0)
  66086. {
  66087. }
  66088. FillType::FillType (const ColourGradient& gradient_)
  66089. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66090. {
  66091. }
  66092. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66093. : colour (0xff000000), image (image_), transform (transform_)
  66094. {
  66095. }
  66096. FillType::FillType (const FillType& other)
  66097. : colour (other.colour),
  66098. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66099. image (other.image), transform (other.transform)
  66100. {
  66101. }
  66102. FillType& FillType::operator= (const FillType& other)
  66103. {
  66104. if (this != &other)
  66105. {
  66106. colour = other.colour;
  66107. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66108. image = other.image;
  66109. transform = other.transform;
  66110. }
  66111. return *this;
  66112. }
  66113. FillType::~FillType() throw()
  66114. {
  66115. }
  66116. bool FillType::operator== (const FillType& other) const
  66117. {
  66118. return colour == other.colour && image == other.image
  66119. && transform == other.transform
  66120. && (gradient == other.gradient
  66121. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66122. }
  66123. bool FillType::operator!= (const FillType& other) const
  66124. {
  66125. return ! operator== (other);
  66126. }
  66127. void FillType::setColour (const Colour& newColour) throw()
  66128. {
  66129. gradient = 0;
  66130. image = Image::null;
  66131. colour = newColour;
  66132. }
  66133. void FillType::setGradient (const ColourGradient& newGradient)
  66134. {
  66135. if (gradient != 0)
  66136. {
  66137. *gradient = newGradient;
  66138. }
  66139. else
  66140. {
  66141. image = Image::null;
  66142. gradient = new ColourGradient (newGradient);
  66143. colour = Colours::black;
  66144. }
  66145. }
  66146. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66147. {
  66148. gradient = 0;
  66149. image = image_;
  66150. transform = transform_;
  66151. colour = Colours::black;
  66152. }
  66153. void FillType::setOpacity (const float newOpacity) throw()
  66154. {
  66155. colour = colour.withAlpha (newOpacity);
  66156. }
  66157. bool FillType::isInvisible() const throw()
  66158. {
  66159. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66160. }
  66161. END_JUCE_NAMESPACE
  66162. /*** End of inlined file: juce_FillType.cpp ***/
  66163. /*** Start of inlined file: juce_Graphics.cpp ***/
  66164. BEGIN_JUCE_NAMESPACE
  66165. namespace
  66166. {
  66167. template <typename Type>
  66168. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66169. {
  66170. const int maxVal = 0x3fffffff;
  66171. return (int) x >= -maxVal && (int) x <= maxVal
  66172. && (int) y >= -maxVal && (int) y <= maxVal
  66173. && (int) w >= -maxVal && (int) w <= maxVal
  66174. && (int) h >= -maxVal && (int) h <= maxVal;
  66175. }
  66176. }
  66177. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66178. {
  66179. }
  66180. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66181. {
  66182. }
  66183. Graphics::Graphics (const Image& imageToDrawOnto)
  66184. : context (imageToDrawOnto.createLowLevelContext()),
  66185. contextToDelete (context),
  66186. saveStatePending (false)
  66187. {
  66188. }
  66189. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66190. : context (internalContext),
  66191. saveStatePending (false)
  66192. {
  66193. }
  66194. Graphics::~Graphics()
  66195. {
  66196. }
  66197. void Graphics::resetToDefaultState()
  66198. {
  66199. saveStateIfPending();
  66200. context->setFill (FillType());
  66201. context->setFont (Font());
  66202. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66203. }
  66204. bool Graphics::isVectorDevice() const
  66205. {
  66206. return context->isVectorDevice();
  66207. }
  66208. bool Graphics::reduceClipRegion (const Rectangle<int>& area)
  66209. {
  66210. saveStateIfPending();
  66211. return context->clipToRectangle (area);
  66212. }
  66213. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66214. {
  66215. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66216. }
  66217. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66218. {
  66219. saveStateIfPending();
  66220. return context->clipToRectangleList (clipRegion);
  66221. }
  66222. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66223. {
  66224. saveStateIfPending();
  66225. context->clipToPath (path, transform);
  66226. return ! context->isClipEmpty();
  66227. }
  66228. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66229. {
  66230. saveStateIfPending();
  66231. context->clipToImageAlpha (image, transform);
  66232. return ! context->isClipEmpty();
  66233. }
  66234. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66235. {
  66236. saveStateIfPending();
  66237. context->excludeClipRectangle (rectangleToExclude);
  66238. }
  66239. bool Graphics::isClipEmpty() const
  66240. {
  66241. return context->isClipEmpty();
  66242. }
  66243. const Rectangle<int> Graphics::getClipBounds() const
  66244. {
  66245. return context->getClipBounds();
  66246. }
  66247. void Graphics::saveState()
  66248. {
  66249. saveStateIfPending();
  66250. saveStatePending = true;
  66251. }
  66252. void Graphics::restoreState()
  66253. {
  66254. if (saveStatePending)
  66255. saveStatePending = false;
  66256. else
  66257. context->restoreState();
  66258. }
  66259. void Graphics::saveStateIfPending()
  66260. {
  66261. if (saveStatePending)
  66262. {
  66263. saveStatePending = false;
  66264. context->saveState();
  66265. }
  66266. }
  66267. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66268. {
  66269. saveStateIfPending();
  66270. context->setOrigin (newOriginX, newOriginY);
  66271. }
  66272. void Graphics::addTransform (const AffineTransform& transform)
  66273. {
  66274. saveStateIfPending();
  66275. context->addTransform (transform);
  66276. }
  66277. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66278. {
  66279. return context->clipRegionIntersects (area);
  66280. }
  66281. void Graphics::beginTransparencyLayer (float layerOpacity)
  66282. {
  66283. saveStateIfPending();
  66284. context->beginTransparencyLayer (layerOpacity);
  66285. }
  66286. void Graphics::endTransparencyLayer()
  66287. {
  66288. context->endTransparencyLayer();
  66289. }
  66290. void Graphics::setColour (const Colour& newColour)
  66291. {
  66292. saveStateIfPending();
  66293. context->setFill (newColour);
  66294. }
  66295. void Graphics::setOpacity (const float newOpacity)
  66296. {
  66297. saveStateIfPending();
  66298. context->setOpacity (newOpacity);
  66299. }
  66300. void Graphics::setGradientFill (const ColourGradient& gradient)
  66301. {
  66302. setFillType (gradient);
  66303. }
  66304. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66305. {
  66306. saveStateIfPending();
  66307. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66308. context->setOpacity (opacity);
  66309. }
  66310. void Graphics::setFillType (const FillType& newFill)
  66311. {
  66312. saveStateIfPending();
  66313. context->setFill (newFill);
  66314. }
  66315. void Graphics::setFont (const Font& newFont)
  66316. {
  66317. saveStateIfPending();
  66318. context->setFont (newFont);
  66319. }
  66320. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66321. {
  66322. saveStateIfPending();
  66323. Font f (context->getFont());
  66324. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66325. context->setFont (f);
  66326. }
  66327. const Font Graphics::getCurrentFont() const
  66328. {
  66329. return context->getFont();
  66330. }
  66331. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66332. {
  66333. if (text.isNotEmpty()
  66334. && startX < context->getClipBounds().getRight())
  66335. {
  66336. GlyphArrangement arr;
  66337. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66338. arr.draw (*this);
  66339. }
  66340. }
  66341. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66342. {
  66343. if (text.isNotEmpty())
  66344. {
  66345. GlyphArrangement arr;
  66346. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66347. arr.draw (*this, transform);
  66348. }
  66349. }
  66350. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66351. {
  66352. if (text.isNotEmpty()
  66353. && startX < context->getClipBounds().getRight())
  66354. {
  66355. GlyphArrangement arr;
  66356. arr.addJustifiedText (context->getFont(), text,
  66357. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66358. Justification::left);
  66359. arr.draw (*this);
  66360. }
  66361. }
  66362. void Graphics::drawText (const String& text,
  66363. const int x, const int y, const int width, const int height,
  66364. const Justification& justificationType,
  66365. const bool useEllipsesIfTooBig) const
  66366. {
  66367. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66368. {
  66369. GlyphArrangement arr;
  66370. arr.addCurtailedLineOfText (context->getFont(), text,
  66371. 0.0f, 0.0f, (float) width,
  66372. useEllipsesIfTooBig);
  66373. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66374. (float) x, (float) y, (float) width, (float) height,
  66375. justificationType);
  66376. arr.draw (*this);
  66377. }
  66378. }
  66379. void Graphics::drawFittedText (const String& text,
  66380. const int x, const int y, const int width, const int height,
  66381. const Justification& justification,
  66382. const int maximumNumberOfLines,
  66383. const float minimumHorizontalScale) const
  66384. {
  66385. if (text.isNotEmpty()
  66386. && width > 0 && height > 0
  66387. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66388. {
  66389. GlyphArrangement arr;
  66390. arr.addFittedText (context->getFont(), text,
  66391. (float) x, (float) y, (float) width, (float) height,
  66392. justification,
  66393. maximumNumberOfLines,
  66394. minimumHorizontalScale);
  66395. arr.draw (*this);
  66396. }
  66397. }
  66398. void Graphics::fillRect (int x, int y, int width, int height) const
  66399. {
  66400. // passing in a silly number can cause maths problems in rendering!
  66401. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66402. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66403. }
  66404. void Graphics::fillRect (const Rectangle<int>& r) const
  66405. {
  66406. context->fillRect (r, false);
  66407. }
  66408. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66409. {
  66410. // passing in a silly number can cause maths problems in rendering!
  66411. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66412. Path p;
  66413. p.addRectangle (x, y, width, height);
  66414. fillPath (p);
  66415. }
  66416. void Graphics::setPixel (int x, int y) const
  66417. {
  66418. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66419. }
  66420. void Graphics::fillAll() const
  66421. {
  66422. fillRect (context->getClipBounds());
  66423. }
  66424. void Graphics::fillAll (const Colour& colourToUse) const
  66425. {
  66426. if (! colourToUse.isTransparent())
  66427. {
  66428. const Rectangle<int> clip (context->getClipBounds());
  66429. context->saveState();
  66430. context->setFill (colourToUse);
  66431. context->fillRect (clip, false);
  66432. context->restoreState();
  66433. }
  66434. }
  66435. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66436. {
  66437. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66438. context->fillPath (path, transform);
  66439. }
  66440. void Graphics::strokePath (const Path& path,
  66441. const PathStrokeType& strokeType,
  66442. const AffineTransform& transform) const
  66443. {
  66444. Path stroke;
  66445. strokeType.createStrokedPath (stroke, path, transform, context->getScaleFactor());
  66446. fillPath (stroke);
  66447. }
  66448. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66449. const int lineThickness) const
  66450. {
  66451. // passing in a silly number can cause maths problems in rendering!
  66452. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66453. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66454. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66455. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66456. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66457. }
  66458. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66459. {
  66460. // passing in a silly number can cause maths problems in rendering!
  66461. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66462. Path p;
  66463. p.addRectangle (x, y, width, lineThickness);
  66464. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66465. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66466. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66467. fillPath (p);
  66468. }
  66469. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66470. {
  66471. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66472. }
  66473. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66474. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66475. const bool useGradient, const bool sharpEdgeOnOutside) const
  66476. {
  66477. // passing in a silly number can cause maths problems in rendering!
  66478. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66479. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66480. {
  66481. context->saveState();
  66482. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66483. const float ramp = oldOpacity / bevelThickness;
  66484. for (int i = bevelThickness; --i >= 0;)
  66485. {
  66486. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66487. : oldOpacity;
  66488. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66489. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66490. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66491. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66492. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66493. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66494. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66495. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66496. }
  66497. context->restoreState();
  66498. }
  66499. }
  66500. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66501. {
  66502. // passing in a silly number can cause maths problems in rendering!
  66503. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66504. Path p;
  66505. p.addEllipse (x, y, width, height);
  66506. fillPath (p);
  66507. }
  66508. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66509. const float lineThickness) const
  66510. {
  66511. // passing in a silly number can cause maths problems in rendering!
  66512. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66513. Path p;
  66514. p.addEllipse (x, y, width, height);
  66515. strokePath (p, PathStrokeType (lineThickness));
  66516. }
  66517. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66518. {
  66519. // passing in a silly number can cause maths problems in rendering!
  66520. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66521. Path p;
  66522. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66523. fillPath (p);
  66524. }
  66525. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66526. {
  66527. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66528. }
  66529. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66530. const float cornerSize, const float lineThickness) const
  66531. {
  66532. // passing in a silly number can cause maths problems in rendering!
  66533. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66534. Path p;
  66535. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66536. strokePath (p, PathStrokeType (lineThickness));
  66537. }
  66538. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66539. {
  66540. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66541. }
  66542. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66543. {
  66544. Path p;
  66545. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66546. fillPath (p);
  66547. }
  66548. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66549. const int checkWidth, const int checkHeight,
  66550. const Colour& colour1, const Colour& colour2) const
  66551. {
  66552. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66553. if (checkWidth > 0 && checkHeight > 0)
  66554. {
  66555. context->saveState();
  66556. if (colour1 == colour2)
  66557. {
  66558. context->setFill (colour1);
  66559. context->fillRect (area, false);
  66560. }
  66561. else
  66562. {
  66563. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66564. if (! clipped.isEmpty())
  66565. {
  66566. context->clipToRectangle (clipped);
  66567. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66568. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66569. const int startX = area.getX() + checkNumX * checkWidth;
  66570. const int startY = area.getY() + checkNumY * checkHeight;
  66571. const int right = clipped.getRight();
  66572. const int bottom = clipped.getBottom();
  66573. for (int i = 0; i < 2; ++i)
  66574. {
  66575. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66576. int cy = i;
  66577. for (int y = startY; y < bottom; y += checkHeight)
  66578. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66579. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66580. }
  66581. }
  66582. }
  66583. context->restoreState();
  66584. }
  66585. }
  66586. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66587. {
  66588. context->drawVerticalLine (x, top, bottom);
  66589. }
  66590. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66591. {
  66592. context->drawHorizontalLine (y, left, right);
  66593. }
  66594. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2) const
  66595. {
  66596. context->drawLine (Line<float> (x1, y1, x2, y2));
  66597. }
  66598. void Graphics::drawLine (const Line<float>& line) const
  66599. {
  66600. context->drawLine (line);
  66601. }
  66602. void Graphics::drawLine (const float x1, const float y1, const float x2, const float y2, const float lineThickness) const
  66603. {
  66604. drawLine (Line<float> (x1, y1, x2, y2), lineThickness);
  66605. }
  66606. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66607. {
  66608. Path p;
  66609. p.addLineSegment (line, lineThickness);
  66610. fillPath (p);
  66611. }
  66612. void Graphics::drawDashedLine (const Line<float>& line, const float* const dashLengths,
  66613. const int numDashLengths, const float lineThickness, int n) const
  66614. {
  66615. jassert (n >= 0 && n < numDashLengths); // your start index must be valid!
  66616. const Point<double> delta ((line.getEnd() - line.getStart()).toDouble());
  66617. const double totalLen = delta.getDistanceFromOrigin();
  66618. if (totalLen >= 0.1)
  66619. {
  66620. const double onePixAlpha = 1.0 / totalLen;
  66621. for (double alpha = 0.0; alpha < 1.0;)
  66622. {
  66623. jassert (dashLengths[n] > 0); // can't have zero-length dashes!
  66624. const double lastAlpha = alpha;
  66625. alpha = jmin (1.0, alpha + dashLengths [n] * onePixAlpha);
  66626. n = (n + 1) % numDashLengths;
  66627. if ((n & 1) != 0)
  66628. {
  66629. const Line<float> segment (line.getStart() + (delta * lastAlpha).toFloat(),
  66630. line.getStart() + (delta * alpha).toFloat());
  66631. if (lineThickness != 1.0f)
  66632. drawLine (segment, lineThickness);
  66633. else
  66634. context->drawLine (segment);
  66635. }
  66636. }
  66637. }
  66638. }
  66639. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66640. {
  66641. saveStateIfPending();
  66642. context->setInterpolationQuality (newQuality);
  66643. }
  66644. void Graphics::drawImageAt (const Image& imageToDraw,
  66645. const int topLeftX, const int topLeftY,
  66646. const bool fillAlphaChannelWithCurrentBrush) const
  66647. {
  66648. const int imageW = imageToDraw.getWidth();
  66649. const int imageH = imageToDraw.getHeight();
  66650. drawImage (imageToDraw,
  66651. topLeftX, topLeftY, imageW, imageH,
  66652. 0, 0, imageW, imageH,
  66653. fillAlphaChannelWithCurrentBrush);
  66654. }
  66655. void Graphics::drawImageWithin (const Image& imageToDraw,
  66656. const int destX, const int destY,
  66657. const int destW, const int destH,
  66658. const RectanglePlacement& placementWithinTarget,
  66659. const bool fillAlphaChannelWithCurrentBrush) const
  66660. {
  66661. // passing in a silly number can cause maths problems in rendering!
  66662. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66663. if (imageToDraw.isValid())
  66664. {
  66665. const int imageW = imageToDraw.getWidth();
  66666. const int imageH = imageToDraw.getHeight();
  66667. if (imageW > 0 && imageH > 0)
  66668. {
  66669. double newX = 0.0, newY = 0.0;
  66670. double newW = imageW;
  66671. double newH = imageH;
  66672. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66673. destX, destY, destW, destH);
  66674. if (newW > 0 && newH > 0)
  66675. {
  66676. drawImage (imageToDraw,
  66677. roundToInt (newX), roundToInt (newY),
  66678. roundToInt (newW), roundToInt (newH),
  66679. 0, 0, imageW, imageH,
  66680. fillAlphaChannelWithCurrentBrush);
  66681. }
  66682. }
  66683. }
  66684. }
  66685. void Graphics::drawImage (const Image& imageToDraw,
  66686. int dx, int dy, int dw, int dh,
  66687. int sx, int sy, int sw, int sh,
  66688. const bool fillAlphaChannelWithCurrentBrush) const
  66689. {
  66690. // passing in a silly number can cause maths problems in rendering!
  66691. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66692. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66693. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66694. {
  66695. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66696. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66697. .translated ((float) dx, (float) dy),
  66698. fillAlphaChannelWithCurrentBrush);
  66699. }
  66700. }
  66701. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66702. const AffineTransform& transform,
  66703. const bool fillAlphaChannelWithCurrentBrush) const
  66704. {
  66705. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66706. {
  66707. if (fillAlphaChannelWithCurrentBrush)
  66708. {
  66709. context->saveState();
  66710. context->clipToImageAlpha (imageToDraw, transform);
  66711. fillAll();
  66712. context->restoreState();
  66713. }
  66714. else
  66715. {
  66716. context->drawImage (imageToDraw, transform, false);
  66717. }
  66718. }
  66719. }
  66720. Graphics::ScopedSaveState::ScopedSaveState (Graphics& g)
  66721. : context (g)
  66722. {
  66723. context.saveState();
  66724. }
  66725. Graphics::ScopedSaveState::~ScopedSaveState()
  66726. {
  66727. context.restoreState();
  66728. }
  66729. END_JUCE_NAMESPACE
  66730. /*** End of inlined file: juce_Graphics.cpp ***/
  66731. /*** Start of inlined file: juce_Justification.cpp ***/
  66732. BEGIN_JUCE_NAMESPACE
  66733. Justification::Justification (const Justification& other) throw()
  66734. : flags (other.flags)
  66735. {
  66736. }
  66737. Justification& Justification::operator= (const Justification& other) throw()
  66738. {
  66739. flags = other.flags;
  66740. return *this;
  66741. }
  66742. int Justification::getOnlyVerticalFlags() const throw()
  66743. {
  66744. return flags & (top | bottom | verticallyCentred);
  66745. }
  66746. int Justification::getOnlyHorizontalFlags() const throw()
  66747. {
  66748. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66749. }
  66750. END_JUCE_NAMESPACE
  66751. /*** End of inlined file: juce_Justification.cpp ***/
  66752. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  66753. BEGIN_JUCE_NAMESPACE
  66754. // this will throw an assertion if you try to draw something that's not
  66755. // possible in postscript
  66756. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  66757. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  66758. #define notPossibleInPostscriptAssert jassertfalse
  66759. #else
  66760. #define notPossibleInPostscriptAssert
  66761. #endif
  66762. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  66763. const String& documentTitle,
  66764. const int totalWidth_,
  66765. const int totalHeight_)
  66766. : out (resultingPostScript),
  66767. totalWidth (totalWidth_),
  66768. totalHeight (totalHeight_),
  66769. needToClip (true)
  66770. {
  66771. stateStack.add (new SavedState());
  66772. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  66773. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  66774. out << "%!PS-Adobe-3.0 EPSF-3.0"
  66775. "\n%%BoundingBox: 0 0 600 824"
  66776. "\n%%Pages: 0"
  66777. "\n%%Creator: Raw Material Software JUCE"
  66778. "\n%%Title: " << documentTitle <<
  66779. "\n%%CreationDate: none"
  66780. "\n%%LanguageLevel: 2"
  66781. "\n%%EndComments"
  66782. "\n%%BeginProlog"
  66783. "\n%%BeginResource: JRes"
  66784. "\n/bd {bind def} bind def"
  66785. "\n/c {setrgbcolor} bd"
  66786. "\n/m {moveto} bd"
  66787. "\n/l {lineto} bd"
  66788. "\n/rl {rlineto} bd"
  66789. "\n/ct {curveto} bd"
  66790. "\n/cp {closepath} bd"
  66791. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  66792. "\n/doclip {initclip newpath} bd"
  66793. "\n/endclip {clip newpath} bd"
  66794. "\n%%EndResource"
  66795. "\n%%EndProlog"
  66796. "\n%%BeginSetup"
  66797. "\n%%EndSetup"
  66798. "\n%%Page: 1 1"
  66799. "\n%%BeginPageSetup"
  66800. "\n%%EndPageSetup\n\n"
  66801. << "40 800 translate\n"
  66802. << scale << ' ' << scale << " scale\n\n";
  66803. }
  66804. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  66805. {
  66806. }
  66807. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  66808. {
  66809. return true;
  66810. }
  66811. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  66812. {
  66813. if (x != 0 || y != 0)
  66814. {
  66815. stateStack.getLast()->xOffset += x;
  66816. stateStack.getLast()->yOffset += y;
  66817. needToClip = true;
  66818. }
  66819. }
  66820. void LowLevelGraphicsPostScriptRenderer::addTransform (const AffineTransform& /*transform*/)
  66821. {
  66822. //xxx
  66823. jassertfalse;
  66824. }
  66825. float LowLevelGraphicsPostScriptRenderer::getScaleFactor()
  66826. {
  66827. jassertfalse; //xxx
  66828. return 1.0f;
  66829. }
  66830. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  66831. {
  66832. needToClip = true;
  66833. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66834. }
  66835. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  66836. {
  66837. needToClip = true;
  66838. return stateStack.getLast()->clip.clipTo (clipRegion);
  66839. }
  66840. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  66841. {
  66842. needToClip = true;
  66843. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66844. }
  66845. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  66846. {
  66847. writeClip();
  66848. Path p (path);
  66849. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  66850. writePath (p);
  66851. out << "clip\n";
  66852. }
  66853. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  66854. {
  66855. needToClip = true;
  66856. jassertfalse; // xxx
  66857. }
  66858. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  66859. {
  66860. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  66861. }
  66862. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  66863. {
  66864. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  66865. -stateStack.getLast()->yOffset);
  66866. }
  66867. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  66868. {
  66869. return stateStack.getLast()->clip.isEmpty();
  66870. }
  66871. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  66872. : xOffset (0),
  66873. yOffset (0)
  66874. {
  66875. }
  66876. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  66877. {
  66878. }
  66879. void LowLevelGraphicsPostScriptRenderer::saveState()
  66880. {
  66881. stateStack.add (new SavedState (*stateStack.getLast()));
  66882. }
  66883. void LowLevelGraphicsPostScriptRenderer::restoreState()
  66884. {
  66885. jassert (stateStack.size() > 0);
  66886. if (stateStack.size() > 0)
  66887. stateStack.removeLast();
  66888. }
  66889. void LowLevelGraphicsPostScriptRenderer::beginTransparencyLayer (float)
  66890. {
  66891. }
  66892. void LowLevelGraphicsPostScriptRenderer::endTransparencyLayer()
  66893. {
  66894. }
  66895. void LowLevelGraphicsPostScriptRenderer::writeClip()
  66896. {
  66897. if (needToClip)
  66898. {
  66899. needToClip = false;
  66900. out << "doclip ";
  66901. int itemsOnLine = 0;
  66902. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  66903. {
  66904. if (++itemsOnLine == 6)
  66905. {
  66906. itemsOnLine = 0;
  66907. out << '\n';
  66908. }
  66909. const Rectangle<int>& r = *i.getRectangle();
  66910. out << r.getX() << ' ' << -r.getY() << ' '
  66911. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  66912. }
  66913. out << "endclip\n";
  66914. }
  66915. }
  66916. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  66917. {
  66918. Colour c (Colours::white.overlaidWith (colour));
  66919. if (lastColour != c)
  66920. {
  66921. lastColour = c;
  66922. out << String (c.getFloatRed(), 3) << ' '
  66923. << String (c.getFloatGreen(), 3) << ' '
  66924. << String (c.getFloatBlue(), 3) << " c\n";
  66925. }
  66926. }
  66927. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  66928. {
  66929. out << String (x, 2) << ' '
  66930. << String (-y, 2) << ' ';
  66931. }
  66932. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  66933. {
  66934. out << "newpath ";
  66935. float lastX = 0.0f;
  66936. float lastY = 0.0f;
  66937. int itemsOnLine = 0;
  66938. Path::Iterator i (path);
  66939. while (i.next())
  66940. {
  66941. if (++itemsOnLine == 4)
  66942. {
  66943. itemsOnLine = 0;
  66944. out << '\n';
  66945. }
  66946. switch (i.elementType)
  66947. {
  66948. case Path::Iterator::startNewSubPath:
  66949. writeXY (i.x1, i.y1);
  66950. lastX = i.x1;
  66951. lastY = i.y1;
  66952. out << "m ";
  66953. break;
  66954. case Path::Iterator::lineTo:
  66955. writeXY (i.x1, i.y1);
  66956. lastX = i.x1;
  66957. lastY = i.y1;
  66958. out << "l ";
  66959. break;
  66960. case Path::Iterator::quadraticTo:
  66961. {
  66962. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  66963. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  66964. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  66965. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  66966. writeXY (cp1x, cp1y);
  66967. writeXY (cp2x, cp2y);
  66968. writeXY (i.x2, i.y2);
  66969. out << "ct ";
  66970. lastX = i.x2;
  66971. lastY = i.y2;
  66972. }
  66973. break;
  66974. case Path::Iterator::cubicTo:
  66975. writeXY (i.x1, i.y1);
  66976. writeXY (i.x2, i.y2);
  66977. writeXY (i.x3, i.y3);
  66978. out << "ct ";
  66979. lastX = i.x3;
  66980. lastY = i.y3;
  66981. break;
  66982. case Path::Iterator::closePath:
  66983. out << "cp ";
  66984. break;
  66985. default:
  66986. jassertfalse;
  66987. break;
  66988. }
  66989. }
  66990. out << '\n';
  66991. }
  66992. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  66993. {
  66994. out << "[ "
  66995. << trans.mat00 << ' '
  66996. << trans.mat10 << ' '
  66997. << trans.mat01 << ' '
  66998. << trans.mat11 << ' '
  66999. << trans.mat02 << ' '
  67000. << trans.mat12 << " ] concat ";
  67001. }
  67002. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67003. {
  67004. stateStack.getLast()->fillType = fillType;
  67005. }
  67006. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67007. {
  67008. }
  67009. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67010. {
  67011. }
  67012. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67013. {
  67014. if (stateStack.getLast()->fillType.isColour())
  67015. {
  67016. writeClip();
  67017. writeColour (stateStack.getLast()->fillType.colour);
  67018. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67019. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67020. }
  67021. else
  67022. {
  67023. Path p;
  67024. p.addRectangle (r);
  67025. fillPath (p, AffineTransform::identity);
  67026. }
  67027. }
  67028. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67029. {
  67030. if (stateStack.getLast()->fillType.isColour())
  67031. {
  67032. writeClip();
  67033. Path p (path);
  67034. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67035. (float) stateStack.getLast()->yOffset));
  67036. writePath (p);
  67037. writeColour (stateStack.getLast()->fillType.colour);
  67038. out << "fill\n";
  67039. }
  67040. else if (stateStack.getLast()->fillType.isGradient())
  67041. {
  67042. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67043. // postscript can't do semi-transparent ones.
  67044. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67045. writeClip();
  67046. out << "gsave ";
  67047. {
  67048. Path p (path);
  67049. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67050. writePath (p);
  67051. out << "clip\n";
  67052. }
  67053. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67054. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67055. // time-being, this just fills it with the average colour..
  67056. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67057. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67058. out << "grestore\n";
  67059. }
  67060. }
  67061. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67062. const int sx, const int sy,
  67063. const int maxW, const int maxH) const
  67064. {
  67065. out << "{<\n";
  67066. const int w = jmin (maxW, im.getWidth());
  67067. const int h = jmin (maxH, im.getHeight());
  67068. int charsOnLine = 0;
  67069. const Image::BitmapData srcData (im, 0, 0, w, h);
  67070. Colour pixel;
  67071. for (int y = h; --y >= 0;)
  67072. {
  67073. for (int x = 0; x < w; ++x)
  67074. {
  67075. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67076. if (x >= sx && y >= sy)
  67077. {
  67078. if (im.isARGB())
  67079. {
  67080. PixelARGB p (*(const PixelARGB*) pixelData);
  67081. p.unpremultiply();
  67082. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67083. }
  67084. else if (im.isRGB())
  67085. {
  67086. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67087. }
  67088. else
  67089. {
  67090. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67091. }
  67092. }
  67093. else
  67094. {
  67095. pixel = Colours::transparentWhite;
  67096. }
  67097. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67098. out << String::toHexString (pixelValues, 3, 0);
  67099. charsOnLine += 3;
  67100. if (charsOnLine > 100)
  67101. {
  67102. out << '\n';
  67103. charsOnLine = 0;
  67104. }
  67105. }
  67106. }
  67107. out << "\n>}\n";
  67108. }
  67109. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67110. {
  67111. const int w = sourceImage.getWidth();
  67112. const int h = sourceImage.getHeight();
  67113. writeClip();
  67114. out << "gsave ";
  67115. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67116. .scaled (1.0f, -1.0f));
  67117. RectangleList imageClip;
  67118. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67119. out << "newpath ";
  67120. int itemsOnLine = 0;
  67121. for (RectangleList::Iterator i (imageClip); i.next();)
  67122. {
  67123. if (++itemsOnLine == 6)
  67124. {
  67125. out << '\n';
  67126. itemsOnLine = 0;
  67127. }
  67128. const Rectangle<int>& r = *i.getRectangle();
  67129. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67130. }
  67131. out << " clip newpath\n";
  67132. out << w << ' ' << h << " scale\n";
  67133. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67134. writeImage (sourceImage, 0, 0, w, h);
  67135. out << "false 3 colorimage grestore\n";
  67136. needToClip = true;
  67137. }
  67138. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67139. {
  67140. Path p;
  67141. p.addLineSegment (line, 1.0f);
  67142. fillPath (p, AffineTransform::identity);
  67143. }
  67144. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67145. {
  67146. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67147. }
  67148. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67149. {
  67150. drawLine (Line<float> (left, (float) y, right, (float) y));
  67151. }
  67152. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67153. {
  67154. stateStack.getLast()->font = newFont;
  67155. }
  67156. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67157. {
  67158. return stateStack.getLast()->font;
  67159. }
  67160. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67161. {
  67162. Path p;
  67163. Font& font = stateStack.getLast()->font;
  67164. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67165. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67166. }
  67167. END_JUCE_NAMESPACE
  67168. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67169. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67170. BEGIN_JUCE_NAMESPACE
  67171. #if JUCE_MSVC
  67172. #pragma warning (push)
  67173. #pragma warning (disable: 4127) // "expression is constant" warning
  67174. #if JUCE_DEBUG
  67175. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67176. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67177. #endif
  67178. #endif
  67179. namespace SoftwareRendererClasses
  67180. {
  67181. template <class PixelType, bool replaceExisting = false>
  67182. class SolidColourEdgeTableRenderer
  67183. {
  67184. public:
  67185. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67186. : data (data_),
  67187. sourceColour (colour)
  67188. {
  67189. if (sizeof (PixelType) == 3)
  67190. {
  67191. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67192. && sourceColour.getGreen() == sourceColour.getBlue();
  67193. filler[0].set (sourceColour);
  67194. filler[1].set (sourceColour);
  67195. filler[2].set (sourceColour);
  67196. filler[3].set (sourceColour);
  67197. }
  67198. }
  67199. forcedinline void setEdgeTableYPos (const int y) throw()
  67200. {
  67201. linePixels = (PixelType*) data.getLinePointer (y);
  67202. }
  67203. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67204. {
  67205. if (replaceExisting)
  67206. linePixels[x].set (sourceColour);
  67207. else
  67208. linePixels[x].blend (sourceColour, alphaLevel);
  67209. }
  67210. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67211. {
  67212. if (replaceExisting)
  67213. linePixels[x].set (sourceColour);
  67214. else
  67215. linePixels[x].blend (sourceColour);
  67216. }
  67217. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67218. {
  67219. PixelARGB p (sourceColour);
  67220. p.multiplyAlpha (alphaLevel);
  67221. PixelType* dest = linePixels + x;
  67222. if (replaceExisting || p.getAlpha() >= 0xff)
  67223. replaceLine (dest, p, width);
  67224. else
  67225. blendLine (dest, p, width);
  67226. }
  67227. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67228. {
  67229. PixelType* dest = linePixels + x;
  67230. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67231. replaceLine (dest, sourceColour, width);
  67232. else
  67233. blendLine (dest, sourceColour, width);
  67234. }
  67235. private:
  67236. const Image::BitmapData& data;
  67237. PixelType* linePixels;
  67238. PixelARGB sourceColour;
  67239. PixelRGB filler [4];
  67240. bool areRGBComponentsEqual;
  67241. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67242. {
  67243. do
  67244. {
  67245. dest->blend (colour);
  67246. ++dest;
  67247. } while (--width > 0);
  67248. }
  67249. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67250. {
  67251. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67252. {
  67253. memset (dest, colour.getRed(), width * 3);
  67254. }
  67255. else
  67256. {
  67257. if (width >> 5)
  67258. {
  67259. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67260. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67261. {
  67262. dest->set (colour);
  67263. ++dest;
  67264. --width;
  67265. }
  67266. while (width > 4)
  67267. {
  67268. int* d = reinterpret_cast<int*> (dest);
  67269. *d++ = intFiller[0];
  67270. *d++ = intFiller[1];
  67271. *d++ = intFiller[2];
  67272. dest = reinterpret_cast<PixelRGB*> (d);
  67273. width -= 4;
  67274. }
  67275. }
  67276. while (--width >= 0)
  67277. {
  67278. dest->set (colour);
  67279. ++dest;
  67280. }
  67281. }
  67282. }
  67283. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67284. {
  67285. memset (dest, colour.getAlpha(), width);
  67286. }
  67287. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67288. {
  67289. do
  67290. {
  67291. dest->set (colour);
  67292. ++dest;
  67293. } while (--width > 0);
  67294. }
  67295. JUCE_DECLARE_NON_COPYABLE (SolidColourEdgeTableRenderer);
  67296. };
  67297. class LinearGradientPixelGenerator
  67298. {
  67299. public:
  67300. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67301. : lookupTable (lookupTable_), numEntries (numEntries_)
  67302. {
  67303. jassert (numEntries_ >= 0);
  67304. Point<float> p1 (gradient.point1);
  67305. Point<float> p2 (gradient.point2);
  67306. if (! transform.isIdentity())
  67307. {
  67308. const Line<float> l (p2, p1);
  67309. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67310. p1.applyTransform (transform);
  67311. p2.applyTransform (transform);
  67312. p3.applyTransform (transform);
  67313. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67314. }
  67315. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67316. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67317. if (vertical)
  67318. {
  67319. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67320. start = roundToInt (p1.getY() * scale);
  67321. }
  67322. else if (horizontal)
  67323. {
  67324. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67325. start = roundToInt (p1.getX() * scale);
  67326. }
  67327. else
  67328. {
  67329. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67330. yTerm = p1.getY() - p1.getX() / grad;
  67331. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67332. grad *= scale;
  67333. }
  67334. }
  67335. forcedinline void setY (const int y) throw()
  67336. {
  67337. if (vertical)
  67338. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67339. else if (! horizontal)
  67340. start = roundToInt ((y - yTerm) * grad);
  67341. }
  67342. inline const PixelARGB getPixel (const int x) const throw()
  67343. {
  67344. return vertical ? linePix
  67345. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67346. }
  67347. private:
  67348. const PixelARGB* const lookupTable;
  67349. const int numEntries;
  67350. PixelARGB linePix;
  67351. int start, scale;
  67352. double grad, yTerm;
  67353. bool vertical, horizontal;
  67354. enum { numScaleBits = 12 };
  67355. JUCE_DECLARE_NON_COPYABLE (LinearGradientPixelGenerator);
  67356. };
  67357. class RadialGradientPixelGenerator
  67358. {
  67359. public:
  67360. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67361. const PixelARGB* const lookupTable_, const int numEntries_)
  67362. : lookupTable (lookupTable_),
  67363. numEntries (numEntries_),
  67364. gx1 (gradient.point1.getX()),
  67365. gy1 (gradient.point1.getY())
  67366. {
  67367. jassert (numEntries_ >= 0);
  67368. const Point<float> diff (gradient.point1 - gradient.point2);
  67369. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67370. invScale = numEntries / std::sqrt (maxDist);
  67371. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67372. }
  67373. forcedinline void setY (const int y) throw()
  67374. {
  67375. dy = y - gy1;
  67376. dy *= dy;
  67377. }
  67378. inline const PixelARGB getPixel (const int px) const throw()
  67379. {
  67380. double x = px - gx1;
  67381. x *= x;
  67382. x += dy;
  67383. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67384. }
  67385. protected:
  67386. const PixelARGB* const lookupTable;
  67387. const int numEntries;
  67388. const double gx1, gy1;
  67389. double maxDist, invScale, dy;
  67390. JUCE_DECLARE_NON_COPYABLE (RadialGradientPixelGenerator);
  67391. };
  67392. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67393. {
  67394. public:
  67395. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67396. const PixelARGB* const lookupTable_, const int numEntries_)
  67397. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67398. inverseTransform (transform.inverted())
  67399. {
  67400. tM10 = inverseTransform.mat10;
  67401. tM00 = inverseTransform.mat00;
  67402. }
  67403. forcedinline void setY (const int y) throw()
  67404. {
  67405. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67406. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67407. }
  67408. inline const PixelARGB getPixel (const int px) const throw()
  67409. {
  67410. double x = px;
  67411. const double y = tM10 * x + lineYM11;
  67412. x = tM00 * x + lineYM01;
  67413. x *= x;
  67414. x += y * y;
  67415. if (x >= maxDist)
  67416. return lookupTable [numEntries];
  67417. else
  67418. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67419. }
  67420. private:
  67421. double tM10, tM00, lineYM01, lineYM11;
  67422. const AffineTransform inverseTransform;
  67423. JUCE_DECLARE_NON_COPYABLE (TransformedRadialGradientPixelGenerator);
  67424. };
  67425. template <class PixelType, class GradientType>
  67426. class GradientEdgeTableRenderer : public GradientType
  67427. {
  67428. public:
  67429. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67430. const PixelARGB* const lookupTable_, const int numEntries_)
  67431. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67432. destData (destData_)
  67433. {
  67434. }
  67435. forcedinline void setEdgeTableYPos (const int y) throw()
  67436. {
  67437. linePixels = (PixelType*) destData.getLinePointer (y);
  67438. GradientType::setY (y);
  67439. }
  67440. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67441. {
  67442. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67443. }
  67444. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67445. {
  67446. linePixels[x].blend (GradientType::getPixel (x));
  67447. }
  67448. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67449. {
  67450. PixelType* dest = linePixels + x;
  67451. if (alphaLevel < 0xff)
  67452. {
  67453. do
  67454. {
  67455. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67456. } while (--width > 0);
  67457. }
  67458. else
  67459. {
  67460. do
  67461. {
  67462. (dest++)->blend (GradientType::getPixel (x++));
  67463. } while (--width > 0);
  67464. }
  67465. }
  67466. void handleEdgeTableLineFull (int x, int width) const throw()
  67467. {
  67468. PixelType* dest = linePixels + x;
  67469. do
  67470. {
  67471. (dest++)->blend (GradientType::getPixel (x++));
  67472. } while (--width > 0);
  67473. }
  67474. private:
  67475. const Image::BitmapData& destData;
  67476. PixelType* linePixels;
  67477. JUCE_DECLARE_NON_COPYABLE (GradientEdgeTableRenderer);
  67478. };
  67479. namespace RenderingHelpers
  67480. {
  67481. forcedinline int safeModulo (int n, const int divisor) throw()
  67482. {
  67483. jassert (divisor > 0);
  67484. n %= divisor;
  67485. return (n < 0) ? (n + divisor) : n;
  67486. }
  67487. }
  67488. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67489. class ImageFillEdgeTableRenderer
  67490. {
  67491. public:
  67492. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67493. const Image::BitmapData& srcData_,
  67494. const int extraAlpha_,
  67495. const int x, const int y)
  67496. : destData (destData_),
  67497. srcData (srcData_),
  67498. extraAlpha (extraAlpha_ + 1),
  67499. xOffset (repeatPattern ? RenderingHelpers::safeModulo (x, srcData_.width) - srcData_.width : x),
  67500. yOffset (repeatPattern ? RenderingHelpers::safeModulo (y, srcData_.height) - srcData_.height : y)
  67501. {
  67502. }
  67503. forcedinline void setEdgeTableYPos (int y) throw()
  67504. {
  67505. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67506. y -= yOffset;
  67507. if (repeatPattern)
  67508. {
  67509. jassert (y >= 0);
  67510. y %= srcData.height;
  67511. }
  67512. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67513. }
  67514. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67515. {
  67516. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67517. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67518. }
  67519. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67520. {
  67521. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67522. }
  67523. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67524. {
  67525. DestPixelType* dest = linePixels + x;
  67526. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67527. x -= xOffset;
  67528. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67529. if (alphaLevel < 0xfe)
  67530. {
  67531. do
  67532. {
  67533. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67534. } while (--width > 0);
  67535. }
  67536. else
  67537. {
  67538. if (repeatPattern)
  67539. {
  67540. do
  67541. {
  67542. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67543. } while (--width > 0);
  67544. }
  67545. else
  67546. {
  67547. copyRow (dest, sourceLineStart + x, width);
  67548. }
  67549. }
  67550. }
  67551. void handleEdgeTableLineFull (int x, int width) const throw()
  67552. {
  67553. DestPixelType* dest = linePixels + x;
  67554. x -= xOffset;
  67555. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67556. if (extraAlpha < 0xfe)
  67557. {
  67558. do
  67559. {
  67560. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67561. } while (--width > 0);
  67562. }
  67563. else
  67564. {
  67565. if (repeatPattern)
  67566. {
  67567. do
  67568. {
  67569. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67570. } while (--width > 0);
  67571. }
  67572. else
  67573. {
  67574. copyRow (dest, sourceLineStart + x, width);
  67575. }
  67576. }
  67577. }
  67578. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67579. {
  67580. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67581. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67582. uint8* mask = (uint8*) (s + x - xOffset);
  67583. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67584. mask += PixelARGB::indexA;
  67585. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67586. }
  67587. private:
  67588. const Image::BitmapData& destData;
  67589. const Image::BitmapData& srcData;
  67590. const int extraAlpha, xOffset, yOffset;
  67591. DestPixelType* linePixels;
  67592. SrcPixelType* sourceLineStart;
  67593. template <class PixelType1, class PixelType2>
  67594. static forcedinline void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67595. {
  67596. do
  67597. {
  67598. dest++ ->blend (*src++);
  67599. } while (--width > 0);
  67600. }
  67601. static forcedinline void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67602. {
  67603. memcpy (dest, src, width * sizeof (PixelRGB));
  67604. }
  67605. JUCE_DECLARE_NON_COPYABLE (ImageFillEdgeTableRenderer);
  67606. };
  67607. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67608. class TransformedImageFillEdgeTableRenderer
  67609. {
  67610. public:
  67611. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67612. const Image::BitmapData& srcData_,
  67613. const AffineTransform& transform,
  67614. const int extraAlpha_,
  67615. const bool betterQuality_)
  67616. : interpolator (transform,
  67617. betterQuality_ ? 0.5f : 0.0f,
  67618. betterQuality_ ? -128 : 0),
  67619. destData (destData_),
  67620. srcData (srcData_),
  67621. extraAlpha (extraAlpha_ + 1),
  67622. betterQuality (betterQuality_),
  67623. maxX (srcData_.width - 1),
  67624. maxY (srcData_.height - 1),
  67625. scratchSize (2048)
  67626. {
  67627. scratchBuffer.malloc (scratchSize);
  67628. }
  67629. forcedinline void setEdgeTableYPos (const int newY) throw()
  67630. {
  67631. y = newY;
  67632. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67633. }
  67634. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) throw()
  67635. {
  67636. SrcPixelType p;
  67637. generate (&p, x, 1);
  67638. linePixels[x].blend (p, (alphaLevel * extraAlpha) >> 8);
  67639. }
  67640. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67641. {
  67642. SrcPixelType p;
  67643. generate (&p, x, 1);
  67644. linePixels[x].blend (p, extraAlpha);
  67645. }
  67646. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67647. {
  67648. if (width > scratchSize)
  67649. {
  67650. scratchSize = width;
  67651. scratchBuffer.malloc (scratchSize);
  67652. }
  67653. SrcPixelType* span = scratchBuffer;
  67654. generate (span, x, width);
  67655. DestPixelType* dest = linePixels + x;
  67656. alphaLevel *= extraAlpha;
  67657. alphaLevel >>= 8;
  67658. if (alphaLevel < 0xfe)
  67659. {
  67660. do
  67661. {
  67662. dest++ ->blend (*span++, alphaLevel);
  67663. } while (--width > 0);
  67664. }
  67665. else
  67666. {
  67667. do
  67668. {
  67669. dest++ ->blend (*span++);
  67670. } while (--width > 0);
  67671. }
  67672. }
  67673. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67674. {
  67675. handleEdgeTableLine (x, width, 255);
  67676. }
  67677. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67678. {
  67679. if (width > scratchSize)
  67680. {
  67681. scratchSize = width;
  67682. scratchBuffer.malloc (scratchSize);
  67683. }
  67684. y = y_;
  67685. generate (scratchBuffer.getData(), x, width);
  67686. et.clipLineToMask (x, y_,
  67687. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67688. sizeof (SrcPixelType), width);
  67689. }
  67690. private:
  67691. template <class PixelType>
  67692. void generate (PixelType* dest, const int x, int numPixels) throw()
  67693. {
  67694. this->interpolator.setStartOfLine ((float) x, (float) y, numPixels);
  67695. do
  67696. {
  67697. int hiResX, hiResY;
  67698. this->interpolator.next (hiResX, hiResY);
  67699. int loResX = hiResX >> 8;
  67700. int loResY = hiResY >> 8;
  67701. if (repeatPattern)
  67702. {
  67703. loResX = RenderingHelpers::safeModulo (loResX, srcData.width);
  67704. loResY = RenderingHelpers::safeModulo (loResY, srcData.height);
  67705. }
  67706. if (betterQuality)
  67707. {
  67708. if (isPositiveAndBelow (loResX, maxX))
  67709. {
  67710. if (isPositiveAndBelow (loResY, maxY))
  67711. {
  67712. // In the centre of the image..
  67713. render4PixelAverage (dest, this->srcData.getPixelPointer (loResX, loResY),
  67714. hiResX & 255, hiResY & 255);
  67715. ++dest;
  67716. continue;
  67717. }
  67718. else
  67719. {
  67720. // At a top or bottom edge..
  67721. if (! repeatPattern)
  67722. {
  67723. if (loResY < 0)
  67724. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, 0), hiResX & 255, hiResY & 255);
  67725. else
  67726. render2PixelAverageX (dest, this->srcData.getPixelPointer (loResX, maxY), hiResX & 255, 255 - (hiResY & 255));
  67727. ++dest;
  67728. continue;
  67729. }
  67730. }
  67731. }
  67732. else
  67733. {
  67734. if (isPositiveAndBelow (loResY, maxY))
  67735. {
  67736. // At a left or right hand edge..
  67737. if (! repeatPattern)
  67738. {
  67739. if (loResX < 0)
  67740. render2PixelAverageY (dest, this->srcData.getPixelPointer (0, loResY), hiResY & 255, hiResX & 255);
  67741. else
  67742. render2PixelAverageY (dest, this->srcData.getPixelPointer (maxX, loResY), hiResY & 255, 255 - (hiResX & 255));
  67743. ++dest;
  67744. continue;
  67745. }
  67746. }
  67747. }
  67748. }
  67749. if (! repeatPattern)
  67750. {
  67751. if (loResX < 0) loResX = 0;
  67752. if (loResY < 0) loResY = 0;
  67753. if (loResX > maxX) loResX = maxX;
  67754. if (loResY > maxY) loResY = maxY;
  67755. }
  67756. dest->set (*(const PixelType*) this->srcData.getPixelPointer (loResX, loResY));
  67757. ++dest;
  67758. } while (--numPixels > 0);
  67759. }
  67760. void render4PixelAverage (PixelARGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67761. {
  67762. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67763. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67764. c[0] += weight * src[0];
  67765. c[1] += weight * src[1];
  67766. c[2] += weight * src[2];
  67767. c[3] += weight * src[3];
  67768. weight = subPixelX * (256 - subPixelY);
  67769. c[0] += weight * src[4];
  67770. c[1] += weight * src[5];
  67771. c[2] += weight * src[6];
  67772. c[3] += weight * src[7];
  67773. src += this->srcData.lineStride;
  67774. weight = (256 - subPixelX) * subPixelY;
  67775. c[0] += weight * src[0];
  67776. c[1] += weight * src[1];
  67777. c[2] += weight * src[2];
  67778. c[3] += weight * src[3];
  67779. weight = subPixelX * subPixelY;
  67780. c[0] += weight * src[4];
  67781. c[1] += weight * src[5];
  67782. c[2] += weight * src[6];
  67783. c[3] += weight * src[7];
  67784. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67785. (uint8) (c[PixelARGB::indexR] >> 16),
  67786. (uint8) (c[PixelARGB::indexG] >> 16),
  67787. (uint8) (c[PixelARGB::indexB] >> 16));
  67788. }
  67789. void render2PixelAverageX (PixelARGB* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67790. {
  67791. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67792. uint32 weight = (256 - subPixelX) * alpha;
  67793. c[0] += weight * src[0];
  67794. c[1] += weight * src[1];
  67795. c[2] += weight * src[2];
  67796. c[3] += weight * src[3];
  67797. weight = subPixelX * alpha;
  67798. c[0] += weight * src[4];
  67799. c[1] += weight * src[5];
  67800. c[2] += weight * src[6];
  67801. c[3] += weight * src[7];
  67802. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67803. (uint8) (c[PixelARGB::indexR] >> 16),
  67804. (uint8) (c[PixelARGB::indexG] >> 16),
  67805. (uint8) (c[PixelARGB::indexB] >> 16));
  67806. }
  67807. void render2PixelAverageY (PixelARGB* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67808. {
  67809. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67810. uint32 weight = (256 - subPixelY) * alpha;
  67811. c[0] += weight * src[0];
  67812. c[1] += weight * src[1];
  67813. c[2] += weight * src[2];
  67814. c[3] += weight * src[3];
  67815. src += this->srcData.lineStride;
  67816. weight = subPixelY * alpha;
  67817. c[0] += weight * src[0];
  67818. c[1] += weight * src[1];
  67819. c[2] += weight * src[2];
  67820. c[3] += weight * src[3];
  67821. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67822. (uint8) (c[PixelARGB::indexR] >> 16),
  67823. (uint8) (c[PixelARGB::indexG] >> 16),
  67824. (uint8) (c[PixelARGB::indexB] >> 16));
  67825. }
  67826. void render4PixelAverage (PixelRGB* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67827. {
  67828. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  67829. uint32 weight = (256 - subPixelX) * (256 - subPixelY);
  67830. c[0] += weight * src[0];
  67831. c[1] += weight * src[1];
  67832. c[2] += weight * src[2];
  67833. weight = subPixelX * (256 - subPixelY);
  67834. c[0] += weight * src[3];
  67835. c[1] += weight * src[4];
  67836. c[2] += weight * src[5];
  67837. src += this->srcData.lineStride;
  67838. weight = (256 - subPixelX) * subPixelY;
  67839. c[0] += weight * src[0];
  67840. c[1] += weight * src[1];
  67841. c[2] += weight * src[2];
  67842. weight = subPixelX * subPixelY;
  67843. c[0] += weight * src[3];
  67844. c[1] += weight * src[4];
  67845. c[2] += weight * src[5];
  67846. dest->setARGB ((uint8) 255,
  67847. (uint8) (c[PixelRGB::indexR] >> 16),
  67848. (uint8) (c[PixelRGB::indexG] >> 16),
  67849. (uint8) (c[PixelRGB::indexB] >> 16));
  67850. }
  67851. void render2PixelAverageX (PixelRGB* const dest, const uint8* src, const int subPixelX, const int /*alpha*/) throw()
  67852. {
  67853. uint32 c[3] = { 128, 128, 128 };
  67854. uint32 weight = (256 - subPixelX);
  67855. c[0] += weight * src[0];
  67856. c[1] += weight * src[1];
  67857. c[2] += weight * src[2];
  67858. c[0] += subPixelX * src[3];
  67859. c[1] += subPixelX * src[4];
  67860. c[2] += subPixelX * src[5];
  67861. dest->setARGB ((uint8) 255,
  67862. (uint8) (c[PixelRGB::indexR] >> 8),
  67863. (uint8) (c[PixelRGB::indexG] >> 8),
  67864. (uint8) (c[PixelRGB::indexB] >> 8));
  67865. }
  67866. void render2PixelAverageY (PixelRGB* const dest, const uint8* src, const int subPixelY, const int /*alpha*/) throw()
  67867. {
  67868. uint32 c[3] = { 128, 128, 128 };
  67869. uint32 weight = (256 - subPixelY);
  67870. c[0] += weight * src[0];
  67871. c[1] += weight * src[1];
  67872. c[2] += weight * src[2];
  67873. src += this->srcData.lineStride;
  67874. c[0] += subPixelY * src[0];
  67875. c[1] += subPixelY * src[1];
  67876. c[2] += subPixelY * src[2];
  67877. dest->setARGB ((uint8) 255,
  67878. (uint8) (c[PixelRGB::indexR] >> 8),
  67879. (uint8) (c[PixelRGB::indexG] >> 8),
  67880. (uint8) (c[PixelRGB::indexB] >> 8));
  67881. }
  67882. void render4PixelAverage (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int subPixelY) throw()
  67883. {
  67884. uint32 c = 256 * 128;
  67885. c += src[0] * ((256 - subPixelX) * (256 - subPixelY));
  67886. c += src[1] * (subPixelX * (256 - subPixelY));
  67887. src += this->srcData.lineStride;
  67888. c += src[0] * ((256 - subPixelX) * subPixelY);
  67889. c += src[1] * (subPixelX * subPixelY);
  67890. *((uint8*) dest) = (uint8) (c >> 16);
  67891. }
  67892. void render2PixelAverageX (PixelAlpha* const dest, const uint8* src, const int subPixelX, const int alpha) throw()
  67893. {
  67894. uint32 c = 256 * 128;
  67895. c += src[0] * (256 - subPixelX) * alpha;
  67896. c += src[1] * subPixelX * alpha;
  67897. *((uint8*) dest) = (uint8) (c >> 16);
  67898. }
  67899. void render2PixelAverageY (PixelAlpha* const dest, const uint8* src, const int subPixelY, const int alpha) throw()
  67900. {
  67901. uint32 c = 256 * 128;
  67902. c += src[0] * (256 - subPixelY) * alpha;
  67903. src += this->srcData.lineStride;
  67904. c += src[0] * subPixelY * alpha;
  67905. *((uint8*) dest) = (uint8) (c >> 16);
  67906. }
  67907. class TransformedImageSpanInterpolator
  67908. {
  67909. public:
  67910. TransformedImageSpanInterpolator (const AffineTransform& transform, const float pixelOffset_, const int pixelOffsetInt_) throw()
  67911. : inverseTransform (transform.inverted()),
  67912. pixelOffset (pixelOffset_), pixelOffsetInt (pixelOffsetInt_)
  67913. {}
  67914. void setStartOfLine (float x, float y, const int numPixels) throw()
  67915. {
  67916. jassert (numPixels > 0);
  67917. x += pixelOffset;
  67918. y += pixelOffset;
  67919. float x1 = x, y1 = y;
  67920. x += numPixels;
  67921. inverseTransform.transformPoints (x1, y1, x, y);
  67922. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels, pixelOffsetInt);
  67923. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels, pixelOffsetInt);
  67924. }
  67925. void next (int& x, int& y) throw()
  67926. {
  67927. x = xBresenham.n;
  67928. xBresenham.stepToNext();
  67929. y = yBresenham.n;
  67930. yBresenham.stepToNext();
  67931. }
  67932. private:
  67933. class BresenhamInterpolator
  67934. {
  67935. public:
  67936. BresenhamInterpolator() throw() {}
  67937. void set (const int n1, const int n2, const int numSteps_, const int pixelOffsetInt) throw()
  67938. {
  67939. numSteps = numSteps_;
  67940. step = (n2 - n1) / numSteps;
  67941. remainder = modulo = (n2 - n1) % numSteps;
  67942. n = n1 + pixelOffsetInt;
  67943. if (modulo <= 0)
  67944. {
  67945. modulo += numSteps;
  67946. remainder += numSteps;
  67947. --step;
  67948. }
  67949. modulo -= numSteps;
  67950. }
  67951. forcedinline void stepToNext() throw()
  67952. {
  67953. modulo += remainder;
  67954. n += step;
  67955. if (modulo > 0)
  67956. {
  67957. modulo -= numSteps;
  67958. ++n;
  67959. }
  67960. }
  67961. int n;
  67962. private:
  67963. int numSteps, step, modulo, remainder;
  67964. };
  67965. const AffineTransform inverseTransform;
  67966. BresenhamInterpolator xBresenham, yBresenham;
  67967. const float pixelOffset;
  67968. const int pixelOffsetInt;
  67969. JUCE_DECLARE_NON_COPYABLE (TransformedImageSpanInterpolator);
  67970. };
  67971. TransformedImageSpanInterpolator interpolator;
  67972. const Image::BitmapData& destData;
  67973. const Image::BitmapData& srcData;
  67974. const int extraAlpha;
  67975. const bool betterQuality;
  67976. const int maxX, maxY;
  67977. int y;
  67978. DestPixelType* linePixels;
  67979. HeapBlock <SrcPixelType> scratchBuffer;
  67980. int scratchSize;
  67981. JUCE_DECLARE_NON_COPYABLE (TransformedImageFillEdgeTableRenderer);
  67982. };
  67983. class ClipRegionBase : public ReferenceCountedObject
  67984. {
  67985. public:
  67986. ClipRegionBase() {}
  67987. virtual ~ClipRegionBase() {}
  67988. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  67989. virtual const Ptr clone() const = 0;
  67990. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  67991. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  67992. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  67993. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  67994. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  67995. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  67996. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  67997. virtual const Ptr translated (const Point<int>& delta) = 0;
  67998. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  67999. virtual const Rectangle<int> getClipBounds() const = 0;
  68000. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68001. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68002. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68003. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68004. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68005. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68006. protected:
  68007. template <class Iterator>
  68008. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68009. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68010. {
  68011. switch (destData.pixelFormat)
  68012. {
  68013. case Image::ARGB:
  68014. switch (srcData.pixelFormat)
  68015. {
  68016. case Image::ARGB:
  68017. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68018. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68019. break;
  68020. case Image::RGB:
  68021. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68022. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68023. break;
  68024. default:
  68025. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68026. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68027. break;
  68028. }
  68029. break;
  68030. case Image::RGB:
  68031. switch (srcData.pixelFormat)
  68032. {
  68033. case Image::ARGB:
  68034. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68035. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68036. break;
  68037. case Image::RGB:
  68038. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68039. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68040. break;
  68041. default:
  68042. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68043. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68044. break;
  68045. }
  68046. break;
  68047. default:
  68048. switch (srcData.pixelFormat)
  68049. {
  68050. case Image::ARGB:
  68051. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68052. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68053. break;
  68054. case Image::RGB:
  68055. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68056. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68057. break;
  68058. default:
  68059. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68060. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68061. break;
  68062. }
  68063. break;
  68064. }
  68065. }
  68066. template <class Iterator>
  68067. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68068. {
  68069. switch (destData.pixelFormat)
  68070. {
  68071. case Image::ARGB:
  68072. switch (srcData.pixelFormat)
  68073. {
  68074. case Image::ARGB:
  68075. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68076. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68077. break;
  68078. case Image::RGB:
  68079. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68080. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68081. break;
  68082. default:
  68083. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68084. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68085. break;
  68086. }
  68087. break;
  68088. case Image::RGB:
  68089. switch (srcData.pixelFormat)
  68090. {
  68091. case Image::ARGB:
  68092. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68093. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68094. break;
  68095. case Image::RGB:
  68096. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68097. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68098. break;
  68099. default:
  68100. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68101. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68102. break;
  68103. }
  68104. break;
  68105. default:
  68106. switch (srcData.pixelFormat)
  68107. {
  68108. case Image::ARGB:
  68109. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68110. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68111. break;
  68112. case Image::RGB:
  68113. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68114. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68115. break;
  68116. default:
  68117. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68118. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68119. break;
  68120. }
  68121. break;
  68122. }
  68123. }
  68124. template <class Iterator, class DestPixelType>
  68125. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68126. {
  68127. jassert (destData.pixelStride == sizeof (DestPixelType));
  68128. if (replaceContents)
  68129. {
  68130. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68131. iter.iterate (r);
  68132. }
  68133. else
  68134. {
  68135. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68136. iter.iterate (r);
  68137. }
  68138. }
  68139. template <class Iterator, class DestPixelType>
  68140. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68141. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68142. {
  68143. jassert (destData.pixelStride == sizeof (DestPixelType));
  68144. if (g.isRadial)
  68145. {
  68146. if (isIdentity)
  68147. {
  68148. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68149. iter.iterate (renderer);
  68150. }
  68151. else
  68152. {
  68153. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68154. iter.iterate (renderer);
  68155. }
  68156. }
  68157. else
  68158. {
  68159. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68160. iter.iterate (renderer);
  68161. }
  68162. }
  68163. };
  68164. class ClipRegion_EdgeTable : public ClipRegionBase
  68165. {
  68166. public:
  68167. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68168. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68169. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68170. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68171. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68172. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68173. ~ClipRegion_EdgeTable() {}
  68174. const Ptr clone() const
  68175. {
  68176. return new ClipRegion_EdgeTable (*this);
  68177. }
  68178. const Ptr applyClipTo (const Ptr& target) const
  68179. {
  68180. return target->clipToEdgeTable (edgeTable);
  68181. }
  68182. const Ptr clipToRectangle (const Rectangle<int>& r)
  68183. {
  68184. edgeTable.clipToRectangle (r);
  68185. return edgeTable.isEmpty() ? 0 : this;
  68186. }
  68187. const Ptr clipToRectangleList (const RectangleList& r)
  68188. {
  68189. RectangleList inverse (edgeTable.getMaximumBounds());
  68190. if (inverse.subtract (r))
  68191. for (RectangleList::Iterator iter (inverse); iter.next();)
  68192. edgeTable.excludeRectangle (*iter.getRectangle());
  68193. return edgeTable.isEmpty() ? 0 : this;
  68194. }
  68195. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68196. {
  68197. edgeTable.excludeRectangle (r);
  68198. return edgeTable.isEmpty() ? 0 : this;
  68199. }
  68200. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68201. {
  68202. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68203. edgeTable.clipToEdgeTable (et);
  68204. return edgeTable.isEmpty() ? 0 : this;
  68205. }
  68206. const Ptr clipToEdgeTable (const EdgeTable& et)
  68207. {
  68208. edgeTable.clipToEdgeTable (et);
  68209. return edgeTable.isEmpty() ? 0 : this;
  68210. }
  68211. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68212. {
  68213. const Image::BitmapData srcData (image, false);
  68214. if (transform.isOnlyTranslation())
  68215. {
  68216. // If our translation doesn't involve any distortion, just use a simple blit..
  68217. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68218. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68219. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68220. {
  68221. const int imageX = ((tx + 128) >> 8);
  68222. const int imageY = ((ty + 128) >> 8);
  68223. if (image.getFormat() == Image::ARGB)
  68224. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68225. else
  68226. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68227. return edgeTable.isEmpty() ? 0 : this;
  68228. }
  68229. }
  68230. if (transform.isSingularity())
  68231. return 0;
  68232. {
  68233. Path p;
  68234. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68235. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68236. edgeTable.clipToEdgeTable (et2);
  68237. }
  68238. if (! edgeTable.isEmpty())
  68239. {
  68240. if (image.getFormat() == Image::ARGB)
  68241. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68242. else
  68243. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68244. }
  68245. return edgeTable.isEmpty() ? 0 : this;
  68246. }
  68247. const Ptr translated (const Point<int>& delta)
  68248. {
  68249. edgeTable.translate ((float) delta.getX(), delta.getY());
  68250. return edgeTable.isEmpty() ? 0 : this;
  68251. }
  68252. bool clipRegionIntersects (const Rectangle<int>& r) const
  68253. {
  68254. return edgeTable.getMaximumBounds().intersects (r);
  68255. }
  68256. const Rectangle<int> getClipBounds() const
  68257. {
  68258. return edgeTable.getMaximumBounds();
  68259. }
  68260. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68261. {
  68262. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68263. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68264. if (! clipped.isEmpty())
  68265. {
  68266. ClipRegion_EdgeTable et (clipped);
  68267. et.edgeTable.clipToEdgeTable (edgeTable);
  68268. et.fillAllWithColour (destData, colour, replaceContents);
  68269. }
  68270. }
  68271. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68272. {
  68273. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68274. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68275. if (! clipped.isEmpty())
  68276. {
  68277. ClipRegion_EdgeTable et (clipped);
  68278. et.edgeTable.clipToEdgeTable (edgeTable);
  68279. et.fillAllWithColour (destData, colour, false);
  68280. }
  68281. }
  68282. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68283. {
  68284. switch (destData.pixelFormat)
  68285. {
  68286. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68287. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68288. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68289. }
  68290. }
  68291. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68292. {
  68293. HeapBlock <PixelARGB> lookupTable;
  68294. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68295. jassert (numLookupEntries > 0);
  68296. switch (destData.pixelFormat)
  68297. {
  68298. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68299. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68300. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68301. }
  68302. }
  68303. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68304. {
  68305. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68306. }
  68307. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68308. {
  68309. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68310. }
  68311. EdgeTable edgeTable;
  68312. private:
  68313. template <class SrcPixelType>
  68314. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68315. {
  68316. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68317. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68318. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68319. edgeTable.getMaximumBounds().getWidth());
  68320. }
  68321. template <class SrcPixelType>
  68322. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68323. {
  68324. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68325. edgeTable.clipToRectangle (r);
  68326. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68327. for (int y = 0; y < r.getHeight(); ++y)
  68328. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68329. }
  68330. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68331. };
  68332. class ClipRegion_RectangleList : public ClipRegionBase
  68333. {
  68334. public:
  68335. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68336. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68337. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68338. ~ClipRegion_RectangleList() {}
  68339. const Ptr clone() const
  68340. {
  68341. return new ClipRegion_RectangleList (*this);
  68342. }
  68343. const Ptr applyClipTo (const Ptr& target) const
  68344. {
  68345. return target->clipToRectangleList (clip);
  68346. }
  68347. const Ptr clipToRectangle (const Rectangle<int>& r)
  68348. {
  68349. clip.clipTo (r);
  68350. return clip.isEmpty() ? 0 : this;
  68351. }
  68352. const Ptr clipToRectangleList (const RectangleList& r)
  68353. {
  68354. clip.clipTo (r);
  68355. return clip.isEmpty() ? 0 : this;
  68356. }
  68357. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68358. {
  68359. clip.subtract (r);
  68360. return clip.isEmpty() ? 0 : this;
  68361. }
  68362. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68363. {
  68364. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68365. }
  68366. const Ptr clipToEdgeTable (const EdgeTable& et)
  68367. {
  68368. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68369. }
  68370. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68371. {
  68372. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68373. }
  68374. const Ptr translated (const Point<int>& delta)
  68375. {
  68376. clip.offsetAll (delta.getX(), delta.getY());
  68377. return clip.isEmpty() ? 0 : this;
  68378. }
  68379. bool clipRegionIntersects (const Rectangle<int>& r) const
  68380. {
  68381. return clip.intersects (r);
  68382. }
  68383. const Rectangle<int> getClipBounds() const
  68384. {
  68385. return clip.getBounds();
  68386. }
  68387. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68388. {
  68389. SubRectangleIterator iter (clip, area);
  68390. switch (destData.pixelFormat)
  68391. {
  68392. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68393. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68394. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68395. }
  68396. }
  68397. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68398. {
  68399. SubRectangleIteratorFloat iter (clip, area);
  68400. switch (destData.pixelFormat)
  68401. {
  68402. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68403. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68404. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68405. }
  68406. }
  68407. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68408. {
  68409. switch (destData.pixelFormat)
  68410. {
  68411. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68412. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68413. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68414. }
  68415. }
  68416. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68417. {
  68418. HeapBlock <PixelARGB> lookupTable;
  68419. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68420. jassert (numLookupEntries > 0);
  68421. switch (destData.pixelFormat)
  68422. {
  68423. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68424. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68425. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68426. }
  68427. }
  68428. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68429. {
  68430. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68431. }
  68432. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68433. {
  68434. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68435. }
  68436. RectangleList clip;
  68437. template <class Renderer>
  68438. void iterate (Renderer& r) const throw()
  68439. {
  68440. RectangleList::Iterator iter (clip);
  68441. while (iter.next())
  68442. {
  68443. const Rectangle<int> rect (*iter.getRectangle());
  68444. const int x = rect.getX();
  68445. const int w = rect.getWidth();
  68446. jassert (w > 0);
  68447. const int bottom = rect.getBottom();
  68448. for (int y = rect.getY(); y < bottom; ++y)
  68449. {
  68450. r.setEdgeTableYPos (y);
  68451. r.handleEdgeTableLineFull (x, w);
  68452. }
  68453. }
  68454. }
  68455. private:
  68456. class SubRectangleIterator
  68457. {
  68458. public:
  68459. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68460. : clip (clip_), area (area_)
  68461. {
  68462. }
  68463. template <class Renderer>
  68464. void iterate (Renderer& r) const throw()
  68465. {
  68466. RectangleList::Iterator iter (clip);
  68467. while (iter.next())
  68468. {
  68469. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68470. if (! rect.isEmpty())
  68471. {
  68472. const int x = rect.getX();
  68473. const int w = rect.getWidth();
  68474. const int bottom = rect.getBottom();
  68475. for (int y = rect.getY(); y < bottom; ++y)
  68476. {
  68477. r.setEdgeTableYPos (y);
  68478. r.handleEdgeTableLineFull (x, w);
  68479. }
  68480. }
  68481. }
  68482. }
  68483. private:
  68484. const RectangleList& clip;
  68485. const Rectangle<int> area;
  68486. JUCE_DECLARE_NON_COPYABLE (SubRectangleIterator);
  68487. };
  68488. class SubRectangleIteratorFloat
  68489. {
  68490. public:
  68491. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68492. : clip (clip_), area (area_)
  68493. {
  68494. }
  68495. template <class Renderer>
  68496. void iterate (Renderer& r) const throw()
  68497. {
  68498. int left = roundToInt (area.getX() * 256.0f);
  68499. int top = roundToInt (area.getY() * 256.0f);
  68500. int right = roundToInt (area.getRight() * 256.0f);
  68501. int bottom = roundToInt (area.getBottom() * 256.0f);
  68502. int totalTop, totalLeft, totalBottom, totalRight;
  68503. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68504. if ((top >> 8) == (bottom >> 8))
  68505. {
  68506. topAlpha = bottom - top;
  68507. bottomAlpha = 0;
  68508. totalTop = top >> 8;
  68509. totalBottom = bottom = top = totalTop + 1;
  68510. }
  68511. else
  68512. {
  68513. if ((top & 255) == 0)
  68514. {
  68515. topAlpha = 0;
  68516. top = totalTop = (top >> 8);
  68517. }
  68518. else
  68519. {
  68520. topAlpha = 255 - (top & 255);
  68521. totalTop = (top >> 8);
  68522. top = totalTop + 1;
  68523. }
  68524. bottomAlpha = bottom & 255;
  68525. bottom >>= 8;
  68526. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68527. }
  68528. if ((left >> 8) == (right >> 8))
  68529. {
  68530. leftAlpha = right - left;
  68531. rightAlpha = 0;
  68532. totalLeft = (left >> 8);
  68533. totalRight = right = left = totalLeft + 1;
  68534. }
  68535. else
  68536. {
  68537. if ((left & 255) == 0)
  68538. {
  68539. leftAlpha = 0;
  68540. left = totalLeft = (left >> 8);
  68541. }
  68542. else
  68543. {
  68544. leftAlpha = 255 - (left & 255);
  68545. totalLeft = (left >> 8);
  68546. left = totalLeft + 1;
  68547. }
  68548. rightAlpha = right & 255;
  68549. right >>= 8;
  68550. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68551. }
  68552. RectangleList::Iterator iter (clip);
  68553. while (iter.next())
  68554. {
  68555. const int clipLeft = iter.getRectangle()->getX();
  68556. const int clipRight = iter.getRectangle()->getRight();
  68557. const int clipTop = iter.getRectangle()->getY();
  68558. const int clipBottom = iter.getRectangle()->getBottom();
  68559. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68560. {
  68561. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68562. {
  68563. if (topAlpha != 0 && totalTop >= clipTop)
  68564. {
  68565. r.setEdgeTableYPos (totalTop);
  68566. r.handleEdgeTablePixel (left, topAlpha);
  68567. }
  68568. const int endY = jmin (bottom, clipBottom);
  68569. for (int y = jmax (clipTop, top); y < endY; ++y)
  68570. {
  68571. r.setEdgeTableYPos (y);
  68572. r.handleEdgeTablePixelFull (left);
  68573. }
  68574. if (bottomAlpha != 0 && bottom < clipBottom)
  68575. {
  68576. r.setEdgeTableYPos (bottom);
  68577. r.handleEdgeTablePixel (left, bottomAlpha);
  68578. }
  68579. }
  68580. else
  68581. {
  68582. const int clippedLeft = jmax (left, clipLeft);
  68583. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68584. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68585. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68586. if (topAlpha != 0 && totalTop >= clipTop)
  68587. {
  68588. r.setEdgeTableYPos (totalTop);
  68589. if (doLeftAlpha)
  68590. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68591. if (clippedWidth > 0)
  68592. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68593. if (doRightAlpha)
  68594. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68595. }
  68596. const int endY = jmin (bottom, clipBottom);
  68597. for (int y = jmax (clipTop, top); y < endY; ++y)
  68598. {
  68599. r.setEdgeTableYPos (y);
  68600. if (doLeftAlpha)
  68601. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68602. if (clippedWidth > 0)
  68603. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68604. if (doRightAlpha)
  68605. r.handleEdgeTablePixel (right, rightAlpha);
  68606. }
  68607. if (bottomAlpha != 0 && bottom < clipBottom)
  68608. {
  68609. r.setEdgeTableYPos (bottom);
  68610. if (doLeftAlpha)
  68611. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68612. if (clippedWidth > 0)
  68613. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68614. if (doRightAlpha)
  68615. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68616. }
  68617. }
  68618. }
  68619. }
  68620. }
  68621. private:
  68622. const RectangleList& clip;
  68623. const Rectangle<float>& area;
  68624. JUCE_DECLARE_NON_COPYABLE (SubRectangleIteratorFloat);
  68625. };
  68626. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68627. };
  68628. }
  68629. class LowLevelGraphicsSoftwareRenderer::SavedState
  68630. {
  68631. public:
  68632. SavedState (const Image& image_, const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68633. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68634. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68635. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68636. {
  68637. }
  68638. SavedState (const Image& image_, const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68639. : image (image_), clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68640. xOffset (xOffset_), yOffset (yOffset_), compositionAlpha (1.0f),
  68641. isOnlyTranslated (true), interpolationQuality (Graphics::mediumResamplingQuality)
  68642. {
  68643. }
  68644. SavedState (const SavedState& other)
  68645. : image (other.image), clip (other.clip), complexTransform (other.complexTransform),
  68646. xOffset (other.xOffset), yOffset (other.yOffset), compositionAlpha (other.compositionAlpha),
  68647. isOnlyTranslated (other.isOnlyTranslated), font (other.font), fillType (other.fillType),
  68648. interpolationQuality (other.interpolationQuality)
  68649. {
  68650. }
  68651. void setOrigin (const int x, const int y) throw()
  68652. {
  68653. if (isOnlyTranslated)
  68654. {
  68655. xOffset += x;
  68656. yOffset += y;
  68657. }
  68658. else
  68659. {
  68660. complexTransform = getTransformWith (AffineTransform::translation ((float) x, (float) y));
  68661. }
  68662. }
  68663. void addTransform (const AffineTransform& t)
  68664. {
  68665. if ((! isOnlyTranslated)
  68666. || (! t.isOnlyTranslation())
  68667. || (int) (t.getTranslationX() * 256.0f) != 0
  68668. || (int) (t.getTranslationY() * 256.0f) != 0)
  68669. {
  68670. complexTransform = getTransformWith (t);
  68671. isOnlyTranslated = false;
  68672. }
  68673. else
  68674. {
  68675. xOffset += (int) t.getTranslationX();
  68676. yOffset += (int) t.getTranslationY();
  68677. }
  68678. }
  68679. float getScaleFactor() const
  68680. {
  68681. return isOnlyTranslated ? 1.0f : complexTransform.getScaleFactor();
  68682. }
  68683. bool clipToRectangle (const Rectangle<int>& r)
  68684. {
  68685. if (clip != 0)
  68686. {
  68687. if (isOnlyTranslated)
  68688. {
  68689. cloneClipIfMultiplyReferenced();
  68690. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68691. }
  68692. else
  68693. {
  68694. Path p;
  68695. p.addRectangle (r);
  68696. clipToPath (p, AffineTransform::identity);
  68697. }
  68698. }
  68699. return clip != 0;
  68700. }
  68701. bool clipToRectangleList (const RectangleList& r)
  68702. {
  68703. if (clip != 0)
  68704. {
  68705. if (isOnlyTranslated)
  68706. {
  68707. cloneClipIfMultiplyReferenced();
  68708. RectangleList offsetList (r);
  68709. offsetList.offsetAll (xOffset, yOffset);
  68710. clip = clip->clipToRectangleList (offsetList);
  68711. }
  68712. else
  68713. {
  68714. clipToPath (r.toPath(), AffineTransform::identity);
  68715. }
  68716. }
  68717. return clip != 0;
  68718. }
  68719. bool excludeClipRectangle (const Rectangle<int>& r)
  68720. {
  68721. if (clip != 0)
  68722. {
  68723. cloneClipIfMultiplyReferenced();
  68724. if (isOnlyTranslated)
  68725. {
  68726. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68727. }
  68728. else
  68729. {
  68730. Path p;
  68731. p.addRectangle (r.toFloat());
  68732. p.applyTransform (complexTransform);
  68733. p.addRectangle (clip->getClipBounds().toFloat());
  68734. p.setUsingNonZeroWinding (false);
  68735. clip = clip->clipToPath (p, AffineTransform::identity);
  68736. }
  68737. }
  68738. return clip != 0;
  68739. }
  68740. void clipToPath (const Path& p, const AffineTransform& transform)
  68741. {
  68742. if (clip != 0)
  68743. {
  68744. cloneClipIfMultiplyReferenced();
  68745. clip = clip->clipToPath (p, getTransformWith (transform));
  68746. }
  68747. }
  68748. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& t)
  68749. {
  68750. if (clip != 0)
  68751. {
  68752. if (sourceImage.hasAlphaChannel())
  68753. {
  68754. cloneClipIfMultiplyReferenced();
  68755. clip = clip->clipToImageAlpha (sourceImage, getTransformWith (t),
  68756. interpolationQuality != Graphics::lowResamplingQuality);
  68757. }
  68758. else
  68759. {
  68760. Path p;
  68761. p.addRectangle (sourceImage.getBounds());
  68762. clipToPath (p, t);
  68763. }
  68764. }
  68765. }
  68766. bool clipRegionIntersects (const Rectangle<int>& r) const
  68767. {
  68768. if (clip != 0)
  68769. {
  68770. if (isOnlyTranslated)
  68771. return clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68772. else
  68773. return getClipBounds().intersects (r);
  68774. }
  68775. return false;
  68776. }
  68777. const Rectangle<int> getUntransformedClipBounds() const
  68778. {
  68779. return clip != 0 ? clip->getClipBounds() : Rectangle<int>();
  68780. }
  68781. const Rectangle<int> getClipBounds() const
  68782. {
  68783. if (clip != 0)
  68784. {
  68785. if (isOnlyTranslated)
  68786. return clip->getClipBounds().translated (-xOffset, -yOffset);
  68787. else
  68788. return clip->getClipBounds().toFloat().transformed (complexTransform.inverted()).getSmallestIntegerContainer();
  68789. }
  68790. return Rectangle<int>();
  68791. }
  68792. SavedState* beginTransparencyLayer (float opacity)
  68793. {
  68794. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68795. SavedState* s = new SavedState (*this);
  68796. s->image = Image (Image::ARGB, layerBounds.getWidth(), layerBounds.getHeight(), true);
  68797. s->compositionAlpha = opacity;
  68798. if (s->isOnlyTranslated)
  68799. {
  68800. s->xOffset -= layerBounds.getX();
  68801. s->yOffset -= layerBounds.getY();
  68802. }
  68803. else
  68804. {
  68805. s->complexTransform = s->complexTransform.followedBy (AffineTransform::translation ((float) -layerBounds.getX(),
  68806. (float) -layerBounds.getY()));
  68807. }
  68808. s->cloneClipIfMultiplyReferenced();
  68809. s->clip = s->clip->translated (-layerBounds.getPosition());
  68810. return s;
  68811. }
  68812. void endTransparencyLayer (SavedState& layerState)
  68813. {
  68814. const Rectangle<int> layerBounds (getUntransformedClipBounds());
  68815. const ScopedPointer<LowLevelGraphicsContext> g (image.createLowLevelContext());
  68816. g->setOpacity (layerState.compositionAlpha);
  68817. g->drawImage (layerState.image, AffineTransform::translation ((float) layerBounds.getX(),
  68818. (float) layerBounds.getY()), false);
  68819. }
  68820. void fillRect (const Rectangle<int>& r, const bool replaceContents)
  68821. {
  68822. if (clip != 0)
  68823. {
  68824. if (isOnlyTranslated)
  68825. {
  68826. if (fillType.isColour())
  68827. {
  68828. Image::BitmapData destData (image, true);
  68829. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68830. }
  68831. else
  68832. {
  68833. const Rectangle<int> totalClip (clip->getClipBounds());
  68834. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68835. if (! clipped.isEmpty())
  68836. fillShape (new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68837. }
  68838. }
  68839. else
  68840. {
  68841. Path p;
  68842. p.addRectangle (r);
  68843. fillPath (p, AffineTransform::identity);
  68844. }
  68845. }
  68846. }
  68847. void fillRect (const Rectangle<float>& r)
  68848. {
  68849. if (clip != 0)
  68850. {
  68851. if (isOnlyTranslated)
  68852. {
  68853. if (fillType.isColour())
  68854. {
  68855. Image::BitmapData destData (image, true);
  68856. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68857. }
  68858. else
  68859. {
  68860. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68861. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68862. if (! clipped.isEmpty())
  68863. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68864. }
  68865. }
  68866. else
  68867. {
  68868. Path p;
  68869. p.addRectangle (r);
  68870. fillPath (p, AffineTransform::identity);
  68871. }
  68872. }
  68873. }
  68874. void fillPath (const Path& path, const AffineTransform& transform)
  68875. {
  68876. if (clip != 0)
  68877. fillShape (new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, getTransformWith (transform)), false);
  68878. }
  68879. void fillEdgeTable (const EdgeTable& edgeTable, const float x, const int y)
  68880. {
  68881. jassert (isOnlyTranslated);
  68882. if (clip != 0)
  68883. {
  68884. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68885. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68886. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68887. fillShape (shapeToFill, false);
  68888. }
  68889. }
  68890. void fillShape (SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68891. {
  68892. jassert (clip != 0);
  68893. shapeToFill = clip->applyClipTo (shapeToFill);
  68894. if (shapeToFill != 0)
  68895. {
  68896. Image::BitmapData destData (image, true);
  68897. if (fillType.isGradient())
  68898. {
  68899. jassert (! replaceContents); // that option is just for solid colours
  68900. ColourGradient g2 (*(fillType.gradient));
  68901. g2.multiplyOpacity (fillType.getOpacity());
  68902. AffineTransform transform (getTransformWith (fillType.transform).translated (-0.5f, -0.5f));
  68903. const bool isIdentity = transform.isOnlyTranslation();
  68904. if (isIdentity)
  68905. {
  68906. // If our translation doesn't involve any distortion, we can speed it up..
  68907. g2.point1.applyTransform (transform);
  68908. g2.point2.applyTransform (transform);
  68909. transform = AffineTransform::identity;
  68910. }
  68911. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68912. }
  68913. else if (fillType.isTiledImage())
  68914. {
  68915. renderImage (fillType.image, fillType.transform, shapeToFill);
  68916. }
  68917. else
  68918. {
  68919. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68920. }
  68921. }
  68922. }
  68923. void renderImage (const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68924. {
  68925. const AffineTransform transform (getTransformWith (t));
  68926. const Image::BitmapData destData (image, true);
  68927. const Image::BitmapData srcData (sourceImage, false);
  68928. const int alpha = fillType.colour.getAlpha();
  68929. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  68930. if (transform.isOnlyTranslation())
  68931. {
  68932. // If our translation doesn't involve any distortion, just use a simple blit..
  68933. int tx = (int) (transform.getTranslationX() * 256.0f);
  68934. int ty = (int) (transform.getTranslationY() * 256.0f);
  68935. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68936. {
  68937. tx = ((tx + 128) >> 8);
  68938. ty = ((ty + 128) >> 8);
  68939. if (tiledFillClipRegion != 0)
  68940. {
  68941. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  68942. }
  68943. else
  68944. {
  68945. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (image.getBounds())));
  68946. c = clip->applyClipTo (c);
  68947. if (c != 0)
  68948. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  68949. }
  68950. return;
  68951. }
  68952. }
  68953. if (transform.isSingularity())
  68954. return;
  68955. if (tiledFillClipRegion != 0)
  68956. {
  68957. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  68958. }
  68959. else
  68960. {
  68961. Path p;
  68962. p.addRectangle (sourceImage.getBounds());
  68963. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  68964. c = c->clipToPath (p, transform);
  68965. if (c != 0)
  68966. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  68967. }
  68968. }
  68969. Image image;
  68970. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  68971. private:
  68972. AffineTransform complexTransform;
  68973. int xOffset, yOffset;
  68974. float compositionAlpha;
  68975. public:
  68976. bool isOnlyTranslated;
  68977. Font font;
  68978. FillType fillType;
  68979. Graphics::ResamplingQuality interpolationQuality;
  68980. private:
  68981. void cloneClipIfMultiplyReferenced()
  68982. {
  68983. if (clip->getReferenceCount() > 1)
  68984. clip = clip->clone();
  68985. }
  68986. const AffineTransform getTransform() const
  68987. {
  68988. if (isOnlyTranslated)
  68989. return AffineTransform::translation ((float) xOffset, (float) yOffset);
  68990. return complexTransform;
  68991. }
  68992. const AffineTransform getTransformWith (const AffineTransform& userTransform) const
  68993. {
  68994. if (isOnlyTranslated)
  68995. return userTransform.translated ((float) xOffset, (float) yOffset);
  68996. return userTransform.followedBy (complexTransform);
  68997. }
  68998. SavedState& operator= (const SavedState&);
  68999. };
  69000. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69001. : image (image_),
  69002. currentState (new SavedState (image_, image_.getBounds(), 0, 0))
  69003. {
  69004. }
  69005. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69006. const RectangleList& initialClip)
  69007. : image (image_),
  69008. currentState (new SavedState (image_, initialClip, xOffset, yOffset))
  69009. {
  69010. }
  69011. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69012. {
  69013. }
  69014. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69015. {
  69016. return false;
  69017. }
  69018. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69019. {
  69020. currentState->setOrigin (x, y);
  69021. }
  69022. void LowLevelGraphicsSoftwareRenderer::addTransform (const AffineTransform& transform)
  69023. {
  69024. currentState->addTransform (transform);
  69025. }
  69026. float LowLevelGraphicsSoftwareRenderer::getScaleFactor()
  69027. {
  69028. return currentState->getScaleFactor();
  69029. }
  69030. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69031. {
  69032. return currentState->clipToRectangle (r);
  69033. }
  69034. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69035. {
  69036. return currentState->clipToRectangleList (clipRegion);
  69037. }
  69038. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69039. {
  69040. currentState->excludeClipRectangle (r);
  69041. }
  69042. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69043. {
  69044. currentState->clipToPath (path, transform);
  69045. }
  69046. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69047. {
  69048. currentState->clipToImageAlpha (sourceImage, transform);
  69049. }
  69050. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69051. {
  69052. return currentState->clipRegionIntersects (r);
  69053. }
  69054. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69055. {
  69056. return currentState->getClipBounds();
  69057. }
  69058. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69059. {
  69060. return currentState->clip == 0;
  69061. }
  69062. void LowLevelGraphicsSoftwareRenderer::saveState()
  69063. {
  69064. stateStack.add (new SavedState (*currentState));
  69065. }
  69066. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69067. {
  69068. SavedState* const top = stateStack.getLast();
  69069. if (top != 0)
  69070. {
  69071. currentState = top;
  69072. stateStack.removeLast (1, false);
  69073. }
  69074. else
  69075. {
  69076. jassertfalse; // trying to pop with an empty stack!
  69077. }
  69078. }
  69079. void LowLevelGraphicsSoftwareRenderer::beginTransparencyLayer (float opacity)
  69080. {
  69081. saveState();
  69082. currentState = currentState->beginTransparencyLayer (opacity);
  69083. }
  69084. void LowLevelGraphicsSoftwareRenderer::endTransparencyLayer()
  69085. {
  69086. const ScopedPointer<SavedState> layer (currentState);
  69087. restoreState();
  69088. currentState->endTransparencyLayer (*layer);
  69089. }
  69090. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69091. {
  69092. currentState->fillType = fillType;
  69093. }
  69094. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69095. {
  69096. currentState->fillType.setOpacity (newOpacity);
  69097. }
  69098. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69099. {
  69100. currentState->interpolationQuality = quality;
  69101. }
  69102. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69103. {
  69104. currentState->fillRect (r, replaceExistingContents);
  69105. }
  69106. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69107. {
  69108. currentState->fillPath (path, transform);
  69109. }
  69110. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69111. {
  69112. currentState->renderImage (sourceImage, transform, fillEntireClipAsTiles ? currentState->clip : 0);
  69113. }
  69114. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69115. {
  69116. Path p;
  69117. p.addLineSegment (line, 1.0f);
  69118. fillPath (p, AffineTransform::identity);
  69119. }
  69120. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69121. {
  69122. if (bottom > top)
  69123. currentState->fillRect (Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69124. }
  69125. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69126. {
  69127. if (right > left)
  69128. currentState->fillRect (Rectangle<float> (left, (float) y, right - left, 1.0f));
  69129. }
  69130. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69131. {
  69132. public:
  69133. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69134. void draw (SavedState& state, float x, const float y) const
  69135. {
  69136. if (snapToIntegerCoordinate)
  69137. x = std::floor (x + 0.5f);
  69138. if (edgeTable != 0)
  69139. state.fillEdgeTable (*edgeTable, x, roundToInt (y));
  69140. }
  69141. void generate (const Font& newFont, const int glyphNumber)
  69142. {
  69143. font = newFont;
  69144. snapToIntegerCoordinate = newFont.getTypeface()->isHinted();
  69145. glyph = glyphNumber;
  69146. edgeTable = 0;
  69147. Path glyphPath;
  69148. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69149. if (! glyphPath.isEmpty())
  69150. {
  69151. const float fontHeight = font.getHeight();
  69152. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69153. #if JUCE_MAC || JUCE_IOS
  69154. .translated (0.0f, -0.5f)
  69155. #endif
  69156. );
  69157. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69158. glyphPath, transform);
  69159. }
  69160. }
  69161. Font font;
  69162. int glyph, lastAccessCount;
  69163. bool snapToIntegerCoordinate;
  69164. private:
  69165. ScopedPointer <EdgeTable> edgeTable;
  69166. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedGlyph);
  69167. };
  69168. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69169. {
  69170. public:
  69171. GlyphCache()
  69172. : accessCounter (0), hits (0), misses (0)
  69173. {
  69174. addNewGlyphSlots (120);
  69175. }
  69176. ~GlyphCache()
  69177. {
  69178. clearSingletonInstance();
  69179. }
  69180. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69181. void drawGlyph (SavedState& state, const Font& font, const int glyphNumber, float x, float y)
  69182. {
  69183. ++accessCounter;
  69184. int oldestCounter = std::numeric_limits<int>::max();
  69185. CachedGlyph* oldest = 0;
  69186. for (int i = glyphs.size(); --i >= 0;)
  69187. {
  69188. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69189. if (glyph->glyph == glyphNumber && glyph->font == font)
  69190. {
  69191. ++hits;
  69192. glyph->lastAccessCount = accessCounter;
  69193. glyph->draw (state, x, y);
  69194. return;
  69195. }
  69196. if (glyph->lastAccessCount <= oldestCounter)
  69197. {
  69198. oldestCounter = glyph->lastAccessCount;
  69199. oldest = glyph;
  69200. }
  69201. }
  69202. if (hits + ++misses > (glyphs.size() << 4))
  69203. {
  69204. if (misses * 2 > hits)
  69205. addNewGlyphSlots (32);
  69206. hits = misses = 0;
  69207. oldest = glyphs.getLast();
  69208. }
  69209. jassert (oldest != 0);
  69210. oldest->lastAccessCount = accessCounter;
  69211. oldest->generate (font, glyphNumber);
  69212. oldest->draw (state, x, y);
  69213. }
  69214. private:
  69215. friend class OwnedArray <CachedGlyph>;
  69216. OwnedArray <CachedGlyph> glyphs;
  69217. int accessCounter, hits, misses;
  69218. void addNewGlyphSlots (int num)
  69219. {
  69220. while (--num >= 0)
  69221. glyphs.add (new CachedGlyph());
  69222. }
  69223. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphCache);
  69224. };
  69225. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69226. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69227. {
  69228. currentState->font = newFont;
  69229. }
  69230. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69231. {
  69232. return currentState->font;
  69233. }
  69234. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69235. {
  69236. Font& f = currentState->font;
  69237. if (transform.isOnlyTranslation() && currentState->isOnlyTranslated)
  69238. {
  69239. GlyphCache::getInstance()->drawGlyph (*currentState, f, glyphNumber,
  69240. transform.getTranslationX(),
  69241. transform.getTranslationY());
  69242. }
  69243. else
  69244. {
  69245. Path p;
  69246. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69247. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69248. }
  69249. }
  69250. #if JUCE_MSVC
  69251. #pragma warning (pop)
  69252. #if JUCE_DEBUG
  69253. #pragma optimize ("", on) // resets optimisations to the project defaults
  69254. #endif
  69255. #endif
  69256. END_JUCE_NAMESPACE
  69257. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69258. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69259. BEGIN_JUCE_NAMESPACE
  69260. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69261. : flags (other.flags)
  69262. {
  69263. }
  69264. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69265. {
  69266. flags = other.flags;
  69267. return *this;
  69268. }
  69269. void RectanglePlacement::applyTo (double& x, double& y, double& w, double& h,
  69270. const double dx, const double dy, const double dw, const double dh) const throw()
  69271. {
  69272. if (w == 0 || h == 0)
  69273. return;
  69274. if ((flags & stretchToFit) != 0)
  69275. {
  69276. x = dx;
  69277. y = dy;
  69278. w = dw;
  69279. h = dh;
  69280. }
  69281. else
  69282. {
  69283. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69284. : jmin (dw / w, dh / h);
  69285. if ((flags & onlyReduceInSize) != 0)
  69286. scale = jmin (scale, 1.0);
  69287. if ((flags & onlyIncreaseInSize) != 0)
  69288. scale = jmax (scale, 1.0);
  69289. w *= scale;
  69290. h *= scale;
  69291. if ((flags & xLeft) != 0)
  69292. x = dx;
  69293. else if ((flags & xRight) != 0)
  69294. x = dx + dw - w;
  69295. else
  69296. x = dx + (dw - w) * 0.5;
  69297. if ((flags & yTop) != 0)
  69298. y = dy;
  69299. else if ((flags & yBottom) != 0)
  69300. y = dy + dh - h;
  69301. else
  69302. y = dy + (dh - h) * 0.5;
  69303. }
  69304. }
  69305. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69306. {
  69307. if (source.isEmpty())
  69308. return AffineTransform::identity;
  69309. float newX = destination.getX();
  69310. float newY = destination.getY();
  69311. float scaleX = destination.getWidth() / source.getWidth();
  69312. float scaleY = destination.getHeight() / source.getHeight();
  69313. if ((flags & stretchToFit) == 0)
  69314. {
  69315. scaleX = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69316. : jmin (scaleX, scaleY);
  69317. if ((flags & onlyReduceInSize) != 0)
  69318. scaleX = jmin (scaleX, 1.0f);
  69319. if ((flags & onlyIncreaseInSize) != 0)
  69320. scaleX = jmax (scaleX, 1.0f);
  69321. scaleY = scaleX;
  69322. if ((flags & xRight) != 0)
  69323. newX += destination.getWidth() - source.getWidth() * scaleX; // right
  69324. else if ((flags & xLeft) == 0)
  69325. newX += (destination.getWidth() - source.getWidth() * scaleX) / 2.0f; // centre
  69326. if ((flags & yBottom) != 0)
  69327. newY += destination.getHeight() - source.getHeight() * scaleX; // bottom
  69328. else if ((flags & yTop) == 0)
  69329. newY += (destination.getHeight() - source.getHeight() * scaleX) / 2.0f; // centre
  69330. }
  69331. return AffineTransform::translation (-source.getX(), -source.getY())
  69332. .scaled (scaleX, scaleY)
  69333. .translated (newX, newY);
  69334. }
  69335. END_JUCE_NAMESPACE
  69336. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69337. /*** Start of inlined file: juce_Drawable.cpp ***/
  69338. BEGIN_JUCE_NAMESPACE
  69339. Drawable::Drawable()
  69340. {
  69341. setInterceptsMouseClicks (false, false);
  69342. setPaintingIsUnclipped (true);
  69343. }
  69344. Drawable::~Drawable()
  69345. {
  69346. }
  69347. void Drawable::draw (Graphics& g, float opacity, const AffineTransform& transform) const
  69348. {
  69349. const_cast <Drawable*> (this)->nonConstDraw (g, opacity, transform);
  69350. }
  69351. void Drawable::nonConstDraw (Graphics& g, float opacity, const AffineTransform& transform)
  69352. {
  69353. Graphics::ScopedSaveState ss (g);
  69354. const float oldOpacity = getAlpha();
  69355. setAlpha (opacity);
  69356. g.addTransform (AffineTransform::translation ((float) -originRelativeToComponent.getX(),
  69357. (float) -originRelativeToComponent.getY())
  69358. .followedBy (getTransform())
  69359. .followedBy (transform));
  69360. if (! g.isClipEmpty())
  69361. paintEntireComponent (g, false);
  69362. setAlpha (oldOpacity);
  69363. }
  69364. void Drawable::drawAt (Graphics& g, float x, float y, float opacity) const
  69365. {
  69366. draw (g, opacity, AffineTransform::translation (x, y));
  69367. }
  69368. void Drawable::drawWithin (Graphics& g, const Rectangle<float>& destArea, const RectanglePlacement& placement, float opacity) const
  69369. {
  69370. draw (g, opacity, placement.getTransformToFit (getDrawableBounds(), destArea));
  69371. }
  69372. DrawableComposite* Drawable::getParent() const
  69373. {
  69374. return dynamic_cast <DrawableComposite*> (getParentComponent());
  69375. }
  69376. void Drawable::transformContextToCorrectOrigin (Graphics& g)
  69377. {
  69378. g.setOrigin (originRelativeToComponent.getX(),
  69379. originRelativeToComponent.getY());
  69380. }
  69381. void Drawable::parentHierarchyChanged()
  69382. {
  69383. setBoundsToEnclose (getDrawableBounds());
  69384. }
  69385. void Drawable::setBoundsToEnclose (const Rectangle<float>& area)
  69386. {
  69387. Drawable* const parent = getParent();
  69388. Point<int> parentOrigin;
  69389. if (parent != 0)
  69390. parentOrigin = parent->originRelativeToComponent;
  69391. const Rectangle<int> newBounds (area.getSmallestIntegerContainer() + parentOrigin);
  69392. originRelativeToComponent = parentOrigin - newBounds.getPosition();
  69393. setBounds (newBounds);
  69394. }
  69395. void Drawable::setOriginWithOriginalSize (const Point<float>& originWithinParent)
  69396. {
  69397. setTransform (AffineTransform::translation (originWithinParent.getX(), originWithinParent.getY()));
  69398. }
  69399. void Drawable::setTransformToFit (const Rectangle<float>& area, const RectanglePlacement& placement)
  69400. {
  69401. if (! area.isEmpty())
  69402. setTransform (placement.getTransformToFit (getDrawableBounds(), area));
  69403. }
  69404. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69405. {
  69406. Drawable* result = 0;
  69407. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69408. if (image.isValid())
  69409. {
  69410. DrawableImage* const di = new DrawableImage();
  69411. di->setImage (image);
  69412. result = di;
  69413. }
  69414. else
  69415. {
  69416. const String asString (String::createStringFromData (data, (int) numBytes));
  69417. XmlDocument doc (asString);
  69418. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69419. if (outer != 0 && outer->hasTagName ("svg"))
  69420. {
  69421. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69422. if (svg != 0)
  69423. result = Drawable::createFromSVG (*svg);
  69424. }
  69425. }
  69426. return result;
  69427. }
  69428. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69429. {
  69430. MemoryOutputStream mo;
  69431. mo.writeFromInputStream (dataSource, -1);
  69432. return createFromImageData (mo.getData(), mo.getDataSize());
  69433. }
  69434. Drawable* Drawable::createFromImageFile (const File& file)
  69435. {
  69436. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69437. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69438. }
  69439. template <class DrawableClass>
  69440. class DrawableTypeHandler : public ComponentBuilder::TypeHandler
  69441. {
  69442. public:
  69443. DrawableTypeHandler()
  69444. : ComponentBuilder::TypeHandler (DrawableClass::valueTreeType)
  69445. {
  69446. }
  69447. Component* addNewComponentFromState (const ValueTree& state, Component* parent)
  69448. {
  69449. DrawableClass* const d = new DrawableClass();
  69450. if (parent != 0)
  69451. parent->addAndMakeVisible (d);
  69452. updateComponentFromState (d, state);
  69453. return d;
  69454. }
  69455. void updateComponentFromState (Component* component, const ValueTree& state)
  69456. {
  69457. DrawableClass* const d = dynamic_cast <DrawableClass*> (component);
  69458. jassert (d != 0);
  69459. d->refreshFromValueTree (state, *this->getBuilder());
  69460. }
  69461. };
  69462. void Drawable::registerDrawableTypeHandlers (ComponentBuilder& builder)
  69463. {
  69464. builder.registerTypeHandler (new DrawableTypeHandler <DrawablePath>());
  69465. builder.registerTypeHandler (new DrawableTypeHandler <DrawableComposite>());
  69466. builder.registerTypeHandler (new DrawableTypeHandler <DrawableRectangle>());
  69467. builder.registerTypeHandler (new DrawableTypeHandler <DrawableImage>());
  69468. builder.registerTypeHandler (new DrawableTypeHandler <DrawableText>());
  69469. }
  69470. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ComponentBuilder::ImageProvider* imageProvider)
  69471. {
  69472. ComponentBuilder builder (tree);
  69473. builder.setImageProvider (imageProvider);
  69474. registerDrawableTypeHandlers (builder);
  69475. ScopedPointer<Component> comp (builder.createComponent());
  69476. Drawable* const d = dynamic_cast<Drawable*> (static_cast <Component*> (comp));
  69477. if (d != 0)
  69478. comp.release();
  69479. return d;
  69480. }
  69481. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69482. : state (state_)
  69483. {
  69484. }
  69485. const String Drawable::ValueTreeWrapperBase::getID() const
  69486. {
  69487. return state [ComponentBuilder::idProperty];
  69488. }
  69489. void Drawable::ValueTreeWrapperBase::setID (const String& newID)
  69490. {
  69491. if (newID.isEmpty())
  69492. state.removeProperty (ComponentBuilder::idProperty, 0);
  69493. else
  69494. state.setProperty (ComponentBuilder::idProperty, newID, 0);
  69495. }
  69496. END_JUCE_NAMESPACE
  69497. /*** End of inlined file: juce_Drawable.cpp ***/
  69498. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69499. BEGIN_JUCE_NAMESPACE
  69500. DrawableShape::DrawableShape()
  69501. : strokeType (0.0f),
  69502. mainFill (Colours::black),
  69503. strokeFill (Colours::black)
  69504. {
  69505. }
  69506. DrawableShape::DrawableShape (const DrawableShape& other)
  69507. : strokeType (other.strokeType),
  69508. mainFill (other.mainFill),
  69509. strokeFill (other.strokeFill)
  69510. {
  69511. }
  69512. DrawableShape::~DrawableShape()
  69513. {
  69514. }
  69515. class DrawableShape::RelativePositioner : public RelativeCoordinatePositionerBase
  69516. {
  69517. public:
  69518. RelativePositioner (DrawableShape& component_, const DrawableShape::RelativeFillType& fill_, bool isMainFill_)
  69519. : RelativeCoordinatePositionerBase (component_),
  69520. owner (component_),
  69521. fill (fill_),
  69522. isMainFill (isMainFill_)
  69523. {
  69524. }
  69525. bool registerCoordinates()
  69526. {
  69527. bool ok = addPoint (fill.gradientPoint1);
  69528. ok = addPoint (fill.gradientPoint2) && ok;
  69529. return addPoint (fill.gradientPoint3) && ok;
  69530. }
  69531. void applyToComponentBounds()
  69532. {
  69533. ComponentScope scope (owner);
  69534. if (isMainFill ? owner.mainFill.recalculateCoords (&scope)
  69535. : owner.strokeFill.recalculateCoords (&scope))
  69536. owner.repaint();
  69537. }
  69538. private:
  69539. DrawableShape& owner;
  69540. const DrawableShape::RelativeFillType fill;
  69541. const bool isMainFill;
  69542. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  69543. };
  69544. void DrawableShape::setFill (const FillType& newFill)
  69545. {
  69546. setFill (RelativeFillType (newFill));
  69547. }
  69548. void DrawableShape::setStrokeFill (const FillType& newFill)
  69549. {
  69550. setStrokeFill (RelativeFillType (newFill));
  69551. }
  69552. void DrawableShape::setFillInternal (RelativeFillType& fill, const RelativeFillType& newFill,
  69553. ScopedPointer<RelativeCoordinatePositionerBase>& positioner)
  69554. {
  69555. if (fill != newFill)
  69556. {
  69557. fill = newFill;
  69558. positioner = 0;
  69559. if (fill.isDynamic())
  69560. {
  69561. positioner = new RelativePositioner (*this, fill, true);
  69562. positioner->apply();
  69563. }
  69564. else
  69565. {
  69566. fill.recalculateCoords (0);
  69567. }
  69568. repaint();
  69569. }
  69570. }
  69571. void DrawableShape::setFill (const RelativeFillType& newFill)
  69572. {
  69573. setFillInternal (mainFill, newFill, mainFillPositioner);
  69574. }
  69575. void DrawableShape::setStrokeFill (const RelativeFillType& newFill)
  69576. {
  69577. setFillInternal (strokeFill, newFill, strokeFillPositioner);
  69578. }
  69579. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69580. {
  69581. if (strokeType != newStrokeType)
  69582. {
  69583. strokeType = newStrokeType;
  69584. strokeChanged();
  69585. }
  69586. }
  69587. void DrawableShape::setStrokeThickness (const float newThickness)
  69588. {
  69589. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69590. }
  69591. bool DrawableShape::isStrokeVisible() const throw()
  69592. {
  69593. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.fill.isInvisible();
  69594. }
  69595. void DrawableShape::refreshFillTypes (const FillAndStrokeState& newState, ComponentBuilder::ImageProvider* imageProvider)
  69596. {
  69597. setFill (newState.getFill (FillAndStrokeState::fill, imageProvider));
  69598. setStrokeFill (newState.getFill (FillAndStrokeState::stroke, imageProvider));
  69599. }
  69600. void DrawableShape::writeTo (FillAndStrokeState& state, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69601. {
  69602. state.setFill (FillAndStrokeState::fill, mainFill, imageProvider, undoManager);
  69603. state.setFill (FillAndStrokeState::stroke, strokeFill, imageProvider, undoManager);
  69604. state.setStrokeType (strokeType, undoManager);
  69605. }
  69606. void DrawableShape::paint (Graphics& g)
  69607. {
  69608. transformContextToCorrectOrigin (g);
  69609. g.setFillType (mainFill.fill);
  69610. g.fillPath (path);
  69611. if (isStrokeVisible())
  69612. {
  69613. g.setFillType (strokeFill.fill);
  69614. g.fillPath (strokePath);
  69615. }
  69616. }
  69617. void DrawableShape::pathChanged()
  69618. {
  69619. strokeChanged();
  69620. }
  69621. void DrawableShape::strokeChanged()
  69622. {
  69623. strokePath.clear();
  69624. strokeType.createStrokedPath (strokePath, path, AffineTransform::identity, 4.0f);
  69625. setBoundsToEnclose (getDrawableBounds());
  69626. repaint();
  69627. }
  69628. const Rectangle<float> DrawableShape::getDrawableBounds() const
  69629. {
  69630. if (isStrokeVisible())
  69631. return strokePath.getBounds();
  69632. else
  69633. return path.getBounds();
  69634. }
  69635. bool DrawableShape::hitTest (int x, int y)
  69636. {
  69637. bool allowsClicksOnThisComponent, allowsClicksOnChildComponents;
  69638. getInterceptsMouseClicks (allowsClicksOnThisComponent, allowsClicksOnChildComponents);
  69639. if (! allowsClicksOnThisComponent)
  69640. return false;
  69641. const float globalX = (float) (x - originRelativeToComponent.getX());
  69642. const float globalY = (float) (y - originRelativeToComponent.getY());
  69643. return path.contains (globalX, globalY)
  69644. || (isStrokeVisible() && strokePath.contains (globalX, globalY));
  69645. }
  69646. DrawableShape::RelativeFillType::RelativeFillType()
  69647. {
  69648. }
  69649. DrawableShape::RelativeFillType::RelativeFillType (const FillType& fill_)
  69650. : fill (fill_)
  69651. {
  69652. if (fill.isGradient())
  69653. {
  69654. const ColourGradient& g = *fill.gradient;
  69655. gradientPoint1 = g.point1.transformedBy (fill.transform);
  69656. gradientPoint2 = g.point2.transformedBy (fill.transform);
  69657. gradientPoint3 = Point<float> (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69658. g.point1.getY() + g.point1.getX() - g.point2.getX())
  69659. .transformedBy (fill.transform);
  69660. fill.transform = AffineTransform::identity;
  69661. }
  69662. }
  69663. DrawableShape::RelativeFillType::RelativeFillType (const RelativeFillType& other)
  69664. : fill (other.fill),
  69665. gradientPoint1 (other.gradientPoint1),
  69666. gradientPoint2 (other.gradientPoint2),
  69667. gradientPoint3 (other.gradientPoint3)
  69668. {
  69669. }
  69670. DrawableShape::RelativeFillType& DrawableShape::RelativeFillType::operator= (const RelativeFillType& other)
  69671. {
  69672. fill = other.fill;
  69673. gradientPoint1 = other.gradientPoint1;
  69674. gradientPoint2 = other.gradientPoint2;
  69675. gradientPoint3 = other.gradientPoint3;
  69676. return *this;
  69677. }
  69678. bool DrawableShape::RelativeFillType::operator== (const RelativeFillType& other) const
  69679. {
  69680. return fill == other.fill
  69681. && ((! fill.isGradient())
  69682. || (gradientPoint1 == other.gradientPoint1
  69683. && gradientPoint2 == other.gradientPoint2
  69684. && gradientPoint3 == other.gradientPoint3));
  69685. }
  69686. bool DrawableShape::RelativeFillType::operator!= (const RelativeFillType& other) const
  69687. {
  69688. return ! operator== (other);
  69689. }
  69690. bool DrawableShape::RelativeFillType::recalculateCoords (Expression::Scope* scope)
  69691. {
  69692. if (fill.isGradient())
  69693. {
  69694. const Point<float> g1 (gradientPoint1.resolve (scope));
  69695. const Point<float> g2 (gradientPoint2.resolve (scope));
  69696. AffineTransform t;
  69697. ColourGradient& g = *fill.gradient;
  69698. if (g.isRadial)
  69699. {
  69700. const Point<float> g3 (gradientPoint3.resolve (scope));
  69701. const Point<float> g3Source (g1.getX() + g2.getY() - g1.getY(),
  69702. g1.getY() + g1.getX() - g2.getX());
  69703. t = AffineTransform::fromTargetPoints (g1.getX(), g1.getY(), g1.getX(), g1.getY(),
  69704. g2.getX(), g2.getY(), g2.getX(), g2.getY(),
  69705. g3Source.getX(), g3Source.getY(), g3.getX(), g3.getY());
  69706. }
  69707. if (g.point1 != g1 || g.point2 != g2 || fill.transform != t)
  69708. {
  69709. g.point1 = g1;
  69710. g.point2 = g2;
  69711. fill.transform = t;
  69712. return true;
  69713. }
  69714. }
  69715. return false;
  69716. }
  69717. bool DrawableShape::RelativeFillType::isDynamic() const
  69718. {
  69719. return gradientPoint1.isDynamic() || gradientPoint2.isDynamic() || gradientPoint3.isDynamic();
  69720. }
  69721. void DrawableShape::RelativeFillType::writeTo (ValueTree& v, ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager) const
  69722. {
  69723. if (fill.isColour())
  69724. {
  69725. v.setProperty (FillAndStrokeState::type, "solid", undoManager);
  69726. v.setProperty (FillAndStrokeState::colour, String::toHexString ((int) fill.colour.getARGB()), undoManager);
  69727. }
  69728. else if (fill.isGradient())
  69729. {
  69730. v.setProperty (FillAndStrokeState::type, "gradient", undoManager);
  69731. v.setProperty (FillAndStrokeState::gradientPoint1, gradientPoint1.toString(), undoManager);
  69732. v.setProperty (FillAndStrokeState::gradientPoint2, gradientPoint2.toString(), undoManager);
  69733. v.setProperty (FillAndStrokeState::gradientPoint3, gradientPoint3.toString(), undoManager);
  69734. const ColourGradient& cg = *fill.gradient;
  69735. v.setProperty (FillAndStrokeState::radial, cg.isRadial, undoManager);
  69736. String s;
  69737. for (int i = 0; i < cg.getNumColours(); ++i)
  69738. s << ' ' << cg.getColourPosition (i)
  69739. << ' ' << String::toHexString ((int) cg.getColour(i).getARGB());
  69740. v.setProperty (FillAndStrokeState::colours, s.trimStart(), undoManager);
  69741. }
  69742. else if (fill.isTiledImage())
  69743. {
  69744. v.setProperty (FillAndStrokeState::type, "image", undoManager);
  69745. if (imageProvider != 0)
  69746. v.setProperty (FillAndStrokeState::imageId, imageProvider->getIdentifierForImage (fill.image), undoManager);
  69747. if (fill.getOpacity() < 1.0f)
  69748. v.setProperty (FillAndStrokeState::imageOpacity, fill.getOpacity(), undoManager);
  69749. else
  69750. v.removeProperty (FillAndStrokeState::imageOpacity, undoManager);
  69751. }
  69752. else
  69753. {
  69754. jassertfalse;
  69755. }
  69756. }
  69757. bool DrawableShape::RelativeFillType::readFrom (const ValueTree& v, ComponentBuilder::ImageProvider* imageProvider)
  69758. {
  69759. const String newType (v [FillAndStrokeState::type].toString());
  69760. if (newType == "solid")
  69761. {
  69762. const String colourString (v [FillAndStrokeState::colour].toString());
  69763. fill.setColour (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69764. : (uint32) colourString.getHexValue32()));
  69765. return true;
  69766. }
  69767. else if (newType == "gradient")
  69768. {
  69769. ColourGradient g;
  69770. g.isRadial = v [FillAndStrokeState::radial];
  69771. StringArray colourSteps;
  69772. colourSteps.addTokens (v [FillAndStrokeState::colours].toString(), false);
  69773. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69774. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69775. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69776. fill.setGradient (g);
  69777. gradientPoint1 = RelativePoint (v [FillAndStrokeState::gradientPoint1]);
  69778. gradientPoint2 = RelativePoint (v [FillAndStrokeState::gradientPoint2]);
  69779. gradientPoint3 = RelativePoint (v [FillAndStrokeState::gradientPoint3]);
  69780. return true;
  69781. }
  69782. else if (newType == "image")
  69783. {
  69784. Image im;
  69785. if (imageProvider != 0)
  69786. im = imageProvider->getImageForIdentifier (v [FillAndStrokeState::imageId]);
  69787. fill.setTiledImage (im, AffineTransform::identity);
  69788. fill.setOpacity ((float) v.getProperty (FillAndStrokeState::imageOpacity, 1.0f));
  69789. return true;
  69790. }
  69791. jassertfalse;
  69792. return false;
  69793. }
  69794. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69795. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69796. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69797. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69798. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69799. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69800. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69801. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69802. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69803. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69804. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69805. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69806. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69807. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69808. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69809. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69810. : Drawable::ValueTreeWrapperBase (state_)
  69811. {
  69812. }
  69813. const DrawableShape::RelativeFillType DrawableShape::FillAndStrokeState::getFill (const Identifier& fillOrStrokeType, ComponentBuilder::ImageProvider* imageProvider) const
  69814. {
  69815. DrawableShape::RelativeFillType f;
  69816. f.readFrom (state.getChildWithName (fillOrStrokeType), imageProvider);
  69817. return f;
  69818. }
  69819. ValueTree DrawableShape::FillAndStrokeState::getFillState (const Identifier& fillOrStrokeType)
  69820. {
  69821. ValueTree v (state.getChildWithName (fillOrStrokeType));
  69822. if (v.isValid())
  69823. return v;
  69824. setFill (fillOrStrokeType, FillType (Colours::black), 0, 0);
  69825. return getFillState (fillOrStrokeType);
  69826. }
  69827. void DrawableShape::FillAndStrokeState::setFill (const Identifier& fillOrStrokeType, const RelativeFillType& newFill,
  69828. ComponentBuilder::ImageProvider* imageProvider, UndoManager* undoManager)
  69829. {
  69830. ValueTree v (state.getOrCreateChildWithName (fillOrStrokeType, undoManager));
  69831. newFill.writeTo (v, imageProvider, undoManager);
  69832. }
  69833. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69834. {
  69835. const String jointStyleString (state [jointStyle].toString());
  69836. const String capStyleString (state [capStyle].toString());
  69837. return PathStrokeType (state [strokeWidth],
  69838. jointStyleString == "curved" ? PathStrokeType::curved
  69839. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69840. : PathStrokeType::mitered),
  69841. capStyleString == "square" ? PathStrokeType::square
  69842. : (capStyleString == "round" ? PathStrokeType::rounded
  69843. : PathStrokeType::butt));
  69844. }
  69845. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69846. {
  69847. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69848. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69849. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69850. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69851. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69852. }
  69853. END_JUCE_NAMESPACE
  69854. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69855. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69856. BEGIN_JUCE_NAMESPACE
  69857. DrawableComposite::DrawableComposite()
  69858. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f)),
  69859. updateBoundsReentrant (false)
  69860. {
  69861. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69862. RelativeCoordinate (100.0),
  69863. RelativeCoordinate (0.0),
  69864. RelativeCoordinate (100.0)));
  69865. }
  69866. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69867. : bounds (other.bounds),
  69868. markersX (other.markersX),
  69869. markersY (other.markersY),
  69870. updateBoundsReentrant (false)
  69871. {
  69872. for (int i = 0; i < other.getNumChildComponents(); ++i)
  69873. {
  69874. const Drawable* const d = dynamic_cast <const Drawable*> (other.getChildComponent(i));
  69875. if (d != 0)
  69876. addAndMakeVisible (d->createCopy());
  69877. }
  69878. }
  69879. DrawableComposite::~DrawableComposite()
  69880. {
  69881. deleteAllChildren();
  69882. }
  69883. Drawable* DrawableComposite::createCopy() const
  69884. {
  69885. return new DrawableComposite (*this);
  69886. }
  69887. const Rectangle<float> DrawableComposite::getDrawableBounds() const
  69888. {
  69889. Rectangle<float> r;
  69890. for (int i = getNumChildComponents(); --i >= 0;)
  69891. {
  69892. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  69893. if (d != 0)
  69894. r = r.getUnion (d->isTransformed() ? d->getDrawableBounds().transformed (d->getTransform())
  69895. : d->getDrawableBounds());
  69896. }
  69897. return r;
  69898. }
  69899. MarkerList* DrawableComposite::getMarkers (bool xAxis)
  69900. {
  69901. return xAxis ? &markersX : &markersY;
  69902. }
  69903. const RelativeRectangle DrawableComposite::getContentArea() const
  69904. {
  69905. jassert (markersX.getNumMarkers() >= 2 && markersX.getMarker (0)->name == contentLeftMarkerName && markersX.getMarker (1)->name == contentRightMarkerName);
  69906. jassert (markersY.getNumMarkers() >= 2 && markersY.getMarker (0)->name == contentTopMarkerName && markersY.getMarker (1)->name == contentBottomMarkerName);
  69907. return RelativeRectangle (markersX.getMarker(0)->position, markersX.getMarker(1)->position,
  69908. markersY.getMarker(0)->position, markersY.getMarker(1)->position);
  69909. }
  69910. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69911. {
  69912. markersX.setMarker (contentLeftMarkerName, newArea.left);
  69913. markersX.setMarker (contentRightMarkerName, newArea.right);
  69914. markersY.setMarker (contentTopMarkerName, newArea.top);
  69915. markersY.setMarker (contentBottomMarkerName, newArea.bottom);
  69916. }
  69917. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBounds)
  69918. {
  69919. if (bounds != newBounds)
  69920. {
  69921. bounds = newBounds;
  69922. if (bounds.isDynamic())
  69923. {
  69924. Drawable::Positioner<DrawableComposite>* const p = new Drawable::Positioner<DrawableComposite> (*this);
  69925. setPositioner (p);
  69926. p->apply();
  69927. }
  69928. else
  69929. {
  69930. setPositioner (0);
  69931. recalculateCoordinates (0);
  69932. }
  69933. }
  69934. }
  69935. void DrawableComposite::resetBoundingBoxToContentArea()
  69936. {
  69937. const RelativeRectangle content (getContentArea());
  69938. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69939. RelativePoint (content.right, content.top),
  69940. RelativePoint (content.left, content.bottom)));
  69941. }
  69942. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69943. {
  69944. const Rectangle<float> activeArea (getDrawableBounds());
  69945. setContentArea (RelativeRectangle (RelativeCoordinate (activeArea.getX()),
  69946. RelativeCoordinate (activeArea.getRight()),
  69947. RelativeCoordinate (activeArea.getY()),
  69948. RelativeCoordinate (activeArea.getBottom())));
  69949. resetBoundingBoxToContentArea();
  69950. }
  69951. bool DrawableComposite::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  69952. {
  69953. bool ok = positioner.addPoint (bounds.topLeft);
  69954. ok = positioner.addPoint (bounds.topRight) && ok;
  69955. return positioner.addPoint (bounds.bottomLeft) && ok;
  69956. }
  69957. void DrawableComposite::recalculateCoordinates (Expression::Scope* scope)
  69958. {
  69959. Point<float> resolved[3];
  69960. bounds.resolveThreePoints (resolved, scope);
  69961. const Rectangle<float> content (getContentArea().resolve (scope));
  69962. AffineTransform t (AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69963. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69964. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY()));
  69965. if (t.isSingularity())
  69966. t = AffineTransform::identity;
  69967. setTransform (t);
  69968. }
  69969. void DrawableComposite::parentHierarchyChanged()
  69970. {
  69971. DrawableComposite* parent = getParent();
  69972. if (parent != 0)
  69973. originRelativeToComponent = parent->originRelativeToComponent - getPosition();
  69974. }
  69975. void DrawableComposite::childBoundsChanged (Component*)
  69976. {
  69977. updateBoundsToFitChildren();
  69978. }
  69979. void DrawableComposite::childrenChanged()
  69980. {
  69981. updateBoundsToFitChildren();
  69982. }
  69983. void DrawableComposite::updateBoundsToFitChildren()
  69984. {
  69985. if (! updateBoundsReentrant)
  69986. {
  69987. const ScopedValueSetter<bool> setter (updateBoundsReentrant, true, false);
  69988. Rectangle<int> childArea;
  69989. for (int i = getNumChildComponents(); --i >= 0;)
  69990. childArea = childArea.getUnion (getChildComponent(i)->getBoundsInParent());
  69991. const Point<int> delta (childArea.getPosition());
  69992. childArea += getPosition();
  69993. if (childArea != getBounds())
  69994. {
  69995. if (! delta.isOrigin())
  69996. {
  69997. originRelativeToComponent -= delta;
  69998. for (int i = getNumChildComponents(); --i >= 0;)
  69999. {
  70000. Component* const c = getChildComponent(i);
  70001. if (c != 0)
  70002. c->setBounds (c->getBounds() - delta);
  70003. }
  70004. }
  70005. setBounds (childArea);
  70006. }
  70007. }
  70008. }
  70009. const char* const DrawableComposite::contentLeftMarkerName = "left";
  70010. const char* const DrawableComposite::contentRightMarkerName = "right";
  70011. const char* const DrawableComposite::contentTopMarkerName = "top";
  70012. const char* const DrawableComposite::contentBottomMarkerName = "bottom";
  70013. const Identifier DrawableComposite::valueTreeType ("Group");
  70014. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70015. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70016. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70017. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70018. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70019. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70020. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70021. : ValueTreeWrapperBase (state_)
  70022. {
  70023. jassert (state.hasType (valueTreeType));
  70024. }
  70025. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70026. {
  70027. return state.getChildWithName (childGroupTag);
  70028. }
  70029. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70030. {
  70031. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70032. }
  70033. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70034. {
  70035. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70036. state.getProperty (topRight, "100, 0"),
  70037. state.getProperty (bottomLeft, "0, 100"));
  70038. }
  70039. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70040. {
  70041. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70042. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70043. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70044. }
  70045. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70046. {
  70047. const RelativeRectangle content (getContentArea());
  70048. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70049. RelativePoint (content.right, content.top),
  70050. RelativePoint (content.left, content.bottom)), undoManager);
  70051. }
  70052. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70053. {
  70054. MarkerList::ValueTreeWrapper markersX (getMarkerList (true));
  70055. MarkerList::ValueTreeWrapper markersY (getMarkerList (false));
  70056. return RelativeRectangle (markersX.getMarker (markersX.getMarkerState (0)).position,
  70057. markersX.getMarker (markersX.getMarkerState (1)).position,
  70058. markersY.getMarker (markersY.getMarkerState (0)).position,
  70059. markersY.getMarker (markersY.getMarkerState (1)).position);
  70060. }
  70061. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70062. {
  70063. MarkerList::ValueTreeWrapper markersX (getMarkerListCreating (true, 0));
  70064. MarkerList::ValueTreeWrapper markersY (getMarkerListCreating (false, 0));
  70065. markersX.setMarker (MarkerList::Marker (contentLeftMarkerName, newArea.left), undoManager);
  70066. markersX.setMarker (MarkerList::Marker (contentRightMarkerName, newArea.right), undoManager);
  70067. markersY.setMarker (MarkerList::Marker (contentTopMarkerName, newArea.top), undoManager);
  70068. markersY.setMarker (MarkerList::Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70069. }
  70070. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70071. {
  70072. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70073. }
  70074. MarkerList::ValueTreeWrapper DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70075. {
  70076. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70077. }
  70078. void DrawableComposite::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70079. {
  70080. const ValueTreeWrapper wrapper (tree);
  70081. setComponentID (wrapper.getID());
  70082. wrapper.getMarkerList (true).applyTo (markersX);
  70083. wrapper.getMarkerList (false).applyTo (markersY);
  70084. setBoundingBox (wrapper.getBoundingBox());
  70085. builder.updateChildComponents (*this, wrapper.getChildList());
  70086. }
  70087. const ValueTree DrawableComposite::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70088. {
  70089. ValueTree tree (valueTreeType);
  70090. ValueTreeWrapper v (tree);
  70091. v.setID (getComponentID());
  70092. v.setBoundingBox (bounds, 0);
  70093. ValueTree childList (v.getChildListCreating (0));
  70094. for (int i = 0; i < getNumChildComponents(); ++i)
  70095. {
  70096. const Drawable* const d = dynamic_cast <const Drawable*> (getChildComponent(i));
  70097. jassert (d != 0); // You can't save a mix of Drawables and normal components!
  70098. childList.addChild (d->createValueTree (imageProvider), -1, 0);
  70099. }
  70100. v.getMarkerListCreating (true, 0).readFrom (markersX, 0);
  70101. v.getMarkerListCreating (false, 0).readFrom (markersY, 0);
  70102. return tree;
  70103. }
  70104. END_JUCE_NAMESPACE
  70105. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70106. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70107. BEGIN_JUCE_NAMESPACE
  70108. DrawableImage::DrawableImage()
  70109. : image (0),
  70110. opacity (1.0f),
  70111. overlayColour (0x00000000)
  70112. {
  70113. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70114. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70115. }
  70116. DrawableImage::DrawableImage (const DrawableImage& other)
  70117. : image (other.image),
  70118. opacity (other.opacity),
  70119. overlayColour (other.overlayColour),
  70120. bounds (other.bounds)
  70121. {
  70122. }
  70123. DrawableImage::~DrawableImage()
  70124. {
  70125. }
  70126. void DrawableImage::setImage (const Image& imageToUse)
  70127. {
  70128. image = imageToUse;
  70129. setBounds (imageToUse.getBounds());
  70130. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70131. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70132. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70133. recalculateCoordinates (0);
  70134. repaint();
  70135. }
  70136. void DrawableImage::setOpacity (const float newOpacity)
  70137. {
  70138. opacity = newOpacity;
  70139. }
  70140. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70141. {
  70142. overlayColour = newOverlayColour;
  70143. }
  70144. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70145. {
  70146. if (bounds != newBounds)
  70147. {
  70148. bounds = newBounds;
  70149. if (bounds.isDynamic())
  70150. {
  70151. Drawable::Positioner<DrawableImage>* const p = new Drawable::Positioner<DrawableImage> (*this);
  70152. setPositioner (p);
  70153. p->apply();
  70154. }
  70155. else
  70156. {
  70157. setPositioner (0);
  70158. recalculateCoordinates (0);
  70159. }
  70160. }
  70161. }
  70162. bool DrawableImage::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70163. {
  70164. bool ok = positioner.addPoint (bounds.topLeft);
  70165. ok = positioner.addPoint (bounds.topRight) && ok;
  70166. return positioner.addPoint (bounds.bottomLeft) && ok;
  70167. }
  70168. void DrawableImage::recalculateCoordinates (Expression::Scope* scope)
  70169. {
  70170. if (image.isValid())
  70171. {
  70172. Point<float> resolved[3];
  70173. bounds.resolveThreePoints (resolved, scope);
  70174. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70175. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70176. AffineTransform t (AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70177. tr.getX(), tr.getY(),
  70178. bl.getX(), bl.getY()));
  70179. if (t.isSingularity())
  70180. t = AffineTransform::identity;
  70181. setTransform (t);
  70182. }
  70183. }
  70184. void DrawableImage::paint (Graphics& g)
  70185. {
  70186. if (image.isValid())
  70187. {
  70188. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70189. {
  70190. g.setOpacity (opacity);
  70191. g.drawImageAt (image, 0, 0, false);
  70192. }
  70193. if (! overlayColour.isTransparent())
  70194. {
  70195. g.setColour (overlayColour.withMultipliedAlpha (opacity));
  70196. g.drawImageAt (image, 0, 0, true);
  70197. }
  70198. }
  70199. }
  70200. const Rectangle<float> DrawableImage::getDrawableBounds() const
  70201. {
  70202. return image.getBounds().toFloat();
  70203. }
  70204. bool DrawableImage::hitTest (int x, int y) const
  70205. {
  70206. return (! image.isNull())
  70207. && image.getPixelAt (x, y).getAlpha() >= 127;
  70208. }
  70209. Drawable* DrawableImage::createCopy() const
  70210. {
  70211. return new DrawableImage (*this);
  70212. }
  70213. const Identifier DrawableImage::valueTreeType ("Image");
  70214. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70215. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70216. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70217. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70218. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70219. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70220. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70221. : ValueTreeWrapperBase (state_)
  70222. {
  70223. jassert (state.hasType (valueTreeType));
  70224. }
  70225. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70226. {
  70227. return state [image];
  70228. }
  70229. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70230. {
  70231. return state.getPropertyAsValue (image, undoManager);
  70232. }
  70233. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70234. {
  70235. state.setProperty (image, newIdentifier, undoManager);
  70236. }
  70237. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70238. {
  70239. return (float) state.getProperty (opacity, 1.0);
  70240. }
  70241. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70242. {
  70243. if (! state.hasProperty (opacity))
  70244. state.setProperty (opacity, 1.0, undoManager);
  70245. return state.getPropertyAsValue (opacity, undoManager);
  70246. }
  70247. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70248. {
  70249. state.setProperty (opacity, newOpacity, undoManager);
  70250. }
  70251. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70252. {
  70253. return Colour (state [overlay].toString().getHexValue32());
  70254. }
  70255. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70256. {
  70257. if (newColour.isTransparent())
  70258. state.removeProperty (overlay, undoManager);
  70259. else
  70260. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70261. }
  70262. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70263. {
  70264. return state.getPropertyAsValue (overlay, undoManager);
  70265. }
  70266. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70267. {
  70268. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70269. state.getProperty (topRight, "100, 0"),
  70270. state.getProperty (bottomLeft, "0, 100"));
  70271. }
  70272. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70273. {
  70274. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70275. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70276. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70277. }
  70278. void DrawableImage::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70279. {
  70280. const ValueTreeWrapper controller (tree);
  70281. setComponentID (controller.getID());
  70282. const float newOpacity = controller.getOpacity();
  70283. const Colour newOverlayColour (controller.getOverlayColour());
  70284. Image newImage;
  70285. const var imageIdentifier (controller.getImageIdentifier());
  70286. jassert (builder.getImageProvider() != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70287. if (builder.getImageProvider() != 0)
  70288. newImage = builder.getImageProvider()->getImageForIdentifier (imageIdentifier);
  70289. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70290. if (bounds != newBounds || newOpacity != opacity
  70291. || overlayColour != newOverlayColour || image != newImage)
  70292. {
  70293. repaint();
  70294. opacity = newOpacity;
  70295. overlayColour = newOverlayColour;
  70296. if (image != newImage)
  70297. setImage (newImage);
  70298. setBoundingBox (newBounds);
  70299. }
  70300. }
  70301. const ValueTree DrawableImage::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70302. {
  70303. ValueTree tree (valueTreeType);
  70304. ValueTreeWrapper v (tree);
  70305. v.setID (getComponentID());
  70306. v.setOpacity (opacity, 0);
  70307. v.setOverlayColour (overlayColour, 0);
  70308. v.setBoundingBox (bounds, 0);
  70309. if (image.isValid())
  70310. {
  70311. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70312. if (imageProvider != 0)
  70313. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70314. }
  70315. return tree;
  70316. }
  70317. END_JUCE_NAMESPACE
  70318. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70319. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70320. BEGIN_JUCE_NAMESPACE
  70321. DrawablePath::DrawablePath()
  70322. {
  70323. }
  70324. DrawablePath::DrawablePath (const DrawablePath& other)
  70325. : DrawableShape (other)
  70326. {
  70327. if (other.relativePath != 0)
  70328. setPath (*other.relativePath);
  70329. else
  70330. setPath (other.path);
  70331. }
  70332. DrawablePath::~DrawablePath()
  70333. {
  70334. }
  70335. Drawable* DrawablePath::createCopy() const
  70336. {
  70337. return new DrawablePath (*this);
  70338. }
  70339. void DrawablePath::setPath (const Path& newPath)
  70340. {
  70341. path = newPath;
  70342. pathChanged();
  70343. }
  70344. const Path& DrawablePath::getPath() const
  70345. {
  70346. return path;
  70347. }
  70348. const Path& DrawablePath::getStrokePath() const
  70349. {
  70350. return strokePath;
  70351. }
  70352. void DrawablePath::applyRelativePath (const RelativePointPath& newRelativePath, Expression::Scope* scope)
  70353. {
  70354. Path newPath;
  70355. newRelativePath.createPath (newPath, scope);
  70356. if (path != newPath)
  70357. {
  70358. path.swapWithPath (newPath);
  70359. pathChanged();
  70360. }
  70361. }
  70362. class DrawablePath::RelativePositioner : public RelativeCoordinatePositionerBase
  70363. {
  70364. public:
  70365. RelativePositioner (DrawablePath& component_)
  70366. : RelativeCoordinatePositionerBase (component_),
  70367. owner (component_)
  70368. {
  70369. }
  70370. bool registerCoordinates()
  70371. {
  70372. bool ok = true;
  70373. jassert (owner.relativePath != 0);
  70374. const RelativePointPath& path = *owner.relativePath;
  70375. for (int i = 0; i < path.elements.size(); ++i)
  70376. {
  70377. RelativePointPath::ElementBase* const e = path.elements.getUnchecked(i);
  70378. int numPoints;
  70379. RelativePoint* const points = e->getControlPoints (numPoints);
  70380. for (int j = numPoints; --j >= 0;)
  70381. ok = addPoint (points[j]) && ok;
  70382. }
  70383. return ok;
  70384. }
  70385. void applyToComponentBounds()
  70386. {
  70387. jassert (owner.relativePath != 0);
  70388. ComponentScope scope (getComponent());
  70389. owner.applyRelativePath (*owner.relativePath, &scope);
  70390. }
  70391. private:
  70392. DrawablePath& owner;
  70393. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (RelativePositioner);
  70394. };
  70395. void DrawablePath::setPath (const RelativePointPath& newRelativePath)
  70396. {
  70397. if (newRelativePath.containsAnyDynamicPoints())
  70398. {
  70399. if (relativePath == 0 || newRelativePath != *relativePath)
  70400. {
  70401. relativePath = new RelativePointPath (newRelativePath);
  70402. RelativePositioner* const p = new RelativePositioner (*this);
  70403. setPositioner (p);
  70404. p->apply();
  70405. }
  70406. }
  70407. else
  70408. {
  70409. relativePath = 0;
  70410. applyRelativePath (newRelativePath, 0);
  70411. }
  70412. }
  70413. const Identifier DrawablePath::valueTreeType ("Path");
  70414. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70415. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70416. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70417. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70418. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70419. : FillAndStrokeState (state_)
  70420. {
  70421. jassert (state.hasType (valueTreeType));
  70422. }
  70423. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70424. {
  70425. return state.getOrCreateChildWithName (path, 0);
  70426. }
  70427. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70428. {
  70429. return state [nonZeroWinding];
  70430. }
  70431. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70432. {
  70433. state.setProperty (nonZeroWinding, b, undoManager);
  70434. }
  70435. void DrawablePath::ValueTreeWrapper::readFrom (const RelativePointPath& relativePath, UndoManager* undoManager)
  70436. {
  70437. setUsesNonZeroWinding (relativePath.usesNonZeroWinding, undoManager);
  70438. ValueTree pathTree (getPathState());
  70439. pathTree.removeAllChildren (undoManager);
  70440. for (int i = 0; i < relativePath.elements.size(); ++i)
  70441. pathTree.addChild (relativePath.elements.getUnchecked(i)->createTree(), -1, undoManager);
  70442. }
  70443. void DrawablePath::ValueTreeWrapper::writeTo (RelativePointPath& relativePath) const
  70444. {
  70445. relativePath.usesNonZeroWinding = usesNonZeroWinding();
  70446. RelativePoint points[3];
  70447. const ValueTree pathTree (state.getChildWithName (path));
  70448. const int num = pathTree.getNumChildren();
  70449. for (int i = 0; i < num; ++i)
  70450. {
  70451. const Element e (pathTree.getChild(i));
  70452. const int numCps = e.getNumControlPoints();
  70453. for (int j = 0; j < numCps; ++j)
  70454. points[j] = e.getControlPoint (j);
  70455. const Identifier type (e.getType());
  70456. RelativePointPath::ElementBase* newElement = 0;
  70457. if (type == Element::startSubPathElement) newElement = new RelativePointPath::StartSubPath (points[0]);
  70458. else if (type == Element::closeSubPathElement) newElement = new RelativePointPath::CloseSubPath();
  70459. else if (type == Element::lineToElement) newElement = new RelativePointPath::LineTo (points[0]);
  70460. else if (type == Element::quadraticToElement) newElement = new RelativePointPath::QuadraticTo (points[0], points[1]);
  70461. else if (type == Element::cubicToElement) newElement = new RelativePointPath::CubicTo (points[0], points[1], points[2]);
  70462. else jassertfalse;
  70463. relativePath.addElement (newElement);
  70464. }
  70465. }
  70466. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70467. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70468. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70469. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70470. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70471. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70472. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70473. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70474. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70475. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70476. : state (state_)
  70477. {
  70478. }
  70479. DrawablePath::ValueTreeWrapper::Element::~Element()
  70480. {
  70481. }
  70482. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70483. {
  70484. return ValueTreeWrapper (state.getParent().getParent());
  70485. }
  70486. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70487. {
  70488. return Element (state.getSibling (-1));
  70489. }
  70490. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70491. {
  70492. const Identifier i (state.getType());
  70493. if (i == startSubPathElement || i == lineToElement) return 1;
  70494. if (i == quadraticToElement) return 2;
  70495. if (i == cubicToElement) return 3;
  70496. return 0;
  70497. }
  70498. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70499. {
  70500. jassert (index >= 0 && index < getNumControlPoints());
  70501. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70502. }
  70503. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70504. {
  70505. jassert (index >= 0 && index < getNumControlPoints());
  70506. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70507. }
  70508. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70509. {
  70510. jassert (index >= 0 && index < getNumControlPoints());
  70511. state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70512. }
  70513. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70514. {
  70515. const Identifier i (state.getType());
  70516. if (i == startSubPathElement)
  70517. return getControlPoint (0);
  70518. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70519. return getPreviousElement().getEndPoint();
  70520. }
  70521. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70522. {
  70523. const Identifier i (state.getType());
  70524. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70525. if (i == quadraticToElement) return getControlPoint (1);
  70526. if (i == cubicToElement) return getControlPoint (2);
  70527. jassert (i == closeSubPathElement);
  70528. return RelativePoint();
  70529. }
  70530. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::Scope* scope) const
  70531. {
  70532. const Identifier i (state.getType());
  70533. if (i == lineToElement || i == closeSubPathElement)
  70534. return getEndPoint().resolve (scope).getDistanceFrom (getStartPoint().resolve (scope));
  70535. if (i == cubicToElement)
  70536. {
  70537. Path p;
  70538. p.startNewSubPath (getStartPoint().resolve (scope));
  70539. p.cubicTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope), getControlPoint (2).resolve (scope));
  70540. return p.getLength();
  70541. }
  70542. if (i == quadraticToElement)
  70543. {
  70544. Path p;
  70545. p.startNewSubPath (getStartPoint().resolve (scope));
  70546. p.quadraticTo (getControlPoint (0).resolve (scope), getControlPoint (1).resolve (scope));
  70547. return p.getLength();
  70548. }
  70549. jassert (i == startSubPathElement);
  70550. return 0;
  70551. }
  70552. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70553. {
  70554. return state [mode].toString();
  70555. }
  70556. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70557. {
  70558. if (state.hasType (cubicToElement))
  70559. state.setProperty (mode, newMode, undoManager);
  70560. }
  70561. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70562. {
  70563. const Identifier i (state.getType());
  70564. if (i == quadraticToElement || i == cubicToElement)
  70565. {
  70566. ValueTree newState (lineToElement);
  70567. Element e (newState);
  70568. e.setControlPoint (0, getEndPoint(), undoManager);
  70569. state = newState;
  70570. }
  70571. }
  70572. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::Scope* scope, UndoManager* undoManager)
  70573. {
  70574. const Identifier i (state.getType());
  70575. if (i == lineToElement || i == quadraticToElement)
  70576. {
  70577. ValueTree newState (cubicToElement);
  70578. Element e (newState);
  70579. const RelativePoint start (getStartPoint());
  70580. const RelativePoint end (getEndPoint());
  70581. const Point<float> startResolved (start.resolve (scope));
  70582. const Point<float> endResolved (end.resolve (scope));
  70583. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70584. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70585. e.setControlPoint (2, end, undoManager);
  70586. state = newState;
  70587. }
  70588. }
  70589. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70590. {
  70591. const Identifier i (state.getType());
  70592. if (i != startSubPathElement)
  70593. {
  70594. ValueTree newState (startSubPathElement);
  70595. Element e (newState);
  70596. e.setControlPoint (0, getEndPoint(), undoManager);
  70597. state = newState;
  70598. }
  70599. }
  70600. namespace DrawablePathHelpers
  70601. {
  70602. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70603. {
  70604. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70605. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70606. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70607. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70608. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70609. return newCp1 + (newCp2 - newCp1) * proportion;
  70610. }
  70611. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70612. {
  70613. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70614. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70615. return mid1 + (mid2 - mid1) * proportion;
  70616. }
  70617. }
  70618. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::Scope* scope) const
  70619. {
  70620. using namespace DrawablePathHelpers;
  70621. const Identifier type (state.getType());
  70622. float bestProp = 0;
  70623. if (type == cubicToElement)
  70624. {
  70625. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70626. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70627. float bestDistance = std::numeric_limits<float>::max();
  70628. for (int i = 110; --i >= 0;)
  70629. {
  70630. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70631. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70632. const float distance = centre.getDistanceFrom (targetPoint);
  70633. if (distance < bestDistance)
  70634. {
  70635. bestProp = prop;
  70636. bestDistance = distance;
  70637. }
  70638. }
  70639. }
  70640. else if (type == quadraticToElement)
  70641. {
  70642. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70643. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70644. float bestDistance = std::numeric_limits<float>::max();
  70645. for (int i = 110; --i >= 0;)
  70646. {
  70647. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70648. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70649. const float distance = centre.getDistanceFrom (targetPoint);
  70650. if (distance < bestDistance)
  70651. {
  70652. bestProp = prop;
  70653. bestDistance = distance;
  70654. }
  70655. }
  70656. }
  70657. else if (type == lineToElement)
  70658. {
  70659. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70660. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70661. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70662. }
  70663. return bestProp;
  70664. }
  70665. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::Scope* scope, UndoManager* undoManager)
  70666. {
  70667. ValueTree newTree;
  70668. const Identifier type (state.getType());
  70669. if (type == cubicToElement)
  70670. {
  70671. float bestProp = findProportionAlongLine (targetPoint, scope);
  70672. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70673. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope), rp4.resolve (scope) };
  70674. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70675. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70676. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70677. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70678. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70679. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70680. setControlPoint (0, mid1, undoManager);
  70681. setControlPoint (1, newCp1, undoManager);
  70682. setControlPoint (2, newCentre, undoManager);
  70683. setModeOfEndPoint (roundedMode, undoManager);
  70684. Element newElement (newTree = ValueTree (cubicToElement));
  70685. newElement.setControlPoint (0, newCp2, 0);
  70686. newElement.setControlPoint (1, mid3, 0);
  70687. newElement.setControlPoint (2, rp4, 0);
  70688. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70689. }
  70690. else if (type == quadraticToElement)
  70691. {
  70692. float bestProp = findProportionAlongLine (targetPoint, scope);
  70693. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70694. const Point<float> points[] = { rp1.resolve (scope), rp2.resolve (scope), rp3.resolve (scope) };
  70695. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70696. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70697. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70698. setControlPoint (0, mid1, undoManager);
  70699. setControlPoint (1, newCentre, undoManager);
  70700. setModeOfEndPoint (roundedMode, undoManager);
  70701. Element newElement (newTree = ValueTree (quadraticToElement));
  70702. newElement.setControlPoint (0, mid2, 0);
  70703. newElement.setControlPoint (1, rp3, 0);
  70704. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70705. }
  70706. else if (type == lineToElement)
  70707. {
  70708. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70709. const Line<float> line (rp1.resolve (scope), rp2.resolve (scope));
  70710. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70711. setControlPoint (0, newPoint, undoManager);
  70712. Element newElement (newTree = ValueTree (lineToElement));
  70713. newElement.setControlPoint (0, rp2, 0);
  70714. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70715. }
  70716. else if (type == closeSubPathElement)
  70717. {
  70718. }
  70719. return newTree;
  70720. }
  70721. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70722. {
  70723. state.getParent().removeChild (state, undoManager);
  70724. }
  70725. void DrawablePath::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70726. {
  70727. ValueTreeWrapper v (tree);
  70728. setComponentID (v.getID());
  70729. refreshFillTypes (v, builder.getImageProvider());
  70730. setStrokeType (v.getStrokeType());
  70731. RelativePointPath newRelativePath;
  70732. v.writeTo (newRelativePath);
  70733. setPath (newRelativePath);
  70734. }
  70735. const ValueTree DrawablePath::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70736. {
  70737. ValueTree tree (valueTreeType);
  70738. ValueTreeWrapper v (tree);
  70739. v.setID (getComponentID());
  70740. writeTo (v, imageProvider, 0);
  70741. if (relativePath != 0)
  70742. v.readFrom (*relativePath, 0);
  70743. else
  70744. v.readFrom (RelativePointPath (path), 0);
  70745. return tree;
  70746. }
  70747. END_JUCE_NAMESPACE
  70748. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70749. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70750. BEGIN_JUCE_NAMESPACE
  70751. DrawableRectangle::DrawableRectangle()
  70752. {
  70753. }
  70754. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70755. : DrawableShape (other),
  70756. bounds (other.bounds),
  70757. cornerSize (other.cornerSize)
  70758. {
  70759. }
  70760. DrawableRectangle::~DrawableRectangle()
  70761. {
  70762. }
  70763. Drawable* DrawableRectangle::createCopy() const
  70764. {
  70765. return new DrawableRectangle (*this);
  70766. }
  70767. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  70768. {
  70769. if (bounds != newBounds)
  70770. {
  70771. bounds = newBounds;
  70772. rebuildPath();
  70773. }
  70774. }
  70775. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  70776. {
  70777. if (cornerSize != newSize)
  70778. {
  70779. cornerSize = newSize;
  70780. rebuildPath();
  70781. }
  70782. }
  70783. void DrawableRectangle::rebuildPath()
  70784. {
  70785. if (bounds.isDynamic() || cornerSize.isDynamic())
  70786. {
  70787. Drawable::Positioner<DrawableRectangle>* const p = new Drawable::Positioner<DrawableRectangle> (*this);
  70788. setPositioner (p);
  70789. p->apply();
  70790. }
  70791. else
  70792. {
  70793. setPositioner (0);
  70794. recalculateCoordinates (0);
  70795. }
  70796. }
  70797. bool DrawableRectangle::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70798. {
  70799. bool ok = positioner.addPoint (bounds.topLeft);
  70800. ok = positioner.addPoint (bounds.topRight) && ok;
  70801. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70802. return positioner.addPoint (cornerSize) && ok;
  70803. }
  70804. void DrawableRectangle::recalculateCoordinates (Expression::Scope* scope)
  70805. {
  70806. Point<float> points[3];
  70807. bounds.resolveThreePoints (points, scope);
  70808. const float cornerSizeX = (float) cornerSize.x.resolve (scope);
  70809. const float cornerSizeY = (float) cornerSize.y.resolve (scope);
  70810. const float w = Line<float> (points[0], points[1]).getLength();
  70811. const float h = Line<float> (points[0], points[2]).getLength();
  70812. Path newPath;
  70813. if (cornerSizeX > 0 && cornerSizeY > 0)
  70814. newPath.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  70815. else
  70816. newPath.addRectangle (0, 0, w, h);
  70817. newPath.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70818. w, 0, points[1].getX(), points[1].getY(),
  70819. 0, h, points[2].getX(), points[2].getY()));
  70820. if (path != newPath)
  70821. {
  70822. path.swapWithPath (newPath);
  70823. pathChanged();
  70824. }
  70825. }
  70826. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  70827. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  70828. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  70829. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70830. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  70831. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70832. : FillAndStrokeState (state_)
  70833. {
  70834. jassert (state.hasType (valueTreeType));
  70835. }
  70836. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  70837. {
  70838. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70839. state.getProperty (topRight, "100, 0"),
  70840. state.getProperty (bottomLeft, "0, 100"));
  70841. }
  70842. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70843. {
  70844. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70845. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70846. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70847. }
  70848. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  70849. {
  70850. state.setProperty (cornerSize, newSize.toString(), undoManager);
  70851. }
  70852. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  70853. {
  70854. return RelativePoint (state [cornerSize]);
  70855. }
  70856. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  70857. {
  70858. return state.getPropertyAsValue (cornerSize, undoManager);
  70859. }
  70860. void DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ComponentBuilder& builder)
  70861. {
  70862. ValueTreeWrapper v (tree);
  70863. setComponentID (v.getID());
  70864. refreshFillTypes (v, builder.getImageProvider());
  70865. setStrokeType (v.getStrokeType());
  70866. setRectangle (v.getRectangle());
  70867. setCornerSize (v.getCornerSize());
  70868. }
  70869. const ValueTree DrawableRectangle::createValueTree (ComponentBuilder::ImageProvider* imageProvider) const
  70870. {
  70871. ValueTree tree (valueTreeType);
  70872. ValueTreeWrapper v (tree);
  70873. v.setID (getComponentID());
  70874. writeTo (v, imageProvider, 0);
  70875. v.setRectangle (bounds, 0);
  70876. v.setCornerSize (cornerSize, 0);
  70877. return tree;
  70878. }
  70879. END_JUCE_NAMESPACE
  70880. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  70881. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70882. BEGIN_JUCE_NAMESPACE
  70883. DrawableText::DrawableText()
  70884. : colour (Colours::black),
  70885. justification (Justification::centredLeft)
  70886. {
  70887. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70888. RelativePoint (50.0f, 0.0f),
  70889. RelativePoint (0.0f, 20.0f)));
  70890. setFont (Font (15.0f), true);
  70891. }
  70892. DrawableText::DrawableText (const DrawableText& other)
  70893. : bounds (other.bounds),
  70894. fontSizeControlPoint (other.fontSizeControlPoint),
  70895. font (other.font),
  70896. text (other.text),
  70897. colour (other.colour),
  70898. justification (other.justification)
  70899. {
  70900. }
  70901. DrawableText::~DrawableText()
  70902. {
  70903. }
  70904. void DrawableText::setText (const String& newText)
  70905. {
  70906. if (text != newText)
  70907. {
  70908. text = newText;
  70909. refreshBounds();
  70910. }
  70911. }
  70912. void DrawableText::setColour (const Colour& newColour)
  70913. {
  70914. if (colour != newColour)
  70915. {
  70916. colour = newColour;
  70917. repaint();
  70918. }
  70919. }
  70920. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70921. {
  70922. if (font != newFont)
  70923. {
  70924. font = newFont;
  70925. if (applySizeAndScale)
  70926. {
  70927. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (resolvedPoints,
  70928. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70929. }
  70930. refreshBounds();
  70931. }
  70932. }
  70933. void DrawableText::setJustification (const Justification& newJustification)
  70934. {
  70935. justification = newJustification;
  70936. repaint();
  70937. }
  70938. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70939. {
  70940. if (bounds != newBounds)
  70941. {
  70942. bounds = newBounds;
  70943. refreshBounds();
  70944. }
  70945. }
  70946. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70947. {
  70948. if (fontSizeControlPoint != newPoint)
  70949. {
  70950. fontSizeControlPoint = newPoint;
  70951. refreshBounds();
  70952. }
  70953. }
  70954. void DrawableText::refreshBounds()
  70955. {
  70956. if (bounds.isDynamic() || fontSizeControlPoint.isDynamic())
  70957. {
  70958. Drawable::Positioner<DrawableText>* const p = new Drawable::Positioner<DrawableText> (*this);
  70959. setPositioner (p);
  70960. p->apply();
  70961. }
  70962. else
  70963. {
  70964. setPositioner (0);
  70965. recalculateCoordinates (0);
  70966. }
  70967. }
  70968. bool DrawableText::registerCoordinates (RelativeCoordinatePositionerBase& positioner)
  70969. {
  70970. bool ok = positioner.addPoint (bounds.topLeft);
  70971. ok = positioner.addPoint (bounds.topRight) && ok;
  70972. ok = positioner.addPoint (bounds.bottomLeft) && ok;
  70973. return positioner.addPoint (fontSizeControlPoint) && ok;
  70974. }
  70975. void DrawableText::recalculateCoordinates (Expression::Scope* scope)
  70976. {
  70977. bounds.resolveThreePoints (resolvedPoints, scope);
  70978. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70979. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70980. const Point<float> fontCoords (RelativeParallelogram::getInternalCoordForPoint (resolvedPoints, fontSizeControlPoint.resolve (scope)));
  70981. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  70982. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  70983. scaledFont = font;
  70984. scaledFont.setHeight (fontHeight);
  70985. scaledFont.setHorizontalScale (fontWidth / fontHeight);
  70986. setBoundsToEnclose (getDrawableBounds());
  70987. repaint();
  70988. }
  70989. const AffineTransform DrawableText::getArrangementAndTransform (GlyphArrangement& glyphs) const
  70990. {
  70991. const float w = Line<float> (resolvedPoints[0], resolvedPoints[1]).getLength();
  70992. const float h = Line<float> (resolvedPoints[0], resolvedPoints[2]).getLength();
  70993. glyphs.addFittedText (scaledFont, text, 0, 0, w, h, justification, 0x100000);
  70994. return AffineTransform::fromTargetPoints (0, 0, resolvedPoints[0].getX(), resolvedPoints[0].getY(),
  70995. w, 0, resolvedPoints[1].getX(), resolvedPoints[1].getY(),
  70996. 0, h, resolvedPoints[2].getX(), resolvedPoints[2].getY());
  70997. }
  70998. void DrawableText::paint (Graphics& g)
  70999. {
  71000. transformContextToCorrectOrigin (g);
  71001. g.setColour (colour);
  71002. GlyphArrangement ga;
  71003. const AffineTransform transform (getArrangementAndTransform (ga));
  71004. ga.draw (g, transform);
  71005. }
  71006. const Rectangle<float> DrawableText::getDrawableBounds() const
  71007. {
  71008. return RelativeParallelogram::getBoundingBox (resolvedPoints);
  71009. }
  71010. Drawable* DrawableText::createCopy() const
  71011. {
  71012. return new DrawableText (*this);
  71013. }
  71014. const Identifier DrawableText::valueTreeType ("Text");
  71015. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71016. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71017. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71018. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71019. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71020. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71021. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71022. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71023. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71024. : ValueTreeWrapperBase (state_)
  71025. {
  71026. jassert (state.hasType (valueTreeType));
  71027. }
  71028. const String DrawableText::ValueTreeWrapper::getText() const
  71029. {
  71030. return state [text].toString();
  71031. }
  71032. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71033. {
  71034. state.setProperty (text, newText, undoManager);
  71035. }
  71036. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71037. {
  71038. return state.getPropertyAsValue (text, undoManager);
  71039. }
  71040. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71041. {
  71042. return Colour::fromString (state [colour].toString());
  71043. }
  71044. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71045. {
  71046. state.setProperty (colour, newColour.toString(), undoManager);
  71047. }
  71048. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71049. {
  71050. return Justification ((int) state [justification]);
  71051. }
  71052. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71053. {
  71054. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71055. }
  71056. const Font DrawableText::ValueTreeWrapper::getFont() const
  71057. {
  71058. return Font::fromString (state [font]);
  71059. }
  71060. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71061. {
  71062. state.setProperty (font, newFont.toString(), undoManager);
  71063. }
  71064. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71065. {
  71066. return state.getPropertyAsValue (font, undoManager);
  71067. }
  71068. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71069. {
  71070. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71071. }
  71072. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71073. {
  71074. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71075. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71076. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71077. }
  71078. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71079. {
  71080. return state [fontSizeAnchor].toString();
  71081. }
  71082. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71083. {
  71084. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71085. }
  71086. void DrawableText::refreshFromValueTree (const ValueTree& tree, ComponentBuilder&)
  71087. {
  71088. ValueTreeWrapper v (tree);
  71089. setComponentID (v.getID());
  71090. const RelativeParallelogram newBounds (v.getBoundingBox());
  71091. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71092. const Colour newColour (v.getColour());
  71093. const Justification newJustification (v.getJustification());
  71094. const String newText (v.getText());
  71095. const Font newFont (v.getFont());
  71096. if (text != newText || font != newFont || justification != newJustification
  71097. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71098. {
  71099. setBoundingBox (newBounds);
  71100. setFontSizeControlPoint (newFontPoint);
  71101. setColour (newColour);
  71102. setFont (newFont, false);
  71103. setJustification (newJustification);
  71104. setText (newText);
  71105. }
  71106. }
  71107. const ValueTree DrawableText::createValueTree (ComponentBuilder::ImageProvider*) const
  71108. {
  71109. ValueTree tree (valueTreeType);
  71110. ValueTreeWrapper v (tree);
  71111. v.setID (getComponentID());
  71112. v.setText (text, 0);
  71113. v.setFont (font, 0);
  71114. v.setJustification (justification, 0);
  71115. v.setColour (colour, 0);
  71116. v.setBoundingBox (bounds, 0);
  71117. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71118. return tree;
  71119. }
  71120. END_JUCE_NAMESPACE
  71121. /*** End of inlined file: juce_DrawableText.cpp ***/
  71122. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71123. BEGIN_JUCE_NAMESPACE
  71124. class SVGState
  71125. {
  71126. public:
  71127. SVGState (const XmlElement* const topLevel)
  71128. : topLevelXml (topLevel),
  71129. elementX (0), elementY (0),
  71130. width (512), height (512),
  71131. viewBoxW (0), viewBoxH (0)
  71132. {
  71133. }
  71134. Drawable* parseSVGElement (const XmlElement& xml)
  71135. {
  71136. if (! xml.hasTagName ("svg"))
  71137. return 0;
  71138. DrawableComposite* const drawable = new DrawableComposite();
  71139. drawable->setName (xml.getStringAttribute ("id"));
  71140. SVGState newState (*this);
  71141. if (xml.hasAttribute ("transform"))
  71142. newState.addTransform (xml);
  71143. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71144. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71145. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71146. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71147. if (xml.hasAttribute ("viewBox"))
  71148. {
  71149. const String viewBoxAtt (xml.getStringAttribute ("viewBox"));
  71150. String::CharPointerType viewParams (viewBoxAtt.getCharPointer());
  71151. float vx, vy, vw, vh;
  71152. if (parseCoords (viewParams, vx, vy, true)
  71153. && parseCoords (viewParams, vw, vh, true)
  71154. && vw > 0
  71155. && vh > 0)
  71156. {
  71157. newState.viewBoxW = vw;
  71158. newState.viewBoxH = vh;
  71159. int placementFlags = 0;
  71160. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71161. if (aspect.containsIgnoreCase ("none"))
  71162. {
  71163. placementFlags = RectanglePlacement::stretchToFit;
  71164. }
  71165. else
  71166. {
  71167. if (aspect.containsIgnoreCase ("slice"))
  71168. placementFlags |= RectanglePlacement::fillDestination;
  71169. if (aspect.containsIgnoreCase ("xMin"))
  71170. placementFlags |= RectanglePlacement::xLeft;
  71171. else if (aspect.containsIgnoreCase ("xMax"))
  71172. placementFlags |= RectanglePlacement::xRight;
  71173. else
  71174. placementFlags |= RectanglePlacement::xMid;
  71175. if (aspect.containsIgnoreCase ("yMin"))
  71176. placementFlags |= RectanglePlacement::yTop;
  71177. else if (aspect.containsIgnoreCase ("yMax"))
  71178. placementFlags |= RectanglePlacement::yBottom;
  71179. else
  71180. placementFlags |= RectanglePlacement::yMid;
  71181. }
  71182. const RectanglePlacement placement (placementFlags);
  71183. newState.transform
  71184. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71185. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71186. .followedBy (newState.transform);
  71187. }
  71188. }
  71189. else
  71190. {
  71191. if (viewBoxW == 0)
  71192. newState.viewBoxW = newState.width;
  71193. if (viewBoxH == 0)
  71194. newState.viewBoxH = newState.height;
  71195. }
  71196. newState.parseSubElements (xml, drawable);
  71197. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71198. return drawable;
  71199. }
  71200. private:
  71201. const XmlElement* const topLevelXml;
  71202. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71203. AffineTransform transform;
  71204. String cssStyleText;
  71205. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71206. {
  71207. forEachXmlChildElement (xml, e)
  71208. {
  71209. Drawable* d = 0;
  71210. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71211. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71212. else if (e->hasTagName ("path")) d = parsePath (*e);
  71213. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71214. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71215. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71216. else if (e->hasTagName ("line")) d = parseLine (*e);
  71217. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71218. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71219. else if (e->hasTagName ("text")) d = parseText (*e);
  71220. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71221. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71222. parentDrawable->addAndMakeVisible (d);
  71223. }
  71224. }
  71225. DrawableComposite* parseSwitch (const XmlElement& xml)
  71226. {
  71227. const XmlElement* const group = xml.getChildByName ("g");
  71228. if (group != 0)
  71229. return parseGroupElement (*group);
  71230. return 0;
  71231. }
  71232. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71233. {
  71234. DrawableComposite* const drawable = new DrawableComposite();
  71235. drawable->setName (xml.getStringAttribute ("id"));
  71236. if (xml.hasAttribute ("transform"))
  71237. {
  71238. SVGState newState (*this);
  71239. newState.addTransform (xml);
  71240. newState.parseSubElements (xml, drawable);
  71241. }
  71242. else
  71243. {
  71244. parseSubElements (xml, drawable);
  71245. }
  71246. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71247. return drawable;
  71248. }
  71249. Drawable* parsePath (const XmlElement& xml) const
  71250. {
  71251. const String dAttribute (xml.getStringAttribute ("d").trimStart());
  71252. String::CharPointerType d (dAttribute.getCharPointer());
  71253. Path path;
  71254. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71255. path.setUsingNonZeroWinding (false);
  71256. float lastX = 0, lastY = 0;
  71257. float lastX2 = 0, lastY2 = 0;
  71258. juce_wchar lastCommandChar = 0;
  71259. bool isRelative = true;
  71260. bool carryOn = true;
  71261. const CharPointer_ASCII validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71262. while (! d.isEmpty())
  71263. {
  71264. float x, y, x2, y2, x3, y3;
  71265. if (validCommandChars.indexOf (*d) >= 0)
  71266. {
  71267. lastCommandChar = d.getAndAdvance();
  71268. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71269. }
  71270. switch (lastCommandChar)
  71271. {
  71272. case 'M':
  71273. case 'm':
  71274. case 'L':
  71275. case 'l':
  71276. if (parseCoords (d, x, y, false))
  71277. {
  71278. if (isRelative)
  71279. {
  71280. x += lastX;
  71281. y += lastY;
  71282. }
  71283. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71284. {
  71285. path.startNewSubPath (x, y);
  71286. lastCommandChar = 'l';
  71287. }
  71288. else
  71289. path.lineTo (x, y);
  71290. lastX2 = lastX;
  71291. lastY2 = lastY;
  71292. lastX = x;
  71293. lastY = y;
  71294. }
  71295. else
  71296. {
  71297. ++d;
  71298. }
  71299. break;
  71300. case 'H':
  71301. case 'h':
  71302. if (parseCoord (d, x, false, true))
  71303. {
  71304. if (isRelative)
  71305. x += lastX;
  71306. path.lineTo (x, lastY);
  71307. lastX2 = lastX;
  71308. lastX = x;
  71309. }
  71310. else
  71311. {
  71312. ++d;
  71313. }
  71314. break;
  71315. case 'V':
  71316. case 'v':
  71317. if (parseCoord (d, y, false, false))
  71318. {
  71319. if (isRelative)
  71320. y += lastY;
  71321. path.lineTo (lastX, y);
  71322. lastY2 = lastY;
  71323. lastY = y;
  71324. }
  71325. else
  71326. {
  71327. ++d;
  71328. }
  71329. break;
  71330. case 'C':
  71331. case 'c':
  71332. if (parseCoords (d, x, y, false)
  71333. && parseCoords (d, x2, y2, false)
  71334. && parseCoords (d, x3, y3, false))
  71335. {
  71336. if (isRelative)
  71337. {
  71338. x += lastX;
  71339. y += lastY;
  71340. x2 += lastX;
  71341. y2 += lastY;
  71342. x3 += lastX;
  71343. y3 += lastY;
  71344. }
  71345. path.cubicTo (x, y, x2, y2, x3, y3);
  71346. lastX2 = x2;
  71347. lastY2 = y2;
  71348. lastX = x3;
  71349. lastY = y3;
  71350. }
  71351. else
  71352. {
  71353. ++d;
  71354. }
  71355. break;
  71356. case 'S':
  71357. case 's':
  71358. if (parseCoords (d, x, y, false)
  71359. && parseCoords (d, x3, y3, false))
  71360. {
  71361. if (isRelative)
  71362. {
  71363. x += lastX;
  71364. y += lastY;
  71365. x3 += lastX;
  71366. y3 += lastY;
  71367. }
  71368. x2 = lastX + (lastX - lastX2);
  71369. y2 = lastY + (lastY - lastY2);
  71370. path.cubicTo (x2, y2, x, y, x3, y3);
  71371. lastX2 = x;
  71372. lastY2 = y;
  71373. lastX = x3;
  71374. lastY = y3;
  71375. }
  71376. else
  71377. {
  71378. ++d;
  71379. }
  71380. break;
  71381. case 'Q':
  71382. case 'q':
  71383. if (parseCoords (d, x, y, false)
  71384. && parseCoords (d, x2, y2, false))
  71385. {
  71386. if (isRelative)
  71387. {
  71388. x += lastX;
  71389. y += lastY;
  71390. x2 += lastX;
  71391. y2 += lastY;
  71392. }
  71393. path.quadraticTo (x, y, x2, y2);
  71394. lastX2 = x;
  71395. lastY2 = y;
  71396. lastX = x2;
  71397. lastY = y2;
  71398. }
  71399. else
  71400. {
  71401. ++d;
  71402. }
  71403. break;
  71404. case 'T':
  71405. case 't':
  71406. if (parseCoords (d, x, y, false))
  71407. {
  71408. if (isRelative)
  71409. {
  71410. x += lastX;
  71411. y += lastY;
  71412. }
  71413. x2 = lastX + (lastX - lastX2);
  71414. y2 = lastY + (lastY - lastY2);
  71415. path.quadraticTo (x2, y2, x, y);
  71416. lastX2 = x2;
  71417. lastY2 = y2;
  71418. lastX = x;
  71419. lastY = y;
  71420. }
  71421. else
  71422. {
  71423. ++d;
  71424. }
  71425. break;
  71426. case 'A':
  71427. case 'a':
  71428. if (parseCoords (d, x, y, false))
  71429. {
  71430. String num;
  71431. if (parseNextNumber (d, num, false))
  71432. {
  71433. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71434. if (parseNextNumber (d, num, false))
  71435. {
  71436. const bool largeArc = num.getIntValue() != 0;
  71437. if (parseNextNumber (d, num, false))
  71438. {
  71439. const bool sweep = num.getIntValue() != 0;
  71440. if (parseCoords (d, x2, y2, false))
  71441. {
  71442. if (isRelative)
  71443. {
  71444. x2 += lastX;
  71445. y2 += lastY;
  71446. }
  71447. if (lastX != x2 || lastY != y2)
  71448. {
  71449. double centreX, centreY, startAngle, deltaAngle;
  71450. double rx = x, ry = y;
  71451. endpointToCentreParameters (lastX, lastY, x2, y2,
  71452. angle, largeArc, sweep,
  71453. rx, ry, centreX, centreY,
  71454. startAngle, deltaAngle);
  71455. path.addCentredArc ((float) centreX, (float) centreY,
  71456. (float) rx, (float) ry,
  71457. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71458. false);
  71459. path.lineTo (x2, y2);
  71460. }
  71461. lastX2 = lastX;
  71462. lastY2 = lastY;
  71463. lastX = x2;
  71464. lastY = y2;
  71465. }
  71466. }
  71467. }
  71468. }
  71469. }
  71470. else
  71471. {
  71472. ++d;
  71473. }
  71474. break;
  71475. case 'Z':
  71476. case 'z':
  71477. path.closeSubPath();
  71478. d = d.findEndOfWhitespace();
  71479. break;
  71480. default:
  71481. carryOn = false;
  71482. break;
  71483. }
  71484. if (! carryOn)
  71485. break;
  71486. }
  71487. return parseShape (xml, path);
  71488. }
  71489. Drawable* parseRect (const XmlElement& xml) const
  71490. {
  71491. Path rect;
  71492. const bool hasRX = xml.hasAttribute ("rx");
  71493. const bool hasRY = xml.hasAttribute ("ry");
  71494. if (hasRX || hasRY)
  71495. {
  71496. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71497. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71498. if (! hasRX)
  71499. rx = ry;
  71500. else if (! hasRY)
  71501. ry = rx;
  71502. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71503. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71504. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71505. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71506. rx, ry);
  71507. }
  71508. else
  71509. {
  71510. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71511. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71512. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71513. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71514. }
  71515. return parseShape (xml, rect);
  71516. }
  71517. Drawable* parseCircle (const XmlElement& xml) const
  71518. {
  71519. Path circle;
  71520. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71521. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71522. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71523. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71524. return parseShape (xml, circle);
  71525. }
  71526. Drawable* parseEllipse (const XmlElement& xml) const
  71527. {
  71528. Path ellipse;
  71529. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71530. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71531. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71532. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71533. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71534. return parseShape (xml, ellipse);
  71535. }
  71536. Drawable* parseLine (const XmlElement& xml) const
  71537. {
  71538. Path line;
  71539. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71540. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71541. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71542. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71543. line.startNewSubPath (x1, y1);
  71544. line.lineTo (x2, y2);
  71545. return parseShape (xml, line);
  71546. }
  71547. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71548. {
  71549. const String pointsAtt (xml.getStringAttribute ("points"));
  71550. String::CharPointerType points (pointsAtt.getCharPointer());
  71551. Path path;
  71552. float x, y;
  71553. if (parseCoords (points, x, y, true))
  71554. {
  71555. float firstX = x;
  71556. float firstY = y;
  71557. float lastX = 0, lastY = 0;
  71558. path.startNewSubPath (x, y);
  71559. while (parseCoords (points, x, y, true))
  71560. {
  71561. lastX = x;
  71562. lastY = y;
  71563. path.lineTo (x, y);
  71564. }
  71565. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71566. path.closeSubPath();
  71567. }
  71568. return parseShape (xml, path);
  71569. }
  71570. Drawable* parseShape (const XmlElement& xml, Path& path,
  71571. const bool shouldParseTransform = true) const
  71572. {
  71573. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71574. {
  71575. SVGState newState (*this);
  71576. newState.addTransform (xml);
  71577. return newState.parseShape (xml, path, false);
  71578. }
  71579. DrawablePath* dp = new DrawablePath();
  71580. dp->setName (xml.getStringAttribute ("id"));
  71581. dp->setFill (Colours::transparentBlack);
  71582. path.applyTransform (transform);
  71583. dp->setPath (path);
  71584. Path::Iterator iter (path);
  71585. bool containsClosedSubPath = false;
  71586. while (iter.next())
  71587. {
  71588. if (iter.elementType == Path::Iterator::closePath)
  71589. {
  71590. containsClosedSubPath = true;
  71591. break;
  71592. }
  71593. }
  71594. dp->setFill (getPathFillType (path,
  71595. getStyleAttribute (&xml, "fill"),
  71596. getStyleAttribute (&xml, "fill-opacity"),
  71597. getStyleAttribute (&xml, "opacity"),
  71598. containsClosedSubPath ? Colours::black
  71599. : Colours::transparentBlack));
  71600. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71601. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71602. {
  71603. dp->setStrokeFill (getPathFillType (path, strokeType,
  71604. getStyleAttribute (&xml, "stroke-opacity"),
  71605. getStyleAttribute (&xml, "opacity"),
  71606. Colours::transparentBlack));
  71607. dp->setStrokeType (getStrokeFor (&xml));
  71608. }
  71609. return dp;
  71610. }
  71611. const XmlElement* findLinkedElement (const XmlElement* e) const
  71612. {
  71613. const String id (e->getStringAttribute ("xlink:href"));
  71614. if (! id.startsWithChar ('#'))
  71615. return 0;
  71616. return findElementForId (topLevelXml, id.substring (1));
  71617. }
  71618. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71619. {
  71620. if (fillXml == 0)
  71621. return;
  71622. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71623. {
  71624. int index = 0;
  71625. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71626. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71627. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71628. double offset = e->getDoubleAttribute ("offset");
  71629. if (e->getStringAttribute ("offset").containsChar ('%'))
  71630. offset *= 0.01;
  71631. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71632. }
  71633. }
  71634. const FillType getPathFillType (const Path& path,
  71635. const String& fill,
  71636. const String& fillOpacity,
  71637. const String& overallOpacity,
  71638. const Colour& defaultColour) const
  71639. {
  71640. float opacity = 1.0f;
  71641. if (overallOpacity.isNotEmpty())
  71642. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71643. if (fillOpacity.isNotEmpty())
  71644. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71645. if (fill.startsWithIgnoreCase ("url"))
  71646. {
  71647. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71648. .upToLastOccurrenceOf (")", false, false).trim());
  71649. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71650. if (fillXml != 0
  71651. && (fillXml->hasTagName ("linearGradient")
  71652. || fillXml->hasTagName ("radialGradient")))
  71653. {
  71654. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71655. ColourGradient gradient;
  71656. addGradientStopsIn (gradient, inheritedFrom);
  71657. addGradientStopsIn (gradient, fillXml);
  71658. if (gradient.getNumColours() > 0)
  71659. {
  71660. gradient.addColour (0.0, gradient.getColour (0));
  71661. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71662. }
  71663. else
  71664. {
  71665. gradient.addColour (0.0, Colours::black);
  71666. gradient.addColour (1.0, Colours::black);
  71667. }
  71668. if (overallOpacity.isNotEmpty())
  71669. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71670. jassert (gradient.getNumColours() > 0);
  71671. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71672. float gradientWidth = viewBoxW;
  71673. float gradientHeight = viewBoxH;
  71674. float dx = 0.0f;
  71675. float dy = 0.0f;
  71676. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71677. if (! userSpace)
  71678. {
  71679. const Rectangle<float> bounds (path.getBounds());
  71680. dx = bounds.getX();
  71681. dy = bounds.getY();
  71682. gradientWidth = bounds.getWidth();
  71683. gradientHeight = bounds.getHeight();
  71684. }
  71685. if (gradient.isRadial)
  71686. {
  71687. if (userSpace)
  71688. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71689. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71690. else
  71691. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71692. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71693. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71694. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71695. //xxx (the fx, fy focal point isn't handled properly here..)
  71696. }
  71697. else
  71698. {
  71699. if (userSpace)
  71700. {
  71701. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71702. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71703. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71704. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71705. }
  71706. else
  71707. {
  71708. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71709. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71710. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71711. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71712. }
  71713. if (gradient.point1 == gradient.point2)
  71714. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71715. }
  71716. FillType type (gradient);
  71717. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71718. .followedBy (transform);
  71719. return type;
  71720. }
  71721. }
  71722. if (fill.equalsIgnoreCase ("none"))
  71723. return Colours::transparentBlack;
  71724. int i = 0;
  71725. const Colour colour (parseColour (fill, i, defaultColour));
  71726. return colour.withMultipliedAlpha (opacity);
  71727. }
  71728. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71729. {
  71730. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71731. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71732. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71733. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71734. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71735. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71736. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71737. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71738. if (join.equalsIgnoreCase ("round"))
  71739. joinStyle = PathStrokeType::curved;
  71740. else if (join.equalsIgnoreCase ("bevel"))
  71741. joinStyle = PathStrokeType::beveled;
  71742. if (cap.equalsIgnoreCase ("round"))
  71743. capStyle = PathStrokeType::rounded;
  71744. else if (cap.equalsIgnoreCase ("square"))
  71745. capStyle = PathStrokeType::square;
  71746. float ox = 0.0f, oy = 0.0f;
  71747. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71748. transform.transformPoints (ox, oy, x, y);
  71749. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypot (x - ox, y - oy) : 1.0f,
  71750. joinStyle, capStyle);
  71751. }
  71752. Drawable* parseText (const XmlElement& xml)
  71753. {
  71754. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71755. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71756. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71757. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71758. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71759. //xxx not done text yet!
  71760. forEachXmlChildElement (xml, e)
  71761. {
  71762. if (e->isTextElement())
  71763. {
  71764. const String text (e->getText());
  71765. Path path;
  71766. Drawable* s = parseShape (*e, path);
  71767. delete s; // xxx not finished!
  71768. }
  71769. else if (e->hasTagName ("tspan"))
  71770. {
  71771. Drawable* s = parseText (*e);
  71772. delete s; // xxx not finished!
  71773. }
  71774. }
  71775. return 0;
  71776. }
  71777. void addTransform (const XmlElement& xml)
  71778. {
  71779. transform = parseTransform (xml.getStringAttribute ("transform"))
  71780. .followedBy (transform);
  71781. }
  71782. bool parseCoord (String::CharPointerType& s, float& value, const bool allowUnits, const bool isX) const
  71783. {
  71784. String number;
  71785. if (! parseNextNumber (s, number, allowUnits))
  71786. {
  71787. value = 0;
  71788. return false;
  71789. }
  71790. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71791. return true;
  71792. }
  71793. bool parseCoords (String::CharPointerType& s, float& x, float& y, const bool allowUnits) const
  71794. {
  71795. return parseCoord (s, x, allowUnits, true)
  71796. && parseCoord (s, y, allowUnits, false);
  71797. }
  71798. float getCoordLength (const String& s, const float sizeForProportions) const
  71799. {
  71800. float n = s.getFloatValue();
  71801. const int len = s.length();
  71802. if (len > 2)
  71803. {
  71804. const float dpi = 96.0f;
  71805. const juce_wchar n1 = s [len - 2];
  71806. const juce_wchar n2 = s [len - 1];
  71807. if (n1 == 'i' && n2 == 'n')
  71808. n *= dpi;
  71809. else if (n1 == 'm' && n2 == 'm')
  71810. n *= dpi / 25.4f;
  71811. else if (n1 == 'c' && n2 == 'm')
  71812. n *= dpi / 2.54f;
  71813. else if (n1 == 'p' && n2 == 'c')
  71814. n *= 15.0f;
  71815. else if (n2 == '%')
  71816. n *= 0.01f * sizeForProportions;
  71817. }
  71818. return n;
  71819. }
  71820. void getCoordList (Array <float>& coords, const String& list,
  71821. const bool allowUnits, const bool isX) const
  71822. {
  71823. String::CharPointerType text (list.getCharPointer());
  71824. float value;
  71825. while (parseCoord (text, value, allowUnits, isX))
  71826. coords.add (value);
  71827. }
  71828. void parseCSSStyle (const XmlElement& xml)
  71829. {
  71830. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71831. }
  71832. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71833. const String& defaultValue = String::empty) const
  71834. {
  71835. if (xml->hasAttribute (attributeName))
  71836. return xml->getStringAttribute (attributeName, defaultValue);
  71837. const String styleAtt (xml->getStringAttribute ("style"));
  71838. if (styleAtt.isNotEmpty())
  71839. {
  71840. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71841. if (value.isNotEmpty())
  71842. return value;
  71843. }
  71844. else if (xml->hasAttribute ("class"))
  71845. {
  71846. const String className ("." + xml->getStringAttribute ("class"));
  71847. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71848. if (index < 0)
  71849. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71850. if (index >= 0)
  71851. {
  71852. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71853. if (openBracket > index)
  71854. {
  71855. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71856. if (closeBracket > openBracket)
  71857. {
  71858. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71859. if (value.isNotEmpty())
  71860. return value;
  71861. }
  71862. }
  71863. }
  71864. }
  71865. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71866. if (xml != 0)
  71867. return getStyleAttribute (xml, attributeName, defaultValue);
  71868. return defaultValue;
  71869. }
  71870. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71871. {
  71872. if (xml->hasAttribute (attributeName))
  71873. return xml->getStringAttribute (attributeName);
  71874. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71875. if (xml != 0)
  71876. return getInheritedAttribute (xml, attributeName);
  71877. return String::empty;
  71878. }
  71879. static bool isIdentifierChar (const juce_wchar c)
  71880. {
  71881. return CharacterFunctions::isLetter (c) || c == '-';
  71882. }
  71883. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71884. {
  71885. int i = 0;
  71886. for (;;)
  71887. {
  71888. i = list.indexOf (i, attributeName);
  71889. if (i < 0)
  71890. break;
  71891. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71892. && ! isIdentifierChar (list [i + attributeName.length()]))
  71893. {
  71894. i = list.indexOfChar (i, ':');
  71895. if (i < 0)
  71896. break;
  71897. int end = list.indexOfChar (i, ';');
  71898. if (end < 0)
  71899. end = 0x7ffff;
  71900. return list.substring (i + 1, end).trim();
  71901. }
  71902. ++i;
  71903. }
  71904. return defaultValue;
  71905. }
  71906. static bool parseNextNumber (String::CharPointerType& s, String& value, const bool allowUnits)
  71907. {
  71908. while (s.isWhitespace() || *s == ',')
  71909. ++s;
  71910. String::CharPointerType start (s);
  71911. int numChars = 0;
  71912. if (s.isDigit() || *s == '.' || *s == '-')
  71913. {
  71914. ++numChars;
  71915. ++s;
  71916. }
  71917. while (s.isDigit() || *s == '.')
  71918. {
  71919. ++numChars;
  71920. ++s;
  71921. }
  71922. if ((*s == 'e' || *s == 'E')
  71923. && ((s + 1).isDigit() || s[1] == '-' || s[1] == '+'))
  71924. {
  71925. s += 2;
  71926. numChars += 2;
  71927. while (s.isDigit())
  71928. {
  71929. ++numChars;
  71930. ++s;
  71931. }
  71932. }
  71933. if (allowUnits)
  71934. {
  71935. while (s.isLetter())
  71936. {
  71937. ++numChars;
  71938. ++s;
  71939. }
  71940. }
  71941. if (numChars == 0)
  71942. return false;
  71943. value = String (start, numChars);
  71944. while (s.isWhitespace() || *s == ',')
  71945. ++s;
  71946. return true;
  71947. }
  71948. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71949. {
  71950. if (s [index] == '#')
  71951. {
  71952. uint32 hex [6];
  71953. zeromem (hex, sizeof (hex));
  71954. int numChars = 0;
  71955. for (int i = 6; --i >= 0;)
  71956. {
  71957. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71958. if (hexValue >= 0)
  71959. hex [numChars++] = hexValue;
  71960. else
  71961. break;
  71962. }
  71963. if (numChars <= 3)
  71964. return Colour ((uint8) (hex [0] * 0x11),
  71965. (uint8) (hex [1] * 0x11),
  71966. (uint8) (hex [2] * 0x11));
  71967. else
  71968. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71969. (uint8) ((hex [2] << 4) + hex [3]),
  71970. (uint8) ((hex [4] << 4) + hex [5]));
  71971. }
  71972. else if (s [index] == 'r'
  71973. && s [index + 1] == 'g'
  71974. && s [index + 2] == 'b')
  71975. {
  71976. const int openBracket = s.indexOfChar (index, '(');
  71977. const int closeBracket = s.indexOfChar (openBracket, ')');
  71978. if (openBracket >= 3 && closeBracket > openBracket)
  71979. {
  71980. index = closeBracket;
  71981. StringArray tokens;
  71982. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71983. tokens.trim();
  71984. tokens.removeEmptyStrings();
  71985. if (tokens[0].containsChar ('%'))
  71986. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71987. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71988. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71989. else
  71990. return Colour ((uint8) tokens[0].getIntValue(),
  71991. (uint8) tokens[1].getIntValue(),
  71992. (uint8) tokens[2].getIntValue());
  71993. }
  71994. }
  71995. return Colours::findColourForName (s, defaultColour);
  71996. }
  71997. static const AffineTransform parseTransform (String t)
  71998. {
  71999. AffineTransform result;
  72000. while (t.isNotEmpty())
  72001. {
  72002. StringArray tokens;
  72003. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72004. .upToFirstOccurrenceOf (")", false, false),
  72005. ", ", String::empty);
  72006. tokens.removeEmptyStrings (true);
  72007. float numbers [6];
  72008. for (int i = 0; i < 6; ++i)
  72009. numbers[i] = tokens[i].getFloatValue();
  72010. AffineTransform trans;
  72011. if (t.startsWithIgnoreCase ("matrix"))
  72012. {
  72013. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72014. numbers[1], numbers[3], numbers[5]);
  72015. }
  72016. else if (t.startsWithIgnoreCase ("translate"))
  72017. {
  72018. jassert (tokens.size() == 2);
  72019. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72020. }
  72021. else if (t.startsWithIgnoreCase ("scale"))
  72022. {
  72023. if (tokens.size() == 1)
  72024. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72025. else
  72026. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72027. }
  72028. else if (t.startsWithIgnoreCase ("rotate"))
  72029. {
  72030. if (tokens.size() != 3)
  72031. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72032. else
  72033. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72034. numbers[1], numbers[2]);
  72035. }
  72036. else if (t.startsWithIgnoreCase ("skewX"))
  72037. {
  72038. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72039. 0.0f, 1.0f, 0.0f);
  72040. }
  72041. else if (t.startsWithIgnoreCase ("skewY"))
  72042. {
  72043. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72044. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72045. }
  72046. result = trans.followedBy (result);
  72047. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72048. }
  72049. return result;
  72050. }
  72051. static void endpointToCentreParameters (const double x1, const double y1,
  72052. const double x2, const double y2,
  72053. const double angle,
  72054. const bool largeArc, const bool sweep,
  72055. double& rx, double& ry,
  72056. double& centreX, double& centreY,
  72057. double& startAngle, double& deltaAngle)
  72058. {
  72059. const double midX = (x1 - x2) * 0.5;
  72060. const double midY = (y1 - y2) * 0.5;
  72061. const double cosAngle = cos (angle);
  72062. const double sinAngle = sin (angle);
  72063. const double xp = cosAngle * midX + sinAngle * midY;
  72064. const double yp = cosAngle * midY - sinAngle * midX;
  72065. const double xp2 = xp * xp;
  72066. const double yp2 = yp * yp;
  72067. double rx2 = rx * rx;
  72068. double ry2 = ry * ry;
  72069. const double s = (xp2 / rx2) + (yp2 / ry2);
  72070. double c;
  72071. if (s <= 1.0)
  72072. {
  72073. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72074. / (( rx2 * yp2) + (ry2 * xp2))));
  72075. if (largeArc == sweep)
  72076. c = -c;
  72077. }
  72078. else
  72079. {
  72080. const double s2 = std::sqrt (s);
  72081. rx *= s2;
  72082. ry *= s2;
  72083. rx2 = rx * rx;
  72084. ry2 = ry * ry;
  72085. c = 0;
  72086. }
  72087. const double cpx = ((rx * yp) / ry) * c;
  72088. const double cpy = ((-ry * xp) / rx) * c;
  72089. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72090. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72091. const double ux = (xp - cpx) / rx;
  72092. const double uy = (yp - cpy) / ry;
  72093. const double vx = (-xp - cpx) / rx;
  72094. const double vy = (-yp - cpy) / ry;
  72095. const double length = juce_hypot (ux, uy);
  72096. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72097. if (uy < 0)
  72098. startAngle = -startAngle;
  72099. startAngle += double_Pi * 0.5;
  72100. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72101. / (length * juce_hypot (vx, vy))));
  72102. if ((ux * vy) - (uy * vx) < 0)
  72103. deltaAngle = -deltaAngle;
  72104. if (sweep)
  72105. {
  72106. if (deltaAngle < 0)
  72107. deltaAngle += double_Pi * 2.0;
  72108. }
  72109. else
  72110. {
  72111. if (deltaAngle > 0)
  72112. deltaAngle -= double_Pi * 2.0;
  72113. }
  72114. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72115. }
  72116. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72117. {
  72118. forEachXmlChildElement (*parent, e)
  72119. {
  72120. if (e->compareAttribute ("id", id))
  72121. return e;
  72122. const XmlElement* const found = findElementForId (e, id);
  72123. if (found != 0)
  72124. return found;
  72125. }
  72126. return 0;
  72127. }
  72128. SVGState& operator= (const SVGState&);
  72129. };
  72130. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72131. {
  72132. SVGState state (&svgDocument);
  72133. return state.parseSVGElement (svgDocument);
  72134. }
  72135. END_JUCE_NAMESPACE
  72136. /*** End of inlined file: juce_SVGParser.cpp ***/
  72137. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72138. BEGIN_JUCE_NAMESPACE
  72139. #if JUCE_MSVC && JUCE_DEBUG
  72140. #pragma optimize ("t", on)
  72141. #endif
  72142. DropShadowEffect::DropShadowEffect()
  72143. : offsetX (0),
  72144. offsetY (0),
  72145. radius (4),
  72146. opacity (0.6f)
  72147. {
  72148. }
  72149. DropShadowEffect::~DropShadowEffect()
  72150. {
  72151. }
  72152. void DropShadowEffect::setShadowProperties (const float newRadius,
  72153. const float newOpacity,
  72154. const int newShadowOffsetX,
  72155. const int newShadowOffsetY)
  72156. {
  72157. radius = jmax (1.1f, newRadius);
  72158. offsetX = newShadowOffsetX;
  72159. offsetY = newShadowOffsetY;
  72160. opacity = newOpacity;
  72161. }
  72162. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72163. {
  72164. const int w = image.getWidth();
  72165. const int h = image.getHeight();
  72166. Image shadowImage (Image::SingleChannel, w, h, false);
  72167. const Image::BitmapData srcData (image, false);
  72168. const Image::BitmapData destData (shadowImage, true);
  72169. const int filter = roundToInt (63.0f / radius);
  72170. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72171. for (int x = w; --x >= 0;)
  72172. {
  72173. int shadowAlpha = 0;
  72174. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72175. uint8* shadowPix = destData.data + x;
  72176. for (int y = h; --y >= 0;)
  72177. {
  72178. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72179. *shadowPix = (uint8) shadowAlpha;
  72180. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72181. shadowPix += destData.lineStride;
  72182. }
  72183. }
  72184. for (int y = h; --y >= 0;)
  72185. {
  72186. int shadowAlpha = 0;
  72187. uint8* shadowPix = destData.getLinePointer (y);
  72188. for (int x = w; --x >= 0;)
  72189. {
  72190. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72191. *shadowPix++ = (uint8) shadowAlpha;
  72192. }
  72193. }
  72194. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72195. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72196. g.setOpacity (alpha);
  72197. g.drawImageAt (image, 0, 0);
  72198. }
  72199. #if JUCE_MSVC && JUCE_DEBUG
  72200. #pragma optimize ("", on) // resets optimisations to the project defaults
  72201. #endif
  72202. END_JUCE_NAMESPACE
  72203. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72204. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72205. BEGIN_JUCE_NAMESPACE
  72206. GlowEffect::GlowEffect()
  72207. : radius (2.0f),
  72208. colour (Colours::white)
  72209. {
  72210. }
  72211. GlowEffect::~GlowEffect()
  72212. {
  72213. }
  72214. void GlowEffect::setGlowProperties (const float newRadius,
  72215. const Colour& newColour)
  72216. {
  72217. radius = newRadius;
  72218. colour = newColour;
  72219. }
  72220. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72221. {
  72222. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72223. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72224. blurKernel.createGaussianBlur (radius);
  72225. blurKernel.rescaleAllValues (radius);
  72226. blurKernel.applyToImage (temp, image, image.getBounds());
  72227. g.setColour (colour.withMultipliedAlpha (alpha));
  72228. g.drawImageAt (temp, 0, 0, true);
  72229. g.setOpacity (alpha);
  72230. g.drawImageAt (image, 0, 0, false);
  72231. }
  72232. END_JUCE_NAMESPACE
  72233. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72234. /*** Start of inlined file: juce_Font.cpp ***/
  72235. BEGIN_JUCE_NAMESPACE
  72236. namespace FontValues
  72237. {
  72238. float limitFontHeight (const float height) throw()
  72239. {
  72240. return jlimit (0.1f, 10000.0f, height);
  72241. }
  72242. const float defaultFontHeight = 14.0f;
  72243. String fallbackFont;
  72244. }
  72245. class TypefaceCache : public DeletedAtShutdown
  72246. {
  72247. public:
  72248. TypefaceCache()
  72249. : counter (0)
  72250. {
  72251. setSize (10);
  72252. }
  72253. ~TypefaceCache()
  72254. {
  72255. clearSingletonInstance();
  72256. }
  72257. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72258. void setSize (const int numToCache)
  72259. {
  72260. faces.clear();
  72261. faces.insertMultiple (-1, CachedFace(), numToCache);
  72262. }
  72263. const Typeface::Ptr findTypefaceFor (const Font& font)
  72264. {
  72265. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72266. const String faceName (font.getTypefaceName());
  72267. int i;
  72268. for (i = faces.size(); --i >= 0;)
  72269. {
  72270. CachedFace& face = faces.getReference(i);
  72271. if (face.flags == flags
  72272. && face.typefaceName == faceName
  72273. && face.typeface->isSuitableForFont (font))
  72274. {
  72275. face.lastUsageCount = ++counter;
  72276. return face.typeface;
  72277. }
  72278. }
  72279. int replaceIndex = 0;
  72280. int bestLastUsageCount = std::numeric_limits<int>::max();
  72281. for (i = faces.size(); --i >= 0;)
  72282. {
  72283. const int lu = faces.getReference(i).lastUsageCount;
  72284. if (bestLastUsageCount > lu)
  72285. {
  72286. bestLastUsageCount = lu;
  72287. replaceIndex = i;
  72288. }
  72289. }
  72290. CachedFace& face = faces.getReference (replaceIndex);
  72291. face.typefaceName = faceName;
  72292. face.flags = flags;
  72293. face.lastUsageCount = ++counter;
  72294. face.typeface = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72295. jassert (face.typeface != 0); // the look and feel must return a typeface!
  72296. if (defaultFace == 0 && font == Font())
  72297. defaultFace = face.typeface;
  72298. return face.typeface;
  72299. }
  72300. const Typeface::Ptr getDefaultTypeface() const throw()
  72301. {
  72302. return defaultFace;
  72303. }
  72304. private:
  72305. struct CachedFace
  72306. {
  72307. CachedFace() throw()
  72308. : lastUsageCount (0), flags (-1)
  72309. {
  72310. }
  72311. // Although it seems a bit wacky to store the name here, it's because it may be a
  72312. // placeholder rather than a real one, e.g. "<Sans-Serif>" vs the actual typeface name.
  72313. // Since the typeface itself doesn't know that it may have this alias, the name under
  72314. // which it was fetched needs to be stored separately.
  72315. String typefaceName;
  72316. int lastUsageCount, flags;
  72317. Typeface::Ptr typeface;
  72318. };
  72319. Array <CachedFace> faces;
  72320. Typeface::Ptr defaultFace;
  72321. int counter;
  72322. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TypefaceCache);
  72323. };
  72324. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72325. void Typeface::setTypefaceCacheSize (int numFontsToCache)
  72326. {
  72327. TypefaceCache::getInstance()->setSize (numFontsToCache);
  72328. }
  72329. Font::SharedFontInternal::SharedFontInternal (const float height_, const int styleFlags_) throw()
  72330. : typefaceName (Font::getDefaultSansSerifFontName()),
  72331. height (height_),
  72332. horizontalScale (1.0f),
  72333. kerning (0),
  72334. ascent (0),
  72335. styleFlags (styleFlags_),
  72336. typeface (TypefaceCache::getInstance()->getDefaultTypeface())
  72337. {
  72338. }
  72339. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const int styleFlags_) throw()
  72340. : typefaceName (typefaceName_),
  72341. height (height_),
  72342. horizontalScale (1.0f),
  72343. kerning (0),
  72344. ascent (0),
  72345. styleFlags (styleFlags_),
  72346. typeface (0)
  72347. {
  72348. }
  72349. Font::SharedFontInternal::SharedFontInternal (const Typeface::Ptr& typeface_) throw()
  72350. : typefaceName (typeface_->getName()),
  72351. height (FontValues::defaultFontHeight),
  72352. horizontalScale (1.0f),
  72353. kerning (0),
  72354. ascent (0),
  72355. styleFlags (Font::plain),
  72356. typeface (typeface_)
  72357. {
  72358. }
  72359. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72360. : typefaceName (other.typefaceName),
  72361. height (other.height),
  72362. horizontalScale (other.horizontalScale),
  72363. kerning (other.kerning),
  72364. ascent (other.ascent),
  72365. styleFlags (other.styleFlags),
  72366. typeface (other.typeface)
  72367. {
  72368. }
  72369. bool Font::SharedFontInternal::operator== (const SharedFontInternal& other) const throw()
  72370. {
  72371. return height == other.height
  72372. && styleFlags == other.styleFlags
  72373. && horizontalScale == other.horizontalScale
  72374. && kerning == other.kerning
  72375. && typefaceName == other.typefaceName;
  72376. }
  72377. Font::Font()
  72378. : font (new SharedFontInternal (FontValues::defaultFontHeight, Font::plain))
  72379. {
  72380. }
  72381. Font::Font (const float fontHeight, const int styleFlags_)
  72382. : font (new SharedFontInternal (FontValues::limitFontHeight (fontHeight), styleFlags_))
  72383. {
  72384. }
  72385. Font::Font (const String& typefaceName_, const float fontHeight, const int styleFlags_)
  72386. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight), styleFlags_))
  72387. {
  72388. }
  72389. Font::Font (const Typeface::Ptr& typeface)
  72390. : font (new SharedFontInternal (typeface))
  72391. {
  72392. }
  72393. Font::Font (const Font& other) throw()
  72394. : font (other.font)
  72395. {
  72396. }
  72397. Font& Font::operator= (const Font& other) throw()
  72398. {
  72399. font = other.font;
  72400. return *this;
  72401. }
  72402. Font::~Font() throw()
  72403. {
  72404. }
  72405. bool Font::operator== (const Font& other) const throw()
  72406. {
  72407. return font == other.font
  72408. || *font == *other.font;
  72409. }
  72410. bool Font::operator!= (const Font& other) const throw()
  72411. {
  72412. return ! operator== (other);
  72413. }
  72414. void Font::dupeInternalIfShared()
  72415. {
  72416. if (font->getReferenceCount() > 1)
  72417. font = new SharedFontInternal (*font);
  72418. }
  72419. const String Font::getDefaultSansSerifFontName()
  72420. {
  72421. static const String name ("<Sans-Serif>");
  72422. return name;
  72423. }
  72424. const String Font::getDefaultSerifFontName()
  72425. {
  72426. static const String name ("<Serif>");
  72427. return name;
  72428. }
  72429. const String Font::getDefaultMonospacedFontName()
  72430. {
  72431. static const String name ("<Monospaced>");
  72432. return name;
  72433. }
  72434. void Font::setTypefaceName (const String& faceName)
  72435. {
  72436. if (faceName != font->typefaceName)
  72437. {
  72438. dupeInternalIfShared();
  72439. font->typefaceName = faceName;
  72440. font->typeface = 0;
  72441. font->ascent = 0;
  72442. }
  72443. }
  72444. const String Font::getFallbackFontName()
  72445. {
  72446. return FontValues::fallbackFont;
  72447. }
  72448. void Font::setFallbackFontName (const String& name)
  72449. {
  72450. FontValues::fallbackFont = name;
  72451. }
  72452. void Font::setHeight (float newHeight)
  72453. {
  72454. newHeight = FontValues::limitFontHeight (newHeight);
  72455. if (font->height != newHeight)
  72456. {
  72457. dupeInternalIfShared();
  72458. font->height = newHeight;
  72459. }
  72460. }
  72461. void Font::setHeightWithoutChangingWidth (float newHeight)
  72462. {
  72463. newHeight = FontValues::limitFontHeight (newHeight);
  72464. if (font->height != newHeight)
  72465. {
  72466. dupeInternalIfShared();
  72467. font->horizontalScale *= (font->height / newHeight);
  72468. font->height = newHeight;
  72469. }
  72470. }
  72471. void Font::setStyleFlags (const int newFlags)
  72472. {
  72473. if (font->styleFlags != newFlags)
  72474. {
  72475. dupeInternalIfShared();
  72476. font->styleFlags = newFlags;
  72477. font->typeface = 0;
  72478. font->ascent = 0;
  72479. }
  72480. }
  72481. void Font::setSizeAndStyle (float newHeight,
  72482. const int newStyleFlags,
  72483. const float newHorizontalScale,
  72484. const float newKerningAmount)
  72485. {
  72486. newHeight = FontValues::limitFontHeight (newHeight);
  72487. if (font->height != newHeight
  72488. || font->horizontalScale != newHorizontalScale
  72489. || font->kerning != newKerningAmount)
  72490. {
  72491. dupeInternalIfShared();
  72492. font->height = newHeight;
  72493. font->horizontalScale = newHorizontalScale;
  72494. font->kerning = newKerningAmount;
  72495. }
  72496. setStyleFlags (newStyleFlags);
  72497. }
  72498. void Font::setHorizontalScale (const float scaleFactor)
  72499. {
  72500. dupeInternalIfShared();
  72501. font->horizontalScale = scaleFactor;
  72502. }
  72503. void Font::setExtraKerningFactor (const float extraKerning)
  72504. {
  72505. dupeInternalIfShared();
  72506. font->kerning = extraKerning;
  72507. }
  72508. void Font::setBold (const bool shouldBeBold)
  72509. {
  72510. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72511. : (font->styleFlags & ~bold));
  72512. }
  72513. const Font Font::boldened() const
  72514. {
  72515. Font f (*this);
  72516. f.setBold (true);
  72517. return f;
  72518. }
  72519. bool Font::isBold() const throw()
  72520. {
  72521. return (font->styleFlags & bold) != 0;
  72522. }
  72523. void Font::setItalic (const bool shouldBeItalic)
  72524. {
  72525. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72526. : (font->styleFlags & ~italic));
  72527. }
  72528. const Font Font::italicised() const
  72529. {
  72530. Font f (*this);
  72531. f.setItalic (true);
  72532. return f;
  72533. }
  72534. bool Font::isItalic() const throw()
  72535. {
  72536. return (font->styleFlags & italic) != 0;
  72537. }
  72538. void Font::setUnderline (const bool shouldBeUnderlined)
  72539. {
  72540. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72541. : (font->styleFlags & ~underlined));
  72542. }
  72543. bool Font::isUnderlined() const throw()
  72544. {
  72545. return (font->styleFlags & underlined) != 0;
  72546. }
  72547. float Font::getAscent() const
  72548. {
  72549. if (font->ascent == 0)
  72550. font->ascent = getTypeface()->getAscent();
  72551. return font->height * font->ascent;
  72552. }
  72553. float Font::getDescent() const
  72554. {
  72555. return font->height - getAscent();
  72556. }
  72557. int Font::getStringWidth (const String& text) const
  72558. {
  72559. return roundToInt (getStringWidthFloat (text));
  72560. }
  72561. float Font::getStringWidthFloat (const String& text) const
  72562. {
  72563. float w = getTypeface()->getStringWidth (text);
  72564. if (font->kerning != 0)
  72565. w += font->kerning * text.length();
  72566. return w * font->height * font->horizontalScale;
  72567. }
  72568. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72569. {
  72570. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72571. const float scale = font->height * font->horizontalScale;
  72572. const int num = xOffsets.size();
  72573. if (num > 0)
  72574. {
  72575. float* const x = &(xOffsets.getReference(0));
  72576. if (font->kerning != 0)
  72577. {
  72578. for (int i = 0; i < num; ++i)
  72579. x[i] = (x[i] + i * font->kerning) * scale;
  72580. }
  72581. else
  72582. {
  72583. for (int i = 0; i < num; ++i)
  72584. x[i] *= scale;
  72585. }
  72586. }
  72587. }
  72588. void Font::findFonts (Array<Font>& destArray)
  72589. {
  72590. const StringArray names (findAllTypefaceNames());
  72591. for (int i = 0; i < names.size(); ++i)
  72592. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72593. }
  72594. const String Font::toString() const
  72595. {
  72596. String s (getTypefaceName());
  72597. if (s == getDefaultSansSerifFontName())
  72598. s = String::empty;
  72599. else
  72600. s += "; ";
  72601. s += String (getHeight(), 1);
  72602. if (isBold())
  72603. s += " bold";
  72604. if (isItalic())
  72605. s += " italic";
  72606. return s;
  72607. }
  72608. const Font Font::fromString (const String& fontDescription)
  72609. {
  72610. String name;
  72611. const int separator = fontDescription.indexOfChar (';');
  72612. if (separator > 0)
  72613. name = fontDescription.substring (0, separator).trim();
  72614. if (name.isEmpty())
  72615. name = getDefaultSansSerifFontName();
  72616. String sizeAndStyle (fontDescription.substring (separator + 1));
  72617. float height = sizeAndStyle.getFloatValue();
  72618. if (height <= 0)
  72619. height = 10.0f;
  72620. int flags = Font::plain;
  72621. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72622. flags |= Font::bold;
  72623. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72624. flags |= Font::italic;
  72625. return Font (name, height, flags);
  72626. }
  72627. Typeface* Font::getTypeface() const
  72628. {
  72629. if (font->typeface == 0)
  72630. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72631. return font->typeface;
  72632. }
  72633. END_JUCE_NAMESPACE
  72634. /*** End of inlined file: juce_Font.cpp ***/
  72635. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72636. BEGIN_JUCE_NAMESPACE
  72637. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72638. const juce_wchar character_, const int glyph_)
  72639. : x (x_),
  72640. y (y_),
  72641. w (w_),
  72642. font (font_),
  72643. character (character_),
  72644. glyph (glyph_)
  72645. {
  72646. }
  72647. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72648. : x (other.x),
  72649. y (other.y),
  72650. w (other.w),
  72651. font (other.font),
  72652. character (other.character),
  72653. glyph (other.glyph)
  72654. {
  72655. }
  72656. void PositionedGlyph::draw (const Graphics& g) const
  72657. {
  72658. if (! isWhitespace())
  72659. {
  72660. g.getInternalContext()->setFont (font);
  72661. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72662. }
  72663. }
  72664. void PositionedGlyph::draw (const Graphics& g,
  72665. const AffineTransform& transform) const
  72666. {
  72667. if (! isWhitespace())
  72668. {
  72669. g.getInternalContext()->setFont (font);
  72670. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72671. .followedBy (transform));
  72672. }
  72673. }
  72674. void PositionedGlyph::createPath (Path& path) const
  72675. {
  72676. if (! isWhitespace())
  72677. {
  72678. Typeface* const t = font.getTypeface();
  72679. if (t != 0)
  72680. {
  72681. Path p;
  72682. t->getOutlineForGlyph (glyph, p);
  72683. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72684. .translated (x, y));
  72685. }
  72686. }
  72687. }
  72688. bool PositionedGlyph::hitTest (float px, float py) const
  72689. {
  72690. if (getBounds().contains (px, py) && ! isWhitespace())
  72691. {
  72692. Typeface* const t = font.getTypeface();
  72693. if (t != 0)
  72694. {
  72695. Path p;
  72696. t->getOutlineForGlyph (glyph, p);
  72697. AffineTransform::translation (-x, -y)
  72698. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72699. .transformPoint (px, py);
  72700. return p.contains (px, py);
  72701. }
  72702. }
  72703. return false;
  72704. }
  72705. void PositionedGlyph::moveBy (const float deltaX,
  72706. const float deltaY)
  72707. {
  72708. x += deltaX;
  72709. y += deltaY;
  72710. }
  72711. GlyphArrangement::GlyphArrangement()
  72712. {
  72713. glyphs.ensureStorageAllocated (128);
  72714. }
  72715. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72716. {
  72717. addGlyphArrangement (other);
  72718. }
  72719. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72720. {
  72721. if (this != &other)
  72722. {
  72723. clear();
  72724. addGlyphArrangement (other);
  72725. }
  72726. return *this;
  72727. }
  72728. GlyphArrangement::~GlyphArrangement()
  72729. {
  72730. }
  72731. void GlyphArrangement::clear()
  72732. {
  72733. glyphs.clear();
  72734. }
  72735. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72736. {
  72737. jassert (isPositiveAndBelow (index, glyphs.size()));
  72738. return *glyphs [index];
  72739. }
  72740. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72741. {
  72742. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72743. glyphs.addCopiesOf (other.glyphs);
  72744. }
  72745. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72746. {
  72747. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72748. }
  72749. void GlyphArrangement::addLineOfText (const Font& font,
  72750. const String& text,
  72751. const float xOffset,
  72752. const float yOffset)
  72753. {
  72754. addCurtailedLineOfText (font, text,
  72755. xOffset, yOffset,
  72756. 1.0e10f, false);
  72757. }
  72758. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72759. const String& text,
  72760. float xOffset,
  72761. const float yOffset,
  72762. const float maxWidthPixels,
  72763. const bool useEllipsis)
  72764. {
  72765. if (text.isNotEmpty())
  72766. {
  72767. Array <int> newGlyphs;
  72768. Array <float> xOffsets;
  72769. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72770. const int textLen = newGlyphs.size();
  72771. String::CharPointerType t (text.getCharPointer());
  72772. for (int i = 0; i < textLen; ++i)
  72773. {
  72774. const float thisX = xOffsets.getUnchecked (i);
  72775. const float nextX = xOffsets.getUnchecked (i + 1);
  72776. if (nextX > maxWidthPixels + 1.0f)
  72777. {
  72778. // curtail the string if it's too wide..
  72779. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72780. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72781. break;
  72782. }
  72783. else
  72784. {
  72785. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72786. font, t.getAndAdvance(), newGlyphs.getUnchecked(i)));
  72787. }
  72788. }
  72789. }
  72790. }
  72791. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72792. const int startIndex, int endIndex)
  72793. {
  72794. int numDeleted = 0;
  72795. if (glyphs.size() > 0)
  72796. {
  72797. Array<int> dotGlyphs;
  72798. Array<float> dotXs;
  72799. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72800. const float dx = dotXs[1];
  72801. float xOffset = 0.0f, yOffset = 0.0f;
  72802. while (endIndex > startIndex)
  72803. {
  72804. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72805. xOffset = pg->x;
  72806. yOffset = pg->y;
  72807. glyphs.remove (endIndex);
  72808. ++numDeleted;
  72809. if (xOffset + dx * 3 <= maxXPos)
  72810. break;
  72811. }
  72812. for (int i = 3; --i >= 0;)
  72813. {
  72814. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72815. font, '.', dotGlyphs.getFirst()));
  72816. --numDeleted;
  72817. xOffset += dx;
  72818. if (xOffset > maxXPos)
  72819. break;
  72820. }
  72821. }
  72822. return numDeleted;
  72823. }
  72824. void GlyphArrangement::addJustifiedText (const Font& font,
  72825. const String& text,
  72826. float x, float y,
  72827. const float maxLineWidth,
  72828. const Justification& horizontalLayout)
  72829. {
  72830. int lineStartIndex = glyphs.size();
  72831. addLineOfText (font, text, x, y);
  72832. const float originalY = y;
  72833. while (lineStartIndex < glyphs.size())
  72834. {
  72835. int i = lineStartIndex;
  72836. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72837. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72838. ++i;
  72839. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72840. int lastWordBreakIndex = -1;
  72841. while (i < glyphs.size())
  72842. {
  72843. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72844. const juce_wchar c = pg->getCharacter();
  72845. if (c == '\r' || c == '\n')
  72846. {
  72847. ++i;
  72848. if (c == '\r' && i < glyphs.size()
  72849. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72850. ++i;
  72851. break;
  72852. }
  72853. else if (pg->isWhitespace())
  72854. {
  72855. lastWordBreakIndex = i + 1;
  72856. }
  72857. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72858. {
  72859. if (lastWordBreakIndex >= 0)
  72860. i = lastWordBreakIndex;
  72861. break;
  72862. }
  72863. ++i;
  72864. }
  72865. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72866. float currentLineEndX = currentLineStartX;
  72867. for (int j = i; --j >= lineStartIndex;)
  72868. {
  72869. if (! glyphs.getUnchecked (j)->isWhitespace())
  72870. {
  72871. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72872. break;
  72873. }
  72874. }
  72875. float deltaX = 0.0f;
  72876. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72877. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72878. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72879. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72880. else if (horizontalLayout.testFlags (Justification::right))
  72881. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72882. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72883. x + deltaX - currentLineStartX, y - originalY);
  72884. lineStartIndex = i;
  72885. y += font.getHeight();
  72886. }
  72887. }
  72888. void GlyphArrangement::addFittedText (const Font& f,
  72889. const String& text,
  72890. const float x, const float y,
  72891. const float width, const float height,
  72892. const Justification& layout,
  72893. int maximumLines,
  72894. const float minimumHorizontalScale)
  72895. {
  72896. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72897. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72898. if (text.containsAnyOf ("\r\n"))
  72899. {
  72900. GlyphArrangement ga;
  72901. ga.addJustifiedText (f, text, x, y, width, layout);
  72902. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72903. float dy = y - bb.getY();
  72904. if (layout.testFlags (Justification::verticallyCentred))
  72905. dy += (height - bb.getHeight()) * 0.5f;
  72906. else if (layout.testFlags (Justification::bottom))
  72907. dy += height - bb.getHeight();
  72908. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72909. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72910. for (int i = 0; i < ga.glyphs.size(); ++i)
  72911. glyphs.add (ga.glyphs.getUnchecked (i));
  72912. ga.glyphs.clear (false);
  72913. return;
  72914. }
  72915. int startIndex = glyphs.size();
  72916. addLineOfText (f, text.trim(), x, y);
  72917. if (glyphs.size() > startIndex)
  72918. {
  72919. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72920. - glyphs.getUnchecked (startIndex)->getLeft();
  72921. if (lineWidth <= 0)
  72922. return;
  72923. if (lineWidth * minimumHorizontalScale < width)
  72924. {
  72925. if (lineWidth > width)
  72926. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72927. width / lineWidth);
  72928. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72929. x, y, width, height, layout);
  72930. }
  72931. else if (maximumLines <= 1)
  72932. {
  72933. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72934. x, y, width, height, f, layout, minimumHorizontalScale);
  72935. }
  72936. else
  72937. {
  72938. Font font (f);
  72939. String txt (text.trim());
  72940. const int length = txt.length();
  72941. const int originalStartIndex = startIndex;
  72942. int numLines = 1;
  72943. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72944. maximumLines = 1;
  72945. maximumLines = jmin (maximumLines, length);
  72946. while (numLines < maximumLines)
  72947. {
  72948. ++numLines;
  72949. const float newFontHeight = height / (float) numLines;
  72950. if (newFontHeight < font.getHeight())
  72951. {
  72952. font.setHeight (jmax (8.0f, newFontHeight));
  72953. removeRangeOfGlyphs (startIndex, -1);
  72954. addLineOfText (font, txt, x, y);
  72955. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72956. - glyphs.getUnchecked (startIndex)->getLeft();
  72957. }
  72958. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72959. break;
  72960. }
  72961. if (numLines < 1)
  72962. numLines = 1;
  72963. float lineY = y;
  72964. float widthPerLine = lineWidth / numLines;
  72965. int lastLineStartIndex = 0;
  72966. for (int line = 0; line < numLines; ++line)
  72967. {
  72968. int i = startIndex;
  72969. lastLineStartIndex = i;
  72970. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72971. if (line == numLines - 1)
  72972. {
  72973. widthPerLine = width;
  72974. i = glyphs.size();
  72975. }
  72976. else
  72977. {
  72978. while (i < glyphs.size())
  72979. {
  72980. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72981. if (lineWidth > widthPerLine)
  72982. {
  72983. // got to a point where the line's too long, so skip forward to find a
  72984. // good place to break it..
  72985. const int searchStartIndex = i;
  72986. while (i < glyphs.size())
  72987. {
  72988. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72989. {
  72990. if (glyphs.getUnchecked (i)->isWhitespace()
  72991. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72992. {
  72993. ++i;
  72994. break;
  72995. }
  72996. }
  72997. else
  72998. {
  72999. // can't find a suitable break, so try looking backwards..
  73000. i = searchStartIndex;
  73001. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73002. {
  73003. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73004. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73005. {
  73006. i -= back - 1;
  73007. break;
  73008. }
  73009. }
  73010. break;
  73011. }
  73012. ++i;
  73013. }
  73014. break;
  73015. }
  73016. ++i;
  73017. }
  73018. int wsStart = i;
  73019. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73020. --wsStart;
  73021. int wsEnd = i;
  73022. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73023. ++wsEnd;
  73024. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73025. i = jmax (wsStart, startIndex + 1);
  73026. }
  73027. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73028. x, lineY, width, font.getHeight(), font,
  73029. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73030. minimumHorizontalScale);
  73031. startIndex = i;
  73032. lineY += font.getHeight();
  73033. if (startIndex >= glyphs.size())
  73034. break;
  73035. }
  73036. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73037. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73038. }
  73039. }
  73040. }
  73041. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73042. const float dx, const float dy)
  73043. {
  73044. jassert (startIndex >= 0);
  73045. if (dx != 0.0f || dy != 0.0f)
  73046. {
  73047. if (num < 0 || startIndex + num > glyphs.size())
  73048. num = glyphs.size() - startIndex;
  73049. while (--num >= 0)
  73050. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73051. }
  73052. }
  73053. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73054. const Justification& justification, float minimumHorizontalScale)
  73055. {
  73056. int numDeleted = 0;
  73057. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73058. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73059. if (lineWidth > w)
  73060. {
  73061. if (minimumHorizontalScale < 1.0f)
  73062. {
  73063. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73064. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73065. }
  73066. if (lineWidth > w)
  73067. {
  73068. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73069. numGlyphs -= numDeleted;
  73070. }
  73071. }
  73072. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73073. return numDeleted;
  73074. }
  73075. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73076. const float horizontalScaleFactor)
  73077. {
  73078. jassert (startIndex >= 0);
  73079. if (num < 0 || startIndex + num > glyphs.size())
  73080. num = glyphs.size() - startIndex;
  73081. if (num > 0)
  73082. {
  73083. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73084. while (--num >= 0)
  73085. {
  73086. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73087. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73088. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73089. pg->w *= horizontalScaleFactor;
  73090. }
  73091. }
  73092. }
  73093. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73094. {
  73095. jassert (startIndex >= 0);
  73096. if (num < 0 || startIndex + num > glyphs.size())
  73097. num = glyphs.size() - startIndex;
  73098. Rectangle<float> result;
  73099. while (--num >= 0)
  73100. {
  73101. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73102. if (includeWhitespace || ! pg->isWhitespace())
  73103. result = result.getUnion (pg->getBounds());
  73104. }
  73105. return result;
  73106. }
  73107. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73108. const float x, const float y, const float width, const float height,
  73109. const Justification& justification)
  73110. {
  73111. jassert (num >= 0 && startIndex >= 0);
  73112. if (glyphs.size() > 0 && num > 0)
  73113. {
  73114. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73115. | Justification::horizontallyCentred)));
  73116. float deltaX = 0.0f;
  73117. if (justification.testFlags (Justification::horizontallyJustified))
  73118. deltaX = x - bb.getX();
  73119. else if (justification.testFlags (Justification::horizontallyCentred))
  73120. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73121. else if (justification.testFlags (Justification::right))
  73122. deltaX = (x + width) - bb.getRight();
  73123. else
  73124. deltaX = x - bb.getX();
  73125. float deltaY = 0.0f;
  73126. if (justification.testFlags (Justification::top))
  73127. deltaY = y - bb.getY();
  73128. else if (justification.testFlags (Justification::bottom))
  73129. deltaY = (y + height) - bb.getBottom();
  73130. else
  73131. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73132. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73133. if (justification.testFlags (Justification::horizontallyJustified))
  73134. {
  73135. int lineStart = 0;
  73136. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73137. int i;
  73138. for (i = 0; i < num; ++i)
  73139. {
  73140. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73141. if (glyphY != baseY)
  73142. {
  73143. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73144. lineStart = i;
  73145. baseY = glyphY;
  73146. }
  73147. }
  73148. if (i > lineStart)
  73149. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73150. }
  73151. }
  73152. }
  73153. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73154. {
  73155. if (start + num < glyphs.size()
  73156. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73157. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73158. {
  73159. int numSpaces = 0;
  73160. int spacesAtEnd = 0;
  73161. for (int i = 0; i < num; ++i)
  73162. {
  73163. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73164. {
  73165. ++spacesAtEnd;
  73166. ++numSpaces;
  73167. }
  73168. else
  73169. {
  73170. spacesAtEnd = 0;
  73171. }
  73172. }
  73173. numSpaces -= spacesAtEnd;
  73174. if (numSpaces > 0)
  73175. {
  73176. const float startX = glyphs.getUnchecked (start)->getLeft();
  73177. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73178. const float extraPaddingBetweenWords
  73179. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73180. float deltaX = 0.0f;
  73181. for (int i = 0; i < num; ++i)
  73182. {
  73183. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73184. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73185. deltaX += extraPaddingBetweenWords;
  73186. }
  73187. }
  73188. }
  73189. }
  73190. void GlyphArrangement::draw (const Graphics& g) const
  73191. {
  73192. for (int i = 0; i < glyphs.size(); ++i)
  73193. {
  73194. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73195. if (pg->font.isUnderlined())
  73196. {
  73197. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73198. float nextX = pg->x + pg->w;
  73199. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73200. nextX = glyphs.getUnchecked (i + 1)->x;
  73201. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73202. nextX - pg->x, lineThickness);
  73203. }
  73204. pg->draw (g);
  73205. }
  73206. }
  73207. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73208. {
  73209. for (int i = 0; i < glyphs.size(); ++i)
  73210. {
  73211. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73212. if (pg->font.isUnderlined())
  73213. {
  73214. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73215. float nextX = pg->x + pg->w;
  73216. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73217. nextX = glyphs.getUnchecked (i + 1)->x;
  73218. Path p;
  73219. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73220. nextX, pg->y + lineThickness * 2.0f),
  73221. lineThickness);
  73222. g.fillPath (p, transform);
  73223. }
  73224. pg->draw (g, transform);
  73225. }
  73226. }
  73227. void GlyphArrangement::createPath (Path& path) const
  73228. {
  73229. for (int i = 0; i < glyphs.size(); ++i)
  73230. glyphs.getUnchecked (i)->createPath (path);
  73231. }
  73232. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73233. {
  73234. for (int i = 0; i < glyphs.size(); ++i)
  73235. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73236. return i;
  73237. return -1;
  73238. }
  73239. END_JUCE_NAMESPACE
  73240. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73241. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73242. BEGIN_JUCE_NAMESPACE
  73243. class TextLayout::Token
  73244. {
  73245. public:
  73246. Token (const String& t,
  73247. const Font& f,
  73248. const bool isWhitespace_)
  73249. : text (t),
  73250. font (f),
  73251. x(0),
  73252. y(0),
  73253. isWhitespace (isWhitespace_)
  73254. {
  73255. w = font.getStringWidth (t);
  73256. h = roundToInt (f.getHeight());
  73257. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73258. }
  73259. Token (const Token& other)
  73260. : text (other.text),
  73261. font (other.font),
  73262. x (other.x),
  73263. y (other.y),
  73264. w (other.w),
  73265. h (other.h),
  73266. line (other.line),
  73267. lineHeight (other.lineHeight),
  73268. isWhitespace (other.isWhitespace),
  73269. isNewLine (other.isNewLine)
  73270. {
  73271. }
  73272. void draw (Graphics& g,
  73273. const int xOffset,
  73274. const int yOffset)
  73275. {
  73276. if (! isWhitespace)
  73277. {
  73278. g.setFont (font);
  73279. g.drawSingleLineText (text.trimEnd(),
  73280. xOffset + x,
  73281. yOffset + y + (lineHeight - h)
  73282. + roundToInt (font.getAscent()));
  73283. }
  73284. }
  73285. String text;
  73286. Font font;
  73287. int x, y, w, h;
  73288. int line, lineHeight;
  73289. bool isWhitespace, isNewLine;
  73290. private:
  73291. JUCE_LEAK_DETECTOR (Token);
  73292. };
  73293. TextLayout::TextLayout()
  73294. : totalLines (0)
  73295. {
  73296. tokens.ensureStorageAllocated (64);
  73297. }
  73298. TextLayout::TextLayout (const String& text, const Font& font)
  73299. : totalLines (0)
  73300. {
  73301. tokens.ensureStorageAllocated (64);
  73302. appendText (text, font);
  73303. }
  73304. TextLayout::TextLayout (const TextLayout& other)
  73305. : totalLines (0)
  73306. {
  73307. *this = other;
  73308. }
  73309. TextLayout& TextLayout::operator= (const TextLayout& other)
  73310. {
  73311. if (this != &other)
  73312. {
  73313. clear();
  73314. totalLines = other.totalLines;
  73315. tokens.addCopiesOf (other.tokens);
  73316. }
  73317. return *this;
  73318. }
  73319. TextLayout::~TextLayout()
  73320. {
  73321. clear();
  73322. }
  73323. void TextLayout::clear()
  73324. {
  73325. tokens.clear();
  73326. totalLines = 0;
  73327. }
  73328. bool TextLayout::isEmpty() const
  73329. {
  73330. return tokens.size() == 0;
  73331. }
  73332. void TextLayout::appendText (const String& text, const Font& font)
  73333. {
  73334. String::CharPointerType t (text.getCharPointer());
  73335. String currentString;
  73336. int lastCharType = 0;
  73337. for (;;)
  73338. {
  73339. const juce_wchar c = t.getAndAdvance();
  73340. if (c == 0)
  73341. break;
  73342. int charType;
  73343. if (c == '\r' || c == '\n')
  73344. {
  73345. charType = 0;
  73346. }
  73347. else if (CharacterFunctions::isWhitespace (c))
  73348. {
  73349. charType = 2;
  73350. }
  73351. else
  73352. {
  73353. charType = 1;
  73354. }
  73355. if (charType == 0 || charType != lastCharType)
  73356. {
  73357. if (currentString.isNotEmpty())
  73358. {
  73359. tokens.add (new Token (currentString, font,
  73360. lastCharType == 2 || lastCharType == 0));
  73361. }
  73362. currentString = String::charToString (c);
  73363. if (c == '\r' && *t == '\n')
  73364. currentString += t.getAndAdvance();
  73365. }
  73366. else
  73367. {
  73368. currentString += c;
  73369. }
  73370. lastCharType = charType;
  73371. }
  73372. if (currentString.isNotEmpty())
  73373. tokens.add (new Token (currentString, font, lastCharType == 2));
  73374. }
  73375. void TextLayout::setText (const String& text, const Font& font)
  73376. {
  73377. clear();
  73378. appendText (text, font);
  73379. }
  73380. void TextLayout::layout (int maxWidth,
  73381. const Justification& justification,
  73382. const bool attemptToBalanceLineLengths)
  73383. {
  73384. if (attemptToBalanceLineLengths)
  73385. {
  73386. const int originalW = maxWidth;
  73387. int bestWidth = maxWidth;
  73388. float bestLineProportion = 0.0f;
  73389. while (maxWidth > originalW / 2)
  73390. {
  73391. layout (maxWidth, justification, false);
  73392. if (getNumLines() <= 1)
  73393. return;
  73394. const int lastLineW = getLineWidth (getNumLines() - 1);
  73395. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73396. const float prop = lastLineW / (float) lastButOneLineW;
  73397. if (prop > 0.9f)
  73398. return;
  73399. if (prop > bestLineProportion)
  73400. {
  73401. bestLineProportion = prop;
  73402. bestWidth = maxWidth;
  73403. }
  73404. maxWidth -= 10;
  73405. }
  73406. layout (bestWidth, justification, false);
  73407. }
  73408. else
  73409. {
  73410. int x = 0;
  73411. int y = 0;
  73412. int h = 0;
  73413. totalLines = 0;
  73414. int i;
  73415. for (i = 0; i < tokens.size(); ++i)
  73416. {
  73417. Token* const t = tokens.getUnchecked(i);
  73418. t->x = x;
  73419. t->y = y;
  73420. t->line = totalLines;
  73421. x += t->w;
  73422. h = jmax (h, t->h);
  73423. const Token* nextTok = tokens [i + 1];
  73424. if (nextTok == 0)
  73425. break;
  73426. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73427. {
  73428. // finished a line, so go back and update the heights of the things on it
  73429. for (int j = i; j >= 0; --j)
  73430. {
  73431. Token* const tok = tokens.getUnchecked(j);
  73432. if (tok->line == totalLines)
  73433. tok->lineHeight = h;
  73434. else
  73435. break;
  73436. }
  73437. x = 0;
  73438. y += h;
  73439. h = 0;
  73440. ++totalLines;
  73441. }
  73442. }
  73443. // finished a line, so go back and update the heights of the things on it
  73444. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73445. {
  73446. Token* const t = tokens.getUnchecked(j);
  73447. if (t->line == totalLines)
  73448. t->lineHeight = h;
  73449. else
  73450. break;
  73451. }
  73452. ++totalLines;
  73453. if (! justification.testFlags (Justification::left))
  73454. {
  73455. int totalW = getWidth();
  73456. for (i = totalLines; --i >= 0;)
  73457. {
  73458. const int lineW = getLineWidth (i);
  73459. int dx = 0;
  73460. if (justification.testFlags (Justification::horizontallyCentred))
  73461. dx = (totalW - lineW) / 2;
  73462. else if (justification.testFlags (Justification::right))
  73463. dx = totalW - lineW;
  73464. for (int j = tokens.size(); --j >= 0;)
  73465. {
  73466. Token* const t = tokens.getUnchecked(j);
  73467. if (t->line == i)
  73468. t->x += dx;
  73469. }
  73470. }
  73471. }
  73472. }
  73473. }
  73474. int TextLayout::getLineWidth (const int lineNumber) const
  73475. {
  73476. int maxW = 0;
  73477. for (int i = tokens.size(); --i >= 0;)
  73478. {
  73479. const Token* const t = tokens.getUnchecked(i);
  73480. if (t->line == lineNumber && ! t->isWhitespace)
  73481. maxW = jmax (maxW, t->x + t->w);
  73482. }
  73483. return maxW;
  73484. }
  73485. int TextLayout::getWidth() const
  73486. {
  73487. int maxW = 0;
  73488. for (int i = tokens.size(); --i >= 0;)
  73489. {
  73490. const Token* const t = tokens.getUnchecked(i);
  73491. if (! t->isWhitespace)
  73492. maxW = jmax (maxW, t->x + t->w);
  73493. }
  73494. return maxW;
  73495. }
  73496. int TextLayout::getHeight() const
  73497. {
  73498. int maxH = 0;
  73499. for (int i = tokens.size(); --i >= 0;)
  73500. {
  73501. const Token* const t = tokens.getUnchecked(i);
  73502. if (! t->isWhitespace)
  73503. maxH = jmax (maxH, t->y + t->h);
  73504. }
  73505. return maxH;
  73506. }
  73507. void TextLayout::draw (Graphics& g,
  73508. const int xOffset,
  73509. const int yOffset) const
  73510. {
  73511. for (int i = tokens.size(); --i >= 0;)
  73512. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73513. }
  73514. void TextLayout::drawWithin (Graphics& g,
  73515. int x, int y, int w, int h,
  73516. const Justification& justification) const
  73517. {
  73518. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73519. x, y, w, h);
  73520. draw (g, x, y);
  73521. }
  73522. END_JUCE_NAMESPACE
  73523. /*** End of inlined file: juce_TextLayout.cpp ***/
  73524. /*** Start of inlined file: juce_Typeface.cpp ***/
  73525. BEGIN_JUCE_NAMESPACE
  73526. Typeface::Typeface (const String& name_) throw()
  73527. : name (name_), isFallbackFont (false)
  73528. {
  73529. }
  73530. Typeface::~Typeface()
  73531. {
  73532. }
  73533. const Typeface::Ptr Typeface::getFallbackTypeface()
  73534. {
  73535. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73536. Typeface* t = fallbackFont.getTypeface();
  73537. t->isFallbackFont = true;
  73538. return t;
  73539. }
  73540. class CustomTypeface::GlyphInfo
  73541. {
  73542. public:
  73543. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73544. : character (character_), path (path_), width (width_)
  73545. {
  73546. }
  73547. struct KerningPair
  73548. {
  73549. juce_wchar character2;
  73550. float kerningAmount;
  73551. };
  73552. void addKerningPair (const juce_wchar subsequentCharacter,
  73553. const float extraKerningAmount) throw()
  73554. {
  73555. KerningPair kp;
  73556. kp.character2 = subsequentCharacter;
  73557. kp.kerningAmount = extraKerningAmount;
  73558. kerningPairs.add (kp);
  73559. }
  73560. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73561. {
  73562. if (subsequentCharacter != 0)
  73563. {
  73564. for (int i = kerningPairs.size(); --i >= 0;)
  73565. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73566. return width + kerningPairs.getReference(i).kerningAmount;
  73567. }
  73568. return width;
  73569. }
  73570. const juce_wchar character;
  73571. const Path path;
  73572. float width;
  73573. Array <KerningPair> kerningPairs;
  73574. private:
  73575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GlyphInfo);
  73576. };
  73577. CustomTypeface::CustomTypeface()
  73578. : Typeface (String::empty)
  73579. {
  73580. clear();
  73581. }
  73582. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73583. : Typeface (String::empty)
  73584. {
  73585. clear();
  73586. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73587. BufferedInputStream in (gzin, 32768);
  73588. name = in.readString();
  73589. isBold = in.readBool();
  73590. isItalic = in.readBool();
  73591. ascent = in.readFloat();
  73592. defaultCharacter = (juce_wchar) in.readShort();
  73593. int i, numChars = in.readInt();
  73594. for (i = 0; i < numChars; ++i)
  73595. {
  73596. const juce_wchar c = (juce_wchar) in.readShort();
  73597. const float width = in.readFloat();
  73598. Path p;
  73599. p.loadPathFromStream (in);
  73600. addGlyph (c, p, width);
  73601. }
  73602. const int numKerningPairs = in.readInt();
  73603. for (i = 0; i < numKerningPairs; ++i)
  73604. {
  73605. const juce_wchar char1 = (juce_wchar) in.readShort();
  73606. const juce_wchar char2 = (juce_wchar) in.readShort();
  73607. addKerningPair (char1, char2, in.readFloat());
  73608. }
  73609. }
  73610. CustomTypeface::~CustomTypeface()
  73611. {
  73612. }
  73613. void CustomTypeface::clear()
  73614. {
  73615. defaultCharacter = 0;
  73616. ascent = 1.0f;
  73617. isBold = isItalic = false;
  73618. zeromem (lookupTable, sizeof (lookupTable));
  73619. glyphs.clear();
  73620. }
  73621. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73622. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73623. {
  73624. name = name_;
  73625. defaultCharacter = defaultCharacter_;
  73626. ascent = ascent_;
  73627. isBold = isBold_;
  73628. isItalic = isItalic_;
  73629. }
  73630. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73631. {
  73632. // Check that you're not trying to add the same character twice..
  73633. jassert (findGlyph (character, false) == 0);
  73634. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)))
  73635. lookupTable [character] = (short) glyphs.size();
  73636. glyphs.add (new GlyphInfo (character, path, width));
  73637. }
  73638. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73639. {
  73640. if (extraAmount != 0)
  73641. {
  73642. GlyphInfo* const g = findGlyph (char1, true);
  73643. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73644. if (g != 0)
  73645. g->addKerningPair (char2, extraAmount);
  73646. }
  73647. }
  73648. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73649. {
  73650. if (isPositiveAndBelow ((int) character, (int) numElementsInArray (lookupTable)) && lookupTable [character] > 0)
  73651. return glyphs [(int) lookupTable [(int) character]];
  73652. for (int i = 0; i < glyphs.size(); ++i)
  73653. {
  73654. GlyphInfo* const g = glyphs.getUnchecked(i);
  73655. if (g->character == character)
  73656. return g;
  73657. }
  73658. if (loadIfNeeded && loadGlyphIfPossible (character))
  73659. return findGlyph (character, false);
  73660. return 0;
  73661. }
  73662. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73663. {
  73664. GlyphInfo* glyph = findGlyph (character, true);
  73665. if (glyph == 0)
  73666. {
  73667. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73668. glyph = findGlyph (L' ', true);
  73669. if (glyph == 0)
  73670. {
  73671. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73672. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73673. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73674. {
  73675. Path path;
  73676. fallbackTypeface->getOutlineForGlyph (character, path);
  73677. addGlyph (character, path, fallbackTypeface->getStringWidth (String::charToString (character)));
  73678. }
  73679. if (glyph == 0)
  73680. glyph = findGlyph (defaultCharacter, true);
  73681. }
  73682. }
  73683. return glyph;
  73684. }
  73685. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73686. {
  73687. return false;
  73688. }
  73689. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73690. {
  73691. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73692. for (int i = 0; i < numCharacters; ++i)
  73693. {
  73694. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73695. Array <int> glyphIndexes;
  73696. Array <float> offsets;
  73697. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73698. const int glyphIndex = glyphIndexes.getFirst();
  73699. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73700. {
  73701. const float glyphWidth = offsets[1];
  73702. Path p;
  73703. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73704. addGlyph (c, p, glyphWidth);
  73705. for (int j = glyphs.size() - 1; --j >= 0;)
  73706. {
  73707. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73708. glyphIndexes.clearQuick();
  73709. offsets.clearQuick();
  73710. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73711. if (offsets.size() > 1)
  73712. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73713. }
  73714. }
  73715. }
  73716. }
  73717. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73718. {
  73719. GZIPCompressorOutputStream out (&outputStream);
  73720. out.writeString (name);
  73721. out.writeBool (isBold);
  73722. out.writeBool (isItalic);
  73723. out.writeFloat (ascent);
  73724. out.writeShort ((short) (unsigned short) defaultCharacter);
  73725. out.writeInt (glyphs.size());
  73726. int i, numKerningPairs = 0;
  73727. for (i = 0; i < glyphs.size(); ++i)
  73728. {
  73729. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73730. out.writeShort ((short) (unsigned short) g->character);
  73731. out.writeFloat (g->width);
  73732. g->path.writePathToStream (out);
  73733. numKerningPairs += g->kerningPairs.size();
  73734. }
  73735. out.writeInt (numKerningPairs);
  73736. for (i = 0; i < glyphs.size(); ++i)
  73737. {
  73738. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73739. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73740. {
  73741. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73742. out.writeShort ((short) (unsigned short) g->character);
  73743. out.writeShort ((short) (unsigned short) p.character2);
  73744. out.writeFloat (p.kerningAmount);
  73745. }
  73746. }
  73747. return true;
  73748. }
  73749. float CustomTypeface::getAscent() const
  73750. {
  73751. return ascent;
  73752. }
  73753. float CustomTypeface::getDescent() const
  73754. {
  73755. return 1.0f - ascent;
  73756. }
  73757. float CustomTypeface::getStringWidth (const String& text)
  73758. {
  73759. float x = 0;
  73760. String::CharPointerType t (text.getCharPointer());
  73761. while (! t.isEmpty())
  73762. {
  73763. const GlyphInfo* const glyph = findGlyphSubstituting (t.getAndAdvance());
  73764. if (glyph == 0 && ! isFallbackFont)
  73765. {
  73766. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73767. if (fallbackTypeface != 0)
  73768. x += fallbackTypeface->getStringWidth (String::charToString (*t));
  73769. }
  73770. if (glyph != 0)
  73771. x += glyph->getHorizontalSpacing (*t);
  73772. }
  73773. return x;
  73774. }
  73775. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73776. {
  73777. xOffsets.add (0);
  73778. float x = 0;
  73779. String::CharPointerType t (text.getCharPointer());
  73780. while (! t.isEmpty())
  73781. {
  73782. const juce_wchar c = t.getAndAdvance();
  73783. const GlyphInfo* const glyph = findGlyph (c, true);
  73784. if (glyph == 0 && ! isFallbackFont)
  73785. {
  73786. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73787. if (fallbackTypeface != 0)
  73788. {
  73789. Array <int> subGlyphs;
  73790. Array <float> subOffsets;
  73791. fallbackTypeface->getGlyphPositions (String::charToString (c), subGlyphs, subOffsets);
  73792. if (subGlyphs.size() > 0)
  73793. {
  73794. resultGlyphs.add (subGlyphs.getFirst());
  73795. x += subOffsets[1];
  73796. xOffsets.add (x);
  73797. }
  73798. }
  73799. }
  73800. if (glyph != 0)
  73801. {
  73802. x += glyph->getHorizontalSpacing (*t);
  73803. resultGlyphs.add ((int) glyph->character);
  73804. xOffsets.add (x);
  73805. }
  73806. }
  73807. }
  73808. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73809. {
  73810. const GlyphInfo* const glyph = findGlyph ((juce_wchar) glyphNumber, true);
  73811. if (glyph == 0 && ! isFallbackFont)
  73812. {
  73813. const Typeface::Ptr fallbackTypeface (Typeface::getFallbackTypeface());
  73814. if (fallbackTypeface != 0)
  73815. fallbackTypeface->getOutlineForGlyph (glyphNumber, path);
  73816. }
  73817. if (glyph != 0)
  73818. {
  73819. path = glyph->path;
  73820. return true;
  73821. }
  73822. return false;
  73823. }
  73824. END_JUCE_NAMESPACE
  73825. /*** End of inlined file: juce_Typeface.cpp ***/
  73826. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73827. BEGIN_JUCE_NAMESPACE
  73828. AffineTransform::AffineTransform() throw()
  73829. : mat00 (1.0f), mat01 (0), mat02 (0),
  73830. mat10 (0), mat11 (1.0f), mat12 (0)
  73831. {
  73832. }
  73833. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73834. : mat00 (other.mat00), mat01 (other.mat01), mat02 (other.mat02),
  73835. mat10 (other.mat10), mat11 (other.mat11), mat12 (other.mat12)
  73836. {
  73837. }
  73838. AffineTransform::AffineTransform (const float mat00_, const float mat01_, const float mat02_,
  73839. const float mat10_, const float mat11_, const float mat12_) throw()
  73840. : mat00 (mat00_), mat01 (mat01_), mat02 (mat02_),
  73841. mat10 (mat10_), mat11 (mat11_), mat12 (mat12_)
  73842. {
  73843. }
  73844. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73845. {
  73846. mat00 = other.mat00;
  73847. mat01 = other.mat01;
  73848. mat02 = other.mat02;
  73849. mat10 = other.mat10;
  73850. mat11 = other.mat11;
  73851. mat12 = other.mat12;
  73852. return *this;
  73853. }
  73854. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73855. {
  73856. return mat00 == other.mat00
  73857. && mat01 == other.mat01
  73858. && mat02 == other.mat02
  73859. && mat10 == other.mat10
  73860. && mat11 == other.mat11
  73861. && mat12 == other.mat12;
  73862. }
  73863. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73864. {
  73865. return ! operator== (other);
  73866. }
  73867. bool AffineTransform::isIdentity() const throw()
  73868. {
  73869. return (mat01 == 0)
  73870. && (mat02 == 0)
  73871. && (mat10 == 0)
  73872. && (mat12 == 0)
  73873. && (mat00 == 1.0f)
  73874. && (mat11 == 1.0f);
  73875. }
  73876. const AffineTransform AffineTransform::identity;
  73877. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73878. {
  73879. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73880. other.mat00 * mat01 + other.mat01 * mat11,
  73881. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73882. other.mat10 * mat00 + other.mat11 * mat10,
  73883. other.mat10 * mat01 + other.mat11 * mat11,
  73884. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73885. }
  73886. const AffineTransform AffineTransform::translated (const float dx, const float dy) const throw()
  73887. {
  73888. return AffineTransform (mat00, mat01, mat02 + dx,
  73889. mat10, mat11, mat12 + dy);
  73890. }
  73891. const AffineTransform AffineTransform::translation (const float dx, const float dy) throw()
  73892. {
  73893. return AffineTransform (1.0f, 0, dx,
  73894. 0, 1.0f, dy);
  73895. }
  73896. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73897. {
  73898. const float cosRad = std::cos (rad);
  73899. const float sinRad = std::sin (rad);
  73900. return AffineTransform (cosRad * mat00 + -sinRad * mat10,
  73901. cosRad * mat01 + -sinRad * mat11,
  73902. cosRad * mat02 + -sinRad * mat12,
  73903. sinRad * mat00 + cosRad * mat10,
  73904. sinRad * mat01 + cosRad * mat11,
  73905. sinRad * mat02 + cosRad * mat12);
  73906. }
  73907. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73908. {
  73909. const float cosRad = std::cos (rad);
  73910. const float sinRad = std::sin (rad);
  73911. return AffineTransform (cosRad, -sinRad, 0,
  73912. sinRad, cosRad, 0);
  73913. }
  73914. const AffineTransform AffineTransform::rotation (const float rad, const float pivotX, const float pivotY) throw()
  73915. {
  73916. const float cosRad = std::cos (rad);
  73917. const float sinRad = std::sin (rad);
  73918. return AffineTransform (cosRad, -sinRad, -cosRad * pivotX + sinRad * pivotY + pivotX,
  73919. sinRad, cosRad, -sinRad * pivotX + -cosRad * pivotY + pivotY);
  73920. }
  73921. const AffineTransform AffineTransform::rotated (const float angle, const float pivotX, const float pivotY) const throw()
  73922. {
  73923. return followedBy (rotation (angle, pivotX, pivotY));
  73924. }
  73925. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY) const throw()
  73926. {
  73927. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73928. factorY * mat10, factorY * mat11, factorY * mat12);
  73929. }
  73930. const AffineTransform AffineTransform::scale (const float factorX, const float factorY) throw()
  73931. {
  73932. return AffineTransform (factorX, 0, 0,
  73933. 0, factorY, 0);
  73934. }
  73935. const AffineTransform AffineTransform::scaled (const float factorX, const float factorY,
  73936. const float pivotX, const float pivotY) const throw()
  73937. {
  73938. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02 + pivotX * (1.0f - factorX),
  73939. factorY * mat10, factorY * mat11, factorY * mat12 + pivotY * (1.0f - factorY));
  73940. }
  73941. const AffineTransform AffineTransform::scale (const float factorX, const float factorY,
  73942. const float pivotX, const float pivotY) throw()
  73943. {
  73944. return AffineTransform (factorX, 0, pivotX * (1.0f - factorX),
  73945. 0, factorY, pivotY * (1.0f - factorY));
  73946. }
  73947. const AffineTransform AffineTransform::shear (float shearX, float shearY) throw()
  73948. {
  73949. return AffineTransform (1.0f, shearX, 0,
  73950. shearY, 1.0f, 0);
  73951. }
  73952. const AffineTransform AffineTransform::sheared (const float shearX, const float shearY) const throw()
  73953. {
  73954. return AffineTransform (mat00 + shearX * mat10,
  73955. mat01 + shearX * mat11,
  73956. mat02 + shearX * mat12,
  73957. shearY * mat00 + mat10,
  73958. shearY * mat01 + mat11,
  73959. shearY * mat02 + mat12);
  73960. }
  73961. const AffineTransform AffineTransform::inverted() const throw()
  73962. {
  73963. double determinant = (mat00 * mat11 - mat10 * mat01);
  73964. if (determinant != 0.0)
  73965. {
  73966. determinant = 1.0 / determinant;
  73967. const float dst00 = (float) (mat11 * determinant);
  73968. const float dst10 = (float) (-mat10 * determinant);
  73969. const float dst01 = (float) (-mat01 * determinant);
  73970. const float dst11 = (float) (mat00 * determinant);
  73971. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73972. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73973. }
  73974. else
  73975. {
  73976. // singularity..
  73977. return *this;
  73978. }
  73979. }
  73980. bool AffineTransform::isSingularity() const throw()
  73981. {
  73982. return (mat00 * mat11 - mat10 * mat01) == 0;
  73983. }
  73984. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73985. const float x10, const float y10,
  73986. const float x01, const float y01) throw()
  73987. {
  73988. return AffineTransform (x10 - x00, x01 - x00, x00,
  73989. y10 - y00, y01 - y00, y00);
  73990. }
  73991. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73992. const float sx2, const float sy2, const float tx2, const float ty2,
  73993. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73994. {
  73995. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73996. .inverted()
  73997. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73998. }
  73999. bool AffineTransform::isOnlyTranslation() const throw()
  74000. {
  74001. return (mat01 == 0)
  74002. && (mat10 == 0)
  74003. && (mat00 == 1.0f)
  74004. && (mat11 == 1.0f);
  74005. }
  74006. float AffineTransform::getScaleFactor() const throw()
  74007. {
  74008. return juce_hypot (mat00 + mat01, mat10 + mat11);
  74009. }
  74010. END_JUCE_NAMESPACE
  74011. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74012. /*** Start of inlined file: juce_Path.cpp ***/
  74013. BEGIN_JUCE_NAMESPACE
  74014. // tests that some co-ords aren't NaNs
  74015. #define CHECK_COORDS_ARE_VALID(x, y) \
  74016. jassert (x == x && y == y);
  74017. namespace PathHelpers
  74018. {
  74019. const float ellipseAngularIncrement = 0.05f;
  74020. const String nextToken (String::CharPointerType& t)
  74021. {
  74022. t = t.findEndOfWhitespace();
  74023. String::CharPointerType start (t);
  74024. int numChars = 0;
  74025. while (! (t.isEmpty() || t.isWhitespace()))
  74026. {
  74027. ++t;
  74028. ++numChars;
  74029. }
  74030. return String (start, numChars);
  74031. }
  74032. inline double lengthOf (float x1, float y1, float x2, float y2) throw()
  74033. {
  74034. return juce_hypot ((double) (x1 - x2), (double) (y1 - y2));
  74035. }
  74036. }
  74037. const float Path::lineMarker = 100001.0f;
  74038. const float Path::moveMarker = 100002.0f;
  74039. const float Path::quadMarker = 100003.0f;
  74040. const float Path::cubicMarker = 100004.0f;
  74041. const float Path::closeSubPathMarker = 100005.0f;
  74042. Path::Path()
  74043. : numElements (0),
  74044. pathXMin (0),
  74045. pathXMax (0),
  74046. pathYMin (0),
  74047. pathYMax (0),
  74048. useNonZeroWinding (true)
  74049. {
  74050. }
  74051. Path::~Path()
  74052. {
  74053. }
  74054. Path::Path (const Path& other)
  74055. : numElements (other.numElements),
  74056. pathXMin (other.pathXMin),
  74057. pathXMax (other.pathXMax),
  74058. pathYMin (other.pathYMin),
  74059. pathYMax (other.pathYMax),
  74060. useNonZeroWinding (other.useNonZeroWinding)
  74061. {
  74062. if (numElements > 0)
  74063. {
  74064. data.setAllocatedSize ((int) numElements);
  74065. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74066. }
  74067. }
  74068. Path& Path::operator= (const Path& other)
  74069. {
  74070. if (this != &other)
  74071. {
  74072. data.ensureAllocatedSize ((int) other.numElements);
  74073. numElements = other.numElements;
  74074. pathXMin = other.pathXMin;
  74075. pathXMax = other.pathXMax;
  74076. pathYMin = other.pathYMin;
  74077. pathYMax = other.pathYMax;
  74078. useNonZeroWinding = other.useNonZeroWinding;
  74079. if (numElements > 0)
  74080. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74081. }
  74082. return *this;
  74083. }
  74084. bool Path::operator== (const Path& other) const throw()
  74085. {
  74086. return ! operator!= (other);
  74087. }
  74088. bool Path::operator!= (const Path& other) const throw()
  74089. {
  74090. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74091. return true;
  74092. for (size_t i = 0; i < numElements; ++i)
  74093. if (data.elements[i] != other.data.elements[i])
  74094. return true;
  74095. return false;
  74096. }
  74097. void Path::clear() throw()
  74098. {
  74099. numElements = 0;
  74100. pathXMin = 0;
  74101. pathYMin = 0;
  74102. pathYMax = 0;
  74103. pathXMax = 0;
  74104. }
  74105. void Path::swapWithPath (Path& other) throw()
  74106. {
  74107. data.swapWith (other.data);
  74108. swapVariables <size_t> (numElements, other.numElements);
  74109. swapVariables <float> (pathXMin, other.pathXMin);
  74110. swapVariables <float> (pathXMax, other.pathXMax);
  74111. swapVariables <float> (pathYMin, other.pathYMin);
  74112. swapVariables <float> (pathYMax, other.pathYMax);
  74113. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74114. }
  74115. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74116. {
  74117. useNonZeroWinding = isNonZero;
  74118. }
  74119. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74120. const bool preserveProportions) throw()
  74121. {
  74122. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74123. }
  74124. bool Path::isEmpty() const throw()
  74125. {
  74126. size_t i = 0;
  74127. while (i < numElements)
  74128. {
  74129. const float type = data.elements [i++];
  74130. if (type == moveMarker)
  74131. {
  74132. i += 2;
  74133. }
  74134. else if (type == lineMarker
  74135. || type == quadMarker
  74136. || type == cubicMarker)
  74137. {
  74138. return false;
  74139. }
  74140. }
  74141. return true;
  74142. }
  74143. const Rectangle<float> Path::getBounds() const throw()
  74144. {
  74145. return Rectangle<float> (pathXMin, pathYMin,
  74146. pathXMax - pathXMin,
  74147. pathYMax - pathYMin);
  74148. }
  74149. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74150. {
  74151. return getBounds().transformed (transform);
  74152. }
  74153. void Path::startNewSubPath (const float x, const float y)
  74154. {
  74155. CHECK_COORDS_ARE_VALID (x, y);
  74156. if (numElements == 0)
  74157. {
  74158. pathXMin = pathXMax = x;
  74159. pathYMin = pathYMax = y;
  74160. }
  74161. else
  74162. {
  74163. pathXMin = jmin (pathXMin, x);
  74164. pathXMax = jmax (pathXMax, x);
  74165. pathYMin = jmin (pathYMin, y);
  74166. pathYMax = jmax (pathYMax, y);
  74167. }
  74168. data.ensureAllocatedSize ((int) numElements + 3);
  74169. data.elements [numElements++] = moveMarker;
  74170. data.elements [numElements++] = x;
  74171. data.elements [numElements++] = y;
  74172. }
  74173. void Path::startNewSubPath (const Point<float>& start)
  74174. {
  74175. startNewSubPath (start.getX(), start.getY());
  74176. }
  74177. void Path::lineTo (const float x, const float y)
  74178. {
  74179. CHECK_COORDS_ARE_VALID (x, y);
  74180. if (numElements == 0)
  74181. startNewSubPath (0, 0);
  74182. data.ensureAllocatedSize ((int) numElements + 3);
  74183. data.elements [numElements++] = lineMarker;
  74184. data.elements [numElements++] = x;
  74185. data.elements [numElements++] = y;
  74186. pathXMin = jmin (pathXMin, x);
  74187. pathXMax = jmax (pathXMax, x);
  74188. pathYMin = jmin (pathYMin, y);
  74189. pathYMax = jmax (pathYMax, y);
  74190. }
  74191. void Path::lineTo (const Point<float>& end)
  74192. {
  74193. lineTo (end.getX(), end.getY());
  74194. }
  74195. void Path::quadraticTo (const float x1, const float y1,
  74196. const float x2, const float y2)
  74197. {
  74198. CHECK_COORDS_ARE_VALID (x1, y1);
  74199. CHECK_COORDS_ARE_VALID (x2, y2);
  74200. if (numElements == 0)
  74201. startNewSubPath (0, 0);
  74202. data.ensureAllocatedSize ((int) numElements + 5);
  74203. data.elements [numElements++] = quadMarker;
  74204. data.elements [numElements++] = x1;
  74205. data.elements [numElements++] = y1;
  74206. data.elements [numElements++] = x2;
  74207. data.elements [numElements++] = y2;
  74208. pathXMin = jmin (pathXMin, x1, x2);
  74209. pathXMax = jmax (pathXMax, x1, x2);
  74210. pathYMin = jmin (pathYMin, y1, y2);
  74211. pathYMax = jmax (pathYMax, y1, y2);
  74212. }
  74213. void Path::quadraticTo (const Point<float>& controlPoint,
  74214. const Point<float>& endPoint)
  74215. {
  74216. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74217. endPoint.getX(), endPoint.getY());
  74218. }
  74219. void Path::cubicTo (const float x1, const float y1,
  74220. const float x2, const float y2,
  74221. const float x3, const float y3)
  74222. {
  74223. CHECK_COORDS_ARE_VALID (x1, y1);
  74224. CHECK_COORDS_ARE_VALID (x2, y2);
  74225. CHECK_COORDS_ARE_VALID (x3, y3);
  74226. if (numElements == 0)
  74227. startNewSubPath (0, 0);
  74228. data.ensureAllocatedSize ((int) numElements + 7);
  74229. data.elements [numElements++] = cubicMarker;
  74230. data.elements [numElements++] = x1;
  74231. data.elements [numElements++] = y1;
  74232. data.elements [numElements++] = x2;
  74233. data.elements [numElements++] = y2;
  74234. data.elements [numElements++] = x3;
  74235. data.elements [numElements++] = y3;
  74236. pathXMin = jmin (pathXMin, x1, x2, x3);
  74237. pathXMax = jmax (pathXMax, x1, x2, x3);
  74238. pathYMin = jmin (pathYMin, y1, y2, y3);
  74239. pathYMax = jmax (pathYMax, y1, y2, y3);
  74240. }
  74241. void Path::cubicTo (const Point<float>& controlPoint1,
  74242. const Point<float>& controlPoint2,
  74243. const Point<float>& endPoint)
  74244. {
  74245. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74246. controlPoint2.getX(), controlPoint2.getY(),
  74247. endPoint.getX(), endPoint.getY());
  74248. }
  74249. void Path::closeSubPath()
  74250. {
  74251. if (numElements > 0
  74252. && data.elements [numElements - 1] != closeSubPathMarker)
  74253. {
  74254. data.ensureAllocatedSize ((int) numElements + 1);
  74255. data.elements [numElements++] = closeSubPathMarker;
  74256. }
  74257. }
  74258. const Point<float> Path::getCurrentPosition() const
  74259. {
  74260. int i = (int) numElements - 1;
  74261. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74262. {
  74263. while (i >= 0)
  74264. {
  74265. if (data.elements[i] == moveMarker)
  74266. {
  74267. i += 2;
  74268. break;
  74269. }
  74270. --i;
  74271. }
  74272. }
  74273. if (i > 0)
  74274. return Point<float> (data.elements [i - 1], data.elements [i]);
  74275. return Point<float>();
  74276. }
  74277. void Path::addRectangle (const float x, const float y,
  74278. const float w, const float h)
  74279. {
  74280. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74281. if (w < 0)
  74282. swapVariables (x1, x2);
  74283. if (h < 0)
  74284. swapVariables (y1, y2);
  74285. data.ensureAllocatedSize ((int) numElements + 13);
  74286. if (numElements == 0)
  74287. {
  74288. pathXMin = x1;
  74289. pathXMax = x2;
  74290. pathYMin = y1;
  74291. pathYMax = y2;
  74292. }
  74293. else
  74294. {
  74295. pathXMin = jmin (pathXMin, x1);
  74296. pathXMax = jmax (pathXMax, x2);
  74297. pathYMin = jmin (pathYMin, y1);
  74298. pathYMax = jmax (pathYMax, y2);
  74299. }
  74300. data.elements [numElements++] = moveMarker;
  74301. data.elements [numElements++] = x1;
  74302. data.elements [numElements++] = y2;
  74303. data.elements [numElements++] = lineMarker;
  74304. data.elements [numElements++] = x1;
  74305. data.elements [numElements++] = y1;
  74306. data.elements [numElements++] = lineMarker;
  74307. data.elements [numElements++] = x2;
  74308. data.elements [numElements++] = y1;
  74309. data.elements [numElements++] = lineMarker;
  74310. data.elements [numElements++] = x2;
  74311. data.elements [numElements++] = y2;
  74312. data.elements [numElements++] = closeSubPathMarker;
  74313. }
  74314. void Path::addRoundedRectangle (const float x, const float y,
  74315. const float w, const float h,
  74316. float csx,
  74317. float csy)
  74318. {
  74319. csx = jmin (csx, w * 0.5f);
  74320. csy = jmin (csy, h * 0.5f);
  74321. const float cs45x = csx * 0.45f;
  74322. const float cs45y = csy * 0.45f;
  74323. const float x2 = x + w;
  74324. const float y2 = y + h;
  74325. startNewSubPath (x + csx, y);
  74326. lineTo (x2 - csx, y);
  74327. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74328. lineTo (x2, y2 - csy);
  74329. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74330. lineTo (x + csx, y2);
  74331. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74332. lineTo (x, y + csy);
  74333. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74334. closeSubPath();
  74335. }
  74336. void Path::addRoundedRectangle (const float x, const float y,
  74337. const float w, const float h,
  74338. float cs)
  74339. {
  74340. addRoundedRectangle (x, y, w, h, cs, cs);
  74341. }
  74342. void Path::addTriangle (const float x1, const float y1,
  74343. const float x2, const float y2,
  74344. const float x3, const float y3)
  74345. {
  74346. startNewSubPath (x1, y1);
  74347. lineTo (x2, y2);
  74348. lineTo (x3, y3);
  74349. closeSubPath();
  74350. }
  74351. void Path::addQuadrilateral (const float x1, const float y1,
  74352. const float x2, const float y2,
  74353. const float x3, const float y3,
  74354. const float x4, const float y4)
  74355. {
  74356. startNewSubPath (x1, y1);
  74357. lineTo (x2, y2);
  74358. lineTo (x3, y3);
  74359. lineTo (x4, y4);
  74360. closeSubPath();
  74361. }
  74362. void Path::addEllipse (const float x, const float y,
  74363. const float w, const float h)
  74364. {
  74365. const float hw = w * 0.5f;
  74366. const float hw55 = hw * 0.55f;
  74367. const float hh = h * 0.5f;
  74368. const float hh55 = hh * 0.55f;
  74369. const float cx = x + hw;
  74370. const float cy = y + hh;
  74371. startNewSubPath (cx, cy - hh);
  74372. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74373. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74374. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74375. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74376. closeSubPath();
  74377. }
  74378. void Path::addArc (const float x, const float y,
  74379. const float w, const float h,
  74380. const float fromRadians,
  74381. const float toRadians,
  74382. const bool startAsNewSubPath)
  74383. {
  74384. const float radiusX = w / 2.0f;
  74385. const float radiusY = h / 2.0f;
  74386. addCentredArc (x + radiusX,
  74387. y + radiusY,
  74388. radiusX, radiusY,
  74389. 0.0f,
  74390. fromRadians, toRadians,
  74391. startAsNewSubPath);
  74392. }
  74393. void Path::addCentredArc (const float centreX, const float centreY,
  74394. const float radiusX, const float radiusY,
  74395. const float rotationOfEllipse,
  74396. const float fromRadians,
  74397. const float toRadians,
  74398. const bool startAsNewSubPath)
  74399. {
  74400. if (radiusX > 0.0f && radiusY > 0.0f)
  74401. {
  74402. const Point<float> centre (centreX, centreY);
  74403. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74404. float angle = fromRadians;
  74405. if (startAsNewSubPath)
  74406. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74407. if (fromRadians < toRadians)
  74408. {
  74409. if (startAsNewSubPath)
  74410. angle += PathHelpers::ellipseAngularIncrement;
  74411. while (angle < toRadians)
  74412. {
  74413. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74414. angle += PathHelpers::ellipseAngularIncrement;
  74415. }
  74416. }
  74417. else
  74418. {
  74419. if (startAsNewSubPath)
  74420. angle -= PathHelpers::ellipseAngularIncrement;
  74421. while (angle > toRadians)
  74422. {
  74423. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74424. angle -= PathHelpers::ellipseAngularIncrement;
  74425. }
  74426. }
  74427. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74428. }
  74429. }
  74430. void Path::addPieSegment (const float x, const float y,
  74431. const float width, const float height,
  74432. const float fromRadians,
  74433. const float toRadians,
  74434. const float innerCircleProportionalSize)
  74435. {
  74436. float radiusX = width * 0.5f;
  74437. float radiusY = height * 0.5f;
  74438. const Point<float> centre (x + radiusX, y + radiusY);
  74439. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74440. addArc (x, y, width, height, fromRadians, toRadians);
  74441. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74442. {
  74443. closeSubPath();
  74444. if (innerCircleProportionalSize > 0)
  74445. {
  74446. radiusX *= innerCircleProportionalSize;
  74447. radiusY *= innerCircleProportionalSize;
  74448. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74449. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74450. }
  74451. }
  74452. else
  74453. {
  74454. if (innerCircleProportionalSize > 0)
  74455. {
  74456. radiusX *= innerCircleProportionalSize;
  74457. radiusY *= innerCircleProportionalSize;
  74458. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74459. }
  74460. else
  74461. {
  74462. lineTo (centre);
  74463. }
  74464. }
  74465. closeSubPath();
  74466. }
  74467. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74468. {
  74469. const Line<float> reversed (line.reversed());
  74470. lineThickness *= 0.5f;
  74471. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74472. lineTo (line.getPointAlongLine (0, -lineThickness));
  74473. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74474. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74475. closeSubPath();
  74476. }
  74477. void Path::addArrow (const Line<float>& line, float lineThickness,
  74478. float arrowheadWidth, float arrowheadLength)
  74479. {
  74480. const Line<float> reversed (line.reversed());
  74481. lineThickness *= 0.5f;
  74482. arrowheadWidth *= 0.5f;
  74483. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74484. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74485. lineTo (line.getPointAlongLine (0, -lineThickness));
  74486. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74487. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74488. lineTo (line.getEnd());
  74489. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74490. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74491. closeSubPath();
  74492. }
  74493. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74494. const float radius, const float startAngle)
  74495. {
  74496. jassert (numberOfSides > 1); // this would be silly.
  74497. if (numberOfSides > 1)
  74498. {
  74499. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74500. for (int i = 0; i < numberOfSides; ++i)
  74501. {
  74502. const float angle = startAngle + i * angleBetweenPoints;
  74503. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74504. if (i == 0)
  74505. startNewSubPath (p);
  74506. else
  74507. lineTo (p);
  74508. }
  74509. closeSubPath();
  74510. }
  74511. }
  74512. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74513. const float innerRadius, const float outerRadius, const float startAngle)
  74514. {
  74515. jassert (numberOfPoints > 1); // this would be silly.
  74516. if (numberOfPoints > 1)
  74517. {
  74518. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74519. for (int i = 0; i < numberOfPoints; ++i)
  74520. {
  74521. const float angle = startAngle + i * angleBetweenPoints;
  74522. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74523. if (i == 0)
  74524. startNewSubPath (p);
  74525. else
  74526. lineTo (p);
  74527. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74528. }
  74529. closeSubPath();
  74530. }
  74531. }
  74532. void Path::addBubble (float x, float y,
  74533. float w, float h,
  74534. float cs,
  74535. float tipX,
  74536. float tipY,
  74537. int whichSide,
  74538. float arrowPos,
  74539. float arrowWidth)
  74540. {
  74541. if (w > 1.0f && h > 1.0f)
  74542. {
  74543. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74544. const float cs2 = 2.0f * cs;
  74545. startNewSubPath (x + cs, y);
  74546. if (whichSide == 0)
  74547. {
  74548. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74549. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74550. lineTo (arrowX1, y);
  74551. lineTo (tipX, tipY);
  74552. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74553. }
  74554. lineTo (x + w - cs, y);
  74555. if (cs > 0.0f)
  74556. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74557. if (whichSide == 3)
  74558. {
  74559. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74560. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74561. lineTo (x + w, arrowY1);
  74562. lineTo (tipX, tipY);
  74563. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74564. }
  74565. lineTo (x + w, y + h - cs);
  74566. if (cs > 0.0f)
  74567. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74568. if (whichSide == 2)
  74569. {
  74570. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74571. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74572. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74573. lineTo (tipX, tipY);
  74574. lineTo (arrowX1, y + h);
  74575. }
  74576. lineTo (x + cs, y + h);
  74577. if (cs > 0.0f)
  74578. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74579. if (whichSide == 1)
  74580. {
  74581. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74582. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74583. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74584. lineTo (tipX, tipY);
  74585. lineTo (x, arrowY1);
  74586. }
  74587. lineTo (x, y + cs);
  74588. if (cs > 0.0f)
  74589. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74590. closeSubPath();
  74591. }
  74592. }
  74593. void Path::addPath (const Path& other)
  74594. {
  74595. size_t i = 0;
  74596. while (i < other.numElements)
  74597. {
  74598. const float type = other.data.elements [i++];
  74599. if (type == moveMarker)
  74600. {
  74601. startNewSubPath (other.data.elements [i],
  74602. other.data.elements [i + 1]);
  74603. i += 2;
  74604. }
  74605. else if (type == lineMarker)
  74606. {
  74607. lineTo (other.data.elements [i],
  74608. other.data.elements [i + 1]);
  74609. i += 2;
  74610. }
  74611. else if (type == quadMarker)
  74612. {
  74613. quadraticTo (other.data.elements [i],
  74614. other.data.elements [i + 1],
  74615. other.data.elements [i + 2],
  74616. other.data.elements [i + 3]);
  74617. i += 4;
  74618. }
  74619. else if (type == cubicMarker)
  74620. {
  74621. cubicTo (other.data.elements [i],
  74622. other.data.elements [i + 1],
  74623. other.data.elements [i + 2],
  74624. other.data.elements [i + 3],
  74625. other.data.elements [i + 4],
  74626. other.data.elements [i + 5]);
  74627. i += 6;
  74628. }
  74629. else if (type == closeSubPathMarker)
  74630. {
  74631. closeSubPath();
  74632. }
  74633. else
  74634. {
  74635. // something's gone wrong with the element list!
  74636. jassertfalse;
  74637. }
  74638. }
  74639. }
  74640. void Path::addPath (const Path& other,
  74641. const AffineTransform& transformToApply)
  74642. {
  74643. size_t i = 0;
  74644. while (i < other.numElements)
  74645. {
  74646. const float type = other.data.elements [i++];
  74647. if (type == closeSubPathMarker)
  74648. {
  74649. closeSubPath();
  74650. }
  74651. else
  74652. {
  74653. float x = other.data.elements [i++];
  74654. float y = other.data.elements [i++];
  74655. transformToApply.transformPoint (x, y);
  74656. if (type == moveMarker)
  74657. {
  74658. startNewSubPath (x, y);
  74659. }
  74660. else if (type == lineMarker)
  74661. {
  74662. lineTo (x, y);
  74663. }
  74664. else if (type == quadMarker)
  74665. {
  74666. float x2 = other.data.elements [i++];
  74667. float y2 = other.data.elements [i++];
  74668. transformToApply.transformPoint (x2, y2);
  74669. quadraticTo (x, y, x2, y2);
  74670. }
  74671. else if (type == cubicMarker)
  74672. {
  74673. float x2 = other.data.elements [i++];
  74674. float y2 = other.data.elements [i++];
  74675. float x3 = other.data.elements [i++];
  74676. float y3 = other.data.elements [i++];
  74677. transformToApply.transformPoints (x2, y2, x3, y3);
  74678. cubicTo (x, y, x2, y2, x3, y3);
  74679. }
  74680. else
  74681. {
  74682. // something's gone wrong with the element list!
  74683. jassertfalse;
  74684. }
  74685. }
  74686. }
  74687. }
  74688. void Path::applyTransform (const AffineTransform& transform) throw()
  74689. {
  74690. size_t i = 0;
  74691. pathYMin = pathXMin = 0;
  74692. pathYMax = pathXMax = 0;
  74693. bool setMaxMin = false;
  74694. while (i < numElements)
  74695. {
  74696. const float type = data.elements [i++];
  74697. if (type == moveMarker)
  74698. {
  74699. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74700. if (setMaxMin)
  74701. {
  74702. pathXMin = jmin (pathXMin, data.elements [i]);
  74703. pathXMax = jmax (pathXMax, data.elements [i]);
  74704. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74705. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74706. }
  74707. else
  74708. {
  74709. pathXMin = pathXMax = data.elements [i];
  74710. pathYMin = pathYMax = data.elements [i + 1];
  74711. setMaxMin = true;
  74712. }
  74713. i += 2;
  74714. }
  74715. else if (type == lineMarker)
  74716. {
  74717. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74718. pathXMin = jmin (pathXMin, data.elements [i]);
  74719. pathXMax = jmax (pathXMax, data.elements [i]);
  74720. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74721. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74722. i += 2;
  74723. }
  74724. else if (type == quadMarker)
  74725. {
  74726. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74727. data.elements [i + 2], data.elements [i + 3]);
  74728. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74729. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74730. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74731. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74732. i += 4;
  74733. }
  74734. else if (type == cubicMarker)
  74735. {
  74736. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74737. data.elements [i + 2], data.elements [i + 3],
  74738. data.elements [i + 4], data.elements [i + 5]);
  74739. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74740. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74741. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74742. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74743. i += 6;
  74744. }
  74745. }
  74746. }
  74747. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74748. const float w, const float h,
  74749. const bool preserveProportions,
  74750. const Justification& justification) const
  74751. {
  74752. Rectangle<float> bounds (getBounds());
  74753. if (preserveProportions)
  74754. {
  74755. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74756. return AffineTransform::identity;
  74757. float newW, newH;
  74758. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74759. if (srcRatio > h / w)
  74760. {
  74761. newW = h / srcRatio;
  74762. newH = h;
  74763. }
  74764. else
  74765. {
  74766. newW = w;
  74767. newH = w * srcRatio;
  74768. }
  74769. float newXCentre = x;
  74770. float newYCentre = y;
  74771. if (justification.testFlags (Justification::left))
  74772. newXCentre += newW * 0.5f;
  74773. else if (justification.testFlags (Justification::right))
  74774. newXCentre += w - newW * 0.5f;
  74775. else
  74776. newXCentre += w * 0.5f;
  74777. if (justification.testFlags (Justification::top))
  74778. newYCentre += newH * 0.5f;
  74779. else if (justification.testFlags (Justification::bottom))
  74780. newYCentre += h - newH * 0.5f;
  74781. else
  74782. newYCentre += h * 0.5f;
  74783. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74784. bounds.getHeight() * -0.5f - bounds.getY())
  74785. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74786. .translated (newXCentre, newYCentre);
  74787. }
  74788. else
  74789. {
  74790. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74791. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74792. .translated (x, y);
  74793. }
  74794. }
  74795. bool Path::contains (const float x, const float y, const float tolerance) const
  74796. {
  74797. if (x <= pathXMin || x >= pathXMax
  74798. || y <= pathYMin || y >= pathYMax)
  74799. return false;
  74800. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74801. int positiveCrossings = 0;
  74802. int negativeCrossings = 0;
  74803. while (i.next())
  74804. {
  74805. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74806. {
  74807. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74808. if (intersectX <= x)
  74809. {
  74810. if (i.y1 < i.y2)
  74811. ++positiveCrossings;
  74812. else
  74813. ++negativeCrossings;
  74814. }
  74815. }
  74816. }
  74817. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74818. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74819. }
  74820. bool Path::contains (const Point<float>& point, const float tolerance) const
  74821. {
  74822. return contains (point.getX(), point.getY(), tolerance);
  74823. }
  74824. bool Path::intersectsLine (const Line<float>& line, const float tolerance)
  74825. {
  74826. PathFlatteningIterator i (*this, AffineTransform::identity, tolerance);
  74827. Point<float> intersection;
  74828. while (i.next())
  74829. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74830. return true;
  74831. return false;
  74832. }
  74833. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74834. {
  74835. Line<float> result (line);
  74836. const bool startInside = contains (line.getStart());
  74837. const bool endInside = contains (line.getEnd());
  74838. if (startInside == endInside)
  74839. {
  74840. if (keepSectionOutsidePath == startInside)
  74841. result = Line<float>();
  74842. }
  74843. else
  74844. {
  74845. PathFlatteningIterator i (*this, AffineTransform::identity);
  74846. Point<float> intersection;
  74847. while (i.next())
  74848. {
  74849. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74850. {
  74851. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74852. result.setStart (intersection);
  74853. else
  74854. result.setEnd (intersection);
  74855. }
  74856. }
  74857. }
  74858. return result;
  74859. }
  74860. float Path::getLength (const AffineTransform& transform) const
  74861. {
  74862. float length = 0;
  74863. PathFlatteningIterator i (*this, transform);
  74864. while (i.next())
  74865. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74866. return length;
  74867. }
  74868. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74869. {
  74870. PathFlatteningIterator i (*this, transform);
  74871. while (i.next())
  74872. {
  74873. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74874. const float lineLength = line.getLength();
  74875. if (distanceFromStart <= lineLength)
  74876. return line.getPointAlongLine (distanceFromStart);
  74877. distanceFromStart -= lineLength;
  74878. }
  74879. return Point<float> (i.x2, i.y2);
  74880. }
  74881. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74882. const AffineTransform& transform) const
  74883. {
  74884. PathFlatteningIterator i (*this, transform);
  74885. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74886. float length = 0;
  74887. Point<float> pointOnLine;
  74888. while (i.next())
  74889. {
  74890. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74891. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74892. if (distance < bestDistance)
  74893. {
  74894. bestDistance = distance;
  74895. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74896. pointOnPath = pointOnLine;
  74897. }
  74898. length += line.getLength();
  74899. }
  74900. return bestPosition;
  74901. }
  74902. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74903. {
  74904. if (cornerRadius <= 0.01f)
  74905. return *this;
  74906. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74907. size_t n = 0;
  74908. bool lastWasLine = false, firstWasLine = false;
  74909. Path p;
  74910. while (n < numElements)
  74911. {
  74912. const float type = data.elements [n++];
  74913. if (type == moveMarker)
  74914. {
  74915. indexOfPathStart = p.numElements;
  74916. indexOfPathStartThis = n - 1;
  74917. const float x = data.elements [n++];
  74918. const float y = data.elements [n++];
  74919. p.startNewSubPath (x, y);
  74920. lastWasLine = false;
  74921. firstWasLine = (data.elements [n] == lineMarker);
  74922. }
  74923. else if (type == lineMarker || type == closeSubPathMarker)
  74924. {
  74925. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74926. if (type == lineMarker)
  74927. {
  74928. endX = data.elements [n++];
  74929. endY = data.elements [n++];
  74930. if (n > 8)
  74931. {
  74932. startX = data.elements [n - 8];
  74933. startY = data.elements [n - 7];
  74934. joinX = data.elements [n - 5];
  74935. joinY = data.elements [n - 4];
  74936. }
  74937. }
  74938. else
  74939. {
  74940. endX = data.elements [indexOfPathStartThis + 1];
  74941. endY = data.elements [indexOfPathStartThis + 2];
  74942. if (n > 6)
  74943. {
  74944. startX = data.elements [n - 6];
  74945. startY = data.elements [n - 5];
  74946. joinX = data.elements [n - 3];
  74947. joinY = data.elements [n - 2];
  74948. }
  74949. }
  74950. if (lastWasLine)
  74951. {
  74952. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74953. if (len1 > 0)
  74954. {
  74955. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74956. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74957. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74958. }
  74959. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74960. if (len2 > 0)
  74961. {
  74962. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74963. p.quadraticTo (joinX, joinY,
  74964. (float) (joinX + (endX - joinX) * propNeeded),
  74965. (float) (joinY + (endY - joinY) * propNeeded));
  74966. }
  74967. p.lineTo (endX, endY);
  74968. }
  74969. else if (type == lineMarker)
  74970. {
  74971. p.lineTo (endX, endY);
  74972. lastWasLine = true;
  74973. }
  74974. if (type == closeSubPathMarker)
  74975. {
  74976. if (firstWasLine)
  74977. {
  74978. startX = data.elements [n - 3];
  74979. startY = data.elements [n - 2];
  74980. joinX = endX;
  74981. joinY = endY;
  74982. endX = data.elements [indexOfPathStartThis + 4];
  74983. endY = data.elements [indexOfPathStartThis + 5];
  74984. const double len1 = PathHelpers::lengthOf (startX, startY, joinX, joinY);
  74985. if (len1 > 0)
  74986. {
  74987. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74988. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74989. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74990. }
  74991. const double len2 = PathHelpers::lengthOf (endX, endY, joinX, joinY);
  74992. if (len2 > 0)
  74993. {
  74994. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74995. endX = (float) (joinX + (endX - joinX) * propNeeded);
  74996. endY = (float) (joinY + (endY - joinY) * propNeeded);
  74997. p.quadraticTo (joinX, joinY, endX, endY);
  74998. p.data.elements [indexOfPathStart + 1] = endX;
  74999. p.data.elements [indexOfPathStart + 2] = endY;
  75000. }
  75001. }
  75002. p.closeSubPath();
  75003. }
  75004. }
  75005. else if (type == quadMarker)
  75006. {
  75007. lastWasLine = false;
  75008. const float x1 = data.elements [n++];
  75009. const float y1 = data.elements [n++];
  75010. const float x2 = data.elements [n++];
  75011. const float y2 = data.elements [n++];
  75012. p.quadraticTo (x1, y1, x2, y2);
  75013. }
  75014. else if (type == cubicMarker)
  75015. {
  75016. lastWasLine = false;
  75017. const float x1 = data.elements [n++];
  75018. const float y1 = data.elements [n++];
  75019. const float x2 = data.elements [n++];
  75020. const float y2 = data.elements [n++];
  75021. const float x3 = data.elements [n++];
  75022. const float y3 = data.elements [n++];
  75023. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75024. }
  75025. }
  75026. return p;
  75027. }
  75028. void Path::loadPathFromStream (InputStream& source)
  75029. {
  75030. while (! source.isExhausted())
  75031. {
  75032. switch (source.readByte())
  75033. {
  75034. case 'm':
  75035. {
  75036. const float x = source.readFloat();
  75037. const float y = source.readFloat();
  75038. startNewSubPath (x, y);
  75039. break;
  75040. }
  75041. case 'l':
  75042. {
  75043. const float x = source.readFloat();
  75044. const float y = source.readFloat();
  75045. lineTo (x, y);
  75046. break;
  75047. }
  75048. case 'q':
  75049. {
  75050. const float x1 = source.readFloat();
  75051. const float y1 = source.readFloat();
  75052. const float x2 = source.readFloat();
  75053. const float y2 = source.readFloat();
  75054. quadraticTo (x1, y1, x2, y2);
  75055. break;
  75056. }
  75057. case 'b':
  75058. {
  75059. const float x1 = source.readFloat();
  75060. const float y1 = source.readFloat();
  75061. const float x2 = source.readFloat();
  75062. const float y2 = source.readFloat();
  75063. const float x3 = source.readFloat();
  75064. const float y3 = source.readFloat();
  75065. cubicTo (x1, y1, x2, y2, x3, y3);
  75066. break;
  75067. }
  75068. case 'c':
  75069. closeSubPath();
  75070. break;
  75071. case 'n':
  75072. useNonZeroWinding = true;
  75073. break;
  75074. case 'z':
  75075. useNonZeroWinding = false;
  75076. break;
  75077. case 'e':
  75078. return; // end of path marker
  75079. default:
  75080. jassertfalse; // illegal char in the stream
  75081. break;
  75082. }
  75083. }
  75084. }
  75085. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75086. {
  75087. MemoryInputStream in (pathData, numberOfBytes, false);
  75088. loadPathFromStream (in);
  75089. }
  75090. void Path::writePathToStream (OutputStream& dest) const
  75091. {
  75092. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75093. size_t i = 0;
  75094. while (i < numElements)
  75095. {
  75096. const float type = data.elements [i++];
  75097. if (type == moveMarker)
  75098. {
  75099. dest.writeByte ('m');
  75100. dest.writeFloat (data.elements [i++]);
  75101. dest.writeFloat (data.elements [i++]);
  75102. }
  75103. else if (type == lineMarker)
  75104. {
  75105. dest.writeByte ('l');
  75106. dest.writeFloat (data.elements [i++]);
  75107. dest.writeFloat (data.elements [i++]);
  75108. }
  75109. else if (type == quadMarker)
  75110. {
  75111. dest.writeByte ('q');
  75112. dest.writeFloat (data.elements [i++]);
  75113. dest.writeFloat (data.elements [i++]);
  75114. dest.writeFloat (data.elements [i++]);
  75115. dest.writeFloat (data.elements [i++]);
  75116. }
  75117. else if (type == cubicMarker)
  75118. {
  75119. dest.writeByte ('b');
  75120. dest.writeFloat (data.elements [i++]);
  75121. dest.writeFloat (data.elements [i++]);
  75122. dest.writeFloat (data.elements [i++]);
  75123. dest.writeFloat (data.elements [i++]);
  75124. dest.writeFloat (data.elements [i++]);
  75125. dest.writeFloat (data.elements [i++]);
  75126. }
  75127. else if (type == closeSubPathMarker)
  75128. {
  75129. dest.writeByte ('c');
  75130. }
  75131. }
  75132. dest.writeByte ('e'); // marks the end-of-path
  75133. }
  75134. const String Path::toString() const
  75135. {
  75136. MemoryOutputStream s (2048);
  75137. if (! useNonZeroWinding)
  75138. s << 'a';
  75139. size_t i = 0;
  75140. float lastMarker = 0.0f;
  75141. while (i < numElements)
  75142. {
  75143. const float marker = data.elements [i++];
  75144. char markerChar = 0;
  75145. int numCoords = 0;
  75146. if (marker == moveMarker)
  75147. {
  75148. markerChar = 'm';
  75149. numCoords = 2;
  75150. }
  75151. else if (marker == lineMarker)
  75152. {
  75153. markerChar = 'l';
  75154. numCoords = 2;
  75155. }
  75156. else if (marker == quadMarker)
  75157. {
  75158. markerChar = 'q';
  75159. numCoords = 4;
  75160. }
  75161. else if (marker == cubicMarker)
  75162. {
  75163. markerChar = 'c';
  75164. numCoords = 6;
  75165. }
  75166. else
  75167. {
  75168. jassert (marker == closeSubPathMarker);
  75169. markerChar = 'z';
  75170. }
  75171. if (marker != lastMarker)
  75172. {
  75173. if (s.getDataSize() != 0)
  75174. s << ' ';
  75175. s << markerChar;
  75176. lastMarker = marker;
  75177. }
  75178. while (--numCoords >= 0 && i < numElements)
  75179. {
  75180. String coord (data.elements [i++], 3);
  75181. while (coord.endsWithChar ('0') && coord != "0")
  75182. coord = coord.dropLastCharacters (1);
  75183. if (coord.endsWithChar ('.'))
  75184. coord = coord.dropLastCharacters (1);
  75185. if (s.getDataSize() != 0)
  75186. s << ' ';
  75187. s << coord;
  75188. }
  75189. }
  75190. return s.toUTF8();
  75191. }
  75192. void Path::restoreFromString (const String& stringVersion)
  75193. {
  75194. clear();
  75195. setUsingNonZeroWinding (true);
  75196. String::CharPointerType t (stringVersion.getCharPointer());
  75197. juce_wchar marker = 'm';
  75198. int numValues = 2;
  75199. float values [6];
  75200. for (;;)
  75201. {
  75202. const String token (PathHelpers::nextToken (t));
  75203. const juce_wchar firstChar = token[0];
  75204. int startNum = 0;
  75205. if (firstChar == 0)
  75206. break;
  75207. if (firstChar == 'm' || firstChar == 'l')
  75208. {
  75209. marker = firstChar;
  75210. numValues = 2;
  75211. }
  75212. else if (firstChar == 'q')
  75213. {
  75214. marker = firstChar;
  75215. numValues = 4;
  75216. }
  75217. else if (firstChar == 'c')
  75218. {
  75219. marker = firstChar;
  75220. numValues = 6;
  75221. }
  75222. else if (firstChar == 'z')
  75223. {
  75224. marker = firstChar;
  75225. numValues = 0;
  75226. }
  75227. else if (firstChar == 'a')
  75228. {
  75229. setUsingNonZeroWinding (false);
  75230. continue;
  75231. }
  75232. else
  75233. {
  75234. ++startNum;
  75235. values [0] = token.getFloatValue();
  75236. }
  75237. for (int i = startNum; i < numValues; ++i)
  75238. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75239. switch (marker)
  75240. {
  75241. case 'm': startNewSubPath (values[0], values[1]); break;
  75242. case 'l': lineTo (values[0], values[1]); break;
  75243. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75244. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75245. case 'z': closeSubPath(); break;
  75246. default: jassertfalse; break; // illegal string format?
  75247. }
  75248. }
  75249. }
  75250. Path::Iterator::Iterator (const Path& path_)
  75251. : path (path_),
  75252. index (0)
  75253. {
  75254. }
  75255. Path::Iterator::~Iterator()
  75256. {
  75257. }
  75258. bool Path::Iterator::next()
  75259. {
  75260. const float* const elements = path.data.elements;
  75261. if (index < path.numElements)
  75262. {
  75263. const float type = elements [index++];
  75264. if (type == moveMarker)
  75265. {
  75266. elementType = startNewSubPath;
  75267. x1 = elements [index++];
  75268. y1 = elements [index++];
  75269. }
  75270. else if (type == lineMarker)
  75271. {
  75272. elementType = lineTo;
  75273. x1 = elements [index++];
  75274. y1 = elements [index++];
  75275. }
  75276. else if (type == quadMarker)
  75277. {
  75278. elementType = quadraticTo;
  75279. x1 = elements [index++];
  75280. y1 = elements [index++];
  75281. x2 = elements [index++];
  75282. y2 = elements [index++];
  75283. }
  75284. else if (type == cubicMarker)
  75285. {
  75286. elementType = cubicTo;
  75287. x1 = elements [index++];
  75288. y1 = elements [index++];
  75289. x2 = elements [index++];
  75290. y2 = elements [index++];
  75291. x3 = elements [index++];
  75292. y3 = elements [index++];
  75293. }
  75294. else if (type == closeSubPathMarker)
  75295. {
  75296. elementType = closePath;
  75297. }
  75298. return true;
  75299. }
  75300. return false;
  75301. }
  75302. END_JUCE_NAMESPACE
  75303. /*** End of inlined file: juce_Path.cpp ***/
  75304. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75305. BEGIN_JUCE_NAMESPACE
  75306. #if JUCE_MSVC && JUCE_DEBUG
  75307. #pragma optimize ("t", on)
  75308. #endif
  75309. const float PathFlatteningIterator::defaultTolerance = 0.6f;
  75310. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75311. const AffineTransform& transform_,
  75312. const float tolerance)
  75313. : x2 (0),
  75314. y2 (0),
  75315. closesSubPath (false),
  75316. subPathIndex (-1),
  75317. path (path_),
  75318. transform (transform_),
  75319. points (path_.data.elements),
  75320. toleranceSquared (tolerance * tolerance),
  75321. subPathCloseX (0),
  75322. subPathCloseY (0),
  75323. isIdentityTransform (transform_.isIdentity()),
  75324. stackBase (32),
  75325. index (0),
  75326. stackSize (32)
  75327. {
  75328. stackPos = stackBase;
  75329. }
  75330. PathFlatteningIterator::~PathFlatteningIterator()
  75331. {
  75332. }
  75333. bool PathFlatteningIterator::next()
  75334. {
  75335. x1 = x2;
  75336. y1 = y2;
  75337. float x3 = 0;
  75338. float y3 = 0;
  75339. float x4 = 0;
  75340. float y4 = 0;
  75341. float type;
  75342. for (;;)
  75343. {
  75344. if (stackPos == stackBase)
  75345. {
  75346. if (index >= path.numElements)
  75347. {
  75348. return false;
  75349. }
  75350. else
  75351. {
  75352. type = points [index++];
  75353. if (type != Path::closeSubPathMarker)
  75354. {
  75355. x2 = points [index++];
  75356. y2 = points [index++];
  75357. if (type == Path::quadMarker)
  75358. {
  75359. x3 = points [index++];
  75360. y3 = points [index++];
  75361. if (! isIdentityTransform)
  75362. transform.transformPoints (x2, y2, x3, y3);
  75363. }
  75364. else if (type == Path::cubicMarker)
  75365. {
  75366. x3 = points [index++];
  75367. y3 = points [index++];
  75368. x4 = points [index++];
  75369. y4 = points [index++];
  75370. if (! isIdentityTransform)
  75371. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75372. }
  75373. else
  75374. {
  75375. if (! isIdentityTransform)
  75376. transform.transformPoint (x2, y2);
  75377. }
  75378. }
  75379. }
  75380. }
  75381. else
  75382. {
  75383. type = *--stackPos;
  75384. if (type != Path::closeSubPathMarker)
  75385. {
  75386. x2 = *--stackPos;
  75387. y2 = *--stackPos;
  75388. if (type == Path::quadMarker)
  75389. {
  75390. x3 = *--stackPos;
  75391. y3 = *--stackPos;
  75392. }
  75393. else if (type == Path::cubicMarker)
  75394. {
  75395. x3 = *--stackPos;
  75396. y3 = *--stackPos;
  75397. x4 = *--stackPos;
  75398. y4 = *--stackPos;
  75399. }
  75400. }
  75401. }
  75402. if (type == Path::lineMarker)
  75403. {
  75404. ++subPathIndex;
  75405. closesSubPath = (stackPos == stackBase)
  75406. && (index < path.numElements)
  75407. && (points [index] == Path::closeSubPathMarker)
  75408. && x2 == subPathCloseX
  75409. && y2 == subPathCloseY;
  75410. return true;
  75411. }
  75412. else if (type == Path::quadMarker)
  75413. {
  75414. const size_t offset = (size_t) (stackPos - stackBase);
  75415. if (offset >= stackSize - 10)
  75416. {
  75417. stackSize <<= 1;
  75418. stackBase.realloc (stackSize);
  75419. stackPos = stackBase + offset;
  75420. }
  75421. const float m1x = (x1 + x2) * 0.5f;
  75422. const float m1y = (y1 + y2) * 0.5f;
  75423. const float m2x = (x2 + x3) * 0.5f;
  75424. const float m2y = (y2 + y3) * 0.5f;
  75425. const float m3x = (m1x + m2x) * 0.5f;
  75426. const float m3y = (m1y + m2y) * 0.5f;
  75427. const float errorX = m3x - x2;
  75428. const float errorY = m3y - y2;
  75429. if (errorX * errorX + errorY * errorY > toleranceSquared)
  75430. {
  75431. *stackPos++ = y3;
  75432. *stackPos++ = x3;
  75433. *stackPos++ = m2y;
  75434. *stackPos++ = m2x;
  75435. *stackPos++ = Path::quadMarker;
  75436. *stackPos++ = m3y;
  75437. *stackPos++ = m3x;
  75438. *stackPos++ = m1y;
  75439. *stackPos++ = m1x;
  75440. *stackPos++ = Path::quadMarker;
  75441. }
  75442. else
  75443. {
  75444. *stackPos++ = y3;
  75445. *stackPos++ = x3;
  75446. *stackPos++ = Path::lineMarker;
  75447. *stackPos++ = m3y;
  75448. *stackPos++ = m3x;
  75449. *stackPos++ = Path::lineMarker;
  75450. }
  75451. jassert (stackPos < stackBase + stackSize);
  75452. }
  75453. else if (type == Path::cubicMarker)
  75454. {
  75455. const size_t offset = (size_t) (stackPos - stackBase);
  75456. if (offset >= stackSize - 16)
  75457. {
  75458. stackSize <<= 1;
  75459. stackBase.realloc (stackSize);
  75460. stackPos = stackBase + offset;
  75461. }
  75462. const float m1x = (x1 + x2) * 0.5f;
  75463. const float m1y = (y1 + y2) * 0.5f;
  75464. const float m2x = (x3 + x2) * 0.5f;
  75465. const float m2y = (y3 + y2) * 0.5f;
  75466. const float m3x = (x3 + x4) * 0.5f;
  75467. const float m3y = (y3 + y4) * 0.5f;
  75468. const float m4x = (m1x + m2x) * 0.5f;
  75469. const float m4y = (m1y + m2y) * 0.5f;
  75470. const float m5x = (m3x + m2x) * 0.5f;
  75471. const float m5y = (m3y + m2y) * 0.5f;
  75472. const float error1X = m4x - x2;
  75473. const float error1Y = m4y - y2;
  75474. const float error2X = m5x - x3;
  75475. const float error2Y = m5y - y3;
  75476. if (error1X * error1X + error1Y * error1Y > toleranceSquared
  75477. || error2X * error2X + error2Y * error2Y > toleranceSquared)
  75478. {
  75479. *stackPos++ = y4;
  75480. *stackPos++ = x4;
  75481. *stackPos++ = m3y;
  75482. *stackPos++ = m3x;
  75483. *stackPos++ = m5y;
  75484. *stackPos++ = m5x;
  75485. *stackPos++ = Path::cubicMarker;
  75486. *stackPos++ = (m4y + m5y) * 0.5f;
  75487. *stackPos++ = (m4x + m5x) * 0.5f;
  75488. *stackPos++ = m4y;
  75489. *stackPos++ = m4x;
  75490. *stackPos++ = m1y;
  75491. *stackPos++ = m1x;
  75492. *stackPos++ = Path::cubicMarker;
  75493. }
  75494. else
  75495. {
  75496. *stackPos++ = y4;
  75497. *stackPos++ = x4;
  75498. *stackPos++ = Path::lineMarker;
  75499. *stackPos++ = m5y;
  75500. *stackPos++ = m5x;
  75501. *stackPos++ = Path::lineMarker;
  75502. *stackPos++ = m4y;
  75503. *stackPos++ = m4x;
  75504. *stackPos++ = Path::lineMarker;
  75505. }
  75506. }
  75507. else if (type == Path::closeSubPathMarker)
  75508. {
  75509. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75510. {
  75511. x1 = x2;
  75512. y1 = y2;
  75513. x2 = subPathCloseX;
  75514. y2 = subPathCloseY;
  75515. closesSubPath = true;
  75516. return true;
  75517. }
  75518. }
  75519. else
  75520. {
  75521. jassert (type == Path::moveMarker);
  75522. subPathIndex = -1;
  75523. subPathCloseX = x1 = x2;
  75524. subPathCloseY = y1 = y2;
  75525. }
  75526. }
  75527. }
  75528. #if JUCE_MSVC && JUCE_DEBUG
  75529. #pragma optimize ("", on) // resets optimisations to the project defaults
  75530. #endif
  75531. END_JUCE_NAMESPACE
  75532. /*** End of inlined file: juce_PathIterator.cpp ***/
  75533. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75534. BEGIN_JUCE_NAMESPACE
  75535. PathStrokeType::PathStrokeType (const float strokeThickness,
  75536. const JointStyle jointStyle_,
  75537. const EndCapStyle endStyle_) throw()
  75538. : thickness (strokeThickness),
  75539. jointStyle (jointStyle_),
  75540. endStyle (endStyle_)
  75541. {
  75542. }
  75543. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75544. : thickness (other.thickness),
  75545. jointStyle (other.jointStyle),
  75546. endStyle (other.endStyle)
  75547. {
  75548. }
  75549. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75550. {
  75551. thickness = other.thickness;
  75552. jointStyle = other.jointStyle;
  75553. endStyle = other.endStyle;
  75554. return *this;
  75555. }
  75556. PathStrokeType::~PathStrokeType() throw()
  75557. {
  75558. }
  75559. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75560. {
  75561. return thickness == other.thickness
  75562. && jointStyle == other.jointStyle
  75563. && endStyle == other.endStyle;
  75564. }
  75565. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75566. {
  75567. return ! operator== (other);
  75568. }
  75569. namespace PathStrokeHelpers
  75570. {
  75571. bool lineIntersection (const float x1, const float y1,
  75572. const float x2, const float y2,
  75573. const float x3, const float y3,
  75574. const float x4, const float y4,
  75575. float& intersectionX,
  75576. float& intersectionY,
  75577. float& distanceBeyondLine1EndSquared) throw()
  75578. {
  75579. if (x2 != x3 || y2 != y3)
  75580. {
  75581. const float dx1 = x2 - x1;
  75582. const float dy1 = y2 - y1;
  75583. const float dx2 = x4 - x3;
  75584. const float dy2 = y4 - y3;
  75585. const float divisor = dx1 * dy2 - dx2 * dy1;
  75586. if (divisor == 0)
  75587. {
  75588. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75589. {
  75590. if (dy1 == 0 && dy2 != 0)
  75591. {
  75592. const float along = (y1 - y3) / dy2;
  75593. intersectionX = x3 + along * dx2;
  75594. intersectionY = y1;
  75595. distanceBeyondLine1EndSquared = intersectionX - x2;
  75596. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75597. if ((x2 > x1) == (intersectionX < x2))
  75598. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75599. return along >= 0 && along <= 1.0f;
  75600. }
  75601. else if (dy2 == 0 && dy1 != 0)
  75602. {
  75603. const float along = (y3 - y1) / dy1;
  75604. intersectionX = x1 + along * dx1;
  75605. intersectionY = y3;
  75606. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75607. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75608. if (along < 1.0f)
  75609. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75610. return along >= 0 && along <= 1.0f;
  75611. }
  75612. else if (dx1 == 0 && dx2 != 0)
  75613. {
  75614. const float along = (x1 - x3) / dx2;
  75615. intersectionX = x1;
  75616. intersectionY = y3 + along * dy2;
  75617. distanceBeyondLine1EndSquared = intersectionY - y2;
  75618. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75619. if ((y2 > y1) == (intersectionY < y2))
  75620. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75621. return along >= 0 && along <= 1.0f;
  75622. }
  75623. else if (dx2 == 0 && dx1 != 0)
  75624. {
  75625. const float along = (x3 - x1) / dx1;
  75626. intersectionX = x3;
  75627. intersectionY = y1 + along * dy1;
  75628. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75629. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75630. if (along < 1.0f)
  75631. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75632. return along >= 0 && along <= 1.0f;
  75633. }
  75634. }
  75635. intersectionX = 0.5f * (x2 + x3);
  75636. intersectionY = 0.5f * (y2 + y3);
  75637. distanceBeyondLine1EndSquared = 0.0f;
  75638. return false;
  75639. }
  75640. else
  75641. {
  75642. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75643. intersectionX = x1 + along1 * dx1;
  75644. intersectionY = y1 + along1 * dy1;
  75645. if (along1 >= 0 && along1 <= 1.0f)
  75646. {
  75647. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75648. if (along2 >= 0 && along2 <= divisor)
  75649. {
  75650. distanceBeyondLine1EndSquared = 0.0f;
  75651. return true;
  75652. }
  75653. }
  75654. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75655. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75656. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75657. if (along1 < 1.0f)
  75658. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75659. return false;
  75660. }
  75661. }
  75662. intersectionX = x2;
  75663. intersectionY = y2;
  75664. distanceBeyondLine1EndSquared = 0.0f;
  75665. return true;
  75666. }
  75667. void addEdgeAndJoint (Path& destPath,
  75668. const PathStrokeType::JointStyle style,
  75669. const float maxMiterExtensionSquared, const float width,
  75670. const float x1, const float y1,
  75671. const float x2, const float y2,
  75672. const float x3, const float y3,
  75673. const float x4, const float y4,
  75674. const float midX, const float midY)
  75675. {
  75676. if (style == PathStrokeType::beveled
  75677. || (x3 == x4 && y3 == y4)
  75678. || (x1 == x2 && y1 == y2))
  75679. {
  75680. destPath.lineTo (x2, y2);
  75681. destPath.lineTo (x3, y3);
  75682. }
  75683. else
  75684. {
  75685. float jx, jy, distanceBeyondLine1EndSquared;
  75686. // if they intersect, use this point..
  75687. if (lineIntersection (x1, y1, x2, y2,
  75688. x3, y3, x4, y4,
  75689. jx, jy, distanceBeyondLine1EndSquared))
  75690. {
  75691. destPath.lineTo (jx, jy);
  75692. }
  75693. else
  75694. {
  75695. if (style == PathStrokeType::mitered)
  75696. {
  75697. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75698. && distanceBeyondLine1EndSquared > 0.0f)
  75699. {
  75700. destPath.lineTo (jx, jy);
  75701. }
  75702. else
  75703. {
  75704. // the end sticks out too far, so just use a blunt joint
  75705. destPath.lineTo (x2, y2);
  75706. destPath.lineTo (x3, y3);
  75707. }
  75708. }
  75709. else
  75710. {
  75711. // curved joints
  75712. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75713. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75714. const float angleIncrement = 0.1f;
  75715. destPath.lineTo (x2, y2);
  75716. if (std::abs (angle1 - angle2) > angleIncrement)
  75717. {
  75718. if (angle2 > angle1 + float_Pi
  75719. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75720. {
  75721. if (angle2 > angle1)
  75722. angle2 -= float_Pi * 2.0f;
  75723. jassert (angle1 <= angle2 + float_Pi);
  75724. angle1 -= angleIncrement;
  75725. while (angle1 > angle2)
  75726. {
  75727. destPath.lineTo (midX + width * std::sin (angle1),
  75728. midY + width * std::cos (angle1));
  75729. angle1 -= angleIncrement;
  75730. }
  75731. }
  75732. else
  75733. {
  75734. if (angle1 > angle2)
  75735. angle1 -= float_Pi * 2.0f;
  75736. jassert (angle1 >= angle2 - float_Pi);
  75737. angle1 += angleIncrement;
  75738. while (angle1 < angle2)
  75739. {
  75740. destPath.lineTo (midX + width * std::sin (angle1),
  75741. midY + width * std::cos (angle1));
  75742. angle1 += angleIncrement;
  75743. }
  75744. }
  75745. }
  75746. destPath.lineTo (x3, y3);
  75747. }
  75748. }
  75749. }
  75750. }
  75751. void addLineEnd (Path& destPath,
  75752. const PathStrokeType::EndCapStyle style,
  75753. const float x1, const float y1,
  75754. const float x2, const float y2,
  75755. const float width)
  75756. {
  75757. if (style == PathStrokeType::butt)
  75758. {
  75759. destPath.lineTo (x2, y2);
  75760. }
  75761. else
  75762. {
  75763. float offx1, offy1, offx2, offy2;
  75764. float dx = x2 - x1;
  75765. float dy = y2 - y1;
  75766. const float len = juce_hypot (dx, dy);
  75767. if (len == 0)
  75768. {
  75769. offx1 = offx2 = x1;
  75770. offy1 = offy2 = y1;
  75771. }
  75772. else
  75773. {
  75774. const float offset = width / len;
  75775. dx *= offset;
  75776. dy *= offset;
  75777. offx1 = x1 + dy;
  75778. offy1 = y1 - dx;
  75779. offx2 = x2 + dy;
  75780. offy2 = y2 - dx;
  75781. }
  75782. if (style == PathStrokeType::square)
  75783. {
  75784. // sqaure ends
  75785. destPath.lineTo (offx1, offy1);
  75786. destPath.lineTo (offx2, offy2);
  75787. destPath.lineTo (x2, y2);
  75788. }
  75789. else
  75790. {
  75791. // rounded ends
  75792. const float midx = (offx1 + offx2) * 0.5f;
  75793. const float midy = (offy1 + offy2) * 0.5f;
  75794. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75795. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75796. midx, midy);
  75797. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75798. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75799. x2, y2);
  75800. }
  75801. }
  75802. }
  75803. struct Arrowhead
  75804. {
  75805. float startWidth, startLength;
  75806. float endWidth, endLength;
  75807. };
  75808. void addArrowhead (Path& destPath,
  75809. const float x1, const float y1,
  75810. const float x2, const float y2,
  75811. const float tipX, const float tipY,
  75812. const float width,
  75813. const float arrowheadWidth)
  75814. {
  75815. Line<float> line (x1, y1, x2, y2);
  75816. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75817. destPath.lineTo (tipX, tipY);
  75818. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75819. destPath.lineTo (x2, y2);
  75820. }
  75821. struct LineSection
  75822. {
  75823. float x1, y1, x2, y2; // original line
  75824. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75825. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75826. };
  75827. void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75828. {
  75829. while (amountAtEnd > 0 && subPath.size() > 0)
  75830. {
  75831. LineSection& l = subPath.getReference (subPath.size() - 1);
  75832. float dx = l.rx2 - l.rx1;
  75833. float dy = l.ry2 - l.ry1;
  75834. const float len = juce_hypot (dx, dy);
  75835. if (len <= amountAtEnd && subPath.size() > 1)
  75836. {
  75837. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75838. prev.x2 = l.x2;
  75839. prev.y2 = l.y2;
  75840. subPath.removeLast();
  75841. amountAtEnd -= len;
  75842. }
  75843. else
  75844. {
  75845. const float prop = jmin (0.9999f, amountAtEnd / len);
  75846. dx *= prop;
  75847. dy *= prop;
  75848. l.rx1 += dx;
  75849. l.ry1 += dy;
  75850. l.lx2 += dx;
  75851. l.ly2 += dy;
  75852. break;
  75853. }
  75854. }
  75855. while (amountAtStart > 0 && subPath.size() > 0)
  75856. {
  75857. LineSection& l = subPath.getReference (0);
  75858. float dx = l.rx2 - l.rx1;
  75859. float dy = l.ry2 - l.ry1;
  75860. const float len = juce_hypot (dx, dy);
  75861. if (len <= amountAtStart && subPath.size() > 1)
  75862. {
  75863. LineSection& next = subPath.getReference (1);
  75864. next.x1 = l.x1;
  75865. next.y1 = l.y1;
  75866. subPath.remove (0);
  75867. amountAtStart -= len;
  75868. }
  75869. else
  75870. {
  75871. const float prop = jmin (0.9999f, amountAtStart / len);
  75872. dx *= prop;
  75873. dy *= prop;
  75874. l.rx2 -= dx;
  75875. l.ry2 -= dy;
  75876. l.lx1 -= dx;
  75877. l.ly1 -= dy;
  75878. break;
  75879. }
  75880. }
  75881. }
  75882. void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75883. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75884. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75885. const Arrowhead* const arrowhead)
  75886. {
  75887. jassert (subPath.size() > 0);
  75888. if (arrowhead != 0)
  75889. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75890. const LineSection& firstLine = subPath.getReference (0);
  75891. float lastX1 = firstLine.lx1;
  75892. float lastY1 = firstLine.ly1;
  75893. float lastX2 = firstLine.lx2;
  75894. float lastY2 = firstLine.ly2;
  75895. if (isClosed)
  75896. {
  75897. destPath.startNewSubPath (lastX1, lastY1);
  75898. }
  75899. else
  75900. {
  75901. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75902. if (arrowhead != 0)
  75903. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75904. width, arrowhead->startWidth);
  75905. else
  75906. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75907. }
  75908. int i;
  75909. for (i = 1; i < subPath.size(); ++i)
  75910. {
  75911. const LineSection& l = subPath.getReference (i);
  75912. addEdgeAndJoint (destPath, jointStyle,
  75913. maxMiterExtensionSquared, width,
  75914. lastX1, lastY1, lastX2, lastY2,
  75915. l.lx1, l.ly1, l.lx2, l.ly2,
  75916. l.x1, l.y1);
  75917. lastX1 = l.lx1;
  75918. lastY1 = l.ly1;
  75919. lastX2 = l.lx2;
  75920. lastY2 = l.ly2;
  75921. }
  75922. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75923. if (isClosed)
  75924. {
  75925. const LineSection& l = subPath.getReference (0);
  75926. addEdgeAndJoint (destPath, jointStyle,
  75927. maxMiterExtensionSquared, width,
  75928. lastX1, lastY1, lastX2, lastY2,
  75929. l.lx1, l.ly1, l.lx2, l.ly2,
  75930. l.x1, l.y1);
  75931. destPath.closeSubPath();
  75932. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75933. }
  75934. else
  75935. {
  75936. destPath.lineTo (lastX2, lastY2);
  75937. if (arrowhead != 0)
  75938. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75939. width, arrowhead->endWidth);
  75940. else
  75941. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75942. }
  75943. lastX1 = lastLine.rx1;
  75944. lastY1 = lastLine.ry1;
  75945. lastX2 = lastLine.rx2;
  75946. lastY2 = lastLine.ry2;
  75947. for (i = subPath.size() - 1; --i >= 0;)
  75948. {
  75949. const LineSection& l = subPath.getReference (i);
  75950. addEdgeAndJoint (destPath, jointStyle,
  75951. maxMiterExtensionSquared, width,
  75952. lastX1, lastY1, lastX2, lastY2,
  75953. l.rx1, l.ry1, l.rx2, l.ry2,
  75954. l.x2, l.y2);
  75955. lastX1 = l.rx1;
  75956. lastY1 = l.ry1;
  75957. lastX2 = l.rx2;
  75958. lastY2 = l.ry2;
  75959. }
  75960. if (isClosed)
  75961. {
  75962. addEdgeAndJoint (destPath, jointStyle,
  75963. maxMiterExtensionSquared, width,
  75964. lastX1, lastY1, lastX2, lastY2,
  75965. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75966. lastLine.x2, lastLine.y2);
  75967. }
  75968. else
  75969. {
  75970. // do the last line
  75971. destPath.lineTo (lastX2, lastY2);
  75972. }
  75973. destPath.closeSubPath();
  75974. }
  75975. void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75976. const PathStrokeType::EndCapStyle endStyle,
  75977. Path& destPath, const Path& source,
  75978. const AffineTransform& transform,
  75979. const float extraAccuracy, const Arrowhead* const arrowhead)
  75980. {
  75981. jassert (extraAccuracy > 0);
  75982. if (thickness <= 0)
  75983. {
  75984. destPath.clear();
  75985. return;
  75986. }
  75987. const Path* sourcePath = &source;
  75988. Path temp;
  75989. if (sourcePath == &destPath)
  75990. {
  75991. destPath.swapWithPath (temp);
  75992. sourcePath = &temp;
  75993. }
  75994. else
  75995. {
  75996. destPath.clear();
  75997. }
  75998. destPath.setUsingNonZeroWinding (true);
  75999. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76000. const float width = 0.5f * thickness;
  76001. // Iterate the path, creating a list of the
  76002. // left/right-hand lines along either side of it...
  76003. PathFlatteningIterator it (*sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76004. Array <LineSection> subPath;
  76005. subPath.ensureStorageAllocated (512);
  76006. LineSection l;
  76007. l.x1 = 0;
  76008. l.y1 = 0;
  76009. const float minSegmentLength = 0.0001f;
  76010. while (it.next())
  76011. {
  76012. if (it.subPathIndex == 0)
  76013. {
  76014. if (subPath.size() > 0)
  76015. {
  76016. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76017. subPath.clearQuick();
  76018. }
  76019. l.x1 = it.x1;
  76020. l.y1 = it.y1;
  76021. }
  76022. l.x2 = it.x2;
  76023. l.y2 = it.y2;
  76024. float dx = l.x2 - l.x1;
  76025. float dy = l.y2 - l.y1;
  76026. const float hypotSquared = dx*dx + dy*dy;
  76027. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76028. {
  76029. const float len = std::sqrt (hypotSquared);
  76030. if (len == 0)
  76031. {
  76032. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76033. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76034. }
  76035. else
  76036. {
  76037. const float offset = width / len;
  76038. dx *= offset;
  76039. dy *= offset;
  76040. l.rx2 = l.x1 - dy;
  76041. l.ry2 = l.y1 + dx;
  76042. l.lx1 = l.x1 + dy;
  76043. l.ly1 = l.y1 - dx;
  76044. l.lx2 = l.x2 + dy;
  76045. l.ly2 = l.y2 - dx;
  76046. l.rx1 = l.x2 - dy;
  76047. l.ry1 = l.y2 + dx;
  76048. }
  76049. subPath.add (l);
  76050. if (it.closesSubPath)
  76051. {
  76052. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76053. subPath.clearQuick();
  76054. }
  76055. else
  76056. {
  76057. l.x1 = it.x2;
  76058. l.y1 = it.y2;
  76059. }
  76060. }
  76061. }
  76062. if (subPath.size() > 0)
  76063. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76064. }
  76065. }
  76066. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76067. const AffineTransform& transform, const float extraAccuracy) const
  76068. {
  76069. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76070. transform, extraAccuracy, 0);
  76071. }
  76072. void PathStrokeType::createDashedStroke (Path& destPath,
  76073. const Path& sourcePath,
  76074. const float* dashLengths,
  76075. int numDashLengths,
  76076. const AffineTransform& transform,
  76077. const float extraAccuracy) const
  76078. {
  76079. jassert (extraAccuracy > 0);
  76080. if (thickness <= 0)
  76081. return;
  76082. // this should really be an even number..
  76083. jassert ((numDashLengths & 1) == 0);
  76084. Path newDestPath;
  76085. PathFlatteningIterator it (sourcePath, transform, PathFlatteningIterator::defaultTolerance / extraAccuracy);
  76086. bool first = true;
  76087. int dashNum = 0;
  76088. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76089. float dx = 0.0f, dy = 0.0f;
  76090. for (;;)
  76091. {
  76092. const bool isSolid = ((dashNum & 1) == 0);
  76093. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76094. jassert (dashLen > 0); // must be a positive increment!
  76095. if (dashLen <= 0)
  76096. break;
  76097. pos += dashLen;
  76098. while (pos > lineEndPos)
  76099. {
  76100. if (! it.next())
  76101. {
  76102. if (isSolid && ! first)
  76103. newDestPath.lineTo (it.x2, it.y2);
  76104. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76105. return;
  76106. }
  76107. if (isSolid && ! first)
  76108. newDestPath.lineTo (it.x1, it.y1);
  76109. else
  76110. newDestPath.startNewSubPath (it.x1, it.y1);
  76111. dx = it.x2 - it.x1;
  76112. dy = it.y2 - it.y1;
  76113. lineLen = juce_hypot (dx, dy);
  76114. lineEndPos += lineLen;
  76115. first = it.closesSubPath;
  76116. }
  76117. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76118. if (isSolid)
  76119. newDestPath.lineTo (it.x1 + dx * alpha,
  76120. it.y1 + dy * alpha);
  76121. else
  76122. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76123. it.y1 + dy * alpha);
  76124. }
  76125. }
  76126. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76127. const Path& sourcePath,
  76128. const float arrowheadStartWidth, const float arrowheadStartLength,
  76129. const float arrowheadEndWidth, const float arrowheadEndLength,
  76130. const AffineTransform& transform,
  76131. const float extraAccuracy) const
  76132. {
  76133. PathStrokeHelpers::Arrowhead head;
  76134. head.startWidth = arrowheadStartWidth;
  76135. head.startLength = arrowheadStartLength;
  76136. head.endWidth = arrowheadEndWidth;
  76137. head.endLength = arrowheadEndLength;
  76138. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76139. destPath, sourcePath, transform, extraAccuracy, &head);
  76140. }
  76141. END_JUCE_NAMESPACE
  76142. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76143. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76144. BEGIN_JUCE_NAMESPACE
  76145. RectangleList::RectangleList() throw()
  76146. {
  76147. }
  76148. RectangleList::RectangleList (const Rectangle<int>& rect)
  76149. {
  76150. if (! rect.isEmpty())
  76151. rects.add (rect);
  76152. }
  76153. RectangleList::RectangleList (const RectangleList& other)
  76154. : rects (other.rects)
  76155. {
  76156. }
  76157. RectangleList& RectangleList::operator= (const RectangleList& other)
  76158. {
  76159. rects = other.rects;
  76160. return *this;
  76161. }
  76162. RectangleList::~RectangleList()
  76163. {
  76164. }
  76165. void RectangleList::clear()
  76166. {
  76167. rects.clearQuick();
  76168. }
  76169. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76170. {
  76171. if (isPositiveAndBelow (index, rects.size()))
  76172. return rects.getReference (index);
  76173. return Rectangle<int>();
  76174. }
  76175. bool RectangleList::isEmpty() const throw()
  76176. {
  76177. return rects.size() == 0;
  76178. }
  76179. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76180. : current (0),
  76181. owner (list),
  76182. index (list.rects.size())
  76183. {
  76184. }
  76185. RectangleList::Iterator::~Iterator()
  76186. {
  76187. }
  76188. bool RectangleList::Iterator::next() throw()
  76189. {
  76190. if (--index >= 0)
  76191. {
  76192. current = & (owner.rects.getReference (index));
  76193. return true;
  76194. }
  76195. return false;
  76196. }
  76197. void RectangleList::add (const Rectangle<int>& rect)
  76198. {
  76199. if (! rect.isEmpty())
  76200. {
  76201. if (rects.size() == 0)
  76202. {
  76203. rects.add (rect);
  76204. }
  76205. else
  76206. {
  76207. bool anyOverlaps = false;
  76208. int i;
  76209. for (i = rects.size(); --i >= 0;)
  76210. {
  76211. Rectangle<int>& ourRect = rects.getReference (i);
  76212. if (rect.intersects (ourRect))
  76213. {
  76214. if (rect.contains (ourRect))
  76215. rects.remove (i);
  76216. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76217. anyOverlaps = true;
  76218. }
  76219. }
  76220. if (anyOverlaps && rects.size() > 0)
  76221. {
  76222. RectangleList r (rect);
  76223. for (i = rects.size(); --i >= 0;)
  76224. {
  76225. const Rectangle<int>& ourRect = rects.getReference (i);
  76226. if (rect.intersects (ourRect))
  76227. {
  76228. r.subtract (ourRect);
  76229. if (r.rects.size() == 0)
  76230. return;
  76231. }
  76232. }
  76233. for (i = r.getNumRectangles(); --i >= 0;)
  76234. rects.add (r.rects.getReference (i));
  76235. }
  76236. else
  76237. {
  76238. rects.add (rect);
  76239. }
  76240. }
  76241. }
  76242. }
  76243. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76244. {
  76245. if (! rect.isEmpty())
  76246. rects.add (rect);
  76247. }
  76248. void RectangleList::add (const int x, const int y, const int w, const int h)
  76249. {
  76250. if (rects.size() == 0)
  76251. {
  76252. if (w > 0 && h > 0)
  76253. rects.add (Rectangle<int> (x, y, w, h));
  76254. }
  76255. else
  76256. {
  76257. add (Rectangle<int> (x, y, w, h));
  76258. }
  76259. }
  76260. void RectangleList::add (const RectangleList& other)
  76261. {
  76262. for (int i = 0; i < other.rects.size(); ++i)
  76263. add (other.rects.getReference (i));
  76264. }
  76265. void RectangleList::subtract (const Rectangle<int>& rect)
  76266. {
  76267. const int originalNumRects = rects.size();
  76268. if (originalNumRects > 0)
  76269. {
  76270. const int x1 = rect.x;
  76271. const int y1 = rect.y;
  76272. const int x2 = x1 + rect.w;
  76273. const int y2 = y1 + rect.h;
  76274. for (int i = getNumRectangles(); --i >= 0;)
  76275. {
  76276. Rectangle<int>& r = rects.getReference (i);
  76277. const int rx1 = r.x;
  76278. const int ry1 = r.y;
  76279. const int rx2 = rx1 + r.w;
  76280. const int ry2 = ry1 + r.h;
  76281. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76282. {
  76283. if (x1 > rx1 && x1 < rx2)
  76284. {
  76285. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76286. {
  76287. r.w = x1 - rx1;
  76288. }
  76289. else
  76290. {
  76291. r.x = x1;
  76292. r.w = rx2 - x1;
  76293. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76294. i += 2;
  76295. }
  76296. }
  76297. else if (x2 > rx1 && x2 < rx2)
  76298. {
  76299. r.x = x2;
  76300. r.w = rx2 - x2;
  76301. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76302. {
  76303. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76304. i += 2;
  76305. }
  76306. }
  76307. else if (y1 > ry1 && y1 < ry2)
  76308. {
  76309. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76310. {
  76311. r.h = y1 - ry1;
  76312. }
  76313. else
  76314. {
  76315. r.y = y1;
  76316. r.h = ry2 - y1;
  76317. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76318. i += 2;
  76319. }
  76320. }
  76321. else if (y2 > ry1 && y2 < ry2)
  76322. {
  76323. r.y = y2;
  76324. r.h = ry2 - y2;
  76325. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76326. {
  76327. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76328. i += 2;
  76329. }
  76330. }
  76331. else
  76332. {
  76333. rects.remove (i);
  76334. }
  76335. }
  76336. }
  76337. }
  76338. }
  76339. bool RectangleList::subtract (const RectangleList& otherList)
  76340. {
  76341. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76342. subtract (otherList.rects.getReference (i));
  76343. return rects.size() > 0;
  76344. }
  76345. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76346. {
  76347. bool notEmpty = false;
  76348. if (rect.isEmpty())
  76349. {
  76350. clear();
  76351. }
  76352. else
  76353. {
  76354. for (int i = rects.size(); --i >= 0;)
  76355. {
  76356. Rectangle<int>& r = rects.getReference (i);
  76357. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76358. rects.remove (i);
  76359. else
  76360. notEmpty = true;
  76361. }
  76362. }
  76363. return notEmpty;
  76364. }
  76365. bool RectangleList::clipTo (const RectangleList& other)
  76366. {
  76367. if (rects.size() == 0)
  76368. return false;
  76369. RectangleList result;
  76370. for (int j = 0; j < rects.size(); ++j)
  76371. {
  76372. const Rectangle<int>& rect = rects.getReference (j);
  76373. for (int i = other.rects.size(); --i >= 0;)
  76374. {
  76375. Rectangle<int> r (other.rects.getReference (i));
  76376. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76377. result.rects.add (r);
  76378. }
  76379. }
  76380. swapWith (result);
  76381. return ! isEmpty();
  76382. }
  76383. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76384. {
  76385. destRegion.clear();
  76386. if (! rect.isEmpty())
  76387. {
  76388. for (int i = rects.size(); --i >= 0;)
  76389. {
  76390. Rectangle<int> r (rects.getReference (i));
  76391. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76392. destRegion.rects.add (r);
  76393. }
  76394. }
  76395. return destRegion.rects.size() > 0;
  76396. }
  76397. void RectangleList::swapWith (RectangleList& otherList) throw()
  76398. {
  76399. rects.swapWithArray (otherList.rects);
  76400. }
  76401. void RectangleList::consolidate()
  76402. {
  76403. int i;
  76404. for (i = 0; i < getNumRectangles() - 1; ++i)
  76405. {
  76406. Rectangle<int>& r = rects.getReference (i);
  76407. const int rx1 = r.x;
  76408. const int ry1 = r.y;
  76409. const int rx2 = rx1 + r.w;
  76410. const int ry2 = ry1 + r.h;
  76411. for (int j = rects.size(); --j > i;)
  76412. {
  76413. Rectangle<int>& r2 = rects.getReference (j);
  76414. const int jrx1 = r2.x;
  76415. const int jry1 = r2.y;
  76416. const int jrx2 = jrx1 + r2.w;
  76417. const int jry2 = jry1 + r2.h;
  76418. // if the vertical edges of any blocks are touching and their horizontals don't
  76419. // line up, split them horizontally..
  76420. if (jrx1 == rx2 || jrx2 == rx1)
  76421. {
  76422. if (jry1 > ry1 && jry1 < ry2)
  76423. {
  76424. r.h = jry1 - ry1;
  76425. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76426. i = -1;
  76427. break;
  76428. }
  76429. if (jry2 > ry1 && jry2 < ry2)
  76430. {
  76431. r.h = jry2 - ry1;
  76432. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76433. i = -1;
  76434. break;
  76435. }
  76436. else if (ry1 > jry1 && ry1 < jry2)
  76437. {
  76438. r2.h = ry1 - jry1;
  76439. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76440. i = -1;
  76441. break;
  76442. }
  76443. else if (ry2 > jry1 && ry2 < jry2)
  76444. {
  76445. r2.h = ry2 - jry1;
  76446. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76447. i = -1;
  76448. break;
  76449. }
  76450. }
  76451. }
  76452. }
  76453. for (i = 0; i < rects.size() - 1; ++i)
  76454. {
  76455. Rectangle<int>& r = rects.getReference (i);
  76456. for (int j = rects.size(); --j > i;)
  76457. {
  76458. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76459. {
  76460. rects.remove (j);
  76461. i = -1;
  76462. break;
  76463. }
  76464. }
  76465. }
  76466. }
  76467. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76468. {
  76469. for (int i = getNumRectangles(); --i >= 0;)
  76470. if (rects.getReference (i).contains (x, y))
  76471. return true;
  76472. return false;
  76473. }
  76474. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76475. {
  76476. if (rects.size() > 1)
  76477. {
  76478. RectangleList r (rectangleToCheck);
  76479. for (int i = rects.size(); --i >= 0;)
  76480. {
  76481. r.subtract (rects.getReference (i));
  76482. if (r.rects.size() == 0)
  76483. return true;
  76484. }
  76485. }
  76486. else if (rects.size() > 0)
  76487. {
  76488. return rects.getReference (0).contains (rectangleToCheck);
  76489. }
  76490. return false;
  76491. }
  76492. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76493. {
  76494. for (int i = rects.size(); --i >= 0;)
  76495. if (rects.getReference (i).intersects (rectangleToCheck))
  76496. return true;
  76497. return false;
  76498. }
  76499. bool RectangleList::intersects (const RectangleList& other) const throw()
  76500. {
  76501. for (int i = rects.size(); --i >= 0;)
  76502. if (other.intersectsRectangle (rects.getReference (i)))
  76503. return true;
  76504. return false;
  76505. }
  76506. const Rectangle<int> RectangleList::getBounds() const throw()
  76507. {
  76508. if (rects.size() <= 1)
  76509. {
  76510. if (rects.size() == 0)
  76511. return Rectangle<int>();
  76512. else
  76513. return rects.getReference (0);
  76514. }
  76515. else
  76516. {
  76517. const Rectangle<int>& r = rects.getReference (0);
  76518. int minX = r.x;
  76519. int minY = r.y;
  76520. int maxX = minX + r.w;
  76521. int maxY = minY + r.h;
  76522. for (int i = rects.size(); --i > 0;)
  76523. {
  76524. const Rectangle<int>& r2 = rects.getReference (i);
  76525. minX = jmin (minX, r2.x);
  76526. minY = jmin (minY, r2.y);
  76527. maxX = jmax (maxX, r2.getRight());
  76528. maxY = jmax (maxY, r2.getBottom());
  76529. }
  76530. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76531. }
  76532. }
  76533. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76534. {
  76535. for (int i = rects.size(); --i >= 0;)
  76536. {
  76537. Rectangle<int>& r = rects.getReference (i);
  76538. r.x += dx;
  76539. r.y += dy;
  76540. }
  76541. }
  76542. const Path RectangleList::toPath() const
  76543. {
  76544. Path p;
  76545. for (int i = rects.size(); --i >= 0;)
  76546. {
  76547. const Rectangle<int>& r = rects.getReference (i);
  76548. p.addRectangle ((float) r.x,
  76549. (float) r.y,
  76550. (float) r.w,
  76551. (float) r.h);
  76552. }
  76553. return p;
  76554. }
  76555. END_JUCE_NAMESPACE
  76556. /*** End of inlined file: juce_RectangleList.cpp ***/
  76557. /*** Start of inlined file: juce_Image.cpp ***/
  76558. BEGIN_JUCE_NAMESPACE
  76559. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76560. : format (format_), width (width_), height (height_)
  76561. {
  76562. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76563. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76564. }
  76565. Image::SharedImage::~SharedImage()
  76566. {
  76567. }
  76568. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76569. {
  76570. return imageData + lineStride * y + pixelStride * x;
  76571. }
  76572. class SoftwareSharedImage : public Image::SharedImage
  76573. {
  76574. public:
  76575. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76576. : Image::SharedImage (format_, width_, height_)
  76577. {
  76578. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76579. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76580. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76581. imageData = imageDataAllocated;
  76582. }
  76583. Image::ImageType getType() const
  76584. {
  76585. return Image::SoftwareImage;
  76586. }
  76587. LowLevelGraphicsContext* createLowLevelContext()
  76588. {
  76589. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76590. }
  76591. Image::SharedImage* clone()
  76592. {
  76593. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76594. memcpy (s->imageData, imageData, lineStride * height);
  76595. return s;
  76596. }
  76597. private:
  76598. HeapBlock<uint8> imageDataAllocated;
  76599. JUCE_LEAK_DETECTOR (SoftwareSharedImage);
  76600. };
  76601. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76602. {
  76603. return new SoftwareSharedImage (format, width, height, clearImage);
  76604. }
  76605. class SubsectionSharedImage : public Image::SharedImage
  76606. {
  76607. public:
  76608. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76609. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76610. image (image_), area (area_)
  76611. {
  76612. pixelStride = image_->getPixelStride();
  76613. lineStride = image_->getLineStride();
  76614. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76615. }
  76616. Image::ImageType getType() const
  76617. {
  76618. return Image::SoftwareImage;
  76619. }
  76620. LowLevelGraphicsContext* createLowLevelContext()
  76621. {
  76622. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76623. g->clipToRectangle (area);
  76624. g->setOrigin (area.getX(), area.getY());
  76625. return g;
  76626. }
  76627. Image::SharedImage* clone()
  76628. {
  76629. return new SubsectionSharedImage (image->clone(), area);
  76630. }
  76631. private:
  76632. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76633. const Rectangle<int> area;
  76634. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SubsectionSharedImage);
  76635. };
  76636. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76637. {
  76638. if (area.contains (getBounds()))
  76639. return *this;
  76640. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76641. if (validArea.isEmpty())
  76642. return Image::null;
  76643. return Image (new SubsectionSharedImage (image, validArea));
  76644. }
  76645. Image::Image()
  76646. {
  76647. }
  76648. Image::Image (SharedImage* const instance)
  76649. : image (instance)
  76650. {
  76651. }
  76652. Image::Image (const PixelFormat format,
  76653. const int width, const int height,
  76654. const bool clearImage, const ImageType type)
  76655. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76656. : new SoftwareSharedImage (format, width, height, clearImage))
  76657. {
  76658. }
  76659. Image::Image (const Image& other)
  76660. : image (other.image)
  76661. {
  76662. }
  76663. Image& Image::operator= (const Image& other)
  76664. {
  76665. image = other.image;
  76666. return *this;
  76667. }
  76668. Image::~Image()
  76669. {
  76670. }
  76671. const Image Image::null;
  76672. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76673. {
  76674. return image == 0 ? 0 : image->createLowLevelContext();
  76675. }
  76676. void Image::duplicateIfShared()
  76677. {
  76678. if (image != 0 && image->getReferenceCount() > 1)
  76679. image = image->clone();
  76680. }
  76681. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  76682. {
  76683. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  76684. return *this;
  76685. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  76686. Graphics g (newImage);
  76687. g.setImageResamplingQuality (quality);
  76688. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  76689. return newImage;
  76690. }
  76691. const Image Image::convertedToFormat (PixelFormat newFormat) const
  76692. {
  76693. if (image == 0 || newFormat == image->format)
  76694. return *this;
  76695. const int w = image->width, h = image->height;
  76696. Image newImage (newFormat, w, h, false, image->getType());
  76697. if (newFormat == SingleChannel)
  76698. {
  76699. if (! hasAlphaChannel())
  76700. {
  76701. newImage.clear (getBounds(), Colours::black);
  76702. }
  76703. else
  76704. {
  76705. const BitmapData destData (newImage, 0, 0, w, h, true);
  76706. const BitmapData srcData (*this, 0, 0, w, h);
  76707. for (int y = 0; y < h; ++y)
  76708. {
  76709. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  76710. uint8* dst = destData.getLinePointer (y);
  76711. for (int x = w; --x >= 0;)
  76712. {
  76713. *dst++ = src->getAlpha();
  76714. ++src;
  76715. }
  76716. }
  76717. }
  76718. }
  76719. else
  76720. {
  76721. if (hasAlphaChannel())
  76722. newImage.clear (getBounds());
  76723. Graphics g (newImage);
  76724. g.drawImageAt (*this, 0, 0);
  76725. }
  76726. return newImage;
  76727. }
  76728. NamedValueSet* Image::getProperties() const
  76729. {
  76730. return image == 0 ? 0 : &(image->userData);
  76731. }
  76732. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  76733. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76734. pixelFormat (image.getFormat()),
  76735. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76736. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76737. width (w),
  76738. height (h)
  76739. {
  76740. jassert (data != 0);
  76741. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76742. }
  76743. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  76744. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  76745. pixelFormat (image.getFormat()),
  76746. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76747. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76748. width (w),
  76749. height (h)
  76750. {
  76751. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  76752. }
  76753. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  76754. : data (image.image == 0 ? 0 : image.image->imageData),
  76755. pixelFormat (image.getFormat()),
  76756. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  76757. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  76758. width (image.getWidth()),
  76759. height (image.getHeight())
  76760. {
  76761. }
  76762. Image::BitmapData::~BitmapData()
  76763. {
  76764. }
  76765. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  76766. {
  76767. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76768. const uint8* const pixel = getPixelPointer (x, y);
  76769. switch (pixelFormat)
  76770. {
  76771. case Image::ARGB:
  76772. {
  76773. PixelARGB p (*(const PixelARGB*) pixel);
  76774. p.unpremultiply();
  76775. return Colour (p.getARGB());
  76776. }
  76777. case Image::RGB:
  76778. return Colour (((const PixelRGB*) pixel)->getARGB());
  76779. case Image::SingleChannel:
  76780. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  76781. default:
  76782. jassertfalse;
  76783. break;
  76784. }
  76785. return Colour();
  76786. }
  76787. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  76788. {
  76789. jassert (isPositiveAndBelow (x, width) && isPositiveAndBelow (y, height));
  76790. uint8* const pixel = getPixelPointer (x, y);
  76791. const PixelARGB col (colour.getPixelARGB());
  76792. switch (pixelFormat)
  76793. {
  76794. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  76795. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  76796. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  76797. default: jassertfalse; break;
  76798. }
  76799. }
  76800. void Image::setPixelData (int x, int y, int w, int h,
  76801. const uint8* const sourcePixelData, const int sourceLineStride)
  76802. {
  76803. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  76804. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  76805. {
  76806. const BitmapData dest (*this, x, y, w, h, true);
  76807. for (int i = 0; i < h; ++i)
  76808. {
  76809. memcpy (dest.getLinePointer(i),
  76810. sourcePixelData + sourceLineStride * i,
  76811. w * dest.pixelStride);
  76812. }
  76813. }
  76814. }
  76815. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  76816. {
  76817. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  76818. if (! clipped.isEmpty())
  76819. {
  76820. const PixelARGB col (colourToClearTo.getPixelARGB());
  76821. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  76822. uint8* dest = destData.data;
  76823. int dh = clipped.getHeight();
  76824. while (--dh >= 0)
  76825. {
  76826. uint8* line = dest;
  76827. dest += destData.lineStride;
  76828. if (isARGB())
  76829. {
  76830. for (int x = clipped.getWidth(); --x >= 0;)
  76831. {
  76832. ((PixelARGB*) line)->set (col);
  76833. line += destData.pixelStride;
  76834. }
  76835. }
  76836. else if (isRGB())
  76837. {
  76838. for (int x = clipped.getWidth(); --x >= 0;)
  76839. {
  76840. ((PixelRGB*) line)->set (col);
  76841. line += destData.pixelStride;
  76842. }
  76843. }
  76844. else
  76845. {
  76846. for (int x = clipped.getWidth(); --x >= 0;)
  76847. {
  76848. *line = col.getAlpha();
  76849. line += destData.pixelStride;
  76850. }
  76851. }
  76852. }
  76853. }
  76854. }
  76855. const Colour Image::getPixelAt (const int x, const int y) const
  76856. {
  76857. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76858. {
  76859. const BitmapData srcData (*this, x, y, 1, 1);
  76860. return srcData.getPixelColour (0, 0);
  76861. }
  76862. return Colour();
  76863. }
  76864. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  76865. {
  76866. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight()))
  76867. {
  76868. const BitmapData destData (*this, x, y, 1, 1, true);
  76869. destData.setPixelColour (0, 0, colour);
  76870. }
  76871. }
  76872. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  76873. {
  76874. if (isPositiveAndBelow (x, getWidth()) && isPositiveAndBelow (y, getHeight())
  76875. && hasAlphaChannel())
  76876. {
  76877. const BitmapData destData (*this, x, y, 1, 1, true);
  76878. if (isARGB())
  76879. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  76880. else
  76881. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  76882. }
  76883. }
  76884. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  76885. {
  76886. if (hasAlphaChannel())
  76887. {
  76888. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76889. if (isARGB())
  76890. {
  76891. for (int y = 0; y < destData.height; ++y)
  76892. {
  76893. uint8* p = destData.getLinePointer (y);
  76894. for (int x = 0; x < destData.width; ++x)
  76895. {
  76896. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  76897. p += destData.pixelStride;
  76898. }
  76899. }
  76900. }
  76901. else
  76902. {
  76903. for (int y = 0; y < destData.height; ++y)
  76904. {
  76905. uint8* p = destData.getLinePointer (y);
  76906. for (int x = 0; x < destData.width; ++x)
  76907. {
  76908. *p = (uint8) (*p * amountToMultiplyBy);
  76909. p += destData.pixelStride;
  76910. }
  76911. }
  76912. }
  76913. }
  76914. else
  76915. {
  76916. jassertfalse; // can't do this without an alpha-channel!
  76917. }
  76918. }
  76919. void Image::desaturate()
  76920. {
  76921. if (isARGB() || isRGB())
  76922. {
  76923. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  76924. if (isARGB())
  76925. {
  76926. for (int y = 0; y < destData.height; ++y)
  76927. {
  76928. uint8* p = destData.getLinePointer (y);
  76929. for (int x = 0; x < destData.width; ++x)
  76930. {
  76931. ((PixelARGB*) p)->desaturate();
  76932. p += destData.pixelStride;
  76933. }
  76934. }
  76935. }
  76936. else
  76937. {
  76938. for (int y = 0; y < destData.height; ++y)
  76939. {
  76940. uint8* p = destData.getLinePointer (y);
  76941. for (int x = 0; x < destData.width; ++x)
  76942. {
  76943. ((PixelRGB*) p)->desaturate();
  76944. p += destData.pixelStride;
  76945. }
  76946. }
  76947. }
  76948. }
  76949. }
  76950. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  76951. {
  76952. if (hasAlphaChannel())
  76953. {
  76954. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  76955. SparseSet<int> pixelsOnRow;
  76956. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  76957. for (int y = 0; y < srcData.height; ++y)
  76958. {
  76959. pixelsOnRow.clear();
  76960. const uint8* lineData = srcData.getLinePointer (y);
  76961. if (isARGB())
  76962. {
  76963. for (int x = 0; x < srcData.width; ++x)
  76964. {
  76965. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  76966. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76967. lineData += srcData.pixelStride;
  76968. }
  76969. }
  76970. else
  76971. {
  76972. for (int x = 0; x < srcData.width; ++x)
  76973. {
  76974. if (*lineData >= threshold)
  76975. pixelsOnRow.addRange (Range<int> (x, x + 1));
  76976. lineData += srcData.pixelStride;
  76977. }
  76978. }
  76979. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  76980. {
  76981. const Range<int> range (pixelsOnRow.getRange (i));
  76982. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  76983. }
  76984. result.consolidate();
  76985. }
  76986. }
  76987. else
  76988. {
  76989. result.add (0, 0, getWidth(), getHeight());
  76990. }
  76991. }
  76992. void Image::moveImageSection (int dx, int dy,
  76993. int sx, int sy,
  76994. int w, int h)
  76995. {
  76996. if (dx < 0)
  76997. {
  76998. w += dx;
  76999. sx -= dx;
  77000. dx = 0;
  77001. }
  77002. if (dy < 0)
  77003. {
  77004. h += dy;
  77005. sy -= dy;
  77006. dy = 0;
  77007. }
  77008. if (sx < 0)
  77009. {
  77010. w += sx;
  77011. dx -= sx;
  77012. sx = 0;
  77013. }
  77014. if (sy < 0)
  77015. {
  77016. h += sy;
  77017. dy -= sy;
  77018. sy = 0;
  77019. }
  77020. const int minX = jmin (dx, sx);
  77021. const int minY = jmin (dy, sy);
  77022. w = jmin (w, getWidth() - jmax (sx, dx));
  77023. h = jmin (h, getHeight() - jmax (sy, dy));
  77024. if (w > 0 && h > 0)
  77025. {
  77026. const int maxX = jmax (dx, sx) + w;
  77027. const int maxY = jmax (dy, sy) + h;
  77028. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77029. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77030. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77031. const int lineSize = destData.pixelStride * w;
  77032. if (dy > sy)
  77033. {
  77034. while (--h >= 0)
  77035. {
  77036. const int offset = h * destData.lineStride;
  77037. memmove (dst + offset, src + offset, lineSize);
  77038. }
  77039. }
  77040. else if (dst != src)
  77041. {
  77042. while (--h >= 0)
  77043. {
  77044. memmove (dst, src, lineSize);
  77045. dst += destData.lineStride;
  77046. src += destData.lineStride;
  77047. }
  77048. }
  77049. }
  77050. }
  77051. END_JUCE_NAMESPACE
  77052. /*** End of inlined file: juce_Image.cpp ***/
  77053. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77054. BEGIN_JUCE_NAMESPACE
  77055. class ImageCache::Pimpl : public Timer,
  77056. public DeletedAtShutdown
  77057. {
  77058. public:
  77059. Pimpl()
  77060. : cacheTimeout (5000)
  77061. {
  77062. }
  77063. ~Pimpl()
  77064. {
  77065. clearSingletonInstance();
  77066. }
  77067. const Image getFromHashCode (const int64 hashCode)
  77068. {
  77069. const ScopedLock sl (lock);
  77070. for (int i = images.size(); --i >= 0;)
  77071. {
  77072. Item* const item = images.getUnchecked(i);
  77073. if (item->hashCode == hashCode)
  77074. return item->image;
  77075. }
  77076. return Image::null;
  77077. }
  77078. void addImageToCache (const Image& image, const int64 hashCode)
  77079. {
  77080. if (image.isValid())
  77081. {
  77082. if (! isTimerRunning())
  77083. startTimer (2000);
  77084. Item* const item = new Item();
  77085. item->hashCode = hashCode;
  77086. item->image = image;
  77087. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77088. const ScopedLock sl (lock);
  77089. images.add (item);
  77090. }
  77091. }
  77092. void timerCallback()
  77093. {
  77094. const uint32 now = Time::getApproximateMillisecondCounter();
  77095. const ScopedLock sl (lock);
  77096. for (int i = images.size(); --i >= 0;)
  77097. {
  77098. Item* const item = images.getUnchecked(i);
  77099. if (item->image.getReferenceCount() <= 1)
  77100. {
  77101. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77102. images.remove (i);
  77103. }
  77104. else
  77105. {
  77106. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77107. }
  77108. }
  77109. if (images.size() == 0)
  77110. stopTimer();
  77111. }
  77112. struct Item
  77113. {
  77114. Image image;
  77115. int64 hashCode;
  77116. uint32 lastUseTime;
  77117. };
  77118. int cacheTimeout;
  77119. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77120. private:
  77121. OwnedArray<Item> images;
  77122. CriticalSection lock;
  77123. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  77124. };
  77125. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77126. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77127. {
  77128. if (Pimpl::getInstanceWithoutCreating() != 0)
  77129. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77130. return Image::null;
  77131. }
  77132. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77133. {
  77134. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77135. }
  77136. const Image ImageCache::getFromFile (const File& file)
  77137. {
  77138. const int64 hashCode = file.hashCode64();
  77139. Image image (getFromHashCode (hashCode));
  77140. if (image.isNull())
  77141. {
  77142. image = ImageFileFormat::loadFrom (file);
  77143. addImageToCache (image, hashCode);
  77144. }
  77145. return image;
  77146. }
  77147. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77148. {
  77149. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77150. Image image (getFromHashCode (hashCode));
  77151. if (image.isNull())
  77152. {
  77153. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77154. addImageToCache (image, hashCode);
  77155. }
  77156. return image;
  77157. }
  77158. void ImageCache::setCacheTimeout (const int millisecs)
  77159. {
  77160. Pimpl::getInstance()->cacheTimeout = millisecs;
  77161. }
  77162. END_JUCE_NAMESPACE
  77163. /*** End of inlined file: juce_ImageCache.cpp ***/
  77164. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77165. BEGIN_JUCE_NAMESPACE
  77166. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77167. : values (size_ * size_),
  77168. size (size_)
  77169. {
  77170. clear();
  77171. }
  77172. ImageConvolutionKernel::~ImageConvolutionKernel()
  77173. {
  77174. }
  77175. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77176. {
  77177. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77178. return values [x + y * size];
  77179. jassertfalse;
  77180. return 0;
  77181. }
  77182. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77183. {
  77184. if (isPositiveAndBelow (x, size) && isPositiveAndBelow (y, size))
  77185. {
  77186. values [x + y * size] = value;
  77187. }
  77188. else
  77189. {
  77190. jassertfalse;
  77191. }
  77192. }
  77193. void ImageConvolutionKernel::clear()
  77194. {
  77195. for (int i = size * size; --i >= 0;)
  77196. values[i] = 0;
  77197. }
  77198. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77199. {
  77200. double currentTotal = 0.0;
  77201. for (int i = size * size; --i >= 0;)
  77202. currentTotal += values[i];
  77203. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77204. }
  77205. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77206. {
  77207. for (int i = size * size; --i >= 0;)
  77208. values[i] *= multiplier;
  77209. }
  77210. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77211. {
  77212. const double radiusFactor = -1.0 / (radius * radius * 2);
  77213. const int centre = size >> 1;
  77214. for (int y = size; --y >= 0;)
  77215. {
  77216. for (int x = size; --x >= 0;)
  77217. {
  77218. const int cx = x - centre;
  77219. const int cy = y - centre;
  77220. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77221. }
  77222. }
  77223. setOverallSum (1.0f);
  77224. }
  77225. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77226. const Image& sourceImage,
  77227. const Rectangle<int>& destinationArea) const
  77228. {
  77229. if (sourceImage == destImage)
  77230. {
  77231. destImage.duplicateIfShared();
  77232. }
  77233. else
  77234. {
  77235. if (sourceImage.getWidth() != destImage.getWidth()
  77236. || sourceImage.getHeight() != destImage.getHeight()
  77237. || sourceImage.getFormat() != destImage.getFormat())
  77238. {
  77239. jassertfalse;
  77240. return;
  77241. }
  77242. }
  77243. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77244. if (area.isEmpty())
  77245. return;
  77246. const int right = area.getRight();
  77247. const int bottom = area.getBottom();
  77248. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77249. uint8* line = destData.data;
  77250. const Image::BitmapData srcData (sourceImage, false);
  77251. if (destData.pixelStride == 4)
  77252. {
  77253. for (int y = area.getY(); y < bottom; ++y)
  77254. {
  77255. uint8* dest = line;
  77256. line += destData.lineStride;
  77257. for (int x = area.getX(); x < right; ++x)
  77258. {
  77259. float c1 = 0;
  77260. float c2 = 0;
  77261. float c3 = 0;
  77262. float c4 = 0;
  77263. for (int yy = 0; yy < size; ++yy)
  77264. {
  77265. const int sy = y + yy - (size >> 1);
  77266. if (sy >= srcData.height)
  77267. break;
  77268. if (sy >= 0)
  77269. {
  77270. int sx = x - (size >> 1);
  77271. const uint8* src = srcData.getPixelPointer (sx, sy);
  77272. for (int xx = 0; xx < size; ++xx)
  77273. {
  77274. if (sx >= srcData.width)
  77275. break;
  77276. if (sx >= 0)
  77277. {
  77278. const float kernelMult = values [xx + yy * size];
  77279. c1 += kernelMult * *src++;
  77280. c2 += kernelMult * *src++;
  77281. c3 += kernelMult * *src++;
  77282. c4 += kernelMult * *src++;
  77283. }
  77284. else
  77285. {
  77286. src += 4;
  77287. }
  77288. ++sx;
  77289. }
  77290. }
  77291. }
  77292. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77293. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77294. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77295. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77296. }
  77297. }
  77298. }
  77299. else if (destData.pixelStride == 3)
  77300. {
  77301. for (int y = area.getY(); y < bottom; ++y)
  77302. {
  77303. uint8* dest = line;
  77304. line += destData.lineStride;
  77305. for (int x = area.getX(); x < right; ++x)
  77306. {
  77307. float c1 = 0;
  77308. float c2 = 0;
  77309. float c3 = 0;
  77310. for (int yy = 0; yy < size; ++yy)
  77311. {
  77312. const int sy = y + yy - (size >> 1);
  77313. if (sy >= srcData.height)
  77314. break;
  77315. if (sy >= 0)
  77316. {
  77317. int sx = x - (size >> 1);
  77318. const uint8* src = srcData.getPixelPointer (sx, sy);
  77319. for (int xx = 0; xx < size; ++xx)
  77320. {
  77321. if (sx >= srcData.width)
  77322. break;
  77323. if (sx >= 0)
  77324. {
  77325. const float kernelMult = values [xx + yy * size];
  77326. c1 += kernelMult * *src++;
  77327. c2 += kernelMult * *src++;
  77328. c3 += kernelMult * *src++;
  77329. }
  77330. else
  77331. {
  77332. src += 3;
  77333. }
  77334. ++sx;
  77335. }
  77336. }
  77337. }
  77338. *dest++ = (uint8) roundToInt (c1);
  77339. *dest++ = (uint8) roundToInt (c2);
  77340. *dest++ = (uint8) roundToInt (c3);
  77341. }
  77342. }
  77343. }
  77344. }
  77345. END_JUCE_NAMESPACE
  77346. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77347. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77348. BEGIN_JUCE_NAMESPACE
  77349. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77350. {
  77351. static PNGImageFormat png;
  77352. static JPEGImageFormat jpg;
  77353. static GIFImageFormat gif;
  77354. ImageFileFormat* formats[4];
  77355. int numFormats = 0;
  77356. formats [numFormats++] = &png;
  77357. formats [numFormats++] = &jpg;
  77358. formats [numFormats++] = &gif;
  77359. const int64 streamPos = input.getPosition();
  77360. for (int i = 0; i < numFormats; ++i)
  77361. {
  77362. const bool found = formats[i]->canUnderstand (input);
  77363. input.setPosition (streamPos);
  77364. if (found)
  77365. return formats[i];
  77366. }
  77367. return 0;
  77368. }
  77369. const Image ImageFileFormat::loadFrom (InputStream& input)
  77370. {
  77371. ImageFileFormat* const format = findImageFormatForStream (input);
  77372. if (format != 0)
  77373. return format->decodeImage (input);
  77374. return Image::null;
  77375. }
  77376. const Image ImageFileFormat::loadFrom (const File& file)
  77377. {
  77378. InputStream* const in = file.createInputStream();
  77379. if (in != 0)
  77380. {
  77381. BufferedInputStream b (in, 8192, true);
  77382. return loadFrom (b);
  77383. }
  77384. return Image::null;
  77385. }
  77386. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77387. {
  77388. if (rawData != 0 && numBytes > 4)
  77389. {
  77390. MemoryInputStream stream (rawData, numBytes, false);
  77391. return loadFrom (stream);
  77392. }
  77393. return Image::null;
  77394. }
  77395. END_JUCE_NAMESPACE
  77396. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77397. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77398. BEGIN_JUCE_NAMESPACE
  77399. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77400. const Image juce_loadWithCoreImage (InputStream& input);
  77401. #else
  77402. class GIFLoader
  77403. {
  77404. public:
  77405. GIFLoader (InputStream& in)
  77406. : input (in),
  77407. dataBlockIsZero (false),
  77408. fresh (false),
  77409. finished (false)
  77410. {
  77411. currentBit = lastBit = lastByteIndex = 0;
  77412. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77413. firstcode = oldcode = 0;
  77414. clearCode = end_code = 0;
  77415. int imageWidth, imageHeight;
  77416. int transparent = -1;
  77417. if (! getSizeFromHeader (imageWidth, imageHeight))
  77418. return;
  77419. if ((imageWidth <= 0) || (imageHeight <= 0))
  77420. return;
  77421. unsigned char buf [16];
  77422. if (in.read (buf, 3) != 3)
  77423. return;
  77424. int numColours = 2 << (buf[0] & 7);
  77425. if ((buf[0] & 0x80) != 0)
  77426. readPalette (numColours);
  77427. for (;;)
  77428. {
  77429. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77430. break;
  77431. if (buf[0] == '!')
  77432. {
  77433. if (input.read (buf, 1) != 1)
  77434. break;
  77435. if (processExtension (buf[0], transparent) < 0)
  77436. break;
  77437. continue;
  77438. }
  77439. if (buf[0] != ',')
  77440. continue;
  77441. if (input.read (buf, 9) != 9)
  77442. break;
  77443. imageWidth = makeWord (buf[4], buf[5]);
  77444. imageHeight = makeWord (buf[6], buf[7]);
  77445. numColours = 2 << (buf[8] & 7);
  77446. if ((buf[8] & 0x80) != 0)
  77447. if (! readPalette (numColours))
  77448. break;
  77449. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77450. imageWidth, imageHeight, (transparent >= 0));
  77451. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  77452. readImage ((buf[8] & 0x40) != 0, transparent);
  77453. break;
  77454. }
  77455. }
  77456. ~GIFLoader() {}
  77457. Image image;
  77458. private:
  77459. InputStream& input;
  77460. uint8 buffer [300];
  77461. uint8 palette [256][4];
  77462. bool dataBlockIsZero, fresh, finished;
  77463. int currentBit, lastBit, lastByteIndex;
  77464. int codeSize, setCodeSize;
  77465. int maxCode, maxCodeSize;
  77466. int firstcode, oldcode;
  77467. int clearCode, end_code;
  77468. enum { maxGifCode = 1 << 12 };
  77469. int table [2] [maxGifCode];
  77470. int stack [2 * maxGifCode];
  77471. int *sp;
  77472. bool getSizeFromHeader (int& w, int& h)
  77473. {
  77474. char b[8];
  77475. if (input.read (b, 6) == 6)
  77476. {
  77477. if ((strncmp ("GIF87a", b, 6) == 0)
  77478. || (strncmp ("GIF89a", b, 6) == 0))
  77479. {
  77480. if (input.read (b, 4) == 4)
  77481. {
  77482. w = makeWord (b[0], b[1]);
  77483. h = makeWord (b[2], b[3]);
  77484. return true;
  77485. }
  77486. }
  77487. }
  77488. return false;
  77489. }
  77490. bool readPalette (const int numCols)
  77491. {
  77492. unsigned char rgb[4];
  77493. for (int i = 0; i < numCols; ++i)
  77494. {
  77495. input.read (rgb, 3);
  77496. palette [i][0] = rgb[0];
  77497. palette [i][1] = rgb[1];
  77498. palette [i][2] = rgb[2];
  77499. palette [i][3] = 0xff;
  77500. }
  77501. return true;
  77502. }
  77503. int readDataBlock (unsigned char* dest)
  77504. {
  77505. unsigned char n;
  77506. if (input.read (&n, 1) == 1)
  77507. {
  77508. dataBlockIsZero = (n == 0);
  77509. if (dataBlockIsZero || (input.read (dest, n) == n))
  77510. return n;
  77511. }
  77512. return -1;
  77513. }
  77514. int processExtension (const int type, int& transparent)
  77515. {
  77516. unsigned char b [300];
  77517. int n = 0;
  77518. if (type == 0xf9)
  77519. {
  77520. n = readDataBlock (b);
  77521. if (n < 0)
  77522. return 1;
  77523. if ((b[0] & 0x1) != 0)
  77524. transparent = b[3];
  77525. }
  77526. do
  77527. {
  77528. n = readDataBlock (b);
  77529. }
  77530. while (n > 0);
  77531. return n;
  77532. }
  77533. int readLZWByte (const bool initialise, const int inputCodeSize)
  77534. {
  77535. int code, incode, i;
  77536. if (initialise)
  77537. {
  77538. setCodeSize = inputCodeSize;
  77539. codeSize = setCodeSize + 1;
  77540. clearCode = 1 << setCodeSize;
  77541. end_code = clearCode + 1;
  77542. maxCodeSize = 2 * clearCode;
  77543. maxCode = clearCode + 2;
  77544. getCode (0, true);
  77545. fresh = true;
  77546. for (i = 0; i < clearCode; ++i)
  77547. {
  77548. table[0][i] = 0;
  77549. table[1][i] = i;
  77550. }
  77551. for (; i < maxGifCode; ++i)
  77552. {
  77553. table[0][i] = 0;
  77554. table[1][i] = 0;
  77555. }
  77556. sp = stack;
  77557. return 0;
  77558. }
  77559. else if (fresh)
  77560. {
  77561. fresh = false;
  77562. do
  77563. {
  77564. firstcode = oldcode
  77565. = getCode (codeSize, false);
  77566. }
  77567. while (firstcode == clearCode);
  77568. return firstcode;
  77569. }
  77570. if (sp > stack)
  77571. return *--sp;
  77572. while ((code = getCode (codeSize, false)) >= 0)
  77573. {
  77574. if (code == clearCode)
  77575. {
  77576. for (i = 0; i < clearCode; ++i)
  77577. {
  77578. table[0][i] = 0;
  77579. table[1][i] = i;
  77580. }
  77581. for (; i < maxGifCode; ++i)
  77582. {
  77583. table[0][i] = 0;
  77584. table[1][i] = 0;
  77585. }
  77586. codeSize = setCodeSize + 1;
  77587. maxCodeSize = 2 * clearCode;
  77588. maxCode = clearCode + 2;
  77589. sp = stack;
  77590. firstcode = oldcode = getCode (codeSize, false);
  77591. return firstcode;
  77592. }
  77593. else if (code == end_code)
  77594. {
  77595. if (dataBlockIsZero)
  77596. return -2;
  77597. unsigned char buf [260];
  77598. int n;
  77599. while ((n = readDataBlock (buf)) > 0)
  77600. {}
  77601. if (n != 0)
  77602. return -2;
  77603. }
  77604. incode = code;
  77605. if (code >= maxCode)
  77606. {
  77607. *sp++ = firstcode;
  77608. code = oldcode;
  77609. }
  77610. while (code >= clearCode)
  77611. {
  77612. *sp++ = table[1][code];
  77613. if (code == table[0][code])
  77614. return -2;
  77615. code = table[0][code];
  77616. }
  77617. *sp++ = firstcode = table[1][code];
  77618. if ((code = maxCode) < maxGifCode)
  77619. {
  77620. table[0][code] = oldcode;
  77621. table[1][code] = firstcode;
  77622. ++maxCode;
  77623. if ((maxCode >= maxCodeSize)
  77624. && (maxCodeSize < maxGifCode))
  77625. {
  77626. maxCodeSize <<= 1;
  77627. ++codeSize;
  77628. }
  77629. }
  77630. oldcode = incode;
  77631. if (sp > stack)
  77632. return *--sp;
  77633. }
  77634. return code;
  77635. }
  77636. int getCode (const int codeSize_, const bool initialise)
  77637. {
  77638. if (initialise)
  77639. {
  77640. currentBit = 0;
  77641. lastBit = 0;
  77642. finished = false;
  77643. return 0;
  77644. }
  77645. if ((currentBit + codeSize_) >= lastBit)
  77646. {
  77647. if (finished)
  77648. return -1;
  77649. buffer[0] = buffer [lastByteIndex - 2];
  77650. buffer[1] = buffer [lastByteIndex - 1];
  77651. const int n = readDataBlock (&buffer[2]);
  77652. if (n == 0)
  77653. finished = true;
  77654. lastByteIndex = 2 + n;
  77655. currentBit = (currentBit - lastBit) + 16;
  77656. lastBit = (2 + n) * 8 ;
  77657. }
  77658. int result = 0;
  77659. int i = currentBit;
  77660. for (int j = 0; j < codeSize_; ++j)
  77661. {
  77662. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77663. ++i;
  77664. }
  77665. currentBit += codeSize_;
  77666. return result;
  77667. }
  77668. bool readImage (const int interlace, const int transparent)
  77669. {
  77670. unsigned char c;
  77671. if (input.read (&c, 1) != 1
  77672. || readLZWByte (true, c) < 0)
  77673. return false;
  77674. if (transparent >= 0)
  77675. {
  77676. palette [transparent][0] = 0;
  77677. palette [transparent][1] = 0;
  77678. palette [transparent][2] = 0;
  77679. palette [transparent][3] = 0;
  77680. }
  77681. int index;
  77682. int xpos = 0, ypos = 0, pass = 0;
  77683. const Image::BitmapData destData (image, true);
  77684. uint8* p = destData.data;
  77685. const bool hasAlpha = image.hasAlphaChannel();
  77686. while ((index = readLZWByte (false, c)) >= 0)
  77687. {
  77688. const uint8* const paletteEntry = palette [index];
  77689. if (hasAlpha)
  77690. {
  77691. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  77692. paletteEntry[0],
  77693. paletteEntry[1],
  77694. paletteEntry[2]);
  77695. ((PixelARGB*) p)->premultiply();
  77696. }
  77697. else
  77698. {
  77699. ((PixelRGB*) p)->setARGB (0,
  77700. paletteEntry[0],
  77701. paletteEntry[1],
  77702. paletteEntry[2]);
  77703. }
  77704. p += destData.pixelStride;
  77705. ++xpos;
  77706. if (xpos == destData.width)
  77707. {
  77708. xpos = 0;
  77709. if (interlace)
  77710. {
  77711. switch (pass)
  77712. {
  77713. case 0:
  77714. case 1: ypos += 8; break;
  77715. case 2: ypos += 4; break;
  77716. case 3: ypos += 2; break;
  77717. }
  77718. while (ypos >= destData.height)
  77719. {
  77720. ++pass;
  77721. switch (pass)
  77722. {
  77723. case 1: ypos = 4; break;
  77724. case 2: ypos = 2; break;
  77725. case 3: ypos = 1; break;
  77726. default: return true;
  77727. }
  77728. }
  77729. }
  77730. else
  77731. {
  77732. ++ypos;
  77733. }
  77734. p = destData.getPixelPointer (xpos, ypos);
  77735. }
  77736. if (ypos >= destData.height)
  77737. break;
  77738. }
  77739. return true;
  77740. }
  77741. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  77742. JUCE_DECLARE_NON_COPYABLE (GIFLoader);
  77743. };
  77744. #endif
  77745. GIFImageFormat::GIFImageFormat() {}
  77746. GIFImageFormat::~GIFImageFormat() {}
  77747. const String GIFImageFormat::getFormatName() { return "GIF"; }
  77748. bool GIFImageFormat::canUnderstand (InputStream& in)
  77749. {
  77750. char header [4];
  77751. return (in.read (header, sizeof (header)) == sizeof (header))
  77752. && header[0] == 'G'
  77753. && header[1] == 'I'
  77754. && header[2] == 'F';
  77755. }
  77756. const Image GIFImageFormat::decodeImage (InputStream& in)
  77757. {
  77758. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77759. return juce_loadWithCoreImage (in);
  77760. #else
  77761. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  77762. return loader->image;
  77763. #endif
  77764. }
  77765. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  77766. {
  77767. jassertfalse; // writing isn't implemented for GIFs!
  77768. return false;
  77769. }
  77770. END_JUCE_NAMESPACE
  77771. /*** End of inlined file: juce_GIFLoader.cpp ***/
  77772. #endif
  77773. //==============================================================================
  77774. // some files include lots of library code, so leave them to the end to avoid cluttering
  77775. // up the build for the clean files.
  77776. #if JUCE_BUILD_CORE
  77777. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  77778. namespace zlibNamespace
  77779. {
  77780. #if JUCE_INCLUDE_ZLIB_CODE
  77781. #undef OS_CODE
  77782. #undef fdopen
  77783. /*** Start of inlined file: zlib.h ***/
  77784. #ifndef ZLIB_H
  77785. #define ZLIB_H
  77786. /*** Start of inlined file: zconf.h ***/
  77787. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  77788. #ifndef ZCONF_H
  77789. #define ZCONF_H
  77790. // *** Just a few hacks here to make it compile nicely with Juce..
  77791. #define Z_PREFIX 1
  77792. #undef __MACTYPES__
  77793. #ifdef _MSC_VER
  77794. #pragma warning (disable : 4131 4127 4244 4267)
  77795. #endif
  77796. /*
  77797. * If you *really* need a unique prefix for all types and library functions,
  77798. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  77799. */
  77800. #ifdef Z_PREFIX
  77801. # define deflateInit_ z_deflateInit_
  77802. # define deflate z_deflate
  77803. # define deflateEnd z_deflateEnd
  77804. # define inflateInit_ z_inflateInit_
  77805. # define inflate z_inflate
  77806. # define inflateEnd z_inflateEnd
  77807. # define inflatePrime z_inflatePrime
  77808. # define inflateGetHeader z_inflateGetHeader
  77809. # define adler32_combine z_adler32_combine
  77810. # define crc32_combine z_crc32_combine
  77811. # define deflateInit2_ z_deflateInit2_
  77812. # define deflateSetDictionary z_deflateSetDictionary
  77813. # define deflateCopy z_deflateCopy
  77814. # define deflateReset z_deflateReset
  77815. # define deflateParams z_deflateParams
  77816. # define deflateBound z_deflateBound
  77817. # define deflatePrime z_deflatePrime
  77818. # define inflateInit2_ z_inflateInit2_
  77819. # define inflateSetDictionary z_inflateSetDictionary
  77820. # define inflateSync z_inflateSync
  77821. # define inflateSyncPoint z_inflateSyncPoint
  77822. # define inflateCopy z_inflateCopy
  77823. # define inflateReset z_inflateReset
  77824. # define inflateBack z_inflateBack
  77825. # define inflateBackEnd z_inflateBackEnd
  77826. # define compress z_compress
  77827. # define compress2 z_compress2
  77828. # define compressBound z_compressBound
  77829. # define uncompress z_uncompress
  77830. # define adler32 z_adler32
  77831. # define crc32 z_crc32
  77832. # define get_crc_table z_get_crc_table
  77833. # define zError z_zError
  77834. # define alloc_func z_alloc_func
  77835. # define free_func z_free_func
  77836. # define in_func z_in_func
  77837. # define out_func z_out_func
  77838. # define Byte z_Byte
  77839. # define uInt z_uInt
  77840. # define uLong z_uLong
  77841. # define Bytef z_Bytef
  77842. # define charf z_charf
  77843. # define intf z_intf
  77844. # define uIntf z_uIntf
  77845. # define uLongf z_uLongf
  77846. # define voidpf z_voidpf
  77847. # define voidp z_voidp
  77848. #endif
  77849. #if defined(__MSDOS__) && !defined(MSDOS)
  77850. # define MSDOS
  77851. #endif
  77852. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  77853. # define OS2
  77854. #endif
  77855. #if defined(_WINDOWS) && !defined(WINDOWS)
  77856. # define WINDOWS
  77857. #endif
  77858. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  77859. # ifndef WIN32
  77860. # define WIN32
  77861. # endif
  77862. #endif
  77863. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  77864. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  77865. # ifndef SYS16BIT
  77866. # define SYS16BIT
  77867. # endif
  77868. # endif
  77869. #endif
  77870. /*
  77871. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  77872. * than 64k bytes at a time (needed on systems with 16-bit int).
  77873. */
  77874. #ifdef SYS16BIT
  77875. # define MAXSEG_64K
  77876. #endif
  77877. #ifdef MSDOS
  77878. # define UNALIGNED_OK
  77879. #endif
  77880. #ifdef __STDC_VERSION__
  77881. # ifndef STDC
  77882. # define STDC
  77883. # endif
  77884. # if __STDC_VERSION__ >= 199901L
  77885. # ifndef STDC99
  77886. # define STDC99
  77887. # endif
  77888. # endif
  77889. #endif
  77890. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  77891. # define STDC
  77892. #endif
  77893. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  77894. # define STDC
  77895. #endif
  77896. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  77897. # define STDC
  77898. #endif
  77899. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  77900. # define STDC
  77901. #endif
  77902. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  77903. # define STDC
  77904. #endif
  77905. #ifndef STDC
  77906. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  77907. # define const /* note: need a more gentle solution here */
  77908. # endif
  77909. #endif
  77910. /* Some Mac compilers merge all .h files incorrectly: */
  77911. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  77912. # define NO_DUMMY_DECL
  77913. #endif
  77914. /* Maximum value for memLevel in deflateInit2 */
  77915. #ifndef MAX_MEM_LEVEL
  77916. # ifdef MAXSEG_64K
  77917. # define MAX_MEM_LEVEL 8
  77918. # else
  77919. # define MAX_MEM_LEVEL 9
  77920. # endif
  77921. #endif
  77922. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  77923. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  77924. * created by gzip. (Files created by minigzip can still be extracted by
  77925. * gzip.)
  77926. */
  77927. #ifndef MAX_WBITS
  77928. # define MAX_WBITS 15 /* 32K LZ77 window */
  77929. #endif
  77930. /* The memory requirements for deflate are (in bytes):
  77931. (1 << (windowBits+2)) + (1 << (memLevel+9))
  77932. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  77933. plus a few kilobytes for small objects. For example, if you want to reduce
  77934. the default memory requirements from 256K to 128K, compile with
  77935. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  77936. Of course this will generally degrade compression (there's no free lunch).
  77937. The memory requirements for inflate are (in bytes) 1 << windowBits
  77938. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  77939. for small objects.
  77940. */
  77941. /* Type declarations */
  77942. #ifndef OF /* function prototypes */
  77943. # ifdef STDC
  77944. # define OF(args) args
  77945. # else
  77946. # define OF(args) ()
  77947. # endif
  77948. #endif
  77949. /* The following definitions for FAR are needed only for MSDOS mixed
  77950. * model programming (small or medium model with some far allocations).
  77951. * This was tested only with MSC; for other MSDOS compilers you may have
  77952. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  77953. * just define FAR to be empty.
  77954. */
  77955. #ifdef SYS16BIT
  77956. # if defined(M_I86SM) || defined(M_I86MM)
  77957. /* MSC small or medium model */
  77958. # define SMALL_MEDIUM
  77959. # ifdef _MSC_VER
  77960. # define FAR _far
  77961. # else
  77962. # define FAR far
  77963. # endif
  77964. # endif
  77965. # if (defined(__SMALL__) || defined(__MEDIUM__))
  77966. /* Turbo C small or medium model */
  77967. # define SMALL_MEDIUM
  77968. # ifdef __BORLANDC__
  77969. # define FAR _far
  77970. # else
  77971. # define FAR far
  77972. # endif
  77973. # endif
  77974. #endif
  77975. #if defined(WINDOWS) || defined(WIN32)
  77976. /* If building or using zlib as a DLL, define ZLIB_DLL.
  77977. * This is not mandatory, but it offers a little performance increase.
  77978. */
  77979. # ifdef ZLIB_DLL
  77980. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  77981. # ifdef ZLIB_INTERNAL
  77982. # define ZEXTERN extern __declspec(dllexport)
  77983. # else
  77984. # define ZEXTERN extern __declspec(dllimport)
  77985. # endif
  77986. # endif
  77987. # endif /* ZLIB_DLL */
  77988. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  77989. * define ZLIB_WINAPI.
  77990. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  77991. */
  77992. # ifdef ZLIB_WINAPI
  77993. # ifdef FAR
  77994. # undef FAR
  77995. # endif
  77996. # include <windows.h>
  77997. /* No need for _export, use ZLIB.DEF instead. */
  77998. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  77999. # define ZEXPORT WINAPI
  78000. # ifdef WIN32
  78001. # define ZEXPORTVA WINAPIV
  78002. # else
  78003. # define ZEXPORTVA FAR CDECL
  78004. # endif
  78005. # endif
  78006. #endif
  78007. #if defined (__BEOS__)
  78008. # ifdef ZLIB_DLL
  78009. # ifdef ZLIB_INTERNAL
  78010. # define ZEXPORT __declspec(dllexport)
  78011. # define ZEXPORTVA __declspec(dllexport)
  78012. # else
  78013. # define ZEXPORT __declspec(dllimport)
  78014. # define ZEXPORTVA __declspec(dllimport)
  78015. # endif
  78016. # endif
  78017. #endif
  78018. #ifndef ZEXTERN
  78019. # define ZEXTERN extern
  78020. #endif
  78021. #ifndef ZEXPORT
  78022. # define ZEXPORT
  78023. #endif
  78024. #ifndef ZEXPORTVA
  78025. # define ZEXPORTVA
  78026. #endif
  78027. #ifndef FAR
  78028. # define FAR
  78029. #endif
  78030. #if !defined(__MACTYPES__)
  78031. typedef unsigned char Byte; /* 8 bits */
  78032. #endif
  78033. typedef unsigned int uInt; /* 16 bits or more */
  78034. typedef unsigned long uLong; /* 32 bits or more */
  78035. #ifdef SMALL_MEDIUM
  78036. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78037. # define Bytef Byte FAR
  78038. #else
  78039. typedef Byte FAR Bytef;
  78040. #endif
  78041. typedef char FAR charf;
  78042. typedef int FAR intf;
  78043. typedef uInt FAR uIntf;
  78044. typedef uLong FAR uLongf;
  78045. #ifdef STDC
  78046. typedef void const *voidpc;
  78047. typedef void FAR *voidpf;
  78048. typedef void *voidp;
  78049. #else
  78050. typedef Byte const *voidpc;
  78051. typedef Byte FAR *voidpf;
  78052. typedef Byte *voidp;
  78053. #endif
  78054. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78055. # include <sys/types.h> /* for off_t */
  78056. # include <unistd.h> /* for SEEK_* and off_t */
  78057. # ifdef VMS
  78058. # include <unixio.h> /* for off_t */
  78059. # endif
  78060. # define z_off_t off_t
  78061. #endif
  78062. #ifndef SEEK_SET
  78063. # define SEEK_SET 0 /* Seek from beginning of file. */
  78064. # define SEEK_CUR 1 /* Seek from current position. */
  78065. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78066. #endif
  78067. #ifndef z_off_t
  78068. # define z_off_t long
  78069. #endif
  78070. #if defined(__OS400__)
  78071. # define NO_vsnprintf
  78072. #endif
  78073. #if defined(__MVS__)
  78074. # define NO_vsnprintf
  78075. # ifdef FAR
  78076. # undef FAR
  78077. # endif
  78078. #endif
  78079. /* MVS linker does not support external names larger than 8 bytes */
  78080. #if defined(__MVS__)
  78081. # pragma map(deflateInit_,"DEIN")
  78082. # pragma map(deflateInit2_,"DEIN2")
  78083. # pragma map(deflateEnd,"DEEND")
  78084. # pragma map(deflateBound,"DEBND")
  78085. # pragma map(inflateInit_,"ININ")
  78086. # pragma map(inflateInit2_,"ININ2")
  78087. # pragma map(inflateEnd,"INEND")
  78088. # pragma map(inflateSync,"INSY")
  78089. # pragma map(inflateSetDictionary,"INSEDI")
  78090. # pragma map(compressBound,"CMBND")
  78091. # pragma map(inflate_table,"INTABL")
  78092. # pragma map(inflate_fast,"INFA")
  78093. # pragma map(inflate_copyright,"INCOPY")
  78094. #endif
  78095. #endif /* ZCONF_H */
  78096. /*** End of inlined file: zconf.h ***/
  78097. #ifdef __cplusplus
  78098. //extern "C" {
  78099. #endif
  78100. #define ZLIB_VERSION "1.2.3"
  78101. #define ZLIB_VERNUM 0x1230
  78102. /*
  78103. The 'zlib' compression library provides in-memory compression and
  78104. decompression functions, including integrity checks of the uncompressed
  78105. data. This version of the library supports only one compression method
  78106. (deflation) but other algorithms will be added later and will have the same
  78107. stream interface.
  78108. Compression can be done in a single step if the buffers are large
  78109. enough (for example if an input file is mmap'ed), or can be done by
  78110. repeated calls of the compression function. In the latter case, the
  78111. application must provide more input and/or consume the output
  78112. (providing more output space) before each call.
  78113. The compressed data format used by default by the in-memory functions is
  78114. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78115. around a deflate stream, which is itself documented in RFC 1951.
  78116. The library also supports reading and writing files in gzip (.gz) format
  78117. with an interface similar to that of stdio using the functions that start
  78118. with "gz". The gzip format is different from the zlib format. gzip is a
  78119. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78120. This library can optionally read and write gzip streams in memory as well.
  78121. The zlib format was designed to be compact and fast for use in memory
  78122. and on communications channels. The gzip format was designed for single-
  78123. file compression on file systems, has a larger header than zlib to maintain
  78124. directory information, and uses a different, slower check method than zlib.
  78125. The library does not install any signal handler. The decoder checks
  78126. the consistency of the compressed data, so the library should never
  78127. crash even in case of corrupted input.
  78128. */
  78129. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78130. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78131. struct internal_state;
  78132. typedef struct z_stream_s {
  78133. Bytef *next_in; /* next input byte */
  78134. uInt avail_in; /* number of bytes available at next_in */
  78135. uLong total_in; /* total nb of input bytes read so far */
  78136. Bytef *next_out; /* next output byte should be put there */
  78137. uInt avail_out; /* remaining free space at next_out */
  78138. uLong total_out; /* total nb of bytes output so far */
  78139. char *msg; /* last error message, NULL if no error */
  78140. struct internal_state FAR *state; /* not visible by applications */
  78141. alloc_func zalloc; /* used to allocate the internal state */
  78142. free_func zfree; /* used to free the internal state */
  78143. voidpf opaque; /* private data object passed to zalloc and zfree */
  78144. int data_type; /* best guess about the data type: binary or text */
  78145. uLong adler; /* adler32 value of the uncompressed data */
  78146. uLong reserved; /* reserved for future use */
  78147. } z_stream;
  78148. typedef z_stream FAR *z_streamp;
  78149. /*
  78150. gzip header information passed to and from zlib routines. See RFC 1952
  78151. for more details on the meanings of these fields.
  78152. */
  78153. typedef struct gz_header_s {
  78154. int text; /* true if compressed data believed to be text */
  78155. uLong time; /* modification time */
  78156. int xflags; /* extra flags (not used when writing a gzip file) */
  78157. int os; /* operating system */
  78158. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78159. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78160. uInt extra_max; /* space at extra (only when reading header) */
  78161. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78162. uInt name_max; /* space at name (only when reading header) */
  78163. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78164. uInt comm_max; /* space at comment (only when reading header) */
  78165. int hcrc; /* true if there was or will be a header crc */
  78166. int done; /* true when done reading gzip header (not used
  78167. when writing a gzip file) */
  78168. } gz_header;
  78169. typedef gz_header FAR *gz_headerp;
  78170. /*
  78171. The application must update next_in and avail_in when avail_in has
  78172. dropped to zero. It must update next_out and avail_out when avail_out
  78173. has dropped to zero. The application must initialize zalloc, zfree and
  78174. opaque before calling the init function. All other fields are set by the
  78175. compression library and must not be updated by the application.
  78176. The opaque value provided by the application will be passed as the first
  78177. parameter for calls of zalloc and zfree. This can be useful for custom
  78178. memory management. The compression library attaches no meaning to the
  78179. opaque value.
  78180. zalloc must return Z_NULL if there is not enough memory for the object.
  78181. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78182. thread safe.
  78183. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78184. exactly 65536 bytes, but will not be required to allocate more than this
  78185. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78186. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78187. have their offset normalized to zero. The default allocation function
  78188. provided by this library ensures this (see zutil.c). To reduce memory
  78189. requirements and avoid any allocation of 64K objects, at the expense of
  78190. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78191. The fields total_in and total_out can be used for statistics or
  78192. progress reports. After compression, total_in holds the total size of
  78193. the uncompressed data and may be saved for use in the decompressor
  78194. (particularly if the decompressor wants to decompress everything in
  78195. a single step).
  78196. */
  78197. /* constants */
  78198. #define Z_NO_FLUSH 0
  78199. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78200. #define Z_SYNC_FLUSH 2
  78201. #define Z_FULL_FLUSH 3
  78202. #define Z_FINISH 4
  78203. #define Z_BLOCK 5
  78204. /* Allowed flush values; see deflate() and inflate() below for details */
  78205. #define Z_OK 0
  78206. #define Z_STREAM_END 1
  78207. #define Z_NEED_DICT 2
  78208. #define Z_ERRNO (-1)
  78209. #define Z_STREAM_ERROR (-2)
  78210. #define Z_DATA_ERROR (-3)
  78211. #define Z_MEM_ERROR (-4)
  78212. #define Z_BUF_ERROR (-5)
  78213. #define Z_VERSION_ERROR (-6)
  78214. /* Return codes for the compression/decompression functions. Negative
  78215. * values are errors, positive values are used for special but normal events.
  78216. */
  78217. #define Z_NO_COMPRESSION 0
  78218. #define Z_BEST_SPEED 1
  78219. #define Z_BEST_COMPRESSION 9
  78220. #define Z_DEFAULT_COMPRESSION (-1)
  78221. /* compression levels */
  78222. #define Z_FILTERED 1
  78223. #define Z_HUFFMAN_ONLY 2
  78224. #define Z_RLE 3
  78225. #define Z_FIXED 4
  78226. #define Z_DEFAULT_STRATEGY 0
  78227. /* compression strategy; see deflateInit2() below for details */
  78228. #define Z_BINARY 0
  78229. #define Z_TEXT 1
  78230. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78231. #define Z_UNKNOWN 2
  78232. /* Possible values of the data_type field (though see inflate()) */
  78233. #define Z_DEFLATED 8
  78234. /* The deflate compression method (the only one supported in this version) */
  78235. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78236. #define zlib_version zlibVersion()
  78237. /* for compatibility with versions < 1.0.2 */
  78238. /* basic functions */
  78239. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78240. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78241. If the first character differs, the library code actually used is
  78242. not compatible with the zlib.h header file used by the application.
  78243. This check is automatically made by deflateInit and inflateInit.
  78244. */
  78245. /*
  78246. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78247. Initializes the internal stream state for compression. The fields
  78248. zalloc, zfree and opaque must be initialized before by the caller.
  78249. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78250. use default allocation functions.
  78251. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78252. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78253. all (the input data is simply copied a block at a time).
  78254. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78255. compression (currently equivalent to level 6).
  78256. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78257. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78258. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78259. with the version assumed by the caller (ZLIB_VERSION).
  78260. msg is set to null if there is no error message. deflateInit does not
  78261. perform any compression: this will be done by deflate().
  78262. */
  78263. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78264. /*
  78265. deflate compresses as much data as possible, and stops when the input
  78266. buffer becomes empty or the output buffer becomes full. It may introduce some
  78267. output latency (reading input without producing any output) except when
  78268. forced to flush.
  78269. The detailed semantics are as follows. deflate performs one or both of the
  78270. following actions:
  78271. - Compress more input starting at next_in and update next_in and avail_in
  78272. accordingly. If not all input can be processed (because there is not
  78273. enough room in the output buffer), next_in and avail_in are updated and
  78274. processing will resume at this point for the next call of deflate().
  78275. - Provide more output starting at next_out and update next_out and avail_out
  78276. accordingly. This action is forced if the parameter flush is non zero.
  78277. Forcing flush frequently degrades the compression ratio, so this parameter
  78278. should be set only when necessary (in interactive applications).
  78279. Some output may be provided even if flush is not set.
  78280. Before the call of deflate(), the application should ensure that at least
  78281. one of the actions is possible, by providing more input and/or consuming
  78282. more output, and updating avail_in or avail_out accordingly; avail_out
  78283. should never be zero before the call. The application can consume the
  78284. compressed output when it wants, for example when the output buffer is full
  78285. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78286. and with zero avail_out, it must be called again after making room in the
  78287. output buffer because there might be more output pending.
  78288. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78289. decide how much data to accumualte before producing output, in order to
  78290. maximize compression.
  78291. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78292. flushed to the output buffer and the output is aligned on a byte boundary, so
  78293. that the decompressor can get all input data available so far. (In particular
  78294. avail_in is zero after the call if enough output space has been provided
  78295. before the call.) Flushing may degrade compression for some compression
  78296. algorithms and so it should be used only when necessary.
  78297. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78298. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78299. restart from this point if previous compressed data has been damaged or if
  78300. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78301. compression.
  78302. If deflate returns with avail_out == 0, this function must be called again
  78303. with the same value of the flush parameter and more output space (updated
  78304. avail_out), until the flush is complete (deflate returns with non-zero
  78305. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78306. avail_out is greater than six to avoid repeated flush markers due to
  78307. avail_out == 0 on return.
  78308. If the parameter flush is set to Z_FINISH, pending input is processed,
  78309. pending output is flushed and deflate returns with Z_STREAM_END if there
  78310. was enough output space; if deflate returns with Z_OK, this function must be
  78311. called again with Z_FINISH and more output space (updated avail_out) but no
  78312. more input data, until it returns with Z_STREAM_END or an error. After
  78313. deflate has returned Z_STREAM_END, the only possible operations on the
  78314. stream are deflateReset or deflateEnd.
  78315. Z_FINISH can be used immediately after deflateInit if all the compression
  78316. is to be done in a single step. In this case, avail_out must be at least
  78317. the value returned by deflateBound (see below). If deflate does not return
  78318. Z_STREAM_END, then it must be called again as described above.
  78319. deflate() sets strm->adler to the adler32 checksum of all input read
  78320. so far (that is, total_in bytes).
  78321. deflate() may update strm->data_type if it can make a good guess about
  78322. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78323. binary. This field is only for information purposes and does not affect
  78324. the compression algorithm in any manner.
  78325. deflate() returns Z_OK if some progress has been made (more input
  78326. processed or more output produced), Z_STREAM_END if all input has been
  78327. consumed and all output has been produced (only when flush is set to
  78328. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78329. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78330. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78331. fatal, and deflate() can be called again with more input and more output
  78332. space to continue compressing.
  78333. */
  78334. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78335. /*
  78336. All dynamically allocated data structures for this stream are freed.
  78337. This function discards any unprocessed input and does not flush any
  78338. pending output.
  78339. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78340. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78341. prematurely (some input or output was discarded). In the error case,
  78342. msg may be set but then points to a static string (which must not be
  78343. deallocated).
  78344. */
  78345. /*
  78346. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78347. Initializes the internal stream state for decompression. The fields
  78348. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78349. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78350. value depends on the compression method), inflateInit determines the
  78351. compression method from the zlib header and allocates all data structures
  78352. accordingly; otherwise the allocation will be deferred to the first call of
  78353. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78354. use default allocation functions.
  78355. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78356. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78357. version assumed by the caller. msg is set to null if there is no error
  78358. message. inflateInit does not perform any decompression apart from reading
  78359. the zlib header if present: this will be done by inflate(). (So next_in and
  78360. avail_in may be modified, but next_out and avail_out are unchanged.)
  78361. */
  78362. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78363. /*
  78364. inflate decompresses as much data as possible, and stops when the input
  78365. buffer becomes empty or the output buffer becomes full. It may introduce
  78366. some output latency (reading input without producing any output) except when
  78367. forced to flush.
  78368. The detailed semantics are as follows. inflate performs one or both of the
  78369. following actions:
  78370. - Decompress more input starting at next_in and update next_in and avail_in
  78371. accordingly. If not all input can be processed (because there is not
  78372. enough room in the output buffer), next_in is updated and processing
  78373. will resume at this point for the next call of inflate().
  78374. - Provide more output starting at next_out and update next_out and avail_out
  78375. accordingly. inflate() provides as much output as possible, until there
  78376. is no more input data or no more space in the output buffer (see below
  78377. about the flush parameter).
  78378. Before the call of inflate(), the application should ensure that at least
  78379. one of the actions is possible, by providing more input and/or consuming
  78380. more output, and updating the next_* and avail_* values accordingly.
  78381. The application can consume the uncompressed output when it wants, for
  78382. example when the output buffer is full (avail_out == 0), or after each
  78383. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78384. must be called again after making room in the output buffer because there
  78385. might be more output pending.
  78386. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78387. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78388. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78389. if and when it gets to the next deflate block boundary. When decoding the
  78390. zlib or gzip format, this will cause inflate() to return immediately after
  78391. the header and before the first block. When doing a raw inflate, inflate()
  78392. will go ahead and process the first block, and will return when it gets to
  78393. the end of that block, or when it runs out of data.
  78394. The Z_BLOCK option assists in appending to or combining deflate streams.
  78395. Also to assist in this, on return inflate() will set strm->data_type to the
  78396. number of unused bits in the last byte taken from strm->next_in, plus 64
  78397. if inflate() is currently decoding the last block in the deflate stream,
  78398. plus 128 if inflate() returned immediately after decoding an end-of-block
  78399. code or decoding the complete header up to just before the first byte of the
  78400. deflate stream. The end-of-block will not be indicated until all of the
  78401. uncompressed data from that block has been written to strm->next_out. The
  78402. number of unused bits may in general be greater than seven, except when
  78403. bit 7 of data_type is set, in which case the number of unused bits will be
  78404. less than eight.
  78405. inflate() should normally be called until it returns Z_STREAM_END or an
  78406. error. However if all decompression is to be performed in a single step
  78407. (a single call of inflate), the parameter flush should be set to
  78408. Z_FINISH. In this case all pending input is processed and all pending
  78409. output is flushed; avail_out must be large enough to hold all the
  78410. uncompressed data. (The size of the uncompressed data may have been saved
  78411. by the compressor for this purpose.) The next operation on this stream must
  78412. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78413. is never required, but can be used to inform inflate that a faster approach
  78414. may be used for the single inflate() call.
  78415. In this implementation, inflate() always flushes as much output as
  78416. possible to the output buffer, and always uses the faster approach on the
  78417. first call. So the only effect of the flush parameter in this implementation
  78418. is on the return value of inflate(), as noted below, or when it returns early
  78419. because Z_BLOCK is used.
  78420. If a preset dictionary is needed after this call (see inflateSetDictionary
  78421. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78422. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78423. strm->adler to the adler32 checksum of all output produced so far (that is,
  78424. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78425. below. At the end of the stream, inflate() checks that its computed adler32
  78426. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78427. only if the checksum is correct.
  78428. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78429. deflate data. The header type is detected automatically. Any information
  78430. contained in the gzip header is not retained, so applications that need that
  78431. information should instead use raw inflate, see inflateInit2() below, or
  78432. inflateBack() and perform their own processing of the gzip header and
  78433. trailer.
  78434. inflate() returns Z_OK if some progress has been made (more input processed
  78435. or more output produced), Z_STREAM_END if the end of the compressed data has
  78436. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78437. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78438. corrupted (input stream not conforming to the zlib format or incorrect check
  78439. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78440. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78441. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78442. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78443. inflate() can be called again with more input and more output space to
  78444. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78445. call inflateSync() to look for a good compression block if a partial recovery
  78446. of the data is desired.
  78447. */
  78448. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78449. /*
  78450. All dynamically allocated data structures for this stream are freed.
  78451. This function discards any unprocessed input and does not flush any
  78452. pending output.
  78453. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78454. was inconsistent. In the error case, msg may be set but then points to a
  78455. static string (which must not be deallocated).
  78456. */
  78457. /* Advanced functions */
  78458. /*
  78459. The following functions are needed only in some special applications.
  78460. */
  78461. /*
  78462. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78463. int level,
  78464. int method,
  78465. int windowBits,
  78466. int memLevel,
  78467. int strategy));
  78468. This is another version of deflateInit with more compression options. The
  78469. fields next_in, zalloc, zfree and opaque must be initialized before by
  78470. the caller.
  78471. The method parameter is the compression method. It must be Z_DEFLATED in
  78472. this version of the library.
  78473. The windowBits parameter is the base two logarithm of the window size
  78474. (the size of the history buffer). It should be in the range 8..15 for this
  78475. version of the library. Larger values of this parameter result in better
  78476. compression at the expense of memory usage. The default value is 15 if
  78477. deflateInit is used instead.
  78478. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78479. determines the window size. deflate() will then generate raw deflate data
  78480. with no zlib header or trailer, and will not compute an adler32 check value.
  78481. windowBits can also be greater than 15 for optional gzip encoding. Add
  78482. 16 to windowBits to write a simple gzip header and trailer around the
  78483. compressed data instead of a zlib wrapper. The gzip header will have no
  78484. file name, no extra data, no comment, no modification time (set to zero),
  78485. no header crc, and the operating system will be set to 255 (unknown). If a
  78486. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78487. The memLevel parameter specifies how much memory should be allocated
  78488. for the internal compression state. memLevel=1 uses minimum memory but
  78489. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78490. for optimal speed. The default value is 8. See zconf.h for total memory
  78491. usage as a function of windowBits and memLevel.
  78492. The strategy parameter is used to tune the compression algorithm. Use the
  78493. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78494. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78495. string match), or Z_RLE to limit match distances to one (run-length
  78496. encoding). Filtered data consists mostly of small values with a somewhat
  78497. random distribution. In this case, the compression algorithm is tuned to
  78498. compress them better. The effect of Z_FILTERED is to force more Huffman
  78499. coding and less string matching; it is somewhat intermediate between
  78500. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78501. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78502. parameter only affects the compression ratio but not the correctness of the
  78503. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78504. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78505. applications.
  78506. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78507. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78508. method). msg is set to null if there is no error message. deflateInit2 does
  78509. not perform any compression: this will be done by deflate().
  78510. */
  78511. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78512. const Bytef *dictionary,
  78513. uInt dictLength));
  78514. /*
  78515. Initializes the compression dictionary from the given byte sequence
  78516. without producing any compressed output. This function must be called
  78517. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78518. call of deflate. The compressor and decompressor must use exactly the same
  78519. dictionary (see inflateSetDictionary).
  78520. The dictionary should consist of strings (byte sequences) that are likely
  78521. to be encountered later in the data to be compressed, with the most commonly
  78522. used strings preferably put towards the end of the dictionary. Using a
  78523. dictionary is most useful when the data to be compressed is short and can be
  78524. predicted with good accuracy; the data can then be compressed better than
  78525. with the default empty dictionary.
  78526. Depending on the size of the compression data structures selected by
  78527. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78528. discarded, for example if the dictionary is larger than the window size in
  78529. deflate or deflate2. Thus the strings most likely to be useful should be
  78530. put at the end of the dictionary, not at the front. In addition, the
  78531. current implementation of deflate will use at most the window size minus
  78532. 262 bytes of the provided dictionary.
  78533. Upon return of this function, strm->adler is set to the adler32 value
  78534. of the dictionary; the decompressor may later use this value to determine
  78535. which dictionary has been used by the compressor. (The adler32 value
  78536. applies to the whole dictionary even if only a subset of the dictionary is
  78537. actually used by the compressor.) If a raw deflate was requested, then the
  78538. adler32 value is not computed and strm->adler is not set.
  78539. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78540. parameter is invalid (such as NULL dictionary) or the stream state is
  78541. inconsistent (for example if deflate has already been called for this stream
  78542. or if the compression method is bsort). deflateSetDictionary does not
  78543. perform any compression: this will be done by deflate().
  78544. */
  78545. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78546. z_streamp source));
  78547. /*
  78548. Sets the destination stream as a complete copy of the source stream.
  78549. This function can be useful when several compression strategies will be
  78550. tried, for example when there are several ways of pre-processing the input
  78551. data with a filter. The streams that will be discarded should then be freed
  78552. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78553. compression state which can be quite large, so this strategy is slow and
  78554. can consume lots of memory.
  78555. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78556. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78557. (such as zalloc being NULL). msg is left unchanged in both source and
  78558. destination.
  78559. */
  78560. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78561. /*
  78562. This function is equivalent to deflateEnd followed by deflateInit,
  78563. but does not free and reallocate all the internal compression state.
  78564. The stream will keep the same compression level and any other attributes
  78565. that may have been set by deflateInit2.
  78566. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78567. stream state was inconsistent (such as zalloc or state being NULL).
  78568. */
  78569. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78570. int level,
  78571. int strategy));
  78572. /*
  78573. Dynamically update the compression level and compression strategy. The
  78574. interpretation of level and strategy is as in deflateInit2. This can be
  78575. used to switch between compression and straight copy of the input data, or
  78576. to switch to a different kind of input data requiring a different
  78577. strategy. If the compression level is changed, the input available so far
  78578. is compressed with the old level (and may be flushed); the new level will
  78579. take effect only at the next call of deflate().
  78580. Before the call of deflateParams, the stream state must be set as for
  78581. a call of deflate(), since the currently available input may have to
  78582. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78583. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78584. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78585. if strm->avail_out was zero.
  78586. */
  78587. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78588. int good_length,
  78589. int max_lazy,
  78590. int nice_length,
  78591. int max_chain));
  78592. /*
  78593. Fine tune deflate's internal compression parameters. This should only be
  78594. used by someone who understands the algorithm used by zlib's deflate for
  78595. searching for the best matching string, and even then only by the most
  78596. fanatic optimizer trying to squeeze out the last compressed bit for their
  78597. specific input data. Read the deflate.c source code for the meaning of the
  78598. max_lazy, good_length, nice_length, and max_chain parameters.
  78599. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78600. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78601. */
  78602. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78603. uLong sourceLen));
  78604. /*
  78605. deflateBound() returns an upper bound on the compressed size after
  78606. deflation of sourceLen bytes. It must be called after deflateInit()
  78607. or deflateInit2(). This would be used to allocate an output buffer
  78608. for deflation in a single pass, and so would be called before deflate().
  78609. */
  78610. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78611. int bits,
  78612. int value));
  78613. /*
  78614. deflatePrime() inserts bits in the deflate output stream. The intent
  78615. is that this function is used to start off the deflate output with the
  78616. bits leftover from a previous deflate stream when appending to it. As such,
  78617. this function can only be used for raw deflate, and must be used before the
  78618. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78619. less than or equal to 16, and that many of the least significant bits of
  78620. value will be inserted in the output.
  78621. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78622. stream state was inconsistent.
  78623. */
  78624. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78625. gz_headerp head));
  78626. /*
  78627. deflateSetHeader() provides gzip header information for when a gzip
  78628. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78629. after deflateInit2() or deflateReset() and before the first call of
  78630. deflate(). The text, time, os, extra field, name, and comment information
  78631. in the provided gz_header structure are written to the gzip header (xflag is
  78632. ignored -- the extra flags are set according to the compression level). The
  78633. caller must assure that, if not Z_NULL, name and comment are terminated with
  78634. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78635. available there. If hcrc is true, a gzip header crc is included. Note that
  78636. the current versions of the command-line version of gzip (up through version
  78637. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78638. gzip file" and give up.
  78639. If deflateSetHeader is not used, the default gzip header has text false,
  78640. the time set to zero, and os set to 255, with no extra, name, or comment
  78641. fields. The gzip header is returned to the default state by deflateReset().
  78642. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78643. stream state was inconsistent.
  78644. */
  78645. /*
  78646. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78647. int windowBits));
  78648. This is another version of inflateInit with an extra parameter. The
  78649. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78650. before by the caller.
  78651. The windowBits parameter is the base two logarithm of the maximum window
  78652. size (the size of the history buffer). It should be in the range 8..15 for
  78653. this version of the library. The default value is 15 if inflateInit is used
  78654. instead. windowBits must be greater than or equal to the windowBits value
  78655. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78656. deflateInit2() was not used. If a compressed stream with a larger window
  78657. size is given as input, inflate() will return with the error code
  78658. Z_DATA_ERROR instead of trying to allocate a larger window.
  78659. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78660. determines the window size. inflate() will then process raw deflate data,
  78661. not looking for a zlib or gzip header, not generating a check value, and not
  78662. looking for any check values for comparison at the end of the stream. This
  78663. is for use with other formats that use the deflate compressed data format
  78664. such as zip. Those formats provide their own check values. If a custom
  78665. format is developed using the raw deflate format for compressed data, it is
  78666. recommended that a check value such as an adler32 or a crc32 be applied to
  78667. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  78668. most applications, the zlib format should be used as is. Note that comments
  78669. above on the use in deflateInit2() applies to the magnitude of windowBits.
  78670. windowBits can also be greater than 15 for optional gzip decoding. Add
  78671. 32 to windowBits to enable zlib and gzip decoding with automatic header
  78672. detection, or add 16 to decode only the gzip format (the zlib format will
  78673. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  78674. a crc32 instead of an adler32.
  78675. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78676. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  78677. is set to null if there is no error message. inflateInit2 does not perform
  78678. any decompression apart from reading the zlib header if present: this will
  78679. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  78680. and avail_out are unchanged.)
  78681. */
  78682. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  78683. const Bytef *dictionary,
  78684. uInt dictLength));
  78685. /*
  78686. Initializes the decompression dictionary from the given uncompressed byte
  78687. sequence. This function must be called immediately after a call of inflate,
  78688. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  78689. can be determined from the adler32 value returned by that call of inflate.
  78690. The compressor and decompressor must use exactly the same dictionary (see
  78691. deflateSetDictionary). For raw inflate, this function can be called
  78692. immediately after inflateInit2() or inflateReset() and before any call of
  78693. inflate() to set the dictionary. The application must insure that the
  78694. dictionary that was used for compression is provided.
  78695. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  78696. parameter is invalid (such as NULL dictionary) or the stream state is
  78697. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  78698. expected one (incorrect adler32 value). inflateSetDictionary does not
  78699. perform any decompression: this will be done by subsequent calls of
  78700. inflate().
  78701. */
  78702. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  78703. /*
  78704. Skips invalid compressed data until a full flush point (see above the
  78705. description of deflate with Z_FULL_FLUSH) can be found, or until all
  78706. available input is skipped. No output is provided.
  78707. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  78708. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  78709. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  78710. case, the application may save the current current value of total_in which
  78711. indicates where valid compressed data was found. In the error case, the
  78712. application may repeatedly call inflateSync, providing more input each time,
  78713. until success or end of the input data.
  78714. */
  78715. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  78716. z_streamp source));
  78717. /*
  78718. Sets the destination stream as a complete copy of the source stream.
  78719. This function can be useful when randomly accessing a large stream. The
  78720. first pass through the stream can periodically record the inflate state,
  78721. allowing restarting inflate at those points when randomly accessing the
  78722. stream.
  78723. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78724. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78725. (such as zalloc being NULL). msg is left unchanged in both source and
  78726. destination.
  78727. */
  78728. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  78729. /*
  78730. This function is equivalent to inflateEnd followed by inflateInit,
  78731. but does not free and reallocate all the internal decompression state.
  78732. The stream will keep attributes that may have been set by inflateInit2.
  78733. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78734. stream state was inconsistent (such as zalloc or state being NULL).
  78735. */
  78736. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  78737. int bits,
  78738. int value));
  78739. /*
  78740. This function inserts bits in the inflate input stream. The intent is
  78741. that this function is used to start inflating at a bit position in the
  78742. middle of a byte. The provided bits will be used before any bytes are used
  78743. from next_in. This function should only be used with raw inflate, and
  78744. should be used before the first inflate() call after inflateInit2() or
  78745. inflateReset(). bits must be less than or equal to 16, and that many of the
  78746. least significant bits of value will be inserted in the input.
  78747. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78748. stream state was inconsistent.
  78749. */
  78750. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  78751. gz_headerp head));
  78752. /*
  78753. inflateGetHeader() requests that gzip header information be stored in the
  78754. provided gz_header structure. inflateGetHeader() may be called after
  78755. inflateInit2() or inflateReset(), and before the first call of inflate().
  78756. As inflate() processes the gzip stream, head->done is zero until the header
  78757. is completed, at which time head->done is set to one. If a zlib stream is
  78758. being decoded, then head->done is set to -1 to indicate that there will be
  78759. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  78760. force inflate() to return immediately after header processing is complete
  78761. and before any actual data is decompressed.
  78762. The text, time, xflags, and os fields are filled in with the gzip header
  78763. contents. hcrc is set to true if there is a header CRC. (The header CRC
  78764. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  78765. contains the maximum number of bytes to write to extra. Once done is true,
  78766. extra_len contains the actual extra field length, and extra contains the
  78767. extra field, or that field truncated if extra_max is less than extra_len.
  78768. If name is not Z_NULL, then up to name_max characters are written there,
  78769. terminated with a zero unless the length is greater than name_max. If
  78770. comment is not Z_NULL, then up to comm_max characters are written there,
  78771. terminated with a zero unless the length is greater than comm_max. When
  78772. any of extra, name, or comment are not Z_NULL and the respective field is
  78773. not present in the header, then that field is set to Z_NULL to signal its
  78774. absence. This allows the use of deflateSetHeader() with the returned
  78775. structure to duplicate the header. However if those fields are set to
  78776. allocated memory, then the application will need to save those pointers
  78777. elsewhere so that they can be eventually freed.
  78778. If inflateGetHeader is not used, then the header information is simply
  78779. discarded. The header is always checked for validity, including the header
  78780. CRC if present. inflateReset() will reset the process to discard the header
  78781. information. The application would need to call inflateGetHeader() again to
  78782. retrieve the header from the next gzip stream.
  78783. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78784. stream state was inconsistent.
  78785. */
  78786. /*
  78787. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  78788. unsigned char FAR *window));
  78789. Initialize the internal stream state for decompression using inflateBack()
  78790. calls. The fields zalloc, zfree and opaque in strm must be initialized
  78791. before the call. If zalloc and zfree are Z_NULL, then the default library-
  78792. derived memory allocation routines are used. windowBits is the base two
  78793. logarithm of the window size, in the range 8..15. window is a caller
  78794. supplied buffer of that size. Except for special applications where it is
  78795. assured that deflate was used with small window sizes, windowBits must be 15
  78796. and a 32K byte window must be supplied to be able to decompress general
  78797. deflate streams.
  78798. See inflateBack() for the usage of these routines.
  78799. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  78800. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  78801. be allocated, or Z_VERSION_ERROR if the version of the library does not
  78802. match the version of the header file.
  78803. */
  78804. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  78805. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  78806. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  78807. in_func in, void FAR *in_desc,
  78808. out_func out, void FAR *out_desc));
  78809. /*
  78810. inflateBack() does a raw inflate with a single call using a call-back
  78811. interface for input and output. This is more efficient than inflate() for
  78812. file i/o applications in that it avoids copying between the output and the
  78813. sliding window by simply making the window itself the output buffer. This
  78814. function trusts the application to not change the output buffer passed by
  78815. the output function, at least until inflateBack() returns.
  78816. inflateBackInit() must be called first to allocate the internal state
  78817. and to initialize the state with the user-provided window buffer.
  78818. inflateBack() may then be used multiple times to inflate a complete, raw
  78819. deflate stream with each call. inflateBackEnd() is then called to free
  78820. the allocated state.
  78821. A raw deflate stream is one with no zlib or gzip header or trailer.
  78822. This routine would normally be used in a utility that reads zip or gzip
  78823. files and writes out uncompressed files. The utility would decode the
  78824. header and process the trailer on its own, hence this routine expects
  78825. only the raw deflate stream to decompress. This is different from the
  78826. normal behavior of inflate(), which expects either a zlib or gzip header and
  78827. trailer around the deflate stream.
  78828. inflateBack() uses two subroutines supplied by the caller that are then
  78829. called by inflateBack() for input and output. inflateBack() calls those
  78830. routines until it reads a complete deflate stream and writes out all of the
  78831. uncompressed data, or until it encounters an error. The function's
  78832. parameters and return types are defined above in the in_func and out_func
  78833. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  78834. number of bytes of provided input, and a pointer to that input in buf. If
  78835. there is no input available, in() must return zero--buf is ignored in that
  78836. case--and inflateBack() will return a buffer error. inflateBack() will call
  78837. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  78838. should return zero on success, or non-zero on failure. If out() returns
  78839. non-zero, inflateBack() will return with an error. Neither in() nor out()
  78840. are permitted to change the contents of the window provided to
  78841. inflateBackInit(), which is also the buffer that out() uses to write from.
  78842. The length written by out() will be at most the window size. Any non-zero
  78843. amount of input may be provided by in().
  78844. For convenience, inflateBack() can be provided input on the first call by
  78845. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  78846. in() will be called. Therefore strm->next_in must be initialized before
  78847. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  78848. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  78849. must also be initialized, and then if strm->avail_in is not zero, input will
  78850. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  78851. The in_desc and out_desc parameters of inflateBack() is passed as the
  78852. first parameter of in() and out() respectively when they are called. These
  78853. descriptors can be optionally used to pass any information that the caller-
  78854. supplied in() and out() functions need to do their job.
  78855. On return, inflateBack() will set strm->next_in and strm->avail_in to
  78856. pass back any unused input that was provided by the last in() call. The
  78857. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  78858. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  78859. error in the deflate stream (in which case strm->msg is set to indicate the
  78860. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  78861. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  78862. distinguished using strm->next_in which will be Z_NULL only if in() returned
  78863. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  78864. out() returning non-zero. (in() will always be called before out(), so
  78865. strm->next_in is assured to be defined if out() returns non-zero.) Note
  78866. that inflateBack() cannot return Z_OK.
  78867. */
  78868. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  78869. /*
  78870. All memory allocated by inflateBackInit() is freed.
  78871. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  78872. state was inconsistent.
  78873. */
  78874. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  78875. /* Return flags indicating compile-time options.
  78876. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  78877. 1.0: size of uInt
  78878. 3.2: size of uLong
  78879. 5.4: size of voidpf (pointer)
  78880. 7.6: size of z_off_t
  78881. Compiler, assembler, and debug options:
  78882. 8: DEBUG
  78883. 9: ASMV or ASMINF -- use ASM code
  78884. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  78885. 11: 0 (reserved)
  78886. One-time table building (smaller code, but not thread-safe if true):
  78887. 12: BUILDFIXED -- build static block decoding tables when needed
  78888. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  78889. 14,15: 0 (reserved)
  78890. Library content (indicates missing functionality):
  78891. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  78892. deflate code when not needed)
  78893. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  78894. and decode gzip streams (to avoid linking crc code)
  78895. 18-19: 0 (reserved)
  78896. Operation variations (changes in library functionality):
  78897. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  78898. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  78899. 22,23: 0 (reserved)
  78900. The sprintf variant used by gzprintf (zero is best):
  78901. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  78902. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  78903. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  78904. Remainder:
  78905. 27-31: 0 (reserved)
  78906. */
  78907. /* utility functions */
  78908. /*
  78909. The following utility functions are implemented on top of the
  78910. basic stream-oriented functions. To simplify the interface, some
  78911. default options are assumed (compression level and memory usage,
  78912. standard memory allocation functions). The source code of these
  78913. utility functions can easily be modified if you need special options.
  78914. */
  78915. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  78916. const Bytef *source, uLong sourceLen));
  78917. /*
  78918. Compresses the source buffer into the destination buffer. sourceLen is
  78919. the byte length of the source buffer. Upon entry, destLen is the total
  78920. size of the destination buffer, which must be at least the value returned
  78921. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78922. compressed buffer.
  78923. This function can be used to compress a whole file at once if the
  78924. input file is mmap'ed.
  78925. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  78926. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78927. buffer.
  78928. */
  78929. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  78930. const Bytef *source, uLong sourceLen,
  78931. int level));
  78932. /*
  78933. Compresses the source buffer into the destination buffer. The level
  78934. parameter has the same meaning as in deflateInit. sourceLen is the byte
  78935. length of the source buffer. Upon entry, destLen is the total size of the
  78936. destination buffer, which must be at least the value returned by
  78937. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  78938. compressed buffer.
  78939. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78940. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  78941. Z_STREAM_ERROR if the level parameter is invalid.
  78942. */
  78943. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  78944. /*
  78945. compressBound() returns an upper bound on the compressed size after
  78946. compress() or compress2() on sourceLen bytes. It would be used before
  78947. a compress() or compress2() call to allocate the destination buffer.
  78948. */
  78949. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  78950. const Bytef *source, uLong sourceLen));
  78951. /*
  78952. Decompresses the source buffer into the destination buffer. sourceLen is
  78953. the byte length of the source buffer. Upon entry, destLen is the total
  78954. size of the destination buffer, which must be large enough to hold the
  78955. entire uncompressed data. (The size of the uncompressed data must have
  78956. been saved previously by the compressor and transmitted to the decompressor
  78957. by some mechanism outside the scope of this compression library.)
  78958. Upon exit, destLen is the actual size of the compressed buffer.
  78959. This function can be used to decompress a whole file at once if the
  78960. input file is mmap'ed.
  78961. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  78962. enough memory, Z_BUF_ERROR if there was not enough room in the output
  78963. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  78964. */
  78965. typedef voidp gzFile;
  78966. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  78967. /*
  78968. Opens a gzip (.gz) file for reading or writing. The mode parameter
  78969. is as in fopen ("rb" or "wb") but can also include a compression level
  78970. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  78971. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  78972. as in "wb1R". (See the description of deflateInit2 for more information
  78973. about the strategy parameter.)
  78974. gzopen can be used to read a file which is not in gzip format; in this
  78975. case gzread will directly read from the file without decompression.
  78976. gzopen returns NULL if the file could not be opened or if there was
  78977. insufficient memory to allocate the (de)compression state; errno
  78978. can be checked to distinguish the two cases (if errno is zero, the
  78979. zlib error is Z_MEM_ERROR). */
  78980. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  78981. /*
  78982. gzdopen() associates a gzFile with the file descriptor fd. File
  78983. descriptors are obtained from calls like open, dup, creat, pipe or
  78984. fileno (in the file has been previously opened with fopen).
  78985. The mode parameter is as in gzopen.
  78986. The next call of gzclose on the returned gzFile will also close the
  78987. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  78988. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  78989. gzdopen returns NULL if there was insufficient memory to allocate
  78990. the (de)compression state.
  78991. */
  78992. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  78993. /*
  78994. Dynamically update the compression level or strategy. See the description
  78995. of deflateInit2 for the meaning of these parameters.
  78996. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  78997. opened for writing.
  78998. */
  78999. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79000. /*
  79001. Reads the given number of uncompressed bytes from the compressed file.
  79002. If the input file was not in gzip format, gzread copies the given number
  79003. of bytes into the buffer.
  79004. gzread returns the number of uncompressed bytes actually read (0 for
  79005. end of file, -1 for error). */
  79006. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79007. voidpc buf, unsigned len));
  79008. /*
  79009. Writes the given number of uncompressed bytes into the compressed file.
  79010. gzwrite returns the number of uncompressed bytes actually written
  79011. (0 in case of error).
  79012. */
  79013. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79014. /*
  79015. Converts, formats, and writes the args to the compressed file under
  79016. control of the format string, as in fprintf. gzprintf returns the number of
  79017. uncompressed bytes actually written (0 in case of error). The number of
  79018. uncompressed bytes written is limited to 4095. The caller should assure that
  79019. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79020. return an error (0) with nothing written. In this case, there may also be a
  79021. buffer overflow with unpredictable consequences, which is possible only if
  79022. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79023. because the secure snprintf() or vsnprintf() functions were not available.
  79024. */
  79025. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79026. /*
  79027. Writes the given null-terminated string to the compressed file, excluding
  79028. the terminating null character.
  79029. gzputs returns the number of characters written, or -1 in case of error.
  79030. */
  79031. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79032. /*
  79033. Reads bytes from the compressed file until len-1 characters are read, or
  79034. a newline character is read and transferred to buf, or an end-of-file
  79035. condition is encountered. The string is then terminated with a null
  79036. character.
  79037. gzgets returns buf, or Z_NULL in case of error.
  79038. */
  79039. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79040. /*
  79041. Writes c, converted to an unsigned char, into the compressed file.
  79042. gzputc returns the value that was written, or -1 in case of error.
  79043. */
  79044. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79045. /*
  79046. Reads one byte from the compressed file. gzgetc returns this byte
  79047. or -1 in case of end of file or error.
  79048. */
  79049. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79050. /*
  79051. Push one character back onto the stream to be read again later.
  79052. Only one character of push-back is allowed. gzungetc() returns the
  79053. character pushed, or -1 on failure. gzungetc() will fail if a
  79054. character has been pushed but not read yet, or if c is -1. The pushed
  79055. character will be discarded if the stream is repositioned with gzseek()
  79056. or gzrewind().
  79057. */
  79058. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79059. /*
  79060. Flushes all pending output into the compressed file. The parameter
  79061. flush is as in the deflate() function. The return value is the zlib
  79062. error number (see function gzerror below). gzflush returns Z_OK if
  79063. the flush parameter is Z_FINISH and all output could be flushed.
  79064. gzflush should be called only when strictly necessary because it can
  79065. degrade compression.
  79066. */
  79067. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79068. z_off_t offset, int whence));
  79069. /*
  79070. Sets the starting position for the next gzread or gzwrite on the
  79071. given compressed file. The offset represents a number of bytes in the
  79072. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79073. the value SEEK_END is not supported.
  79074. If the file is opened for reading, this function is emulated but can be
  79075. extremely slow. If the file is opened for writing, only forward seeks are
  79076. supported; gzseek then compresses a sequence of zeroes up to the new
  79077. starting position.
  79078. gzseek returns the resulting offset location as measured in bytes from
  79079. the beginning of the uncompressed stream, or -1 in case of error, in
  79080. particular if the file is opened for writing and the new starting position
  79081. would be before the current position.
  79082. */
  79083. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79084. /*
  79085. Rewinds the given file. This function is supported only for reading.
  79086. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79087. */
  79088. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79089. /*
  79090. Returns the starting position for the next gzread or gzwrite on the
  79091. given compressed file. This position represents a number of bytes in the
  79092. uncompressed data stream.
  79093. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79094. */
  79095. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79096. /*
  79097. Returns 1 when EOF has previously been detected reading the given
  79098. input stream, otherwise zero.
  79099. */
  79100. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79101. /*
  79102. Returns 1 if file is being read directly without decompression, otherwise
  79103. zero.
  79104. */
  79105. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79106. /*
  79107. Flushes all pending output if necessary, closes the compressed file
  79108. and deallocates all the (de)compression state. The return value is the zlib
  79109. error number (see function gzerror below).
  79110. */
  79111. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79112. /*
  79113. Returns the error message for the last error which occurred on the
  79114. given compressed file. errnum is set to zlib error number. If an
  79115. error occurred in the file system and not in the compression library,
  79116. errnum is set to Z_ERRNO and the application may consult errno
  79117. to get the exact error code.
  79118. */
  79119. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79120. /*
  79121. Clears the error and end-of-file flags for file. This is analogous to the
  79122. clearerr() function in stdio. This is useful for continuing to read a gzip
  79123. file that is being written concurrently.
  79124. */
  79125. /* checksum functions */
  79126. /*
  79127. These functions are not related to compression but are exported
  79128. anyway because they might be useful in applications using the
  79129. compression library.
  79130. */
  79131. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79132. /*
  79133. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79134. return the updated checksum. If buf is NULL, this function returns
  79135. the required initial value for the checksum.
  79136. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79137. much faster. Usage example:
  79138. uLong adler = adler32(0L, Z_NULL, 0);
  79139. while (read_buffer(buffer, length) != EOF) {
  79140. adler = adler32(adler, buffer, length);
  79141. }
  79142. if (adler != original_adler) error();
  79143. */
  79144. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79145. z_off_t len2));
  79146. /*
  79147. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79148. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79149. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79150. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79151. */
  79152. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79153. /*
  79154. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79155. updated CRC-32. If buf is NULL, this function returns the required initial
  79156. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79157. performed within this function so it shouldn't be done by the application.
  79158. Usage example:
  79159. uLong crc = crc32(0L, Z_NULL, 0);
  79160. while (read_buffer(buffer, length) != EOF) {
  79161. crc = crc32(crc, buffer, length);
  79162. }
  79163. if (crc != original_crc) error();
  79164. */
  79165. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79166. /*
  79167. Combine two CRC-32 check values into one. For two sequences of bytes,
  79168. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79169. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79170. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79171. len2.
  79172. */
  79173. /* various hacks, don't look :) */
  79174. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79175. * and the compiler's view of z_stream:
  79176. */
  79177. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79178. const char *version, int stream_size));
  79179. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79180. const char *version, int stream_size));
  79181. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79182. int windowBits, int memLevel,
  79183. int strategy, const char *version,
  79184. int stream_size));
  79185. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79186. const char *version, int stream_size));
  79187. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79188. unsigned char FAR *window,
  79189. const char *version,
  79190. int stream_size));
  79191. #define deflateInit(strm, level) \
  79192. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79193. #define inflateInit(strm) \
  79194. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79195. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79196. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79197. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79198. #define inflateInit2(strm, windowBits) \
  79199. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79200. #define inflateBackInit(strm, windowBits, window) \
  79201. inflateBackInit_((strm), (windowBits), (window), \
  79202. ZLIB_VERSION, sizeof(z_stream))
  79203. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79204. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79205. #endif
  79206. ZEXTERN const char * ZEXPORT zError OF((int));
  79207. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79208. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79209. #ifdef __cplusplus
  79210. //}
  79211. #endif
  79212. #endif /* ZLIB_H */
  79213. /*** End of inlined file: zlib.h ***/
  79214. #undef OS_CODE
  79215. #else
  79216. #include <zlib.h>
  79217. #endif
  79218. }
  79219. BEGIN_JUCE_NAMESPACE
  79220. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79221. {
  79222. public:
  79223. GZIPCompressorHelper (const int compressionLevel, const int windowBits)
  79224. : data (0),
  79225. dataSize (0),
  79226. compLevel (compressionLevel),
  79227. strategy (0),
  79228. setParams (true),
  79229. streamIsValid (false),
  79230. finished (false),
  79231. shouldFinish (false)
  79232. {
  79233. using namespace zlibNamespace;
  79234. zerostruct (stream);
  79235. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79236. windowBits != 0 ? windowBits : MAX_WBITS,
  79237. 8, strategy) == Z_OK);
  79238. }
  79239. ~GZIPCompressorHelper()
  79240. {
  79241. using namespace zlibNamespace;
  79242. if (streamIsValid)
  79243. deflateEnd (&stream);
  79244. }
  79245. bool needsInput() const throw()
  79246. {
  79247. return dataSize <= 0;
  79248. }
  79249. void setInput (const uint8* const newData, const int size) throw()
  79250. {
  79251. data = newData;
  79252. dataSize = size;
  79253. }
  79254. int doNextBlock (uint8* const dest, const int destSize) throw()
  79255. {
  79256. using namespace zlibNamespace;
  79257. if (streamIsValid)
  79258. {
  79259. stream.next_in = const_cast <uint8*> (data);
  79260. stream.next_out = dest;
  79261. stream.avail_in = dataSize;
  79262. stream.avail_out = destSize;
  79263. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79264. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79265. setParams = false;
  79266. switch (result)
  79267. {
  79268. case Z_STREAM_END:
  79269. finished = true;
  79270. // Deliberate fall-through..
  79271. case Z_OK:
  79272. data += dataSize - stream.avail_in;
  79273. dataSize = stream.avail_in;
  79274. return destSize - stream.avail_out;
  79275. default:
  79276. break;
  79277. }
  79278. }
  79279. return 0;
  79280. }
  79281. enum { gzipCompBufferSize = 32768 };
  79282. private:
  79283. zlibNamespace::z_stream stream;
  79284. const uint8* data;
  79285. int dataSize, compLevel, strategy;
  79286. bool setParams, streamIsValid;
  79287. public:
  79288. bool finished, shouldFinish;
  79289. };
  79290. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79291. int compressionLevel,
  79292. const bool deleteDestStream,
  79293. const int windowBits)
  79294. : destStream (destStream_),
  79295. streamToDelete (deleteDestStream ? destStream_ : 0),
  79296. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79297. {
  79298. if (compressionLevel < 1 || compressionLevel > 9)
  79299. compressionLevel = -1;
  79300. helper = new GZIPCompressorHelper (compressionLevel, windowBits);
  79301. }
  79302. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79303. {
  79304. flush();
  79305. }
  79306. void GZIPCompressorOutputStream::flush()
  79307. {
  79308. if (! helper->finished)
  79309. {
  79310. helper->shouldFinish = true;
  79311. while (! helper->finished)
  79312. doNextBlock();
  79313. }
  79314. destStream->flush();
  79315. }
  79316. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79317. {
  79318. if (! helper->finished)
  79319. {
  79320. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79321. while (! helper->needsInput())
  79322. {
  79323. if (! doNextBlock())
  79324. return false;
  79325. }
  79326. }
  79327. return true;
  79328. }
  79329. bool GZIPCompressorOutputStream::doNextBlock()
  79330. {
  79331. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79332. return len <= 0 || destStream->write (buffer, len);
  79333. }
  79334. int64 GZIPCompressorOutputStream::getPosition()
  79335. {
  79336. return destStream->getPosition();
  79337. }
  79338. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79339. {
  79340. jassertfalse; // can't do it!
  79341. return false;
  79342. }
  79343. END_JUCE_NAMESPACE
  79344. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79345. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79346. #if JUCE_MSVC
  79347. #pragma warning (push)
  79348. #pragma warning (disable: 4309 4305)
  79349. #endif
  79350. namespace zlibNamespace
  79351. {
  79352. #if JUCE_INCLUDE_ZLIB_CODE
  79353. #undef OS_CODE
  79354. #undef fdopen
  79355. #define ZLIB_INTERNAL
  79356. #define NO_DUMMY_DECL
  79357. /*** Start of inlined file: adler32.c ***/
  79358. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79359. #define ZLIB_INTERNAL
  79360. #define BASE 65521UL /* largest prime smaller than 65536 */
  79361. #define NMAX 5552
  79362. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79363. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79364. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79365. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79366. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79367. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79368. /* use NO_DIVIDE if your processor does not do division in hardware */
  79369. #ifdef NO_DIVIDE
  79370. # define MOD(a) \
  79371. do { \
  79372. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79373. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79374. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79375. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79376. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79377. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79378. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79379. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79380. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79381. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79382. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79383. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79384. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79385. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79386. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79387. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79388. if (a >= BASE) a -= BASE; \
  79389. } while (0)
  79390. # define MOD4(a) \
  79391. do { \
  79392. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79393. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79394. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79395. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79396. if (a >= BASE) a -= BASE; \
  79397. } while (0)
  79398. #else
  79399. # define MOD(a) a %= BASE
  79400. # define MOD4(a) a %= BASE
  79401. #endif
  79402. /* ========================================================================= */
  79403. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79404. {
  79405. unsigned long sum2;
  79406. unsigned n;
  79407. /* split Adler-32 into component sums */
  79408. sum2 = (adler >> 16) & 0xffff;
  79409. adler &= 0xffff;
  79410. /* in case user likes doing a byte at a time, keep it fast */
  79411. if (len == 1) {
  79412. adler += buf[0];
  79413. if (adler >= BASE)
  79414. adler -= BASE;
  79415. sum2 += adler;
  79416. if (sum2 >= BASE)
  79417. sum2 -= BASE;
  79418. return adler | (sum2 << 16);
  79419. }
  79420. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79421. if (buf == Z_NULL)
  79422. return 1L;
  79423. /* in case short lengths are provided, keep it somewhat fast */
  79424. if (len < 16) {
  79425. while (len--) {
  79426. adler += *buf++;
  79427. sum2 += adler;
  79428. }
  79429. if (adler >= BASE)
  79430. adler -= BASE;
  79431. MOD4(sum2); /* only added so many BASE's */
  79432. return adler | (sum2 << 16);
  79433. }
  79434. /* do length NMAX blocks -- requires just one modulo operation */
  79435. while (len >= NMAX) {
  79436. len -= NMAX;
  79437. n = NMAX / 16; /* NMAX is divisible by 16 */
  79438. do {
  79439. DO16(buf); /* 16 sums unrolled */
  79440. buf += 16;
  79441. } while (--n);
  79442. MOD(adler);
  79443. MOD(sum2);
  79444. }
  79445. /* do remaining bytes (less than NMAX, still just one modulo) */
  79446. if (len) { /* avoid modulos if none remaining */
  79447. while (len >= 16) {
  79448. len -= 16;
  79449. DO16(buf);
  79450. buf += 16;
  79451. }
  79452. while (len--) {
  79453. adler += *buf++;
  79454. sum2 += adler;
  79455. }
  79456. MOD(adler);
  79457. MOD(sum2);
  79458. }
  79459. /* return recombined sums */
  79460. return adler | (sum2 << 16);
  79461. }
  79462. /* ========================================================================= */
  79463. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79464. {
  79465. unsigned long sum1;
  79466. unsigned long sum2;
  79467. unsigned rem;
  79468. /* the derivation of this formula is left as an exercise for the reader */
  79469. rem = (unsigned)(len2 % BASE);
  79470. sum1 = adler1 & 0xffff;
  79471. sum2 = rem * sum1;
  79472. MOD(sum2);
  79473. sum1 += (adler2 & 0xffff) + BASE - 1;
  79474. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79475. if (sum1 > BASE) sum1 -= BASE;
  79476. if (sum1 > BASE) sum1 -= BASE;
  79477. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79478. if (sum2 > BASE) sum2 -= BASE;
  79479. return sum1 | (sum2 << 16);
  79480. }
  79481. /*** End of inlined file: adler32.c ***/
  79482. /*** Start of inlined file: compress.c ***/
  79483. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79484. #define ZLIB_INTERNAL
  79485. /* ===========================================================================
  79486. Compresses the source buffer into the destination buffer. The level
  79487. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79488. length of the source buffer. Upon entry, destLen is the total size of the
  79489. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79490. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79491. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79492. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79493. Z_STREAM_ERROR if the level parameter is invalid.
  79494. */
  79495. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79496. uLong sourceLen, int level)
  79497. {
  79498. z_stream stream;
  79499. int err;
  79500. stream.next_in = (Bytef*)source;
  79501. stream.avail_in = (uInt)sourceLen;
  79502. #ifdef MAXSEG_64K
  79503. /* Check for source > 64K on 16-bit machine: */
  79504. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79505. #endif
  79506. stream.next_out = dest;
  79507. stream.avail_out = (uInt)*destLen;
  79508. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79509. stream.zalloc = (alloc_func)0;
  79510. stream.zfree = (free_func)0;
  79511. stream.opaque = (voidpf)0;
  79512. err = deflateInit(&stream, level);
  79513. if (err != Z_OK) return err;
  79514. err = deflate(&stream, Z_FINISH);
  79515. if (err != Z_STREAM_END) {
  79516. deflateEnd(&stream);
  79517. return err == Z_OK ? Z_BUF_ERROR : err;
  79518. }
  79519. *destLen = stream.total_out;
  79520. err = deflateEnd(&stream);
  79521. return err;
  79522. }
  79523. /* ===========================================================================
  79524. */
  79525. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79526. {
  79527. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79528. }
  79529. /* ===========================================================================
  79530. If the default memLevel or windowBits for deflateInit() is changed, then
  79531. this function needs to be updated.
  79532. */
  79533. uLong ZEXPORT compressBound (uLong sourceLen)
  79534. {
  79535. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79536. }
  79537. /*** End of inlined file: compress.c ***/
  79538. #undef DO1
  79539. #undef DO8
  79540. /*** Start of inlined file: crc32.c ***/
  79541. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79542. /*
  79543. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79544. protection on the static variables used to control the first-use generation
  79545. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79546. first call get_crc_table() to initialize the tables before allowing more than
  79547. one thread to use crc32().
  79548. */
  79549. #ifdef MAKECRCH
  79550. # include <stdio.h>
  79551. # ifndef DYNAMIC_CRC_TABLE
  79552. # define DYNAMIC_CRC_TABLE
  79553. # endif /* !DYNAMIC_CRC_TABLE */
  79554. #endif /* MAKECRCH */
  79555. /*** Start of inlined file: zutil.h ***/
  79556. /* WARNING: this file should *not* be used by applications. It is
  79557. part of the implementation of the compression library and is
  79558. subject to change. Applications should only use zlib.h.
  79559. */
  79560. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79561. #ifndef ZUTIL_H
  79562. #define ZUTIL_H
  79563. #define ZLIB_INTERNAL
  79564. #ifdef STDC
  79565. # ifndef _WIN32_WCE
  79566. # include <stddef.h>
  79567. # endif
  79568. # include <string.h>
  79569. # include <stdlib.h>
  79570. #endif
  79571. #ifdef NO_ERRNO_H
  79572. # ifdef _WIN32_WCE
  79573. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79574. * errno. We define it as a global variable to simplify porting.
  79575. * Its value is always 0 and should not be used. We rename it to
  79576. * avoid conflict with other libraries that use the same workaround.
  79577. */
  79578. # define errno z_errno
  79579. # endif
  79580. extern int errno;
  79581. #else
  79582. # ifndef _WIN32_WCE
  79583. # include <errno.h>
  79584. # endif
  79585. #endif
  79586. #ifndef local
  79587. # define local static
  79588. #endif
  79589. /* compile with -Dlocal if your debugger can't find static symbols */
  79590. typedef unsigned char uch;
  79591. typedef uch FAR uchf;
  79592. typedef unsigned short ush;
  79593. typedef ush FAR ushf;
  79594. typedef unsigned long ulg;
  79595. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79596. /* (size given to avoid silly warnings with Visual C++) */
  79597. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79598. #define ERR_RETURN(strm,err) \
  79599. return (strm->msg = (char*)ERR_MSG(err), (err))
  79600. /* To be used only when the state is known to be valid */
  79601. /* common constants */
  79602. #ifndef DEF_WBITS
  79603. # define DEF_WBITS MAX_WBITS
  79604. #endif
  79605. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79606. #if MAX_MEM_LEVEL >= 8
  79607. # define DEF_MEM_LEVEL 8
  79608. #else
  79609. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79610. #endif
  79611. /* default memLevel */
  79612. #define STORED_BLOCK 0
  79613. #define STATIC_TREES 1
  79614. #define DYN_TREES 2
  79615. /* The three kinds of block type */
  79616. #define MIN_MATCH 3
  79617. #define MAX_MATCH 258
  79618. /* The minimum and maximum match lengths */
  79619. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79620. /* target dependencies */
  79621. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79622. # define OS_CODE 0x00
  79623. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79624. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79625. /* Allow compilation with ANSI keywords only enabled */
  79626. void _Cdecl farfree( void *block );
  79627. void *_Cdecl farmalloc( unsigned long nbytes );
  79628. # else
  79629. # include <alloc.h>
  79630. # endif
  79631. # else /* MSC or DJGPP */
  79632. # include <malloc.h>
  79633. # endif
  79634. #endif
  79635. #ifdef AMIGA
  79636. # define OS_CODE 0x01
  79637. #endif
  79638. #if defined(VAXC) || defined(VMS)
  79639. # define OS_CODE 0x02
  79640. # define F_OPEN(name, mode) \
  79641. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79642. #endif
  79643. #if defined(ATARI) || defined(atarist)
  79644. # define OS_CODE 0x05
  79645. #endif
  79646. #ifdef OS2
  79647. # define OS_CODE 0x06
  79648. # ifdef M_I86
  79649. #include <malloc.h>
  79650. # endif
  79651. #endif
  79652. #if defined(MACOS) || TARGET_OS_MAC
  79653. # define OS_CODE 0x07
  79654. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79655. # include <unix.h> /* for fdopen */
  79656. # else
  79657. # ifndef fdopen
  79658. # define fdopen(fd,mode) NULL /* No fdopen() */
  79659. # endif
  79660. # endif
  79661. #endif
  79662. #ifdef TOPS20
  79663. # define OS_CODE 0x0a
  79664. #endif
  79665. #ifdef WIN32
  79666. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  79667. # define OS_CODE 0x0b
  79668. # endif
  79669. #endif
  79670. #ifdef __50SERIES /* Prime/PRIMOS */
  79671. # define OS_CODE 0x0f
  79672. #endif
  79673. #if defined(_BEOS_) || defined(RISCOS)
  79674. # define fdopen(fd,mode) NULL /* No fdopen() */
  79675. #endif
  79676. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  79677. # if defined(_WIN32_WCE)
  79678. # define fdopen(fd,mode) NULL /* No fdopen() */
  79679. # ifndef _PTRDIFF_T_DEFINED
  79680. typedef int ptrdiff_t;
  79681. # define _PTRDIFF_T_DEFINED
  79682. # endif
  79683. # else
  79684. # define fdopen(fd,type) _fdopen(fd,type)
  79685. # endif
  79686. #endif
  79687. /* common defaults */
  79688. #ifndef OS_CODE
  79689. # define OS_CODE 0x03 /* assume Unix */
  79690. #endif
  79691. #ifndef F_OPEN
  79692. # define F_OPEN(name, mode) fopen((name), (mode))
  79693. #endif
  79694. /* functions */
  79695. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  79696. # ifndef HAVE_VSNPRINTF
  79697. # define HAVE_VSNPRINTF
  79698. # endif
  79699. #endif
  79700. #if defined(__CYGWIN__)
  79701. # ifndef HAVE_VSNPRINTF
  79702. # define HAVE_VSNPRINTF
  79703. # endif
  79704. #endif
  79705. #ifndef HAVE_VSNPRINTF
  79706. # ifdef MSDOS
  79707. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  79708. but for now we just assume it doesn't. */
  79709. # define NO_vsnprintf
  79710. # endif
  79711. # ifdef __TURBOC__
  79712. # define NO_vsnprintf
  79713. # endif
  79714. # ifdef WIN32
  79715. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  79716. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  79717. # define vsnprintf _vsnprintf
  79718. # endif
  79719. # endif
  79720. # ifdef __SASC
  79721. # define NO_vsnprintf
  79722. # endif
  79723. #endif
  79724. #ifdef VMS
  79725. # define NO_vsnprintf
  79726. #endif
  79727. #if defined(pyr)
  79728. # define NO_MEMCPY
  79729. #endif
  79730. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  79731. /* Use our own functions for small and medium model with MSC <= 5.0.
  79732. * You may have to use the same strategy for Borland C (untested).
  79733. * The __SC__ check is for Symantec.
  79734. */
  79735. # define NO_MEMCPY
  79736. #endif
  79737. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  79738. # define HAVE_MEMCPY
  79739. #endif
  79740. #ifdef HAVE_MEMCPY
  79741. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  79742. # define zmemcpy _fmemcpy
  79743. # define zmemcmp _fmemcmp
  79744. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  79745. # else
  79746. # define zmemcpy memcpy
  79747. # define zmemcmp memcmp
  79748. # define zmemzero(dest, len) memset(dest, 0, len)
  79749. # endif
  79750. #else
  79751. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  79752. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  79753. extern void zmemzero OF((Bytef* dest, uInt len));
  79754. #endif
  79755. /* Diagnostic functions */
  79756. #ifdef DEBUG
  79757. # include <stdio.h>
  79758. extern int z_verbose;
  79759. extern void z_error OF((const char *m));
  79760. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  79761. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  79762. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  79763. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  79764. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  79765. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  79766. #else
  79767. # define Assert(cond,msg)
  79768. # define Trace(x)
  79769. # define Tracev(x)
  79770. # define Tracevv(x)
  79771. # define Tracec(c,x)
  79772. # define Tracecv(c,x)
  79773. #endif
  79774. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  79775. void zcfree OF((voidpf opaque, voidpf ptr));
  79776. #define ZALLOC(strm, items, size) \
  79777. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  79778. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  79779. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  79780. #endif /* ZUTIL_H */
  79781. /*** End of inlined file: zutil.h ***/
  79782. /* for STDC and FAR definitions */
  79783. #define local static
  79784. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  79785. #ifndef NOBYFOUR
  79786. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  79787. # include <limits.h>
  79788. # define BYFOUR
  79789. # if (UINT_MAX == 0xffffffffUL)
  79790. typedef unsigned int u4;
  79791. # else
  79792. # if (ULONG_MAX == 0xffffffffUL)
  79793. typedef unsigned long u4;
  79794. # else
  79795. # if (USHRT_MAX == 0xffffffffUL)
  79796. typedef unsigned short u4;
  79797. # else
  79798. # undef BYFOUR /* can't find a four-byte integer type! */
  79799. # endif
  79800. # endif
  79801. # endif
  79802. # endif /* STDC */
  79803. #endif /* !NOBYFOUR */
  79804. /* Definitions for doing the crc four data bytes at a time. */
  79805. #ifdef BYFOUR
  79806. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  79807. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  79808. local unsigned long crc32_little OF((unsigned long,
  79809. const unsigned char FAR *, unsigned));
  79810. local unsigned long crc32_big OF((unsigned long,
  79811. const unsigned char FAR *, unsigned));
  79812. # define TBLS 8
  79813. #else
  79814. # define TBLS 1
  79815. #endif /* BYFOUR */
  79816. /* Local functions for crc concatenation */
  79817. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  79818. unsigned long vec));
  79819. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  79820. #ifdef DYNAMIC_CRC_TABLE
  79821. local volatile int crc_table_empty = 1;
  79822. local unsigned long FAR crc_table[TBLS][256];
  79823. local void make_crc_table OF((void));
  79824. #ifdef MAKECRCH
  79825. local void write_table OF((FILE *, const unsigned long FAR *));
  79826. #endif /* MAKECRCH */
  79827. /*
  79828. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  79829. 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.
  79830. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  79831. with the lowest powers in the most significant bit. Then adding polynomials
  79832. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  79833. one. If we call the above polynomial p, and represent a byte as the
  79834. polynomial q, also with the lowest power in the most significant bit (so the
  79835. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  79836. where a mod b means the remainder after dividing a by b.
  79837. This calculation is done using the shift-register method of multiplying and
  79838. taking the remainder. The register is initialized to zero, and for each
  79839. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  79840. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  79841. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  79842. out is a one). We start with the highest power (least significant bit) of
  79843. q and repeat for all eight bits of q.
  79844. The first table is simply the CRC of all possible eight bit values. This is
  79845. all the information needed to generate CRCs on data a byte at a time for all
  79846. combinations of CRC register values and incoming bytes. The remaining tables
  79847. allow for word-at-a-time CRC calculation for both big-endian and little-
  79848. endian machines, where a word is four bytes.
  79849. */
  79850. local void make_crc_table()
  79851. {
  79852. unsigned long c;
  79853. int n, k;
  79854. unsigned long poly; /* polynomial exclusive-or pattern */
  79855. /* terms of polynomial defining this crc (except x^32): */
  79856. static volatile int first = 1; /* flag to limit concurrent making */
  79857. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  79858. /* See if another task is already doing this (not thread-safe, but better
  79859. than nothing -- significantly reduces duration of vulnerability in
  79860. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  79861. if (first) {
  79862. first = 0;
  79863. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  79864. poly = 0UL;
  79865. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  79866. poly |= 1UL << (31 - p[n]);
  79867. /* generate a crc for every 8-bit value */
  79868. for (n = 0; n < 256; n++) {
  79869. c = (unsigned long)n;
  79870. for (k = 0; k < 8; k++)
  79871. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  79872. crc_table[0][n] = c;
  79873. }
  79874. #ifdef BYFOUR
  79875. /* generate crc for each value followed by one, two, and three zeros,
  79876. and then the byte reversal of those as well as the first table */
  79877. for (n = 0; n < 256; n++) {
  79878. c = crc_table[0][n];
  79879. crc_table[4][n] = REV(c);
  79880. for (k = 1; k < 4; k++) {
  79881. c = crc_table[0][c & 0xff] ^ (c >> 8);
  79882. crc_table[k][n] = c;
  79883. crc_table[k + 4][n] = REV(c);
  79884. }
  79885. }
  79886. #endif /* BYFOUR */
  79887. crc_table_empty = 0;
  79888. }
  79889. else { /* not first */
  79890. /* wait for the other guy to finish (not efficient, but rare) */
  79891. while (crc_table_empty)
  79892. ;
  79893. }
  79894. #ifdef MAKECRCH
  79895. /* write out CRC tables to crc32.h */
  79896. {
  79897. FILE *out;
  79898. out = fopen("crc32.h", "w");
  79899. if (out == NULL) return;
  79900. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  79901. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  79902. fprintf(out, "local const unsigned long FAR ");
  79903. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  79904. write_table(out, crc_table[0]);
  79905. # ifdef BYFOUR
  79906. fprintf(out, "#ifdef BYFOUR\n");
  79907. for (k = 1; k < 8; k++) {
  79908. fprintf(out, " },\n {\n");
  79909. write_table(out, crc_table[k]);
  79910. }
  79911. fprintf(out, "#endif\n");
  79912. # endif /* BYFOUR */
  79913. fprintf(out, " }\n};\n");
  79914. fclose(out);
  79915. }
  79916. #endif /* MAKECRCH */
  79917. }
  79918. #ifdef MAKECRCH
  79919. local void write_table(out, table)
  79920. FILE *out;
  79921. const unsigned long FAR *table;
  79922. {
  79923. int n;
  79924. for (n = 0; n < 256; n++)
  79925. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  79926. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  79927. }
  79928. #endif /* MAKECRCH */
  79929. #else /* !DYNAMIC_CRC_TABLE */
  79930. /* ========================================================================
  79931. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  79932. */
  79933. /*** Start of inlined file: crc32.h ***/
  79934. local const unsigned long FAR crc_table[TBLS][256] =
  79935. {
  79936. {
  79937. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  79938. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  79939. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  79940. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  79941. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  79942. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  79943. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  79944. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  79945. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  79946. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  79947. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  79948. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  79949. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  79950. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  79951. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  79952. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  79953. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  79954. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  79955. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  79956. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  79957. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  79958. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  79959. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  79960. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  79961. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  79962. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  79963. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  79964. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  79965. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  79966. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  79967. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  79968. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  79969. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  79970. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  79971. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  79972. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  79973. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  79974. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  79975. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  79976. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  79977. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  79978. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  79979. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  79980. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  79981. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  79982. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  79983. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  79984. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  79985. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  79986. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  79987. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  79988. 0x2d02ef8dUL
  79989. #ifdef BYFOUR
  79990. },
  79991. {
  79992. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  79993. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  79994. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  79995. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  79996. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  79997. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  79998. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  79999. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80000. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80001. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80002. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80003. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80004. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80005. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80006. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80007. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80008. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80009. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80010. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80011. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80012. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80013. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80014. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80015. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80016. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80017. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80018. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80019. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80020. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80021. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80022. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80023. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80024. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80025. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80026. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80027. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80028. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80029. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80030. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80031. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80032. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80033. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80034. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80035. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80036. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80037. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80038. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80039. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80040. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80041. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80042. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80043. 0x9324fd72UL
  80044. },
  80045. {
  80046. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80047. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80048. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80049. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80050. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80051. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80052. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80053. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80054. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80055. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80056. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80057. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80058. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80059. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80060. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80061. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80062. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80063. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80064. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80065. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80066. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80067. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80068. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80069. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80070. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80071. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80072. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80073. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80074. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80075. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80076. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80077. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80078. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80079. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80080. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80081. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80082. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80083. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80084. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80085. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80086. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80087. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80088. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80089. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80090. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80091. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80092. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80093. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80094. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80095. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80096. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80097. 0xbe9834edUL
  80098. },
  80099. {
  80100. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80101. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80102. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80103. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80104. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80105. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80106. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80107. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80108. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80109. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80110. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80111. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80112. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80113. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80114. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80115. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80116. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80117. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80118. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80119. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80120. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80121. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80122. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80123. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80124. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80125. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80126. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80127. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80128. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80129. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80130. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80131. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80132. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80133. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80134. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80135. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80136. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80137. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80138. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80139. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80140. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80141. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80142. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80143. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80144. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80145. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80146. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80147. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80148. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80149. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80150. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80151. 0xde0506f1UL
  80152. },
  80153. {
  80154. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80155. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80156. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80157. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80158. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80159. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80160. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80161. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80162. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80163. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80164. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80165. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80166. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80167. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80168. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80169. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80170. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80171. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80172. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80173. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80174. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80175. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80176. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80177. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80178. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80179. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80180. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80181. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80182. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80183. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80184. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80185. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80186. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80187. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80188. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80189. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80190. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80191. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80192. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80193. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80194. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80195. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80196. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80197. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80198. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80199. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80200. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80201. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80202. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80203. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80204. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80205. 0x8def022dUL
  80206. },
  80207. {
  80208. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80209. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80210. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80211. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80212. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80213. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80214. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80215. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80216. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80217. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80218. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80219. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80220. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80221. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80222. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80223. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80224. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80225. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80226. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80227. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80228. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80229. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80230. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80231. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80232. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80233. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80234. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80235. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80236. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80237. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80238. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80239. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80240. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80241. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80242. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80243. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80244. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80245. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80246. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80247. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80248. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80249. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80250. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80251. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80252. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80253. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80254. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80255. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80256. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80257. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80258. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80259. 0x72fd2493UL
  80260. },
  80261. {
  80262. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80263. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80264. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80265. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80266. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80267. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80268. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80269. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80270. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80271. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80272. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80273. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80274. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80275. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80276. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80277. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80278. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80279. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80280. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80281. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80282. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80283. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80284. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80285. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80286. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80287. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80288. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80289. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80290. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80291. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80292. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80293. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80294. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80295. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80296. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80297. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80298. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80299. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80300. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80301. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80302. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80303. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80304. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80305. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80306. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80307. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80308. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80309. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80310. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80311. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80312. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80313. 0xed3498beUL
  80314. },
  80315. {
  80316. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80317. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80318. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80319. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80320. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80321. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80322. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80323. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80324. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80325. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80326. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80327. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80328. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80329. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80330. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80331. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80332. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80333. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80334. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80335. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80336. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80337. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80338. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80339. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80340. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80341. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80342. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80343. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80344. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80345. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80346. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80347. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80348. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80349. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80350. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80351. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80352. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80353. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80354. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80355. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80356. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80357. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80358. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80359. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80360. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80361. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80362. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80363. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80364. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80365. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80366. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80367. 0xf10605deUL
  80368. #endif
  80369. }
  80370. };
  80371. /*** End of inlined file: crc32.h ***/
  80372. #endif /* DYNAMIC_CRC_TABLE */
  80373. /* =========================================================================
  80374. * This function can be used by asm versions of crc32()
  80375. */
  80376. const unsigned long FAR * ZEXPORT get_crc_table()
  80377. {
  80378. #ifdef DYNAMIC_CRC_TABLE
  80379. if (crc_table_empty)
  80380. make_crc_table();
  80381. #endif /* DYNAMIC_CRC_TABLE */
  80382. return (const unsigned long FAR *)crc_table;
  80383. }
  80384. /* ========================================================================= */
  80385. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80386. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80387. /* ========================================================================= */
  80388. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80389. {
  80390. if (buf == Z_NULL) return 0UL;
  80391. #ifdef DYNAMIC_CRC_TABLE
  80392. if (crc_table_empty)
  80393. make_crc_table();
  80394. #endif /* DYNAMIC_CRC_TABLE */
  80395. #ifdef BYFOUR
  80396. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80397. u4 endian;
  80398. endian = 1;
  80399. if (*((unsigned char *)(&endian)))
  80400. return crc32_little(crc, buf, len);
  80401. else
  80402. return crc32_big(crc, buf, len);
  80403. }
  80404. #endif /* BYFOUR */
  80405. crc = crc ^ 0xffffffffUL;
  80406. while (len >= 8) {
  80407. DO8;
  80408. len -= 8;
  80409. }
  80410. if (len) do {
  80411. DO1;
  80412. } while (--len);
  80413. return crc ^ 0xffffffffUL;
  80414. }
  80415. #ifdef BYFOUR
  80416. /* ========================================================================= */
  80417. #define DOLIT4 c ^= *buf4++; \
  80418. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80419. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80420. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80421. /* ========================================================================= */
  80422. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80423. {
  80424. register u4 c;
  80425. register const u4 FAR *buf4;
  80426. c = (u4)crc;
  80427. c = ~c;
  80428. while (len && ((ptrdiff_t)buf & 3)) {
  80429. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80430. len--;
  80431. }
  80432. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80433. while (len >= 32) {
  80434. DOLIT32;
  80435. len -= 32;
  80436. }
  80437. while (len >= 4) {
  80438. DOLIT4;
  80439. len -= 4;
  80440. }
  80441. buf = (const unsigned char FAR *)buf4;
  80442. if (len) do {
  80443. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80444. } while (--len);
  80445. c = ~c;
  80446. return (unsigned long)c;
  80447. }
  80448. /* ========================================================================= */
  80449. #define DOBIG4 c ^= *++buf4; \
  80450. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80451. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80452. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80453. /* ========================================================================= */
  80454. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80455. {
  80456. register u4 c;
  80457. register const u4 FAR *buf4;
  80458. c = REV((u4)crc);
  80459. c = ~c;
  80460. while (len && ((ptrdiff_t)buf & 3)) {
  80461. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80462. len--;
  80463. }
  80464. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80465. buf4--;
  80466. while (len >= 32) {
  80467. DOBIG32;
  80468. len -= 32;
  80469. }
  80470. while (len >= 4) {
  80471. DOBIG4;
  80472. len -= 4;
  80473. }
  80474. buf4++;
  80475. buf = (const unsigned char FAR *)buf4;
  80476. if (len) do {
  80477. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80478. } while (--len);
  80479. c = ~c;
  80480. return (unsigned long)(REV(c));
  80481. }
  80482. #endif /* BYFOUR */
  80483. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80484. /* ========================================================================= */
  80485. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80486. {
  80487. unsigned long sum;
  80488. sum = 0;
  80489. while (vec) {
  80490. if (vec & 1)
  80491. sum ^= *mat;
  80492. vec >>= 1;
  80493. mat++;
  80494. }
  80495. return sum;
  80496. }
  80497. /* ========================================================================= */
  80498. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80499. {
  80500. int n;
  80501. for (n = 0; n < GF2_DIM; n++)
  80502. square[n] = gf2_matrix_times(mat, mat[n]);
  80503. }
  80504. /* ========================================================================= */
  80505. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80506. {
  80507. int n;
  80508. unsigned long row;
  80509. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80510. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80511. /* degenerate case */
  80512. if (len2 == 0)
  80513. return crc1;
  80514. /* put operator for one zero bit in odd */
  80515. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80516. row = 1;
  80517. for (n = 1; n < GF2_DIM; n++) {
  80518. odd[n] = row;
  80519. row <<= 1;
  80520. }
  80521. /* put operator for two zero bits in even */
  80522. gf2_matrix_square(even, odd);
  80523. /* put operator for four zero bits in odd */
  80524. gf2_matrix_square(odd, even);
  80525. /* apply len2 zeros to crc1 (first square will put the operator for one
  80526. zero byte, eight zero bits, in even) */
  80527. do {
  80528. /* apply zeros operator for this bit of len2 */
  80529. gf2_matrix_square(even, odd);
  80530. if (len2 & 1)
  80531. crc1 = gf2_matrix_times(even, crc1);
  80532. len2 >>= 1;
  80533. /* if no more bits set, then done */
  80534. if (len2 == 0)
  80535. break;
  80536. /* another iteration of the loop with odd and even swapped */
  80537. gf2_matrix_square(odd, even);
  80538. if (len2 & 1)
  80539. crc1 = gf2_matrix_times(odd, crc1);
  80540. len2 >>= 1;
  80541. /* if no more bits set, then done */
  80542. } while (len2 != 0);
  80543. /* return combined crc */
  80544. crc1 ^= crc2;
  80545. return crc1;
  80546. }
  80547. /*** End of inlined file: crc32.c ***/
  80548. /*** Start of inlined file: deflate.c ***/
  80549. /*
  80550. * ALGORITHM
  80551. *
  80552. * The "deflation" process depends on being able to identify portions
  80553. * of the input text which are identical to earlier input (within a
  80554. * sliding window trailing behind the input currently being processed).
  80555. *
  80556. * The most straightforward technique turns out to be the fastest for
  80557. * most input files: try all possible matches and select the longest.
  80558. * The key feature of this algorithm is that insertions into the string
  80559. * dictionary are very simple and thus fast, and deletions are avoided
  80560. * completely. Insertions are performed at each input character, whereas
  80561. * string matches are performed only when the previous match ends. So it
  80562. * is preferable to spend more time in matches to allow very fast string
  80563. * insertions and avoid deletions. The matching algorithm for small
  80564. * strings is inspired from that of Rabin & Karp. A brute force approach
  80565. * is used to find longer strings when a small match has been found.
  80566. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80567. * (by Leonid Broukhis).
  80568. * A previous version of this file used a more sophisticated algorithm
  80569. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80570. * time, but has a larger average cost, uses more memory and is patented.
  80571. * However the F&G algorithm may be faster for some highly redundant
  80572. * files if the parameter max_chain_length (described below) is too large.
  80573. *
  80574. * ACKNOWLEDGEMENTS
  80575. *
  80576. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80577. * I found it in 'freeze' written by Leonid Broukhis.
  80578. * Thanks to many people for bug reports and testing.
  80579. *
  80580. * REFERENCES
  80581. *
  80582. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80583. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80584. *
  80585. * A description of the Rabin and Karp algorithm is given in the book
  80586. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80587. *
  80588. * Fiala,E.R., and Greene,D.H.
  80589. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80590. *
  80591. */
  80592. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80593. /*** Start of inlined file: deflate.h ***/
  80594. /* WARNING: this file should *not* be used by applications. It is
  80595. part of the implementation of the compression library and is
  80596. subject to change. Applications should only use zlib.h.
  80597. */
  80598. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80599. #ifndef DEFLATE_H
  80600. #define DEFLATE_H
  80601. /* define NO_GZIP when compiling if you want to disable gzip header and
  80602. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80603. the crc code when it is not needed. For shared libraries, gzip encoding
  80604. should be left enabled. */
  80605. #ifndef NO_GZIP
  80606. # define GZIP
  80607. #endif
  80608. #define NO_DUMMY_DECL
  80609. /* ===========================================================================
  80610. * Internal compression state.
  80611. */
  80612. #define LENGTH_CODES 29
  80613. /* number of length codes, not counting the special END_BLOCK code */
  80614. #define LITERALS 256
  80615. /* number of literal bytes 0..255 */
  80616. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80617. /* number of Literal or Length codes, including the END_BLOCK code */
  80618. #define D_CODES 30
  80619. /* number of distance codes */
  80620. #define BL_CODES 19
  80621. /* number of codes used to transfer the bit lengths */
  80622. #define HEAP_SIZE (2*L_CODES+1)
  80623. /* maximum heap size */
  80624. #define MAX_BITS 15
  80625. /* All codes must not exceed MAX_BITS bits */
  80626. #define INIT_STATE 42
  80627. #define EXTRA_STATE 69
  80628. #define NAME_STATE 73
  80629. #define COMMENT_STATE 91
  80630. #define HCRC_STATE 103
  80631. #define BUSY_STATE 113
  80632. #define FINISH_STATE 666
  80633. /* Stream status */
  80634. /* Data structure describing a single value and its code string. */
  80635. typedef struct ct_data_s {
  80636. union {
  80637. ush freq; /* frequency count */
  80638. ush code; /* bit string */
  80639. } fc;
  80640. union {
  80641. ush dad; /* father node in Huffman tree */
  80642. ush len; /* length of bit string */
  80643. } dl;
  80644. } FAR ct_data;
  80645. #define Freq fc.freq
  80646. #define Code fc.code
  80647. #define Dad dl.dad
  80648. #define Len dl.len
  80649. typedef struct static_tree_desc_s static_tree_desc;
  80650. typedef struct tree_desc_s {
  80651. ct_data *dyn_tree; /* the dynamic tree */
  80652. int max_code; /* largest code with non zero frequency */
  80653. static_tree_desc *stat_desc; /* the corresponding static tree */
  80654. } FAR tree_desc;
  80655. typedef ush Pos;
  80656. typedef Pos FAR Posf;
  80657. typedef unsigned IPos;
  80658. /* A Pos is an index in the character window. We use short instead of int to
  80659. * save space in the various tables. IPos is used only for parameter passing.
  80660. */
  80661. typedef struct internal_state {
  80662. z_streamp strm; /* pointer back to this zlib stream */
  80663. int status; /* as the name implies */
  80664. Bytef *pending_buf; /* output still pending */
  80665. ulg pending_buf_size; /* size of pending_buf */
  80666. Bytef *pending_out; /* next pending byte to output to the stream */
  80667. uInt pending; /* nb of bytes in the pending buffer */
  80668. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  80669. gz_headerp gzhead; /* gzip header information to write */
  80670. uInt gzindex; /* where in extra, name, or comment */
  80671. Byte method; /* STORED (for zip only) or DEFLATED */
  80672. int last_flush; /* value of flush param for previous deflate call */
  80673. /* used by deflate.c: */
  80674. uInt w_size; /* LZ77 window size (32K by default) */
  80675. uInt w_bits; /* log2(w_size) (8..16) */
  80676. uInt w_mask; /* w_size - 1 */
  80677. Bytef *window;
  80678. /* Sliding window. Input bytes are read into the second half of the window,
  80679. * and move to the first half later to keep a dictionary of at least wSize
  80680. * bytes. With this organization, matches are limited to a distance of
  80681. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  80682. * performed with a length multiple of the block size. Also, it limits
  80683. * the window size to 64K, which is quite useful on MSDOS.
  80684. * To do: use the user input buffer as sliding window.
  80685. */
  80686. ulg window_size;
  80687. /* Actual size of window: 2*wSize, except when the user input buffer
  80688. * is directly used as sliding window.
  80689. */
  80690. Posf *prev;
  80691. /* Link to older string with same hash index. To limit the size of this
  80692. * array to 64K, this link is maintained only for the last 32K strings.
  80693. * An index in this array is thus a window index modulo 32K.
  80694. */
  80695. Posf *head; /* Heads of the hash chains or NIL. */
  80696. uInt ins_h; /* hash index of string to be inserted */
  80697. uInt hash_size; /* number of elements in hash table */
  80698. uInt hash_bits; /* log2(hash_size) */
  80699. uInt hash_mask; /* hash_size-1 */
  80700. uInt hash_shift;
  80701. /* Number of bits by which ins_h must be shifted at each input
  80702. * step. It must be such that after MIN_MATCH steps, the oldest
  80703. * byte no longer takes part in the hash key, that is:
  80704. * hash_shift * MIN_MATCH >= hash_bits
  80705. */
  80706. long block_start;
  80707. /* Window position at the beginning of the current output block. Gets
  80708. * negative when the window is moved backwards.
  80709. */
  80710. uInt match_length; /* length of best match */
  80711. IPos prev_match; /* previous match */
  80712. int match_available; /* set if previous match exists */
  80713. uInt strstart; /* start of string to insert */
  80714. uInt match_start; /* start of matching string */
  80715. uInt lookahead; /* number of valid bytes ahead in window */
  80716. uInt prev_length;
  80717. /* Length of the best match at previous step. Matches not greater than this
  80718. * are discarded. This is used in the lazy match evaluation.
  80719. */
  80720. uInt max_chain_length;
  80721. /* To speed up deflation, hash chains are never searched beyond this
  80722. * length. A higher limit improves compression ratio but degrades the
  80723. * speed.
  80724. */
  80725. uInt max_lazy_match;
  80726. /* Attempt to find a better match only when the current match is strictly
  80727. * smaller than this value. This mechanism is used only for compression
  80728. * levels >= 4.
  80729. */
  80730. # define max_insert_length max_lazy_match
  80731. /* Insert new strings in the hash table only if the match length is not
  80732. * greater than this length. This saves time but degrades compression.
  80733. * max_insert_length is used only for compression levels <= 3.
  80734. */
  80735. int level; /* compression level (1..9) */
  80736. int strategy; /* favor or force Huffman coding*/
  80737. uInt good_match;
  80738. /* Use a faster search when the previous match is longer than this */
  80739. int nice_match; /* Stop searching when current match exceeds this */
  80740. /* used by trees.c: */
  80741. /* Didn't use ct_data typedef below to supress compiler warning */
  80742. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  80743. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  80744. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  80745. struct tree_desc_s l_desc; /* desc. for literal tree */
  80746. struct tree_desc_s d_desc; /* desc. for distance tree */
  80747. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  80748. ush bl_count[MAX_BITS+1];
  80749. /* number of codes at each bit length for an optimal tree */
  80750. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  80751. int heap_len; /* number of elements in the heap */
  80752. int heap_max; /* element of largest frequency */
  80753. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  80754. * The same heap array is used to build all trees.
  80755. */
  80756. uch depth[2*L_CODES+1];
  80757. /* Depth of each subtree used as tie breaker for trees of equal frequency
  80758. */
  80759. uchf *l_buf; /* buffer for literals or lengths */
  80760. uInt lit_bufsize;
  80761. /* Size of match buffer for literals/lengths. There are 4 reasons for
  80762. * limiting lit_bufsize to 64K:
  80763. * - frequencies can be kept in 16 bit counters
  80764. * - if compression is not successful for the first block, all input
  80765. * data is still in the window so we can still emit a stored block even
  80766. * when input comes from standard input. (This can also be done for
  80767. * all blocks if lit_bufsize is not greater than 32K.)
  80768. * - if compression is not successful for a file smaller than 64K, we can
  80769. * even emit a stored file instead of a stored block (saving 5 bytes).
  80770. * This is applicable only for zip (not gzip or zlib).
  80771. * - creating new Huffman trees less frequently may not provide fast
  80772. * adaptation to changes in the input data statistics. (Take for
  80773. * example a binary file with poorly compressible code followed by
  80774. * a highly compressible string table.) Smaller buffer sizes give
  80775. * fast adaptation but have of course the overhead of transmitting
  80776. * trees more frequently.
  80777. * - I can't count above 4
  80778. */
  80779. uInt last_lit; /* running index in l_buf */
  80780. ushf *d_buf;
  80781. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  80782. * the same number of elements. To use different lengths, an extra flag
  80783. * array would be necessary.
  80784. */
  80785. ulg opt_len; /* bit length of current block with optimal trees */
  80786. ulg static_len; /* bit length of current block with static trees */
  80787. uInt matches; /* number of string matches in current block */
  80788. int last_eob_len; /* bit length of EOB code for last block */
  80789. #ifdef DEBUG
  80790. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  80791. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  80792. #endif
  80793. ush bi_buf;
  80794. /* Output buffer. bits are inserted starting at the bottom (least
  80795. * significant bits).
  80796. */
  80797. int bi_valid;
  80798. /* Number of valid bits in bi_buf. All bits above the last valid bit
  80799. * are always zero.
  80800. */
  80801. } FAR deflate_state;
  80802. /* Output a byte on the stream.
  80803. * IN assertion: there is enough room in pending_buf.
  80804. */
  80805. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  80806. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80807. /* Minimum amount of lookahead, except at the end of the input file.
  80808. * See deflate.c for comments about the MIN_MATCH+1.
  80809. */
  80810. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  80811. /* In order to simplify the code, particularly on 16 bit machines, match
  80812. * distances are limited to MAX_DIST instead of WSIZE.
  80813. */
  80814. /* in trees.c */
  80815. void _tr_init OF((deflate_state *s));
  80816. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  80817. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80818. int eof));
  80819. void _tr_align OF((deflate_state *s));
  80820. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  80821. int eof));
  80822. #define d_code(dist) \
  80823. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  80824. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  80825. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  80826. * used.
  80827. */
  80828. #ifndef DEBUG
  80829. /* Inline versions of _tr_tally for speed: */
  80830. #if defined(GEN_TREES_H) || !defined(STDC)
  80831. extern uch _length_code[];
  80832. extern uch _dist_code[];
  80833. #else
  80834. extern const uch _length_code[];
  80835. extern const uch _dist_code[];
  80836. #endif
  80837. # define _tr_tally_lit(s, c, flush) \
  80838. { uch cc = (c); \
  80839. s->d_buf[s->last_lit] = 0; \
  80840. s->l_buf[s->last_lit++] = cc; \
  80841. s->dyn_ltree[cc].Freq++; \
  80842. flush = (s->last_lit == s->lit_bufsize-1); \
  80843. }
  80844. # define _tr_tally_dist(s, distance, length, flush) \
  80845. { uch len = (length); \
  80846. ush dist = (distance); \
  80847. s->d_buf[s->last_lit] = dist; \
  80848. s->l_buf[s->last_lit++] = len; \
  80849. dist--; \
  80850. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  80851. s->dyn_dtree[d_code(dist)].Freq++; \
  80852. flush = (s->last_lit == s->lit_bufsize-1); \
  80853. }
  80854. #else
  80855. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  80856. # define _tr_tally_dist(s, distance, length, flush) \
  80857. flush = _tr_tally(s, distance, length)
  80858. #endif
  80859. #endif /* DEFLATE_H */
  80860. /*** End of inlined file: deflate.h ***/
  80861. const char deflate_copyright[] =
  80862. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  80863. /*
  80864. If you use the zlib library in a product, an acknowledgment is welcome
  80865. in the documentation of your product. If for some reason you cannot
  80866. include such an acknowledgment, I would appreciate that you keep this
  80867. copyright string in the executable of your product.
  80868. */
  80869. /* ===========================================================================
  80870. * Function prototypes.
  80871. */
  80872. typedef enum {
  80873. need_more, /* block not completed, need more input or more output */
  80874. block_done, /* block flush performed */
  80875. finish_started, /* finish started, need only more output at next deflate */
  80876. finish_done /* finish done, accept no more input or output */
  80877. } block_state;
  80878. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  80879. /* Compression function. Returns the block state after the call. */
  80880. local void fill_window OF((deflate_state *s));
  80881. local block_state deflate_stored OF((deflate_state *s, int flush));
  80882. local block_state deflate_fast OF((deflate_state *s, int flush));
  80883. #ifndef FASTEST
  80884. local block_state deflate_slow OF((deflate_state *s, int flush));
  80885. #endif
  80886. local void lm_init OF((deflate_state *s));
  80887. local void putShortMSB OF((deflate_state *s, uInt b));
  80888. local void flush_pending OF((z_streamp strm));
  80889. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  80890. #ifndef FASTEST
  80891. #ifdef ASMV
  80892. void match_init OF((void)); /* asm code initialization */
  80893. uInt longest_match OF((deflate_state *s, IPos cur_match));
  80894. #else
  80895. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  80896. #endif
  80897. #endif
  80898. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  80899. #ifdef DEBUG
  80900. local void check_match OF((deflate_state *s, IPos start, IPos match,
  80901. int length));
  80902. #endif
  80903. /* ===========================================================================
  80904. * Local data
  80905. */
  80906. #define NIL 0
  80907. /* Tail of hash chains */
  80908. #ifndef TOO_FAR
  80909. # define TOO_FAR 4096
  80910. #endif
  80911. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  80912. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  80913. /* Minimum amount of lookahead, except at the end of the input file.
  80914. * See deflate.c for comments about the MIN_MATCH+1.
  80915. */
  80916. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  80917. * the desired pack level (0..9). The values given below have been tuned to
  80918. * exclude worst case performance for pathological files. Better values may be
  80919. * found for specific files.
  80920. */
  80921. typedef struct config_s {
  80922. ush good_length; /* reduce lazy search above this match length */
  80923. ush max_lazy; /* do not perform lazy search above this match length */
  80924. ush nice_length; /* quit search above this match length */
  80925. ush max_chain;
  80926. compress_func func;
  80927. } config;
  80928. #ifdef FASTEST
  80929. local const config configuration_table[2] = {
  80930. /* good lazy nice chain */
  80931. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80932. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  80933. #else
  80934. local const config configuration_table[10] = {
  80935. /* good lazy nice chain */
  80936. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  80937. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  80938. /* 2 */ {4, 5, 16, 8, deflate_fast},
  80939. /* 3 */ {4, 6, 32, 32, deflate_fast},
  80940. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  80941. /* 5 */ {8, 16, 32, 32, deflate_slow},
  80942. /* 6 */ {8, 16, 128, 128, deflate_slow},
  80943. /* 7 */ {8, 32, 128, 256, deflate_slow},
  80944. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  80945. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  80946. #endif
  80947. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  80948. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  80949. * meaning.
  80950. */
  80951. #define EQUAL 0
  80952. /* result of memcmp for equal strings */
  80953. #ifndef NO_DUMMY_DECL
  80954. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  80955. #endif
  80956. /* ===========================================================================
  80957. * Update a hash value with the given input byte
  80958. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  80959. * input characters, so that a running hash key can be computed from the
  80960. * previous key instead of complete recalculation each time.
  80961. */
  80962. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  80963. /* ===========================================================================
  80964. * Insert string str in the dictionary and set match_head to the previous head
  80965. * of the hash chain (the most recent string with same hash key). Return
  80966. * the previous length of the hash chain.
  80967. * If this file is compiled with -DFASTEST, the compression level is forced
  80968. * to 1, and no hash chains are maintained.
  80969. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  80970. * input characters and the first MIN_MATCH bytes of str are valid
  80971. * (except for the last MIN_MATCH-1 bytes of the input file).
  80972. */
  80973. #ifdef FASTEST
  80974. #define INSERT_STRING(s, str, match_head) \
  80975. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80976. match_head = s->head[s->ins_h], \
  80977. s->head[s->ins_h] = (Pos)(str))
  80978. #else
  80979. #define INSERT_STRING(s, str, match_head) \
  80980. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  80981. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  80982. s->head[s->ins_h] = (Pos)(str))
  80983. #endif
  80984. /* ===========================================================================
  80985. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  80986. * prev[] will be initialized on the fly.
  80987. */
  80988. #define CLEAR_HASH(s) \
  80989. s->head[s->hash_size-1] = NIL; \
  80990. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  80991. /* ========================================================================= */
  80992. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  80993. {
  80994. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  80995. Z_DEFAULT_STRATEGY, version, stream_size);
  80996. /* To do: ignore strm->next_in if we use it as window */
  80997. }
  80998. /* ========================================================================= */
  80999. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81000. {
  81001. deflate_state *s;
  81002. int wrap = 1;
  81003. static const char my_version[] = ZLIB_VERSION;
  81004. ushf *overlay;
  81005. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81006. * output size for (length,distance) codes is <= 24 bits.
  81007. */
  81008. if (version == Z_NULL || version[0] != my_version[0] ||
  81009. stream_size != sizeof(z_stream)) {
  81010. return Z_VERSION_ERROR;
  81011. }
  81012. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81013. strm->msg = Z_NULL;
  81014. if (strm->zalloc == (alloc_func)0) {
  81015. strm->zalloc = zcalloc;
  81016. strm->opaque = (voidpf)0;
  81017. }
  81018. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81019. #ifdef FASTEST
  81020. if (level != 0) level = 1;
  81021. #else
  81022. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81023. #endif
  81024. if (windowBits < 0) { /* suppress zlib wrapper */
  81025. wrap = 0;
  81026. windowBits = -windowBits;
  81027. }
  81028. #ifdef GZIP
  81029. else if (windowBits > 15) {
  81030. wrap = 2; /* write gzip wrapper instead */
  81031. windowBits -= 16;
  81032. }
  81033. #endif
  81034. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81035. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81036. strategy < 0 || strategy > Z_FIXED) {
  81037. return Z_STREAM_ERROR;
  81038. }
  81039. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81040. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81041. if (s == Z_NULL) return Z_MEM_ERROR;
  81042. strm->state = (struct internal_state FAR *)s;
  81043. s->strm = strm;
  81044. s->wrap = wrap;
  81045. s->gzhead = Z_NULL;
  81046. s->w_bits = windowBits;
  81047. s->w_size = 1 << s->w_bits;
  81048. s->w_mask = s->w_size - 1;
  81049. s->hash_bits = memLevel + 7;
  81050. s->hash_size = 1 << s->hash_bits;
  81051. s->hash_mask = s->hash_size - 1;
  81052. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81053. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81054. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81055. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81056. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81057. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81058. s->pending_buf = (uchf *) overlay;
  81059. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81060. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81061. s->pending_buf == Z_NULL) {
  81062. s->status = FINISH_STATE;
  81063. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81064. deflateEnd (strm);
  81065. return Z_MEM_ERROR;
  81066. }
  81067. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81068. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81069. s->level = level;
  81070. s->strategy = strategy;
  81071. s->method = (Byte)method;
  81072. return deflateReset(strm);
  81073. }
  81074. /* ========================================================================= */
  81075. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81076. {
  81077. deflate_state *s;
  81078. uInt length = dictLength;
  81079. uInt n;
  81080. IPos hash_head = 0;
  81081. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81082. strm->state->wrap == 2 ||
  81083. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81084. return Z_STREAM_ERROR;
  81085. s = strm->state;
  81086. if (s->wrap)
  81087. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81088. if (length < MIN_MATCH) return Z_OK;
  81089. if (length > MAX_DIST(s)) {
  81090. length = MAX_DIST(s);
  81091. dictionary += dictLength - length; /* use the tail of the dictionary */
  81092. }
  81093. zmemcpy(s->window, dictionary, length);
  81094. s->strstart = length;
  81095. s->block_start = (long)length;
  81096. /* Insert all strings in the hash table (except for the last two bytes).
  81097. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81098. * call of fill_window.
  81099. */
  81100. s->ins_h = s->window[0];
  81101. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81102. for (n = 0; n <= length - MIN_MATCH; n++) {
  81103. INSERT_STRING(s, n, hash_head);
  81104. }
  81105. if (hash_head) hash_head = 0; /* to make compiler happy */
  81106. return Z_OK;
  81107. }
  81108. /* ========================================================================= */
  81109. int ZEXPORT deflateReset (z_streamp strm)
  81110. {
  81111. deflate_state *s;
  81112. if (strm == Z_NULL || strm->state == Z_NULL ||
  81113. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81114. return Z_STREAM_ERROR;
  81115. }
  81116. strm->total_in = strm->total_out = 0;
  81117. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81118. strm->data_type = Z_UNKNOWN;
  81119. s = (deflate_state *)strm->state;
  81120. s->pending = 0;
  81121. s->pending_out = s->pending_buf;
  81122. if (s->wrap < 0) {
  81123. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81124. }
  81125. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81126. strm->adler =
  81127. #ifdef GZIP
  81128. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81129. #endif
  81130. adler32(0L, Z_NULL, 0);
  81131. s->last_flush = Z_NO_FLUSH;
  81132. _tr_init(s);
  81133. lm_init(s);
  81134. return Z_OK;
  81135. }
  81136. /* ========================================================================= */
  81137. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81138. {
  81139. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81140. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81141. strm->state->gzhead = head;
  81142. return Z_OK;
  81143. }
  81144. /* ========================================================================= */
  81145. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81146. {
  81147. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81148. strm->state->bi_valid = bits;
  81149. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81150. return Z_OK;
  81151. }
  81152. /* ========================================================================= */
  81153. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81154. {
  81155. deflate_state *s;
  81156. compress_func func;
  81157. int err = Z_OK;
  81158. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81159. s = strm->state;
  81160. #ifdef FASTEST
  81161. if (level != 0) level = 1;
  81162. #else
  81163. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81164. #endif
  81165. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81166. return Z_STREAM_ERROR;
  81167. }
  81168. func = configuration_table[s->level].func;
  81169. if (func != configuration_table[level].func && strm->total_in != 0) {
  81170. /* Flush the last buffer: */
  81171. err = deflate(strm, Z_PARTIAL_FLUSH);
  81172. }
  81173. if (s->level != level) {
  81174. s->level = level;
  81175. s->max_lazy_match = configuration_table[level].max_lazy;
  81176. s->good_match = configuration_table[level].good_length;
  81177. s->nice_match = configuration_table[level].nice_length;
  81178. s->max_chain_length = configuration_table[level].max_chain;
  81179. }
  81180. s->strategy = strategy;
  81181. return err;
  81182. }
  81183. /* ========================================================================= */
  81184. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81185. {
  81186. deflate_state *s;
  81187. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81188. s = strm->state;
  81189. s->good_match = good_length;
  81190. s->max_lazy_match = max_lazy;
  81191. s->nice_match = nice_length;
  81192. s->max_chain_length = max_chain;
  81193. return Z_OK;
  81194. }
  81195. /* =========================================================================
  81196. * For the default windowBits of 15 and memLevel of 8, this function returns
  81197. * a close to exact, as well as small, upper bound on the compressed size.
  81198. * They are coded as constants here for a reason--if the #define's are
  81199. * changed, then this function needs to be changed as well. The return
  81200. * value for 15 and 8 only works for those exact settings.
  81201. *
  81202. * For any setting other than those defaults for windowBits and memLevel,
  81203. * the value returned is a conservative worst case for the maximum expansion
  81204. * resulting from using fixed blocks instead of stored blocks, which deflate
  81205. * can emit on compressed data for some combinations of the parameters.
  81206. *
  81207. * This function could be more sophisticated to provide closer upper bounds
  81208. * for every combination of windowBits and memLevel, as well as wrap.
  81209. * But even the conservative upper bound of about 14% expansion does not
  81210. * seem onerous for output buffer allocation.
  81211. */
  81212. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81213. {
  81214. deflate_state *s;
  81215. uLong destLen;
  81216. /* conservative upper bound */
  81217. destLen = sourceLen +
  81218. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81219. /* if can't get parameters, return conservative bound */
  81220. if (strm == Z_NULL || strm->state == Z_NULL)
  81221. return destLen;
  81222. /* if not default parameters, return conservative bound */
  81223. s = strm->state;
  81224. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81225. return destLen;
  81226. /* default settings: return tight bound for that case */
  81227. return compressBound(sourceLen);
  81228. }
  81229. /* =========================================================================
  81230. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81231. * IN assertion: the stream state is correct and there is enough room in
  81232. * pending_buf.
  81233. */
  81234. local void putShortMSB (deflate_state *s, uInt b)
  81235. {
  81236. put_byte(s, (Byte)(b >> 8));
  81237. put_byte(s, (Byte)(b & 0xff));
  81238. }
  81239. /* =========================================================================
  81240. * Flush as much pending output as possible. All deflate() output goes
  81241. * through this function so some applications may wish to modify it
  81242. * to avoid allocating a large strm->next_out buffer and copying into it.
  81243. * (See also read_buf()).
  81244. */
  81245. local void flush_pending (z_streamp strm)
  81246. {
  81247. unsigned len = strm->state->pending;
  81248. if (len > strm->avail_out) len = strm->avail_out;
  81249. if (len == 0) return;
  81250. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81251. strm->next_out += len;
  81252. strm->state->pending_out += len;
  81253. strm->total_out += len;
  81254. strm->avail_out -= len;
  81255. strm->state->pending -= len;
  81256. if (strm->state->pending == 0) {
  81257. strm->state->pending_out = strm->state->pending_buf;
  81258. }
  81259. }
  81260. /* ========================================================================= */
  81261. int ZEXPORT deflate (z_streamp strm, int flush)
  81262. {
  81263. int old_flush; /* value of flush param for previous deflate call */
  81264. deflate_state *s;
  81265. if (strm == Z_NULL || strm->state == Z_NULL ||
  81266. flush > Z_FINISH || flush < 0) {
  81267. return Z_STREAM_ERROR;
  81268. }
  81269. s = strm->state;
  81270. if (strm->next_out == Z_NULL ||
  81271. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81272. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81273. ERR_RETURN(strm, Z_STREAM_ERROR);
  81274. }
  81275. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81276. s->strm = strm; /* just in case */
  81277. old_flush = s->last_flush;
  81278. s->last_flush = flush;
  81279. /* Write the header */
  81280. if (s->status == INIT_STATE) {
  81281. #ifdef GZIP
  81282. if (s->wrap == 2) {
  81283. strm->adler = crc32(0L, Z_NULL, 0);
  81284. put_byte(s, 31);
  81285. put_byte(s, 139);
  81286. put_byte(s, 8);
  81287. if (s->gzhead == NULL) {
  81288. put_byte(s, 0);
  81289. put_byte(s, 0);
  81290. put_byte(s, 0);
  81291. put_byte(s, 0);
  81292. put_byte(s, 0);
  81293. put_byte(s, s->level == 9 ? 2 :
  81294. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81295. 4 : 0));
  81296. put_byte(s, OS_CODE);
  81297. s->status = BUSY_STATE;
  81298. }
  81299. else {
  81300. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81301. (s->gzhead->hcrc ? 2 : 0) +
  81302. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81303. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81304. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81305. );
  81306. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81307. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81308. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81309. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81310. put_byte(s, s->level == 9 ? 2 :
  81311. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81312. 4 : 0));
  81313. put_byte(s, s->gzhead->os & 0xff);
  81314. if (s->gzhead->extra != NULL) {
  81315. put_byte(s, s->gzhead->extra_len & 0xff);
  81316. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81317. }
  81318. if (s->gzhead->hcrc)
  81319. strm->adler = crc32(strm->adler, s->pending_buf,
  81320. s->pending);
  81321. s->gzindex = 0;
  81322. s->status = EXTRA_STATE;
  81323. }
  81324. }
  81325. else
  81326. #endif
  81327. {
  81328. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81329. uInt level_flags;
  81330. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81331. level_flags = 0;
  81332. else if (s->level < 6)
  81333. level_flags = 1;
  81334. else if (s->level == 6)
  81335. level_flags = 2;
  81336. else
  81337. level_flags = 3;
  81338. header |= (level_flags << 6);
  81339. if (s->strstart != 0) header |= PRESET_DICT;
  81340. header += 31 - (header % 31);
  81341. s->status = BUSY_STATE;
  81342. putShortMSB(s, header);
  81343. /* Save the adler32 of the preset dictionary: */
  81344. if (s->strstart != 0) {
  81345. putShortMSB(s, (uInt)(strm->adler >> 16));
  81346. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81347. }
  81348. strm->adler = adler32(0L, Z_NULL, 0);
  81349. }
  81350. }
  81351. #ifdef GZIP
  81352. if (s->status == EXTRA_STATE) {
  81353. if (s->gzhead->extra != NULL) {
  81354. uInt beg = s->pending; /* start of bytes to update crc */
  81355. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81356. if (s->pending == s->pending_buf_size) {
  81357. if (s->gzhead->hcrc && s->pending > beg)
  81358. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81359. s->pending - beg);
  81360. flush_pending(strm);
  81361. beg = s->pending;
  81362. if (s->pending == s->pending_buf_size)
  81363. break;
  81364. }
  81365. put_byte(s, s->gzhead->extra[s->gzindex]);
  81366. s->gzindex++;
  81367. }
  81368. if (s->gzhead->hcrc && s->pending > beg)
  81369. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81370. s->pending - beg);
  81371. if (s->gzindex == s->gzhead->extra_len) {
  81372. s->gzindex = 0;
  81373. s->status = NAME_STATE;
  81374. }
  81375. }
  81376. else
  81377. s->status = NAME_STATE;
  81378. }
  81379. if (s->status == NAME_STATE) {
  81380. if (s->gzhead->name != NULL) {
  81381. uInt beg = s->pending; /* start of bytes to update crc */
  81382. int val;
  81383. do {
  81384. if (s->pending == s->pending_buf_size) {
  81385. if (s->gzhead->hcrc && s->pending > beg)
  81386. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81387. s->pending - beg);
  81388. flush_pending(strm);
  81389. beg = s->pending;
  81390. if (s->pending == s->pending_buf_size) {
  81391. val = 1;
  81392. break;
  81393. }
  81394. }
  81395. val = s->gzhead->name[s->gzindex++];
  81396. put_byte(s, val);
  81397. } while (val != 0);
  81398. if (s->gzhead->hcrc && s->pending > beg)
  81399. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81400. s->pending - beg);
  81401. if (val == 0) {
  81402. s->gzindex = 0;
  81403. s->status = COMMENT_STATE;
  81404. }
  81405. }
  81406. else
  81407. s->status = COMMENT_STATE;
  81408. }
  81409. if (s->status == COMMENT_STATE) {
  81410. if (s->gzhead->comment != NULL) {
  81411. uInt beg = s->pending; /* start of bytes to update crc */
  81412. int val;
  81413. do {
  81414. if (s->pending == s->pending_buf_size) {
  81415. if (s->gzhead->hcrc && s->pending > beg)
  81416. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81417. s->pending - beg);
  81418. flush_pending(strm);
  81419. beg = s->pending;
  81420. if (s->pending == s->pending_buf_size) {
  81421. val = 1;
  81422. break;
  81423. }
  81424. }
  81425. val = s->gzhead->comment[s->gzindex++];
  81426. put_byte(s, val);
  81427. } while (val != 0);
  81428. if (s->gzhead->hcrc && s->pending > beg)
  81429. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81430. s->pending - beg);
  81431. if (val == 0)
  81432. s->status = HCRC_STATE;
  81433. }
  81434. else
  81435. s->status = HCRC_STATE;
  81436. }
  81437. if (s->status == HCRC_STATE) {
  81438. if (s->gzhead->hcrc) {
  81439. if (s->pending + 2 > s->pending_buf_size)
  81440. flush_pending(strm);
  81441. if (s->pending + 2 <= s->pending_buf_size) {
  81442. put_byte(s, (Byte)(strm->adler & 0xff));
  81443. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81444. strm->adler = crc32(0L, Z_NULL, 0);
  81445. s->status = BUSY_STATE;
  81446. }
  81447. }
  81448. else
  81449. s->status = BUSY_STATE;
  81450. }
  81451. #endif
  81452. /* Flush as much pending output as possible */
  81453. if (s->pending != 0) {
  81454. flush_pending(strm);
  81455. if (strm->avail_out == 0) {
  81456. /* Since avail_out is 0, deflate will be called again with
  81457. * more output space, but possibly with both pending and
  81458. * avail_in equal to zero. There won't be anything to do,
  81459. * but this is not an error situation so make sure we
  81460. * return OK instead of BUF_ERROR at next call of deflate:
  81461. */
  81462. s->last_flush = -1;
  81463. return Z_OK;
  81464. }
  81465. /* Make sure there is something to do and avoid duplicate consecutive
  81466. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81467. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81468. */
  81469. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81470. flush != Z_FINISH) {
  81471. ERR_RETURN(strm, Z_BUF_ERROR);
  81472. }
  81473. /* User must not provide more input after the first FINISH: */
  81474. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81475. ERR_RETURN(strm, Z_BUF_ERROR);
  81476. }
  81477. /* Start a new block or continue the current one.
  81478. */
  81479. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81480. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81481. block_state bstate;
  81482. bstate = (*(configuration_table[s->level].func))(s, flush);
  81483. if (bstate == finish_started || bstate == finish_done) {
  81484. s->status = FINISH_STATE;
  81485. }
  81486. if (bstate == need_more || bstate == finish_started) {
  81487. if (strm->avail_out == 0) {
  81488. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81489. }
  81490. return Z_OK;
  81491. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81492. * of deflate should use the same flush parameter to make sure
  81493. * that the flush is complete. So we don't have to output an
  81494. * empty block here, this will be done at next call. This also
  81495. * ensures that for a very small output buffer, we emit at most
  81496. * one empty block.
  81497. */
  81498. }
  81499. if (bstate == block_done) {
  81500. if (flush == Z_PARTIAL_FLUSH) {
  81501. _tr_align(s);
  81502. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81503. _tr_stored_block(s, (char*)0, 0L, 0);
  81504. /* For a full flush, this empty block will be recognized
  81505. * as a special marker by inflate_sync().
  81506. */
  81507. if (flush == Z_FULL_FLUSH) {
  81508. CLEAR_HASH(s); /* forget history */
  81509. }
  81510. }
  81511. flush_pending(strm);
  81512. if (strm->avail_out == 0) {
  81513. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81514. return Z_OK;
  81515. }
  81516. }
  81517. }
  81518. Assert(strm->avail_out > 0, "bug2");
  81519. if (flush != Z_FINISH) return Z_OK;
  81520. if (s->wrap <= 0) return Z_STREAM_END;
  81521. /* Write the trailer */
  81522. #ifdef GZIP
  81523. if (s->wrap == 2) {
  81524. put_byte(s, (Byte)(strm->adler & 0xff));
  81525. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81526. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81527. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81528. put_byte(s, (Byte)(strm->total_in & 0xff));
  81529. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81530. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81531. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81532. }
  81533. else
  81534. #endif
  81535. {
  81536. putShortMSB(s, (uInt)(strm->adler >> 16));
  81537. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81538. }
  81539. flush_pending(strm);
  81540. /* If avail_out is zero, the application will call deflate again
  81541. * to flush the rest.
  81542. */
  81543. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81544. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81545. }
  81546. /* ========================================================================= */
  81547. int ZEXPORT deflateEnd (z_streamp strm)
  81548. {
  81549. int status;
  81550. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81551. status = strm->state->status;
  81552. if (status != INIT_STATE &&
  81553. status != EXTRA_STATE &&
  81554. status != NAME_STATE &&
  81555. status != COMMENT_STATE &&
  81556. status != HCRC_STATE &&
  81557. status != BUSY_STATE &&
  81558. status != FINISH_STATE) {
  81559. return Z_STREAM_ERROR;
  81560. }
  81561. /* Deallocate in reverse order of allocations: */
  81562. TRY_FREE(strm, strm->state->pending_buf);
  81563. TRY_FREE(strm, strm->state->head);
  81564. TRY_FREE(strm, strm->state->prev);
  81565. TRY_FREE(strm, strm->state->window);
  81566. ZFREE(strm, strm->state);
  81567. strm->state = Z_NULL;
  81568. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81569. }
  81570. /* =========================================================================
  81571. * Copy the source state to the destination state.
  81572. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81573. * doesn't have enough memory anyway to duplicate compression states).
  81574. */
  81575. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81576. {
  81577. #ifdef MAXSEG_64K
  81578. return Z_STREAM_ERROR;
  81579. #else
  81580. deflate_state *ds;
  81581. deflate_state *ss;
  81582. ushf *overlay;
  81583. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81584. return Z_STREAM_ERROR;
  81585. }
  81586. ss = source->state;
  81587. zmemcpy(dest, source, sizeof(z_stream));
  81588. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81589. if (ds == Z_NULL) return Z_MEM_ERROR;
  81590. dest->state = (struct internal_state FAR *) ds;
  81591. zmemcpy(ds, ss, sizeof(deflate_state));
  81592. ds->strm = dest;
  81593. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81594. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81595. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81596. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81597. ds->pending_buf = (uchf *) overlay;
  81598. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81599. ds->pending_buf == Z_NULL) {
  81600. deflateEnd (dest);
  81601. return Z_MEM_ERROR;
  81602. }
  81603. /* following zmemcpy do not work for 16-bit MSDOS */
  81604. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81605. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81606. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81607. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81608. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81609. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81610. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81611. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81612. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81613. ds->bl_desc.dyn_tree = ds->bl_tree;
  81614. return Z_OK;
  81615. #endif /* MAXSEG_64K */
  81616. }
  81617. /* ===========================================================================
  81618. * Read a new buffer from the current input stream, update the adler32
  81619. * and total number of bytes read. All deflate() input goes through
  81620. * this function so some applications may wish to modify it to avoid
  81621. * allocating a large strm->next_in buffer and copying from it.
  81622. * (See also flush_pending()).
  81623. */
  81624. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81625. {
  81626. unsigned len = strm->avail_in;
  81627. if (len > size) len = size;
  81628. if (len == 0) return 0;
  81629. strm->avail_in -= len;
  81630. if (strm->state->wrap == 1) {
  81631. strm->adler = adler32(strm->adler, strm->next_in, len);
  81632. }
  81633. #ifdef GZIP
  81634. else if (strm->state->wrap == 2) {
  81635. strm->adler = crc32(strm->adler, strm->next_in, len);
  81636. }
  81637. #endif
  81638. zmemcpy(buf, strm->next_in, len);
  81639. strm->next_in += len;
  81640. strm->total_in += len;
  81641. return (int)len;
  81642. }
  81643. /* ===========================================================================
  81644. * Initialize the "longest match" routines for a new zlib stream
  81645. */
  81646. local void lm_init (deflate_state *s)
  81647. {
  81648. s->window_size = (ulg)2L*s->w_size;
  81649. CLEAR_HASH(s);
  81650. /* Set the default configuration parameters:
  81651. */
  81652. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81653. s->good_match = configuration_table[s->level].good_length;
  81654. s->nice_match = configuration_table[s->level].nice_length;
  81655. s->max_chain_length = configuration_table[s->level].max_chain;
  81656. s->strstart = 0;
  81657. s->block_start = 0L;
  81658. s->lookahead = 0;
  81659. s->match_length = s->prev_length = MIN_MATCH-1;
  81660. s->match_available = 0;
  81661. s->ins_h = 0;
  81662. #ifndef FASTEST
  81663. #ifdef ASMV
  81664. match_init(); /* initialize the asm code */
  81665. #endif
  81666. #endif
  81667. }
  81668. #ifndef FASTEST
  81669. /* ===========================================================================
  81670. * Set match_start to the longest match starting at the given string and
  81671. * return its length. Matches shorter or equal to prev_length are discarded,
  81672. * in which case the result is equal to prev_length and match_start is
  81673. * garbage.
  81674. * IN assertions: cur_match is the head of the hash chain for the current
  81675. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  81676. * OUT assertion: the match length is not greater than s->lookahead.
  81677. */
  81678. #ifndef ASMV
  81679. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  81680. * match.S. The code will be functionally equivalent.
  81681. */
  81682. local uInt longest_match(deflate_state *s, IPos cur_match)
  81683. {
  81684. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  81685. register Bytef *scan = s->window + s->strstart; /* current string */
  81686. register Bytef *match; /* matched string */
  81687. register int len; /* length of current match */
  81688. int best_len = s->prev_length; /* best match length so far */
  81689. int nice_match = s->nice_match; /* stop if match long enough */
  81690. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  81691. s->strstart - (IPos)MAX_DIST(s) : NIL;
  81692. /* Stop when cur_match becomes <= limit. To simplify the code,
  81693. * we prevent matches with the string of window index 0.
  81694. */
  81695. Posf *prev = s->prev;
  81696. uInt wmask = s->w_mask;
  81697. #ifdef UNALIGNED_OK
  81698. /* Compare two bytes at a time. Note: this is not always beneficial.
  81699. * Try with and without -DUNALIGNED_OK to check.
  81700. */
  81701. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  81702. register ush scan_start = *(ushf*)scan;
  81703. register ush scan_end = *(ushf*)(scan+best_len-1);
  81704. #else
  81705. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81706. register Byte scan_end1 = scan[best_len-1];
  81707. register Byte scan_end = scan[best_len];
  81708. #endif
  81709. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81710. * It is easy to get rid of this optimization if necessary.
  81711. */
  81712. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81713. /* Do not waste too much time if we already have a good match: */
  81714. if (s->prev_length >= s->good_match) {
  81715. chain_length >>= 2;
  81716. }
  81717. /* Do not look for matches beyond the end of the input. This is necessary
  81718. * to make deflate deterministic.
  81719. */
  81720. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  81721. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81722. do {
  81723. Assert(cur_match < s->strstart, "no future");
  81724. match = s->window + cur_match;
  81725. /* Skip to next match if the match length cannot increase
  81726. * or if the match length is less than 2. Note that the checks below
  81727. * for insufficient lookahead only occur occasionally for performance
  81728. * reasons. Therefore uninitialized memory will be accessed, and
  81729. * conditional jumps will be made that depend on those values.
  81730. * However the length of the match is limited to the lookahead, so
  81731. * the output of deflate is not affected by the uninitialized values.
  81732. */
  81733. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  81734. /* This code assumes sizeof(unsigned short) == 2. Do not use
  81735. * UNALIGNED_OK if your compiler uses a different size.
  81736. */
  81737. if (*(ushf*)(match+best_len-1) != scan_end ||
  81738. *(ushf*)match != scan_start) continue;
  81739. /* It is not necessary to compare scan[2] and match[2] since they are
  81740. * always equal when the other bytes match, given that the hash keys
  81741. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  81742. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  81743. * lookahead only every 4th comparison; the 128th check will be made
  81744. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  81745. * necessary to put more guard bytes at the end of the window, or
  81746. * to check more often for insufficient lookahead.
  81747. */
  81748. Assert(scan[2] == match[2], "scan[2]?");
  81749. scan++, match++;
  81750. do {
  81751. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81752. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81753. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81754. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  81755. scan < strend);
  81756. /* The funny "do {}" generates better code on most compilers */
  81757. /* Here, scan <= window+strstart+257 */
  81758. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81759. if (*scan == *match) scan++;
  81760. len = (MAX_MATCH - 1) - (int)(strend-scan);
  81761. scan = strend - (MAX_MATCH-1);
  81762. #else /* UNALIGNED_OK */
  81763. if (match[best_len] != scan_end ||
  81764. match[best_len-1] != scan_end1 ||
  81765. *match != *scan ||
  81766. *++match != scan[1]) continue;
  81767. /* The check at best_len-1 can be removed because it will be made
  81768. * again later. (This heuristic is not always a win.)
  81769. * It is not necessary to compare scan[2] and match[2] since they
  81770. * are always equal when the other bytes match, given that
  81771. * the hash keys are equal and that HASH_BITS >= 8.
  81772. */
  81773. scan += 2, match++;
  81774. Assert(*scan == *match, "match[2]?");
  81775. /* We check for insufficient lookahead only every 8th comparison;
  81776. * the 256th check will be made at strstart+258.
  81777. */
  81778. do {
  81779. } while (*++scan == *++match && *++scan == *++match &&
  81780. *++scan == *++match && *++scan == *++match &&
  81781. *++scan == *++match && *++scan == *++match &&
  81782. *++scan == *++match && *++scan == *++match &&
  81783. scan < strend);
  81784. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81785. len = MAX_MATCH - (int)(strend - scan);
  81786. scan = strend - MAX_MATCH;
  81787. #endif /* UNALIGNED_OK */
  81788. if (len > best_len) {
  81789. s->match_start = cur_match;
  81790. best_len = len;
  81791. if (len >= nice_match) break;
  81792. #ifdef UNALIGNED_OK
  81793. scan_end = *(ushf*)(scan+best_len-1);
  81794. #else
  81795. scan_end1 = scan[best_len-1];
  81796. scan_end = scan[best_len];
  81797. #endif
  81798. }
  81799. } while ((cur_match = prev[cur_match & wmask]) > limit
  81800. && --chain_length != 0);
  81801. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  81802. return s->lookahead;
  81803. }
  81804. #endif /* ASMV */
  81805. #endif /* FASTEST */
  81806. /* ---------------------------------------------------------------------------
  81807. * Optimized version for level == 1 or strategy == Z_RLE only
  81808. */
  81809. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  81810. {
  81811. register Bytef *scan = s->window + s->strstart; /* current string */
  81812. register Bytef *match; /* matched string */
  81813. register int len; /* length of current match */
  81814. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  81815. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  81816. * It is easy to get rid of this optimization if necessary.
  81817. */
  81818. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  81819. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  81820. Assert(cur_match < s->strstart, "no future");
  81821. match = s->window + cur_match;
  81822. /* Return failure if the match length is less than 2:
  81823. */
  81824. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  81825. /* The check at best_len-1 can be removed because it will be made
  81826. * again later. (This heuristic is not always a win.)
  81827. * It is not necessary to compare scan[2] and match[2] since they
  81828. * are always equal when the other bytes match, given that
  81829. * the hash keys are equal and that HASH_BITS >= 8.
  81830. */
  81831. scan += 2, match += 2;
  81832. Assert(*scan == *match, "match[2]?");
  81833. /* We check for insufficient lookahead only every 8th comparison;
  81834. * the 256th check will be made at strstart+258.
  81835. */
  81836. do {
  81837. } while (*++scan == *++match && *++scan == *++match &&
  81838. *++scan == *++match && *++scan == *++match &&
  81839. *++scan == *++match && *++scan == *++match &&
  81840. *++scan == *++match && *++scan == *++match &&
  81841. scan < strend);
  81842. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  81843. len = MAX_MATCH - (int)(strend - scan);
  81844. if (len < MIN_MATCH) return MIN_MATCH - 1;
  81845. s->match_start = cur_match;
  81846. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  81847. }
  81848. #ifdef DEBUG
  81849. /* ===========================================================================
  81850. * Check that the match at match_start is indeed a match.
  81851. */
  81852. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  81853. {
  81854. /* check that the match is indeed a match */
  81855. if (zmemcmp(s->window + match,
  81856. s->window + start, length) != EQUAL) {
  81857. fprintf(stderr, " start %u, match %u, length %d\n",
  81858. start, match, length);
  81859. do {
  81860. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  81861. } while (--length != 0);
  81862. z_error("invalid match");
  81863. }
  81864. if (z_verbose > 1) {
  81865. fprintf(stderr,"\\[%d,%d]", start-match, length);
  81866. do { putc(s->window[start++], stderr); } while (--length != 0);
  81867. }
  81868. }
  81869. #else
  81870. # define check_match(s, start, match, length)
  81871. #endif /* DEBUG */
  81872. /* ===========================================================================
  81873. * Fill the window when the lookahead becomes insufficient.
  81874. * Updates strstart and lookahead.
  81875. *
  81876. * IN assertion: lookahead < MIN_LOOKAHEAD
  81877. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  81878. * At least one byte has been read, or avail_in == 0; reads are
  81879. * performed for at least two bytes (required for the zip translate_eol
  81880. * option -- not supported here).
  81881. */
  81882. local void fill_window (deflate_state *s)
  81883. {
  81884. register unsigned n, m;
  81885. register Posf *p;
  81886. unsigned more; /* Amount of free space at the end of the window. */
  81887. uInt wsize = s->w_size;
  81888. do {
  81889. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  81890. /* Deal with !@#$% 64K limit: */
  81891. if (sizeof(int) <= 2) {
  81892. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  81893. more = wsize;
  81894. } else if (more == (unsigned)(-1)) {
  81895. /* Very unlikely, but possible on 16 bit machine if
  81896. * strstart == 0 && lookahead == 1 (input done a byte at time)
  81897. */
  81898. more--;
  81899. }
  81900. }
  81901. /* If the window is almost full and there is insufficient lookahead,
  81902. * move the upper half to the lower one to make room in the upper half.
  81903. */
  81904. if (s->strstart >= wsize+MAX_DIST(s)) {
  81905. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  81906. s->match_start -= wsize;
  81907. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  81908. s->block_start -= (long) wsize;
  81909. /* Slide the hash table (could be avoided with 32 bit values
  81910. at the expense of memory usage). We slide even when level == 0
  81911. to keep the hash table consistent if we switch back to level > 0
  81912. later. (Using level 0 permanently is not an optimal usage of
  81913. zlib, so we don't care about this pathological case.)
  81914. */
  81915. /* %%% avoid this when Z_RLE */
  81916. n = s->hash_size;
  81917. p = &s->head[n];
  81918. do {
  81919. m = *--p;
  81920. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81921. } while (--n);
  81922. n = wsize;
  81923. #ifndef FASTEST
  81924. p = &s->prev[n];
  81925. do {
  81926. m = *--p;
  81927. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  81928. /* If n is not on any hash chain, prev[n] is garbage but
  81929. * its value will never be used.
  81930. */
  81931. } while (--n);
  81932. #endif
  81933. more += wsize;
  81934. }
  81935. if (s->strm->avail_in == 0) return;
  81936. /* If there was no sliding:
  81937. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  81938. * more == window_size - lookahead - strstart
  81939. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  81940. * => more >= window_size - 2*WSIZE + 2
  81941. * In the BIG_MEM or MMAP case (not yet supported),
  81942. * window_size == input_size + MIN_LOOKAHEAD &&
  81943. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  81944. * Otherwise, window_size == 2*WSIZE so more >= 2.
  81945. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  81946. */
  81947. Assert(more >= 2, "more < 2");
  81948. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  81949. s->lookahead += n;
  81950. /* Initialize the hash value now that we have some input: */
  81951. if (s->lookahead >= MIN_MATCH) {
  81952. s->ins_h = s->window[s->strstart];
  81953. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  81954. #if MIN_MATCH != 3
  81955. Call UPDATE_HASH() MIN_MATCH-3 more times
  81956. #endif
  81957. }
  81958. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  81959. * but this is not important since only literal bytes will be emitted.
  81960. */
  81961. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  81962. }
  81963. /* ===========================================================================
  81964. * Flush the current block, with given end-of-file flag.
  81965. * IN assertion: strstart is set to the end of the current match.
  81966. */
  81967. #define FLUSH_BLOCK_ONLY(s, eof) { \
  81968. _tr_flush_block(s, (s->block_start >= 0L ? \
  81969. (charf *)&s->window[(unsigned)s->block_start] : \
  81970. (charf *)Z_NULL), \
  81971. (ulg)((long)s->strstart - s->block_start), \
  81972. (eof)); \
  81973. s->block_start = s->strstart; \
  81974. flush_pending(s->strm); \
  81975. Tracev((stderr,"[FLUSH]")); \
  81976. }
  81977. /* Same but force premature exit if necessary. */
  81978. #define FLUSH_BLOCK(s, eof) { \
  81979. FLUSH_BLOCK_ONLY(s, eof); \
  81980. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  81981. }
  81982. /* ===========================================================================
  81983. * Copy without compression as much as possible from the input stream, return
  81984. * the current block state.
  81985. * This function does not insert new strings in the dictionary since
  81986. * uncompressible data is probably not useful. This function is used
  81987. * only for the level=0 compression option.
  81988. * NOTE: this function should be optimized to avoid extra copying from
  81989. * window to pending_buf.
  81990. */
  81991. local block_state deflate_stored(deflate_state *s, int flush)
  81992. {
  81993. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  81994. * to pending_buf_size, and each stored block has a 5 byte header:
  81995. */
  81996. ulg max_block_size = 0xffff;
  81997. ulg max_start;
  81998. if (max_block_size > s->pending_buf_size - 5) {
  81999. max_block_size = s->pending_buf_size - 5;
  82000. }
  82001. /* Copy as much as possible from input to output: */
  82002. for (;;) {
  82003. /* Fill the window as much as possible: */
  82004. if (s->lookahead <= 1) {
  82005. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82006. s->block_start >= (long)s->w_size, "slide too late");
  82007. fill_window(s);
  82008. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82009. if (s->lookahead == 0) break; /* flush the current block */
  82010. }
  82011. Assert(s->block_start >= 0L, "block gone");
  82012. s->strstart += s->lookahead;
  82013. s->lookahead = 0;
  82014. /* Emit a stored block if pending_buf will be full: */
  82015. max_start = s->block_start + max_block_size;
  82016. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82017. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82018. s->lookahead = (uInt)(s->strstart - max_start);
  82019. s->strstart = (uInt)max_start;
  82020. FLUSH_BLOCK(s, 0);
  82021. }
  82022. /* Flush if we may have to slide, otherwise block_start may become
  82023. * negative and the data will be gone:
  82024. */
  82025. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82026. FLUSH_BLOCK(s, 0);
  82027. }
  82028. }
  82029. FLUSH_BLOCK(s, flush == Z_FINISH);
  82030. return flush == Z_FINISH ? finish_done : block_done;
  82031. }
  82032. /* ===========================================================================
  82033. * Compress as much as possible from the input stream, return the current
  82034. * block state.
  82035. * This function does not perform lazy evaluation of matches and inserts
  82036. * new strings in the dictionary only for unmatched strings or for short
  82037. * matches. It is used only for the fast compression options.
  82038. */
  82039. local block_state deflate_fast(deflate_state *s, int flush)
  82040. {
  82041. IPos hash_head = NIL; /* head of the hash chain */
  82042. int bflush; /* set if current block must be flushed */
  82043. for (;;) {
  82044. /* Make sure that we always have enough lookahead, except
  82045. * at the end of the input file. We need MAX_MATCH bytes
  82046. * for the next match, plus MIN_MATCH bytes to insert the
  82047. * string following the next match.
  82048. */
  82049. if (s->lookahead < MIN_LOOKAHEAD) {
  82050. fill_window(s);
  82051. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82052. return need_more;
  82053. }
  82054. if (s->lookahead == 0) break; /* flush the current block */
  82055. }
  82056. /* Insert the string window[strstart .. strstart+2] in the
  82057. * dictionary, and set hash_head to the head of the hash chain:
  82058. */
  82059. if (s->lookahead >= MIN_MATCH) {
  82060. INSERT_STRING(s, s->strstart, hash_head);
  82061. }
  82062. /* Find the longest match, discarding those <= prev_length.
  82063. * At this point we have always match_length < MIN_MATCH
  82064. */
  82065. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82066. /* To simplify the code, we prevent matches with the string
  82067. * of window index 0 (in particular we have to avoid a match
  82068. * of the string with itself at the start of the input file).
  82069. */
  82070. #ifdef FASTEST
  82071. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82072. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82073. s->match_length = longest_match_fast (s, hash_head);
  82074. }
  82075. #else
  82076. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82077. s->match_length = longest_match (s, hash_head);
  82078. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82079. s->match_length = longest_match_fast (s, hash_head);
  82080. }
  82081. #endif
  82082. /* longest_match() or longest_match_fast() sets match_start */
  82083. }
  82084. if (s->match_length >= MIN_MATCH) {
  82085. check_match(s, s->strstart, s->match_start, s->match_length);
  82086. _tr_tally_dist(s, s->strstart - s->match_start,
  82087. s->match_length - MIN_MATCH, bflush);
  82088. s->lookahead -= s->match_length;
  82089. /* Insert new strings in the hash table only if the match length
  82090. * is not too large. This saves time but degrades compression.
  82091. */
  82092. #ifndef FASTEST
  82093. if (s->match_length <= s->max_insert_length &&
  82094. s->lookahead >= MIN_MATCH) {
  82095. s->match_length--; /* string at strstart already in table */
  82096. do {
  82097. s->strstart++;
  82098. INSERT_STRING(s, s->strstart, hash_head);
  82099. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82100. * always MIN_MATCH bytes ahead.
  82101. */
  82102. } while (--s->match_length != 0);
  82103. s->strstart++;
  82104. } else
  82105. #endif
  82106. {
  82107. s->strstart += s->match_length;
  82108. s->match_length = 0;
  82109. s->ins_h = s->window[s->strstart];
  82110. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82111. #if MIN_MATCH != 3
  82112. Call UPDATE_HASH() MIN_MATCH-3 more times
  82113. #endif
  82114. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82115. * matter since it will be recomputed at next deflate call.
  82116. */
  82117. }
  82118. } else {
  82119. /* No match, output a literal byte */
  82120. Tracevv((stderr,"%c", s->window[s->strstart]));
  82121. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82122. s->lookahead--;
  82123. s->strstart++;
  82124. }
  82125. if (bflush) FLUSH_BLOCK(s, 0);
  82126. }
  82127. FLUSH_BLOCK(s, flush == Z_FINISH);
  82128. return flush == Z_FINISH ? finish_done : block_done;
  82129. }
  82130. #ifndef FASTEST
  82131. /* ===========================================================================
  82132. * Same as above, but achieves better compression. We use a lazy
  82133. * evaluation for matches: a match is finally adopted only if there is
  82134. * no better match at the next window position.
  82135. */
  82136. local block_state deflate_slow(deflate_state *s, int flush)
  82137. {
  82138. IPos hash_head = NIL; /* head of hash chain */
  82139. int bflush; /* set if current block must be flushed */
  82140. /* Process the input block. */
  82141. for (;;) {
  82142. /* Make sure that we always have enough lookahead, except
  82143. * at the end of the input file. We need MAX_MATCH bytes
  82144. * for the next match, plus MIN_MATCH bytes to insert the
  82145. * string following the next match.
  82146. */
  82147. if (s->lookahead < MIN_LOOKAHEAD) {
  82148. fill_window(s);
  82149. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82150. return need_more;
  82151. }
  82152. if (s->lookahead == 0) break; /* flush the current block */
  82153. }
  82154. /* Insert the string window[strstart .. strstart+2] in the
  82155. * dictionary, and set hash_head to the head of the hash chain:
  82156. */
  82157. if (s->lookahead >= MIN_MATCH) {
  82158. INSERT_STRING(s, s->strstart, hash_head);
  82159. }
  82160. /* Find the longest match, discarding those <= prev_length.
  82161. */
  82162. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82163. s->match_length = MIN_MATCH-1;
  82164. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82165. s->strstart - hash_head <= MAX_DIST(s)) {
  82166. /* To simplify the code, we prevent matches with the string
  82167. * of window index 0 (in particular we have to avoid a match
  82168. * of the string with itself at the start of the input file).
  82169. */
  82170. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82171. s->match_length = longest_match (s, hash_head);
  82172. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82173. s->match_length = longest_match_fast (s, hash_head);
  82174. }
  82175. /* longest_match() or longest_match_fast() sets match_start */
  82176. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82177. #if TOO_FAR <= 32767
  82178. || (s->match_length == MIN_MATCH &&
  82179. s->strstart - s->match_start > TOO_FAR)
  82180. #endif
  82181. )) {
  82182. /* If prev_match is also MIN_MATCH, match_start is garbage
  82183. * but we will ignore the current match anyway.
  82184. */
  82185. s->match_length = MIN_MATCH-1;
  82186. }
  82187. }
  82188. /* If there was a match at the previous step and the current
  82189. * match is not better, output the previous match:
  82190. */
  82191. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82192. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82193. /* Do not insert strings in hash table beyond this. */
  82194. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82195. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82196. s->prev_length - MIN_MATCH, bflush);
  82197. /* Insert in hash table all strings up to the end of the match.
  82198. * strstart-1 and strstart are already inserted. If there is not
  82199. * enough lookahead, the last two strings are not inserted in
  82200. * the hash table.
  82201. */
  82202. s->lookahead -= s->prev_length-1;
  82203. s->prev_length -= 2;
  82204. do {
  82205. if (++s->strstart <= max_insert) {
  82206. INSERT_STRING(s, s->strstart, hash_head);
  82207. }
  82208. } while (--s->prev_length != 0);
  82209. s->match_available = 0;
  82210. s->match_length = MIN_MATCH-1;
  82211. s->strstart++;
  82212. if (bflush) FLUSH_BLOCK(s, 0);
  82213. } else if (s->match_available) {
  82214. /* If there was no match at the previous position, output a
  82215. * single literal. If there was a match but the current match
  82216. * is longer, truncate the previous match to a single literal.
  82217. */
  82218. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82219. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82220. if (bflush) {
  82221. FLUSH_BLOCK_ONLY(s, 0);
  82222. }
  82223. s->strstart++;
  82224. s->lookahead--;
  82225. if (s->strm->avail_out == 0) return need_more;
  82226. } else {
  82227. /* There is no previous match to compare with, wait for
  82228. * the next step to decide.
  82229. */
  82230. s->match_available = 1;
  82231. s->strstart++;
  82232. s->lookahead--;
  82233. }
  82234. }
  82235. Assert (flush != Z_NO_FLUSH, "no flush?");
  82236. if (s->match_available) {
  82237. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82238. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82239. s->match_available = 0;
  82240. }
  82241. FLUSH_BLOCK(s, flush == Z_FINISH);
  82242. return flush == Z_FINISH ? finish_done : block_done;
  82243. }
  82244. #endif /* FASTEST */
  82245. #if 0
  82246. /* ===========================================================================
  82247. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82248. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82249. * deflate switches away from Z_RLE.)
  82250. */
  82251. local block_state deflate_rle(s, flush)
  82252. deflate_state *s;
  82253. int flush;
  82254. {
  82255. int bflush; /* set if current block must be flushed */
  82256. uInt run; /* length of run */
  82257. uInt max; /* maximum length of run */
  82258. uInt prev; /* byte at distance one to match */
  82259. Bytef *scan; /* scan for end of run */
  82260. for (;;) {
  82261. /* Make sure that we always have enough lookahead, except
  82262. * at the end of the input file. We need MAX_MATCH bytes
  82263. * for the longest encodable run.
  82264. */
  82265. if (s->lookahead < MAX_MATCH) {
  82266. fill_window(s);
  82267. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82268. return need_more;
  82269. }
  82270. if (s->lookahead == 0) break; /* flush the current block */
  82271. }
  82272. /* See how many times the previous byte repeats */
  82273. run = 0;
  82274. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82275. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82276. scan = s->window + s->strstart - 1;
  82277. prev = *scan++;
  82278. do {
  82279. if (*scan++ != prev)
  82280. break;
  82281. } while (++run < max);
  82282. }
  82283. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82284. if (run >= MIN_MATCH) {
  82285. check_match(s, s->strstart, s->strstart - 1, run);
  82286. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82287. s->lookahead -= run;
  82288. s->strstart += run;
  82289. } else {
  82290. /* No match, output a literal byte */
  82291. Tracevv((stderr,"%c", s->window[s->strstart]));
  82292. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82293. s->lookahead--;
  82294. s->strstart++;
  82295. }
  82296. if (bflush) FLUSH_BLOCK(s, 0);
  82297. }
  82298. FLUSH_BLOCK(s, flush == Z_FINISH);
  82299. return flush == Z_FINISH ? finish_done : block_done;
  82300. }
  82301. #endif
  82302. /*** End of inlined file: deflate.c ***/
  82303. /*** Start of inlined file: inffast.c ***/
  82304. /*** Start of inlined file: inftrees.h ***/
  82305. /* WARNING: this file should *not* be used by applications. It is
  82306. part of the implementation of the compression library and is
  82307. subject to change. Applications should only use zlib.h.
  82308. */
  82309. #ifndef _INFTREES_H_
  82310. #define _INFTREES_H_
  82311. /* Structure for decoding tables. Each entry provides either the
  82312. information needed to do the operation requested by the code that
  82313. indexed that table entry, or it provides a pointer to another
  82314. table that indexes more bits of the code. op indicates whether
  82315. the entry is a pointer to another table, a literal, a length or
  82316. distance, an end-of-block, or an invalid code. For a table
  82317. pointer, the low four bits of op is the number of index bits of
  82318. that table. For a length or distance, the low four bits of op
  82319. is the number of extra bits to get after the code. bits is
  82320. the number of bits in this code or part of the code to drop off
  82321. of the bit buffer. val is the actual byte to output in the case
  82322. of a literal, the base length or distance, or the offset from
  82323. the current table to the next table. Each entry is four bytes. */
  82324. typedef struct {
  82325. unsigned char op; /* operation, extra bits, table bits */
  82326. unsigned char bits; /* bits in this part of the code */
  82327. unsigned short val; /* offset in table or code value */
  82328. } code;
  82329. /* op values as set by inflate_table():
  82330. 00000000 - literal
  82331. 0000tttt - table link, tttt != 0 is the number of table index bits
  82332. 0001eeee - length or distance, eeee is the number of extra bits
  82333. 01100000 - end of block
  82334. 01000000 - invalid code
  82335. */
  82336. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82337. exhaustive search was 1444 code structures (852 for length/literals
  82338. and 592 for distances, the latter actually the result of an
  82339. exhaustive search). The true maximum is not known, but the value
  82340. below is more than safe. */
  82341. #define ENOUGH 2048
  82342. #define MAXD 592
  82343. /* Type of code to build for inftable() */
  82344. typedef enum {
  82345. CODES,
  82346. LENS,
  82347. DISTS
  82348. } codetype;
  82349. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82350. unsigned codes, code FAR * FAR *table,
  82351. unsigned FAR *bits, unsigned short FAR *work));
  82352. #endif
  82353. /*** End of inlined file: inftrees.h ***/
  82354. /*** Start of inlined file: inflate.h ***/
  82355. /* WARNING: this file should *not* be used by applications. It is
  82356. part of the implementation of the compression library and is
  82357. subject to change. Applications should only use zlib.h.
  82358. */
  82359. #ifndef _INFLATE_H_
  82360. #define _INFLATE_H_
  82361. /* define NO_GZIP when compiling if you want to disable gzip header and
  82362. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82363. the crc code when it is not needed. For shared libraries, gzip decoding
  82364. should be left enabled. */
  82365. #ifndef NO_GZIP
  82366. # define GUNZIP
  82367. #endif
  82368. /* Possible inflate modes between inflate() calls */
  82369. typedef enum {
  82370. HEAD, /* i: waiting for magic header */
  82371. FLAGS, /* i: waiting for method and flags (gzip) */
  82372. TIME, /* i: waiting for modification time (gzip) */
  82373. OS, /* i: waiting for extra flags and operating system (gzip) */
  82374. EXLEN, /* i: waiting for extra length (gzip) */
  82375. EXTRA, /* i: waiting for extra bytes (gzip) */
  82376. NAME, /* i: waiting for end of file name (gzip) */
  82377. COMMENT, /* i: waiting for end of comment (gzip) */
  82378. HCRC, /* i: waiting for header crc (gzip) */
  82379. DICTID, /* i: waiting for dictionary check value */
  82380. DICT, /* waiting for inflateSetDictionary() call */
  82381. TYPE, /* i: waiting for type bits, including last-flag bit */
  82382. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82383. STORED, /* i: waiting for stored size (length and complement) */
  82384. COPY, /* i/o: waiting for input or output to copy stored block */
  82385. TABLE, /* i: waiting for dynamic block table lengths */
  82386. LENLENS, /* i: waiting for code length code lengths */
  82387. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82388. LEN, /* i: waiting for length/lit code */
  82389. LENEXT, /* i: waiting for length extra bits */
  82390. DIST, /* i: waiting for distance code */
  82391. DISTEXT, /* i: waiting for distance extra bits */
  82392. MATCH, /* o: waiting for output space to copy string */
  82393. LIT, /* o: waiting for output space to write literal */
  82394. CHECK, /* i: waiting for 32-bit check value */
  82395. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82396. DONE, /* finished check, done -- remain here until reset */
  82397. BAD, /* got a data error -- remain here until reset */
  82398. MEM, /* got an inflate() memory error -- remain here until reset */
  82399. SYNC /* looking for synchronization bytes to restart inflate() */
  82400. } inflate_mode;
  82401. /*
  82402. State transitions between above modes -
  82403. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82404. Process header:
  82405. HEAD -> (gzip) or (zlib)
  82406. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82407. NAME -> COMMENT -> HCRC -> TYPE
  82408. (zlib) -> DICTID or TYPE
  82409. DICTID -> DICT -> TYPE
  82410. Read deflate blocks:
  82411. TYPE -> STORED or TABLE or LEN or CHECK
  82412. STORED -> COPY -> TYPE
  82413. TABLE -> LENLENS -> CODELENS -> LEN
  82414. Read deflate codes:
  82415. LEN -> LENEXT or LIT or TYPE
  82416. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82417. LIT -> LEN
  82418. Process trailer:
  82419. CHECK -> LENGTH -> DONE
  82420. */
  82421. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82422. struct inflate_state {
  82423. inflate_mode mode; /* current inflate mode */
  82424. int last; /* true if processing last block */
  82425. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82426. int havedict; /* true if dictionary provided */
  82427. int flags; /* gzip header method and flags (0 if zlib) */
  82428. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82429. unsigned long check; /* protected copy of check value */
  82430. unsigned long total; /* protected copy of output count */
  82431. gz_headerp head; /* where to save gzip header information */
  82432. /* sliding window */
  82433. unsigned wbits; /* log base 2 of requested window size */
  82434. unsigned wsize; /* window size or zero if not using window */
  82435. unsigned whave; /* valid bytes in the window */
  82436. unsigned write; /* window write index */
  82437. unsigned char FAR *window; /* allocated sliding window, if needed */
  82438. /* bit accumulator */
  82439. unsigned long hold; /* input bit accumulator */
  82440. unsigned bits; /* number of bits in "in" */
  82441. /* for string and stored block copying */
  82442. unsigned length; /* literal or length of data to copy */
  82443. unsigned offset; /* distance back to copy string from */
  82444. /* for table and code decoding */
  82445. unsigned extra; /* extra bits needed */
  82446. /* fixed and dynamic code tables */
  82447. code const FAR *lencode; /* starting table for length/literal codes */
  82448. code const FAR *distcode; /* starting table for distance codes */
  82449. unsigned lenbits; /* index bits for lencode */
  82450. unsigned distbits; /* index bits for distcode */
  82451. /* dynamic table building */
  82452. unsigned ncode; /* number of code length code lengths */
  82453. unsigned nlen; /* number of length code lengths */
  82454. unsigned ndist; /* number of distance code lengths */
  82455. unsigned have; /* number of code lengths in lens[] */
  82456. code FAR *next; /* next available space in codes[] */
  82457. unsigned short lens[320]; /* temporary storage for code lengths */
  82458. unsigned short work[288]; /* work area for code table building */
  82459. code codes[ENOUGH]; /* space for code tables */
  82460. };
  82461. #endif
  82462. /*** End of inlined file: inflate.h ***/
  82463. /*** Start of inlined file: inffast.h ***/
  82464. /* WARNING: this file should *not* be used by applications. It is
  82465. part of the implementation of the compression library and is
  82466. subject to change. Applications should only use zlib.h.
  82467. */
  82468. void inflate_fast OF((z_streamp strm, unsigned start));
  82469. /*** End of inlined file: inffast.h ***/
  82470. #ifndef ASMINF
  82471. /* Allow machine dependent optimization for post-increment or pre-increment.
  82472. Based on testing to date,
  82473. Pre-increment preferred for:
  82474. - PowerPC G3 (Adler)
  82475. - MIPS R5000 (Randers-Pehrson)
  82476. Post-increment preferred for:
  82477. - none
  82478. No measurable difference:
  82479. - Pentium III (Anderson)
  82480. - M68060 (Nikl)
  82481. */
  82482. #ifdef POSTINC
  82483. # define OFF 0
  82484. # define PUP(a) *(a)++
  82485. #else
  82486. # define OFF 1
  82487. # define PUP(a) *++(a)
  82488. #endif
  82489. /*
  82490. Decode literal, length, and distance codes and write out the resulting
  82491. literal and match bytes until either not enough input or output is
  82492. available, an end-of-block is encountered, or a data error is encountered.
  82493. When large enough input and output buffers are supplied to inflate(), for
  82494. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82495. inflate execution time is spent in this routine.
  82496. Entry assumptions:
  82497. state->mode == LEN
  82498. strm->avail_in >= 6
  82499. strm->avail_out >= 258
  82500. start >= strm->avail_out
  82501. state->bits < 8
  82502. On return, state->mode is one of:
  82503. LEN -- ran out of enough output space or enough available input
  82504. TYPE -- reached end of block code, inflate() to interpret next block
  82505. BAD -- error in block data
  82506. Notes:
  82507. - The maximum input bits used by a length/distance pair is 15 bits for the
  82508. length code, 5 bits for the length extra, 15 bits for the distance code,
  82509. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82510. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82511. checking for available input while decoding.
  82512. - The maximum bytes that a single length/distance pair can output is 258
  82513. bytes, which is the maximum length that can be coded. inflate_fast()
  82514. requires strm->avail_out >= 258 for each loop to avoid checking for
  82515. output space.
  82516. */
  82517. void inflate_fast (z_streamp strm, unsigned start)
  82518. {
  82519. struct inflate_state FAR *state;
  82520. unsigned char FAR *in; /* local strm->next_in */
  82521. unsigned char FAR *last; /* while in < last, enough input available */
  82522. unsigned char FAR *out; /* local strm->next_out */
  82523. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82524. unsigned char FAR *end; /* while out < end, enough space available */
  82525. #ifdef INFLATE_STRICT
  82526. unsigned dmax; /* maximum distance from zlib header */
  82527. #endif
  82528. unsigned wsize; /* window size or zero if not using window */
  82529. unsigned whave; /* valid bytes in the window */
  82530. unsigned write; /* window write index */
  82531. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82532. unsigned long hold; /* local strm->hold */
  82533. unsigned bits; /* local strm->bits */
  82534. code const FAR *lcode; /* local strm->lencode */
  82535. code const FAR *dcode; /* local strm->distcode */
  82536. unsigned lmask; /* mask for first level of length codes */
  82537. unsigned dmask; /* mask for first level of distance codes */
  82538. code thisx; /* retrieved table entry */
  82539. unsigned op; /* code bits, operation, extra bits, or */
  82540. /* window position, window bytes to copy */
  82541. unsigned len; /* match length, unused bytes */
  82542. unsigned dist; /* match distance */
  82543. unsigned char FAR *from; /* where to copy match from */
  82544. /* copy state to local variables */
  82545. state = (struct inflate_state FAR *)strm->state;
  82546. in = strm->next_in - OFF;
  82547. last = in + (strm->avail_in - 5);
  82548. out = strm->next_out - OFF;
  82549. beg = out - (start - strm->avail_out);
  82550. end = out + (strm->avail_out - 257);
  82551. #ifdef INFLATE_STRICT
  82552. dmax = state->dmax;
  82553. #endif
  82554. wsize = state->wsize;
  82555. whave = state->whave;
  82556. write = state->write;
  82557. window = state->window;
  82558. hold = state->hold;
  82559. bits = state->bits;
  82560. lcode = state->lencode;
  82561. dcode = state->distcode;
  82562. lmask = (1U << state->lenbits) - 1;
  82563. dmask = (1U << state->distbits) - 1;
  82564. /* decode literals and length/distances until end-of-block or not enough
  82565. input data or output space */
  82566. do {
  82567. if (bits < 15) {
  82568. hold += (unsigned long)(PUP(in)) << bits;
  82569. bits += 8;
  82570. hold += (unsigned long)(PUP(in)) << bits;
  82571. bits += 8;
  82572. }
  82573. thisx = lcode[hold & lmask];
  82574. dolen:
  82575. op = (unsigned)(thisx.bits);
  82576. hold >>= op;
  82577. bits -= op;
  82578. op = (unsigned)(thisx.op);
  82579. if (op == 0) { /* literal */
  82580. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82581. "inflate: literal '%c'\n" :
  82582. "inflate: literal 0x%02x\n", thisx.val));
  82583. PUP(out) = (unsigned char)(thisx.val);
  82584. }
  82585. else if (op & 16) { /* length base */
  82586. len = (unsigned)(thisx.val);
  82587. op &= 15; /* number of extra bits */
  82588. if (op) {
  82589. if (bits < op) {
  82590. hold += (unsigned long)(PUP(in)) << bits;
  82591. bits += 8;
  82592. }
  82593. len += (unsigned)hold & ((1U << op) - 1);
  82594. hold >>= op;
  82595. bits -= op;
  82596. }
  82597. Tracevv((stderr, "inflate: length %u\n", len));
  82598. if (bits < 15) {
  82599. hold += (unsigned long)(PUP(in)) << bits;
  82600. bits += 8;
  82601. hold += (unsigned long)(PUP(in)) << bits;
  82602. bits += 8;
  82603. }
  82604. thisx = dcode[hold & dmask];
  82605. dodist:
  82606. op = (unsigned)(thisx.bits);
  82607. hold >>= op;
  82608. bits -= op;
  82609. op = (unsigned)(thisx.op);
  82610. if (op & 16) { /* distance base */
  82611. dist = (unsigned)(thisx.val);
  82612. op &= 15; /* number of extra bits */
  82613. if (bits < op) {
  82614. hold += (unsigned long)(PUP(in)) << bits;
  82615. bits += 8;
  82616. if (bits < op) {
  82617. hold += (unsigned long)(PUP(in)) << bits;
  82618. bits += 8;
  82619. }
  82620. }
  82621. dist += (unsigned)hold & ((1U << op) - 1);
  82622. #ifdef INFLATE_STRICT
  82623. if (dist > dmax) {
  82624. strm->msg = (char *)"invalid distance too far back";
  82625. state->mode = BAD;
  82626. break;
  82627. }
  82628. #endif
  82629. hold >>= op;
  82630. bits -= op;
  82631. Tracevv((stderr, "inflate: distance %u\n", dist));
  82632. op = (unsigned)(out - beg); /* max distance in output */
  82633. if (dist > op) { /* see if copy from window */
  82634. op = dist - op; /* distance back in window */
  82635. if (op > whave) {
  82636. strm->msg = (char *)"invalid distance too far back";
  82637. state->mode = BAD;
  82638. break;
  82639. }
  82640. from = window - OFF;
  82641. if (write == 0) { /* very common case */
  82642. from += wsize - op;
  82643. if (op < len) { /* some from window */
  82644. len -= op;
  82645. do {
  82646. PUP(out) = PUP(from);
  82647. } while (--op);
  82648. from = out - dist; /* rest from output */
  82649. }
  82650. }
  82651. else if (write < op) { /* wrap around window */
  82652. from += wsize + write - op;
  82653. op -= write;
  82654. if (op < len) { /* some from end of window */
  82655. len -= op;
  82656. do {
  82657. PUP(out) = PUP(from);
  82658. } while (--op);
  82659. from = window - OFF;
  82660. if (write < len) { /* some from start of window */
  82661. op = write;
  82662. len -= op;
  82663. do {
  82664. PUP(out) = PUP(from);
  82665. } while (--op);
  82666. from = out - dist; /* rest from output */
  82667. }
  82668. }
  82669. }
  82670. else { /* contiguous in window */
  82671. from += write - op;
  82672. if (op < len) { /* some from window */
  82673. len -= op;
  82674. do {
  82675. PUP(out) = PUP(from);
  82676. } while (--op);
  82677. from = out - dist; /* rest from output */
  82678. }
  82679. }
  82680. while (len > 2) {
  82681. PUP(out) = PUP(from);
  82682. PUP(out) = PUP(from);
  82683. PUP(out) = PUP(from);
  82684. len -= 3;
  82685. }
  82686. if (len) {
  82687. PUP(out) = PUP(from);
  82688. if (len > 1)
  82689. PUP(out) = PUP(from);
  82690. }
  82691. }
  82692. else {
  82693. from = out - dist; /* copy direct from output */
  82694. do { /* minimum length is three */
  82695. PUP(out) = PUP(from);
  82696. PUP(out) = PUP(from);
  82697. PUP(out) = PUP(from);
  82698. len -= 3;
  82699. } while (len > 2);
  82700. if (len) {
  82701. PUP(out) = PUP(from);
  82702. if (len > 1)
  82703. PUP(out) = PUP(from);
  82704. }
  82705. }
  82706. }
  82707. else if ((op & 64) == 0) { /* 2nd level distance code */
  82708. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  82709. goto dodist;
  82710. }
  82711. else {
  82712. strm->msg = (char *)"invalid distance code";
  82713. state->mode = BAD;
  82714. break;
  82715. }
  82716. }
  82717. else if ((op & 64) == 0) { /* 2nd level length code */
  82718. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  82719. goto dolen;
  82720. }
  82721. else if (op & 32) { /* end-of-block */
  82722. Tracevv((stderr, "inflate: end of block\n"));
  82723. state->mode = TYPE;
  82724. break;
  82725. }
  82726. else {
  82727. strm->msg = (char *)"invalid literal/length code";
  82728. state->mode = BAD;
  82729. break;
  82730. }
  82731. } while (in < last && out < end);
  82732. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  82733. len = bits >> 3;
  82734. in -= len;
  82735. bits -= len << 3;
  82736. hold &= (1U << bits) - 1;
  82737. /* update state and return */
  82738. strm->next_in = in + OFF;
  82739. strm->next_out = out + OFF;
  82740. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  82741. strm->avail_out = (unsigned)(out < end ?
  82742. 257 + (end - out) : 257 - (out - end));
  82743. state->hold = hold;
  82744. state->bits = bits;
  82745. return;
  82746. }
  82747. /*
  82748. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  82749. - Using bit fields for code structure
  82750. - Different op definition to avoid & for extra bits (do & for table bits)
  82751. - Three separate decoding do-loops for direct, window, and write == 0
  82752. - Special case for distance > 1 copies to do overlapped load and store copy
  82753. - Explicit branch predictions (based on measured branch probabilities)
  82754. - Deferring match copy and interspersed it with decoding subsequent codes
  82755. - Swapping literal/length else
  82756. - Swapping window/direct else
  82757. - Larger unrolled copy loops (three is about right)
  82758. - Moving len -= 3 statement into middle of loop
  82759. */
  82760. #endif /* !ASMINF */
  82761. /*** End of inlined file: inffast.c ***/
  82762. #undef PULLBYTE
  82763. #undef LOAD
  82764. #undef RESTORE
  82765. #undef INITBITS
  82766. #undef NEEDBITS
  82767. #undef DROPBITS
  82768. #undef BYTEBITS
  82769. /*** Start of inlined file: inflate.c ***/
  82770. /*
  82771. * Change history:
  82772. *
  82773. * 1.2.beta0 24 Nov 2002
  82774. * - First version -- complete rewrite of inflate to simplify code, avoid
  82775. * creation of window when not needed, minimize use of window when it is
  82776. * needed, make inffast.c even faster, implement gzip decoding, and to
  82777. * improve code readability and style over the previous zlib inflate code
  82778. *
  82779. * 1.2.beta1 25 Nov 2002
  82780. * - Use pointers for available input and output checking in inffast.c
  82781. * - Remove input and output counters in inffast.c
  82782. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  82783. * - Remove unnecessary second byte pull from length extra in inffast.c
  82784. * - Unroll direct copy to three copies per loop in inffast.c
  82785. *
  82786. * 1.2.beta2 4 Dec 2002
  82787. * - Change external routine names to reduce potential conflicts
  82788. * - Correct filename to inffixed.h for fixed tables in inflate.c
  82789. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  82790. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  82791. * to avoid negation problem on Alphas (64 bit) in inflate.c
  82792. *
  82793. * 1.2.beta3 22 Dec 2002
  82794. * - Add comments on state->bits assertion in inffast.c
  82795. * - Add comments on op field in inftrees.h
  82796. * - Fix bug in reuse of allocated window after inflateReset()
  82797. * - Remove bit fields--back to byte structure for speed
  82798. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  82799. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  82800. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  82801. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  82802. * - Use local copies of stream next and avail values, as well as local bit
  82803. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  82804. *
  82805. * 1.2.beta4 1 Jan 2003
  82806. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  82807. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  82808. * - Add comments in inffast.c to introduce the inflate_fast() routine
  82809. * - Rearrange window copies in inflate_fast() for speed and simplification
  82810. * - Unroll last copy for window match in inflate_fast()
  82811. * - Use local copies of window variables in inflate_fast() for speed
  82812. * - Pull out common write == 0 case for speed in inflate_fast()
  82813. * - Make op and len in inflate_fast() unsigned for consistency
  82814. * - Add FAR to lcode and dcode declarations in inflate_fast()
  82815. * - Simplified bad distance check in inflate_fast()
  82816. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  82817. * source file infback.c to provide a call-back interface to inflate for
  82818. * programs like gzip and unzip -- uses window as output buffer to avoid
  82819. * window copying
  82820. *
  82821. * 1.2.beta5 1 Jan 2003
  82822. * - Improved inflateBack() interface to allow the caller to provide initial
  82823. * input in strm.
  82824. * - Fixed stored blocks bug in inflateBack()
  82825. *
  82826. * 1.2.beta6 4 Jan 2003
  82827. * - Added comments in inffast.c on effectiveness of POSTINC
  82828. * - Typecasting all around to reduce compiler warnings
  82829. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  82830. * make compilers happy
  82831. * - Changed type of window in inflateBackInit() to unsigned char *
  82832. *
  82833. * 1.2.beta7 27 Jan 2003
  82834. * - Changed many types to unsigned or unsigned short to avoid warnings
  82835. * - Added inflateCopy() function
  82836. *
  82837. * 1.2.0 9 Mar 2003
  82838. * - Changed inflateBack() interface to provide separate opaque descriptors
  82839. * for the in() and out() functions
  82840. * - Changed inflateBack() argument and in_func typedef to swap the length
  82841. * and buffer address return values for the input function
  82842. * - Check next_in and next_out for Z_NULL on entry to inflate()
  82843. *
  82844. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  82845. */
  82846. /*** Start of inlined file: inffast.h ***/
  82847. /* WARNING: this file should *not* be used by applications. It is
  82848. part of the implementation of the compression library and is
  82849. subject to change. Applications should only use zlib.h.
  82850. */
  82851. void inflate_fast OF((z_streamp strm, unsigned start));
  82852. /*** End of inlined file: inffast.h ***/
  82853. #ifdef MAKEFIXED
  82854. # ifndef BUILDFIXED
  82855. # define BUILDFIXED
  82856. # endif
  82857. #endif
  82858. /* function prototypes */
  82859. local void fixedtables OF((struct inflate_state FAR *state));
  82860. local int updatewindow OF((z_streamp strm, unsigned out));
  82861. #ifdef BUILDFIXED
  82862. void makefixed OF((void));
  82863. #endif
  82864. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  82865. unsigned len));
  82866. int ZEXPORT inflateReset (z_streamp strm)
  82867. {
  82868. struct inflate_state FAR *state;
  82869. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82870. state = (struct inflate_state FAR *)strm->state;
  82871. strm->total_in = strm->total_out = state->total = 0;
  82872. strm->msg = Z_NULL;
  82873. strm->adler = 1; /* to support ill-conceived Java test suite */
  82874. state->mode = HEAD;
  82875. state->last = 0;
  82876. state->havedict = 0;
  82877. state->dmax = 32768U;
  82878. state->head = Z_NULL;
  82879. state->wsize = 0;
  82880. state->whave = 0;
  82881. state->write = 0;
  82882. state->hold = 0;
  82883. state->bits = 0;
  82884. state->lencode = state->distcode = state->next = state->codes;
  82885. Tracev((stderr, "inflate: reset\n"));
  82886. return Z_OK;
  82887. }
  82888. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  82889. {
  82890. struct inflate_state FAR *state;
  82891. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82892. state = (struct inflate_state FAR *)strm->state;
  82893. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  82894. value &= (1L << bits) - 1;
  82895. state->hold += value << state->bits;
  82896. state->bits += bits;
  82897. return Z_OK;
  82898. }
  82899. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  82900. {
  82901. struct inflate_state FAR *state;
  82902. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  82903. stream_size != (int)(sizeof(z_stream)))
  82904. return Z_VERSION_ERROR;
  82905. if (strm == Z_NULL) return Z_STREAM_ERROR;
  82906. strm->msg = Z_NULL; /* in case we return an error */
  82907. if (strm->zalloc == (alloc_func)0) {
  82908. strm->zalloc = zcalloc;
  82909. strm->opaque = (voidpf)0;
  82910. }
  82911. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  82912. state = (struct inflate_state FAR *)
  82913. ZALLOC(strm, 1, sizeof(struct inflate_state));
  82914. if (state == Z_NULL) return Z_MEM_ERROR;
  82915. Tracev((stderr, "inflate: allocated\n"));
  82916. strm->state = (struct internal_state FAR *)state;
  82917. if (windowBits < 0) {
  82918. state->wrap = 0;
  82919. windowBits = -windowBits;
  82920. }
  82921. else {
  82922. state->wrap = (windowBits >> 4) + 1;
  82923. #ifdef GUNZIP
  82924. if (windowBits < 48) windowBits &= 15;
  82925. #endif
  82926. }
  82927. if (windowBits < 8 || windowBits > 15) {
  82928. ZFREE(strm, state);
  82929. strm->state = Z_NULL;
  82930. return Z_STREAM_ERROR;
  82931. }
  82932. state->wbits = (unsigned)windowBits;
  82933. state->window = Z_NULL;
  82934. return inflateReset(strm);
  82935. }
  82936. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  82937. {
  82938. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  82939. }
  82940. /*
  82941. Return state with length and distance decoding tables and index sizes set to
  82942. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  82943. If BUILDFIXED is defined, then instead this routine builds the tables the
  82944. first time it's called, and returns those tables the first time and
  82945. thereafter. This reduces the size of the code by about 2K bytes, in
  82946. exchange for a little execution time. However, BUILDFIXED should not be
  82947. used for threaded applications, since the rewriting of the tables and virgin
  82948. may not be thread-safe.
  82949. */
  82950. local void fixedtables (struct inflate_state FAR *state)
  82951. {
  82952. #ifdef BUILDFIXED
  82953. static int virgin = 1;
  82954. static code *lenfix, *distfix;
  82955. static code fixed[544];
  82956. /* build fixed huffman tables if first call (may not be thread safe) */
  82957. if (virgin) {
  82958. unsigned sym, bits;
  82959. static code *next;
  82960. /* literal/length table */
  82961. sym = 0;
  82962. while (sym < 144) state->lens[sym++] = 8;
  82963. while (sym < 256) state->lens[sym++] = 9;
  82964. while (sym < 280) state->lens[sym++] = 7;
  82965. while (sym < 288) state->lens[sym++] = 8;
  82966. next = fixed;
  82967. lenfix = next;
  82968. bits = 9;
  82969. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  82970. /* distance table */
  82971. sym = 0;
  82972. while (sym < 32) state->lens[sym++] = 5;
  82973. distfix = next;
  82974. bits = 5;
  82975. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  82976. /* do this just once */
  82977. virgin = 0;
  82978. }
  82979. #else /* !BUILDFIXED */
  82980. /*** Start of inlined file: inffixed.h ***/
  82981. /* WARNING: this file should *not* be used by applications. It
  82982. is part of the implementation of the compression library and
  82983. is subject to change. Applications should only use zlib.h.
  82984. */
  82985. static const code lenfix[512] = {
  82986. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  82987. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  82988. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  82989. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  82990. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  82991. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  82992. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  82993. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  82994. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  82995. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  82996. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  82997. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  82998. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  82999. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83000. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83001. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83002. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83003. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83004. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83005. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83006. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83007. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83008. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83009. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83010. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83011. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83012. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83013. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83014. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83015. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83016. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83017. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83018. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83019. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83020. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83021. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83022. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83023. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83024. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83025. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83026. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83027. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83028. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83029. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83030. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83031. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83032. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83033. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83034. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83035. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83036. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83037. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83038. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83039. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83040. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83041. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83042. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83043. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83044. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83045. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83046. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83047. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83048. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83049. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83050. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83051. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83052. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83053. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83054. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83055. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83056. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83057. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83058. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83059. {0,9,255}
  83060. };
  83061. static const code distfix[32] = {
  83062. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83063. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83064. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83065. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83066. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83067. {22,5,193},{64,5,0}
  83068. };
  83069. /*** End of inlined file: inffixed.h ***/
  83070. #endif /* BUILDFIXED */
  83071. state->lencode = lenfix;
  83072. state->lenbits = 9;
  83073. state->distcode = distfix;
  83074. state->distbits = 5;
  83075. }
  83076. #ifdef MAKEFIXED
  83077. #include <stdio.h>
  83078. /*
  83079. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83080. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83081. those tables to stdout, which would be piped to inffixed.h. A small program
  83082. can simply call makefixed to do this:
  83083. void makefixed(void);
  83084. int main(void)
  83085. {
  83086. makefixed();
  83087. return 0;
  83088. }
  83089. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83090. a.out > inffixed.h
  83091. */
  83092. void makefixed()
  83093. {
  83094. unsigned low, size;
  83095. struct inflate_state state;
  83096. fixedtables(&state);
  83097. puts(" /* inffixed.h -- table for decoding fixed codes");
  83098. puts(" * Generated automatically by makefixed().");
  83099. puts(" */");
  83100. puts("");
  83101. puts(" /* WARNING: this file should *not* be used by applications.");
  83102. puts(" It is part of the implementation of this library and is");
  83103. puts(" subject to change. Applications should only use zlib.h.");
  83104. puts(" */");
  83105. puts("");
  83106. size = 1U << 9;
  83107. printf(" static const code lenfix[%u] = {", size);
  83108. low = 0;
  83109. for (;;) {
  83110. if ((low % 7) == 0) printf("\n ");
  83111. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83112. state.lencode[low].val);
  83113. if (++low == size) break;
  83114. putchar(',');
  83115. }
  83116. puts("\n };");
  83117. size = 1U << 5;
  83118. printf("\n static const code distfix[%u] = {", size);
  83119. low = 0;
  83120. for (;;) {
  83121. if ((low % 6) == 0) printf("\n ");
  83122. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83123. state.distcode[low].val);
  83124. if (++low == size) break;
  83125. putchar(',');
  83126. }
  83127. puts("\n };");
  83128. }
  83129. #endif /* MAKEFIXED */
  83130. /*
  83131. Update the window with the last wsize (normally 32K) bytes written before
  83132. returning. If window does not exist yet, create it. This is only called
  83133. when a window is already in use, or when output has been written during this
  83134. inflate call, but the end of the deflate stream has not been reached yet.
  83135. It is also called to create a window for dictionary data when a dictionary
  83136. is loaded.
  83137. Providing output buffers larger than 32K to inflate() should provide a speed
  83138. advantage, since only the last 32K of output is copied to the sliding window
  83139. upon return from inflate(), and since all distances after the first 32K of
  83140. output will fall in the output data, making match copies simpler and faster.
  83141. The advantage may be dependent on the size of the processor's data caches.
  83142. */
  83143. local int updatewindow (z_streamp strm, unsigned out)
  83144. {
  83145. struct inflate_state FAR *state;
  83146. unsigned copy, dist;
  83147. state = (struct inflate_state FAR *)strm->state;
  83148. /* if it hasn't been done already, allocate space for the window */
  83149. if (state->window == Z_NULL) {
  83150. state->window = (unsigned char FAR *)
  83151. ZALLOC(strm, 1U << state->wbits,
  83152. sizeof(unsigned char));
  83153. if (state->window == Z_NULL) return 1;
  83154. }
  83155. /* if window not in use yet, initialize */
  83156. if (state->wsize == 0) {
  83157. state->wsize = 1U << state->wbits;
  83158. state->write = 0;
  83159. state->whave = 0;
  83160. }
  83161. /* copy state->wsize or less output bytes into the circular window */
  83162. copy = out - strm->avail_out;
  83163. if (copy >= state->wsize) {
  83164. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83165. state->write = 0;
  83166. state->whave = state->wsize;
  83167. }
  83168. else {
  83169. dist = state->wsize - state->write;
  83170. if (dist > copy) dist = copy;
  83171. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83172. copy -= dist;
  83173. if (copy) {
  83174. zmemcpy(state->window, strm->next_out - copy, copy);
  83175. state->write = copy;
  83176. state->whave = state->wsize;
  83177. }
  83178. else {
  83179. state->write += dist;
  83180. if (state->write == state->wsize) state->write = 0;
  83181. if (state->whave < state->wsize) state->whave += dist;
  83182. }
  83183. }
  83184. return 0;
  83185. }
  83186. /* Macros for inflate(): */
  83187. /* check function to use adler32() for zlib or crc32() for gzip */
  83188. #ifdef GUNZIP
  83189. # define UPDATE(check, buf, len) \
  83190. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83191. #else
  83192. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83193. #endif
  83194. /* check macros for header crc */
  83195. #ifdef GUNZIP
  83196. # define CRC2(check, word) \
  83197. do { \
  83198. hbuf[0] = (unsigned char)(word); \
  83199. hbuf[1] = (unsigned char)((word) >> 8); \
  83200. check = crc32(check, hbuf, 2); \
  83201. } while (0)
  83202. # define CRC4(check, word) \
  83203. do { \
  83204. hbuf[0] = (unsigned char)(word); \
  83205. hbuf[1] = (unsigned char)((word) >> 8); \
  83206. hbuf[2] = (unsigned char)((word) >> 16); \
  83207. hbuf[3] = (unsigned char)((word) >> 24); \
  83208. check = crc32(check, hbuf, 4); \
  83209. } while (0)
  83210. #endif
  83211. /* Load registers with state in inflate() for speed */
  83212. #define LOAD() \
  83213. do { \
  83214. put = strm->next_out; \
  83215. left = strm->avail_out; \
  83216. next = strm->next_in; \
  83217. have = strm->avail_in; \
  83218. hold = state->hold; \
  83219. bits = state->bits; \
  83220. } while (0)
  83221. /* Restore state from registers in inflate() */
  83222. #define RESTORE() \
  83223. do { \
  83224. strm->next_out = put; \
  83225. strm->avail_out = left; \
  83226. strm->next_in = next; \
  83227. strm->avail_in = have; \
  83228. state->hold = hold; \
  83229. state->bits = bits; \
  83230. } while (0)
  83231. /* Clear the input bit accumulator */
  83232. #define INITBITS() \
  83233. do { \
  83234. hold = 0; \
  83235. bits = 0; \
  83236. } while (0)
  83237. /* Get a byte of input into the bit accumulator, or return from inflate()
  83238. if there is no input available. */
  83239. #define PULLBYTE() \
  83240. do { \
  83241. if (have == 0) goto inf_leave; \
  83242. have--; \
  83243. hold += (unsigned long)(*next++) << bits; \
  83244. bits += 8; \
  83245. } while (0)
  83246. /* Assure that there are at least n bits in the bit accumulator. If there is
  83247. not enough available input to do that, then return from inflate(). */
  83248. #define NEEDBITS(n) \
  83249. do { \
  83250. while (bits < (unsigned)(n)) \
  83251. PULLBYTE(); \
  83252. } while (0)
  83253. /* Return the low n bits of the bit accumulator (n < 16) */
  83254. #define BITS(n) \
  83255. ((unsigned)hold & ((1U << (n)) - 1))
  83256. /* Remove n bits from the bit accumulator */
  83257. #define DROPBITS(n) \
  83258. do { \
  83259. hold >>= (n); \
  83260. bits -= (unsigned)(n); \
  83261. } while (0)
  83262. /* Remove zero to seven bits as needed to go to a byte boundary */
  83263. #define BYTEBITS() \
  83264. do { \
  83265. hold >>= bits & 7; \
  83266. bits -= bits & 7; \
  83267. } while (0)
  83268. /* Reverse the bytes in a 32-bit value */
  83269. #define REVERSE(q) \
  83270. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83271. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83272. /*
  83273. inflate() uses a state machine to process as much input data and generate as
  83274. much output data as possible before returning. The state machine is
  83275. structured roughly as follows:
  83276. for (;;) switch (state) {
  83277. ...
  83278. case STATEn:
  83279. if (not enough input data or output space to make progress)
  83280. return;
  83281. ... make progress ...
  83282. state = STATEm;
  83283. break;
  83284. ...
  83285. }
  83286. so when inflate() is called again, the same case is attempted again, and
  83287. if the appropriate resources are provided, the machine proceeds to the
  83288. next state. The NEEDBITS() macro is usually the way the state evaluates
  83289. whether it can proceed or should return. NEEDBITS() does the return if
  83290. the requested bits are not available. The typical use of the BITS macros
  83291. is:
  83292. NEEDBITS(n);
  83293. ... do something with BITS(n) ...
  83294. DROPBITS(n);
  83295. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83296. input left to load n bits into the accumulator, or it continues. BITS(n)
  83297. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83298. the low n bits off the accumulator. INITBITS() clears the accumulator
  83299. and sets the number of available bits to zero. BYTEBITS() discards just
  83300. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83301. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83302. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83303. if there is no input available. The decoding of variable length codes uses
  83304. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83305. code, and no more.
  83306. Some states loop until they get enough input, making sure that enough
  83307. state information is maintained to continue the loop where it left off
  83308. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83309. would all have to actually be part of the saved state in case NEEDBITS()
  83310. returns:
  83311. case STATEw:
  83312. while (want < need) {
  83313. NEEDBITS(n);
  83314. keep[want++] = BITS(n);
  83315. DROPBITS(n);
  83316. }
  83317. state = STATEx;
  83318. case STATEx:
  83319. As shown above, if the next state is also the next case, then the break
  83320. is omitted.
  83321. A state may also return if there is not enough output space available to
  83322. complete that state. Those states are copying stored data, writing a
  83323. literal byte, and copying a matching string.
  83324. When returning, a "goto inf_leave" is used to update the total counters,
  83325. update the check value, and determine whether any progress has been made
  83326. during that inflate() call in order to return the proper return code.
  83327. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83328. When there is a window, goto inf_leave will update the window with the last
  83329. output written. If a goto inf_leave occurs in the middle of decompression
  83330. and there is no window currently, goto inf_leave will create one and copy
  83331. output to the window for the next call of inflate().
  83332. In this implementation, the flush parameter of inflate() only affects the
  83333. return code (per zlib.h). inflate() always writes as much as possible to
  83334. strm->next_out, given the space available and the provided input--the effect
  83335. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83336. the allocation of and copying into a sliding window until necessary, which
  83337. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83338. stream available. So the only thing the flush parameter actually does is:
  83339. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83340. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83341. */
  83342. int ZEXPORT inflate (z_streamp strm, int flush)
  83343. {
  83344. struct inflate_state FAR *state;
  83345. unsigned char FAR *next; /* next input */
  83346. unsigned char FAR *put; /* next output */
  83347. unsigned have, left; /* available input and output */
  83348. unsigned long hold; /* bit buffer */
  83349. unsigned bits; /* bits in bit buffer */
  83350. unsigned in, out; /* save starting available input and output */
  83351. unsigned copy; /* number of stored or match bytes to copy */
  83352. unsigned char FAR *from; /* where to copy match bytes from */
  83353. code thisx; /* current decoding table entry */
  83354. code last; /* parent table entry */
  83355. unsigned len; /* length to copy for repeats, bits to drop */
  83356. int ret; /* return code */
  83357. #ifdef GUNZIP
  83358. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83359. #endif
  83360. static const unsigned short order[19] = /* permutation of code lengths */
  83361. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83362. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83363. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83364. return Z_STREAM_ERROR;
  83365. state = (struct inflate_state FAR *)strm->state;
  83366. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83367. LOAD();
  83368. in = have;
  83369. out = left;
  83370. ret = Z_OK;
  83371. for (;;)
  83372. switch (state->mode) {
  83373. case HEAD:
  83374. if (state->wrap == 0) {
  83375. state->mode = TYPEDO;
  83376. break;
  83377. }
  83378. NEEDBITS(16);
  83379. #ifdef GUNZIP
  83380. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83381. state->check = crc32(0L, Z_NULL, 0);
  83382. CRC2(state->check, hold);
  83383. INITBITS();
  83384. state->mode = FLAGS;
  83385. break;
  83386. }
  83387. state->flags = 0; /* expect zlib header */
  83388. if (state->head != Z_NULL)
  83389. state->head->done = -1;
  83390. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83391. #else
  83392. if (
  83393. #endif
  83394. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83395. strm->msg = (char *)"incorrect header check";
  83396. state->mode = BAD;
  83397. break;
  83398. }
  83399. if (BITS(4) != Z_DEFLATED) {
  83400. strm->msg = (char *)"unknown compression method";
  83401. state->mode = BAD;
  83402. break;
  83403. }
  83404. DROPBITS(4);
  83405. len = BITS(4) + 8;
  83406. if (len > state->wbits) {
  83407. strm->msg = (char *)"invalid window size";
  83408. state->mode = BAD;
  83409. break;
  83410. }
  83411. state->dmax = 1U << len;
  83412. Tracev((stderr, "inflate: zlib header ok\n"));
  83413. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83414. state->mode = hold & 0x200 ? DICTID : TYPE;
  83415. INITBITS();
  83416. break;
  83417. #ifdef GUNZIP
  83418. case FLAGS:
  83419. NEEDBITS(16);
  83420. state->flags = (int)(hold);
  83421. if ((state->flags & 0xff) != Z_DEFLATED) {
  83422. strm->msg = (char *)"unknown compression method";
  83423. state->mode = BAD;
  83424. break;
  83425. }
  83426. if (state->flags & 0xe000) {
  83427. strm->msg = (char *)"unknown header flags set";
  83428. state->mode = BAD;
  83429. break;
  83430. }
  83431. if (state->head != Z_NULL)
  83432. state->head->text = (int)((hold >> 8) & 1);
  83433. if (state->flags & 0x0200) CRC2(state->check, hold);
  83434. INITBITS();
  83435. state->mode = TIME;
  83436. case TIME:
  83437. NEEDBITS(32);
  83438. if (state->head != Z_NULL)
  83439. state->head->time = hold;
  83440. if (state->flags & 0x0200) CRC4(state->check, hold);
  83441. INITBITS();
  83442. state->mode = OS;
  83443. case OS:
  83444. NEEDBITS(16);
  83445. if (state->head != Z_NULL) {
  83446. state->head->xflags = (int)(hold & 0xff);
  83447. state->head->os = (int)(hold >> 8);
  83448. }
  83449. if (state->flags & 0x0200) CRC2(state->check, hold);
  83450. INITBITS();
  83451. state->mode = EXLEN;
  83452. case EXLEN:
  83453. if (state->flags & 0x0400) {
  83454. NEEDBITS(16);
  83455. state->length = (unsigned)(hold);
  83456. if (state->head != Z_NULL)
  83457. state->head->extra_len = (unsigned)hold;
  83458. if (state->flags & 0x0200) CRC2(state->check, hold);
  83459. INITBITS();
  83460. }
  83461. else if (state->head != Z_NULL)
  83462. state->head->extra = Z_NULL;
  83463. state->mode = EXTRA;
  83464. case EXTRA:
  83465. if (state->flags & 0x0400) {
  83466. copy = state->length;
  83467. if (copy > have) copy = have;
  83468. if (copy) {
  83469. if (state->head != Z_NULL &&
  83470. state->head->extra != Z_NULL) {
  83471. len = state->head->extra_len - state->length;
  83472. zmemcpy(state->head->extra + len, next,
  83473. len + copy > state->head->extra_max ?
  83474. state->head->extra_max - len : copy);
  83475. }
  83476. if (state->flags & 0x0200)
  83477. state->check = crc32(state->check, next, copy);
  83478. have -= copy;
  83479. next += copy;
  83480. state->length -= copy;
  83481. }
  83482. if (state->length) goto inf_leave;
  83483. }
  83484. state->length = 0;
  83485. state->mode = NAME;
  83486. case NAME:
  83487. if (state->flags & 0x0800) {
  83488. if (have == 0) goto inf_leave;
  83489. copy = 0;
  83490. do {
  83491. len = (unsigned)(next[copy++]);
  83492. if (state->head != Z_NULL &&
  83493. state->head->name != Z_NULL &&
  83494. state->length < state->head->name_max)
  83495. state->head->name[state->length++] = len;
  83496. } while (len && copy < have);
  83497. if (state->flags & 0x0200)
  83498. state->check = crc32(state->check, next, copy);
  83499. have -= copy;
  83500. next += copy;
  83501. if (len) goto inf_leave;
  83502. }
  83503. else if (state->head != Z_NULL)
  83504. state->head->name = Z_NULL;
  83505. state->length = 0;
  83506. state->mode = COMMENT;
  83507. case COMMENT:
  83508. if (state->flags & 0x1000) {
  83509. if (have == 0) goto inf_leave;
  83510. copy = 0;
  83511. do {
  83512. len = (unsigned)(next[copy++]);
  83513. if (state->head != Z_NULL &&
  83514. state->head->comment != Z_NULL &&
  83515. state->length < state->head->comm_max)
  83516. state->head->comment[state->length++] = len;
  83517. } while (len && copy < have);
  83518. if (state->flags & 0x0200)
  83519. state->check = crc32(state->check, next, copy);
  83520. have -= copy;
  83521. next += copy;
  83522. if (len) goto inf_leave;
  83523. }
  83524. else if (state->head != Z_NULL)
  83525. state->head->comment = Z_NULL;
  83526. state->mode = HCRC;
  83527. case HCRC:
  83528. if (state->flags & 0x0200) {
  83529. NEEDBITS(16);
  83530. if (hold != (state->check & 0xffff)) {
  83531. strm->msg = (char *)"header crc mismatch";
  83532. state->mode = BAD;
  83533. break;
  83534. }
  83535. INITBITS();
  83536. }
  83537. if (state->head != Z_NULL) {
  83538. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83539. state->head->done = 1;
  83540. }
  83541. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83542. state->mode = TYPE;
  83543. break;
  83544. #endif
  83545. case DICTID:
  83546. NEEDBITS(32);
  83547. strm->adler = state->check = REVERSE(hold);
  83548. INITBITS();
  83549. state->mode = DICT;
  83550. case DICT:
  83551. if (state->havedict == 0) {
  83552. RESTORE();
  83553. return Z_NEED_DICT;
  83554. }
  83555. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83556. state->mode = TYPE;
  83557. case TYPE:
  83558. if (flush == Z_BLOCK) goto inf_leave;
  83559. case TYPEDO:
  83560. if (state->last) {
  83561. BYTEBITS();
  83562. state->mode = CHECK;
  83563. break;
  83564. }
  83565. NEEDBITS(3);
  83566. state->last = BITS(1);
  83567. DROPBITS(1);
  83568. switch (BITS(2)) {
  83569. case 0: /* stored block */
  83570. Tracev((stderr, "inflate: stored block%s\n",
  83571. state->last ? " (last)" : ""));
  83572. state->mode = STORED;
  83573. break;
  83574. case 1: /* fixed block */
  83575. fixedtables(state);
  83576. Tracev((stderr, "inflate: fixed codes block%s\n",
  83577. state->last ? " (last)" : ""));
  83578. state->mode = LEN; /* decode codes */
  83579. break;
  83580. case 2: /* dynamic block */
  83581. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83582. state->last ? " (last)" : ""));
  83583. state->mode = TABLE;
  83584. break;
  83585. case 3:
  83586. strm->msg = (char *)"invalid block type";
  83587. state->mode = BAD;
  83588. }
  83589. DROPBITS(2);
  83590. break;
  83591. case STORED:
  83592. BYTEBITS(); /* go to byte boundary */
  83593. NEEDBITS(32);
  83594. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83595. strm->msg = (char *)"invalid stored block lengths";
  83596. state->mode = BAD;
  83597. break;
  83598. }
  83599. state->length = (unsigned)hold & 0xffff;
  83600. Tracev((stderr, "inflate: stored length %u\n",
  83601. state->length));
  83602. INITBITS();
  83603. state->mode = COPY;
  83604. case COPY:
  83605. copy = state->length;
  83606. if (copy) {
  83607. if (copy > have) copy = have;
  83608. if (copy > left) copy = left;
  83609. if (copy == 0) goto inf_leave;
  83610. zmemcpy(put, next, copy);
  83611. have -= copy;
  83612. next += copy;
  83613. left -= copy;
  83614. put += copy;
  83615. state->length -= copy;
  83616. break;
  83617. }
  83618. Tracev((stderr, "inflate: stored end\n"));
  83619. state->mode = TYPE;
  83620. break;
  83621. case TABLE:
  83622. NEEDBITS(14);
  83623. state->nlen = BITS(5) + 257;
  83624. DROPBITS(5);
  83625. state->ndist = BITS(5) + 1;
  83626. DROPBITS(5);
  83627. state->ncode = BITS(4) + 4;
  83628. DROPBITS(4);
  83629. #ifndef PKZIP_BUG_WORKAROUND
  83630. if (state->nlen > 286 || state->ndist > 30) {
  83631. strm->msg = (char *)"too many length or distance symbols";
  83632. state->mode = BAD;
  83633. break;
  83634. }
  83635. #endif
  83636. Tracev((stderr, "inflate: table sizes ok\n"));
  83637. state->have = 0;
  83638. state->mode = LENLENS;
  83639. case LENLENS:
  83640. while (state->have < state->ncode) {
  83641. NEEDBITS(3);
  83642. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83643. DROPBITS(3);
  83644. }
  83645. while (state->have < 19)
  83646. state->lens[order[state->have++]] = 0;
  83647. state->next = state->codes;
  83648. state->lencode = (code const FAR *)(state->next);
  83649. state->lenbits = 7;
  83650. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83651. &(state->lenbits), state->work);
  83652. if (ret) {
  83653. strm->msg = (char *)"invalid code lengths set";
  83654. state->mode = BAD;
  83655. break;
  83656. }
  83657. Tracev((stderr, "inflate: code lengths ok\n"));
  83658. state->have = 0;
  83659. state->mode = CODELENS;
  83660. case CODELENS:
  83661. while (state->have < state->nlen + state->ndist) {
  83662. for (;;) {
  83663. thisx = state->lencode[BITS(state->lenbits)];
  83664. if ((unsigned)(thisx.bits) <= bits) break;
  83665. PULLBYTE();
  83666. }
  83667. if (thisx.val < 16) {
  83668. NEEDBITS(thisx.bits);
  83669. DROPBITS(thisx.bits);
  83670. state->lens[state->have++] = thisx.val;
  83671. }
  83672. else {
  83673. if (thisx.val == 16) {
  83674. NEEDBITS(thisx.bits + 2);
  83675. DROPBITS(thisx.bits);
  83676. if (state->have == 0) {
  83677. strm->msg = (char *)"invalid bit length repeat";
  83678. state->mode = BAD;
  83679. break;
  83680. }
  83681. len = state->lens[state->have - 1];
  83682. copy = 3 + BITS(2);
  83683. DROPBITS(2);
  83684. }
  83685. else if (thisx.val == 17) {
  83686. NEEDBITS(thisx.bits + 3);
  83687. DROPBITS(thisx.bits);
  83688. len = 0;
  83689. copy = 3 + BITS(3);
  83690. DROPBITS(3);
  83691. }
  83692. else {
  83693. NEEDBITS(thisx.bits + 7);
  83694. DROPBITS(thisx.bits);
  83695. len = 0;
  83696. copy = 11 + BITS(7);
  83697. DROPBITS(7);
  83698. }
  83699. if (state->have + copy > state->nlen + state->ndist) {
  83700. strm->msg = (char *)"invalid bit length repeat";
  83701. state->mode = BAD;
  83702. break;
  83703. }
  83704. while (copy--)
  83705. state->lens[state->have++] = (unsigned short)len;
  83706. }
  83707. }
  83708. /* handle error breaks in while */
  83709. if (state->mode == BAD) break;
  83710. /* build code tables */
  83711. state->next = state->codes;
  83712. state->lencode = (code const FAR *)(state->next);
  83713. state->lenbits = 9;
  83714. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  83715. &(state->lenbits), state->work);
  83716. if (ret) {
  83717. strm->msg = (char *)"invalid literal/lengths set";
  83718. state->mode = BAD;
  83719. break;
  83720. }
  83721. state->distcode = (code const FAR *)(state->next);
  83722. state->distbits = 6;
  83723. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  83724. &(state->next), &(state->distbits), state->work);
  83725. if (ret) {
  83726. strm->msg = (char *)"invalid distances set";
  83727. state->mode = BAD;
  83728. break;
  83729. }
  83730. Tracev((stderr, "inflate: codes ok\n"));
  83731. state->mode = LEN;
  83732. case LEN:
  83733. if (have >= 6 && left >= 258) {
  83734. RESTORE();
  83735. inflate_fast(strm, out);
  83736. LOAD();
  83737. break;
  83738. }
  83739. for (;;) {
  83740. thisx = state->lencode[BITS(state->lenbits)];
  83741. if ((unsigned)(thisx.bits) <= bits) break;
  83742. PULLBYTE();
  83743. }
  83744. if (thisx.op && (thisx.op & 0xf0) == 0) {
  83745. last = thisx;
  83746. for (;;) {
  83747. thisx = state->lencode[last.val +
  83748. (BITS(last.bits + last.op) >> last.bits)];
  83749. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83750. PULLBYTE();
  83751. }
  83752. DROPBITS(last.bits);
  83753. }
  83754. DROPBITS(thisx.bits);
  83755. state->length = (unsigned)thisx.val;
  83756. if ((int)(thisx.op) == 0) {
  83757. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83758. "inflate: literal '%c'\n" :
  83759. "inflate: literal 0x%02x\n", thisx.val));
  83760. state->mode = LIT;
  83761. break;
  83762. }
  83763. if (thisx.op & 32) {
  83764. Tracevv((stderr, "inflate: end of block\n"));
  83765. state->mode = TYPE;
  83766. break;
  83767. }
  83768. if (thisx.op & 64) {
  83769. strm->msg = (char *)"invalid literal/length code";
  83770. state->mode = BAD;
  83771. break;
  83772. }
  83773. state->extra = (unsigned)(thisx.op) & 15;
  83774. state->mode = LENEXT;
  83775. case LENEXT:
  83776. if (state->extra) {
  83777. NEEDBITS(state->extra);
  83778. state->length += BITS(state->extra);
  83779. DROPBITS(state->extra);
  83780. }
  83781. Tracevv((stderr, "inflate: length %u\n", state->length));
  83782. state->mode = DIST;
  83783. case DIST:
  83784. for (;;) {
  83785. thisx = state->distcode[BITS(state->distbits)];
  83786. if ((unsigned)(thisx.bits) <= bits) break;
  83787. PULLBYTE();
  83788. }
  83789. if ((thisx.op & 0xf0) == 0) {
  83790. last = thisx;
  83791. for (;;) {
  83792. thisx = state->distcode[last.val +
  83793. (BITS(last.bits + last.op) >> last.bits)];
  83794. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  83795. PULLBYTE();
  83796. }
  83797. DROPBITS(last.bits);
  83798. }
  83799. DROPBITS(thisx.bits);
  83800. if (thisx.op & 64) {
  83801. strm->msg = (char *)"invalid distance code";
  83802. state->mode = BAD;
  83803. break;
  83804. }
  83805. state->offset = (unsigned)thisx.val;
  83806. state->extra = (unsigned)(thisx.op) & 15;
  83807. state->mode = DISTEXT;
  83808. case DISTEXT:
  83809. if (state->extra) {
  83810. NEEDBITS(state->extra);
  83811. state->offset += BITS(state->extra);
  83812. DROPBITS(state->extra);
  83813. }
  83814. #ifdef INFLATE_STRICT
  83815. if (state->offset > state->dmax) {
  83816. strm->msg = (char *)"invalid distance too far back";
  83817. state->mode = BAD;
  83818. break;
  83819. }
  83820. #endif
  83821. if (state->offset > state->whave + out - left) {
  83822. strm->msg = (char *)"invalid distance too far back";
  83823. state->mode = BAD;
  83824. break;
  83825. }
  83826. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  83827. state->mode = MATCH;
  83828. case MATCH:
  83829. if (left == 0) goto inf_leave;
  83830. copy = out - left;
  83831. if (state->offset > copy) { /* copy from window */
  83832. copy = state->offset - copy;
  83833. if (copy > state->write) {
  83834. copy -= state->write;
  83835. from = state->window + (state->wsize - copy);
  83836. }
  83837. else
  83838. from = state->window + (state->write - copy);
  83839. if (copy > state->length) copy = state->length;
  83840. }
  83841. else { /* copy from output */
  83842. from = put - state->offset;
  83843. copy = state->length;
  83844. }
  83845. if (copy > left) copy = left;
  83846. left -= copy;
  83847. state->length -= copy;
  83848. do {
  83849. *put++ = *from++;
  83850. } while (--copy);
  83851. if (state->length == 0) state->mode = LEN;
  83852. break;
  83853. case LIT:
  83854. if (left == 0) goto inf_leave;
  83855. *put++ = (unsigned char)(state->length);
  83856. left--;
  83857. state->mode = LEN;
  83858. break;
  83859. case CHECK:
  83860. if (state->wrap) {
  83861. NEEDBITS(32);
  83862. out -= left;
  83863. strm->total_out += out;
  83864. state->total += out;
  83865. if (out)
  83866. strm->adler = state->check =
  83867. UPDATE(state->check, put - out, out);
  83868. out = left;
  83869. if ((
  83870. #ifdef GUNZIP
  83871. state->flags ? hold :
  83872. #endif
  83873. REVERSE(hold)) != state->check) {
  83874. strm->msg = (char *)"incorrect data check";
  83875. state->mode = BAD;
  83876. break;
  83877. }
  83878. INITBITS();
  83879. Tracev((stderr, "inflate: check matches trailer\n"));
  83880. }
  83881. #ifdef GUNZIP
  83882. state->mode = LENGTH;
  83883. case LENGTH:
  83884. if (state->wrap && state->flags) {
  83885. NEEDBITS(32);
  83886. if (hold != (state->total & 0xffffffffUL)) {
  83887. strm->msg = (char *)"incorrect length check";
  83888. state->mode = BAD;
  83889. break;
  83890. }
  83891. INITBITS();
  83892. Tracev((stderr, "inflate: length matches trailer\n"));
  83893. }
  83894. #endif
  83895. state->mode = DONE;
  83896. case DONE:
  83897. ret = Z_STREAM_END;
  83898. goto inf_leave;
  83899. case BAD:
  83900. ret = Z_DATA_ERROR;
  83901. goto inf_leave;
  83902. case MEM:
  83903. return Z_MEM_ERROR;
  83904. case SYNC:
  83905. default:
  83906. return Z_STREAM_ERROR;
  83907. }
  83908. /*
  83909. Return from inflate(), updating the total counts and the check value.
  83910. If there was no progress during the inflate() call, return a buffer
  83911. error. Call updatewindow() to create and/or update the window state.
  83912. Note: a memory error from inflate() is non-recoverable.
  83913. */
  83914. inf_leave:
  83915. RESTORE();
  83916. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  83917. if (updatewindow(strm, out)) {
  83918. state->mode = MEM;
  83919. return Z_MEM_ERROR;
  83920. }
  83921. in -= strm->avail_in;
  83922. out -= strm->avail_out;
  83923. strm->total_in += in;
  83924. strm->total_out += out;
  83925. state->total += out;
  83926. if (state->wrap && out)
  83927. strm->adler = state->check =
  83928. UPDATE(state->check, strm->next_out - out, out);
  83929. strm->data_type = state->bits + (state->last ? 64 : 0) +
  83930. (state->mode == TYPE ? 128 : 0);
  83931. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  83932. ret = Z_BUF_ERROR;
  83933. return ret;
  83934. }
  83935. int ZEXPORT inflateEnd (z_streamp strm)
  83936. {
  83937. struct inflate_state FAR *state;
  83938. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  83939. return Z_STREAM_ERROR;
  83940. state = (struct inflate_state FAR *)strm->state;
  83941. if (state->window != Z_NULL) ZFREE(strm, state->window);
  83942. ZFREE(strm, strm->state);
  83943. strm->state = Z_NULL;
  83944. Tracev((stderr, "inflate: end\n"));
  83945. return Z_OK;
  83946. }
  83947. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  83948. {
  83949. struct inflate_state FAR *state;
  83950. unsigned long id_;
  83951. /* check state */
  83952. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83953. state = (struct inflate_state FAR *)strm->state;
  83954. if (state->wrap != 0 && state->mode != DICT)
  83955. return Z_STREAM_ERROR;
  83956. /* check for correct dictionary id */
  83957. if (state->mode == DICT) {
  83958. id_ = adler32(0L, Z_NULL, 0);
  83959. id_ = adler32(id_, dictionary, dictLength);
  83960. if (id_ != state->check)
  83961. return Z_DATA_ERROR;
  83962. }
  83963. /* copy dictionary to window */
  83964. if (updatewindow(strm, strm->avail_out)) {
  83965. state->mode = MEM;
  83966. return Z_MEM_ERROR;
  83967. }
  83968. if (dictLength > state->wsize) {
  83969. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  83970. state->wsize);
  83971. state->whave = state->wsize;
  83972. }
  83973. else {
  83974. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  83975. dictLength);
  83976. state->whave = dictLength;
  83977. }
  83978. state->havedict = 1;
  83979. Tracev((stderr, "inflate: dictionary set\n"));
  83980. return Z_OK;
  83981. }
  83982. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  83983. {
  83984. struct inflate_state FAR *state;
  83985. /* check state */
  83986. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83987. state = (struct inflate_state FAR *)strm->state;
  83988. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  83989. /* save header structure */
  83990. state->head = head;
  83991. head->done = 0;
  83992. return Z_OK;
  83993. }
  83994. /*
  83995. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  83996. or when out of input. When called, *have is the number of pattern bytes
  83997. found in order so far, in 0..3. On return *have is updated to the new
  83998. state. If on return *have equals four, then the pattern was found and the
  83999. return value is how many bytes were read including the last byte of the
  84000. pattern. If *have is less than four, then the pattern has not been found
  84001. yet and the return value is len. In the latter case, syncsearch() can be
  84002. called again with more data and the *have state. *have is initialized to
  84003. zero for the first call.
  84004. */
  84005. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84006. {
  84007. unsigned got;
  84008. unsigned next;
  84009. got = *have;
  84010. next = 0;
  84011. while (next < len && got < 4) {
  84012. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84013. got++;
  84014. else if (buf[next])
  84015. got = 0;
  84016. else
  84017. got = 4 - got;
  84018. next++;
  84019. }
  84020. *have = got;
  84021. return next;
  84022. }
  84023. int ZEXPORT inflateSync (z_streamp strm)
  84024. {
  84025. unsigned len; /* number of bytes to look at or looked at */
  84026. unsigned long in, out; /* temporary to save total_in and total_out */
  84027. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84028. struct inflate_state FAR *state;
  84029. /* check parameters */
  84030. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84031. state = (struct inflate_state FAR *)strm->state;
  84032. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84033. /* if first time, start search in bit buffer */
  84034. if (state->mode != SYNC) {
  84035. state->mode = SYNC;
  84036. state->hold <<= state->bits & 7;
  84037. state->bits -= state->bits & 7;
  84038. len = 0;
  84039. while (state->bits >= 8) {
  84040. buf[len++] = (unsigned char)(state->hold);
  84041. state->hold >>= 8;
  84042. state->bits -= 8;
  84043. }
  84044. state->have = 0;
  84045. syncsearch(&(state->have), buf, len);
  84046. }
  84047. /* search available input */
  84048. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84049. strm->avail_in -= len;
  84050. strm->next_in += len;
  84051. strm->total_in += len;
  84052. /* return no joy or set up to restart inflate() on a new block */
  84053. if (state->have != 4) return Z_DATA_ERROR;
  84054. in = strm->total_in; out = strm->total_out;
  84055. inflateReset(strm);
  84056. strm->total_in = in; strm->total_out = out;
  84057. state->mode = TYPE;
  84058. return Z_OK;
  84059. }
  84060. /*
  84061. Returns true if inflate is currently at the end of a block generated by
  84062. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84063. implementation to provide an additional safety check. PPP uses
  84064. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84065. block. When decompressing, PPP checks that at the end of input packet,
  84066. inflate is waiting for these length bytes.
  84067. */
  84068. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84069. {
  84070. struct inflate_state FAR *state;
  84071. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84072. state = (struct inflate_state FAR *)strm->state;
  84073. return state->mode == STORED && state->bits == 0;
  84074. }
  84075. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84076. {
  84077. struct inflate_state FAR *state;
  84078. struct inflate_state FAR *copy;
  84079. unsigned char FAR *window;
  84080. unsigned wsize;
  84081. /* check input */
  84082. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84083. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84084. return Z_STREAM_ERROR;
  84085. state = (struct inflate_state FAR *)source->state;
  84086. /* allocate space */
  84087. copy = (struct inflate_state FAR *)
  84088. ZALLOC(source, 1, sizeof(struct inflate_state));
  84089. if (copy == Z_NULL) return Z_MEM_ERROR;
  84090. window = Z_NULL;
  84091. if (state->window != Z_NULL) {
  84092. window = (unsigned char FAR *)
  84093. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84094. if (window == Z_NULL) {
  84095. ZFREE(source, copy);
  84096. return Z_MEM_ERROR;
  84097. }
  84098. }
  84099. /* copy state */
  84100. zmemcpy(dest, source, sizeof(z_stream));
  84101. zmemcpy(copy, state, sizeof(struct inflate_state));
  84102. if (state->lencode >= state->codes &&
  84103. state->lencode <= state->codes + ENOUGH - 1) {
  84104. copy->lencode = copy->codes + (state->lencode - state->codes);
  84105. copy->distcode = copy->codes + (state->distcode - state->codes);
  84106. }
  84107. copy->next = copy->codes + (state->next - state->codes);
  84108. if (window != Z_NULL) {
  84109. wsize = 1U << state->wbits;
  84110. zmemcpy(window, state->window, wsize);
  84111. }
  84112. copy->window = window;
  84113. dest->state = (struct internal_state FAR *)copy;
  84114. return Z_OK;
  84115. }
  84116. /*** End of inlined file: inflate.c ***/
  84117. /*** Start of inlined file: inftrees.c ***/
  84118. #define MAXBITS 15
  84119. const char inflate_copyright[] =
  84120. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84121. /*
  84122. If you use the zlib library in a product, an acknowledgment is welcome
  84123. in the documentation of your product. If for some reason you cannot
  84124. include such an acknowledgment, I would appreciate that you keep this
  84125. copyright string in the executable of your product.
  84126. */
  84127. /*
  84128. Build a set of tables to decode the provided canonical Huffman code.
  84129. The code lengths are lens[0..codes-1]. The result starts at *table,
  84130. whose indices are 0..2^bits-1. work is a writable array of at least
  84131. lens shorts, which is used as a work area. type is the type of code
  84132. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84133. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84134. on return points to the next available entry's address. bits is the
  84135. requested root table index bits, and on return it is the actual root
  84136. table index bits. It will differ if the request is greater than the
  84137. longest code or if it is less than the shortest code.
  84138. */
  84139. int inflate_table (codetype type,
  84140. unsigned short FAR *lens,
  84141. unsigned codes,
  84142. code FAR * FAR *table,
  84143. unsigned FAR *bits,
  84144. unsigned short FAR *work)
  84145. {
  84146. unsigned len; /* a code's length in bits */
  84147. unsigned sym; /* index of code symbols */
  84148. unsigned min, max; /* minimum and maximum code lengths */
  84149. unsigned root; /* number of index bits for root table */
  84150. unsigned curr; /* number of index bits for current table */
  84151. unsigned drop; /* code bits to drop for sub-table */
  84152. int left; /* number of prefix codes available */
  84153. unsigned used; /* code entries in table used */
  84154. unsigned huff; /* Huffman code */
  84155. unsigned incr; /* for incrementing code, index */
  84156. unsigned fill; /* index for replicating entries */
  84157. unsigned low; /* low bits for current root entry */
  84158. unsigned mask; /* mask for low root bits */
  84159. code thisx; /* table entry for duplication */
  84160. code FAR *next; /* next available space in table */
  84161. const unsigned short FAR *base; /* base value table to use */
  84162. const unsigned short FAR *extra; /* extra bits table to use */
  84163. int end; /* use base and extra for symbol > end */
  84164. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84165. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84166. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84167. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84168. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84169. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84170. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84171. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84172. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84173. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84174. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84175. 8193, 12289, 16385, 24577, 0, 0};
  84176. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84177. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84178. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84179. 28, 28, 29, 29, 64, 64};
  84180. /*
  84181. Process a set of code lengths to create a canonical Huffman code. The
  84182. code lengths are lens[0..codes-1]. Each length corresponds to the
  84183. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84184. symbols by length from short to long, and retaining the symbol order
  84185. for codes with equal lengths. Then the code starts with all zero bits
  84186. for the first code of the shortest length, and the codes are integer
  84187. increments for the same length, and zeros are appended as the length
  84188. increases. For the deflate format, these bits are stored backwards
  84189. from their more natural integer increment ordering, and so when the
  84190. decoding tables are built in the large loop below, the integer codes
  84191. are incremented backwards.
  84192. This routine assumes, but does not check, that all of the entries in
  84193. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84194. 1..MAXBITS is interpreted as that code length. zero means that that
  84195. symbol does not occur in this code.
  84196. The codes are sorted by computing a count of codes for each length,
  84197. creating from that a table of starting indices for each length in the
  84198. sorted table, and then entering the symbols in order in the sorted
  84199. table. The sorted table is work[], with that space being provided by
  84200. the caller.
  84201. The length counts are used for other purposes as well, i.e. finding
  84202. the minimum and maximum length codes, determining if there are any
  84203. codes at all, checking for a valid set of lengths, and looking ahead
  84204. at length counts to determine sub-table sizes when building the
  84205. decoding tables.
  84206. */
  84207. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84208. for (len = 0; len <= MAXBITS; len++)
  84209. count[len] = 0;
  84210. for (sym = 0; sym < codes; sym++)
  84211. count[lens[sym]]++;
  84212. /* bound code lengths, force root to be within code lengths */
  84213. root = *bits;
  84214. for (max = MAXBITS; max >= 1; max--)
  84215. if (count[max] != 0) break;
  84216. if (root > max) root = max;
  84217. if (max == 0) { /* no symbols to code at all */
  84218. thisx.op = (unsigned char)64; /* invalid code marker */
  84219. thisx.bits = (unsigned char)1;
  84220. thisx.val = (unsigned short)0;
  84221. *(*table)++ = thisx; /* make a table to force an error */
  84222. *(*table)++ = thisx;
  84223. *bits = 1;
  84224. return 0; /* no symbols, but wait for decoding to report error */
  84225. }
  84226. for (min = 1; min <= MAXBITS; min++)
  84227. if (count[min] != 0) break;
  84228. if (root < min) root = min;
  84229. /* check for an over-subscribed or incomplete set of lengths */
  84230. left = 1;
  84231. for (len = 1; len <= MAXBITS; len++) {
  84232. left <<= 1;
  84233. left -= count[len];
  84234. if (left < 0) return -1; /* over-subscribed */
  84235. }
  84236. if (left > 0 && (type == CODES || max != 1))
  84237. return -1; /* incomplete set */
  84238. /* generate offsets into symbol table for each length for sorting */
  84239. offs[1] = 0;
  84240. for (len = 1; len < MAXBITS; len++)
  84241. offs[len + 1] = offs[len] + count[len];
  84242. /* sort symbols by length, by symbol order within each length */
  84243. for (sym = 0; sym < codes; sym++)
  84244. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84245. /*
  84246. Create and fill in decoding tables. In this loop, the table being
  84247. filled is at next and has curr index bits. The code being used is huff
  84248. with length len. That code is converted to an index by dropping drop
  84249. bits off of the bottom. For codes where len is less than drop + curr,
  84250. those top drop + curr - len bits are incremented through all values to
  84251. fill the table with replicated entries.
  84252. root is the number of index bits for the root table. When len exceeds
  84253. root, sub-tables are created pointed to by the root entry with an index
  84254. of the low root bits of huff. This is saved in low to check for when a
  84255. new sub-table should be started. drop is zero when the root table is
  84256. being filled, and drop is root when sub-tables are being filled.
  84257. When a new sub-table is needed, it is necessary to look ahead in the
  84258. code lengths to determine what size sub-table is needed. The length
  84259. counts are used for this, and so count[] is decremented as codes are
  84260. entered in the tables.
  84261. used keeps track of how many table entries have been allocated from the
  84262. provided *table space. It is checked when a LENS table is being made
  84263. against the space in *table, ENOUGH, minus the maximum space needed by
  84264. the worst case distance code, MAXD. This should never happen, but the
  84265. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84266. This assumes that when type == LENS, bits == 9.
  84267. sym increments through all symbols, and the loop terminates when
  84268. all codes of length max, i.e. all codes, have been processed. This
  84269. routine permits incomplete codes, so another loop after this one fills
  84270. in the rest of the decoding tables with invalid code markers.
  84271. */
  84272. /* set up for code type */
  84273. switch (type) {
  84274. case CODES:
  84275. base = extra = work; /* dummy value--not used */
  84276. end = 19;
  84277. break;
  84278. case LENS:
  84279. base = lbase;
  84280. base -= 257;
  84281. extra = lext;
  84282. extra -= 257;
  84283. end = 256;
  84284. break;
  84285. default: /* DISTS */
  84286. base = dbase;
  84287. extra = dext;
  84288. end = -1;
  84289. }
  84290. /* initialize state for loop */
  84291. huff = 0; /* starting code */
  84292. sym = 0; /* starting code symbol */
  84293. len = min; /* starting code length */
  84294. next = *table; /* current table to fill in */
  84295. curr = root; /* current table index bits */
  84296. drop = 0; /* current bits to drop from code for index */
  84297. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84298. used = 1U << root; /* use root table entries */
  84299. mask = used - 1; /* mask for comparing low */
  84300. /* check available table space */
  84301. if (type == LENS && used >= ENOUGH - MAXD)
  84302. return 1;
  84303. /* process all codes and make table entries */
  84304. for (;;) {
  84305. /* create table entry */
  84306. thisx.bits = (unsigned char)(len - drop);
  84307. if ((int)(work[sym]) < end) {
  84308. thisx.op = (unsigned char)0;
  84309. thisx.val = work[sym];
  84310. }
  84311. else if ((int)(work[sym]) > end) {
  84312. thisx.op = (unsigned char)(extra[work[sym]]);
  84313. thisx.val = base[work[sym]];
  84314. }
  84315. else {
  84316. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84317. thisx.val = 0;
  84318. }
  84319. /* replicate for those indices with low len bits equal to huff */
  84320. incr = 1U << (len - drop);
  84321. fill = 1U << curr;
  84322. min = fill; /* save offset to next table */
  84323. do {
  84324. fill -= incr;
  84325. next[(huff >> drop) + fill] = thisx;
  84326. } while (fill != 0);
  84327. /* backwards increment the len-bit code huff */
  84328. incr = 1U << (len - 1);
  84329. while (huff & incr)
  84330. incr >>= 1;
  84331. if (incr != 0) {
  84332. huff &= incr - 1;
  84333. huff += incr;
  84334. }
  84335. else
  84336. huff = 0;
  84337. /* go to next symbol, update count, len */
  84338. sym++;
  84339. if (--(count[len]) == 0) {
  84340. if (len == max) break;
  84341. len = lens[work[sym]];
  84342. }
  84343. /* create new sub-table if needed */
  84344. if (len > root && (huff & mask) != low) {
  84345. /* if first time, transition to sub-tables */
  84346. if (drop == 0)
  84347. drop = root;
  84348. /* increment past last table */
  84349. next += min; /* here min is 1 << curr */
  84350. /* determine length of next table */
  84351. curr = len - drop;
  84352. left = (int)(1 << curr);
  84353. while (curr + drop < max) {
  84354. left -= count[curr + drop];
  84355. if (left <= 0) break;
  84356. curr++;
  84357. left <<= 1;
  84358. }
  84359. /* check for enough space */
  84360. used += 1U << curr;
  84361. if (type == LENS && used >= ENOUGH - MAXD)
  84362. return 1;
  84363. /* point entry in root table to sub-table */
  84364. low = huff & mask;
  84365. (*table)[low].op = (unsigned char)curr;
  84366. (*table)[low].bits = (unsigned char)root;
  84367. (*table)[low].val = (unsigned short)(next - *table);
  84368. }
  84369. }
  84370. /*
  84371. Fill in rest of table for incomplete codes. This loop is similar to the
  84372. loop above in incrementing huff for table indices. It is assumed that
  84373. len is equal to curr + drop, so there is no loop needed to increment
  84374. through high index bits. When the current sub-table is filled, the loop
  84375. drops back to the root table to fill in any remaining entries there.
  84376. */
  84377. thisx.op = (unsigned char)64; /* invalid code marker */
  84378. thisx.bits = (unsigned char)(len - drop);
  84379. thisx.val = (unsigned short)0;
  84380. while (huff != 0) {
  84381. /* when done with sub-table, drop back to root table */
  84382. if (drop != 0 && (huff & mask) != low) {
  84383. drop = 0;
  84384. len = root;
  84385. next = *table;
  84386. thisx.bits = (unsigned char)len;
  84387. }
  84388. /* put invalid code marker in table */
  84389. next[huff >> drop] = thisx;
  84390. /* backwards increment the len-bit code huff */
  84391. incr = 1U << (len - 1);
  84392. while (huff & incr)
  84393. incr >>= 1;
  84394. if (incr != 0) {
  84395. huff &= incr - 1;
  84396. huff += incr;
  84397. }
  84398. else
  84399. huff = 0;
  84400. }
  84401. /* set return parameters */
  84402. *table += used;
  84403. *bits = root;
  84404. return 0;
  84405. }
  84406. /*** End of inlined file: inftrees.c ***/
  84407. /*** Start of inlined file: trees.c ***/
  84408. /*
  84409. * ALGORITHM
  84410. *
  84411. * The "deflation" process uses several Huffman trees. The more
  84412. * common source values are represented by shorter bit sequences.
  84413. *
  84414. * Each code tree is stored in a compressed form which is itself
  84415. * a Huffman encoding of the lengths of all the code strings (in
  84416. * ascending order by source values). The actual code strings are
  84417. * reconstructed from the lengths in the inflate process, as described
  84418. * in the deflate specification.
  84419. *
  84420. * REFERENCES
  84421. *
  84422. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84423. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84424. *
  84425. * Storer, James A.
  84426. * Data Compression: Methods and Theory, pp. 49-50.
  84427. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84428. *
  84429. * Sedgewick, R.
  84430. * Algorithms, p290.
  84431. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84432. */
  84433. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84434. /* #define GEN_TREES_H */
  84435. #ifdef DEBUG
  84436. # include <ctype.h>
  84437. #endif
  84438. /* ===========================================================================
  84439. * Constants
  84440. */
  84441. #define MAX_BL_BITS 7
  84442. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84443. #define END_BLOCK 256
  84444. /* end of block literal code */
  84445. #define REP_3_6 16
  84446. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84447. #define REPZ_3_10 17
  84448. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84449. #define REPZ_11_138 18
  84450. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84451. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84452. = {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};
  84453. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84454. = {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};
  84455. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84456. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84457. local const uch bl_order[BL_CODES]
  84458. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84459. /* The lengths of the bit length codes are sent in order of decreasing
  84460. * probability, to avoid transmitting the lengths for unused bit length codes.
  84461. */
  84462. #define Buf_size (8 * 2*sizeof(char))
  84463. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84464. * more than 16 bits on some systems.)
  84465. */
  84466. /* ===========================================================================
  84467. * Local data. These are initialized only once.
  84468. */
  84469. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84470. #if defined(GEN_TREES_H) || !defined(STDC)
  84471. /* non ANSI compilers may not accept trees.h */
  84472. local ct_data static_ltree[L_CODES+2];
  84473. /* The static literal tree. Since the bit lengths are imposed, there is no
  84474. * need for the L_CODES extra codes used during heap construction. However
  84475. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84476. * below).
  84477. */
  84478. local ct_data static_dtree[D_CODES];
  84479. /* The static distance tree. (Actually a trivial tree since all codes use
  84480. * 5 bits.)
  84481. */
  84482. uch _dist_code[DIST_CODE_LEN];
  84483. /* Distance codes. The first 256 values correspond to the distances
  84484. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84485. * the 15 bit distances.
  84486. */
  84487. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84488. /* length code for each normalized match length (0 == MIN_MATCH) */
  84489. local int base_length[LENGTH_CODES];
  84490. /* First normalized length for each code (0 = MIN_MATCH) */
  84491. local int base_dist[D_CODES];
  84492. /* First normalized distance for each code (0 = distance of 1) */
  84493. #else
  84494. /*** Start of inlined file: trees.h ***/
  84495. local const ct_data static_ltree[L_CODES+2] = {
  84496. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84497. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84498. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84499. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84500. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84501. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84502. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84503. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84504. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84505. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84506. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84507. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84508. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84509. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84510. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84511. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84512. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84513. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84514. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84515. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84516. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84517. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84518. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84519. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84520. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84521. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84522. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84523. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84524. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84525. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84526. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84527. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84528. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84529. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84530. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84531. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84532. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84533. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84534. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84535. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84536. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84537. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84538. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84539. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84540. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84541. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84542. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84543. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84544. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84545. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84546. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84547. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84548. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84549. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84550. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84551. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84552. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84553. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84554. };
  84555. local const ct_data static_dtree[D_CODES] = {
  84556. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84557. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84558. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84559. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84560. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84561. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84562. };
  84563. const uch _dist_code[DIST_CODE_LEN] = {
  84564. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84565. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84566. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84567. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84568. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84569. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84570. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84571. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84572. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84573. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84574. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84575. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84576. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84577. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84578. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84579. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84580. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84581. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84582. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84583. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84584. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84585. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84586. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84587. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84588. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84589. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84590. };
  84591. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84592. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84593. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84594. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84595. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84596. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84597. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84598. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84599. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84600. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84601. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84602. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84603. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84604. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84605. };
  84606. local const int base_length[LENGTH_CODES] = {
  84607. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84608. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84609. };
  84610. local const int base_dist[D_CODES] = {
  84611. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84612. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84613. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84614. };
  84615. /*** End of inlined file: trees.h ***/
  84616. #endif /* GEN_TREES_H */
  84617. struct static_tree_desc_s {
  84618. const ct_data *static_tree; /* static tree or NULL */
  84619. const intf *extra_bits; /* extra bits for each code or NULL */
  84620. int extra_base; /* base index for extra_bits */
  84621. int elems; /* max number of elements in the tree */
  84622. int max_length; /* max bit length for the codes */
  84623. };
  84624. local static_tree_desc static_l_desc =
  84625. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84626. local static_tree_desc static_d_desc =
  84627. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84628. local static_tree_desc static_bl_desc =
  84629. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84630. /* ===========================================================================
  84631. * Local (static) routines in this file.
  84632. */
  84633. local void tr_static_init OF((void));
  84634. local void init_block OF((deflate_state *s));
  84635. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84636. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84637. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84638. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84639. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84640. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84641. local int build_bl_tree OF((deflate_state *s));
  84642. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84643. int blcodes));
  84644. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84645. ct_data *dtree));
  84646. local void set_data_type OF((deflate_state *s));
  84647. local unsigned bi_reverse OF((unsigned value, int length));
  84648. local void bi_windup OF((deflate_state *s));
  84649. local void bi_flush OF((deflate_state *s));
  84650. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84651. int header));
  84652. #ifdef GEN_TREES_H
  84653. local void gen_trees_header OF((void));
  84654. #endif
  84655. #ifndef DEBUG
  84656. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84657. /* Send a code of the given tree. c and tree must not have side effects */
  84658. #else /* DEBUG */
  84659. # define send_code(s, c, tree) \
  84660. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  84661. send_bits(s, tree[c].Code, tree[c].Len); }
  84662. #endif
  84663. /* ===========================================================================
  84664. * Output a short LSB first on the stream.
  84665. * IN assertion: there is enough room in pendingBuf.
  84666. */
  84667. #define put_short(s, w) { \
  84668. put_byte(s, (uch)((w) & 0xff)); \
  84669. put_byte(s, (uch)((ush)(w) >> 8)); \
  84670. }
  84671. /* ===========================================================================
  84672. * Send a value on a given number of bits.
  84673. * IN assertion: length <= 16 and value fits in length bits.
  84674. */
  84675. #ifdef DEBUG
  84676. local void send_bits OF((deflate_state *s, int value, int length));
  84677. local void send_bits (deflate_state *s, int value, int length)
  84678. {
  84679. Tracevv((stderr," l %2d v %4x ", length, value));
  84680. Assert(length > 0 && length <= 15, "invalid length");
  84681. s->bits_sent += (ulg)length;
  84682. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  84683. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  84684. * unused bits in value.
  84685. */
  84686. if (s->bi_valid > (int)Buf_size - length) {
  84687. s->bi_buf |= (value << s->bi_valid);
  84688. put_short(s, s->bi_buf);
  84689. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  84690. s->bi_valid += length - Buf_size;
  84691. } else {
  84692. s->bi_buf |= value << s->bi_valid;
  84693. s->bi_valid += length;
  84694. }
  84695. }
  84696. #else /* !DEBUG */
  84697. #define send_bits(s, value, length) \
  84698. { int len = length;\
  84699. if (s->bi_valid > (int)Buf_size - len) {\
  84700. int val = value;\
  84701. s->bi_buf |= (val << s->bi_valid);\
  84702. put_short(s, s->bi_buf);\
  84703. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  84704. s->bi_valid += len - Buf_size;\
  84705. } else {\
  84706. s->bi_buf |= (value) << s->bi_valid;\
  84707. s->bi_valid += len;\
  84708. }\
  84709. }
  84710. #endif /* DEBUG */
  84711. /* the arguments must not have side effects */
  84712. /* ===========================================================================
  84713. * Initialize the various 'constant' tables.
  84714. */
  84715. local void tr_static_init()
  84716. {
  84717. #if defined(GEN_TREES_H) || !defined(STDC)
  84718. static int static_init_done = 0;
  84719. int n; /* iterates over tree elements */
  84720. int bits; /* bit counter */
  84721. int length; /* length value */
  84722. int code; /* code value */
  84723. int dist; /* distance index */
  84724. ush bl_count[MAX_BITS+1];
  84725. /* number of codes at each bit length for an optimal tree */
  84726. if (static_init_done) return;
  84727. /* For some embedded targets, global variables are not initialized: */
  84728. static_l_desc.static_tree = static_ltree;
  84729. static_l_desc.extra_bits = extra_lbits;
  84730. static_d_desc.static_tree = static_dtree;
  84731. static_d_desc.extra_bits = extra_dbits;
  84732. static_bl_desc.extra_bits = extra_blbits;
  84733. /* Initialize the mapping length (0..255) -> length code (0..28) */
  84734. length = 0;
  84735. for (code = 0; code < LENGTH_CODES-1; code++) {
  84736. base_length[code] = length;
  84737. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  84738. _length_code[length++] = (uch)code;
  84739. }
  84740. }
  84741. Assert (length == 256, "tr_static_init: length != 256");
  84742. /* Note that the length 255 (match length 258) can be represented
  84743. * in two different ways: code 284 + 5 bits or code 285, so we
  84744. * overwrite length_code[255] to use the best encoding:
  84745. */
  84746. _length_code[length-1] = (uch)code;
  84747. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  84748. dist = 0;
  84749. for (code = 0 ; code < 16; code++) {
  84750. base_dist[code] = dist;
  84751. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  84752. _dist_code[dist++] = (uch)code;
  84753. }
  84754. }
  84755. Assert (dist == 256, "tr_static_init: dist != 256");
  84756. dist >>= 7; /* from now on, all distances are divided by 128 */
  84757. for ( ; code < D_CODES; code++) {
  84758. base_dist[code] = dist << 7;
  84759. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  84760. _dist_code[256 + dist++] = (uch)code;
  84761. }
  84762. }
  84763. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  84764. /* Construct the codes of the static literal tree */
  84765. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  84766. n = 0;
  84767. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  84768. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  84769. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  84770. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  84771. /* Codes 286 and 287 do not exist, but we must include them in the
  84772. * tree construction to get a canonical Huffman tree (longest code
  84773. * all ones)
  84774. */
  84775. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  84776. /* The static distance tree is trivial: */
  84777. for (n = 0; n < D_CODES; n++) {
  84778. static_dtree[n].Len = 5;
  84779. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  84780. }
  84781. static_init_done = 1;
  84782. # ifdef GEN_TREES_H
  84783. gen_trees_header();
  84784. # endif
  84785. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  84786. }
  84787. /* ===========================================================================
  84788. * Genererate the file trees.h describing the static trees.
  84789. */
  84790. #ifdef GEN_TREES_H
  84791. # ifndef DEBUG
  84792. # include <stdio.h>
  84793. # endif
  84794. # define SEPARATOR(i, last, width) \
  84795. ((i) == (last)? "\n};\n\n" : \
  84796. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  84797. void gen_trees_header()
  84798. {
  84799. FILE *header = fopen("trees.h", "w");
  84800. int i;
  84801. Assert (header != NULL, "Can't open trees.h");
  84802. fprintf(header,
  84803. "/* header created automatically with -DGEN_TREES_H */\n\n");
  84804. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  84805. for (i = 0; i < L_CODES+2; i++) {
  84806. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  84807. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  84808. }
  84809. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  84810. for (i = 0; i < D_CODES; i++) {
  84811. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  84812. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  84813. }
  84814. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  84815. for (i = 0; i < DIST_CODE_LEN; i++) {
  84816. fprintf(header, "%2u%s", _dist_code[i],
  84817. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  84818. }
  84819. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  84820. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  84821. fprintf(header, "%2u%s", _length_code[i],
  84822. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  84823. }
  84824. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  84825. for (i = 0; i < LENGTH_CODES; i++) {
  84826. fprintf(header, "%1u%s", base_length[i],
  84827. SEPARATOR(i, LENGTH_CODES-1, 20));
  84828. }
  84829. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  84830. for (i = 0; i < D_CODES; i++) {
  84831. fprintf(header, "%5u%s", base_dist[i],
  84832. SEPARATOR(i, D_CODES-1, 10));
  84833. }
  84834. fclose(header);
  84835. }
  84836. #endif /* GEN_TREES_H */
  84837. /* ===========================================================================
  84838. * Initialize the tree data structures for a new zlib stream.
  84839. */
  84840. void _tr_init(deflate_state *s)
  84841. {
  84842. tr_static_init();
  84843. s->l_desc.dyn_tree = s->dyn_ltree;
  84844. s->l_desc.stat_desc = &static_l_desc;
  84845. s->d_desc.dyn_tree = s->dyn_dtree;
  84846. s->d_desc.stat_desc = &static_d_desc;
  84847. s->bl_desc.dyn_tree = s->bl_tree;
  84848. s->bl_desc.stat_desc = &static_bl_desc;
  84849. s->bi_buf = 0;
  84850. s->bi_valid = 0;
  84851. s->last_eob_len = 8; /* enough lookahead for inflate */
  84852. #ifdef DEBUG
  84853. s->compressed_len = 0L;
  84854. s->bits_sent = 0L;
  84855. #endif
  84856. /* Initialize the first block of the first file: */
  84857. init_block(s);
  84858. }
  84859. /* ===========================================================================
  84860. * Initialize a new block.
  84861. */
  84862. local void init_block (deflate_state *s)
  84863. {
  84864. int n; /* iterates over tree elements */
  84865. /* Initialize the trees. */
  84866. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  84867. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  84868. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  84869. s->dyn_ltree[END_BLOCK].Freq = 1;
  84870. s->opt_len = s->static_len = 0L;
  84871. s->last_lit = s->matches = 0;
  84872. }
  84873. #define SMALLEST 1
  84874. /* Index within the heap array of least frequent node in the Huffman tree */
  84875. /* ===========================================================================
  84876. * Remove the smallest element from the heap and recreate the heap with
  84877. * one less element. Updates heap and heap_len.
  84878. */
  84879. #define pqremove(s, tree, top) \
  84880. {\
  84881. top = s->heap[SMALLEST]; \
  84882. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  84883. pqdownheap(s, tree, SMALLEST); \
  84884. }
  84885. /* ===========================================================================
  84886. * Compares to subtrees, using the tree depth as tie breaker when
  84887. * the subtrees have equal frequency. This minimizes the worst case length.
  84888. */
  84889. #define smaller(tree, n, m, depth) \
  84890. (tree[n].Freq < tree[m].Freq || \
  84891. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  84892. /* ===========================================================================
  84893. * Restore the heap property by moving down the tree starting at node k,
  84894. * exchanging a node with the smallest of its two sons if necessary, stopping
  84895. * when the heap property is re-established (each father smaller than its
  84896. * two sons).
  84897. */
  84898. local void pqdownheap (deflate_state *s,
  84899. ct_data *tree, /* the tree to restore */
  84900. int k) /* node to move down */
  84901. {
  84902. int v = s->heap[k];
  84903. int j = k << 1; /* left son of k */
  84904. while (j <= s->heap_len) {
  84905. /* Set j to the smallest of the two sons: */
  84906. if (j < s->heap_len &&
  84907. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  84908. j++;
  84909. }
  84910. /* Exit if v is smaller than both sons */
  84911. if (smaller(tree, v, s->heap[j], s->depth)) break;
  84912. /* Exchange v with the smallest son */
  84913. s->heap[k] = s->heap[j]; k = j;
  84914. /* And continue down the tree, setting j to the left son of k */
  84915. j <<= 1;
  84916. }
  84917. s->heap[k] = v;
  84918. }
  84919. /* ===========================================================================
  84920. * Compute the optimal bit lengths for a tree and update the total bit length
  84921. * for the current block.
  84922. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  84923. * above are the tree nodes sorted by increasing frequency.
  84924. * OUT assertions: the field len is set to the optimal bit length, the
  84925. * array bl_count contains the frequencies for each bit length.
  84926. * The length opt_len is updated; static_len is also updated if stree is
  84927. * not null.
  84928. */
  84929. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  84930. {
  84931. ct_data *tree = desc->dyn_tree;
  84932. int max_code = desc->max_code;
  84933. const ct_data *stree = desc->stat_desc->static_tree;
  84934. const intf *extra = desc->stat_desc->extra_bits;
  84935. int base = desc->stat_desc->extra_base;
  84936. int max_length = desc->stat_desc->max_length;
  84937. int h; /* heap index */
  84938. int n, m; /* iterate over the tree elements */
  84939. int bits; /* bit length */
  84940. int xbits; /* extra bits */
  84941. ush f; /* frequency */
  84942. int overflow = 0; /* number of elements with bit length too large */
  84943. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  84944. /* In a first pass, compute the optimal bit lengths (which may
  84945. * overflow in the case of the bit length tree).
  84946. */
  84947. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  84948. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  84949. n = s->heap[h];
  84950. bits = tree[tree[n].Dad].Len + 1;
  84951. if (bits > max_length) bits = max_length, overflow++;
  84952. tree[n].Len = (ush)bits;
  84953. /* We overwrite tree[n].Dad which is no longer needed */
  84954. if (n > max_code) continue; /* not a leaf node */
  84955. s->bl_count[bits]++;
  84956. xbits = 0;
  84957. if (n >= base) xbits = extra[n-base];
  84958. f = tree[n].Freq;
  84959. s->opt_len += (ulg)f * (bits + xbits);
  84960. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  84961. }
  84962. if (overflow == 0) return;
  84963. Trace((stderr,"\nbit length overflow\n"));
  84964. /* This happens for example on obj2 and pic of the Calgary corpus */
  84965. /* Find the first bit length which could increase: */
  84966. do {
  84967. bits = max_length-1;
  84968. while (s->bl_count[bits] == 0) bits--;
  84969. s->bl_count[bits]--; /* move one leaf down the tree */
  84970. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  84971. s->bl_count[max_length]--;
  84972. /* The brother of the overflow item also moves one step up,
  84973. * but this does not affect bl_count[max_length]
  84974. */
  84975. overflow -= 2;
  84976. } while (overflow > 0);
  84977. /* Now recompute all bit lengths, scanning in increasing frequency.
  84978. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  84979. * lengths instead of fixing only the wrong ones. This idea is taken
  84980. * from 'ar' written by Haruhiko Okumura.)
  84981. */
  84982. for (bits = max_length; bits != 0; bits--) {
  84983. n = s->bl_count[bits];
  84984. while (n != 0) {
  84985. m = s->heap[--h];
  84986. if (m > max_code) continue;
  84987. if ((unsigned) tree[m].Len != (unsigned) bits) {
  84988. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  84989. s->opt_len += ((long)bits - (long)tree[m].Len)
  84990. *(long)tree[m].Freq;
  84991. tree[m].Len = (ush)bits;
  84992. }
  84993. n--;
  84994. }
  84995. }
  84996. }
  84997. /* ===========================================================================
  84998. * Generate the codes for a given tree and bit counts (which need not be
  84999. * optimal).
  85000. * IN assertion: the array bl_count contains the bit length statistics for
  85001. * the given tree and the field len is set for all tree elements.
  85002. * OUT assertion: the field code is set for all tree elements of non
  85003. * zero code length.
  85004. */
  85005. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85006. int max_code, /* largest code with non zero frequency */
  85007. ushf *bl_count) /* number of codes at each bit length */
  85008. {
  85009. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85010. ush code = 0; /* running code value */
  85011. int bits; /* bit index */
  85012. int n; /* code index */
  85013. /* The distribution counts are first used to generate the code values
  85014. * without bit reversal.
  85015. */
  85016. for (bits = 1; bits <= MAX_BITS; bits++) {
  85017. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85018. }
  85019. /* Check that the bit counts in bl_count are consistent. The last code
  85020. * must be all ones.
  85021. */
  85022. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85023. "inconsistent bit counts");
  85024. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85025. for (n = 0; n <= max_code; n++) {
  85026. int len = tree[n].Len;
  85027. if (len == 0) continue;
  85028. /* Now reverse the bits */
  85029. tree[n].Code = bi_reverse(next_code[len]++, len);
  85030. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85031. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85032. }
  85033. }
  85034. /* ===========================================================================
  85035. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85036. * Update the total bit length for the current block.
  85037. * IN assertion: the field freq is set for all tree elements.
  85038. * OUT assertions: the fields len and code are set to the optimal bit length
  85039. * and corresponding code. The length opt_len is updated; static_len is
  85040. * also updated if stree is not null. The field max_code is set.
  85041. */
  85042. local void build_tree (deflate_state *s,
  85043. tree_desc *desc) /* the tree descriptor */
  85044. {
  85045. ct_data *tree = desc->dyn_tree;
  85046. const ct_data *stree = desc->stat_desc->static_tree;
  85047. int elems = desc->stat_desc->elems;
  85048. int n, m; /* iterate over heap elements */
  85049. int max_code = -1; /* largest code with non zero frequency */
  85050. int node; /* new node being created */
  85051. /* Construct the initial heap, with least frequent element in
  85052. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85053. * heap[0] is not used.
  85054. */
  85055. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85056. for (n = 0; n < elems; n++) {
  85057. if (tree[n].Freq != 0) {
  85058. s->heap[++(s->heap_len)] = max_code = n;
  85059. s->depth[n] = 0;
  85060. } else {
  85061. tree[n].Len = 0;
  85062. }
  85063. }
  85064. /* The pkzip format requires that at least one distance code exists,
  85065. * and that at least one bit should be sent even if there is only one
  85066. * possible code. So to avoid special checks later on we force at least
  85067. * two codes of non zero frequency.
  85068. */
  85069. while (s->heap_len < 2) {
  85070. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85071. tree[node].Freq = 1;
  85072. s->depth[node] = 0;
  85073. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85074. /* node is 0 or 1 so it does not have extra bits */
  85075. }
  85076. desc->max_code = max_code;
  85077. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85078. * establish sub-heaps of increasing lengths:
  85079. */
  85080. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85081. /* Construct the Huffman tree by repeatedly combining the least two
  85082. * frequent nodes.
  85083. */
  85084. node = elems; /* next internal node of the tree */
  85085. do {
  85086. pqremove(s, tree, n); /* n = node of least frequency */
  85087. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85088. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85089. s->heap[--(s->heap_max)] = m;
  85090. /* Create a new node father of n and m */
  85091. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85092. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85093. s->depth[n] : s->depth[m]) + 1);
  85094. tree[n].Dad = tree[m].Dad = (ush)node;
  85095. #ifdef DUMP_BL_TREE
  85096. if (tree == s->bl_tree) {
  85097. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85098. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85099. }
  85100. #endif
  85101. /* and insert the new node in the heap */
  85102. s->heap[SMALLEST] = node++;
  85103. pqdownheap(s, tree, SMALLEST);
  85104. } while (s->heap_len >= 2);
  85105. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85106. /* At this point, the fields freq and dad are set. We can now
  85107. * generate the bit lengths.
  85108. */
  85109. gen_bitlen(s, (tree_desc *)desc);
  85110. /* The field len is now set, we can generate the bit codes */
  85111. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85112. }
  85113. /* ===========================================================================
  85114. * Scan a literal or distance tree to determine the frequencies of the codes
  85115. * in the bit length tree.
  85116. */
  85117. local void scan_tree (deflate_state *s,
  85118. ct_data *tree, /* the tree to be scanned */
  85119. int max_code) /* and its largest code of non zero frequency */
  85120. {
  85121. int n; /* iterates over all tree elements */
  85122. int prevlen = -1; /* last emitted length */
  85123. int curlen; /* length of current code */
  85124. int nextlen = tree[0].Len; /* length of next code */
  85125. int count = 0; /* repeat count of the current code */
  85126. int max_count = 7; /* max repeat count */
  85127. int min_count = 4; /* min repeat count */
  85128. if (nextlen == 0) max_count = 138, min_count = 3;
  85129. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85130. for (n = 0; n <= max_code; n++) {
  85131. curlen = nextlen; nextlen = tree[n+1].Len;
  85132. if (++count < max_count && curlen == nextlen) {
  85133. continue;
  85134. } else if (count < min_count) {
  85135. s->bl_tree[curlen].Freq += count;
  85136. } else if (curlen != 0) {
  85137. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85138. s->bl_tree[REP_3_6].Freq++;
  85139. } else if (count <= 10) {
  85140. s->bl_tree[REPZ_3_10].Freq++;
  85141. } else {
  85142. s->bl_tree[REPZ_11_138].Freq++;
  85143. }
  85144. count = 0; prevlen = curlen;
  85145. if (nextlen == 0) {
  85146. max_count = 138, min_count = 3;
  85147. } else if (curlen == nextlen) {
  85148. max_count = 6, min_count = 3;
  85149. } else {
  85150. max_count = 7, min_count = 4;
  85151. }
  85152. }
  85153. }
  85154. /* ===========================================================================
  85155. * Send a literal or distance tree in compressed form, using the codes in
  85156. * bl_tree.
  85157. */
  85158. local void send_tree (deflate_state *s,
  85159. ct_data *tree, /* the tree to be scanned */
  85160. int max_code) /* and its largest code of non zero frequency */
  85161. {
  85162. int n; /* iterates over all tree elements */
  85163. int prevlen = -1; /* last emitted length */
  85164. int curlen; /* length of current code */
  85165. int nextlen = tree[0].Len; /* length of next code */
  85166. int count = 0; /* repeat count of the current code */
  85167. int max_count = 7; /* max repeat count */
  85168. int min_count = 4; /* min repeat count */
  85169. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85170. if (nextlen == 0) max_count = 138, min_count = 3;
  85171. for (n = 0; n <= max_code; n++) {
  85172. curlen = nextlen; nextlen = tree[n+1].Len;
  85173. if (++count < max_count && curlen == nextlen) {
  85174. continue;
  85175. } else if (count < min_count) {
  85176. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85177. } else if (curlen != 0) {
  85178. if (curlen != prevlen) {
  85179. send_code(s, curlen, s->bl_tree); count--;
  85180. }
  85181. Assert(count >= 3 && count <= 6, " 3_6?");
  85182. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85183. } else if (count <= 10) {
  85184. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85185. } else {
  85186. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85187. }
  85188. count = 0; prevlen = curlen;
  85189. if (nextlen == 0) {
  85190. max_count = 138, min_count = 3;
  85191. } else if (curlen == nextlen) {
  85192. max_count = 6, min_count = 3;
  85193. } else {
  85194. max_count = 7, min_count = 4;
  85195. }
  85196. }
  85197. }
  85198. /* ===========================================================================
  85199. * Construct the Huffman tree for the bit lengths and return the index in
  85200. * bl_order of the last bit length code to send.
  85201. */
  85202. local int build_bl_tree (deflate_state *s)
  85203. {
  85204. int max_blindex; /* index of last bit length code of non zero freq */
  85205. /* Determine the bit length frequencies for literal and distance trees */
  85206. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85207. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85208. /* Build the bit length tree: */
  85209. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85210. /* opt_len now includes the length of the tree representations, except
  85211. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85212. */
  85213. /* Determine the number of bit length codes to send. The pkzip format
  85214. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85215. * 3 but the actual value used is 4.)
  85216. */
  85217. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85218. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85219. }
  85220. /* Update opt_len to include the bit length tree and counts */
  85221. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85222. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85223. s->opt_len, s->static_len));
  85224. return max_blindex;
  85225. }
  85226. /* ===========================================================================
  85227. * Send the header for a block using dynamic Huffman trees: the counts, the
  85228. * lengths of the bit length codes, the literal tree and the distance tree.
  85229. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85230. */
  85231. local void send_all_trees (deflate_state *s,
  85232. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85233. {
  85234. int rank; /* index in bl_order */
  85235. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85236. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85237. "too many codes");
  85238. Tracev((stderr, "\nbl counts: "));
  85239. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85240. send_bits(s, dcodes-1, 5);
  85241. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85242. for (rank = 0; rank < blcodes; rank++) {
  85243. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85244. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85245. }
  85246. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85247. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85248. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85249. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85250. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85251. }
  85252. /* ===========================================================================
  85253. * Send a stored block
  85254. */
  85255. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85256. {
  85257. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85258. #ifdef DEBUG
  85259. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85260. s->compressed_len += (stored_len + 4) << 3;
  85261. #endif
  85262. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85263. }
  85264. /* ===========================================================================
  85265. * Send one empty static block to give enough lookahead for inflate.
  85266. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85267. * The current inflate code requires 9 bits of lookahead. If the
  85268. * last two codes for the previous block (real code plus EOB) were coded
  85269. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85270. * the last real code. In this case we send two empty static blocks instead
  85271. * of one. (There are no problems if the previous block is stored or fixed.)
  85272. * To simplify the code, we assume the worst case of last real code encoded
  85273. * on one bit only.
  85274. */
  85275. void _tr_align (deflate_state *s)
  85276. {
  85277. send_bits(s, STATIC_TREES<<1, 3);
  85278. send_code(s, END_BLOCK, static_ltree);
  85279. #ifdef DEBUG
  85280. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85281. #endif
  85282. bi_flush(s);
  85283. /* Of the 10 bits for the empty block, we have already sent
  85284. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85285. * the EOB of the previous block) was thus at least one plus the length
  85286. * of the EOB plus what we have just sent of the empty static block.
  85287. */
  85288. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85289. send_bits(s, STATIC_TREES<<1, 3);
  85290. send_code(s, END_BLOCK, static_ltree);
  85291. #ifdef DEBUG
  85292. s->compressed_len += 10L;
  85293. #endif
  85294. bi_flush(s);
  85295. }
  85296. s->last_eob_len = 7;
  85297. }
  85298. /* ===========================================================================
  85299. * Determine the best encoding for the current block: dynamic trees, static
  85300. * trees or store, and output the encoded block to the zip file.
  85301. */
  85302. void _tr_flush_block (deflate_state *s,
  85303. charf *buf, /* input block, or NULL if too old */
  85304. ulg stored_len, /* length of input block */
  85305. int eof) /* true if this is the last block for a file */
  85306. {
  85307. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85308. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85309. /* Build the Huffman trees unless a stored block is forced */
  85310. if (s->level > 0) {
  85311. /* Check if the file is binary or text */
  85312. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85313. set_data_type(s);
  85314. /* Construct the literal and distance trees */
  85315. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85316. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85317. s->static_len));
  85318. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85319. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85320. s->static_len));
  85321. /* At this point, opt_len and static_len are the total bit lengths of
  85322. * the compressed block data, excluding the tree representations.
  85323. */
  85324. /* Build the bit length tree for the above two trees, and get the index
  85325. * in bl_order of the last bit length code to send.
  85326. */
  85327. max_blindex = build_bl_tree(s);
  85328. /* Determine the best encoding. Compute the block lengths in bytes. */
  85329. opt_lenb = (s->opt_len+3+7)>>3;
  85330. static_lenb = (s->static_len+3+7)>>3;
  85331. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85332. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85333. s->last_lit));
  85334. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85335. } else {
  85336. Assert(buf != (char*)0, "lost buf");
  85337. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85338. }
  85339. #ifdef FORCE_STORED
  85340. if (buf != (char*)0) { /* force stored block */
  85341. #else
  85342. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85343. /* 4: two words for the lengths */
  85344. #endif
  85345. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85346. * Otherwise we can't have processed more than WSIZE input bytes since
  85347. * the last block flush, because compression would have been
  85348. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85349. * transform a block into a stored block.
  85350. */
  85351. _tr_stored_block(s, buf, stored_len, eof);
  85352. #ifdef FORCE_STATIC
  85353. } else if (static_lenb >= 0) { /* force static trees */
  85354. #else
  85355. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85356. #endif
  85357. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85358. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85359. #ifdef DEBUG
  85360. s->compressed_len += 3 + s->static_len;
  85361. #endif
  85362. } else {
  85363. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85364. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85365. max_blindex+1);
  85366. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85367. #ifdef DEBUG
  85368. s->compressed_len += 3 + s->opt_len;
  85369. #endif
  85370. }
  85371. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85372. /* The above check is made mod 2^32, for files larger than 512 MB
  85373. * and uLong implemented on 32 bits.
  85374. */
  85375. init_block(s);
  85376. if (eof) {
  85377. bi_windup(s);
  85378. #ifdef DEBUG
  85379. s->compressed_len += 7; /* align on byte boundary */
  85380. #endif
  85381. }
  85382. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85383. s->compressed_len-7*eof));
  85384. }
  85385. /* ===========================================================================
  85386. * Save the match info and tally the frequency counts. Return true if
  85387. * the current block must be flushed.
  85388. */
  85389. int _tr_tally (deflate_state *s,
  85390. unsigned dist, /* distance of matched string */
  85391. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85392. {
  85393. s->d_buf[s->last_lit] = (ush)dist;
  85394. s->l_buf[s->last_lit++] = (uch)lc;
  85395. if (dist == 0) {
  85396. /* lc is the unmatched char */
  85397. s->dyn_ltree[lc].Freq++;
  85398. } else {
  85399. s->matches++;
  85400. /* Here, lc is the match length - MIN_MATCH */
  85401. dist--; /* dist = match distance - 1 */
  85402. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85403. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85404. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85405. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85406. s->dyn_dtree[d_code(dist)].Freq++;
  85407. }
  85408. #ifdef TRUNCATE_BLOCK
  85409. /* Try to guess if it is profitable to stop the current block here */
  85410. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85411. /* Compute an upper bound for the compressed length */
  85412. ulg out_length = (ulg)s->last_lit*8L;
  85413. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85414. int dcode;
  85415. for (dcode = 0; dcode < D_CODES; dcode++) {
  85416. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85417. (5L+extra_dbits[dcode]);
  85418. }
  85419. out_length >>= 3;
  85420. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85421. s->last_lit, in_length, out_length,
  85422. 100L - out_length*100L/in_length));
  85423. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85424. }
  85425. #endif
  85426. return (s->last_lit == s->lit_bufsize-1);
  85427. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85428. * on 16 bit machines and because stored blocks are restricted to
  85429. * 64K-1 bytes.
  85430. */
  85431. }
  85432. /* ===========================================================================
  85433. * Send the block data compressed using the given Huffman trees
  85434. */
  85435. local void compress_block (deflate_state *s,
  85436. ct_data *ltree, /* literal tree */
  85437. ct_data *dtree) /* distance tree */
  85438. {
  85439. unsigned dist; /* distance of matched string */
  85440. int lc; /* match length or unmatched char (if dist == 0) */
  85441. unsigned lx = 0; /* running index in l_buf */
  85442. unsigned code; /* the code to send */
  85443. int extra; /* number of extra bits to send */
  85444. if (s->last_lit != 0) do {
  85445. dist = s->d_buf[lx];
  85446. lc = s->l_buf[lx++];
  85447. if (dist == 0) {
  85448. send_code(s, lc, ltree); /* send a literal byte */
  85449. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85450. } else {
  85451. /* Here, lc is the match length - MIN_MATCH */
  85452. code = _length_code[lc];
  85453. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85454. extra = extra_lbits[code];
  85455. if (extra != 0) {
  85456. lc -= base_length[code];
  85457. send_bits(s, lc, extra); /* send the extra length bits */
  85458. }
  85459. dist--; /* dist is now the match distance - 1 */
  85460. code = d_code(dist);
  85461. Assert (code < D_CODES, "bad d_code");
  85462. send_code(s, code, dtree); /* send the distance code */
  85463. extra = extra_dbits[code];
  85464. if (extra != 0) {
  85465. dist -= base_dist[code];
  85466. send_bits(s, dist, extra); /* send the extra distance bits */
  85467. }
  85468. } /* literal or match pair ? */
  85469. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85470. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85471. "pendingBuf overflow");
  85472. } while (lx < s->last_lit);
  85473. send_code(s, END_BLOCK, ltree);
  85474. s->last_eob_len = ltree[END_BLOCK].Len;
  85475. }
  85476. /* ===========================================================================
  85477. * Set the data type to BINARY or TEXT, using a crude approximation:
  85478. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85479. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85480. * IN assertion: the fields Freq of dyn_ltree are set.
  85481. */
  85482. local void set_data_type (deflate_state *s)
  85483. {
  85484. int n;
  85485. for (n = 0; n < 9; n++)
  85486. if (s->dyn_ltree[n].Freq != 0)
  85487. break;
  85488. if (n == 9)
  85489. for (n = 14; n < 32; n++)
  85490. if (s->dyn_ltree[n].Freq != 0)
  85491. break;
  85492. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85493. }
  85494. /* ===========================================================================
  85495. * Reverse the first len bits of a code, using straightforward code (a faster
  85496. * method would use a table)
  85497. * IN assertion: 1 <= len <= 15
  85498. */
  85499. local unsigned bi_reverse (unsigned code, int len)
  85500. {
  85501. register unsigned res = 0;
  85502. do {
  85503. res |= code & 1;
  85504. code >>= 1, res <<= 1;
  85505. } while (--len > 0);
  85506. return res >> 1;
  85507. }
  85508. /* ===========================================================================
  85509. * Flush the bit buffer, keeping at most 7 bits in it.
  85510. */
  85511. local void bi_flush (deflate_state *s)
  85512. {
  85513. if (s->bi_valid == 16) {
  85514. put_short(s, s->bi_buf);
  85515. s->bi_buf = 0;
  85516. s->bi_valid = 0;
  85517. } else if (s->bi_valid >= 8) {
  85518. put_byte(s, (Byte)s->bi_buf);
  85519. s->bi_buf >>= 8;
  85520. s->bi_valid -= 8;
  85521. }
  85522. }
  85523. /* ===========================================================================
  85524. * Flush the bit buffer and align the output on a byte boundary
  85525. */
  85526. local void bi_windup (deflate_state *s)
  85527. {
  85528. if (s->bi_valid > 8) {
  85529. put_short(s, s->bi_buf);
  85530. } else if (s->bi_valid > 0) {
  85531. put_byte(s, (Byte)s->bi_buf);
  85532. }
  85533. s->bi_buf = 0;
  85534. s->bi_valid = 0;
  85535. #ifdef DEBUG
  85536. s->bits_sent = (s->bits_sent+7) & ~7;
  85537. #endif
  85538. }
  85539. /* ===========================================================================
  85540. * Copy a stored block, storing first the length and its
  85541. * one's complement if requested.
  85542. */
  85543. local void copy_block(deflate_state *s,
  85544. charf *buf, /* the input data */
  85545. unsigned len, /* its length */
  85546. int header) /* true if block header must be written */
  85547. {
  85548. bi_windup(s); /* align on byte boundary */
  85549. s->last_eob_len = 8; /* enough lookahead for inflate */
  85550. if (header) {
  85551. put_short(s, (ush)len);
  85552. put_short(s, (ush)~len);
  85553. #ifdef DEBUG
  85554. s->bits_sent += 2*16;
  85555. #endif
  85556. }
  85557. #ifdef DEBUG
  85558. s->bits_sent += (ulg)len<<3;
  85559. #endif
  85560. while (len--) {
  85561. put_byte(s, *buf++);
  85562. }
  85563. }
  85564. /*** End of inlined file: trees.c ***/
  85565. /*** Start of inlined file: zutil.c ***/
  85566. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85567. #ifndef NO_DUMMY_DECL
  85568. struct internal_state {int dummy;}; /* for buggy compilers */
  85569. #endif
  85570. const char * const z_errmsg[10] = {
  85571. "need dictionary", /* Z_NEED_DICT 2 */
  85572. "stream end", /* Z_STREAM_END 1 */
  85573. "", /* Z_OK 0 */
  85574. "file error", /* Z_ERRNO (-1) */
  85575. "stream error", /* Z_STREAM_ERROR (-2) */
  85576. "data error", /* Z_DATA_ERROR (-3) */
  85577. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85578. "buffer error", /* Z_BUF_ERROR (-5) */
  85579. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85580. ""};
  85581. /*const char * ZEXPORT zlibVersion()
  85582. {
  85583. return ZLIB_VERSION;
  85584. }
  85585. uLong ZEXPORT zlibCompileFlags()
  85586. {
  85587. uLong flags;
  85588. flags = 0;
  85589. switch (sizeof(uInt)) {
  85590. case 2: break;
  85591. case 4: flags += 1; break;
  85592. case 8: flags += 2; break;
  85593. default: flags += 3;
  85594. }
  85595. switch (sizeof(uLong)) {
  85596. case 2: break;
  85597. case 4: flags += 1 << 2; break;
  85598. case 8: flags += 2 << 2; break;
  85599. default: flags += 3 << 2;
  85600. }
  85601. switch (sizeof(voidpf)) {
  85602. case 2: break;
  85603. case 4: flags += 1 << 4; break;
  85604. case 8: flags += 2 << 4; break;
  85605. default: flags += 3 << 4;
  85606. }
  85607. switch (sizeof(z_off_t)) {
  85608. case 2: break;
  85609. case 4: flags += 1 << 6; break;
  85610. case 8: flags += 2 << 6; break;
  85611. default: flags += 3 << 6;
  85612. }
  85613. #ifdef DEBUG
  85614. flags += 1 << 8;
  85615. #endif
  85616. #if defined(ASMV) || defined(ASMINF)
  85617. flags += 1 << 9;
  85618. #endif
  85619. #ifdef ZLIB_WINAPI
  85620. flags += 1 << 10;
  85621. #endif
  85622. #ifdef BUILDFIXED
  85623. flags += 1 << 12;
  85624. #endif
  85625. #ifdef DYNAMIC_CRC_TABLE
  85626. flags += 1 << 13;
  85627. #endif
  85628. #ifdef NO_GZCOMPRESS
  85629. flags += 1L << 16;
  85630. #endif
  85631. #ifdef NO_GZIP
  85632. flags += 1L << 17;
  85633. #endif
  85634. #ifdef PKZIP_BUG_WORKAROUND
  85635. flags += 1L << 20;
  85636. #endif
  85637. #ifdef FASTEST
  85638. flags += 1L << 21;
  85639. #endif
  85640. #ifdef STDC
  85641. # ifdef NO_vsnprintf
  85642. flags += 1L << 25;
  85643. # ifdef HAS_vsprintf_void
  85644. flags += 1L << 26;
  85645. # endif
  85646. # else
  85647. # ifdef HAS_vsnprintf_void
  85648. flags += 1L << 26;
  85649. # endif
  85650. # endif
  85651. #else
  85652. flags += 1L << 24;
  85653. # ifdef NO_snprintf
  85654. flags += 1L << 25;
  85655. # ifdef HAS_sprintf_void
  85656. flags += 1L << 26;
  85657. # endif
  85658. # else
  85659. # ifdef HAS_snprintf_void
  85660. flags += 1L << 26;
  85661. # endif
  85662. # endif
  85663. #endif
  85664. return flags;
  85665. }*/
  85666. #ifdef DEBUG
  85667. # ifndef verbose
  85668. # define verbose 0
  85669. # endif
  85670. int z_verbose = verbose;
  85671. void z_error (const char *m)
  85672. {
  85673. fprintf(stderr, "%s\n", m);
  85674. exit(1);
  85675. }
  85676. #endif
  85677. /* exported to allow conversion of error code to string for compress() and
  85678. * uncompress()
  85679. */
  85680. const char * ZEXPORT zError(int err)
  85681. {
  85682. return ERR_MSG(err);
  85683. }
  85684. #if defined(_WIN32_WCE)
  85685. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  85686. * errno. We define it as a global variable to simplify porting.
  85687. * Its value is always 0 and should not be used.
  85688. */
  85689. int errno = 0;
  85690. #endif
  85691. #ifndef HAVE_MEMCPY
  85692. void zmemcpy(dest, source, len)
  85693. Bytef* dest;
  85694. const Bytef* source;
  85695. uInt len;
  85696. {
  85697. if (len == 0) return;
  85698. do {
  85699. *dest++ = *source++; /* ??? to be unrolled */
  85700. } while (--len != 0);
  85701. }
  85702. int zmemcmp(s1, s2, len)
  85703. const Bytef* s1;
  85704. const Bytef* s2;
  85705. uInt len;
  85706. {
  85707. uInt j;
  85708. for (j = 0; j < len; j++) {
  85709. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  85710. }
  85711. return 0;
  85712. }
  85713. void zmemzero(dest, len)
  85714. Bytef* dest;
  85715. uInt len;
  85716. {
  85717. if (len == 0) return;
  85718. do {
  85719. *dest++ = 0; /* ??? to be unrolled */
  85720. } while (--len != 0);
  85721. }
  85722. #endif
  85723. #ifdef SYS16BIT
  85724. #ifdef __TURBOC__
  85725. /* Turbo C in 16-bit mode */
  85726. # define MY_ZCALLOC
  85727. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  85728. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  85729. * must fix the pointer. Warning: the pointer must be put back to its
  85730. * original form in order to free it, use zcfree().
  85731. */
  85732. #define MAX_PTR 10
  85733. /* 10*64K = 640K */
  85734. local int next_ptr = 0;
  85735. typedef struct ptr_table_s {
  85736. voidpf org_ptr;
  85737. voidpf new_ptr;
  85738. } ptr_table;
  85739. local ptr_table table[MAX_PTR];
  85740. /* This table is used to remember the original form of pointers
  85741. * to large buffers (64K). Such pointers are normalized with a zero offset.
  85742. * Since MSDOS is not a preemptive multitasking OS, this table is not
  85743. * protected from concurrent access. This hack doesn't work anyway on
  85744. * a protected system like OS/2. Use Microsoft C instead.
  85745. */
  85746. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85747. {
  85748. voidpf buf = opaque; /* just to make some compilers happy */
  85749. ulg bsize = (ulg)items*size;
  85750. /* If we allocate less than 65520 bytes, we assume that farmalloc
  85751. * will return a usable pointer which doesn't have to be normalized.
  85752. */
  85753. if (bsize < 65520L) {
  85754. buf = farmalloc(bsize);
  85755. if (*(ush*)&buf != 0) return buf;
  85756. } else {
  85757. buf = farmalloc(bsize + 16L);
  85758. }
  85759. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  85760. table[next_ptr].org_ptr = buf;
  85761. /* Normalize the pointer to seg:0 */
  85762. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  85763. *(ush*)&buf = 0;
  85764. table[next_ptr++].new_ptr = buf;
  85765. return buf;
  85766. }
  85767. void zcfree (voidpf opaque, voidpf ptr)
  85768. {
  85769. int n;
  85770. if (*(ush*)&ptr != 0) { /* object < 64K */
  85771. farfree(ptr);
  85772. return;
  85773. }
  85774. /* Find the original pointer */
  85775. for (n = 0; n < next_ptr; n++) {
  85776. if (ptr != table[n].new_ptr) continue;
  85777. farfree(table[n].org_ptr);
  85778. while (++n < next_ptr) {
  85779. table[n-1] = table[n];
  85780. }
  85781. next_ptr--;
  85782. return;
  85783. }
  85784. ptr = opaque; /* just to make some compilers happy */
  85785. Assert(0, "zcfree: ptr not found");
  85786. }
  85787. #endif /* __TURBOC__ */
  85788. #ifdef M_I86
  85789. /* Microsoft C in 16-bit mode */
  85790. # define MY_ZCALLOC
  85791. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  85792. # define _halloc halloc
  85793. # define _hfree hfree
  85794. #endif
  85795. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85796. {
  85797. if (opaque) opaque = 0; /* to make compiler happy */
  85798. return _halloc((long)items, size);
  85799. }
  85800. void zcfree (voidpf opaque, voidpf ptr)
  85801. {
  85802. if (opaque) opaque = 0; /* to make compiler happy */
  85803. _hfree(ptr);
  85804. }
  85805. #endif /* M_I86 */
  85806. #endif /* SYS16BIT */
  85807. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  85808. #ifndef STDC
  85809. extern voidp malloc OF((uInt size));
  85810. extern voidp calloc OF((uInt items, uInt size));
  85811. extern void free OF((voidpf ptr));
  85812. #endif
  85813. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  85814. {
  85815. if (opaque) items += size - size; /* make compiler happy */
  85816. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  85817. (voidpf)calloc(items, size);
  85818. }
  85819. void zcfree (voidpf opaque, voidpf ptr)
  85820. {
  85821. free(ptr);
  85822. if (opaque) return; /* make compiler happy */
  85823. }
  85824. #endif /* MY_ZCALLOC */
  85825. /*** End of inlined file: zutil.c ***/
  85826. #undef Byte
  85827. #else
  85828. #include <zlib.h>
  85829. #endif
  85830. }
  85831. #if JUCE_MSVC
  85832. #pragma warning (pop)
  85833. #endif
  85834. BEGIN_JUCE_NAMESPACE
  85835. // internal helper object that holds the zlib structures so they don't have to be
  85836. // included publicly.
  85837. class GZIPDecompressorInputStream::GZIPDecompressHelper
  85838. {
  85839. public:
  85840. GZIPDecompressHelper (const bool noWrap)
  85841. : finished (true),
  85842. needsDictionary (false),
  85843. error (true),
  85844. streamIsValid (false),
  85845. data (0),
  85846. dataSize (0)
  85847. {
  85848. using namespace zlibNamespace;
  85849. zerostruct (stream);
  85850. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  85851. finished = error = ! streamIsValid;
  85852. }
  85853. ~GZIPDecompressHelper()
  85854. {
  85855. using namespace zlibNamespace;
  85856. if (streamIsValid)
  85857. inflateEnd (&stream);
  85858. }
  85859. bool needsInput() const throw() { return dataSize <= 0; }
  85860. void setInput (uint8* const data_, const int size) throw()
  85861. {
  85862. data = data_;
  85863. dataSize = size;
  85864. }
  85865. int doNextBlock (uint8* const dest, const int destSize)
  85866. {
  85867. using namespace zlibNamespace;
  85868. if (streamIsValid && data != 0 && ! finished)
  85869. {
  85870. stream.next_in = data;
  85871. stream.next_out = dest;
  85872. stream.avail_in = dataSize;
  85873. stream.avail_out = destSize;
  85874. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  85875. {
  85876. case Z_STREAM_END:
  85877. finished = true;
  85878. // deliberate fall-through
  85879. case Z_OK:
  85880. data += dataSize - stream.avail_in;
  85881. dataSize = stream.avail_in;
  85882. return destSize - stream.avail_out;
  85883. case Z_NEED_DICT:
  85884. needsDictionary = true;
  85885. data += dataSize - stream.avail_in;
  85886. dataSize = stream.avail_in;
  85887. break;
  85888. case Z_DATA_ERROR:
  85889. case Z_MEM_ERROR:
  85890. error = true;
  85891. default:
  85892. break;
  85893. }
  85894. }
  85895. return 0;
  85896. }
  85897. bool finished, needsDictionary, error, streamIsValid;
  85898. enum { gzipDecompBufferSize = 32768 };
  85899. private:
  85900. zlibNamespace::z_stream stream;
  85901. uint8* data;
  85902. int dataSize;
  85903. JUCE_DECLARE_NON_COPYABLE (GZIPDecompressHelper);
  85904. };
  85905. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  85906. const bool deleteSourceWhenDestroyed,
  85907. const bool noWrap_,
  85908. const int64 uncompressedStreamLength_)
  85909. : sourceStream (sourceStream_),
  85910. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  85911. uncompressedStreamLength (uncompressedStreamLength_),
  85912. noWrap (noWrap_),
  85913. isEof (false),
  85914. activeBufferSize (0),
  85915. originalSourcePos (sourceStream_->getPosition()),
  85916. currentPos (0),
  85917. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85918. helper (new GZIPDecompressHelper (noWrap_))
  85919. {
  85920. }
  85921. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  85922. : sourceStream (&sourceStream_),
  85923. uncompressedStreamLength (-1),
  85924. noWrap (false),
  85925. isEof (false),
  85926. activeBufferSize (0),
  85927. originalSourcePos (sourceStream_.getPosition()),
  85928. currentPos (0),
  85929. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  85930. helper (new GZIPDecompressHelper (false))
  85931. {
  85932. }
  85933. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  85934. {
  85935. }
  85936. int64 GZIPDecompressorInputStream::getTotalLength()
  85937. {
  85938. return uncompressedStreamLength;
  85939. }
  85940. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  85941. {
  85942. if ((howMany > 0) && ! isEof)
  85943. {
  85944. jassert (destBuffer != 0);
  85945. if (destBuffer != 0)
  85946. {
  85947. int numRead = 0;
  85948. uint8* d = static_cast <uint8*> (destBuffer);
  85949. while (! helper->error)
  85950. {
  85951. const int n = helper->doNextBlock (d, howMany);
  85952. currentPos += n;
  85953. if (n == 0)
  85954. {
  85955. if (helper->finished || helper->needsDictionary)
  85956. {
  85957. isEof = true;
  85958. return numRead;
  85959. }
  85960. if (helper->needsInput())
  85961. {
  85962. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  85963. if (activeBufferSize > 0)
  85964. {
  85965. helper->setInput (buffer, activeBufferSize);
  85966. }
  85967. else
  85968. {
  85969. isEof = true;
  85970. return numRead;
  85971. }
  85972. }
  85973. }
  85974. else
  85975. {
  85976. numRead += n;
  85977. howMany -= n;
  85978. d += n;
  85979. if (howMany <= 0)
  85980. return numRead;
  85981. }
  85982. }
  85983. }
  85984. }
  85985. return 0;
  85986. }
  85987. bool GZIPDecompressorInputStream::isExhausted()
  85988. {
  85989. return helper->error || isEof;
  85990. }
  85991. int64 GZIPDecompressorInputStream::getPosition()
  85992. {
  85993. return currentPos;
  85994. }
  85995. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  85996. {
  85997. if (newPos < currentPos)
  85998. {
  85999. // to go backwards, reset the stream and start again..
  86000. isEof = false;
  86001. activeBufferSize = 0;
  86002. currentPos = 0;
  86003. helper = new GZIPDecompressHelper (noWrap);
  86004. sourceStream->setPosition (originalSourcePos);
  86005. }
  86006. skipNextBytes (newPos - currentPos);
  86007. return true;
  86008. }
  86009. END_JUCE_NAMESPACE
  86010. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86011. #endif
  86012. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86013. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86014. #if JUCE_USE_FLAC
  86015. #if JUCE_WINDOWS
  86016. #include <windows.h>
  86017. #endif
  86018. namespace FlacNamespace
  86019. {
  86020. #if JUCE_INCLUDE_FLAC_CODE
  86021. #if JUCE_MSVC
  86022. #pragma warning (disable: 4505 181 111)
  86023. #endif
  86024. #define FLAC__NO_DLL 1
  86025. #if ! defined (SIZE_MAX)
  86026. #define SIZE_MAX 0xffffffff
  86027. #endif
  86028. #define __STDC_LIMIT_MACROS 1
  86029. /*** Start of inlined file: all.h ***/
  86030. #ifndef FLAC__ALL_H
  86031. #define FLAC__ALL_H
  86032. /*** Start of inlined file: export.h ***/
  86033. #ifndef FLAC__EXPORT_H
  86034. #define FLAC__EXPORT_H
  86035. /** \file include/FLAC/export.h
  86036. *
  86037. * \brief
  86038. * This module contains #defines and symbols for exporting function
  86039. * calls, and providing version information and compiled-in features.
  86040. *
  86041. * See the \link flac_export export \endlink module.
  86042. */
  86043. /** \defgroup flac_export FLAC/export.h: export symbols
  86044. * \ingroup flac
  86045. *
  86046. * \brief
  86047. * This module contains #defines and symbols for exporting function
  86048. * calls, and providing version information and compiled-in features.
  86049. *
  86050. * If you are compiling with MSVC and will link to the static library
  86051. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86052. * make sure the symbols are exported properly.
  86053. *
  86054. * \{
  86055. */
  86056. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86057. #define FLAC_API
  86058. #else
  86059. #ifdef FLAC_API_EXPORTS
  86060. #define FLAC_API _declspec(dllexport)
  86061. #else
  86062. #define FLAC_API _declspec(dllimport)
  86063. #endif
  86064. #endif
  86065. /** These #defines will mirror the libtool-based library version number, see
  86066. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86067. */
  86068. #define FLAC_API_VERSION_CURRENT 10
  86069. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86070. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86071. #ifdef __cplusplus
  86072. extern "C" {
  86073. #endif
  86074. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86075. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86076. #ifdef __cplusplus
  86077. }
  86078. #endif
  86079. /* \} */
  86080. #endif
  86081. /*** End of inlined file: export.h ***/
  86082. /*** Start of inlined file: assert.h ***/
  86083. #ifndef FLAC__ASSERT_H
  86084. #define FLAC__ASSERT_H
  86085. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86086. #ifdef DEBUG
  86087. #include <assert.h>
  86088. #define FLAC__ASSERT(x) assert(x)
  86089. #define FLAC__ASSERT_DECLARATION(x) x
  86090. #else
  86091. #define FLAC__ASSERT(x)
  86092. #define FLAC__ASSERT_DECLARATION(x)
  86093. #endif
  86094. #endif
  86095. /*** End of inlined file: assert.h ***/
  86096. /*** Start of inlined file: callback.h ***/
  86097. #ifndef FLAC__CALLBACK_H
  86098. #define FLAC__CALLBACK_H
  86099. /*** Start of inlined file: ordinals.h ***/
  86100. #ifndef FLAC__ORDINALS_H
  86101. #define FLAC__ORDINALS_H
  86102. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86103. #include <inttypes.h>
  86104. #endif
  86105. typedef signed char FLAC__int8;
  86106. typedef unsigned char FLAC__uint8;
  86107. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86108. typedef __int16 FLAC__int16;
  86109. typedef __int32 FLAC__int32;
  86110. typedef __int64 FLAC__int64;
  86111. typedef unsigned __int16 FLAC__uint16;
  86112. typedef unsigned __int32 FLAC__uint32;
  86113. typedef unsigned __int64 FLAC__uint64;
  86114. #elif defined(__EMX__)
  86115. typedef short FLAC__int16;
  86116. typedef long FLAC__int32;
  86117. typedef long long FLAC__int64;
  86118. typedef unsigned short FLAC__uint16;
  86119. typedef unsigned long FLAC__uint32;
  86120. typedef unsigned long long FLAC__uint64;
  86121. #else
  86122. typedef int16_t FLAC__int16;
  86123. typedef int32_t FLAC__int32;
  86124. typedef int64_t FLAC__int64;
  86125. typedef uint16_t FLAC__uint16;
  86126. typedef uint32_t FLAC__uint32;
  86127. typedef uint64_t FLAC__uint64;
  86128. #endif
  86129. typedef int FLAC__bool;
  86130. typedef FLAC__uint8 FLAC__byte;
  86131. #ifdef true
  86132. #undef true
  86133. #endif
  86134. #ifdef false
  86135. #undef false
  86136. #endif
  86137. #ifndef __cplusplus
  86138. #define true 1
  86139. #define false 0
  86140. #endif
  86141. #endif
  86142. /*** End of inlined file: ordinals.h ***/
  86143. #include <stdlib.h> /* for size_t */
  86144. /** \file include/FLAC/callback.h
  86145. *
  86146. * \brief
  86147. * This module defines the structures for describing I/O callbacks
  86148. * to the other FLAC interfaces.
  86149. *
  86150. * See the detailed documentation for callbacks in the
  86151. * \link flac_callbacks callbacks \endlink module.
  86152. */
  86153. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86154. * \ingroup flac
  86155. *
  86156. * \brief
  86157. * This module defines the structures for describing I/O callbacks
  86158. * to the other FLAC interfaces.
  86159. *
  86160. * The purpose of the I/O callback functions is to create a common way
  86161. * for the metadata interfaces to handle I/O.
  86162. *
  86163. * Originally the metadata interfaces required filenames as the way of
  86164. * specifying FLAC files to operate on. This is problematic in some
  86165. * environments so there is an additional option to specify a set of
  86166. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86167. *
  86168. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86169. * opaque structure for a data source.
  86170. *
  86171. * The callback function prototypes are similar (but not identical) to the
  86172. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86173. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86174. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86175. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86176. * is required. \warning You generally CANNOT directly use fseek or ftell
  86177. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86178. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86179. * large files. You will have to find an equivalent function (e.g. ftello),
  86180. * or write a wrapper. The same is true for feof() since this is usually
  86181. * implemented as a macro, not as a function whose address can be taken.
  86182. *
  86183. * \{
  86184. */
  86185. #ifdef __cplusplus
  86186. extern "C" {
  86187. #endif
  86188. /** This is the opaque handle type used by the callbacks. Typically
  86189. * this is a \c FILE* or address of a file descriptor.
  86190. */
  86191. typedef void* FLAC__IOHandle;
  86192. /** Signature for the read callback.
  86193. * The signature and semantics match POSIX fread() implementations
  86194. * and can generally be used interchangeably.
  86195. *
  86196. * \param ptr The address of the read buffer.
  86197. * \param size The size of the records to be read.
  86198. * \param nmemb The number of records to be read.
  86199. * \param handle The handle to the data source.
  86200. * \retval size_t
  86201. * The number of records read.
  86202. */
  86203. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86204. /** Signature for the write callback.
  86205. * The signature and semantics match POSIX fwrite() implementations
  86206. * and can generally be used interchangeably.
  86207. *
  86208. * \param ptr The address of the write buffer.
  86209. * \param size The size of the records to be written.
  86210. * \param nmemb The number of records to be written.
  86211. * \param handle The handle to the data source.
  86212. * \retval size_t
  86213. * The number of records written.
  86214. */
  86215. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86216. /** Signature for the seek callback.
  86217. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86218. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86219. * and 32-bits wide.
  86220. *
  86221. * \param handle The handle to the data source.
  86222. * \param offset The new position, relative to \a whence
  86223. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86224. * \retval int
  86225. * \c 0 on success, \c -1 on error.
  86226. */
  86227. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86228. /** Signature for the tell callback.
  86229. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86230. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86231. * and 32-bits wide.
  86232. *
  86233. * \param handle The handle to the data source.
  86234. * \retval FLAC__int64
  86235. * The current position on success, \c -1 on error.
  86236. */
  86237. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86238. /** Signature for the EOF callback.
  86239. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86240. * on many systems, feof() is a macro, so in this case a wrapper function
  86241. * must be provided instead.
  86242. *
  86243. * \param handle The handle to the data source.
  86244. * \retval int
  86245. * \c 0 if not at end of file, nonzero if at end of file.
  86246. */
  86247. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86248. /** Signature for the close callback.
  86249. * The signature and semantics match POSIX fclose() implementations
  86250. * and can generally be used interchangeably.
  86251. *
  86252. * \param handle The handle to the data source.
  86253. * \retval int
  86254. * \c 0 on success, \c EOF on error.
  86255. */
  86256. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86257. /** A structure for holding a set of callbacks.
  86258. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86259. * describe which of the callbacks are required. The ones that are not
  86260. * required may be set to NULL.
  86261. *
  86262. * If the seek requirement for an interface is optional, you can signify that
  86263. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86264. */
  86265. typedef struct {
  86266. FLAC__IOCallback_Read read;
  86267. FLAC__IOCallback_Write write;
  86268. FLAC__IOCallback_Seek seek;
  86269. FLAC__IOCallback_Tell tell;
  86270. FLAC__IOCallback_Eof eof;
  86271. FLAC__IOCallback_Close close;
  86272. } FLAC__IOCallbacks;
  86273. /* \} */
  86274. #ifdef __cplusplus
  86275. }
  86276. #endif
  86277. #endif
  86278. /*** End of inlined file: callback.h ***/
  86279. /*** Start of inlined file: format.h ***/
  86280. #ifndef FLAC__FORMAT_H
  86281. #define FLAC__FORMAT_H
  86282. #ifdef __cplusplus
  86283. extern "C" {
  86284. #endif
  86285. /** \file include/FLAC/format.h
  86286. *
  86287. * \brief
  86288. * This module contains structure definitions for the representation
  86289. * of FLAC format components in memory. These are the basic
  86290. * structures used by the rest of the interfaces.
  86291. *
  86292. * See the detailed documentation in the
  86293. * \link flac_format format \endlink module.
  86294. */
  86295. /** \defgroup flac_format FLAC/format.h: format components
  86296. * \ingroup flac
  86297. *
  86298. * \brief
  86299. * This module contains structure definitions for the representation
  86300. * of FLAC format components in memory. These are the basic
  86301. * structures used by the rest of the interfaces.
  86302. *
  86303. * First, you should be familiar with the
  86304. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86305. * follow directly from the specification. As a user of libFLAC, the
  86306. * interesting parts really are the structures that describe the frame
  86307. * header and metadata blocks.
  86308. *
  86309. * The format structures here are very primitive, designed to store
  86310. * information in an efficient way. Reading information from the
  86311. * structures is easy but creating or modifying them directly is
  86312. * more complex. For the most part, as a user of a library, editing
  86313. * is not necessary; however, for metadata blocks it is, so there are
  86314. * convenience functions provided in the \link flac_metadata metadata
  86315. * module \endlink to simplify the manipulation of metadata blocks.
  86316. *
  86317. * \note
  86318. * It's not the best convention, but symbols ending in _LEN are in bits
  86319. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86320. * global variables because they are usually used when declaring byte
  86321. * arrays and some compilers require compile-time knowledge of array
  86322. * sizes when declared on the stack.
  86323. *
  86324. * \{
  86325. */
  86326. /*
  86327. Most of the values described in this file are defined by the FLAC
  86328. format specification. There is nothing to tune here.
  86329. */
  86330. /** The largest legal metadata type code. */
  86331. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86332. /** The minimum block size, in samples, permitted by the format. */
  86333. #define FLAC__MIN_BLOCK_SIZE (16u)
  86334. /** The maximum block size, in samples, permitted by the format. */
  86335. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86336. /** The maximum block size, in samples, permitted by the FLAC subset for
  86337. * sample rates up to 48kHz. */
  86338. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86339. /** The maximum number of channels permitted by the format. */
  86340. #define FLAC__MAX_CHANNELS (8u)
  86341. /** The minimum sample resolution permitted by the format. */
  86342. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86343. /** The maximum sample resolution permitted by the format. */
  86344. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86345. /** The maximum sample resolution permitted by libFLAC.
  86346. *
  86347. * \warning
  86348. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86349. * the reference encoder/decoder is currently limited to 24 bits because
  86350. * of prevalent 32-bit math, so make sure and use this value when
  86351. * appropriate.
  86352. */
  86353. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86354. /** The maximum sample rate permitted by the format. The value is
  86355. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86356. * as to why.
  86357. */
  86358. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86359. /** The maximum LPC order permitted by the format. */
  86360. #define FLAC__MAX_LPC_ORDER (32u)
  86361. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86362. * up to 48kHz. */
  86363. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86364. /** The minimum quantized linear predictor coefficient precision
  86365. * permitted by the format.
  86366. */
  86367. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86368. /** The maximum quantized linear predictor coefficient precision
  86369. * permitted by the format.
  86370. */
  86371. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86372. /** The maximum order of the fixed predictors permitted by the format. */
  86373. #define FLAC__MAX_FIXED_ORDER (4u)
  86374. /** The maximum Rice partition order permitted by the format. */
  86375. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86376. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86377. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86378. /** The version string of the release, stamped onto the libraries and binaries.
  86379. *
  86380. * \note
  86381. * This does not correspond to the shared library version number, which
  86382. * is used to determine binary compatibility.
  86383. */
  86384. extern FLAC_API const char *FLAC__VERSION_STRING;
  86385. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86386. * This is a NUL-terminated ASCII string; when inserted into the
  86387. * VORBIS_COMMENT the trailing null is stripped.
  86388. */
  86389. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86390. /** The byte string representation of the beginning of a FLAC stream. */
  86391. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86392. /** The 32-bit integer big-endian representation of the beginning of
  86393. * a FLAC stream.
  86394. */
  86395. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86396. /** The length of the FLAC signature in bits. */
  86397. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86398. /** The length of the FLAC signature in bytes. */
  86399. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86400. /*****************************************************************************
  86401. *
  86402. * Subframe structures
  86403. *
  86404. *****************************************************************************/
  86405. /*****************************************************************************/
  86406. /** An enumeration of the available entropy coding methods. */
  86407. typedef enum {
  86408. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86409. /**< Residual is coded by partitioning into contexts, each with it's own
  86410. * 4-bit Rice parameter. */
  86411. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86412. /**< Residual is coded by partitioning into contexts, each with it's own
  86413. * 5-bit Rice parameter. */
  86414. } FLAC__EntropyCodingMethodType;
  86415. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86416. *
  86417. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86418. * give the string equivalent. The contents should not be modified.
  86419. */
  86420. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86421. /** Contents of a Rice partitioned residual
  86422. */
  86423. typedef struct {
  86424. unsigned *parameters;
  86425. /**< The Rice parameters for each context. */
  86426. unsigned *raw_bits;
  86427. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86428. * partitions and zero for unescaped partitions.
  86429. */
  86430. unsigned capacity_by_order;
  86431. /**< The capacity of the \a parameters and \a raw_bits arrays
  86432. * specified as an order, i.e. the number of array elements
  86433. * allocated is 2 ^ \a capacity_by_order.
  86434. */
  86435. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86436. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86437. */
  86438. typedef struct {
  86439. unsigned order;
  86440. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86441. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86442. /**< The context's Rice parameters and/or raw bits. */
  86443. } FLAC__EntropyCodingMethod_PartitionedRice;
  86444. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86445. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86446. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86447. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86448. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86449. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86450. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86451. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86452. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86453. */
  86454. typedef struct {
  86455. FLAC__EntropyCodingMethodType type;
  86456. union {
  86457. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86458. } data;
  86459. } FLAC__EntropyCodingMethod;
  86460. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86461. /*****************************************************************************/
  86462. /** An enumeration of the available subframe types. */
  86463. typedef enum {
  86464. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86465. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86466. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86467. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86468. } FLAC__SubframeType;
  86469. /** Maps a FLAC__SubframeType to a C string.
  86470. *
  86471. * Using a FLAC__SubframeType as the index to this array will
  86472. * give the string equivalent. The contents should not be modified.
  86473. */
  86474. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86475. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86476. */
  86477. typedef struct {
  86478. FLAC__int32 value; /**< The constant signal value. */
  86479. } FLAC__Subframe_Constant;
  86480. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86481. */
  86482. typedef struct {
  86483. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86484. } FLAC__Subframe_Verbatim;
  86485. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86486. */
  86487. typedef struct {
  86488. FLAC__EntropyCodingMethod entropy_coding_method;
  86489. /**< The residual coding method. */
  86490. unsigned order;
  86491. /**< The polynomial order. */
  86492. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86493. /**< Warmup samples to prime the predictor, length == order. */
  86494. const FLAC__int32 *residual;
  86495. /**< The residual signal, length == (blocksize minus order) samples. */
  86496. } FLAC__Subframe_Fixed;
  86497. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86498. */
  86499. typedef struct {
  86500. FLAC__EntropyCodingMethod entropy_coding_method;
  86501. /**< The residual coding method. */
  86502. unsigned order;
  86503. /**< The FIR order. */
  86504. unsigned qlp_coeff_precision;
  86505. /**< Quantized FIR filter coefficient precision in bits. */
  86506. int quantization_level;
  86507. /**< The qlp coeff shift needed. */
  86508. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86509. /**< FIR filter coefficients. */
  86510. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86511. /**< Warmup samples to prime the predictor, length == order. */
  86512. const FLAC__int32 *residual;
  86513. /**< The residual signal, length == (blocksize minus order) samples. */
  86514. } FLAC__Subframe_LPC;
  86515. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86516. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86517. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86518. */
  86519. typedef struct {
  86520. FLAC__SubframeType type;
  86521. union {
  86522. FLAC__Subframe_Constant constant;
  86523. FLAC__Subframe_Fixed fixed;
  86524. FLAC__Subframe_LPC lpc;
  86525. FLAC__Subframe_Verbatim verbatim;
  86526. } data;
  86527. unsigned wasted_bits;
  86528. } FLAC__Subframe;
  86529. /** == 1 (bit)
  86530. *
  86531. * This used to be a zero-padding bit (hence the name
  86532. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86533. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86534. * to mean something else.
  86535. */
  86536. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86537. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86538. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86539. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86540. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86541. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86542. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86543. /*****************************************************************************/
  86544. /*****************************************************************************
  86545. *
  86546. * Frame structures
  86547. *
  86548. *****************************************************************************/
  86549. /** An enumeration of the available channel assignments. */
  86550. typedef enum {
  86551. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86552. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86553. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86554. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86555. } FLAC__ChannelAssignment;
  86556. /** Maps a FLAC__ChannelAssignment to a C string.
  86557. *
  86558. * Using a FLAC__ChannelAssignment as the index to this array will
  86559. * give the string equivalent. The contents should not be modified.
  86560. */
  86561. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86562. /** An enumeration of the possible frame numbering methods. */
  86563. typedef enum {
  86564. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86565. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86566. } FLAC__FrameNumberType;
  86567. /** Maps a FLAC__FrameNumberType to a C string.
  86568. *
  86569. * Using a FLAC__FrameNumberType as the index to this array will
  86570. * give the string equivalent. The contents should not be modified.
  86571. */
  86572. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86573. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86574. */
  86575. typedef struct {
  86576. unsigned blocksize;
  86577. /**< The number of samples per subframe. */
  86578. unsigned sample_rate;
  86579. /**< The sample rate in Hz. */
  86580. unsigned channels;
  86581. /**< The number of channels (== number of subframes). */
  86582. FLAC__ChannelAssignment channel_assignment;
  86583. /**< The channel assignment for the frame. */
  86584. unsigned bits_per_sample;
  86585. /**< The sample resolution. */
  86586. FLAC__FrameNumberType number_type;
  86587. /**< The numbering scheme used for the frame. As a convenience, the
  86588. * decoder will always convert a frame number to a sample number because
  86589. * the rules are complex. */
  86590. union {
  86591. FLAC__uint32 frame_number;
  86592. FLAC__uint64 sample_number;
  86593. } number;
  86594. /**< The frame number or sample number of first sample in frame;
  86595. * use the \a number_type value to determine which to use. */
  86596. FLAC__uint8 crc;
  86597. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86598. * of the raw frame header bytes, meaning everything before the CRC byte
  86599. * including the sync code.
  86600. */
  86601. } FLAC__FrameHeader;
  86602. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86603. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86604. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86605. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86606. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86607. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86608. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86609. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86610. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86611. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86612. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86613. */
  86614. typedef struct {
  86615. FLAC__uint16 crc;
  86616. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86617. * 0) of the bytes before the crc, back to and including the frame header
  86618. * sync code.
  86619. */
  86620. } FLAC__FrameFooter;
  86621. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86622. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86623. */
  86624. typedef struct {
  86625. FLAC__FrameHeader header;
  86626. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86627. FLAC__FrameFooter footer;
  86628. } FLAC__Frame;
  86629. /*****************************************************************************/
  86630. /*****************************************************************************
  86631. *
  86632. * Meta-data structures
  86633. *
  86634. *****************************************************************************/
  86635. /** An enumeration of the available metadata block types. */
  86636. typedef enum {
  86637. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86638. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86639. FLAC__METADATA_TYPE_PADDING = 1,
  86640. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86641. FLAC__METADATA_TYPE_APPLICATION = 2,
  86642. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86643. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86644. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86645. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86646. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86647. FLAC__METADATA_TYPE_CUESHEET = 5,
  86648. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86649. FLAC__METADATA_TYPE_PICTURE = 6,
  86650. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86651. FLAC__METADATA_TYPE_UNDEFINED = 7
  86652. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86653. } FLAC__MetadataType;
  86654. /** Maps a FLAC__MetadataType to a C string.
  86655. *
  86656. * Using a FLAC__MetadataType as the index to this array will
  86657. * give the string equivalent. The contents should not be modified.
  86658. */
  86659. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86660. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86661. */
  86662. typedef struct {
  86663. unsigned min_blocksize, max_blocksize;
  86664. unsigned min_framesize, max_framesize;
  86665. unsigned sample_rate;
  86666. unsigned channels;
  86667. unsigned bits_per_sample;
  86668. FLAC__uint64 total_samples;
  86669. FLAC__byte md5sum[16];
  86670. } FLAC__StreamMetadata_StreamInfo;
  86671. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86672. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  86673. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86674. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  86675. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  86676. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  86677. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  86678. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  86679. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  86680. /** The total stream length of the STREAMINFO block in bytes. */
  86681. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  86682. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  86683. */
  86684. typedef struct {
  86685. int dummy;
  86686. /**< Conceptually this is an empty struct since we don't store the
  86687. * padding bytes. Empty structs are not allowed by some C compilers,
  86688. * hence the dummy.
  86689. */
  86690. } FLAC__StreamMetadata_Padding;
  86691. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  86692. */
  86693. typedef struct {
  86694. FLAC__byte id[4];
  86695. FLAC__byte *data;
  86696. } FLAC__StreamMetadata_Application;
  86697. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  86698. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  86699. */
  86700. typedef struct {
  86701. FLAC__uint64 sample_number;
  86702. /**< The sample number of the target frame. */
  86703. FLAC__uint64 stream_offset;
  86704. /**< The offset, in bytes, of the target frame with respect to
  86705. * beginning of the first frame. */
  86706. unsigned frame_samples;
  86707. /**< The number of samples in the target frame. */
  86708. } FLAC__StreamMetadata_SeekPoint;
  86709. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  86710. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  86711. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  86712. /** The total stream length of a seek point in bytes. */
  86713. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  86714. /** The value used in the \a sample_number field of
  86715. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  86716. * point (== 0xffffffffffffffff).
  86717. */
  86718. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  86719. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  86720. *
  86721. * \note From the format specification:
  86722. * - The seek points must be sorted by ascending sample number.
  86723. * - Each seek point's sample number must be the first sample of the
  86724. * target frame.
  86725. * - Each seek point's sample number must be unique within the table.
  86726. * - Existence of a SEEKTABLE block implies a correct setting of
  86727. * total_samples in the stream_info block.
  86728. * - Behavior is undefined when more than one SEEKTABLE block is
  86729. * present in a stream.
  86730. */
  86731. typedef struct {
  86732. unsigned num_points;
  86733. FLAC__StreamMetadata_SeekPoint *points;
  86734. } FLAC__StreamMetadata_SeekTable;
  86735. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86736. *
  86737. * For convenience, the APIs maintain a trailing NUL character at the end of
  86738. * \a entry which is not counted toward \a length, i.e.
  86739. * \code strlen(entry) == length \endcode
  86740. */
  86741. typedef struct {
  86742. FLAC__uint32 length;
  86743. FLAC__byte *entry;
  86744. } FLAC__StreamMetadata_VorbisComment_Entry;
  86745. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  86746. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  86747. */
  86748. typedef struct {
  86749. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  86750. FLAC__uint32 num_comments;
  86751. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  86752. } FLAC__StreamMetadata_VorbisComment;
  86753. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  86754. /** FLAC CUESHEET track index structure. (See the
  86755. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  86756. * the full description of each field.)
  86757. */
  86758. typedef struct {
  86759. FLAC__uint64 offset;
  86760. /**< Offset in samples, relative to the track offset, of the index
  86761. * point.
  86762. */
  86763. FLAC__byte number;
  86764. /**< The index point number. */
  86765. } FLAC__StreamMetadata_CueSheet_Index;
  86766. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  86767. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  86768. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  86769. /** FLAC CUESHEET track structure. (See the
  86770. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  86771. * the full description of each field.)
  86772. */
  86773. typedef struct {
  86774. FLAC__uint64 offset;
  86775. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  86776. FLAC__byte number;
  86777. /**< The track number. */
  86778. char isrc[13];
  86779. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  86780. unsigned type:1;
  86781. /**< The track type: 0 for audio, 1 for non-audio. */
  86782. unsigned pre_emphasis:1;
  86783. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  86784. FLAC__byte num_indices;
  86785. /**< The number of track index points. */
  86786. FLAC__StreamMetadata_CueSheet_Index *indices;
  86787. /**< NULL if num_indices == 0, else pointer to array of index points. */
  86788. } FLAC__StreamMetadata_CueSheet_Track;
  86789. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  86790. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  86791. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  86792. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  86793. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  86794. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  86795. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  86796. /** FLAC CUESHEET structure. (See the
  86797. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  86798. * for the full description of each field.)
  86799. */
  86800. typedef struct {
  86801. char media_catalog_number[129];
  86802. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  86803. * general, the media catalog number may be 0 to 128 bytes long; any
  86804. * unused characters should be right-padded with NUL characters.
  86805. */
  86806. FLAC__uint64 lead_in;
  86807. /**< The number of lead-in samples. */
  86808. FLAC__bool is_cd;
  86809. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  86810. unsigned num_tracks;
  86811. /**< The number of tracks. */
  86812. FLAC__StreamMetadata_CueSheet_Track *tracks;
  86813. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  86814. } FLAC__StreamMetadata_CueSheet;
  86815. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  86816. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  86817. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  86818. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  86819. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  86820. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  86821. typedef enum {
  86822. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  86823. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  86824. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  86825. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  86826. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  86827. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  86828. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  86829. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  86830. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  86831. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  86832. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  86833. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  86834. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  86835. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  86836. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  86837. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  86838. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  86839. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  86840. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  86841. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  86842. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  86843. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  86844. } FLAC__StreamMetadata_Picture_Type;
  86845. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  86846. *
  86847. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  86848. * will give the string equivalent. The contents should not be
  86849. * modified.
  86850. */
  86851. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  86852. /** FLAC PICTURE structure. (See the
  86853. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  86854. * for the full description of each field.)
  86855. */
  86856. typedef struct {
  86857. FLAC__StreamMetadata_Picture_Type type;
  86858. /**< The kind of picture stored. */
  86859. char *mime_type;
  86860. /**< Picture data's MIME type, in ASCII printable characters
  86861. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  86862. * use picture data of MIME type \c image/jpeg or \c image/png. A
  86863. * MIME type of '-->' is also allowed, in which case the picture
  86864. * data should be a complete URL. In file storage, the MIME type is
  86865. * stored as a 32-bit length followed by the ASCII string with no NUL
  86866. * terminator, but is converted to a plain C string in this structure
  86867. * for convenience.
  86868. */
  86869. FLAC__byte *description;
  86870. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  86871. * the description is stored as a 32-bit length followed by the UTF-8
  86872. * string with no NUL terminator, but is converted to a plain C string
  86873. * in this structure for convenience.
  86874. */
  86875. FLAC__uint32 width;
  86876. /**< Picture's width in pixels. */
  86877. FLAC__uint32 height;
  86878. /**< Picture's height in pixels. */
  86879. FLAC__uint32 depth;
  86880. /**< Picture's color depth in bits-per-pixel. */
  86881. FLAC__uint32 colors;
  86882. /**< For indexed palettes (like GIF), picture's number of colors (the
  86883. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  86884. */
  86885. FLAC__uint32 data_length;
  86886. /**< Length of binary picture data in bytes. */
  86887. FLAC__byte *data;
  86888. /**< Binary picture data. */
  86889. } FLAC__StreamMetadata_Picture;
  86890. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  86891. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  86892. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  86893. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  86894. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  86895. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  86896. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  86897. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  86898. /** Structure that is used when a metadata block of unknown type is loaded.
  86899. * The contents are opaque. The structure is used only internally to
  86900. * correctly handle unknown metadata.
  86901. */
  86902. typedef struct {
  86903. FLAC__byte *data;
  86904. } FLAC__StreamMetadata_Unknown;
  86905. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  86906. */
  86907. typedef struct {
  86908. FLAC__MetadataType type;
  86909. /**< The type of the metadata block; used determine which member of the
  86910. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  86911. * then \a data.unknown must be used. */
  86912. FLAC__bool is_last;
  86913. /**< \c true if this metadata block is the last, else \a false */
  86914. unsigned length;
  86915. /**< Length, in bytes, of the block data as it appears in the stream. */
  86916. union {
  86917. FLAC__StreamMetadata_StreamInfo stream_info;
  86918. FLAC__StreamMetadata_Padding padding;
  86919. FLAC__StreamMetadata_Application application;
  86920. FLAC__StreamMetadata_SeekTable seek_table;
  86921. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  86922. FLAC__StreamMetadata_CueSheet cue_sheet;
  86923. FLAC__StreamMetadata_Picture picture;
  86924. FLAC__StreamMetadata_Unknown unknown;
  86925. } data;
  86926. /**< Polymorphic block data; use the \a type value to determine which
  86927. * to use. */
  86928. } FLAC__StreamMetadata;
  86929. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  86930. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  86931. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  86932. /** The total stream length of a metadata block header in bytes. */
  86933. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  86934. /*****************************************************************************/
  86935. /*****************************************************************************
  86936. *
  86937. * Utility functions
  86938. *
  86939. *****************************************************************************/
  86940. /** Tests that a sample rate is valid for FLAC.
  86941. *
  86942. * \param sample_rate The sample rate to test for compliance.
  86943. * \retval FLAC__bool
  86944. * \c true if the given sample rate conforms to the specification, else
  86945. * \c false.
  86946. */
  86947. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  86948. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  86949. * for valid sample rates are slightly more complex since the rate has to
  86950. * be expressible completely in the frame header.
  86951. *
  86952. * \param sample_rate The sample rate to test for compliance.
  86953. * \retval FLAC__bool
  86954. * \c true if the given sample rate conforms to the specification for the
  86955. * subset, else \c false.
  86956. */
  86957. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  86958. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  86959. * comment specification.
  86960. *
  86961. * Vorbis comment names must be composed only of characters from
  86962. * [0x20-0x3C,0x3E-0x7D].
  86963. *
  86964. * \param name A NUL-terminated string to be checked.
  86965. * \assert
  86966. * \code name != NULL \endcode
  86967. * \retval FLAC__bool
  86968. * \c false if entry name is illegal, else \c true.
  86969. */
  86970. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  86971. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  86972. * comment specification.
  86973. *
  86974. * Vorbis comment values must be valid UTF-8 sequences.
  86975. *
  86976. * \param value A string to be checked.
  86977. * \param length A the length of \a value in bytes. May be
  86978. * \c (unsigned)(-1) to indicate that \a value is a plain
  86979. * UTF-8 NUL-terminated string.
  86980. * \assert
  86981. * \code value != NULL \endcode
  86982. * \retval FLAC__bool
  86983. * \c false if entry name is illegal, else \c true.
  86984. */
  86985. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  86986. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  86987. * comment specification.
  86988. *
  86989. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  86990. * 'value' must be legal according to
  86991. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  86992. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  86993. *
  86994. * \param entry An entry to be checked.
  86995. * \param length The length of \a entry in bytes.
  86996. * \assert
  86997. * \code value != NULL \endcode
  86998. * \retval FLAC__bool
  86999. * \c false if entry name is illegal, else \c true.
  87000. */
  87001. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87002. /** Check a seek table to see if it conforms to the FLAC specification.
  87003. * See the format specification for limits on the contents of the
  87004. * seek table.
  87005. *
  87006. * \param seek_table A pointer to a seek table to be checked.
  87007. * \assert
  87008. * \code seek_table != NULL \endcode
  87009. * \retval FLAC__bool
  87010. * \c false if seek table is illegal, else \c true.
  87011. */
  87012. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87013. /** Sort a seek table's seek points according to the format specification.
  87014. * This includes a "unique-ification" step to remove duplicates, i.e.
  87015. * seek points with identical \a sample_number values. Duplicate seek
  87016. * points are converted into placeholder points and sorted to the end of
  87017. * the table.
  87018. *
  87019. * \param seek_table A pointer to a seek table to be sorted.
  87020. * \assert
  87021. * \code seek_table != NULL \endcode
  87022. * \retval unsigned
  87023. * The number of duplicate seek points converted into placeholders.
  87024. */
  87025. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87026. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87027. * See the format specification for limits on the contents of the
  87028. * cue sheet.
  87029. *
  87030. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87031. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87032. * stringent requirements for a CD-DA (audio) disc.
  87033. * \param violation Address of a pointer to a string. If there is a
  87034. * violation, a pointer to a string explanation of the
  87035. * violation will be returned here. \a violation may be
  87036. * \c NULL if you don't need the returned string. Do not
  87037. * free the returned string; it will always point to static
  87038. * data.
  87039. * \assert
  87040. * \code cue_sheet != NULL \endcode
  87041. * \retval FLAC__bool
  87042. * \c false if cue sheet is illegal, else \c true.
  87043. */
  87044. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87045. /** Check picture data to see if it conforms to the FLAC specification.
  87046. * See the format specification for limits on the contents of the
  87047. * PICTURE block.
  87048. *
  87049. * \param picture A pointer to existing picture data to be checked.
  87050. * \param violation Address of a pointer to a string. If there is a
  87051. * violation, a pointer to a string explanation of the
  87052. * violation will be returned here. \a violation may be
  87053. * \c NULL if you don't need the returned string. Do not
  87054. * free the returned string; it will always point to static
  87055. * data.
  87056. * \assert
  87057. * \code picture != NULL \endcode
  87058. * \retval FLAC__bool
  87059. * \c false if picture data is illegal, else \c true.
  87060. */
  87061. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87062. /* \} */
  87063. #ifdef __cplusplus
  87064. }
  87065. #endif
  87066. #endif
  87067. /*** End of inlined file: format.h ***/
  87068. /*** Start of inlined file: metadata.h ***/
  87069. #ifndef FLAC__METADATA_H
  87070. #define FLAC__METADATA_H
  87071. #include <sys/types.h> /* for off_t */
  87072. /* --------------------------------------------------------------------
  87073. (For an example of how all these routines are used, see the source
  87074. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87075. metaflac in src/metaflac/)
  87076. ------------------------------------------------------------------*/
  87077. /** \file include/FLAC/metadata.h
  87078. *
  87079. * \brief
  87080. * This module provides functions for creating and manipulating FLAC
  87081. * metadata blocks in memory, and three progressively more powerful
  87082. * interfaces for traversing and editing metadata in FLAC files.
  87083. *
  87084. * See the detailed documentation for each interface in the
  87085. * \link flac_metadata metadata \endlink module.
  87086. */
  87087. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87088. * \ingroup flac
  87089. *
  87090. * \brief
  87091. * This module provides functions for creating and manipulating FLAC
  87092. * metadata blocks in memory, and three progressively more powerful
  87093. * interfaces for traversing and editing metadata in native FLAC files.
  87094. * Note that currently only the Chain interface (level 2) supports Ogg
  87095. * FLAC files, and it is read-only i.e. no writing back changed
  87096. * metadata to file.
  87097. *
  87098. * There are three metadata interfaces of increasing complexity:
  87099. *
  87100. * Level 0:
  87101. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87102. * PICTURE blocks.
  87103. *
  87104. * Level 1:
  87105. * Read-write access to all metadata blocks. This level is write-
  87106. * efficient in most cases (more on this below), and uses less memory
  87107. * than level 2.
  87108. *
  87109. * Level 2:
  87110. * Read-write access to all metadata blocks. This level is write-
  87111. * efficient in all cases, but uses more memory since all metadata for
  87112. * the whole file is read into memory and manipulated before writing
  87113. * out again.
  87114. *
  87115. * What do we mean by efficient? Since FLAC metadata appears at the
  87116. * beginning of the file, when writing metadata back to a FLAC file
  87117. * it is possible to grow or shrink the metadata such that the entire
  87118. * file must be rewritten. However, if the size remains the same during
  87119. * changes or PADDING blocks are utilized, only the metadata needs to be
  87120. * overwritten, which is much faster.
  87121. *
  87122. * Efficient means the whole file is rewritten at most one time, and only
  87123. * when necessary. Level 1 is not efficient only in the case that you
  87124. * cause more than one metadata block to grow or shrink beyond what can
  87125. * be accomodated by padding. In this case you should probably use level
  87126. * 2, which allows you to edit all the metadata for a file in memory and
  87127. * write it out all at once.
  87128. *
  87129. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87130. * front of the file.
  87131. *
  87132. * All levels access files via their filenames. In addition, level 2
  87133. * has additional alternative read and write functions that take an I/O
  87134. * handle and callbacks, for situations where access by filename is not
  87135. * possible.
  87136. *
  87137. * In addition to the three interfaces, this module defines functions for
  87138. * creating and manipulating various metadata objects in memory. As we see
  87139. * from the Format module, FLAC metadata blocks in memory are very primitive
  87140. * structures for storing information in an efficient way. Reading
  87141. * information from the structures is easy but creating or modifying them
  87142. * directly is more complex. The metadata object routines here facilitate
  87143. * this by taking care of the consistency and memory management drudgery.
  87144. *
  87145. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87146. * metadata however, you will not probably not need these.
  87147. *
  87148. * From a dependency standpoint, none of the encoders or decoders require
  87149. * the metadata module. This is so that embedded users can strip out the
  87150. * metadata module from libFLAC to reduce the size and complexity.
  87151. */
  87152. #ifdef __cplusplus
  87153. extern "C" {
  87154. #endif
  87155. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87156. * \ingroup flac_metadata
  87157. *
  87158. * \brief
  87159. * The level 0 interface consists of individual routines to read the
  87160. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87161. * only a filename.
  87162. *
  87163. * They try to skip any ID3v2 tag at the head of the file.
  87164. *
  87165. * \{
  87166. */
  87167. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87168. * will try to skip any ID3v2 tag at the head of the file.
  87169. *
  87170. * \param filename The path to the FLAC file to read.
  87171. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87172. * FLAC__StreamMetadata is a simple structure with no
  87173. * memory allocation involved, you pass the address of
  87174. * an existing structure. It need not be initialized.
  87175. * \assert
  87176. * \code filename != NULL \endcode
  87177. * \code streaminfo != NULL \endcode
  87178. * \retval FLAC__bool
  87179. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87180. * \c false if there was a memory allocation error, a file decoder error,
  87181. * or the file contained no STREAMINFO block. (A memory allocation error
  87182. * is possible because this function must set up a file decoder.)
  87183. */
  87184. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87185. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87186. * function will try to skip any ID3v2 tag at the head of the file.
  87187. *
  87188. * \param filename The path to the FLAC file to read.
  87189. * \param tags The address where the returned pointer will be
  87190. * stored. The \a tags object must be deleted by
  87191. * the caller using FLAC__metadata_object_delete().
  87192. * \assert
  87193. * \code filename != NULL \endcode
  87194. * \code tags != NULL \endcode
  87195. * \retval FLAC__bool
  87196. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87197. * and \a *tags will be set to the address of the metadata structure.
  87198. * Returns \c false if there was a memory allocation error, a file
  87199. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87200. * \a *tags will be set to \c NULL.
  87201. */
  87202. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87203. /** Read the CUESHEET metadata block of the given FLAC file. This
  87204. * function will try to skip any ID3v2 tag at the head of the file.
  87205. *
  87206. * \param filename The path to the FLAC file to read.
  87207. * \param cuesheet The address where the returned pointer will be
  87208. * stored. The \a cuesheet object must be deleted by
  87209. * the caller using FLAC__metadata_object_delete().
  87210. * \assert
  87211. * \code filename != NULL \endcode
  87212. * \code cuesheet != NULL \endcode
  87213. * \retval FLAC__bool
  87214. * \c true if a valid CUESHEET block was read from \a filename,
  87215. * and \a *cuesheet will be set to the address of the metadata
  87216. * structure. Returns \c false if there was a memory allocation
  87217. * error, a file decoder error, or the file contained no CUESHEET
  87218. * block, and \a *cuesheet will be set to \c NULL.
  87219. */
  87220. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87221. /** Read a PICTURE metadata block of the given FLAC file. This
  87222. * function will try to skip any ID3v2 tag at the head of the file.
  87223. * Since there can be more than one PICTURE block in a file, this
  87224. * function takes a number of parameters that act as constraints to
  87225. * the search. The PICTURE block with the largest area matching all
  87226. * the constraints will be returned, or \a *picture will be set to
  87227. * \c NULL if there was no such block.
  87228. *
  87229. * \param filename The path to the FLAC file to read.
  87230. * \param picture The address where the returned pointer will be
  87231. * stored. The \a picture object must be deleted by
  87232. * the caller using FLAC__metadata_object_delete().
  87233. * \param type The desired picture type. Use \c -1 to mean
  87234. * "any type".
  87235. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87236. * string will be matched exactly. Use \c NULL to
  87237. * mean "any MIME type".
  87238. * \param description The desired description. The string will be
  87239. * matched exactly. Use \c NULL to mean "any
  87240. * description".
  87241. * \param max_width The maximum width in pixels desired. Use
  87242. * \c (unsigned)(-1) to mean "any width".
  87243. * \param max_height The maximum height in pixels desired. Use
  87244. * \c (unsigned)(-1) to mean "any height".
  87245. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87246. * Use \c (unsigned)(-1) to mean "any depth".
  87247. * \param max_colors The maximum number of colors desired. Use
  87248. * \c (unsigned)(-1) to mean "any number of colors".
  87249. * \assert
  87250. * \code filename != NULL \endcode
  87251. * \code picture != NULL \endcode
  87252. * \retval FLAC__bool
  87253. * \c true if a valid PICTURE block was read from \a filename,
  87254. * and \a *picture will be set to the address of the metadata
  87255. * structure. Returns \c false if there was a memory allocation
  87256. * error, a file decoder error, or the file contained no PICTURE
  87257. * block, and \a *picture will be set to \c NULL.
  87258. */
  87259. 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);
  87260. /* \} */
  87261. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87262. * \ingroup flac_metadata
  87263. *
  87264. * \brief
  87265. * The level 1 interface provides read-write access to FLAC file metadata and
  87266. * operates directly on the FLAC file.
  87267. *
  87268. * The general usage of this interface is:
  87269. *
  87270. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87271. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87272. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87273. * see if the file is writable, or only read access is allowed.
  87274. * - Use FLAC__metadata_simple_iterator_next() and
  87275. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87276. * This is does not read the actual blocks themselves.
  87277. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87278. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87279. * forward from the front of the file.
  87280. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87281. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87282. * the current iterator position. The returned object is yours to modify
  87283. * and free.
  87284. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87285. * back. You must have write permission to the original file. Make sure to
  87286. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87287. * below.
  87288. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87289. * Use the object creation functions from
  87290. * \link flac_metadata_object here \endlink to generate new objects.
  87291. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87292. * currently referred to by the iterator, or replace it with padding.
  87293. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87294. * finished.
  87295. *
  87296. * \note
  87297. * The FLAC file remains open the whole time between
  87298. * FLAC__metadata_simple_iterator_init() and
  87299. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87300. * the file during this time.
  87301. *
  87302. * \note
  87303. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87304. * FLAC__StreamMetadata objects. These are managed automatically.
  87305. *
  87306. * \note
  87307. * If any of the modification functions
  87308. * (FLAC__metadata_simple_iterator_set_block(),
  87309. * FLAC__metadata_simple_iterator_delete_block(),
  87310. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87311. * you should delete the iterator as it may no longer be valid.
  87312. *
  87313. * \{
  87314. */
  87315. struct FLAC__Metadata_SimpleIterator;
  87316. /** The opaque structure definition for the level 1 iterator type.
  87317. * See the
  87318. * \link flac_metadata_level1 metadata level 1 module \endlink
  87319. * for a detailed description.
  87320. */
  87321. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87322. /** Status type for FLAC__Metadata_SimpleIterator.
  87323. *
  87324. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87325. */
  87326. typedef enum {
  87327. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87328. /**< The iterator is in the normal OK state */
  87329. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87330. /**< The data passed into a function violated the function's usage criteria */
  87331. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87332. /**< The iterator could not open the target file */
  87333. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87334. /**< The iterator could not find the FLAC signature at the start of the file */
  87335. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87336. /**< The iterator tried to write to a file that was not writable */
  87337. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87338. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87339. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87340. /**< The iterator encountered an error while reading the FLAC file */
  87341. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87342. /**< The iterator encountered an error while seeking in the FLAC file */
  87343. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87344. /**< The iterator encountered an error while writing the FLAC file */
  87345. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87346. /**< The iterator encountered an error renaming the FLAC file */
  87347. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87348. /**< The iterator encountered an error removing the temporary file */
  87349. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87350. /**< Memory allocation failed */
  87351. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87352. /**< The caller violated an assertion or an unexpected error occurred */
  87353. } FLAC__Metadata_SimpleIteratorStatus;
  87354. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87355. *
  87356. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87357. * will give the string equivalent. The contents should not be modified.
  87358. */
  87359. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87360. /** Create a new iterator instance.
  87361. *
  87362. * \retval FLAC__Metadata_SimpleIterator*
  87363. * \c NULL if there was an error allocating memory, else the new instance.
  87364. */
  87365. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87366. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87367. *
  87368. * \param iterator A pointer to an existing iterator.
  87369. * \assert
  87370. * \code iterator != NULL \endcode
  87371. */
  87372. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87373. /** Get the current status of the iterator. Call this after a function
  87374. * returns \c false to get the reason for the error. Also resets the status
  87375. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87376. *
  87377. * \param iterator A pointer to an existing iterator.
  87378. * \assert
  87379. * \code iterator != NULL \endcode
  87380. * \retval FLAC__Metadata_SimpleIteratorStatus
  87381. * The current status of the iterator.
  87382. */
  87383. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87384. /** Initialize the iterator to point to the first metadata block in the
  87385. * given FLAC file.
  87386. *
  87387. * \param iterator A pointer to an existing iterator.
  87388. * \param filename The path to the FLAC file.
  87389. * \param read_only If \c true, the FLAC file will be opened
  87390. * in read-only mode; if \c false, the FLAC
  87391. * file will be opened for edit even if no
  87392. * edits are performed.
  87393. * \param preserve_file_stats If \c true, the owner and modification
  87394. * time will be preserved even if the FLAC
  87395. * file is written to.
  87396. * \assert
  87397. * \code iterator != NULL \endcode
  87398. * \code filename != NULL \endcode
  87399. * \retval FLAC__bool
  87400. * \c false if a memory allocation error occurs, the file can't be
  87401. * opened, or another error occurs, else \c true.
  87402. */
  87403. 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);
  87404. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87405. * FLAC__metadata_simple_iterator_set_block() and
  87406. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87407. *
  87408. * \param iterator A pointer to an existing iterator.
  87409. * \assert
  87410. * \code iterator != NULL \endcode
  87411. * \retval FLAC__bool
  87412. * See above.
  87413. */
  87414. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87415. /** Moves the iterator forward one metadata block, returning \c false if
  87416. * already at the end.
  87417. *
  87418. * \param iterator A pointer to an existing initialized iterator.
  87419. * \assert
  87420. * \code iterator != NULL \endcode
  87421. * \a iterator has been successfully initialized with
  87422. * FLAC__metadata_simple_iterator_init()
  87423. * \retval FLAC__bool
  87424. * \c false if already at the last metadata block of the chain, else
  87425. * \c true.
  87426. */
  87427. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87428. /** Moves the iterator backward one metadata block, returning \c false if
  87429. * already at the beginning.
  87430. *
  87431. * \param iterator A pointer to an existing initialized iterator.
  87432. * \assert
  87433. * \code iterator != NULL \endcode
  87434. * \a iterator has been successfully initialized with
  87435. * FLAC__metadata_simple_iterator_init()
  87436. * \retval FLAC__bool
  87437. * \c false if already at the first metadata block of the chain, else
  87438. * \c true.
  87439. */
  87440. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87441. /** Returns a flag telling if the current metadata block is the last.
  87442. *
  87443. * \param iterator A pointer to an existing initialized iterator.
  87444. * \assert
  87445. * \code iterator != NULL \endcode
  87446. * \a iterator has been successfully initialized with
  87447. * FLAC__metadata_simple_iterator_init()
  87448. * \retval FLAC__bool
  87449. * \c true if the current metadata block is the last in the file,
  87450. * else \c false.
  87451. */
  87452. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87453. /** Get the offset of the metadata block at the current position. This
  87454. * avoids reading the actual block data which can save time for large
  87455. * blocks.
  87456. *
  87457. * \param iterator A pointer to an existing initialized iterator.
  87458. * \assert
  87459. * \code iterator != NULL \endcode
  87460. * \a iterator has been successfully initialized with
  87461. * FLAC__metadata_simple_iterator_init()
  87462. * \retval off_t
  87463. * The offset of the metadata block at the current iterator position.
  87464. * This is the byte offset relative to the beginning of the file of
  87465. * the current metadata block's header.
  87466. */
  87467. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87468. /** Get the type of the metadata block at the current position. This
  87469. * avoids reading the actual block data which can save time for large
  87470. * blocks.
  87471. *
  87472. * \param iterator A pointer to an existing initialized iterator.
  87473. * \assert
  87474. * \code iterator != NULL \endcode
  87475. * \a iterator has been successfully initialized with
  87476. * FLAC__metadata_simple_iterator_init()
  87477. * \retval FLAC__MetadataType
  87478. * The type of the metadata block at the current iterator position.
  87479. */
  87480. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87481. /** Get the length of the metadata block at the current position. This
  87482. * avoids reading the actual block data which can save time for large
  87483. * blocks.
  87484. *
  87485. * \param iterator A pointer to an existing initialized iterator.
  87486. * \assert
  87487. * \code iterator != NULL \endcode
  87488. * \a iterator has been successfully initialized with
  87489. * FLAC__metadata_simple_iterator_init()
  87490. * \retval unsigned
  87491. * The length of the metadata block at the current iterator position.
  87492. * The is same length as that in the
  87493. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87494. * i.e. the length of the metadata body that follows the header.
  87495. */
  87496. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87497. /** Get the application ID of the \c APPLICATION block at the current
  87498. * position. This avoids reading the actual block data which can save
  87499. * time for large blocks.
  87500. *
  87501. * \param iterator A pointer to an existing initialized iterator.
  87502. * \param id A pointer to a buffer of at least \c 4 bytes where
  87503. * the ID will be stored.
  87504. * \assert
  87505. * \code iterator != NULL \endcode
  87506. * \code id != NULL \endcode
  87507. * \a iterator has been successfully initialized with
  87508. * FLAC__metadata_simple_iterator_init()
  87509. * \retval FLAC__bool
  87510. * \c true if the ID was successfully read, else \c false, in which
  87511. * case you should check FLAC__metadata_simple_iterator_status() to
  87512. * find out why. If the status is
  87513. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87514. * current metadata block is not an \c APPLICATION block. Otherwise
  87515. * if the status is
  87516. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87517. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87518. * occurred and the iterator can no longer be used.
  87519. */
  87520. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87521. /** Get the metadata block at the current position. You can modify the
  87522. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87523. * write it back to the FLAC file.
  87524. *
  87525. * You must call FLAC__metadata_object_delete() on the returned object
  87526. * when you are finished with it.
  87527. *
  87528. * \param iterator A pointer to an existing initialized iterator.
  87529. * \assert
  87530. * \code iterator != NULL \endcode
  87531. * \a iterator has been successfully initialized with
  87532. * FLAC__metadata_simple_iterator_init()
  87533. * \retval FLAC__StreamMetadata*
  87534. * The current metadata block, or \c NULL if there was a memory
  87535. * allocation error.
  87536. */
  87537. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87538. /** Write a block back to the FLAC file. This function tries to be
  87539. * as efficient as possible; how the block is actually written is
  87540. * shown by the following:
  87541. *
  87542. * Existing block is a STREAMINFO block and the new block is a
  87543. * STREAMINFO block: the new block is written in place. Make sure
  87544. * you know what you're doing when changing the values of a
  87545. * STREAMINFO block.
  87546. *
  87547. * Existing block is a STREAMINFO block and the new block is a
  87548. * not a STREAMINFO block: this is an error since the first block
  87549. * must be a STREAMINFO block. Returns \c false without altering the
  87550. * file.
  87551. *
  87552. * Existing block is not a STREAMINFO block and the new block is a
  87553. * STREAMINFO block: this is an error since there may be only one
  87554. * STREAMINFO block. Returns \c false without altering the file.
  87555. *
  87556. * Existing block and new block are the same length: the existing
  87557. * block will be replaced by the new block, written in place.
  87558. *
  87559. * Existing block is longer than new block: if use_padding is \c true,
  87560. * the existing block will be overwritten in place with the new
  87561. * block followed by a PADDING block, if possible, to make the total
  87562. * size the same as the existing block. Remember that a padding
  87563. * block requires at least four bytes so if the difference in size
  87564. * between the new block and existing block is less than that, the
  87565. * entire file will have to be rewritten, using the new block's
  87566. * exact size. If use_padding is \c false, the entire file will be
  87567. * rewritten, replacing the existing block by the new block.
  87568. *
  87569. * Existing block is shorter than new block: if use_padding is \c true,
  87570. * the function will try and expand the new block into the following
  87571. * PADDING block, if it exists and doing so won't shrink the PADDING
  87572. * block to less than 4 bytes. If there is no following PADDING
  87573. * block, or it will shrink to less than 4 bytes, or use_padding is
  87574. * \c false, the entire file is rewritten, replacing the existing block
  87575. * with the new block. Note that in this case any following PADDING
  87576. * block is preserved as is.
  87577. *
  87578. * After writing the block, the iterator will remain in the same
  87579. * place, i.e. pointing to the new block.
  87580. *
  87581. * \param iterator A pointer to an existing initialized iterator.
  87582. * \param block The block to set.
  87583. * \param use_padding See above.
  87584. * \assert
  87585. * \code iterator != NULL \endcode
  87586. * \a iterator has been successfully initialized with
  87587. * FLAC__metadata_simple_iterator_init()
  87588. * \code block != NULL \endcode
  87589. * \retval FLAC__bool
  87590. * \c true if successful, else \c false.
  87591. */
  87592. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87593. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87594. * except that instead of writing over an existing block, it appends
  87595. * a block after the existing block. \a use_padding is again used to
  87596. * tell the function to try an expand into following padding in an
  87597. * attempt to avoid rewriting the entire file.
  87598. *
  87599. * This function will fail and return \c false if given a STREAMINFO
  87600. * block.
  87601. *
  87602. * After writing the block, the iterator will be pointing to the
  87603. * new block.
  87604. *
  87605. * \param iterator A pointer to an existing initialized iterator.
  87606. * \param block The block to set.
  87607. * \param use_padding See above.
  87608. * \assert
  87609. * \code iterator != NULL \endcode
  87610. * \a iterator has been successfully initialized with
  87611. * FLAC__metadata_simple_iterator_init()
  87612. * \code block != NULL \endcode
  87613. * \retval FLAC__bool
  87614. * \c true if successful, else \c false.
  87615. */
  87616. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87617. /** Deletes the block at the current position. This will cause the
  87618. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87619. * in which case the block will be replaced by an equal-sized PADDING
  87620. * block. The iterator will be left pointing to the block before the
  87621. * one just deleted.
  87622. *
  87623. * You may not delete the STREAMINFO block.
  87624. *
  87625. * \param iterator A pointer to an existing initialized iterator.
  87626. * \param use_padding See above.
  87627. * \assert
  87628. * \code iterator != NULL \endcode
  87629. * \a iterator has been successfully initialized with
  87630. * FLAC__metadata_simple_iterator_init()
  87631. * \retval FLAC__bool
  87632. * \c true if successful, else \c false.
  87633. */
  87634. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87635. /* \} */
  87636. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87637. * \ingroup flac_metadata
  87638. *
  87639. * \brief
  87640. * The level 2 interface provides read-write access to FLAC file metadata;
  87641. * all metadata is read into memory, operated on in memory, and then written
  87642. * to file, which is more efficient than level 1 when editing multiple blocks.
  87643. *
  87644. * Currently Ogg FLAC is supported for read only, via
  87645. * FLAC__metadata_chain_read_ogg() but a subsequent
  87646. * FLAC__metadata_chain_write() will fail.
  87647. *
  87648. * The general usage of this interface is:
  87649. *
  87650. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87651. * linked list of FLAC metadata blocks.
  87652. * - Read all metadata into the the chain from a FLAC file using
  87653. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87654. * check the status.
  87655. * - Optionally, consolidate the padding using
  87656. * FLAC__metadata_chain_merge_padding() or
  87657. * FLAC__metadata_chain_sort_padding().
  87658. * - Create a new iterator using FLAC__metadata_iterator_new()
  87659. * - Initialize the iterator to point to the first element in the chain
  87660. * using FLAC__metadata_iterator_init()
  87661. * - Traverse the chain using FLAC__metadata_iterator_next and
  87662. * FLAC__metadata_iterator_prev().
  87663. * - Get a block for reading or modification using
  87664. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87665. * inside the chain is returned, so the block is yours to modify.
  87666. * Changes will be reflected in the FLAC file when you write the
  87667. * chain. You can also add and delete blocks (see functions below).
  87668. * - When done, write out the chain using FLAC__metadata_chain_write().
  87669. * Make sure to read the whole comment to the function below.
  87670. * - Delete the chain using FLAC__metadata_chain_delete().
  87671. *
  87672. * \note
  87673. * Even though the FLAC file is not open while the chain is being
  87674. * manipulated, you must not alter the file externally during
  87675. * this time. The chain assumes the FLAC file will not change
  87676. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  87677. * and FLAC__metadata_chain_write().
  87678. *
  87679. * \note
  87680. * Do not modify the is_last, length, or type fields of returned
  87681. * FLAC__StreamMetadata objects. These are managed automatically.
  87682. *
  87683. * \note
  87684. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  87685. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  87686. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  87687. * become owned by the chain and they will be deleted when the chain is
  87688. * deleted.
  87689. *
  87690. * \{
  87691. */
  87692. struct FLAC__Metadata_Chain;
  87693. /** The opaque structure definition for the level 2 chain type.
  87694. */
  87695. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  87696. struct FLAC__Metadata_Iterator;
  87697. /** The opaque structure definition for the level 2 iterator type.
  87698. */
  87699. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  87700. typedef enum {
  87701. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  87702. /**< The chain is in the normal OK state */
  87703. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  87704. /**< The data passed into a function violated the function's usage criteria */
  87705. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  87706. /**< The chain could not open the target file */
  87707. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  87708. /**< The chain could not find the FLAC signature at the start of the file */
  87709. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  87710. /**< The chain tried to write to a file that was not writable */
  87711. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  87712. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  87713. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  87714. /**< The chain encountered an error while reading the FLAC file */
  87715. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  87716. /**< The chain encountered an error while seeking in the FLAC file */
  87717. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  87718. /**< The chain encountered an error while writing the FLAC file */
  87719. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  87720. /**< The chain encountered an error renaming the FLAC file */
  87721. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  87722. /**< The chain encountered an error removing the temporary file */
  87723. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  87724. /**< Memory allocation failed */
  87725. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  87726. /**< The caller violated an assertion or an unexpected error occurred */
  87727. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  87728. /**< One or more of the required callbacks was NULL */
  87729. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  87730. /**< FLAC__metadata_chain_write() was called on a chain read by
  87731. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87732. * or
  87733. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  87734. * was called on a chain read by
  87735. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87736. * Matching read/write methods must always be used. */
  87737. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  87738. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  87739. * chain write requires a tempfile; use
  87740. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  87741. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  87742. * called when the chain write does not require a tempfile; use
  87743. * FLAC__metadata_chain_write_with_callbacks() instead.
  87744. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  87745. * before writing via callbacks. */
  87746. } FLAC__Metadata_ChainStatus;
  87747. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  87748. *
  87749. * Using a FLAC__Metadata_ChainStatus as the index to this array
  87750. * will give the string equivalent. The contents should not be modified.
  87751. */
  87752. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  87753. /*********** FLAC__Metadata_Chain ***********/
  87754. /** Create a new chain instance.
  87755. *
  87756. * \retval FLAC__Metadata_Chain*
  87757. * \c NULL if there was an error allocating memory, else the new instance.
  87758. */
  87759. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  87760. /** Free a chain instance. Deletes the object pointed to by \a chain.
  87761. *
  87762. * \param chain A pointer to an existing chain.
  87763. * \assert
  87764. * \code chain != NULL \endcode
  87765. */
  87766. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  87767. /** Get the current status of the chain. Call this after a function
  87768. * returns \c false to get the reason for the error. Also resets the
  87769. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  87770. *
  87771. * \param chain A pointer to an existing chain.
  87772. * \assert
  87773. * \code chain != NULL \endcode
  87774. * \retval FLAC__Metadata_ChainStatus
  87775. * The current status of the chain.
  87776. */
  87777. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  87778. /** Read all metadata from a FLAC file into the chain.
  87779. *
  87780. * \param chain A pointer to an existing chain.
  87781. * \param filename The path to the FLAC file to read.
  87782. * \assert
  87783. * \code chain != NULL \endcode
  87784. * \code filename != NULL \endcode
  87785. * \retval FLAC__bool
  87786. * \c true if a valid list of metadata blocks was read from
  87787. * \a filename, else \c false. On failure, check the status with
  87788. * FLAC__metadata_chain_status().
  87789. */
  87790. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  87791. /** Read all metadata from an Ogg FLAC file into the chain.
  87792. *
  87793. * \note Ogg FLAC metadata data writing is not supported yet and
  87794. * FLAC__metadata_chain_write() will fail.
  87795. *
  87796. * \param chain A pointer to an existing chain.
  87797. * \param filename The path to the Ogg FLAC file to read.
  87798. * \assert
  87799. * \code chain != NULL \endcode
  87800. * \code filename != NULL \endcode
  87801. * \retval FLAC__bool
  87802. * \c true if a valid list of metadata blocks was read from
  87803. * \a filename, else \c false. On failure, check the status with
  87804. * FLAC__metadata_chain_status().
  87805. */
  87806. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  87807. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  87808. *
  87809. * The \a handle need only be open for reading, but must be seekable.
  87810. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87811. * for Windows).
  87812. *
  87813. * \param chain A pointer to an existing chain.
  87814. * \param handle The I/O handle of the FLAC stream to read. The
  87815. * handle will NOT be closed after the metadata is read;
  87816. * that is the duty of the caller.
  87817. * \param callbacks
  87818. * A set of callbacks to use for I/O. The mandatory
  87819. * callbacks are \a read, \a seek, and \a tell.
  87820. * \assert
  87821. * \code chain != NULL \endcode
  87822. * \retval FLAC__bool
  87823. * \c true if a valid list of metadata blocks was read from
  87824. * \a handle, else \c false. On failure, check the status with
  87825. * FLAC__metadata_chain_status().
  87826. */
  87827. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87828. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  87829. *
  87830. * The \a handle need only be open for reading, but must be seekable.
  87831. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87832. * for Windows).
  87833. *
  87834. * \note Ogg FLAC metadata data writing is not supported yet and
  87835. * FLAC__metadata_chain_write() will fail.
  87836. *
  87837. * \param chain A pointer to an existing chain.
  87838. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  87839. * handle will NOT be closed after the metadata is read;
  87840. * that is the duty of the caller.
  87841. * \param callbacks
  87842. * A set of callbacks to use for I/O. The mandatory
  87843. * callbacks are \a read, \a seek, and \a tell.
  87844. * \assert
  87845. * \code chain != NULL \endcode
  87846. * \retval FLAC__bool
  87847. * \c true if a valid list of metadata blocks was read from
  87848. * \a handle, else \c false. On failure, check the status with
  87849. * FLAC__metadata_chain_status().
  87850. */
  87851. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87852. /** Checks if writing the given chain would require the use of a
  87853. * temporary file, or if it could be written in place.
  87854. *
  87855. * Under certain conditions, padding can be utilized so that writing
  87856. * edited metadata back to the FLAC file does not require rewriting the
  87857. * entire file. If rewriting is required, then a temporary workfile is
  87858. * required. When writing metadata using callbacks, you must check
  87859. * this function to know whether to call
  87860. * FLAC__metadata_chain_write_with_callbacks() or
  87861. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  87862. * writing with FLAC__metadata_chain_write(), the temporary file is
  87863. * handled internally.
  87864. *
  87865. * \param chain A pointer to an existing chain.
  87866. * \param use_padding
  87867. * Whether or not padding will be allowed to be used
  87868. * during the write. The value of \a use_padding given
  87869. * here must match the value later passed to
  87870. * FLAC__metadata_chain_write_with_callbacks() or
  87871. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  87872. * \assert
  87873. * \code chain != NULL \endcode
  87874. * \retval FLAC__bool
  87875. * \c true if writing the current chain would require a tempfile, or
  87876. * \c false if metadata can be written in place.
  87877. */
  87878. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  87879. /** Write all metadata out to the FLAC file. This function tries to be as
  87880. * efficient as possible; how the metadata is actually written is shown by
  87881. * the following:
  87882. *
  87883. * If the current chain is the same size as the existing metadata, the new
  87884. * data is written in place.
  87885. *
  87886. * If the current chain is longer than the existing metadata, and
  87887. * \a use_padding is \c true, and the last block is a PADDING block of
  87888. * sufficient length, the function will truncate the final padding block
  87889. * so that the overall size of the metadata is the same as the existing
  87890. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  87891. * the above conditions are met, the entire FLAC file must be rewritten.
  87892. * If you want to use padding this way it is a good idea to call
  87893. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  87894. * amount of padding to work with, unless you need to preserve ordering
  87895. * of the PADDING blocks for some reason.
  87896. *
  87897. * If the current chain is shorter than the existing metadata, and
  87898. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  87899. * is extended to make the overall size the same as the existing data. If
  87900. * \a use_padding is \c true and the last block is not a PADDING block, a new
  87901. * PADDING block is added to the end of the new data to make it the same
  87902. * size as the existing data (if possible, see the note to
  87903. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  87904. * and the new data is written in place. If none of the above apply or
  87905. * \a use_padding is \c false, the entire FLAC file is rewritten.
  87906. *
  87907. * If \a preserve_file_stats is \c true, the owner and modification time will
  87908. * be preserved even if the FLAC file is written.
  87909. *
  87910. * For this write function to be used, the chain must have been read with
  87911. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  87912. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  87913. *
  87914. * \param chain A pointer to an existing chain.
  87915. * \param use_padding See above.
  87916. * \param preserve_file_stats See above.
  87917. * \assert
  87918. * \code chain != NULL \endcode
  87919. * \retval FLAC__bool
  87920. * \c true if the write succeeded, else \c false. On failure,
  87921. * check the status with FLAC__metadata_chain_status().
  87922. */
  87923. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  87924. /** Write all metadata out to a FLAC stream via callbacks.
  87925. *
  87926. * (See FLAC__metadata_chain_write() for the details on how padding is
  87927. * used to write metadata in place if possible.)
  87928. *
  87929. * The \a handle must be open for updating and be seekable. The
  87930. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  87931. * for Windows).
  87932. *
  87933. * For this write function to be used, the chain must have been read with
  87934. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87935. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87936. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87937. * \c false.
  87938. *
  87939. * \param chain A pointer to an existing chain.
  87940. * \param use_padding See FLAC__metadata_chain_write()
  87941. * \param handle The I/O handle of the FLAC stream to write. The
  87942. * handle will NOT be closed after the metadata is
  87943. * written; that is the duty of the caller.
  87944. * \param callbacks A set of callbacks to use for I/O. The mandatory
  87945. * callbacks are \a write and \a seek.
  87946. * \assert
  87947. * \code chain != NULL \endcode
  87948. * \retval FLAC__bool
  87949. * \c true if the write succeeded, else \c false. On failure,
  87950. * check the status with FLAC__metadata_chain_status().
  87951. */
  87952. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  87953. /** Write all metadata out to a FLAC stream via callbacks.
  87954. *
  87955. * (See FLAC__metadata_chain_write() for the details on how padding is
  87956. * used to write metadata in place if possible.)
  87957. *
  87958. * This version of the write-with-callbacks function must be used when
  87959. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  87960. * this function, you must supply an I/O handle corresponding to the
  87961. * FLAC file to edit, and a temporary handle to which the new FLAC
  87962. * file will be written. It is the caller's job to move this temporary
  87963. * FLAC file on top of the original FLAC file to complete the metadata
  87964. * edit.
  87965. *
  87966. * The \a handle must be open for reading and be seekable. The
  87967. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  87968. * for Windows).
  87969. *
  87970. * The \a temp_handle must be open for writing. The
  87971. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  87972. * for Windows). It should be an empty stream, or at least positioned
  87973. * at the start-of-file (in which case it is the caller's duty to
  87974. * truncate it on return).
  87975. *
  87976. * For this write function to be used, the chain must have been read with
  87977. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  87978. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  87979. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  87980. * \c true.
  87981. *
  87982. * \param chain A pointer to an existing chain.
  87983. * \param use_padding See FLAC__metadata_chain_write()
  87984. * \param handle The I/O handle of the original FLAC stream to read.
  87985. * The handle will NOT be closed after the metadata is
  87986. * written; that is the duty of the caller.
  87987. * \param callbacks A set of callbacks to use for I/O on \a handle.
  87988. * The mandatory callbacks are \a read, \a seek, and
  87989. * \a eof.
  87990. * \param temp_handle The I/O handle of the FLAC stream to write. The
  87991. * handle will NOT be closed after the metadata is
  87992. * written; that is the duty of the caller.
  87993. * \param temp_callbacks
  87994. * A set of callbacks to use for I/O on temp_handle.
  87995. * The only mandatory callback is \a write.
  87996. * \assert
  87997. * \code chain != NULL \endcode
  87998. * \retval FLAC__bool
  87999. * \c true if the write succeeded, else \c false. On failure,
  88000. * check the status with FLAC__metadata_chain_status().
  88001. */
  88002. 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);
  88003. /** Merge adjacent PADDING blocks into a single block.
  88004. *
  88005. * \note This function does not write to the FLAC file, it only
  88006. * modifies the chain.
  88007. *
  88008. * \warning Any iterator on the current chain will become invalid after this
  88009. * call. You should delete the iterator and get a new one.
  88010. *
  88011. * \param chain A pointer to an existing chain.
  88012. * \assert
  88013. * \code chain != NULL \endcode
  88014. */
  88015. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88016. /** This function will move all PADDING blocks to the end on the metadata,
  88017. * then merge them into a single block.
  88018. *
  88019. * \note This function does not write to the FLAC file, it only
  88020. * modifies the chain.
  88021. *
  88022. * \warning Any iterator on the current chain will become invalid after this
  88023. * call. You should delete the iterator and get a new one.
  88024. *
  88025. * \param chain A pointer to an existing chain.
  88026. * \assert
  88027. * \code chain != NULL \endcode
  88028. */
  88029. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88030. /*********** FLAC__Metadata_Iterator ***********/
  88031. /** Create a new iterator instance.
  88032. *
  88033. * \retval FLAC__Metadata_Iterator*
  88034. * \c NULL if there was an error allocating memory, else the new instance.
  88035. */
  88036. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88037. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88038. *
  88039. * \param iterator A pointer to an existing iterator.
  88040. * \assert
  88041. * \code iterator != NULL \endcode
  88042. */
  88043. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88044. /** Initialize the iterator to point to the first metadata block in the
  88045. * given chain.
  88046. *
  88047. * \param iterator A pointer to an existing iterator.
  88048. * \param chain A pointer to an existing and initialized (read) chain.
  88049. * \assert
  88050. * \code iterator != NULL \endcode
  88051. * \code chain != NULL \endcode
  88052. */
  88053. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88054. /** Moves the iterator forward one metadata block, returning \c false if
  88055. * already at the end.
  88056. *
  88057. * \param iterator A pointer to an existing initialized iterator.
  88058. * \assert
  88059. * \code iterator != NULL \endcode
  88060. * \a iterator has been successfully initialized with
  88061. * FLAC__metadata_iterator_init()
  88062. * \retval FLAC__bool
  88063. * \c false if already at the last metadata block of the chain, else
  88064. * \c true.
  88065. */
  88066. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88067. /** Moves the iterator backward one metadata block, returning \c false if
  88068. * already at the beginning.
  88069. *
  88070. * \param iterator A pointer to an existing initialized iterator.
  88071. * \assert
  88072. * \code iterator != NULL \endcode
  88073. * \a iterator has been successfully initialized with
  88074. * FLAC__metadata_iterator_init()
  88075. * \retval FLAC__bool
  88076. * \c false if already at the first metadata block of the chain, else
  88077. * \c true.
  88078. */
  88079. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88080. /** Get the type of the metadata block at the current position.
  88081. *
  88082. * \param iterator A pointer to an existing initialized iterator.
  88083. * \assert
  88084. * \code iterator != NULL \endcode
  88085. * \a iterator has been successfully initialized with
  88086. * FLAC__metadata_iterator_init()
  88087. * \retval FLAC__MetadataType
  88088. * The type of the metadata block at the current iterator position.
  88089. */
  88090. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88091. /** Get the metadata block at the current position. You can modify
  88092. * the block in place but must write the chain before the changes
  88093. * are reflected to the FLAC file. You do not need to call
  88094. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88095. * the pointer returned by FLAC__metadata_iterator_get_block()
  88096. * points directly into the chain.
  88097. *
  88098. * \warning
  88099. * Do not call FLAC__metadata_object_delete() on the returned object;
  88100. * to delete a block use FLAC__metadata_iterator_delete_block().
  88101. *
  88102. * \param iterator A pointer to an existing initialized iterator.
  88103. * \assert
  88104. * \code iterator != NULL \endcode
  88105. * \a iterator has been successfully initialized with
  88106. * FLAC__metadata_iterator_init()
  88107. * \retval FLAC__StreamMetadata*
  88108. * The current metadata block.
  88109. */
  88110. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88111. /** Set the metadata block at the current position, replacing the existing
  88112. * block. The new block passed in becomes owned by the chain and it will be
  88113. * deleted when the chain is deleted.
  88114. *
  88115. * \param iterator A pointer to an existing initialized iterator.
  88116. * \param block A pointer to a metadata block.
  88117. * \assert
  88118. * \code iterator != NULL \endcode
  88119. * \a iterator has been successfully initialized with
  88120. * FLAC__metadata_iterator_init()
  88121. * \code block != NULL \endcode
  88122. * \retval FLAC__bool
  88123. * \c false if the conditions in the above description are not met, or
  88124. * a memory allocation error occurs, otherwise \c true.
  88125. */
  88126. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88127. /** Removes the current block from the chain. If \a replace_with_padding is
  88128. * \c true, the block will instead be replaced with a padding block of equal
  88129. * size. You can not delete the STREAMINFO block. The iterator will be
  88130. * left pointing to the block before the one just "deleted", even if
  88131. * \a replace_with_padding is \c true.
  88132. *
  88133. * \param iterator A pointer to an existing initialized iterator.
  88134. * \param replace_with_padding See above.
  88135. * \assert
  88136. * \code iterator != NULL \endcode
  88137. * \a iterator has been successfully initialized with
  88138. * FLAC__metadata_iterator_init()
  88139. * \retval FLAC__bool
  88140. * \c false if the conditions in the above description are not met,
  88141. * otherwise \c true.
  88142. */
  88143. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88144. /** Insert a new block before the current block. You cannot insert a block
  88145. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88146. * as there can be only one, the one that already exists at the head when you
  88147. * read in a chain. The chain takes ownership of the new block and it will be
  88148. * deleted when the chain is deleted. The iterator will be left pointing to
  88149. * the new block.
  88150. *
  88151. * \param iterator A pointer to an existing initialized iterator.
  88152. * \param block A pointer to a metadata block to insert.
  88153. * \assert
  88154. * \code iterator != NULL \endcode
  88155. * \a iterator has been successfully initialized with
  88156. * FLAC__metadata_iterator_init()
  88157. * \retval FLAC__bool
  88158. * \c false if the conditions in the above description are not met, or
  88159. * a memory allocation error occurs, otherwise \c true.
  88160. */
  88161. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88162. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88163. * block as there can be only one, the one that already exists at the head when
  88164. * you read in a chain. The chain takes ownership of the new block and it will
  88165. * be deleted when the chain is deleted. The iterator will be left pointing to
  88166. * the new block.
  88167. *
  88168. * \param iterator A pointer to an existing initialized iterator.
  88169. * \param block A pointer to a metadata block to insert.
  88170. * \assert
  88171. * \code iterator != NULL \endcode
  88172. * \a iterator has been successfully initialized with
  88173. * FLAC__metadata_iterator_init()
  88174. * \retval FLAC__bool
  88175. * \c false if the conditions in the above description are not met, or
  88176. * a memory allocation error occurs, otherwise \c true.
  88177. */
  88178. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88179. /* \} */
  88180. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88181. * \ingroup flac_metadata
  88182. *
  88183. * \brief
  88184. * This module contains methods for manipulating FLAC metadata objects.
  88185. *
  88186. * Since many are variable length we have to be careful about the memory
  88187. * management. We decree that all pointers to data in the object are
  88188. * owned by the object and memory-managed by the object.
  88189. *
  88190. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88191. * functions to create all instances. When using the
  88192. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88193. * \a copy to \c true to have the function make it's own copy of the data, or
  88194. * to \c false to give the object ownership of your data. In the latter case
  88195. * your pointer must be freeable by free() and will be free()d when the object
  88196. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88197. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88198. * the length argument is 0 and the \a copy argument is \c false.
  88199. *
  88200. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88201. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88202. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88203. * case of a memory allocation error.
  88204. *
  88205. * We don't have the convenience of C++ here, so note that the library relies
  88206. * on you to keep the types straight. In other words, if you pass, for
  88207. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88208. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88209. * failure.
  88210. *
  88211. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88212. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88213. * toward the length or stored in the stream, but it can make working with plain
  88214. * comments (those that don't contain embedded-NULs in the value) easier.
  88215. * Entries passed into these functions have trailing NULs added if missing, and
  88216. * returned entries are guaranteed to have a trailing NUL.
  88217. *
  88218. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88219. * comment entry/name/value will first validate that it complies with the Vorbis
  88220. * comment specification and return false if it does not.
  88221. *
  88222. * There is no need to recalculate the length field on metadata blocks you
  88223. * have modified. They will be calculated automatically before they are
  88224. * written back to a file.
  88225. *
  88226. * \{
  88227. */
  88228. /** Create a new metadata object instance of the given type.
  88229. *
  88230. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88231. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88232. * the vendor string set (but zero comments).
  88233. *
  88234. * Do not pass in a value greater than or equal to
  88235. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88236. * doing.
  88237. *
  88238. * \param type Type of object to create
  88239. * \retval FLAC__StreamMetadata*
  88240. * \c NULL if there was an error allocating memory or the type code is
  88241. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88242. */
  88243. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88244. /** Create a copy of an existing metadata object.
  88245. *
  88246. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88247. * object is also copied. The caller takes ownership of the new block and
  88248. * is responsible for freeing it with FLAC__metadata_object_delete().
  88249. *
  88250. * \param object Pointer to object to copy.
  88251. * \assert
  88252. * \code object != NULL \endcode
  88253. * \retval FLAC__StreamMetadata*
  88254. * \c NULL if there was an error allocating memory, else the new instance.
  88255. */
  88256. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88257. /** Free a metadata object. Deletes the object pointed to by \a object.
  88258. *
  88259. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88260. * object is also deleted.
  88261. *
  88262. * \param object A pointer to an existing object.
  88263. * \assert
  88264. * \code object != NULL \endcode
  88265. */
  88266. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88267. /** Compares two metadata objects.
  88268. *
  88269. * The compare is "deep", i.e. dynamically allocated data within the
  88270. * object is also compared.
  88271. *
  88272. * \param block1 A pointer to an existing object.
  88273. * \param block2 A pointer to an existing object.
  88274. * \assert
  88275. * \code block1 != NULL \endcode
  88276. * \code block2 != NULL \endcode
  88277. * \retval FLAC__bool
  88278. * \c true if objects are identical, else \c false.
  88279. */
  88280. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88281. /** Sets the application data of an APPLICATION block.
  88282. *
  88283. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88284. * takes ownership of the pointer. The existing data will be freed if this
  88285. * function is successful, otherwise the original data will remain if \a copy
  88286. * is \c true and malloc() fails.
  88287. *
  88288. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88289. *
  88290. * \param object A pointer to an existing APPLICATION object.
  88291. * \param data A pointer to the data to set.
  88292. * \param length The length of \a data in bytes.
  88293. * \param copy See above.
  88294. * \assert
  88295. * \code object != NULL \endcode
  88296. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88297. * \code (data != NULL && length > 0) ||
  88298. * (data == NULL && length == 0 && copy == false) \endcode
  88299. * \retval FLAC__bool
  88300. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88301. */
  88302. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88303. /** Resize the seekpoint array.
  88304. *
  88305. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88306. * points will be added to the end.
  88307. *
  88308. * \param object A pointer to an existing SEEKTABLE object.
  88309. * \param new_num_points The desired length of the array; may be \c 0.
  88310. * \assert
  88311. * \code object != NULL \endcode
  88312. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88313. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88314. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88315. * \retval FLAC__bool
  88316. * \c false if memory allocation error, else \c true.
  88317. */
  88318. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88319. /** Set a seekpoint in a seektable.
  88320. *
  88321. * \param object A pointer to an existing SEEKTABLE object.
  88322. * \param point_num Index into seekpoint array to set.
  88323. * \param point The point to set.
  88324. * \assert
  88325. * \code object != NULL \endcode
  88326. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88327. * \code object->data.seek_table.num_points > point_num \endcode
  88328. */
  88329. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88330. /** Insert a seekpoint into a seektable.
  88331. *
  88332. * \param object A pointer to an existing SEEKTABLE object.
  88333. * \param point_num Index into seekpoint array to set.
  88334. * \param point The point to set.
  88335. * \assert
  88336. * \code object != NULL \endcode
  88337. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88338. * \code object->data.seek_table.num_points >= point_num \endcode
  88339. * \retval FLAC__bool
  88340. * \c false if memory allocation error, else \c true.
  88341. */
  88342. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88343. /** Delete a seekpoint from a seektable.
  88344. *
  88345. * \param object A pointer to an existing SEEKTABLE object.
  88346. * \param point_num Index into seekpoint array to set.
  88347. * \assert
  88348. * \code object != NULL \endcode
  88349. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88350. * \code object->data.seek_table.num_points > point_num \endcode
  88351. * \retval FLAC__bool
  88352. * \c false if memory allocation error, else \c true.
  88353. */
  88354. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88355. /** Check a seektable to see if it conforms to the FLAC specification.
  88356. * See the format specification for limits on the contents of the
  88357. * seektable.
  88358. *
  88359. * \param object A pointer to an existing SEEKTABLE object.
  88360. * \assert
  88361. * \code object != NULL \endcode
  88362. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88363. * \retval FLAC__bool
  88364. * \c false if seek table is illegal, else \c true.
  88365. */
  88366. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88367. /** Append a number of placeholder points to the end of a seek table.
  88368. *
  88369. * \note
  88370. * As with the other ..._seektable_template_... functions, you should
  88371. * call FLAC__metadata_object_seektable_template_sort() when finished
  88372. * to make the seek table legal.
  88373. *
  88374. * \param object A pointer to an existing SEEKTABLE object.
  88375. * \param num The number of placeholder points to append.
  88376. * \assert
  88377. * \code object != NULL \endcode
  88378. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88379. * \retval FLAC__bool
  88380. * \c false if memory allocation fails, else \c true.
  88381. */
  88382. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88383. /** Append a specific seek point template to the end of a seek table.
  88384. *
  88385. * \note
  88386. * As with the other ..._seektable_template_... functions, you should
  88387. * call FLAC__metadata_object_seektable_template_sort() when finished
  88388. * to make the seek table legal.
  88389. *
  88390. * \param object A pointer to an existing SEEKTABLE object.
  88391. * \param sample_number The sample number of the seek point template.
  88392. * \assert
  88393. * \code object != NULL \endcode
  88394. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88395. * \retval FLAC__bool
  88396. * \c false if memory allocation fails, else \c true.
  88397. */
  88398. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88399. /** Append specific seek point templates to the end of a seek table.
  88400. *
  88401. * \note
  88402. * As with the other ..._seektable_template_... functions, you should
  88403. * call FLAC__metadata_object_seektable_template_sort() when finished
  88404. * to make the seek table legal.
  88405. *
  88406. * \param object A pointer to an existing SEEKTABLE object.
  88407. * \param sample_numbers An array of sample numbers for the seek points.
  88408. * \param num The number of seek point templates to append.
  88409. * \assert
  88410. * \code object != NULL \endcode
  88411. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88412. * \retval FLAC__bool
  88413. * \c false if memory allocation fails, else \c true.
  88414. */
  88415. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88416. /** Append a set of evenly-spaced seek point templates to the end of a
  88417. * seek table.
  88418. *
  88419. * \note
  88420. * As with the other ..._seektable_template_... functions, you should
  88421. * call FLAC__metadata_object_seektable_template_sort() when finished
  88422. * to make the seek table legal.
  88423. *
  88424. * \param object A pointer to an existing SEEKTABLE object.
  88425. * \param num The number of placeholder points to append.
  88426. * \param total_samples The total number of samples to be encoded;
  88427. * the seekpoints will be spaced approximately
  88428. * \a total_samples / \a num samples apart.
  88429. * \assert
  88430. * \code object != NULL \endcode
  88431. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88432. * \code total_samples > 0 \endcode
  88433. * \retval FLAC__bool
  88434. * \c false if memory allocation fails, else \c true.
  88435. */
  88436. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88437. /** Append a set of evenly-spaced seek point templates to the end of a
  88438. * seek table.
  88439. *
  88440. * \note
  88441. * As with the other ..._seektable_template_... functions, you should
  88442. * call FLAC__metadata_object_seektable_template_sort() when finished
  88443. * to make the seek table legal.
  88444. *
  88445. * \param object A pointer to an existing SEEKTABLE object.
  88446. * \param samples The number of samples apart to space the placeholder
  88447. * points. The first point will be at sample \c 0, the
  88448. * second at sample \a samples, then 2*\a samples, and
  88449. * so on. As long as \a samples and \a total_samples
  88450. * are greater than \c 0, there will always be at least
  88451. * one seekpoint at sample \c 0.
  88452. * \param total_samples The total number of samples to be encoded;
  88453. * the seekpoints will be spaced
  88454. * \a samples samples apart.
  88455. * \assert
  88456. * \code object != NULL \endcode
  88457. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88458. * \code samples > 0 \endcode
  88459. * \code total_samples > 0 \endcode
  88460. * \retval FLAC__bool
  88461. * \c false if memory allocation fails, else \c true.
  88462. */
  88463. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88464. /** Sort a seek table's seek points according to the format specification,
  88465. * removing duplicates.
  88466. *
  88467. * \param object A pointer to a seek table to be sorted.
  88468. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88469. * If \c true, duplicates are deleted and the seek table is
  88470. * shrunk appropriately; the number of placeholder points
  88471. * present in the seek table will be the same after the call
  88472. * as before.
  88473. * \assert
  88474. * \code object != NULL \endcode
  88475. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88476. * \retval FLAC__bool
  88477. * \c false if realloc() fails, else \c true.
  88478. */
  88479. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88480. /** Sets the vendor string in a VORBIS_COMMENT block.
  88481. *
  88482. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88483. * one already.
  88484. *
  88485. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88486. * takes ownership of the \c entry.entry pointer.
  88487. *
  88488. * \note If this function returns \c false, the caller still owns the
  88489. * pointer.
  88490. *
  88491. * \param object A pointer to an existing VORBIS_COMMENT object.
  88492. * \param entry The entry to set the vendor string to.
  88493. * \param copy See above.
  88494. * \assert
  88495. * \code object != NULL \endcode
  88496. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88497. * \code (entry.entry != NULL && entry.length > 0) ||
  88498. * (entry.entry == NULL && entry.length == 0) \endcode
  88499. * \retval FLAC__bool
  88500. * \c false if memory allocation fails or \a entry does not comply with the
  88501. * Vorbis comment specification, else \c true.
  88502. */
  88503. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88504. /** Resize the comment array.
  88505. *
  88506. * If the size shrinks, elements will truncated; if it grows, new empty
  88507. * fields will be added to the end.
  88508. *
  88509. * \param object A pointer to an existing VORBIS_COMMENT object.
  88510. * \param new_num_comments The desired length of the array; may be \c 0.
  88511. * \assert
  88512. * \code object != NULL \endcode
  88513. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88514. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88515. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88516. * \retval FLAC__bool
  88517. * \c false if memory allocation fails, else \c true.
  88518. */
  88519. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88520. /** Sets a comment in a VORBIS_COMMENT block.
  88521. *
  88522. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88523. * one already.
  88524. *
  88525. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88526. * takes ownership of the \c entry.entry pointer.
  88527. *
  88528. * \note If this function returns \c false, the caller still owns the
  88529. * pointer.
  88530. *
  88531. * \param object A pointer to an existing VORBIS_COMMENT object.
  88532. * \param comment_num Index into comment array to set.
  88533. * \param entry The entry to set the comment to.
  88534. * \param copy See above.
  88535. * \assert
  88536. * \code object != NULL \endcode
  88537. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88538. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88539. * \code (entry.entry != NULL && entry.length > 0) ||
  88540. * (entry.entry == NULL && entry.length == 0) \endcode
  88541. * \retval FLAC__bool
  88542. * \c false if memory allocation fails or \a entry does not comply with the
  88543. * Vorbis comment specification, else \c true.
  88544. */
  88545. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88546. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88547. *
  88548. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88549. * one already.
  88550. *
  88551. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88552. * takes ownership of the \c entry.entry pointer.
  88553. *
  88554. * \note If this function returns \c false, the caller still owns the
  88555. * pointer.
  88556. *
  88557. * \param object A pointer to an existing VORBIS_COMMENT object.
  88558. * \param comment_num The index at which to insert the comment. The comments
  88559. * at and after \a comment_num move right one position.
  88560. * To append a comment to the end, set \a comment_num to
  88561. * \c object->data.vorbis_comment.num_comments .
  88562. * \param entry The comment to insert.
  88563. * \param copy See above.
  88564. * \assert
  88565. * \code object != NULL \endcode
  88566. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88567. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88568. * \code (entry.entry != NULL && entry.length > 0) ||
  88569. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88570. * \retval FLAC__bool
  88571. * \c false if memory allocation fails or \a entry does not comply with the
  88572. * Vorbis comment specification, else \c true.
  88573. */
  88574. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88575. /** Appends a comment to a VORBIS_COMMENT block.
  88576. *
  88577. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88578. * one already.
  88579. *
  88580. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88581. * takes ownership of the \c entry.entry pointer.
  88582. *
  88583. * \note If this function returns \c false, the caller still owns the
  88584. * pointer.
  88585. *
  88586. * \param object A pointer to an existing VORBIS_COMMENT object.
  88587. * \param entry The comment to insert.
  88588. * \param copy See above.
  88589. * \assert
  88590. * \code object != NULL \endcode
  88591. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88592. * \code (entry.entry != NULL && entry.length > 0) ||
  88593. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88594. * \retval FLAC__bool
  88595. * \c false if memory allocation fails or \a entry does not comply with the
  88596. * Vorbis comment specification, else \c true.
  88597. */
  88598. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88599. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88600. *
  88601. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88602. * one already.
  88603. *
  88604. * Depending on the the value of \a all, either all or just the first comment
  88605. * whose field name(s) match the given entry's name will be replaced by the
  88606. * given entry. If no comments match, \a entry will simply be appended.
  88607. *
  88608. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88609. * takes ownership of the \c entry.entry pointer.
  88610. *
  88611. * \note If this function returns \c false, the caller still owns the
  88612. * pointer.
  88613. *
  88614. * \param object A pointer to an existing VORBIS_COMMENT object.
  88615. * \param entry The comment to insert.
  88616. * \param all If \c true, all comments whose field name matches
  88617. * \a entry's field name will be removed, and \a entry will
  88618. * be inserted at the position of the first matching
  88619. * comment. If \c false, only the first comment whose
  88620. * field name matches \a entry's field name will be
  88621. * replaced with \a entry.
  88622. * \param copy See above.
  88623. * \assert
  88624. * \code object != NULL \endcode
  88625. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88626. * \code (entry.entry != NULL && entry.length > 0) ||
  88627. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88628. * \retval FLAC__bool
  88629. * \c false if memory allocation fails or \a entry does not comply with the
  88630. * Vorbis comment specification, else \c true.
  88631. */
  88632. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88633. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88634. *
  88635. * \param object A pointer to an existing VORBIS_COMMENT object.
  88636. * \param comment_num The index of the comment to delete.
  88637. * \assert
  88638. * \code object != NULL \endcode
  88639. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88640. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88641. * \retval FLAC__bool
  88642. * \c false if realloc() fails, else \c true.
  88643. */
  88644. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88645. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88646. *
  88647. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88648. * memory and shall be owned by the caller. For convenience the entry will
  88649. * have a terminating NUL.
  88650. *
  88651. * \param entry A pointer to a Vorbis comment entry. The entry's
  88652. * \c entry pointer should not point to allocated
  88653. * memory as it will be overwritten.
  88654. * \param field_name The field name in ASCII, \c NUL terminated.
  88655. * \param field_value The field value in UTF-8, \c NUL terminated.
  88656. * \assert
  88657. * \code entry != NULL \endcode
  88658. * \code field_name != NULL \endcode
  88659. * \code field_value != NULL \endcode
  88660. * \retval FLAC__bool
  88661. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88662. * not comply with the Vorbis comment specification, else \c true.
  88663. */
  88664. 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);
  88665. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88666. *
  88667. * The returned pointers to name and value will be allocated by malloc()
  88668. * and shall be owned by the caller.
  88669. *
  88670. * \param entry An existing Vorbis comment entry.
  88671. * \param field_name The address of where the returned pointer to the
  88672. * field name will be stored.
  88673. * \param field_value The address of where the returned pointer to the
  88674. * field value will be stored.
  88675. * \assert
  88676. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88677. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  88678. * \code field_name != NULL \endcode
  88679. * \code field_value != NULL \endcode
  88680. * \retval FLAC__bool
  88681. * \c false if memory allocation fails or \a entry does not comply with the
  88682. * Vorbis comment specification, else \c true.
  88683. */
  88684. 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);
  88685. /** Check if the given Vorbis comment entry's field name matches the given
  88686. * field name.
  88687. *
  88688. * \param entry An existing Vorbis comment entry.
  88689. * \param field_name The field name to check.
  88690. * \param field_name_length The length of \a field_name, not including the
  88691. * terminating \c NUL.
  88692. * \assert
  88693. * \code (entry.entry != NULL && entry.length > 0) \endcode
  88694. * \retval FLAC__bool
  88695. * \c true if the field names match, else \c false
  88696. */
  88697. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  88698. /** Find a Vorbis comment with the given field name.
  88699. *
  88700. * The search begins at entry number \a offset; use an offset of 0 to
  88701. * search from the beginning of the comment array.
  88702. *
  88703. * \param object A pointer to an existing VORBIS_COMMENT object.
  88704. * \param offset The offset into the comment array from where to start
  88705. * the search.
  88706. * \param field_name The field name of the comment to find.
  88707. * \assert
  88708. * \code object != NULL \endcode
  88709. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88710. * \code field_name != NULL \endcode
  88711. * \retval int
  88712. * The offset in the comment array of the first comment whose field
  88713. * name matches \a field_name, or \c -1 if no match was found.
  88714. */
  88715. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  88716. /** Remove first Vorbis comment matching the given field name.
  88717. *
  88718. * \param object A pointer to an existing VORBIS_COMMENT object.
  88719. * \param field_name The field name of comment to delete.
  88720. * \assert
  88721. * \code object != NULL \endcode
  88722. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88723. * \retval int
  88724. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88725. * \c 1 for one matching entry deleted.
  88726. */
  88727. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  88728. /** Remove all Vorbis comments matching the given field name.
  88729. *
  88730. * \param object A pointer to an existing VORBIS_COMMENT object.
  88731. * \param field_name The field name of comments to delete.
  88732. * \assert
  88733. * \code object != NULL \endcode
  88734. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88735. * \retval int
  88736. * \c -1 for memory allocation error, \c 0 for no matching entries,
  88737. * else the number of matching entries deleted.
  88738. */
  88739. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  88740. /** Create a new CUESHEET track instance.
  88741. *
  88742. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  88743. *
  88744. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88745. * \c NULL if there was an error allocating memory, else the new instance.
  88746. */
  88747. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  88748. /** Create a copy of an existing CUESHEET track object.
  88749. *
  88750. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88751. * object is also copied. The caller takes ownership of the new object and
  88752. * is responsible for freeing it with
  88753. * FLAC__metadata_object_cuesheet_track_delete().
  88754. *
  88755. * \param object Pointer to object to copy.
  88756. * \assert
  88757. * \code object != NULL \endcode
  88758. * \retval FLAC__StreamMetadata_CueSheet_Track*
  88759. * \c NULL if there was an error allocating memory, else the new instance.
  88760. */
  88761. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  88762. /** Delete a CUESHEET track object
  88763. *
  88764. * \param object A pointer to an existing CUESHEET track object.
  88765. * \assert
  88766. * \code object != NULL \endcode
  88767. */
  88768. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  88769. /** Resize a track's index point array.
  88770. *
  88771. * If the size shrinks, elements will truncated; if it grows, new blank
  88772. * indices will be added to the end.
  88773. *
  88774. * \param object A pointer to an existing CUESHEET object.
  88775. * \param track_num The index of the track to modify. NOTE: this is not
  88776. * necessarily the same as the track's \a number field.
  88777. * \param new_num_indices The desired length of the array; may be \c 0.
  88778. * \assert
  88779. * \code object != NULL \endcode
  88780. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88781. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88782. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  88783. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  88784. * \retval FLAC__bool
  88785. * \c false if memory allocation error, else \c true.
  88786. */
  88787. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  88788. /** Insert an index point in a CUESHEET track at the given index.
  88789. *
  88790. * \param object A pointer to an existing CUESHEET object.
  88791. * \param track_num The index of the track to modify. NOTE: this is not
  88792. * necessarily the same as the track's \a number field.
  88793. * \param index_num The index into the track's index array at which to
  88794. * insert the index point. NOTE: this is not necessarily
  88795. * the same as the index point's \a number field. The
  88796. * indices at and after \a index_num move right one
  88797. * position. To append an index point to the end, set
  88798. * \a index_num to
  88799. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88800. * \param index The index point to insert.
  88801. * \assert
  88802. * \code object != NULL \endcode
  88803. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88804. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88805. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88806. * \retval FLAC__bool
  88807. * \c false if realloc() fails, else \c true.
  88808. */
  88809. 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);
  88810. /** Insert a blank index point in a CUESHEET track at the given index.
  88811. *
  88812. * A blank index point is one in which all field values are zero.
  88813. *
  88814. * \param object A pointer to an existing CUESHEET object.
  88815. * \param track_num The index of the track to modify. NOTE: this is not
  88816. * necessarily the same as the track's \a number field.
  88817. * \param index_num The index into the track's index array at which to
  88818. * insert the index point. NOTE: this is not necessarily
  88819. * the same as the index point's \a number field. The
  88820. * indices at and after \a index_num move right one
  88821. * position. To append an index point to the end, set
  88822. * \a index_num to
  88823. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  88824. * \assert
  88825. * \code object != NULL \endcode
  88826. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88827. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88828. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  88829. * \retval FLAC__bool
  88830. * \c false if realloc() fails, else \c true.
  88831. */
  88832. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88833. /** Delete an index point in a CUESHEET track at the given index.
  88834. *
  88835. * \param object A pointer to an existing CUESHEET object.
  88836. * \param track_num The index into the track array of the track to
  88837. * modify. NOTE: this is not necessarily the same
  88838. * as the track's \a number field.
  88839. * \param index_num The index into the track's index array of the index
  88840. * to delete. NOTE: this is not necessarily the same
  88841. * as the index's \a number field.
  88842. * \assert
  88843. * \code object != NULL \endcode
  88844. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88845. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88846. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  88847. * \retval FLAC__bool
  88848. * \c false if realloc() fails, else \c true.
  88849. */
  88850. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  88851. /** Resize the track array.
  88852. *
  88853. * If the size shrinks, elements will truncated; if it grows, new blank
  88854. * tracks will be added to the end.
  88855. *
  88856. * \param object A pointer to an existing CUESHEET object.
  88857. * \param new_num_tracks The desired length of the array; may be \c 0.
  88858. * \assert
  88859. * \code object != NULL \endcode
  88860. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88861. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  88862. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  88863. * \retval FLAC__bool
  88864. * \c false if memory allocation error, else \c true.
  88865. */
  88866. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  88867. /** Sets a track in a CUESHEET block.
  88868. *
  88869. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88870. * takes ownership of the \a track pointer.
  88871. *
  88872. * \param object A pointer to an existing CUESHEET object.
  88873. * \param track_num Index into track array to set. NOTE: this is not
  88874. * necessarily the same as the track's \a number field.
  88875. * \param track The track to set the track to. You may safely pass in
  88876. * a const pointer if \a copy is \c true.
  88877. * \param copy See above.
  88878. * \assert
  88879. * \code object != NULL \endcode
  88880. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88881. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  88882. * \code (track->indices != NULL && track->num_indices > 0) ||
  88883. * (track->indices == NULL && track->num_indices == 0)
  88884. * \retval FLAC__bool
  88885. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88886. */
  88887. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88888. /** Insert a track in a CUESHEET block at the given index.
  88889. *
  88890. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  88891. * takes ownership of the \a track pointer.
  88892. *
  88893. * \param object A pointer to an existing CUESHEET object.
  88894. * \param track_num The index at which to insert the track. NOTE: this
  88895. * is not necessarily the same as the track's \a number
  88896. * field. The tracks at and after \a track_num move right
  88897. * one position. To append a track to the end, set
  88898. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88899. * \param track The track to insert. You may safely pass in a const
  88900. * pointer if \a copy is \c true.
  88901. * \param copy See above.
  88902. * \assert
  88903. * \code object != NULL \endcode
  88904. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88905. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88906. * \retval FLAC__bool
  88907. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88908. */
  88909. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  88910. /** Insert a blank track in a CUESHEET block at the given index.
  88911. *
  88912. * A blank track is one in which all field values are zero.
  88913. *
  88914. * \param object A pointer to an existing CUESHEET object.
  88915. * \param track_num The index at which to insert the track. NOTE: this
  88916. * is not necessarily the same as the track's \a number
  88917. * field. The tracks at and after \a track_num move right
  88918. * one position. To append a track to the end, set
  88919. * \a track_num to \c object->data.cue_sheet.num_tracks .
  88920. * \assert
  88921. * \code object != NULL \endcode
  88922. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88923. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  88924. * \retval FLAC__bool
  88925. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88926. */
  88927. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  88928. /** Delete a track in a CUESHEET block at the given index.
  88929. *
  88930. * \param object A pointer to an existing CUESHEET object.
  88931. * \param track_num The index into the track array of the track to
  88932. * delete. NOTE: this is not necessarily the same
  88933. * as the track's \a number field.
  88934. * \assert
  88935. * \code object != NULL \endcode
  88936. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88937. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  88938. * \retval FLAC__bool
  88939. * \c false if realloc() fails, else \c true.
  88940. */
  88941. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  88942. /** Check a cue sheet to see if it conforms to the FLAC specification.
  88943. * See the format specification for limits on the contents of the
  88944. * cue sheet.
  88945. *
  88946. * \param object A pointer to an existing CUESHEET object.
  88947. * \param check_cd_da_subset If \c true, check CUESHEET against more
  88948. * stringent requirements for a CD-DA (audio) disc.
  88949. * \param violation Address of a pointer to a string. If there is a
  88950. * violation, a pointer to a string explanation of the
  88951. * violation will be returned here. \a violation may be
  88952. * \c NULL if you don't need the returned string. Do not
  88953. * free the returned string; it will always point to static
  88954. * data.
  88955. * \assert
  88956. * \code object != NULL \endcode
  88957. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88958. * \retval FLAC__bool
  88959. * \c false if cue sheet is illegal, else \c true.
  88960. */
  88961. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  88962. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  88963. * assumes the cue sheet corresponds to a CD; the result is undefined
  88964. * if the cuesheet's is_cd bit is not set.
  88965. *
  88966. * \param object A pointer to an existing CUESHEET object.
  88967. * \assert
  88968. * \code object != NULL \endcode
  88969. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  88970. * \retval FLAC__uint32
  88971. * The unsigned integer representation of the CDDB/freedb ID
  88972. */
  88973. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  88974. /** Sets the MIME type of a PICTURE block.
  88975. *
  88976. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88977. * takes ownership of the pointer. The existing string will be freed if this
  88978. * function is successful, otherwise the original string will remain if \a copy
  88979. * is \c true and malloc() fails.
  88980. *
  88981. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  88982. *
  88983. * \param object A pointer to an existing PICTURE object.
  88984. * \param mime_type A pointer to the MIME type string. The string must be
  88985. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  88986. * is done.
  88987. * \param copy See above.
  88988. * \assert
  88989. * \code object != NULL \endcode
  88990. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  88991. * \code (mime_type != NULL) \endcode
  88992. * \retval FLAC__bool
  88993. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88994. */
  88995. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  88996. /** Sets the description of a PICTURE block.
  88997. *
  88998. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  88999. * takes ownership of the pointer. The existing string will be freed if this
  89000. * function is successful, otherwise the original string will remain if \a copy
  89001. * is \c true and malloc() fails.
  89002. *
  89003. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89004. *
  89005. * \param object A pointer to an existing PICTURE object.
  89006. * \param description A pointer to the description string. The string must be
  89007. * valid UTF-8, NUL-terminated. No validation is done.
  89008. * \param copy See above.
  89009. * \assert
  89010. * \code object != NULL \endcode
  89011. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89012. * \code (description != NULL) \endcode
  89013. * \retval FLAC__bool
  89014. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89015. */
  89016. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89017. /** Sets the picture data of a PICTURE block.
  89018. *
  89019. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89020. * takes ownership of the pointer. Also sets the \a data_length field of the
  89021. * metadata object to what is passed in as the \a length parameter. The
  89022. * existing data will be freed if this function is successful, otherwise the
  89023. * original data and data_length will remain if \a copy is \c true and
  89024. * malloc() fails.
  89025. *
  89026. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89027. *
  89028. * \param object A pointer to an existing PICTURE object.
  89029. * \param data A pointer to the data to set.
  89030. * \param length The length of \a data in bytes.
  89031. * \param copy See above.
  89032. * \assert
  89033. * \code object != NULL \endcode
  89034. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89035. * \code (data != NULL && length > 0) ||
  89036. * (data == NULL && length == 0 && copy == false) \endcode
  89037. * \retval FLAC__bool
  89038. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89039. */
  89040. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89041. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89042. * See the format specification for limits on the contents of the
  89043. * PICTURE block.
  89044. *
  89045. * \param object A pointer to existing PICTURE block to be checked.
  89046. * \param violation Address of a pointer to a string. If there is a
  89047. * violation, a pointer to a string explanation of the
  89048. * violation will be returned here. \a violation may be
  89049. * \c NULL if you don't need the returned string. Do not
  89050. * free the returned string; it will always point to static
  89051. * data.
  89052. * \assert
  89053. * \code object != NULL \endcode
  89054. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89055. * \retval FLAC__bool
  89056. * \c false if PICTURE block is illegal, else \c true.
  89057. */
  89058. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89059. /* \} */
  89060. #ifdef __cplusplus
  89061. }
  89062. #endif
  89063. #endif
  89064. /*** End of inlined file: metadata.h ***/
  89065. /*** Start of inlined file: stream_decoder.h ***/
  89066. #ifndef FLAC__STREAM_DECODER_H
  89067. #define FLAC__STREAM_DECODER_H
  89068. #include <stdio.h> /* for FILE */
  89069. #ifdef __cplusplus
  89070. extern "C" {
  89071. #endif
  89072. /** \file include/FLAC/stream_decoder.h
  89073. *
  89074. * \brief
  89075. * This module contains the functions which implement the stream
  89076. * decoder.
  89077. *
  89078. * See the detailed documentation in the
  89079. * \link flac_stream_decoder stream decoder \endlink module.
  89080. */
  89081. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89082. * \ingroup flac
  89083. *
  89084. * \brief
  89085. * This module describes the decoder layers provided by libFLAC.
  89086. *
  89087. * The stream decoder can be used to decode complete streams either from
  89088. * the client via callbacks, or directly from a file, depending on how
  89089. * it is initialized. When decoding via callbacks, the client provides
  89090. * callbacks for reading FLAC data and writing decoded samples, and
  89091. * handling metadata and errors. If the client also supplies seek-related
  89092. * callback, the decoder function for sample-accurate seeking within the
  89093. * FLAC input is also available. When decoding from a file, the client
  89094. * needs only supply a filename or open \c FILE* and write/metadata/error
  89095. * callbacks; the rest of the callbacks are supplied internally. For more
  89096. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89097. */
  89098. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89099. * \ingroup flac_decoder
  89100. *
  89101. * \brief
  89102. * This module contains the functions which implement the stream
  89103. * decoder.
  89104. *
  89105. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89106. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89107. *
  89108. * The basic usage of this decoder is as follows:
  89109. * - The program creates an instance of a decoder using
  89110. * FLAC__stream_decoder_new().
  89111. * - The program overrides the default settings using
  89112. * FLAC__stream_decoder_set_*() functions.
  89113. * - The program initializes the instance to validate the settings and
  89114. * prepare for decoding using
  89115. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89116. * or FLAC__stream_decoder_init_file() for native FLAC,
  89117. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89118. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89119. * - The program calls the FLAC__stream_decoder_process_*() functions
  89120. * to decode data, which subsequently calls the callbacks.
  89121. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89122. * which flushes the input and output and resets the decoder to the
  89123. * uninitialized state.
  89124. * - The instance may be used again or deleted with
  89125. * FLAC__stream_decoder_delete().
  89126. *
  89127. * In more detail, the program will create a new instance by calling
  89128. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89129. * functions to override the default decoder options, and call
  89130. * one of the FLAC__stream_decoder_init_*() functions.
  89131. *
  89132. * There are three initialization functions for native FLAC, one for
  89133. * setting up the decoder to decode FLAC data from the client via
  89134. * callbacks, and two for decoding directly from a FLAC file.
  89135. *
  89136. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89137. * You must also supply several callbacks for handling I/O. Some (like
  89138. * seeking) are optional, depending on the capabilities of the input.
  89139. *
  89140. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89141. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89142. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89143. * the other callbacks internally.
  89144. *
  89145. * There are three similarly-named init functions for decoding from Ogg
  89146. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89147. * library has been built with Ogg support.
  89148. *
  89149. * Once the decoder is initialized, your program will call one of several
  89150. * functions to start the decoding process:
  89151. *
  89152. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89153. * most one metadata block or audio frame and return, calling either the
  89154. * metadata callback or write callback, respectively, once. If the decoder
  89155. * loses sync it will return with only the error callback being called.
  89156. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89157. * to process the stream from the current location and stop upon reaching
  89158. * the first audio frame. The client will get one metadata, write, or error
  89159. * callback per metadata block, audio frame, or sync error, respectively.
  89160. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89161. * to process the stream from the current location until the read callback
  89162. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89163. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89164. * write, or error callback per metadata block, audio frame, or sync error,
  89165. * respectively.
  89166. *
  89167. * When the decoder has finished decoding (normally or through an abort),
  89168. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89169. * ensures the decoder is in the correct state and frees memory. Then the
  89170. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89171. * again to decode another stream.
  89172. *
  89173. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89174. * At any point after the stream decoder has been initialized, the client can
  89175. * call this function to seek to an exact sample within the stream.
  89176. * Subsequently, the first time the write callback is called it will be
  89177. * passed a (possibly partial) block starting at that sample.
  89178. *
  89179. * If the client cannot seek via the callback interface provided, but still
  89180. * has another way of seeking, it can flush the decoder using
  89181. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89182. * through the read callback.
  89183. *
  89184. * The stream decoder also provides MD5 signature checking. If this is
  89185. * turned on before initialization, FLAC__stream_decoder_finish() will
  89186. * report when the decoded MD5 signature does not match the one stored
  89187. * in the STREAMINFO block. MD5 checking is automatically turned off
  89188. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89189. * in the STREAMINFO block or when a seek is attempted.
  89190. *
  89191. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89192. * attention. By default, the decoder only calls the metadata_callback for
  89193. * the STREAMINFO block. These functions allow you to tell the decoder
  89194. * explicitly which blocks to parse and return via the metadata_callback
  89195. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89196. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89197. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89198. * which blocks to return. Remember that metadata blocks can potentially
  89199. * be big (for example, cover art) so filtering out the ones you don't
  89200. * use can reduce the memory requirements of the decoder. Also note the
  89201. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89202. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89203. * filtering APPLICATION blocks based on the application ID.
  89204. *
  89205. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89206. * they still can legally be filtered from the metadata_callback.
  89207. *
  89208. * \note
  89209. * The "set" functions may only be called when the decoder is in the
  89210. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89211. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89212. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89213. * return \c true, otherwise \c false.
  89214. *
  89215. * \note
  89216. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89217. * defaults, including the callbacks.
  89218. *
  89219. * \{
  89220. */
  89221. /** State values for a FLAC__StreamDecoder
  89222. *
  89223. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89224. */
  89225. typedef enum {
  89226. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89227. /**< The decoder is ready to search for metadata. */
  89228. FLAC__STREAM_DECODER_READ_METADATA,
  89229. /**< The decoder is ready to or is in the process of reading metadata. */
  89230. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89231. /**< The decoder is ready to or is in the process of searching for the
  89232. * frame sync code.
  89233. */
  89234. FLAC__STREAM_DECODER_READ_FRAME,
  89235. /**< The decoder is ready to or is in the process of reading a frame. */
  89236. FLAC__STREAM_DECODER_END_OF_STREAM,
  89237. /**< The decoder has reached the end of the stream. */
  89238. FLAC__STREAM_DECODER_OGG_ERROR,
  89239. /**< An error occurred in the underlying Ogg layer. */
  89240. FLAC__STREAM_DECODER_SEEK_ERROR,
  89241. /**< An error occurred while seeking. The decoder must be flushed
  89242. * with FLAC__stream_decoder_flush() or reset with
  89243. * FLAC__stream_decoder_reset() before decoding can continue.
  89244. */
  89245. FLAC__STREAM_DECODER_ABORTED,
  89246. /**< The decoder was aborted by the read callback. */
  89247. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89248. /**< An error occurred allocating memory. The decoder is in an invalid
  89249. * state and can no longer be used.
  89250. */
  89251. FLAC__STREAM_DECODER_UNINITIALIZED
  89252. /**< The decoder is in the uninitialized state; one of the
  89253. * FLAC__stream_decoder_init_*() functions must be called before samples
  89254. * can be processed.
  89255. */
  89256. } FLAC__StreamDecoderState;
  89257. /** Maps a FLAC__StreamDecoderState to a C string.
  89258. *
  89259. * Using a FLAC__StreamDecoderState as the index to this array
  89260. * will give the string equivalent. The contents should not be modified.
  89261. */
  89262. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89263. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89264. */
  89265. typedef enum {
  89266. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89267. /**< Initialization was successful. */
  89268. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89269. /**< The library was not compiled with support for the given container
  89270. * format.
  89271. */
  89272. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89273. /**< A required callback was not supplied. */
  89274. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89275. /**< An error occurred allocating memory. */
  89276. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89277. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89278. * FLAC__stream_decoder_init_ogg_file(). */
  89279. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89280. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89281. * already initialized, usually because
  89282. * FLAC__stream_decoder_finish() was not called.
  89283. */
  89284. } FLAC__StreamDecoderInitStatus;
  89285. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89286. *
  89287. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89288. * will give the string equivalent. The contents should not be modified.
  89289. */
  89290. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89291. /** Return values for the FLAC__StreamDecoder read callback.
  89292. */
  89293. typedef enum {
  89294. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89295. /**< The read was OK and decoding can continue. */
  89296. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89297. /**< The read was attempted while at the end of the stream. Note that
  89298. * the client must only return this value when the read callback was
  89299. * called when already at the end of the stream. Otherwise, if the read
  89300. * itself moves to the end of the stream, the client should still return
  89301. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89302. * the next read callback it should return
  89303. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89304. * of \c 0.
  89305. */
  89306. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89307. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89308. } FLAC__StreamDecoderReadStatus;
  89309. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89310. *
  89311. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89312. * will give the string equivalent. The contents should not be modified.
  89313. */
  89314. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89315. /** Return values for the FLAC__StreamDecoder seek callback.
  89316. */
  89317. typedef enum {
  89318. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89319. /**< The seek was OK and decoding can continue. */
  89320. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89321. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89322. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89323. /**< Client does not support seeking. */
  89324. } FLAC__StreamDecoderSeekStatus;
  89325. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89326. *
  89327. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89328. * will give the string equivalent. The contents should not be modified.
  89329. */
  89330. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89331. /** Return values for the FLAC__StreamDecoder tell callback.
  89332. */
  89333. typedef enum {
  89334. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89335. /**< The tell was OK and decoding can continue. */
  89336. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89337. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89338. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89339. /**< Client does not support telling the position. */
  89340. } FLAC__StreamDecoderTellStatus;
  89341. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89342. *
  89343. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89344. * will give the string equivalent. The contents should not be modified.
  89345. */
  89346. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89347. /** Return values for the FLAC__StreamDecoder length callback.
  89348. */
  89349. typedef enum {
  89350. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89351. /**< The length call was OK and decoding can continue. */
  89352. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89353. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89354. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89355. /**< Client does not support reporting the length. */
  89356. } FLAC__StreamDecoderLengthStatus;
  89357. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89358. *
  89359. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89360. * will give the string equivalent. The contents should not be modified.
  89361. */
  89362. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89363. /** Return values for the FLAC__StreamDecoder write callback.
  89364. */
  89365. typedef enum {
  89366. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89367. /**< The write was OK and decoding can continue. */
  89368. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89369. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89370. } FLAC__StreamDecoderWriteStatus;
  89371. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89372. *
  89373. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89374. * will give the string equivalent. The contents should not be modified.
  89375. */
  89376. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89377. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89378. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89379. * all. The rest could be caused by bad sync (false synchronization on
  89380. * data that is not the start of a frame) or corrupted data. The error
  89381. * itself is the decoder's best guess at what happened assuming a correct
  89382. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89383. * could be caused by a correct sync on the start of a frame, but some
  89384. * data in the frame header was corrupted. Or it could be the result of
  89385. * syncing on a point the stream that looked like the starting of a frame
  89386. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89387. * could be because the decoder encountered a valid frame made by a future
  89388. * version of the encoder which it cannot parse, or because of a false
  89389. * sync making it appear as though an encountered frame was generated by
  89390. * a future encoder.
  89391. */
  89392. typedef enum {
  89393. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89394. /**< An error in the stream caused the decoder to lose synchronization. */
  89395. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89396. /**< The decoder encountered a corrupted frame header. */
  89397. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89398. /**< The frame's data did not match the CRC in the footer. */
  89399. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89400. /**< The decoder encountered reserved fields in use in the stream. */
  89401. } FLAC__StreamDecoderErrorStatus;
  89402. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89403. *
  89404. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89405. * will give the string equivalent. The contents should not be modified.
  89406. */
  89407. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89408. /***********************************************************************
  89409. *
  89410. * class FLAC__StreamDecoder
  89411. *
  89412. ***********************************************************************/
  89413. struct FLAC__StreamDecoderProtected;
  89414. struct FLAC__StreamDecoderPrivate;
  89415. /** The opaque structure definition for the stream decoder type.
  89416. * See the \link flac_stream_decoder stream decoder module \endlink
  89417. * for a detailed description.
  89418. */
  89419. typedef struct {
  89420. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89421. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89422. } FLAC__StreamDecoder;
  89423. /** Signature for the read callback.
  89424. *
  89425. * A function pointer matching this signature must be passed to
  89426. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89427. * called when the decoder needs more input data. The address of the
  89428. * buffer to be filled is supplied, along with the number of bytes the
  89429. * buffer can hold. The callback may choose to supply less data and
  89430. * modify the byte count but must be careful not to overflow the buffer.
  89431. * The callback then returns a status code chosen from
  89432. * FLAC__StreamDecoderReadStatus.
  89433. *
  89434. * Here is an example of a read callback for stdio streams:
  89435. * \code
  89436. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89437. * {
  89438. * FILE *file = ((MyClientData*)client_data)->file;
  89439. * if(*bytes > 0) {
  89440. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89441. * if(ferror(file))
  89442. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89443. * else if(*bytes == 0)
  89444. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89445. * else
  89446. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89447. * }
  89448. * else
  89449. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89450. * }
  89451. * \endcode
  89452. *
  89453. * \note In general, FLAC__StreamDecoder functions which change the
  89454. * state should not be called on the \a decoder while in the callback.
  89455. *
  89456. * \param decoder The decoder instance calling the callback.
  89457. * \param buffer A pointer to a location for the callee to store
  89458. * data to be decoded.
  89459. * \param bytes A pointer to the size of the buffer. On entry
  89460. * to the callback, it contains the maximum number
  89461. * of bytes that may be stored in \a buffer. The
  89462. * callee must set it to the actual number of bytes
  89463. * stored (0 in case of error or end-of-stream) before
  89464. * returning.
  89465. * \param client_data The callee's client data set through
  89466. * FLAC__stream_decoder_init_*().
  89467. * \retval FLAC__StreamDecoderReadStatus
  89468. * The callee's return status. Note that the callback should return
  89469. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89470. * zero bytes were read and there is no more data to be read.
  89471. */
  89472. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89473. /** Signature for the seek callback.
  89474. *
  89475. * A function pointer matching this signature may be passed to
  89476. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89477. * called when the decoder needs to seek the input stream. The decoder
  89478. * will pass the absolute byte offset to seek to, 0 meaning the
  89479. * beginning of the stream.
  89480. *
  89481. * Here is an example of a seek callback for stdio streams:
  89482. * \code
  89483. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89484. * {
  89485. * FILE *file = ((MyClientData*)client_data)->file;
  89486. * if(file == stdin)
  89487. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89488. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89489. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89490. * else
  89491. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89492. * }
  89493. * \endcode
  89494. *
  89495. * \note In general, FLAC__StreamDecoder functions which change the
  89496. * state should not be called on the \a decoder while in the callback.
  89497. *
  89498. * \param decoder The decoder instance calling the callback.
  89499. * \param absolute_byte_offset The offset from the beginning of the stream
  89500. * to seek to.
  89501. * \param client_data The callee's client data set through
  89502. * FLAC__stream_decoder_init_*().
  89503. * \retval FLAC__StreamDecoderSeekStatus
  89504. * The callee's return status.
  89505. */
  89506. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89507. /** Signature for the tell callback.
  89508. *
  89509. * A function pointer matching this signature may be passed to
  89510. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89511. * called when the decoder wants to know the current position of the
  89512. * stream. The callback should return the byte offset from the
  89513. * beginning of the stream.
  89514. *
  89515. * Here is an example of a tell callback for stdio streams:
  89516. * \code
  89517. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89518. * {
  89519. * FILE *file = ((MyClientData*)client_data)->file;
  89520. * off_t pos;
  89521. * if(file == stdin)
  89522. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89523. * else if((pos = ftello(file)) < 0)
  89524. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89525. * else {
  89526. * *absolute_byte_offset = (FLAC__uint64)pos;
  89527. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89528. * }
  89529. * }
  89530. * \endcode
  89531. *
  89532. * \note In general, FLAC__StreamDecoder functions which change the
  89533. * state should not be called on the \a decoder while in the callback.
  89534. *
  89535. * \param decoder The decoder instance calling the callback.
  89536. * \param absolute_byte_offset A pointer to storage for the current offset
  89537. * from the beginning of the stream.
  89538. * \param client_data The callee's client data set through
  89539. * FLAC__stream_decoder_init_*().
  89540. * \retval FLAC__StreamDecoderTellStatus
  89541. * The callee's return status.
  89542. */
  89543. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89544. /** Signature for the length callback.
  89545. *
  89546. * A function pointer matching this signature may be passed to
  89547. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89548. * called when the decoder wants to know the total length of the stream
  89549. * in bytes.
  89550. *
  89551. * Here is an example of a length callback for stdio streams:
  89552. * \code
  89553. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89554. * {
  89555. * FILE *file = ((MyClientData*)client_data)->file;
  89556. * struct stat filestats;
  89557. *
  89558. * if(file == stdin)
  89559. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89560. * else if(fstat(fileno(file), &filestats) != 0)
  89561. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89562. * else {
  89563. * *stream_length = (FLAC__uint64)filestats.st_size;
  89564. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89565. * }
  89566. * }
  89567. * \endcode
  89568. *
  89569. * \note In general, FLAC__StreamDecoder functions which change the
  89570. * state should not be called on the \a decoder while in the callback.
  89571. *
  89572. * \param decoder The decoder instance calling the callback.
  89573. * \param stream_length A pointer to storage for the length of the stream
  89574. * in bytes.
  89575. * \param client_data The callee's client data set through
  89576. * FLAC__stream_decoder_init_*().
  89577. * \retval FLAC__StreamDecoderLengthStatus
  89578. * The callee's return status.
  89579. */
  89580. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89581. /** Signature for the EOF callback.
  89582. *
  89583. * A function pointer matching this signature may be passed to
  89584. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89585. * called when the decoder needs to know if the end of the stream has
  89586. * been reached.
  89587. *
  89588. * Here is an example of a EOF callback for stdio streams:
  89589. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89590. * \code
  89591. * {
  89592. * FILE *file = ((MyClientData*)client_data)->file;
  89593. * return feof(file)? true : false;
  89594. * }
  89595. * \endcode
  89596. *
  89597. * \note In general, FLAC__StreamDecoder functions which change the
  89598. * state should not be called on the \a decoder while in the callback.
  89599. *
  89600. * \param decoder The decoder instance calling the callback.
  89601. * \param client_data The callee's client data set through
  89602. * FLAC__stream_decoder_init_*().
  89603. * \retval FLAC__bool
  89604. * \c true if the currently at the end of the stream, else \c false.
  89605. */
  89606. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89607. /** Signature for the write callback.
  89608. *
  89609. * A function pointer matching this signature must be passed to one of
  89610. * the FLAC__stream_decoder_init_*() functions.
  89611. * The supplied function will be called when the decoder has decoded a
  89612. * single audio frame. The decoder will pass the frame metadata as well
  89613. * as an array of pointers (one for each channel) pointing to the
  89614. * decoded audio.
  89615. *
  89616. * \note In general, FLAC__StreamDecoder functions which change the
  89617. * state should not be called on the \a decoder while in the callback.
  89618. *
  89619. * \param decoder The decoder instance calling the callback.
  89620. * \param frame The description of the decoded frame. See
  89621. * FLAC__Frame.
  89622. * \param buffer An array of pointers to decoded channels of data.
  89623. * Each pointer will point to an array of signed
  89624. * samples of length \a frame->header.blocksize.
  89625. * Channels will be ordered according to the FLAC
  89626. * specification; see the documentation for the
  89627. * <A HREF="../format.html#frame_header">frame header</A>.
  89628. * \param client_data The callee's client data set through
  89629. * FLAC__stream_decoder_init_*().
  89630. * \retval FLAC__StreamDecoderWriteStatus
  89631. * The callee's return status.
  89632. */
  89633. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89634. /** Signature for the metadata callback.
  89635. *
  89636. * A function pointer matching this signature must be passed to one of
  89637. * the FLAC__stream_decoder_init_*() functions.
  89638. * The supplied function will be called when the decoder has decoded a
  89639. * metadata block. In a valid FLAC file there will always be one
  89640. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89641. * These will be supplied by the decoder in the same order as they
  89642. * appear in the stream and always before the first audio frame (i.e.
  89643. * write callback). The metadata block that is passed in must not be
  89644. * modified, and it doesn't live beyond the callback, so you should make
  89645. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89646. * elsewhere. Since metadata blocks can potentially be large, by
  89647. * default the decoder only calls the metadata callback for the
  89648. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89649. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89650. *
  89651. * \note In general, FLAC__StreamDecoder functions which change the
  89652. * state should not be called on the \a decoder while in the callback.
  89653. *
  89654. * \param decoder The decoder instance calling the callback.
  89655. * \param metadata The decoded metadata block.
  89656. * \param client_data The callee's client data set through
  89657. * FLAC__stream_decoder_init_*().
  89658. */
  89659. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89660. /** Signature for the error callback.
  89661. *
  89662. * A function pointer matching this signature must be passed to one of
  89663. * the FLAC__stream_decoder_init_*() functions.
  89664. * The supplied function will be called whenever an error occurs during
  89665. * decoding.
  89666. *
  89667. * \note In general, FLAC__StreamDecoder functions which change the
  89668. * state should not be called on the \a decoder while in the callback.
  89669. *
  89670. * \param decoder The decoder instance calling the callback.
  89671. * \param status The error encountered by the decoder.
  89672. * \param client_data The callee's client data set through
  89673. * FLAC__stream_decoder_init_*().
  89674. */
  89675. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  89676. /***********************************************************************
  89677. *
  89678. * Class constructor/destructor
  89679. *
  89680. ***********************************************************************/
  89681. /** Create a new stream decoder instance. The instance is created with
  89682. * default settings; see the individual FLAC__stream_decoder_set_*()
  89683. * functions for each setting's default.
  89684. *
  89685. * \retval FLAC__StreamDecoder*
  89686. * \c NULL if there was an error allocating memory, else the new instance.
  89687. */
  89688. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  89689. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  89690. *
  89691. * \param decoder A pointer to an existing decoder.
  89692. * \assert
  89693. * \code decoder != NULL \endcode
  89694. */
  89695. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  89696. /***********************************************************************
  89697. *
  89698. * Public class method prototypes
  89699. *
  89700. ***********************************************************************/
  89701. /** Set the serial number for the FLAC stream within the Ogg container.
  89702. * The default behavior is to use the serial number of the first Ogg
  89703. * page. Setting a serial number here will explicitly specify which
  89704. * stream is to be decoded.
  89705. *
  89706. * \note
  89707. * This does not need to be set for native FLAC decoding.
  89708. *
  89709. * \default \c use serial number of first page
  89710. * \param decoder A decoder instance to set.
  89711. * \param serial_number See above.
  89712. * \assert
  89713. * \code decoder != NULL \endcode
  89714. * \retval FLAC__bool
  89715. * \c false if the decoder is already initialized, else \c true.
  89716. */
  89717. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  89718. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  89719. * compute the MD5 signature of the unencoded audio data while decoding
  89720. * and compare it to the signature from the STREAMINFO block, if it
  89721. * exists, during FLAC__stream_decoder_finish().
  89722. *
  89723. * MD5 signature checking will be turned off (until the next
  89724. * FLAC__stream_decoder_reset()) if there is no signature in the
  89725. * STREAMINFO block or when a seek is attempted.
  89726. *
  89727. * Clients that do not use the MD5 check should leave this off to speed
  89728. * up decoding.
  89729. *
  89730. * \default \c false
  89731. * \param decoder A decoder instance to set.
  89732. * \param value Flag value (see above).
  89733. * \assert
  89734. * \code decoder != NULL \endcode
  89735. * \retval FLAC__bool
  89736. * \c false if the decoder is already initialized, else \c true.
  89737. */
  89738. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  89739. /** Direct the decoder to pass on all metadata blocks of type \a type.
  89740. *
  89741. * \default By default, only the \c STREAMINFO block is returned via the
  89742. * metadata callback.
  89743. * \param decoder A decoder instance to set.
  89744. * \param type See above.
  89745. * \assert
  89746. * \code decoder != NULL \endcode
  89747. * \a type is valid
  89748. * \retval FLAC__bool
  89749. * \c false if the decoder is already initialized, else \c true.
  89750. */
  89751. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89752. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  89753. * given \a id.
  89754. *
  89755. * \default By default, only the \c STREAMINFO block is returned via the
  89756. * metadata callback.
  89757. * \param decoder A decoder instance to set.
  89758. * \param id See above.
  89759. * \assert
  89760. * \code decoder != NULL \endcode
  89761. * \code id != NULL \endcode
  89762. * \retval FLAC__bool
  89763. * \c false if the decoder is already initialized, else \c true.
  89764. */
  89765. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89766. /** Direct the decoder to pass on all metadata blocks of any type.
  89767. *
  89768. * \default By default, only the \c STREAMINFO block is returned via the
  89769. * metadata callback.
  89770. * \param decoder A decoder instance to set.
  89771. * \assert
  89772. * \code decoder != NULL \endcode
  89773. * \retval FLAC__bool
  89774. * \c false if the decoder is already initialized, else \c true.
  89775. */
  89776. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  89777. /** Direct the decoder to filter out all metadata blocks of type \a type.
  89778. *
  89779. * \default By default, only the \c STREAMINFO block is returned via the
  89780. * metadata callback.
  89781. * \param decoder A decoder instance to set.
  89782. * \param type See above.
  89783. * \assert
  89784. * \code decoder != NULL \endcode
  89785. * \a type is valid
  89786. * \retval FLAC__bool
  89787. * \c false if the decoder is already initialized, else \c true.
  89788. */
  89789. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  89790. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  89791. * the given \a id.
  89792. *
  89793. * \default By default, only the \c STREAMINFO block is returned via the
  89794. * metadata callback.
  89795. * \param decoder A decoder instance to set.
  89796. * \param id See above.
  89797. * \assert
  89798. * \code decoder != NULL \endcode
  89799. * \code id != NULL \endcode
  89800. * \retval FLAC__bool
  89801. * \c false if the decoder is already initialized, else \c true.
  89802. */
  89803. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  89804. /** Direct the decoder to filter out all metadata blocks of any type.
  89805. *
  89806. * \default By default, only the \c STREAMINFO block is returned via the
  89807. * metadata callback.
  89808. * \param decoder A decoder instance to set.
  89809. * \assert
  89810. * \code decoder != NULL \endcode
  89811. * \retval FLAC__bool
  89812. * \c false if the decoder is already initialized, else \c true.
  89813. */
  89814. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  89815. /** Get the current decoder state.
  89816. *
  89817. * \param decoder A decoder instance to query.
  89818. * \assert
  89819. * \code decoder != NULL \endcode
  89820. * \retval FLAC__StreamDecoderState
  89821. * The current decoder state.
  89822. */
  89823. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  89824. /** Get the current decoder state as a C string.
  89825. *
  89826. * \param decoder A decoder instance to query.
  89827. * \assert
  89828. * \code decoder != NULL \endcode
  89829. * \retval const char *
  89830. * The decoder state as a C string. Do not modify the contents.
  89831. */
  89832. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  89833. /** Get the "MD5 signature checking" flag.
  89834. * This is the value of the setting, not whether or not the decoder is
  89835. * currently checking the MD5 (remember, it can be turned off automatically
  89836. * by a seek). When the decoder is reset the flag will be restored to the
  89837. * value returned by this function.
  89838. *
  89839. * \param decoder A decoder instance to query.
  89840. * \assert
  89841. * \code decoder != NULL \endcode
  89842. * \retval FLAC__bool
  89843. * See above.
  89844. */
  89845. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  89846. /** Get the total number of samples in the stream being decoded.
  89847. * Will only be valid after decoding has started and will contain the
  89848. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  89849. *
  89850. * \param decoder A decoder instance to query.
  89851. * \assert
  89852. * \code decoder != NULL \endcode
  89853. * \retval unsigned
  89854. * See above.
  89855. */
  89856. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  89857. /** Get the current number of channels in the stream being decoded.
  89858. * Will only be valid after decoding has started and will contain the
  89859. * value from the most recently decoded frame header.
  89860. *
  89861. * \param decoder A decoder instance to query.
  89862. * \assert
  89863. * \code decoder != NULL \endcode
  89864. * \retval unsigned
  89865. * See above.
  89866. */
  89867. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  89868. /** Get the current channel assignment in the stream being decoded.
  89869. * Will only be valid after decoding has started and will contain the
  89870. * value from the most recently decoded frame header.
  89871. *
  89872. * \param decoder A decoder instance to query.
  89873. * \assert
  89874. * \code decoder != NULL \endcode
  89875. * \retval FLAC__ChannelAssignment
  89876. * See above.
  89877. */
  89878. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  89879. /** Get the current sample resolution in the stream being decoded.
  89880. * Will only be valid after decoding has started and will contain the
  89881. * value from the most recently decoded frame header.
  89882. *
  89883. * \param decoder A decoder instance to query.
  89884. * \assert
  89885. * \code decoder != NULL \endcode
  89886. * \retval unsigned
  89887. * See above.
  89888. */
  89889. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  89890. /** Get the current sample rate in Hz of the stream being decoded.
  89891. * Will only be valid after decoding has started and will contain the
  89892. * value from the most recently decoded frame header.
  89893. *
  89894. * \param decoder A decoder instance to query.
  89895. * \assert
  89896. * \code decoder != NULL \endcode
  89897. * \retval unsigned
  89898. * See above.
  89899. */
  89900. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  89901. /** Get the current blocksize of the stream being decoded.
  89902. * Will only be valid after decoding has started and will contain the
  89903. * value from the most recently decoded frame header.
  89904. *
  89905. * \param decoder A decoder instance to query.
  89906. * \assert
  89907. * \code decoder != NULL \endcode
  89908. * \retval unsigned
  89909. * See above.
  89910. */
  89911. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  89912. /** Returns the decoder's current read position within the stream.
  89913. * The position is the byte offset from the start of the stream.
  89914. * Bytes before this position have been fully decoded. Note that
  89915. * there may still be undecoded bytes in the decoder's read FIFO.
  89916. * The returned position is correct even after a seek.
  89917. *
  89918. * \warning This function currently only works for native FLAC,
  89919. * not Ogg FLAC streams.
  89920. *
  89921. * \param decoder A decoder instance to query.
  89922. * \param position Address at which to return the desired position.
  89923. * \assert
  89924. * \code decoder != NULL \endcode
  89925. * \code position != NULL \endcode
  89926. * \retval FLAC__bool
  89927. * \c true if successful, \c false if the stream is not native FLAC,
  89928. * or there was an error from the 'tell' callback or it returned
  89929. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  89930. */
  89931. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  89932. /** Initialize the decoder instance to decode native FLAC streams.
  89933. *
  89934. * This flavor of initialization sets up the decoder to decode from a
  89935. * native FLAC stream. I/O is performed via callbacks to the client.
  89936. * For decoding from a plain file via filename or open FILE*,
  89937. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  89938. * provide a simpler interface.
  89939. *
  89940. * This function should be called after FLAC__stream_decoder_new() and
  89941. * FLAC__stream_decoder_set_*() but before any of the
  89942. * FLAC__stream_decoder_process_*() functions. Will set and return the
  89943. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  89944. * if initialization succeeded.
  89945. *
  89946. * \param decoder An uninitialized decoder instance.
  89947. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  89948. * pointer must not be \c NULL.
  89949. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  89950. * pointer may be \c NULL if seeking is not
  89951. * supported. If \a seek_callback is not \c NULL then a
  89952. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  89953. * Alternatively, a dummy seek callback that just
  89954. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89955. * may also be supplied, all though this is slightly
  89956. * less efficient for the decoder.
  89957. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  89958. * pointer may be \c NULL if not supported by the client. If
  89959. * \a seek_callback is not \c NULL then a
  89960. * \a tell_callback must also be supplied.
  89961. * Alternatively, a dummy tell callback that just
  89962. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89963. * may also be supplied, all though this is slightly
  89964. * less efficient for the decoder.
  89965. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  89966. * pointer may be \c NULL if not supported by the client. If
  89967. * \a seek_callback is not \c NULL then a
  89968. * \a length_callback must also be supplied.
  89969. * Alternatively, a dummy length callback that just
  89970. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89971. * may also be supplied, all though this is slightly
  89972. * less efficient for the decoder.
  89973. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  89974. * pointer may be \c NULL if not supported by the client. If
  89975. * \a seek_callback is not \c NULL then a
  89976. * \a eof_callback must also be supplied.
  89977. * Alternatively, a dummy length callback that just
  89978. * returns \c false
  89979. * may also be supplied, all though this is slightly
  89980. * less efficient for the decoder.
  89981. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  89982. * pointer must not be \c NULL.
  89983. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  89984. * pointer may be \c NULL if the callback is not
  89985. * desired.
  89986. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  89987. * pointer must not be \c NULL.
  89988. * \param client_data This value will be supplied to callbacks in their
  89989. * \a client_data argument.
  89990. * \assert
  89991. * \code decoder != NULL \endcode
  89992. * \retval FLAC__StreamDecoderInitStatus
  89993. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  89994. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  89995. */
  89996. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  89997. FLAC__StreamDecoder *decoder,
  89998. FLAC__StreamDecoderReadCallback read_callback,
  89999. FLAC__StreamDecoderSeekCallback seek_callback,
  90000. FLAC__StreamDecoderTellCallback tell_callback,
  90001. FLAC__StreamDecoderLengthCallback length_callback,
  90002. FLAC__StreamDecoderEofCallback eof_callback,
  90003. FLAC__StreamDecoderWriteCallback write_callback,
  90004. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90005. FLAC__StreamDecoderErrorCallback error_callback,
  90006. void *client_data
  90007. );
  90008. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90009. *
  90010. * This flavor of initialization sets up the decoder to decode from a
  90011. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90012. * client. For decoding from a plain file via filename or open FILE*,
  90013. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90014. * provide a simpler interface.
  90015. *
  90016. * This function should be called after FLAC__stream_decoder_new() and
  90017. * FLAC__stream_decoder_set_*() but before any of the
  90018. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90019. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90020. * if initialization succeeded.
  90021. *
  90022. * \note Support for Ogg FLAC in the library is optional. If this
  90023. * library has been built without support for Ogg FLAC, this function
  90024. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90025. *
  90026. * \param decoder An uninitialized decoder instance.
  90027. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90028. * pointer must not be \c NULL.
  90029. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90030. * pointer may be \c NULL if seeking is not
  90031. * supported. If \a seek_callback is not \c NULL then a
  90032. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90033. * Alternatively, a dummy seek callback that just
  90034. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90035. * may also be supplied, all though this is slightly
  90036. * less efficient for the decoder.
  90037. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90038. * pointer may be \c NULL if not supported by the client. If
  90039. * \a seek_callback is not \c NULL then a
  90040. * \a tell_callback must also be supplied.
  90041. * Alternatively, a dummy tell callback that just
  90042. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90043. * may also be supplied, all though this is slightly
  90044. * less efficient for the decoder.
  90045. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90046. * pointer may be \c NULL if not supported by the client. If
  90047. * \a seek_callback is not \c NULL then a
  90048. * \a length_callback must also be supplied.
  90049. * Alternatively, a dummy length callback that just
  90050. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90051. * may also be supplied, all though this is slightly
  90052. * less efficient for the decoder.
  90053. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90054. * pointer may be \c NULL if not supported by the client. If
  90055. * \a seek_callback is not \c NULL then a
  90056. * \a eof_callback must also be supplied.
  90057. * Alternatively, a dummy length callback that just
  90058. * returns \c false
  90059. * may also be supplied, all though this is slightly
  90060. * less efficient for the decoder.
  90061. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90062. * pointer must not be \c NULL.
  90063. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90064. * pointer may be \c NULL if the callback is not
  90065. * desired.
  90066. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90067. * pointer must not be \c NULL.
  90068. * \param client_data This value will be supplied to callbacks in their
  90069. * \a client_data argument.
  90070. * \assert
  90071. * \code decoder != NULL \endcode
  90072. * \retval FLAC__StreamDecoderInitStatus
  90073. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90074. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90075. */
  90076. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90077. FLAC__StreamDecoder *decoder,
  90078. FLAC__StreamDecoderReadCallback read_callback,
  90079. FLAC__StreamDecoderSeekCallback seek_callback,
  90080. FLAC__StreamDecoderTellCallback tell_callback,
  90081. FLAC__StreamDecoderLengthCallback length_callback,
  90082. FLAC__StreamDecoderEofCallback eof_callback,
  90083. FLAC__StreamDecoderWriteCallback write_callback,
  90084. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90085. FLAC__StreamDecoderErrorCallback error_callback,
  90086. void *client_data
  90087. );
  90088. /** Initialize the decoder instance to decode native FLAC files.
  90089. *
  90090. * This flavor of initialization sets up the decoder to decode from a
  90091. * plain native FLAC file. For non-stdio streams, you must use
  90092. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90093. *
  90094. * This function should be called after FLAC__stream_decoder_new() and
  90095. * FLAC__stream_decoder_set_*() but before any of the
  90096. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90097. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90098. * if initialization succeeded.
  90099. *
  90100. * \param decoder An uninitialized decoder instance.
  90101. * \param file An open FLAC file. The file should have been
  90102. * opened with mode \c "rb" and rewound. The file
  90103. * becomes owned by the decoder and should not be
  90104. * manipulated by the client while decoding.
  90105. * Unless \a file is \c stdin, it will be closed
  90106. * when FLAC__stream_decoder_finish() is called.
  90107. * Note however that seeking will not work when
  90108. * decoding from \c stdout since it is not seekable.
  90109. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90110. * pointer must not be \c NULL.
  90111. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90112. * pointer may be \c NULL if the callback is not
  90113. * desired.
  90114. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90115. * pointer must not be \c NULL.
  90116. * \param client_data This value will be supplied to callbacks in their
  90117. * \a client_data argument.
  90118. * \assert
  90119. * \code decoder != NULL \endcode
  90120. * \code file != NULL \endcode
  90121. * \retval FLAC__StreamDecoderInitStatus
  90122. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90123. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90124. */
  90125. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90126. FLAC__StreamDecoder *decoder,
  90127. FILE *file,
  90128. FLAC__StreamDecoderWriteCallback write_callback,
  90129. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90130. FLAC__StreamDecoderErrorCallback error_callback,
  90131. void *client_data
  90132. );
  90133. /** Initialize the decoder instance to decode Ogg FLAC files.
  90134. *
  90135. * This flavor of initialization sets up the decoder to decode from a
  90136. * plain Ogg FLAC file. For non-stdio streams, you must use
  90137. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90138. *
  90139. * This function should be called after FLAC__stream_decoder_new() and
  90140. * FLAC__stream_decoder_set_*() but before any of the
  90141. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90142. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90143. * if initialization succeeded.
  90144. *
  90145. * \note Support for Ogg FLAC in the library is optional. If this
  90146. * library has been built without support for Ogg FLAC, this function
  90147. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90148. *
  90149. * \param decoder An uninitialized decoder instance.
  90150. * \param file An open FLAC file. The file should have been
  90151. * opened with mode \c "rb" and rewound. The file
  90152. * becomes owned by the decoder and should not be
  90153. * manipulated by the client while decoding.
  90154. * Unless \a file is \c stdin, it will be closed
  90155. * when FLAC__stream_decoder_finish() is called.
  90156. * Note however that seeking will not work when
  90157. * decoding from \c stdout since it is not seekable.
  90158. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90159. * pointer must not be \c NULL.
  90160. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90161. * pointer may be \c NULL if the callback is not
  90162. * desired.
  90163. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90164. * pointer must not be \c NULL.
  90165. * \param client_data This value will be supplied to callbacks in their
  90166. * \a client_data argument.
  90167. * \assert
  90168. * \code decoder != NULL \endcode
  90169. * \code file != NULL \endcode
  90170. * \retval FLAC__StreamDecoderInitStatus
  90171. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90172. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90173. */
  90174. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90175. FLAC__StreamDecoder *decoder,
  90176. FILE *file,
  90177. FLAC__StreamDecoderWriteCallback write_callback,
  90178. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90179. FLAC__StreamDecoderErrorCallback error_callback,
  90180. void *client_data
  90181. );
  90182. /** Initialize the decoder instance to decode native FLAC files.
  90183. *
  90184. * This flavor of initialization sets up the decoder to decode from a plain
  90185. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90186. * example, with Unicode filenames on Windows), you must use
  90187. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90188. * and provide callbacks for the I/O.
  90189. *
  90190. * This function should be called after FLAC__stream_decoder_new() and
  90191. * FLAC__stream_decoder_set_*() but before any of the
  90192. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90193. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90194. * if initialization succeeded.
  90195. *
  90196. * \param decoder An uninitialized decoder instance.
  90197. * \param filename The name of the file to decode from. The file will
  90198. * be opened with fopen(). Use \c NULL to decode from
  90199. * \c stdin. Note that \c stdin is not seekable.
  90200. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90201. * pointer must not be \c NULL.
  90202. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90203. * pointer may be \c NULL if the callback is not
  90204. * desired.
  90205. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90206. * pointer must not be \c NULL.
  90207. * \param client_data This value will be supplied to callbacks in their
  90208. * \a client_data argument.
  90209. * \assert
  90210. * \code decoder != NULL \endcode
  90211. * \retval FLAC__StreamDecoderInitStatus
  90212. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90213. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90214. */
  90215. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90216. FLAC__StreamDecoder *decoder,
  90217. const char *filename,
  90218. FLAC__StreamDecoderWriteCallback write_callback,
  90219. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90220. FLAC__StreamDecoderErrorCallback error_callback,
  90221. void *client_data
  90222. );
  90223. /** Initialize the decoder instance to decode Ogg FLAC files.
  90224. *
  90225. * This flavor of initialization sets up the decoder to decode from a plain
  90226. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90227. * example, with Unicode filenames on Windows), you must use
  90228. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90229. * and provide callbacks for the I/O.
  90230. *
  90231. * This function should be called after FLAC__stream_decoder_new() and
  90232. * FLAC__stream_decoder_set_*() but before any of the
  90233. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90234. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90235. * if initialization succeeded.
  90236. *
  90237. * \note Support for Ogg FLAC in the library is optional. If this
  90238. * library has been built without support for Ogg FLAC, this function
  90239. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90240. *
  90241. * \param decoder An uninitialized decoder instance.
  90242. * \param filename The name of the file to decode from. The file will
  90243. * be opened with fopen(). Use \c NULL to decode from
  90244. * \c stdin. Note that \c stdin is not seekable.
  90245. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90246. * pointer must not be \c NULL.
  90247. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90248. * pointer may be \c NULL if the callback is not
  90249. * desired.
  90250. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90251. * pointer must not be \c NULL.
  90252. * \param client_data This value will be supplied to callbacks in their
  90253. * \a client_data argument.
  90254. * \assert
  90255. * \code decoder != NULL \endcode
  90256. * \retval FLAC__StreamDecoderInitStatus
  90257. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90258. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90259. */
  90260. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90261. FLAC__StreamDecoder *decoder,
  90262. const char *filename,
  90263. FLAC__StreamDecoderWriteCallback write_callback,
  90264. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90265. FLAC__StreamDecoderErrorCallback error_callback,
  90266. void *client_data
  90267. );
  90268. /** Finish the decoding process.
  90269. * Flushes the decoding buffer, releases resources, resets the decoder
  90270. * settings to their defaults, and returns the decoder state to
  90271. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90272. *
  90273. * In the event of a prematurely-terminated decode, it is not strictly
  90274. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90275. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90276. * with a FLAC__stream_decoder_finish().
  90277. *
  90278. * \param decoder An uninitialized decoder instance.
  90279. * \assert
  90280. * \code decoder != NULL \endcode
  90281. * \retval FLAC__bool
  90282. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90283. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90284. * signature does not match the one computed by the decoder; else
  90285. * \c true.
  90286. */
  90287. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90288. /** Flush the stream input.
  90289. * The decoder's input buffer will be cleared and the state set to
  90290. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90291. * off MD5 checking.
  90292. *
  90293. * \param decoder A decoder instance.
  90294. * \assert
  90295. * \code decoder != NULL \endcode
  90296. * \retval FLAC__bool
  90297. * \c true if successful, else \c false if a memory allocation
  90298. * error occurs (in which case the state will be set to
  90299. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90300. */
  90301. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90302. /** Reset the decoding process.
  90303. * The decoder's input buffer will be cleared and the state set to
  90304. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90305. * FLAC__stream_decoder_finish() except that the settings are
  90306. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90307. * before decoding again. MD5 checking will be restored to its original
  90308. * setting.
  90309. *
  90310. * If the decoder is seekable, or was initialized with
  90311. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90312. * the decoder will also attempt to seek to the beginning of the file.
  90313. * If this rewind fails, this function will return \c false. It follows
  90314. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90315. * \c stdin.
  90316. *
  90317. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90318. * and is not seekable (i.e. no seek callback was provided or the seek
  90319. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90320. * is the duty of the client to start feeding data from the beginning of
  90321. * the stream on the next FLAC__stream_decoder_process() or
  90322. * FLAC__stream_decoder_process_interleaved() call.
  90323. *
  90324. * \param decoder A decoder instance.
  90325. * \assert
  90326. * \code decoder != NULL \endcode
  90327. * \retval FLAC__bool
  90328. * \c true if successful, else \c false if a memory allocation occurs
  90329. * (in which case the state will be set to
  90330. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90331. * occurs (the state will be unchanged).
  90332. */
  90333. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90334. /** Decode one metadata block or audio frame.
  90335. * This version instructs the decoder to decode a either a single metadata
  90336. * block or a single frame and stop, unless the callbacks return a fatal
  90337. * error or the read callback returns
  90338. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90339. *
  90340. * As the decoder needs more input it will call the read callback.
  90341. * Depending on what was decoded, the metadata or write callback will be
  90342. * called with the decoded metadata block or audio frame.
  90343. *
  90344. * Unless there is a fatal read error or end of stream, this function
  90345. * will return once one whole frame is decoded. In other words, if the
  90346. * stream is not synchronized or points to a corrupt frame header, the
  90347. * decoder will continue to try and resync until it gets to a valid
  90348. * frame, then decode one frame, then return. If the decoder points to
  90349. * a frame whose frame CRC in the frame footer does not match the
  90350. * computed frame CRC, this function will issue a
  90351. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90352. * error callback, and return, having decoded one complete, although
  90353. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90354. * correct length to the write callback.)
  90355. *
  90356. * \param decoder An initialized decoder instance.
  90357. * \assert
  90358. * \code decoder != NULL \endcode
  90359. * \retval FLAC__bool
  90360. * \c false if any fatal read, write, or memory allocation error
  90361. * occurred (meaning decoding must stop), else \c true; for more
  90362. * information about the decoder, check the decoder state with
  90363. * FLAC__stream_decoder_get_state().
  90364. */
  90365. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90366. /** Decode until the end of the metadata.
  90367. * This version instructs the decoder to decode from the current position
  90368. * and continue until all the metadata has been read, or until the
  90369. * callbacks return a fatal error or the read callback returns
  90370. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90371. *
  90372. * As the decoder needs more input it will call the read callback.
  90373. * As each metadata block is decoded, the metadata callback will be called
  90374. * with the decoded metadata.
  90375. *
  90376. * \param decoder An initialized decoder instance.
  90377. * \assert
  90378. * \code decoder != NULL \endcode
  90379. * \retval FLAC__bool
  90380. * \c false if any fatal read, write, or memory allocation error
  90381. * occurred (meaning decoding must stop), else \c true; for more
  90382. * information about the decoder, check the decoder state with
  90383. * FLAC__stream_decoder_get_state().
  90384. */
  90385. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90386. /** Decode until the end of the stream.
  90387. * This version instructs the decoder to decode from the current position
  90388. * and continue until the end of stream (the read callback returns
  90389. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90390. * callbacks return a fatal error.
  90391. *
  90392. * As the decoder needs more input it will call the read callback.
  90393. * As each metadata block and frame is decoded, the metadata or write
  90394. * callback will be called with the decoded metadata or frame.
  90395. *
  90396. * \param decoder An initialized decoder instance.
  90397. * \assert
  90398. * \code decoder != NULL \endcode
  90399. * \retval FLAC__bool
  90400. * \c false if any fatal read, write, or memory allocation error
  90401. * occurred (meaning decoding must stop), else \c true; for more
  90402. * information about the decoder, check the decoder state with
  90403. * FLAC__stream_decoder_get_state().
  90404. */
  90405. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90406. /** Skip one audio frame.
  90407. * This version instructs the decoder to 'skip' a single frame and stop,
  90408. * unless the callbacks return a fatal error or the read callback returns
  90409. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90410. *
  90411. * The decoding flow is the same as what occurs when
  90412. * FLAC__stream_decoder_process_single() is called to process an audio
  90413. * frame, except that this function does not decode the parsed data into
  90414. * PCM or call the write callback. The integrity of the frame is still
  90415. * checked the same way as in the other process functions.
  90416. *
  90417. * This function will return once one whole frame is skipped, in the
  90418. * same way that FLAC__stream_decoder_process_single() will return once
  90419. * one whole frame is decoded.
  90420. *
  90421. * This function can be used in more quickly determining FLAC frame
  90422. * boundaries when decoding of the actual data is not needed, for
  90423. * example when an application is separating a FLAC stream into frames
  90424. * for editing or storing in a container. To do this, the application
  90425. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90426. * to the next frame, then use
  90427. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90428. * boundary.
  90429. *
  90430. * This function should only be called when the stream has advanced
  90431. * past all the metadata, otherwise it will return \c false.
  90432. *
  90433. * \param decoder An initialized decoder instance not in a metadata
  90434. * state.
  90435. * \assert
  90436. * \code decoder != NULL \endcode
  90437. * \retval FLAC__bool
  90438. * \c false if any fatal read, write, or memory allocation error
  90439. * occurred (meaning decoding must stop), or if the decoder
  90440. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90441. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90442. * information about the decoder, check the decoder state with
  90443. * FLAC__stream_decoder_get_state().
  90444. */
  90445. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90446. /** Flush the input and seek to an absolute sample.
  90447. * Decoding will resume at the given sample. Note that because of
  90448. * this, the next write callback may contain a partial block. The
  90449. * client must support seeking the input or this function will fail
  90450. * and return \c false. Furthermore, if the decoder state is
  90451. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90452. * with FLAC__stream_decoder_flush() or reset with
  90453. * FLAC__stream_decoder_reset() before decoding can continue.
  90454. *
  90455. * \param decoder A decoder instance.
  90456. * \param sample The target sample number to seek to.
  90457. * \assert
  90458. * \code decoder != NULL \endcode
  90459. * \retval FLAC__bool
  90460. * \c true if successful, else \c false.
  90461. */
  90462. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90463. /* \} */
  90464. #ifdef __cplusplus
  90465. }
  90466. #endif
  90467. #endif
  90468. /*** End of inlined file: stream_decoder.h ***/
  90469. /*** Start of inlined file: stream_encoder.h ***/
  90470. #ifndef FLAC__STREAM_ENCODER_H
  90471. #define FLAC__STREAM_ENCODER_H
  90472. #include <stdio.h> /* for FILE */
  90473. #ifdef __cplusplus
  90474. extern "C" {
  90475. #endif
  90476. /** \file include/FLAC/stream_encoder.h
  90477. *
  90478. * \brief
  90479. * This module contains the functions which implement the stream
  90480. * encoder.
  90481. *
  90482. * See the detailed documentation in the
  90483. * \link flac_stream_encoder stream encoder \endlink module.
  90484. */
  90485. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90486. * \ingroup flac
  90487. *
  90488. * \brief
  90489. * This module describes the encoder layers provided by libFLAC.
  90490. *
  90491. * The stream encoder can be used to encode complete streams either to the
  90492. * client via callbacks, or directly to a file, depending on how it is
  90493. * initialized. When encoding via callbacks, the client provides a write
  90494. * callback which will be called whenever FLAC data is ready to be written.
  90495. * If the client also supplies a seek callback, the encoder will also
  90496. * automatically handle the writing back of metadata discovered while
  90497. * encoding, like stream info, seek points offsets, etc. When encoding to
  90498. * a file, the client needs only supply a filename or open \c FILE* and an
  90499. * optional progress callback for periodic notification of progress; the
  90500. * write and seek callbacks are supplied internally. For more info see the
  90501. * \link flac_stream_encoder stream encoder \endlink module.
  90502. */
  90503. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90504. * \ingroup flac_encoder
  90505. *
  90506. * \brief
  90507. * This module contains the functions which implement the stream
  90508. * encoder.
  90509. *
  90510. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90511. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90512. *
  90513. * The basic usage of this encoder is as follows:
  90514. * - The program creates an instance of an encoder using
  90515. * FLAC__stream_encoder_new().
  90516. * - The program overrides the default settings using
  90517. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90518. * functions should be called:
  90519. * - FLAC__stream_encoder_set_channels()
  90520. * - FLAC__stream_encoder_set_bits_per_sample()
  90521. * - FLAC__stream_encoder_set_sample_rate()
  90522. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90523. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90524. * - If the application wants to control the compression level or set its own
  90525. * metadata, then the following should also be called:
  90526. * - FLAC__stream_encoder_set_compression_level()
  90527. * - FLAC__stream_encoder_set_verify()
  90528. * - FLAC__stream_encoder_set_metadata()
  90529. * - The rest of the set functions should only be called if the client needs
  90530. * exact control over how the audio is compressed; thorough understanding
  90531. * of the FLAC format is necessary to achieve good results.
  90532. * - The program initializes the instance to validate the settings and
  90533. * prepare for encoding using
  90534. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90535. * or FLAC__stream_encoder_init_file() for native FLAC
  90536. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90537. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90538. * - The program calls FLAC__stream_encoder_process() or
  90539. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90540. * subsequently calls the callbacks when there is encoder data ready
  90541. * to be written.
  90542. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90543. * which causes the encoder to encode any data still in its input pipe,
  90544. * update the metadata with the final encoding statistics if output
  90545. * seeking is possible, and finally reset the encoder to the
  90546. * uninitialized state.
  90547. * - The instance may be used again or deleted with
  90548. * FLAC__stream_encoder_delete().
  90549. *
  90550. * In more detail, the stream encoder functions similarly to the
  90551. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90552. * callbacks and more options. Typically the client will create a new
  90553. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90554. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90555. * calling one of the FLAC__stream_encoder_init_*() functions.
  90556. *
  90557. * Unlike the decoders, the stream encoder has many options that can
  90558. * affect the speed and compression ratio. When setting these parameters
  90559. * you should have some basic knowledge of the format (see the
  90560. * <A HREF="../documentation.html#format">user-level documentation</A>
  90561. * or the <A HREF="../format.html">formal description</A>). The
  90562. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90563. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90564. * functions will do this, so make sure to pay attention to the state
  90565. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90566. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90567. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90568. * the constructor.
  90569. *
  90570. * There are three initialization functions for native FLAC, one for
  90571. * setting up the encoder to encode FLAC data to the client via
  90572. * callbacks, and two for encoding directly to a file.
  90573. *
  90574. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90575. * You must also supply a write callback which will be called anytime
  90576. * there is raw encoded data to write. If the client can seek the output
  90577. * it is best to also supply seek and tell callbacks, as this allows the
  90578. * encoder to go back after encoding is finished to write back
  90579. * information that was collected while encoding, like seek point offsets,
  90580. * frame sizes, etc.
  90581. *
  90582. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90583. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90584. * filename or open \c FILE*; the encoder will handle all the callbacks
  90585. * internally. You may also supply a progress callback for periodic
  90586. * notification of the encoding progress.
  90587. *
  90588. * There are three similarly-named init functions for encoding to Ogg
  90589. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90590. * library has been built with Ogg support.
  90591. *
  90592. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90593. * call the write callback several times, once with the \c fLaC signature,
  90594. * and once for each encoded metadata block. Note that for Ogg FLAC
  90595. * encoding you will usually get at least twice the number of callbacks than
  90596. * with native FLAC, one for the Ogg page header and one for the page body.
  90597. *
  90598. * After initializing the instance, the client may feed audio data to the
  90599. * encoder in one of two ways:
  90600. *
  90601. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90602. * will pass an array of pointers to buffers, one for each channel, to
  90603. * the encoder, each of the same length. The samples need not be
  90604. * block-aligned, but each channel should have the same number of samples.
  90605. * - Channel interleaved, through
  90606. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90607. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90608. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90609. * Again, the samples need not be block-aligned but they must be
  90610. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90611. * the last value channelN_sampleM.
  90612. *
  90613. * Note that for either process call, each sample in the buffers should be a
  90614. * signed integer, right-justified to the resolution set by
  90615. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90616. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90617. *
  90618. * When the client is finished encoding data, it calls
  90619. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90620. * data still in its input pipe, and call the metadata callback with the
  90621. * final encoding statistics. Then the instance may be deleted with
  90622. * FLAC__stream_encoder_delete() or initialized again to encode another
  90623. * stream.
  90624. *
  90625. * For programs that write their own metadata, but that do not know the
  90626. * actual metadata until after encoding, it is advantageous to instruct
  90627. * the encoder to write a PADDING block of the correct size, so that
  90628. * instead of rewriting the whole stream after encoding, the program can
  90629. * just overwrite the PADDING block. If only the maximum size of the
  90630. * metadata is known, the program can write a slightly larger padding
  90631. * block, then split it after encoding.
  90632. *
  90633. * Make sure you understand how lengths are calculated. All FLAC metadata
  90634. * blocks have a 4 byte header which contains the type and length. This
  90635. * length does not include the 4 bytes of the header. See the format page
  90636. * for the specification of metadata blocks and their lengths.
  90637. *
  90638. * \note
  90639. * If you are writing the FLAC data to a file via callbacks, make sure it
  90640. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90641. * after the first encoding pass, the encoder will try to seek back to the
  90642. * beginning of the stream, to the STREAMINFO block, to write some data
  90643. * there. (If using FLAC__stream_encoder_init*_file() or
  90644. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90645. *
  90646. * \note
  90647. * The "set" functions may only be called when the encoder is in the
  90648. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90649. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90650. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90651. * return \c true, otherwise \c false.
  90652. *
  90653. * \note
  90654. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90655. * defaults.
  90656. *
  90657. * \{
  90658. */
  90659. /** State values for a FLAC__StreamEncoder.
  90660. *
  90661. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90662. *
  90663. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90664. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90665. * must be deleted with FLAC__stream_encoder_delete().
  90666. */
  90667. typedef enum {
  90668. FLAC__STREAM_ENCODER_OK = 0,
  90669. /**< The encoder is in the normal OK state and samples can be processed. */
  90670. FLAC__STREAM_ENCODER_UNINITIALIZED,
  90671. /**< The encoder is in the uninitialized state; one of the
  90672. * FLAC__stream_encoder_init_*() functions must be called before samples
  90673. * can be processed.
  90674. */
  90675. FLAC__STREAM_ENCODER_OGG_ERROR,
  90676. /**< An error occurred in the underlying Ogg layer. */
  90677. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  90678. /**< An error occurred in the underlying verify stream decoder;
  90679. * check FLAC__stream_encoder_get_verify_decoder_state().
  90680. */
  90681. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  90682. /**< The verify decoder detected a mismatch between the original
  90683. * audio signal and the decoded audio signal.
  90684. */
  90685. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  90686. /**< One of the callbacks returned a fatal error. */
  90687. FLAC__STREAM_ENCODER_IO_ERROR,
  90688. /**< An I/O error occurred while opening/reading/writing a file.
  90689. * Check \c errno.
  90690. */
  90691. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  90692. /**< An error occurred while writing the stream; usually, the
  90693. * write_callback returned an error.
  90694. */
  90695. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  90696. /**< Memory allocation failed. */
  90697. } FLAC__StreamEncoderState;
  90698. /** Maps a FLAC__StreamEncoderState to a C string.
  90699. *
  90700. * Using a FLAC__StreamEncoderState as the index to this array
  90701. * will give the string equivalent. The contents should not be modified.
  90702. */
  90703. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  90704. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  90705. */
  90706. typedef enum {
  90707. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  90708. /**< Initialization was successful. */
  90709. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  90710. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  90711. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  90712. /**< The library was not compiled with support for the given container
  90713. * format.
  90714. */
  90715. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  90716. /**< A required callback was not supplied. */
  90717. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  90718. /**< The encoder has an invalid setting for number of channels. */
  90719. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  90720. /**< The encoder has an invalid setting for bits-per-sample.
  90721. * FLAC supports 4-32 bps but the reference encoder currently supports
  90722. * only up to 24 bps.
  90723. */
  90724. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  90725. /**< The encoder has an invalid setting for the input sample rate. */
  90726. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  90727. /**< The encoder has an invalid setting for the block size. */
  90728. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  90729. /**< The encoder has an invalid setting for the maximum LPC order. */
  90730. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  90731. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  90732. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  90733. /**< The specified block size is less than the maximum LPC order. */
  90734. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  90735. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  90736. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  90737. /**< The metadata input to the encoder is invalid, in one of the following ways:
  90738. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  90739. * - One of the metadata blocks contains an undefined type
  90740. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  90741. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  90742. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  90743. */
  90744. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  90745. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  90746. * already initialized, usually because
  90747. * FLAC__stream_encoder_finish() was not called.
  90748. */
  90749. } FLAC__StreamEncoderInitStatus;
  90750. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  90751. *
  90752. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  90753. * will give the string equivalent. The contents should not be modified.
  90754. */
  90755. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  90756. /** Return values for the FLAC__StreamEncoder read callback.
  90757. */
  90758. typedef enum {
  90759. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  90760. /**< The read was OK and decoding can continue. */
  90761. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  90762. /**< The read was attempted at the end of the stream. */
  90763. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  90764. /**< An unrecoverable error occurred. */
  90765. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  90766. /**< Client does not support reading back from the output. */
  90767. } FLAC__StreamEncoderReadStatus;
  90768. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  90769. *
  90770. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  90771. * will give the string equivalent. The contents should not be modified.
  90772. */
  90773. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  90774. /** Return values for the FLAC__StreamEncoder write callback.
  90775. */
  90776. typedef enum {
  90777. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  90778. /**< The write was OK and encoding can continue. */
  90779. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  90780. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  90781. } FLAC__StreamEncoderWriteStatus;
  90782. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  90783. *
  90784. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  90785. * will give the string equivalent. The contents should not be modified.
  90786. */
  90787. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  90788. /** Return values for the FLAC__StreamEncoder seek callback.
  90789. */
  90790. typedef enum {
  90791. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  90792. /**< The seek was OK and encoding can continue. */
  90793. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  90794. /**< An unrecoverable error occurred. */
  90795. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  90796. /**< Client does not support seeking. */
  90797. } FLAC__StreamEncoderSeekStatus;
  90798. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  90799. *
  90800. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  90801. * will give the string equivalent. The contents should not be modified.
  90802. */
  90803. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  90804. /** Return values for the FLAC__StreamEncoder tell callback.
  90805. */
  90806. typedef enum {
  90807. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  90808. /**< The tell was OK and encoding can continue. */
  90809. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  90810. /**< An unrecoverable error occurred. */
  90811. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  90812. /**< Client does not support seeking. */
  90813. } FLAC__StreamEncoderTellStatus;
  90814. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  90815. *
  90816. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  90817. * will give the string equivalent. The contents should not be modified.
  90818. */
  90819. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  90820. /***********************************************************************
  90821. *
  90822. * class FLAC__StreamEncoder
  90823. *
  90824. ***********************************************************************/
  90825. struct FLAC__StreamEncoderProtected;
  90826. struct FLAC__StreamEncoderPrivate;
  90827. /** The opaque structure definition for the stream encoder type.
  90828. * See the \link flac_stream_encoder stream encoder module \endlink
  90829. * for a detailed description.
  90830. */
  90831. typedef struct {
  90832. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  90833. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  90834. } FLAC__StreamEncoder;
  90835. /** Signature for the read callback.
  90836. *
  90837. * A function pointer matching this signature must be passed to
  90838. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  90839. * The supplied function will be called when the encoder needs to read back
  90840. * encoded data. This happens during the metadata callback, when the encoder
  90841. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  90842. * while encoding. The address of the buffer to be filled is supplied, along
  90843. * with the number of bytes the buffer can hold. The callback may choose to
  90844. * supply less data and modify the byte count but must be careful not to
  90845. * overflow the buffer. The callback then returns a status code chosen from
  90846. * FLAC__StreamEncoderReadStatus.
  90847. *
  90848. * Here is an example of a read callback for stdio streams:
  90849. * \code
  90850. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  90851. * {
  90852. * FILE *file = ((MyClientData*)client_data)->file;
  90853. * if(*bytes > 0) {
  90854. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  90855. * if(ferror(file))
  90856. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90857. * else if(*bytes == 0)
  90858. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  90859. * else
  90860. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  90861. * }
  90862. * else
  90863. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  90864. * }
  90865. * \endcode
  90866. *
  90867. * \note In general, FLAC__StreamEncoder functions which change the
  90868. * state should not be called on the \a encoder while in the callback.
  90869. *
  90870. * \param encoder The encoder instance calling the callback.
  90871. * \param buffer A pointer to a location for the callee to store
  90872. * data to be encoded.
  90873. * \param bytes A pointer to the size of the buffer. On entry
  90874. * to the callback, it contains the maximum number
  90875. * of bytes that may be stored in \a buffer. The
  90876. * callee must set it to the actual number of bytes
  90877. * stored (0 in case of error or end-of-stream) before
  90878. * returning.
  90879. * \param client_data The callee's client data set through
  90880. * FLAC__stream_encoder_set_client_data().
  90881. * \retval FLAC__StreamEncoderReadStatus
  90882. * The callee's return status.
  90883. */
  90884. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90885. /** Signature for the write callback.
  90886. *
  90887. * A function pointer matching this signature must be passed to
  90888. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90889. * by the encoder anytime there is raw encoded data ready to write. It may
  90890. * include metadata mixed with encoded audio frames and the data is not
  90891. * guaranteed to be aligned on frame or metadata block boundaries.
  90892. *
  90893. * The only duty of the callback is to write out the \a bytes worth of data
  90894. * in \a buffer to the current position in the output stream. The arguments
  90895. * \a samples and \a current_frame are purely informational. If \a samples
  90896. * is greater than \c 0, then \a current_frame will hold the current frame
  90897. * number that is being written; otherwise it indicates that the write
  90898. * callback is being called to write metadata.
  90899. *
  90900. * \note
  90901. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  90902. * write callback will be called twice when writing each audio
  90903. * frame; once for the page header, and once for the page body.
  90904. * When writing the page header, the \a samples argument to the
  90905. * write callback will be \c 0.
  90906. *
  90907. * \note In general, FLAC__StreamEncoder functions which change the
  90908. * state should not be called on the \a encoder while in the callback.
  90909. *
  90910. * \param encoder The encoder instance calling the callback.
  90911. * \param buffer An array of encoded data of length \a bytes.
  90912. * \param bytes The byte length of \a buffer.
  90913. * \param samples The number of samples encoded by \a buffer.
  90914. * \c 0 has a special meaning; see above.
  90915. * \param current_frame The number of the current frame being encoded.
  90916. * \param client_data The callee's client data set through
  90917. * FLAC__stream_encoder_init_*().
  90918. * \retval FLAC__StreamEncoderWriteStatus
  90919. * The callee's return status.
  90920. */
  90921. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  90922. /** Signature for the seek callback.
  90923. *
  90924. * A function pointer matching this signature may be passed to
  90925. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90926. * when the encoder needs to seek the output stream. The encoder will pass
  90927. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  90928. *
  90929. * Here is an example of a seek callback for stdio streams:
  90930. * \code
  90931. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90932. * {
  90933. * FILE *file = ((MyClientData*)client_data)->file;
  90934. * if(file == stdin)
  90935. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  90936. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90937. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  90938. * else
  90939. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  90940. * }
  90941. * \endcode
  90942. *
  90943. * \note In general, FLAC__StreamEncoder functions which change the
  90944. * state should not be called on the \a encoder while in the callback.
  90945. *
  90946. * \param encoder The encoder instance calling the callback.
  90947. * \param absolute_byte_offset The offset from the beginning of the stream
  90948. * to seek to.
  90949. * \param client_data The callee's client data set through
  90950. * FLAC__stream_encoder_init_*().
  90951. * \retval FLAC__StreamEncoderSeekStatus
  90952. * The callee's return status.
  90953. */
  90954. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90955. /** Signature for the tell callback.
  90956. *
  90957. * A function pointer matching this signature may be passed to
  90958. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  90959. * when the encoder needs to know the current position of the output stream.
  90960. *
  90961. * \warning
  90962. * The callback must return the true current byte offset of the output to
  90963. * which the encoder is writing. If you are buffering the output, make
  90964. * sure and take this into account. If you are writing directly to a
  90965. * FILE* from your write callback, ftell() is sufficient. If you are
  90966. * writing directly to a file descriptor from your write callback, you
  90967. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  90968. * these points to rewrite metadata after encoding.
  90969. *
  90970. * Here is an example of a tell callback for stdio streams:
  90971. * \code
  90972. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90973. * {
  90974. * FILE *file = ((MyClientData*)client_data)->file;
  90975. * off_t pos;
  90976. * if(file == stdin)
  90977. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  90978. * else if((pos = ftello(file)) < 0)
  90979. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  90980. * else {
  90981. * *absolute_byte_offset = (FLAC__uint64)pos;
  90982. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  90983. * }
  90984. * }
  90985. * \endcode
  90986. *
  90987. * \note In general, FLAC__StreamEncoder functions which change the
  90988. * state should not be called on the \a encoder while in the callback.
  90989. *
  90990. * \param encoder The encoder instance calling the callback.
  90991. * \param absolute_byte_offset The address at which to store the current
  90992. * position of the output.
  90993. * \param client_data The callee's client data set through
  90994. * FLAC__stream_encoder_init_*().
  90995. * \retval FLAC__StreamEncoderTellStatus
  90996. * The callee's return status.
  90997. */
  90998. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90999. /** Signature for the metadata callback.
  91000. *
  91001. * A function pointer matching this signature may be passed to
  91002. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91003. * once at the end of encoding with the populated STREAMINFO structure. This
  91004. * is so the client can seek back to the beginning of the file and write the
  91005. * STREAMINFO block with the correct statistics after encoding (like
  91006. * minimum/maximum frame size and total samples).
  91007. *
  91008. * \note In general, FLAC__StreamEncoder functions which change the
  91009. * state should not be called on the \a encoder while in the callback.
  91010. *
  91011. * \param encoder The encoder instance calling the callback.
  91012. * \param metadata The final populated STREAMINFO block.
  91013. * \param client_data The callee's client data set through
  91014. * FLAC__stream_encoder_init_*().
  91015. */
  91016. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91017. /** Signature for the progress callback.
  91018. *
  91019. * A function pointer matching this signature may be passed to
  91020. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91021. * The supplied function will be called when the encoder has finished
  91022. * writing a frame. The \c total_frames_estimate argument to the
  91023. * callback will be based on the value from
  91024. * FLAC__stream_encoder_set_total_samples_estimate().
  91025. *
  91026. * \note In general, FLAC__StreamEncoder functions which change the
  91027. * state should not be called on the \a encoder while in the callback.
  91028. *
  91029. * \param encoder The encoder instance calling the callback.
  91030. * \param bytes_written Bytes written so far.
  91031. * \param samples_written Samples written so far.
  91032. * \param frames_written Frames written so far.
  91033. * \param total_frames_estimate The estimate of the total number of
  91034. * frames to be written.
  91035. * \param client_data The callee's client data set through
  91036. * FLAC__stream_encoder_init_*().
  91037. */
  91038. 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);
  91039. /***********************************************************************
  91040. *
  91041. * Class constructor/destructor
  91042. *
  91043. ***********************************************************************/
  91044. /** Create a new stream encoder instance. The instance is created with
  91045. * default settings; see the individual FLAC__stream_encoder_set_*()
  91046. * functions for each setting's default.
  91047. *
  91048. * \retval FLAC__StreamEncoder*
  91049. * \c NULL if there was an error allocating memory, else the new instance.
  91050. */
  91051. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91052. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91053. *
  91054. * \param encoder A pointer to an existing encoder.
  91055. * \assert
  91056. * \code encoder != NULL \endcode
  91057. */
  91058. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91059. /***********************************************************************
  91060. *
  91061. * Public class method prototypes
  91062. *
  91063. ***********************************************************************/
  91064. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91065. *
  91066. * \note
  91067. * This does not need to be set for native FLAC encoding.
  91068. *
  91069. * \note
  91070. * It is recommended to set a serial number explicitly as the default of '0'
  91071. * may collide with other streams.
  91072. *
  91073. * \default \c 0
  91074. * \param encoder An encoder instance to set.
  91075. * \param serial_number See above.
  91076. * \assert
  91077. * \code encoder != NULL \endcode
  91078. * \retval FLAC__bool
  91079. * \c false if the encoder is already initialized, else \c true.
  91080. */
  91081. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91082. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91083. * encoded output by feeding it through an internal decoder and comparing
  91084. * the original signal against the decoded signal. If a mismatch occurs,
  91085. * the process call will return \c false. Note that this will slow the
  91086. * encoding process by the extra time required for decoding and comparison.
  91087. *
  91088. * \default \c false
  91089. * \param encoder An encoder instance to set.
  91090. * \param value Flag value (see above).
  91091. * \assert
  91092. * \code encoder != NULL \endcode
  91093. * \retval FLAC__bool
  91094. * \c false if the encoder is already initialized, else \c true.
  91095. */
  91096. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91097. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91098. * the encoder will comply with the Subset and will check the
  91099. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91100. * comply. If \c false, the settings may take advantage of the full
  91101. * range that the format allows.
  91102. *
  91103. * Make sure you know what it entails before setting this to \c false.
  91104. *
  91105. * \default \c true
  91106. * \param encoder An encoder instance to set.
  91107. * \param value Flag value (see above).
  91108. * \assert
  91109. * \code encoder != NULL \endcode
  91110. * \retval FLAC__bool
  91111. * \c false if the encoder is already initialized, else \c true.
  91112. */
  91113. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91114. /** Set the number of channels to be encoded.
  91115. *
  91116. * \default \c 2
  91117. * \param encoder An encoder instance to set.
  91118. * \param value See above.
  91119. * \assert
  91120. * \code encoder != NULL \endcode
  91121. * \retval FLAC__bool
  91122. * \c false if the encoder is already initialized, else \c true.
  91123. */
  91124. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91125. /** Set the sample resolution of the input to be encoded.
  91126. *
  91127. * \warning
  91128. * Do not feed the encoder data that is wider than the value you
  91129. * set here or you will generate an invalid stream.
  91130. *
  91131. * \default \c 16
  91132. * \param encoder An encoder instance to set.
  91133. * \param value See above.
  91134. * \assert
  91135. * \code encoder != NULL \endcode
  91136. * \retval FLAC__bool
  91137. * \c false if the encoder is already initialized, else \c true.
  91138. */
  91139. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91140. /** Set the sample rate (in Hz) of the input to be encoded.
  91141. *
  91142. * \default \c 44100
  91143. * \param encoder An encoder instance to set.
  91144. * \param value See above.
  91145. * \assert
  91146. * \code encoder != NULL \endcode
  91147. * \retval FLAC__bool
  91148. * \c false if the encoder is already initialized, else \c true.
  91149. */
  91150. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91151. /** Set the compression level
  91152. *
  91153. * The compression level is roughly proportional to the amount of effort
  91154. * the encoder expends to compress the file. A higher level usually
  91155. * means more computation but higher compression. The default level is
  91156. * suitable for most applications.
  91157. *
  91158. * Currently the levels range from \c 0 (fastest, least compression) to
  91159. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91160. * treated as \c 8.
  91161. *
  91162. * This function automatically calls the following other \c _set_
  91163. * functions with appropriate values, so the client does not need to
  91164. * unless it specifically wants to override them:
  91165. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91166. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91167. * - FLAC__stream_encoder_set_apodization()
  91168. * - FLAC__stream_encoder_set_max_lpc_order()
  91169. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91170. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91171. * - FLAC__stream_encoder_set_do_escape_coding()
  91172. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91173. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91174. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91175. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91176. *
  91177. * The actual values set for each level are:
  91178. * <table>
  91179. * <tr>
  91180. * <td><b>level</b><td>
  91181. * <td>do mid-side stereo<td>
  91182. * <td>loose mid-side stereo<td>
  91183. * <td>apodization<td>
  91184. * <td>max lpc order<td>
  91185. * <td>qlp coeff precision<td>
  91186. * <td>qlp coeff prec search<td>
  91187. * <td>escape coding<td>
  91188. * <td>exhaustive model search<td>
  91189. * <td>min residual partition order<td>
  91190. * <td>max residual partition order<td>
  91191. * <td>rice parameter search dist<td>
  91192. * </tr>
  91193. * <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>
  91194. * <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>
  91195. * <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>
  91196. * <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>
  91197. * <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>
  91198. * <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>
  91199. * <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>
  91200. * <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>
  91201. * <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>
  91202. * </table>
  91203. *
  91204. * \default \c 5
  91205. * \param encoder An encoder instance to set.
  91206. * \param value See above.
  91207. * \assert
  91208. * \code encoder != NULL \endcode
  91209. * \retval FLAC__bool
  91210. * \c false if the encoder is already initialized, else \c true.
  91211. */
  91212. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91213. /** Set the blocksize to use while encoding.
  91214. *
  91215. * The number of samples to use per frame. Use \c 0 to let the encoder
  91216. * estimate a blocksize; this is usually best.
  91217. *
  91218. * \default \c 0
  91219. * \param encoder An encoder instance to set.
  91220. * \param value See above.
  91221. * \assert
  91222. * \code encoder != NULL \endcode
  91223. * \retval FLAC__bool
  91224. * \c false if the encoder is already initialized, else \c true.
  91225. */
  91226. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91227. /** Set to \c true to enable mid-side encoding on stereo input. The
  91228. * number of channels must be 2 for this to have any effect. Set to
  91229. * \c false to use only independent channel coding.
  91230. *
  91231. * \default \c false
  91232. * \param encoder An encoder instance to set.
  91233. * \param value Flag value (see above).
  91234. * \assert
  91235. * \code encoder != NULL \endcode
  91236. * \retval FLAC__bool
  91237. * \c false if the encoder is already initialized, else \c true.
  91238. */
  91239. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91240. /** Set to \c true to enable adaptive switching between mid-side and
  91241. * left-right encoding on stereo input. Set to \c false to use
  91242. * exhaustive searching. Setting this to \c true requires
  91243. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91244. * \c true in order to have any effect.
  91245. *
  91246. * \default \c false
  91247. * \param encoder An encoder instance to set.
  91248. * \param value Flag value (see above).
  91249. * \assert
  91250. * \code encoder != NULL \endcode
  91251. * \retval FLAC__bool
  91252. * \c false if the encoder is already initialized, else \c true.
  91253. */
  91254. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91255. /** Sets the apodization function(s) the encoder will use when windowing
  91256. * audio data for LPC analysis.
  91257. *
  91258. * The \a specification is a plain ASCII string which specifies exactly
  91259. * which functions to use. There may be more than one (up to 32),
  91260. * separated by \c ';' characters. Some functions take one or more
  91261. * comma-separated arguments in parentheses.
  91262. *
  91263. * The available functions are \c bartlett, \c bartlett_hann,
  91264. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91265. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91266. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91267. *
  91268. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91269. * (0<STDDEV<=0.5).
  91270. *
  91271. * For \c tukey(P), P specifies the fraction of the window that is
  91272. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91273. * corresponds to \c hann.
  91274. *
  91275. * Example specifications are \c "blackman" or
  91276. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91277. *
  91278. * Any function that is specified erroneously is silently dropped. Up
  91279. * to 32 functions are kept, the rest are dropped. If the specification
  91280. * is empty the encoder defaults to \c "tukey(0.5)".
  91281. *
  91282. * When more than one function is specified, then for every subframe the
  91283. * encoder will try each of them separately and choose the window that
  91284. * results in the smallest compressed subframe.
  91285. *
  91286. * Note that each function specified causes the encoder to occupy a
  91287. * floating point array in which to store the window.
  91288. *
  91289. * \default \c "tukey(0.5)"
  91290. * \param encoder An encoder instance to set.
  91291. * \param specification See above.
  91292. * \assert
  91293. * \code encoder != NULL \endcode
  91294. * \code specification != NULL \endcode
  91295. * \retval FLAC__bool
  91296. * \c false if the encoder is already initialized, else \c true.
  91297. */
  91298. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91299. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91300. *
  91301. * \default \c 0
  91302. * \param encoder An encoder instance to set.
  91303. * \param value See above.
  91304. * \assert
  91305. * \code encoder != NULL \endcode
  91306. * \retval FLAC__bool
  91307. * \c false if the encoder is already initialized, else \c true.
  91308. */
  91309. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91310. /** Set the precision, in bits, of the quantized linear predictor
  91311. * coefficients, or \c 0 to let the encoder select it based on the
  91312. * blocksize.
  91313. *
  91314. * \note
  91315. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91316. * be less than 32.
  91317. *
  91318. * \default \c 0
  91319. * \param encoder An encoder instance to set.
  91320. * \param value See above.
  91321. * \assert
  91322. * \code encoder != NULL \endcode
  91323. * \retval FLAC__bool
  91324. * \c false if the encoder is already initialized, else \c true.
  91325. */
  91326. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91327. /** Set to \c false to use only the specified quantized linear predictor
  91328. * coefficient precision, or \c true to search neighboring precision
  91329. * values and use the best one.
  91330. *
  91331. * \default \c false
  91332. * \param encoder An encoder instance to set.
  91333. * \param value See above.
  91334. * \assert
  91335. * \code encoder != NULL \endcode
  91336. * \retval FLAC__bool
  91337. * \c false if the encoder is already initialized, else \c true.
  91338. */
  91339. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91340. /** Deprecated. Setting this value has no effect.
  91341. *
  91342. * \default \c false
  91343. * \param encoder An encoder instance to set.
  91344. * \param value See above.
  91345. * \assert
  91346. * \code encoder != NULL \endcode
  91347. * \retval FLAC__bool
  91348. * \c false if the encoder is already initialized, else \c true.
  91349. */
  91350. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91351. /** Set to \c false to let the encoder estimate the best model order
  91352. * based on the residual signal energy, or \c true to force the
  91353. * encoder to evaluate all order models and select the best.
  91354. *
  91355. * \default \c false
  91356. * \param encoder An encoder instance to set.
  91357. * \param value See above.
  91358. * \assert
  91359. * \code encoder != NULL \endcode
  91360. * \retval FLAC__bool
  91361. * \c false if the encoder is already initialized, else \c true.
  91362. */
  91363. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91364. /** Set the minimum partition order to search when coding the residual.
  91365. * This is used in tandem with
  91366. * FLAC__stream_encoder_set_max_residual_partition_order().
  91367. *
  91368. * The partition order determines the context size in the residual.
  91369. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91370. *
  91371. * Set both min and max values to \c 0 to force a single context,
  91372. * whose Rice parameter is based on the residual signal variance.
  91373. * Otherwise, set a min and max order, and the encoder will search
  91374. * all orders, using the mean of each context for its Rice parameter,
  91375. * and use the best.
  91376. *
  91377. * \default \c 0
  91378. * \param encoder An encoder instance to set.
  91379. * \param value See above.
  91380. * \assert
  91381. * \code encoder != NULL \endcode
  91382. * \retval FLAC__bool
  91383. * \c false if the encoder is already initialized, else \c true.
  91384. */
  91385. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91386. /** Set the maximum partition order to search when coding the residual.
  91387. * This is used in tandem with
  91388. * FLAC__stream_encoder_set_min_residual_partition_order().
  91389. *
  91390. * The partition order determines the context size in the residual.
  91391. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91392. *
  91393. * Set both min and max values to \c 0 to force a single context,
  91394. * whose Rice parameter is based on the residual signal variance.
  91395. * Otherwise, set a min and max order, and the encoder will search
  91396. * all orders, using the mean of each context for its Rice parameter,
  91397. * and use the best.
  91398. *
  91399. * \default \c 0
  91400. * \param encoder An encoder instance to set.
  91401. * \param value See above.
  91402. * \assert
  91403. * \code encoder != NULL \endcode
  91404. * \retval FLAC__bool
  91405. * \c false if the encoder is already initialized, else \c true.
  91406. */
  91407. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91408. /** Deprecated. Setting this value has no effect.
  91409. *
  91410. * \default \c 0
  91411. * \param encoder An encoder instance to set.
  91412. * \param value See above.
  91413. * \assert
  91414. * \code encoder != NULL \endcode
  91415. * \retval FLAC__bool
  91416. * \c false if the encoder is already initialized, else \c true.
  91417. */
  91418. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91419. /** Set an estimate of the total samples that will be encoded.
  91420. * This is merely an estimate and may be set to \c 0 if unknown.
  91421. * This value will be written to the STREAMINFO block before encoding,
  91422. * and can remove the need for the caller to rewrite the value later
  91423. * if the value is known before encoding.
  91424. *
  91425. * \default \c 0
  91426. * \param encoder An encoder instance to set.
  91427. * \param value See above.
  91428. * \assert
  91429. * \code encoder != NULL \endcode
  91430. * \retval FLAC__bool
  91431. * \c false if the encoder is already initialized, else \c true.
  91432. */
  91433. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91434. /** Set the metadata blocks to be emitted to the stream before encoding.
  91435. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91436. * array of pointers to metadata blocks. The array is non-const since
  91437. * the encoder may need to change the \a is_last flag inside them, and
  91438. * in some cases update seek point offsets. Otherwise, the encoder will
  91439. * not modify or free the blocks. It is up to the caller to free the
  91440. * metadata blocks after encoding finishes.
  91441. *
  91442. * \note
  91443. * The encoder stores only copies of the pointers in the \a metadata array;
  91444. * the metadata blocks themselves must survive at least until after
  91445. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91446. *
  91447. * \note
  91448. * The STREAMINFO block is always written and no STREAMINFO block may
  91449. * occur in the supplied array.
  91450. *
  91451. * \note
  91452. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91453. * in the \a metadata array, but the client has specified that it does not
  91454. * support seeking, then the SEEKTABLE will be written verbatim. However
  91455. * by itself this is not very useful as the client will not know the stream
  91456. * offsets for the seekpoints ahead of time. In order to get a proper
  91457. * seektable the client must support seeking. See next note.
  91458. *
  91459. * \note
  91460. * SEEKTABLE blocks are handled specially. Since you will not know
  91461. * the values for the seek point stream offsets, you should pass in
  91462. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91463. * required sample numbers (or placeholder points), with \c 0 for the
  91464. * \a frame_samples and \a stream_offset fields for each point. If the
  91465. * client has specified that it supports seeking by providing a seek
  91466. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91467. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91468. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91469. * then while it is encoding the encoder will fill the stream offsets in
  91470. * for you and when encoding is finished, it will seek back and write the
  91471. * real values into the SEEKTABLE block in the stream. There are helper
  91472. * routines for manipulating seektable template blocks; see metadata.h:
  91473. * FLAC__metadata_object_seektable_template_*(). If the client does
  91474. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91475. * will slow down or remove the ability to seek in the FLAC stream.
  91476. *
  91477. * \note
  91478. * The encoder instance \b will modify the first \c SEEKTABLE block
  91479. * as it transforms the template to a valid seektable while encoding,
  91480. * but it is still up to the caller to free all metadata blocks after
  91481. * encoding.
  91482. *
  91483. * \note
  91484. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91485. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91486. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91487. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91488. * block is present in the \a metadata array, libFLAC will write an
  91489. * empty one, containing only the vendor string.
  91490. *
  91491. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91492. * the second metadata block of the stream. The encoder already supplies
  91493. * the STREAMINFO block automatically. If \a metadata does not contain a
  91494. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91495. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91496. * first, the init function will reorder \a metadata by moving the
  91497. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91498. * blocks will remain as they were.
  91499. *
  91500. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91501. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91502. * return \c false.
  91503. *
  91504. * \default \c NULL, 0
  91505. * \param encoder An encoder instance to set.
  91506. * \param metadata See above.
  91507. * \param num_blocks See above.
  91508. * \assert
  91509. * \code encoder != NULL \endcode
  91510. * \retval FLAC__bool
  91511. * \c false if the encoder is already initialized, else \c true.
  91512. * \c false if the encoder is already initialized, or if
  91513. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91514. */
  91515. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91516. /** Get the current encoder state.
  91517. *
  91518. * \param encoder An encoder instance to query.
  91519. * \assert
  91520. * \code encoder != NULL \endcode
  91521. * \retval FLAC__StreamEncoderState
  91522. * The current encoder state.
  91523. */
  91524. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91525. /** Get the state of the verify stream decoder.
  91526. * Useful when the stream encoder state is
  91527. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91528. *
  91529. * \param encoder An encoder instance to query.
  91530. * \assert
  91531. * \code encoder != NULL \endcode
  91532. * \retval FLAC__StreamDecoderState
  91533. * The verify stream decoder state.
  91534. */
  91535. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91536. /** Get the current encoder state as a C string.
  91537. * This version automatically resolves
  91538. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91539. * verify decoder's state.
  91540. *
  91541. * \param encoder A encoder instance to query.
  91542. * \assert
  91543. * \code encoder != NULL \endcode
  91544. * \retval const char *
  91545. * The encoder state as a C string. Do not modify the contents.
  91546. */
  91547. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91548. /** Get relevant values about the nature of a verify decoder error.
  91549. * Useful when the stream encoder state is
  91550. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91551. * be addresses in which the stats will be returned, or NULL if value
  91552. * is not desired.
  91553. *
  91554. * \param encoder An encoder instance to query.
  91555. * \param absolute_sample The absolute sample number of the mismatch.
  91556. * \param frame_number The number of the frame in which the mismatch occurred.
  91557. * \param channel The channel in which the mismatch occurred.
  91558. * \param sample The number of the sample (relative to the frame) in
  91559. * which the mismatch occurred.
  91560. * \param expected The expected value for the sample in question.
  91561. * \param got The actual value returned by the decoder.
  91562. * \assert
  91563. * \code encoder != NULL \endcode
  91564. */
  91565. 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);
  91566. /** Get the "verify" flag.
  91567. *
  91568. * \param encoder An encoder instance to query.
  91569. * \assert
  91570. * \code encoder != NULL \endcode
  91571. * \retval FLAC__bool
  91572. * See FLAC__stream_encoder_set_verify().
  91573. */
  91574. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91575. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91576. *
  91577. * \param encoder An encoder instance to query.
  91578. * \assert
  91579. * \code encoder != NULL \endcode
  91580. * \retval FLAC__bool
  91581. * See FLAC__stream_encoder_set_streamable_subset().
  91582. */
  91583. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91584. /** Get the number of input channels being processed.
  91585. *
  91586. * \param encoder An encoder instance to query.
  91587. * \assert
  91588. * \code encoder != NULL \endcode
  91589. * \retval unsigned
  91590. * See FLAC__stream_encoder_set_channels().
  91591. */
  91592. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91593. /** Get the input sample resolution setting.
  91594. *
  91595. * \param encoder An encoder instance to query.
  91596. * \assert
  91597. * \code encoder != NULL \endcode
  91598. * \retval unsigned
  91599. * See FLAC__stream_encoder_set_bits_per_sample().
  91600. */
  91601. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91602. /** Get the input sample rate setting.
  91603. *
  91604. * \param encoder An encoder instance to query.
  91605. * \assert
  91606. * \code encoder != NULL \endcode
  91607. * \retval unsigned
  91608. * See FLAC__stream_encoder_set_sample_rate().
  91609. */
  91610. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91611. /** Get the blocksize setting.
  91612. *
  91613. * \param encoder An encoder instance to query.
  91614. * \assert
  91615. * \code encoder != NULL \endcode
  91616. * \retval unsigned
  91617. * See FLAC__stream_encoder_set_blocksize().
  91618. */
  91619. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91620. /** Get the "mid/side stereo coding" flag.
  91621. *
  91622. * \param encoder An encoder instance to query.
  91623. * \assert
  91624. * \code encoder != NULL \endcode
  91625. * \retval FLAC__bool
  91626. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91627. */
  91628. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91629. /** Get the "adaptive mid/side switching" flag.
  91630. *
  91631. * \param encoder An encoder instance to query.
  91632. * \assert
  91633. * \code encoder != NULL \endcode
  91634. * \retval FLAC__bool
  91635. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91636. */
  91637. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91638. /** Get the maximum LPC order setting.
  91639. *
  91640. * \param encoder An encoder instance to query.
  91641. * \assert
  91642. * \code encoder != NULL \endcode
  91643. * \retval unsigned
  91644. * See FLAC__stream_encoder_set_max_lpc_order().
  91645. */
  91646. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91647. /** Get the quantized linear predictor coefficient precision setting.
  91648. *
  91649. * \param encoder An encoder instance to query.
  91650. * \assert
  91651. * \code encoder != NULL \endcode
  91652. * \retval unsigned
  91653. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91654. */
  91655. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91656. /** Get the qlp coefficient precision search flag.
  91657. *
  91658. * \param encoder An encoder instance to query.
  91659. * \assert
  91660. * \code encoder != NULL \endcode
  91661. * \retval FLAC__bool
  91662. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91663. */
  91664. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91665. /** Get the "escape coding" flag.
  91666. *
  91667. * \param encoder An encoder instance to query.
  91668. * \assert
  91669. * \code encoder != NULL \endcode
  91670. * \retval FLAC__bool
  91671. * See FLAC__stream_encoder_set_do_escape_coding().
  91672. */
  91673. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  91674. /** Get the exhaustive model search flag.
  91675. *
  91676. * \param encoder An encoder instance to query.
  91677. * \assert
  91678. * \code encoder != NULL \endcode
  91679. * \retval FLAC__bool
  91680. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  91681. */
  91682. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  91683. /** Get the minimum residual partition order setting.
  91684. *
  91685. * \param encoder An encoder instance to query.
  91686. * \assert
  91687. * \code encoder != NULL \endcode
  91688. * \retval unsigned
  91689. * See FLAC__stream_encoder_set_min_residual_partition_order().
  91690. */
  91691. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91692. /** Get maximum residual partition order setting.
  91693. *
  91694. * \param encoder An encoder instance to query.
  91695. * \assert
  91696. * \code encoder != NULL \endcode
  91697. * \retval unsigned
  91698. * See FLAC__stream_encoder_set_max_residual_partition_order().
  91699. */
  91700. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  91701. /** Get the Rice parameter search distance setting.
  91702. *
  91703. * \param encoder An encoder instance to query.
  91704. * \assert
  91705. * \code encoder != NULL \endcode
  91706. * \retval unsigned
  91707. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  91708. */
  91709. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  91710. /** Get the previously set estimate of the total samples to be encoded.
  91711. * The encoder merely mimics back the value given to
  91712. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  91713. * other way of knowing how many samples the client will encode.
  91714. *
  91715. * \param encoder An encoder instance to set.
  91716. * \assert
  91717. * \code encoder != NULL \endcode
  91718. * \retval FLAC__uint64
  91719. * See FLAC__stream_encoder_get_total_samples_estimate().
  91720. */
  91721. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  91722. /** Initialize the encoder instance to encode native FLAC streams.
  91723. *
  91724. * This flavor of initialization sets up the encoder to encode to a
  91725. * native FLAC stream. I/O is performed via callbacks to the client.
  91726. * For encoding to a plain file via filename or open \c FILE*,
  91727. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  91728. * provide a simpler interface.
  91729. *
  91730. * This function should be called after FLAC__stream_encoder_new() and
  91731. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91732. * or FLAC__stream_encoder_process_interleaved().
  91733. * initialization succeeded.
  91734. *
  91735. * The call to FLAC__stream_encoder_init_stream() currently will also
  91736. * immediately call the write callback several times, once with the \c fLaC
  91737. * signature, and once for each encoded metadata block.
  91738. *
  91739. * \param encoder An uninitialized encoder instance.
  91740. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91741. * pointer must not be \c NULL.
  91742. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91743. * pointer may be \c NULL if seeking is not
  91744. * supported. The encoder uses seeking to go back
  91745. * and write some some stream statistics to the
  91746. * STREAMINFO block; this is recommended but not
  91747. * necessary to create a valid FLAC stream. If
  91748. * \a seek_callback is not \c NULL then a
  91749. * \a tell_callback must also be supplied.
  91750. * Alternatively, a dummy seek callback that just
  91751. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91752. * may also be supplied, all though this is slightly
  91753. * less efficient for the encoder.
  91754. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91755. * pointer may be \c NULL if seeking is not
  91756. * supported. If \a seek_callback is \c NULL then
  91757. * this argument will be ignored. If
  91758. * \a seek_callback is not \c NULL then a
  91759. * \a tell_callback must also be supplied.
  91760. * Alternatively, a dummy tell callback that just
  91761. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91762. * may also be supplied, all though this is slightly
  91763. * less efficient for the encoder.
  91764. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91765. * pointer may be \c NULL if the callback is not
  91766. * desired. If the client provides a seek callback,
  91767. * this function is not necessary as the encoder
  91768. * will automatically seek back and update the
  91769. * STREAMINFO block. It may also be \c NULL if the
  91770. * client does not support seeking, since it will
  91771. * have no way of going back to update the
  91772. * STREAMINFO. However the client can still supply
  91773. * a callback if it would like to know the details
  91774. * from the STREAMINFO.
  91775. * \param client_data This value will be supplied to callbacks in their
  91776. * \a client_data argument.
  91777. * \assert
  91778. * \code encoder != NULL \endcode
  91779. * \retval FLAC__StreamEncoderInitStatus
  91780. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91781. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91782. */
  91783. 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);
  91784. /** Initialize the encoder instance to encode Ogg FLAC streams.
  91785. *
  91786. * This flavor of initialization sets up the encoder to encode to a FLAC
  91787. * stream in an Ogg container. I/O is performed via callbacks to the
  91788. * client. For encoding to a plain file via filename or open \c FILE*,
  91789. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  91790. * provide a simpler interface.
  91791. *
  91792. * This function should be called after FLAC__stream_encoder_new() and
  91793. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91794. * or FLAC__stream_encoder_process_interleaved().
  91795. * initialization succeeded.
  91796. *
  91797. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  91798. * immediately call the write callback several times to write the metadata
  91799. * packets.
  91800. *
  91801. * \param encoder An uninitialized encoder instance.
  91802. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  91803. * pointer must not be \c NULL if \a seek_callback
  91804. * is non-NULL since they are both needed to be
  91805. * able to write data back to the Ogg FLAC stream
  91806. * in the post-encode phase.
  91807. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  91808. * pointer must not be \c NULL.
  91809. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  91810. * pointer may be \c NULL if seeking is not
  91811. * supported. The encoder uses seeking to go back
  91812. * and write some some stream statistics to the
  91813. * STREAMINFO block; this is recommended but not
  91814. * necessary to create a valid FLAC stream. If
  91815. * \a seek_callback is not \c NULL then a
  91816. * \a tell_callback must also be supplied.
  91817. * Alternatively, a dummy seek callback that just
  91818. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91819. * may also be supplied, all though this is slightly
  91820. * less efficient for the encoder.
  91821. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  91822. * pointer may be \c NULL if seeking is not
  91823. * supported. If \a seek_callback is \c NULL then
  91824. * this argument will be ignored. If
  91825. * \a seek_callback is not \c NULL then a
  91826. * \a tell_callback must also be supplied.
  91827. * Alternatively, a dummy tell callback that just
  91828. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91829. * may also be supplied, all though this is slightly
  91830. * less efficient for the encoder.
  91831. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  91832. * pointer may be \c NULL if the callback is not
  91833. * desired. If the client provides a seek callback,
  91834. * this function is not necessary as the encoder
  91835. * will automatically seek back and update the
  91836. * STREAMINFO block. It may also be \c NULL if the
  91837. * client does not support seeking, since it will
  91838. * have no way of going back to update the
  91839. * STREAMINFO. However the client can still supply
  91840. * a callback if it would like to know the details
  91841. * from the STREAMINFO.
  91842. * \param client_data This value will be supplied to callbacks in their
  91843. * \a client_data argument.
  91844. * \assert
  91845. * \code encoder != NULL \endcode
  91846. * \retval FLAC__StreamEncoderInitStatus
  91847. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91848. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91849. */
  91850. 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);
  91851. /** Initialize the encoder instance to encode native FLAC files.
  91852. *
  91853. * This flavor of initialization sets up the encoder to encode to a
  91854. * plain native FLAC file. For non-stdio streams, you must use
  91855. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  91856. *
  91857. * This function should be called after FLAC__stream_encoder_new() and
  91858. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91859. * or FLAC__stream_encoder_process_interleaved().
  91860. * initialization succeeded.
  91861. *
  91862. * \param encoder An uninitialized encoder instance.
  91863. * \param file An open file. The file should have been opened
  91864. * with mode \c "w+b" and rewound. The file
  91865. * becomes owned by the encoder and should not be
  91866. * manipulated by the client while encoding.
  91867. * Unless \a file is \c stdout, it will be closed
  91868. * when FLAC__stream_encoder_finish() is called.
  91869. * Note however that a proper SEEKTABLE cannot be
  91870. * created when encoding to \c stdout since it is
  91871. * not seekable.
  91872. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91873. * pointer may be \c NULL if the callback is not
  91874. * desired.
  91875. * \param client_data This value will be supplied to callbacks in their
  91876. * \a client_data argument.
  91877. * \assert
  91878. * \code encoder != NULL \endcode
  91879. * \code file != NULL \endcode
  91880. * \retval FLAC__StreamEncoderInitStatus
  91881. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91882. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91883. */
  91884. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91885. /** Initialize the encoder instance to encode Ogg FLAC files.
  91886. *
  91887. * This flavor of initialization sets up the encoder to encode to a
  91888. * plain Ogg FLAC file. For non-stdio streams, you must use
  91889. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  91890. *
  91891. * This function should be called after FLAC__stream_encoder_new() and
  91892. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91893. * or FLAC__stream_encoder_process_interleaved().
  91894. * initialization succeeded.
  91895. *
  91896. * \param encoder An uninitialized encoder instance.
  91897. * \param file An open file. The file should have been opened
  91898. * with mode \c "w+b" and rewound. The file
  91899. * becomes owned by the encoder and should not be
  91900. * manipulated by the client while encoding.
  91901. * Unless \a file is \c stdout, it will be closed
  91902. * when FLAC__stream_encoder_finish() is called.
  91903. * Note however that a proper SEEKTABLE cannot be
  91904. * created when encoding to \c stdout since it is
  91905. * not seekable.
  91906. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91907. * pointer may be \c NULL if the callback is not
  91908. * desired.
  91909. * \param client_data This value will be supplied to callbacks in their
  91910. * \a client_data argument.
  91911. * \assert
  91912. * \code encoder != NULL \endcode
  91913. * \code file != NULL \endcode
  91914. * \retval FLAC__StreamEncoderInitStatus
  91915. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91916. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91917. */
  91918. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91919. /** Initialize the encoder instance to encode native FLAC files.
  91920. *
  91921. * This flavor of initialization sets up the encoder to encode to a plain
  91922. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91923. * with Unicode filenames on Windows), you must use
  91924. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  91925. * and provide callbacks for the I/O.
  91926. *
  91927. * This function should be called after FLAC__stream_encoder_new() and
  91928. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91929. * or FLAC__stream_encoder_process_interleaved().
  91930. * initialization succeeded.
  91931. *
  91932. * \param encoder An uninitialized encoder instance.
  91933. * \param filename The name of the file to encode to. The file will
  91934. * be opened with fopen(). Use \c NULL to encode to
  91935. * \c stdout. Note however that a proper SEEKTABLE
  91936. * cannot be created when encoding to \c stdout since
  91937. * it is not seekable.
  91938. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91939. * pointer may be \c NULL if the callback is not
  91940. * desired.
  91941. * \param client_data This value will be supplied to callbacks in their
  91942. * \a client_data argument.
  91943. * \assert
  91944. * \code encoder != NULL \endcode
  91945. * \retval FLAC__StreamEncoderInitStatus
  91946. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91947. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91948. */
  91949. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91950. /** Initialize the encoder instance to encode Ogg FLAC files.
  91951. *
  91952. * This flavor of initialization sets up the encoder to encode to a plain
  91953. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  91954. * with Unicode filenames on Windows), you must use
  91955. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  91956. * and provide callbacks for the I/O.
  91957. *
  91958. * This function should be called after FLAC__stream_encoder_new() and
  91959. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  91960. * or FLAC__stream_encoder_process_interleaved().
  91961. * initialization succeeded.
  91962. *
  91963. * \param encoder An uninitialized encoder instance.
  91964. * \param filename The name of the file to encode to. The file will
  91965. * be opened with fopen(). Use \c NULL to encode to
  91966. * \c stdout. Note however that a proper SEEKTABLE
  91967. * cannot be created when encoding to \c stdout since
  91968. * it is not seekable.
  91969. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  91970. * pointer may be \c NULL if the callback is not
  91971. * desired.
  91972. * \param client_data This value will be supplied to callbacks in their
  91973. * \a client_data argument.
  91974. * \assert
  91975. * \code encoder != NULL \endcode
  91976. * \retval FLAC__StreamEncoderInitStatus
  91977. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  91978. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  91979. */
  91980. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  91981. /** Finish the encoding process.
  91982. * Flushes the encoding buffer, releases resources, resets the encoder
  91983. * settings to their defaults, and returns the encoder state to
  91984. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  91985. * one or more write callbacks before returning, and will generate
  91986. * a metadata callback.
  91987. *
  91988. * Note that in the course of processing the last frame, errors can
  91989. * occur, so the caller should be sure to check the return value to
  91990. * ensure the file was encoded properly.
  91991. *
  91992. * In the event of a prematurely-terminated encode, it is not strictly
  91993. * necessary to call this immediately before FLAC__stream_encoder_delete()
  91994. * but it is good practice to match every FLAC__stream_encoder_init_*()
  91995. * with a FLAC__stream_encoder_finish().
  91996. *
  91997. * \param encoder An uninitialized encoder instance.
  91998. * \assert
  91999. * \code encoder != NULL \endcode
  92000. * \retval FLAC__bool
  92001. * \c false if an error occurred processing the last frame; or if verify
  92002. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92003. * verify mismatch; else \c true. If \c false, caller should check the
  92004. * state with FLAC__stream_encoder_get_state() for more information
  92005. * about the error.
  92006. */
  92007. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92008. /** Submit data for encoding.
  92009. * This version allows you to supply the input data via an array of
  92010. * pointers, each pointer pointing to an array of \a samples samples
  92011. * representing one channel. The samples need not be block-aligned,
  92012. * but each channel should have the same number of samples. Each sample
  92013. * should be a signed integer, right-justified to the resolution set by
  92014. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92015. * resolution is 16 bits per sample, the samples should all be in the
  92016. * range [-32768,32767].
  92017. *
  92018. * For applications where channel order is important, channels must
  92019. * follow the order as described in the
  92020. * <A HREF="../format.html#frame_header">frame header</A>.
  92021. *
  92022. * \param encoder An initialized encoder instance in the OK state.
  92023. * \param buffer An array of pointers to each channel's signal.
  92024. * \param samples The number of samples in one channel.
  92025. * \assert
  92026. * \code encoder != NULL \endcode
  92027. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92028. * \retval FLAC__bool
  92029. * \c true if successful, else \c false; in this case, check the
  92030. * encoder state with FLAC__stream_encoder_get_state() to see what
  92031. * went wrong.
  92032. */
  92033. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92034. /** Submit data for encoding.
  92035. * This version allows you to supply the input data where the channels
  92036. * are interleaved into a single array (i.e. channel0_sample0,
  92037. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92038. * The samples need not be block-aligned but they must be
  92039. * sample-aligned, i.e. the first value should be channel0_sample0
  92040. * and the last value channelN_sampleM. Each sample should be a signed
  92041. * integer, right-justified to the resolution set by
  92042. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92043. * resolution is 16 bits per sample, the samples should all be in the
  92044. * range [-32768,32767].
  92045. *
  92046. * For applications where channel order is important, channels must
  92047. * follow the order as described in the
  92048. * <A HREF="../format.html#frame_header">frame header</A>.
  92049. *
  92050. * \param encoder An initialized encoder instance in the OK state.
  92051. * \param buffer An array of channel-interleaved data (see above).
  92052. * \param samples The number of samples in one channel, the same as for
  92053. * FLAC__stream_encoder_process(). For example, if
  92054. * encoding two channels, \c 1000 \a samples corresponds
  92055. * to a \a buffer of 2000 values.
  92056. * \assert
  92057. * \code encoder != NULL \endcode
  92058. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92059. * \retval FLAC__bool
  92060. * \c true if successful, else \c false; in this case, check the
  92061. * encoder state with FLAC__stream_encoder_get_state() to see what
  92062. * went wrong.
  92063. */
  92064. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92065. /* \} */
  92066. #ifdef __cplusplus
  92067. }
  92068. #endif
  92069. #endif
  92070. /*** End of inlined file: stream_encoder.h ***/
  92071. #ifdef _MSC_VER
  92072. /* OPT: an MSVC built-in would be better */
  92073. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92074. {
  92075. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92076. return (x>>16) | (x<<16);
  92077. }
  92078. #endif
  92079. #if defined(_MSC_VER) && defined(_X86_)
  92080. /* OPT: an MSVC built-in would be better */
  92081. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92082. {
  92083. __asm {
  92084. mov edx, start
  92085. mov ecx, len
  92086. test ecx, ecx
  92087. loop1:
  92088. jz done1
  92089. mov eax, [edx]
  92090. bswap eax
  92091. mov [edx], eax
  92092. add edx, 4
  92093. dec ecx
  92094. jmp short loop1
  92095. done1:
  92096. }
  92097. }
  92098. #endif
  92099. /** \mainpage
  92100. *
  92101. * \section intro Introduction
  92102. *
  92103. * This is the documentation for the FLAC C and C++ APIs. It is
  92104. * highly interconnected; this introduction should give you a top
  92105. * level idea of the structure and how to find the information you
  92106. * need. As a prerequisite you should have at least a basic
  92107. * knowledge of the FLAC format, documented
  92108. * <A HREF="../format.html">here</A>.
  92109. *
  92110. * \section c_api FLAC C API
  92111. *
  92112. * The FLAC C API is the interface to libFLAC, a set of structures
  92113. * describing the components of FLAC streams, and functions for
  92114. * encoding and decoding streams, as well as manipulating FLAC
  92115. * metadata in files. The public include files will be installed
  92116. * in your include area (for example /usr/include/FLAC/...).
  92117. *
  92118. * By writing a little code and linking against libFLAC, it is
  92119. * relatively easy to add FLAC support to another program. The
  92120. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92121. * Complete source code of libFLAC as well as the command-line
  92122. * encoder and plugins is available and is a useful source of
  92123. * examples.
  92124. *
  92125. * Aside from encoders and decoders, libFLAC provides a powerful
  92126. * metadata interface for manipulating metadata in FLAC files. It
  92127. * allows the user to add, delete, and modify FLAC metadata blocks
  92128. * and it can automatically take advantage of PADDING blocks to avoid
  92129. * rewriting the entire FLAC file when changing the size of the
  92130. * metadata.
  92131. *
  92132. * libFLAC usually only requires the standard C library and C math
  92133. * library. In particular, threading is not used so there is no
  92134. * dependency on a thread library. However, libFLAC does not use
  92135. * global variables and should be thread-safe.
  92136. *
  92137. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92138. * However the metadata editing interfaces currently have limited
  92139. * read-only support for Ogg FLAC files.
  92140. *
  92141. * \section cpp_api FLAC C++ API
  92142. *
  92143. * The FLAC C++ API is a set of classes that encapsulate the
  92144. * structures and functions in libFLAC. They provide slightly more
  92145. * functionality with respect to metadata but are otherwise
  92146. * equivalent. For the most part, they share the same usage as
  92147. * their counterparts in libFLAC, and the FLAC C API documentation
  92148. * can be used as a supplement. The public include files
  92149. * for the C++ API will be installed in your include area (for
  92150. * example /usr/include/FLAC++/...).
  92151. *
  92152. * libFLAC++ is also licensed under
  92153. * <A HREF="../license.html">Xiph's BSD license</A>.
  92154. *
  92155. * \section getting_started Getting Started
  92156. *
  92157. * A good starting point for learning the API is to browse through
  92158. * the <A HREF="modules.html">modules</A>. Modules are logical
  92159. * groupings of related functions or classes, which correspond roughly
  92160. * to header files or sections of header files. Each module includes a
  92161. * detailed description of the general usage of its functions or
  92162. * classes.
  92163. *
  92164. * From there you can go on to look at the documentation of
  92165. * individual functions. You can see different views of the individual
  92166. * functions through the links in top bar across this page.
  92167. *
  92168. * If you prefer a more hands-on approach, you can jump right to some
  92169. * <A HREF="../documentation_example_code.html">example code</A>.
  92170. *
  92171. * \section porting_guide Porting Guide
  92172. *
  92173. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92174. * has been introduced which gives detailed instructions on how to
  92175. * port your code to newer versions of FLAC.
  92176. *
  92177. * \section embedded_developers Embedded Developers
  92178. *
  92179. * libFLAC has grown larger over time as more functionality has been
  92180. * included, but much of it may be unnecessary for a particular embedded
  92181. * implementation. Unused parts may be pruned by some simple editing of
  92182. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92183. * metadata interface are all independent from each other.
  92184. *
  92185. * It is easiest to just describe the dependencies:
  92186. *
  92187. * - All modules depend on the \link flac_format Format \endlink module.
  92188. * - The decoders and encoders depend on the bitbuffer.
  92189. * - The decoder is independent of the encoder. The encoder uses the
  92190. * decoder because of the verify feature, but this can be removed if
  92191. * not needed.
  92192. * - Parts of the metadata interface require the stream decoder (but not
  92193. * the encoder).
  92194. * - Ogg support is selectable through the compile time macro
  92195. * \c FLAC__HAS_OGG.
  92196. *
  92197. * For example, if your application only requires the stream decoder, no
  92198. * encoder, and no metadata interface, you can remove the stream encoder
  92199. * and the metadata interface, which will greatly reduce the size of the
  92200. * library.
  92201. *
  92202. * Also, there are several places in the libFLAC code with comments marked
  92203. * with "OPT:" where a #define can be changed to enable code that might be
  92204. * faster on a specific platform. Experimenting with these can yield faster
  92205. * binaries.
  92206. */
  92207. /** \defgroup porting Porting Guide for New Versions
  92208. *
  92209. * This module describes differences in the library interfaces from
  92210. * version to version. It assists in the porting of code that uses
  92211. * the libraries to newer versions of FLAC.
  92212. *
  92213. * One simple facility for making porting easier that has been added
  92214. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92215. * library's includes (e.g. \c include/FLAC/export.h). The
  92216. * \c #defines mirror the libraries'
  92217. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92218. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92219. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92220. * These can be used to support multiple versions of an API during the
  92221. * transition phase, e.g.
  92222. *
  92223. * \code
  92224. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92225. * legacy code
  92226. * #else
  92227. * new code
  92228. * #endif
  92229. * \endcode
  92230. *
  92231. * The the source will work for multiple versions and the legacy code can
  92232. * easily be removed when the transition is complete.
  92233. *
  92234. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92235. * include/FLAC/export.h), which can be used to determine whether or not
  92236. * the library has been compiled with support for Ogg FLAC. This is
  92237. * simpler than trying to call an Ogg init function and catching the
  92238. * error.
  92239. */
  92240. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92241. * \ingroup porting
  92242. *
  92243. * \brief
  92244. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92245. *
  92246. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92247. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92248. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92249. * decoding layers and three encoding layers have been merged into a
  92250. * single stream decoder and stream encoder. That is, the functionality
  92251. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92252. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92253. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92254. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92255. * is there is now a single API that can be used to encode or decode
  92256. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92257. * on both seekable and non-seekable streams.
  92258. *
  92259. * Instead of creating an encoder or decoder of a certain layer, now the
  92260. * client will always create a FLAC__StreamEncoder or
  92261. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92262. * initialization function. For example, for the decoder,
  92263. * FLAC__stream_decoder_init() has been replaced by
  92264. * FLAC__stream_decoder_init_stream(). This init function takes
  92265. * callbacks for the I/O, and the seeking callbacks are optional. This
  92266. * allows the client to use the same object for seekable and
  92267. * non-seekable streams. For decoding a FLAC file directly, the client
  92268. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92269. * and fewer callbacks; most of the other callbacks are supplied
  92270. * internally. For situations where fopen()ing by filename is not
  92271. * possible (e.g. Unicode filenames on Windows) the client can instead
  92272. * open the file itself and supply the FILE* to
  92273. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92274. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92275. * Since the callbacks and client data are now passed to the init
  92276. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92277. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92278. * rest of the calls to the decoder are the same as before.
  92279. *
  92280. * There are counterpart init functions for Ogg FLAC, e.g.
  92281. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92282. * and callbacks are the same as for native FLAC.
  92283. *
  92284. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92285. * been set up like so:
  92286. *
  92287. * \code
  92288. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92289. * if(decoder == NULL) do_something;
  92290. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92291. * [... other settings ...]
  92292. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92293. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92294. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92295. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92296. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92297. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92298. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92299. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92300. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92301. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92302. * \endcode
  92303. *
  92304. * In FLAC 1.1.3 it is like this:
  92305. *
  92306. * \code
  92307. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92308. * if(decoder == NULL) do_something;
  92309. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92310. * [... other settings ...]
  92311. * if(FLAC__stream_decoder_init_stream(
  92312. * decoder,
  92313. * my_read_callback,
  92314. * my_seek_callback, // or NULL
  92315. * my_tell_callback, // or NULL
  92316. * my_length_callback, // or NULL
  92317. * my_eof_callback, // or NULL
  92318. * my_write_callback,
  92319. * my_metadata_callback, // or NULL
  92320. * my_error_callback,
  92321. * my_client_data
  92322. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92323. * \endcode
  92324. *
  92325. * or you could do;
  92326. *
  92327. * \code
  92328. * [...]
  92329. * FILE *file = fopen("somefile.flac","rb");
  92330. * if(file == NULL) do_somthing;
  92331. * if(FLAC__stream_decoder_init_FILE(
  92332. * decoder,
  92333. * file,
  92334. * my_write_callback,
  92335. * my_metadata_callback, // or NULL
  92336. * my_error_callback,
  92337. * my_client_data
  92338. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92339. * \endcode
  92340. *
  92341. * or just:
  92342. *
  92343. * \code
  92344. * [...]
  92345. * if(FLAC__stream_decoder_init_file(
  92346. * decoder,
  92347. * "somefile.flac",
  92348. * my_write_callback,
  92349. * my_metadata_callback, // or NULL
  92350. * my_error_callback,
  92351. * my_client_data
  92352. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92353. * \endcode
  92354. *
  92355. * Another small change to the decoder is in how it handles unparseable
  92356. * streams. Before, when the decoder found an unparseable stream
  92357. * (reserved for when the decoder encounters a stream from a future
  92358. * encoder that it can't parse), it changed the state to
  92359. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92360. * drops sync and calls the error callback with a new error code
  92361. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92362. * more robust. If your error callback does not discriminate on the the
  92363. * error state, your code does not need to be changed.
  92364. *
  92365. * The encoder now has a new setting:
  92366. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92367. * method used to window the data before LPC analysis. You only need to
  92368. * add a call to this function if the default is not suitable. There
  92369. * are also two new convenience functions that may be useful:
  92370. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92371. * FLAC__metadata_get_cuesheet().
  92372. *
  92373. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92374. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92375. * is now \c size_t instead of \c unsigned.
  92376. */
  92377. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92378. * \ingroup porting
  92379. *
  92380. * \brief
  92381. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92382. *
  92383. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92384. * There was a slight change in the implementation of
  92385. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92386. * of the \a metadata array of pointers so the client no longer needs
  92387. * to maintain it after the call. The objects themselves that are
  92388. * pointed to by the array are still not copied though and must be
  92389. * maintained until the call to FLAC__stream_encoder_finish().
  92390. */
  92391. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92392. * \ingroup porting
  92393. *
  92394. * \brief
  92395. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92396. *
  92397. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92398. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92399. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92400. *
  92401. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92402. * has changed to reflect the conversion of one of the reserved bits
  92403. * into active use. It used to be \c 2 and now is \c 1. However the
  92404. * FLAC frame header length has not changed, so to skip the proper
  92405. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92406. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92407. */
  92408. /** \defgroup flac FLAC C API
  92409. *
  92410. * The FLAC C API is the interface to libFLAC, a set of structures
  92411. * describing the components of FLAC streams, and functions for
  92412. * encoding and decoding streams, as well as manipulating FLAC
  92413. * metadata in files.
  92414. *
  92415. * You should start with the format components as all other modules
  92416. * are dependent on it.
  92417. */
  92418. #endif
  92419. /*** End of inlined file: all.h ***/
  92420. /*** Start of inlined file: bitmath.c ***/
  92421. /*** Start of inlined file: juce_FlacHeader.h ***/
  92422. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92423. // tasks..
  92424. #define VERSION "1.2.1"
  92425. #define FLAC__NO_DLL 1
  92426. #if JUCE_MSVC
  92427. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92428. #endif
  92429. #if JUCE_MAC
  92430. #define FLAC__SYS_DARWIN 1
  92431. #endif
  92432. /*** End of inlined file: juce_FlacHeader.h ***/
  92433. #if JUCE_USE_FLAC
  92434. #if HAVE_CONFIG_H
  92435. # include <config.h>
  92436. #endif
  92437. /*** Start of inlined file: bitmath.h ***/
  92438. #ifndef FLAC__PRIVATE__BITMATH_H
  92439. #define FLAC__PRIVATE__BITMATH_H
  92440. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92441. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92442. unsigned FLAC__bitmath_silog2(int v);
  92443. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92444. #endif
  92445. /*** End of inlined file: bitmath.h ***/
  92446. /* An example of what FLAC__bitmath_ilog2() computes:
  92447. *
  92448. * ilog2( 0) = assertion failure
  92449. * ilog2( 1) = 0
  92450. * ilog2( 2) = 1
  92451. * ilog2( 3) = 1
  92452. * ilog2( 4) = 2
  92453. * ilog2( 5) = 2
  92454. * ilog2( 6) = 2
  92455. * ilog2( 7) = 2
  92456. * ilog2( 8) = 3
  92457. * ilog2( 9) = 3
  92458. * ilog2(10) = 3
  92459. * ilog2(11) = 3
  92460. * ilog2(12) = 3
  92461. * ilog2(13) = 3
  92462. * ilog2(14) = 3
  92463. * ilog2(15) = 3
  92464. * ilog2(16) = 4
  92465. * ilog2(17) = 4
  92466. * ilog2(18) = 4
  92467. */
  92468. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92469. {
  92470. unsigned l = 0;
  92471. FLAC__ASSERT(v > 0);
  92472. while(v >>= 1)
  92473. l++;
  92474. return l;
  92475. }
  92476. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92477. {
  92478. unsigned l = 0;
  92479. FLAC__ASSERT(v > 0);
  92480. while(v >>= 1)
  92481. l++;
  92482. return l;
  92483. }
  92484. /* An example of what FLAC__bitmath_silog2() computes:
  92485. *
  92486. * silog2(-10) = 5
  92487. * silog2(- 9) = 5
  92488. * silog2(- 8) = 4
  92489. * silog2(- 7) = 4
  92490. * silog2(- 6) = 4
  92491. * silog2(- 5) = 4
  92492. * silog2(- 4) = 3
  92493. * silog2(- 3) = 3
  92494. * silog2(- 2) = 2
  92495. * silog2(- 1) = 2
  92496. * silog2( 0) = 0
  92497. * silog2( 1) = 2
  92498. * silog2( 2) = 3
  92499. * silog2( 3) = 3
  92500. * silog2( 4) = 4
  92501. * silog2( 5) = 4
  92502. * silog2( 6) = 4
  92503. * silog2( 7) = 4
  92504. * silog2( 8) = 5
  92505. * silog2( 9) = 5
  92506. * silog2( 10) = 5
  92507. */
  92508. unsigned FLAC__bitmath_silog2(int v)
  92509. {
  92510. while(1) {
  92511. if(v == 0) {
  92512. return 0;
  92513. }
  92514. else if(v > 0) {
  92515. unsigned l = 0;
  92516. while(v) {
  92517. l++;
  92518. v >>= 1;
  92519. }
  92520. return l+1;
  92521. }
  92522. else if(v == -1) {
  92523. return 2;
  92524. }
  92525. else {
  92526. v++;
  92527. v = -v;
  92528. }
  92529. }
  92530. }
  92531. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92532. {
  92533. while(1) {
  92534. if(v == 0) {
  92535. return 0;
  92536. }
  92537. else if(v > 0) {
  92538. unsigned l = 0;
  92539. while(v) {
  92540. l++;
  92541. v >>= 1;
  92542. }
  92543. return l+1;
  92544. }
  92545. else if(v == -1) {
  92546. return 2;
  92547. }
  92548. else {
  92549. v++;
  92550. v = -v;
  92551. }
  92552. }
  92553. }
  92554. #endif
  92555. /*** End of inlined file: bitmath.c ***/
  92556. /*** Start of inlined file: bitreader.c ***/
  92557. /*** Start of inlined file: juce_FlacHeader.h ***/
  92558. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92559. // tasks..
  92560. #define VERSION "1.2.1"
  92561. #define FLAC__NO_DLL 1
  92562. #if JUCE_MSVC
  92563. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92564. #endif
  92565. #if JUCE_MAC
  92566. #define FLAC__SYS_DARWIN 1
  92567. #endif
  92568. /*** End of inlined file: juce_FlacHeader.h ***/
  92569. #if JUCE_USE_FLAC
  92570. #if HAVE_CONFIG_H
  92571. # include <config.h>
  92572. #endif
  92573. #include <stdlib.h> /* for malloc() */
  92574. #include <string.h> /* for memcpy(), memset() */
  92575. #ifdef _MSC_VER
  92576. #include <winsock.h> /* for ntohl() */
  92577. #elif defined FLAC__SYS_DARWIN
  92578. #include <machine/endian.h> /* for ntohl() */
  92579. #elif defined __MINGW32__
  92580. #include <winsock.h> /* for ntohl() */
  92581. #else
  92582. #include <netinet/in.h> /* for ntohl() */
  92583. #endif
  92584. /*** Start of inlined file: bitreader.h ***/
  92585. #ifndef FLAC__PRIVATE__BITREADER_H
  92586. #define FLAC__PRIVATE__BITREADER_H
  92587. #include <stdio.h> /* for FILE */
  92588. /*** Start of inlined file: cpu.h ***/
  92589. #ifndef FLAC__PRIVATE__CPU_H
  92590. #define FLAC__PRIVATE__CPU_H
  92591. #ifdef HAVE_CONFIG_H
  92592. #include <config.h>
  92593. #endif
  92594. typedef enum {
  92595. FLAC__CPUINFO_TYPE_IA32,
  92596. FLAC__CPUINFO_TYPE_PPC,
  92597. FLAC__CPUINFO_TYPE_UNKNOWN
  92598. } FLAC__CPUInfo_Type;
  92599. typedef struct {
  92600. FLAC__bool cpuid;
  92601. FLAC__bool bswap;
  92602. FLAC__bool cmov;
  92603. FLAC__bool mmx;
  92604. FLAC__bool fxsr;
  92605. FLAC__bool sse;
  92606. FLAC__bool sse2;
  92607. FLAC__bool sse3;
  92608. FLAC__bool ssse3;
  92609. FLAC__bool _3dnow;
  92610. FLAC__bool ext3dnow;
  92611. FLAC__bool extmmx;
  92612. } FLAC__CPUInfo_IA32;
  92613. typedef struct {
  92614. FLAC__bool altivec;
  92615. FLAC__bool ppc64;
  92616. } FLAC__CPUInfo_PPC;
  92617. typedef struct {
  92618. FLAC__bool use_asm;
  92619. FLAC__CPUInfo_Type type;
  92620. union {
  92621. FLAC__CPUInfo_IA32 ia32;
  92622. FLAC__CPUInfo_PPC ppc;
  92623. } data;
  92624. } FLAC__CPUInfo;
  92625. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92626. #ifndef FLAC__NO_ASM
  92627. #ifdef FLAC__CPU_IA32
  92628. #ifdef FLAC__HAS_NASM
  92629. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92630. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92631. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92632. #endif
  92633. #endif
  92634. #endif
  92635. #endif
  92636. /*** End of inlined file: cpu.h ***/
  92637. /*
  92638. * opaque structure definition
  92639. */
  92640. struct FLAC__BitReader;
  92641. typedef struct FLAC__BitReader FLAC__BitReader;
  92642. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92643. /*
  92644. * construction, deletion, initialization, etc functions
  92645. */
  92646. FLAC__BitReader *FLAC__bitreader_new(void);
  92647. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92648. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92649. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92650. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92651. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92652. /*
  92653. * CRC functions
  92654. */
  92655. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92656. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92657. /*
  92658. * info functions
  92659. */
  92660. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92661. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92662. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92663. /*
  92664. * read functions
  92665. */
  92666. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92667. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92668. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  92669. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  92670. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  92671. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  92672. 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! */
  92673. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  92674. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92675. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92676. #ifndef FLAC__NO_ASM
  92677. # ifdef FLAC__CPU_IA32
  92678. # ifdef FLAC__HAS_NASM
  92679. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  92680. # endif
  92681. # endif
  92682. #endif
  92683. #if 0 /* UNUSED */
  92684. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  92685. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  92686. #endif
  92687. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  92688. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  92689. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  92690. #endif
  92691. /*** End of inlined file: bitreader.h ***/
  92692. /*** Start of inlined file: crc.h ***/
  92693. #ifndef FLAC__PRIVATE__CRC_H
  92694. #define FLAC__PRIVATE__CRC_H
  92695. /* 8 bit CRC generator, MSB shifted first
  92696. ** polynomial = x^8 + x^2 + x^1 + x^0
  92697. ** init = 0
  92698. */
  92699. extern FLAC__byte const FLAC__crc8_table[256];
  92700. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  92701. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  92702. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  92703. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  92704. /* 16 bit CRC generator, MSB shifted first
  92705. ** polynomial = x^16 + x^15 + x^2 + x^0
  92706. ** init = 0
  92707. */
  92708. extern unsigned FLAC__crc16_table[256];
  92709. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  92710. /* this alternate may be faster on some systems/compilers */
  92711. #if 0
  92712. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  92713. #endif
  92714. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  92715. #endif
  92716. /*** End of inlined file: crc.h ***/
  92717. /* Things should be fastest when this matches the machine word size */
  92718. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  92719. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  92720. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  92721. typedef FLAC__uint32 brword;
  92722. #define FLAC__BYTES_PER_WORD 4
  92723. #define FLAC__BITS_PER_WORD 32
  92724. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  92725. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  92726. #if WORDS_BIGENDIAN
  92727. #define SWAP_BE_WORD_TO_HOST(x) (x)
  92728. #else
  92729. #if defined (_MSC_VER) && defined (_X86_)
  92730. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  92731. #else
  92732. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  92733. #endif
  92734. #endif
  92735. /* counts the # of zero MSBs in a word */
  92736. #define COUNT_ZERO_MSBS(word) ( \
  92737. (word) <= 0xffff ? \
  92738. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  92739. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  92740. )
  92741. /* this alternate might be slightly faster on some systems/compilers: */
  92742. #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])) )
  92743. /*
  92744. * This should be at least twice as large as the largest number of words
  92745. * required to represent any 'number' (in any encoding) you are going to
  92746. * read. With FLAC this is on the order of maybe a few hundred bits.
  92747. * If the buffer is smaller than that, the decoder won't be able to read
  92748. * in a whole number that is in a variable length encoding (e.g. Rice).
  92749. * But to be practical it should be at least 1K bytes.
  92750. *
  92751. * Increase this number to decrease the number of read callbacks, at the
  92752. * expense of using more memory. Or decrease for the reverse effect,
  92753. * keeping in mind the limit from the first paragraph. The optimal size
  92754. * also depends on the CPU cache size and other factors; some twiddling
  92755. * may be necessary to squeeze out the best performance.
  92756. */
  92757. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  92758. static const unsigned char byte_to_unary_table[] = {
  92759. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  92760. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  92761. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92762. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92763. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92764. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92765. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92766. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  92767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  92775. };
  92776. #ifdef min
  92777. #undef min
  92778. #endif
  92779. #define min(x,y) ((x)<(y)?(x):(y))
  92780. #ifdef max
  92781. #undef max
  92782. #endif
  92783. #define max(x,y) ((x)>(y)?(x):(y))
  92784. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92785. #ifdef _MSC_VER
  92786. #define FLAC__U64L(x) x
  92787. #else
  92788. #define FLAC__U64L(x) x##LLU
  92789. #endif
  92790. #ifndef FLaC__INLINE
  92791. #define FLaC__INLINE
  92792. #endif
  92793. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  92794. struct FLAC__BitReader {
  92795. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  92796. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  92797. brword *buffer;
  92798. unsigned capacity; /* in words */
  92799. unsigned words; /* # of completed words in buffer */
  92800. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  92801. unsigned consumed_words; /* #words ... */
  92802. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  92803. unsigned read_crc16; /* the running frame CRC */
  92804. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  92805. FLAC__BitReaderReadCallback read_callback;
  92806. void *client_data;
  92807. FLAC__CPUInfo cpu_info;
  92808. };
  92809. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  92810. {
  92811. register unsigned crc = br->read_crc16;
  92812. #if FLAC__BYTES_PER_WORD == 4
  92813. switch(br->crc16_align) {
  92814. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  92815. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92816. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92817. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92818. }
  92819. #elif FLAC__BYTES_PER_WORD == 8
  92820. switch(br->crc16_align) {
  92821. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  92822. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  92823. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  92824. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  92825. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  92826. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  92827. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  92828. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  92829. }
  92830. #else
  92831. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  92832. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  92833. br->read_crc16 = crc;
  92834. #endif
  92835. br->crc16_align = 0;
  92836. }
  92837. /* would be static except it needs to be called by asm routines */
  92838. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  92839. {
  92840. unsigned start, end;
  92841. size_t bytes;
  92842. FLAC__byte *target;
  92843. /* first shift the unconsumed buffer data toward the front as much as possible */
  92844. if(br->consumed_words > 0) {
  92845. start = br->consumed_words;
  92846. end = br->words + (br->bytes? 1:0);
  92847. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  92848. br->words -= start;
  92849. br->consumed_words = 0;
  92850. }
  92851. /*
  92852. * set the target for reading, taking into account word alignment and endianness
  92853. */
  92854. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  92855. if(bytes == 0)
  92856. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  92857. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  92858. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  92859. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  92860. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  92861. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  92862. * ^^-------target, bytes=3
  92863. * on LE machines, have to byteswap the odd tail word so nothing is
  92864. * overwritten:
  92865. */
  92866. #if WORDS_BIGENDIAN
  92867. #else
  92868. if(br->bytes)
  92869. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  92870. #endif
  92871. /* now it looks like:
  92872. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  92873. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  92874. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  92875. * ^^-------target, bytes=3
  92876. */
  92877. /* read in the data; note that the callback may return a smaller number of bytes */
  92878. if(!br->read_callback(target, &bytes, br->client_data))
  92879. return false;
  92880. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  92881. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92882. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92883. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  92884. * now have to byteswap on LE machines:
  92885. */
  92886. #if WORDS_BIGENDIAN
  92887. #else
  92888. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  92889. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  92890. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  92891. start = br->words;
  92892. local_swap32_block_(br->buffer + start, end - start);
  92893. }
  92894. else
  92895. # endif
  92896. for(start = br->words; start < end; start++)
  92897. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  92898. #endif
  92899. /* now it looks like:
  92900. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  92901. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  92902. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  92903. * finally we'll update the reader values:
  92904. */
  92905. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  92906. br->words = end / FLAC__BYTES_PER_WORD;
  92907. br->bytes = end % FLAC__BYTES_PER_WORD;
  92908. return true;
  92909. }
  92910. /***********************************************************************
  92911. *
  92912. * Class constructor/destructor
  92913. *
  92914. ***********************************************************************/
  92915. FLAC__BitReader *FLAC__bitreader_new(void)
  92916. {
  92917. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  92918. /* calloc() implies:
  92919. memset(br, 0, sizeof(FLAC__BitReader));
  92920. br->buffer = 0;
  92921. br->capacity = 0;
  92922. br->words = br->bytes = 0;
  92923. br->consumed_words = br->consumed_bits = 0;
  92924. br->read_callback = 0;
  92925. br->client_data = 0;
  92926. */
  92927. return br;
  92928. }
  92929. void FLAC__bitreader_delete(FLAC__BitReader *br)
  92930. {
  92931. FLAC__ASSERT(0 != br);
  92932. FLAC__bitreader_free(br);
  92933. free(br);
  92934. }
  92935. /***********************************************************************
  92936. *
  92937. * Public class methods
  92938. *
  92939. ***********************************************************************/
  92940. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  92941. {
  92942. FLAC__ASSERT(0 != br);
  92943. br->words = br->bytes = 0;
  92944. br->consumed_words = br->consumed_bits = 0;
  92945. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  92946. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  92947. if(br->buffer == 0)
  92948. return false;
  92949. br->read_callback = rcb;
  92950. br->client_data = cd;
  92951. br->cpu_info = cpu;
  92952. return true;
  92953. }
  92954. void FLAC__bitreader_free(FLAC__BitReader *br)
  92955. {
  92956. FLAC__ASSERT(0 != br);
  92957. if(0 != br->buffer)
  92958. free(br->buffer);
  92959. br->buffer = 0;
  92960. br->capacity = 0;
  92961. br->words = br->bytes = 0;
  92962. br->consumed_words = br->consumed_bits = 0;
  92963. br->read_callback = 0;
  92964. br->client_data = 0;
  92965. }
  92966. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  92967. {
  92968. br->words = br->bytes = 0;
  92969. br->consumed_words = br->consumed_bits = 0;
  92970. return true;
  92971. }
  92972. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  92973. {
  92974. unsigned i, j;
  92975. if(br == 0) {
  92976. fprintf(out, "bitreader is NULL\n");
  92977. }
  92978. else {
  92979. 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);
  92980. for(i = 0; i < br->words; i++) {
  92981. fprintf(out, "%08X: ", i);
  92982. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  92983. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92984. fprintf(out, ".");
  92985. else
  92986. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  92987. fprintf(out, "\n");
  92988. }
  92989. if(br->bytes > 0) {
  92990. fprintf(out, "%08X: ", i);
  92991. for(j = 0; j < br->bytes*8; j++)
  92992. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  92993. fprintf(out, ".");
  92994. else
  92995. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  92996. fprintf(out, "\n");
  92997. }
  92998. }
  92999. }
  93000. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93001. {
  93002. FLAC__ASSERT(0 != br);
  93003. FLAC__ASSERT(0 != br->buffer);
  93004. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93005. br->read_crc16 = (unsigned)seed;
  93006. br->crc16_align = br->consumed_bits;
  93007. }
  93008. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93009. {
  93010. FLAC__ASSERT(0 != br);
  93011. FLAC__ASSERT(0 != br->buffer);
  93012. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93013. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93014. /* CRC any tail bytes in a partially-consumed word */
  93015. if(br->consumed_bits) {
  93016. const brword tail = br->buffer[br->consumed_words];
  93017. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93018. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93019. }
  93020. return br->read_crc16;
  93021. }
  93022. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93023. {
  93024. return ((br->consumed_bits & 7) == 0);
  93025. }
  93026. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93027. {
  93028. return 8 - (br->consumed_bits & 7);
  93029. }
  93030. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93031. {
  93032. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93033. }
  93034. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93035. {
  93036. FLAC__ASSERT(0 != br);
  93037. FLAC__ASSERT(0 != br->buffer);
  93038. FLAC__ASSERT(bits <= 32);
  93039. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93040. FLAC__ASSERT(br->consumed_words <= br->words);
  93041. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93042. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93043. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93044. *val = 0;
  93045. return true;
  93046. }
  93047. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93048. if(!bitreader_read_from_client_(br))
  93049. return false;
  93050. }
  93051. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93052. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93053. if(br->consumed_bits) {
  93054. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93055. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93056. const brword word = br->buffer[br->consumed_words];
  93057. if(bits < n) {
  93058. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93059. br->consumed_bits += bits;
  93060. return true;
  93061. }
  93062. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93063. bits -= n;
  93064. crc16_update_word_(br, word);
  93065. br->consumed_words++;
  93066. br->consumed_bits = 0;
  93067. 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 */
  93068. *val <<= bits;
  93069. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93070. br->consumed_bits = bits;
  93071. }
  93072. return true;
  93073. }
  93074. else {
  93075. const brword word = br->buffer[br->consumed_words];
  93076. if(bits < FLAC__BITS_PER_WORD) {
  93077. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93078. br->consumed_bits = bits;
  93079. return true;
  93080. }
  93081. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93082. *val = word;
  93083. crc16_update_word_(br, word);
  93084. br->consumed_words++;
  93085. return true;
  93086. }
  93087. }
  93088. else {
  93089. /* in this case we're starting our read at a partial tail word;
  93090. * the reader has guaranteed that we have at least 'bits' bits
  93091. * available to read, which makes this case simpler.
  93092. */
  93093. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93094. if(br->consumed_bits) {
  93095. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93096. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93097. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93098. br->consumed_bits += bits;
  93099. return true;
  93100. }
  93101. else {
  93102. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93103. br->consumed_bits += bits;
  93104. return true;
  93105. }
  93106. }
  93107. }
  93108. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93109. {
  93110. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93111. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93112. return false;
  93113. /* sign-extend: */
  93114. *val <<= (32-bits);
  93115. *val >>= (32-bits);
  93116. return true;
  93117. }
  93118. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93119. {
  93120. FLAC__uint32 hi, lo;
  93121. if(bits > 32) {
  93122. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93123. return false;
  93124. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93125. return false;
  93126. *val = hi;
  93127. *val <<= 32;
  93128. *val |= lo;
  93129. }
  93130. else {
  93131. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93132. return false;
  93133. *val = lo;
  93134. }
  93135. return true;
  93136. }
  93137. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93138. {
  93139. FLAC__uint32 x8, x32 = 0;
  93140. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93141. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93142. return false;
  93143. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93144. return false;
  93145. x32 |= (x8 << 8);
  93146. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93147. return false;
  93148. x32 |= (x8 << 16);
  93149. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93150. return false;
  93151. x32 |= (x8 << 24);
  93152. *val = x32;
  93153. return true;
  93154. }
  93155. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93156. {
  93157. /*
  93158. * OPT: a faster implementation is possible but probably not that useful
  93159. * since this is only called a couple of times in the metadata readers.
  93160. */
  93161. FLAC__ASSERT(0 != br);
  93162. FLAC__ASSERT(0 != br->buffer);
  93163. if(bits > 0) {
  93164. const unsigned n = br->consumed_bits & 7;
  93165. unsigned m;
  93166. FLAC__uint32 x;
  93167. if(n != 0) {
  93168. m = min(8-n, bits);
  93169. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93170. return false;
  93171. bits -= m;
  93172. }
  93173. m = bits / 8;
  93174. if(m > 0) {
  93175. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93176. return false;
  93177. bits %= 8;
  93178. }
  93179. if(bits > 0) {
  93180. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93181. return false;
  93182. }
  93183. }
  93184. return true;
  93185. }
  93186. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93187. {
  93188. FLAC__uint32 x;
  93189. FLAC__ASSERT(0 != br);
  93190. FLAC__ASSERT(0 != br->buffer);
  93191. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93192. /* step 1: skip over partial head word to get word aligned */
  93193. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93194. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93195. return false;
  93196. nvals--;
  93197. }
  93198. if(0 == nvals)
  93199. return true;
  93200. /* step 2: skip whole words in chunks */
  93201. while(nvals >= FLAC__BYTES_PER_WORD) {
  93202. if(br->consumed_words < br->words) {
  93203. br->consumed_words++;
  93204. nvals -= FLAC__BYTES_PER_WORD;
  93205. }
  93206. else if(!bitreader_read_from_client_(br))
  93207. return false;
  93208. }
  93209. /* step 3: skip any remainder from partial tail bytes */
  93210. while(nvals) {
  93211. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93212. return false;
  93213. nvals--;
  93214. }
  93215. return true;
  93216. }
  93217. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93218. {
  93219. FLAC__uint32 x;
  93220. FLAC__ASSERT(0 != br);
  93221. FLAC__ASSERT(0 != br->buffer);
  93222. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93223. /* step 1: read from partial head word to get word aligned */
  93224. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93225. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93226. return false;
  93227. *val++ = (FLAC__byte)x;
  93228. nvals--;
  93229. }
  93230. if(0 == nvals)
  93231. return true;
  93232. /* step 2: read whole words in chunks */
  93233. while(nvals >= FLAC__BYTES_PER_WORD) {
  93234. if(br->consumed_words < br->words) {
  93235. const brword word = br->buffer[br->consumed_words++];
  93236. #if FLAC__BYTES_PER_WORD == 4
  93237. val[0] = (FLAC__byte)(word >> 24);
  93238. val[1] = (FLAC__byte)(word >> 16);
  93239. val[2] = (FLAC__byte)(word >> 8);
  93240. val[3] = (FLAC__byte)word;
  93241. #elif FLAC__BYTES_PER_WORD == 8
  93242. val[0] = (FLAC__byte)(word >> 56);
  93243. val[1] = (FLAC__byte)(word >> 48);
  93244. val[2] = (FLAC__byte)(word >> 40);
  93245. val[3] = (FLAC__byte)(word >> 32);
  93246. val[4] = (FLAC__byte)(word >> 24);
  93247. val[5] = (FLAC__byte)(word >> 16);
  93248. val[6] = (FLAC__byte)(word >> 8);
  93249. val[7] = (FLAC__byte)word;
  93250. #else
  93251. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93252. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93253. #endif
  93254. val += FLAC__BYTES_PER_WORD;
  93255. nvals -= FLAC__BYTES_PER_WORD;
  93256. }
  93257. else if(!bitreader_read_from_client_(br))
  93258. return false;
  93259. }
  93260. /* step 3: read any remainder from partial tail bytes */
  93261. while(nvals) {
  93262. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93263. return false;
  93264. *val++ = (FLAC__byte)x;
  93265. nvals--;
  93266. }
  93267. return true;
  93268. }
  93269. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93270. #if 0 /* slow but readable version */
  93271. {
  93272. unsigned bit;
  93273. FLAC__ASSERT(0 != br);
  93274. FLAC__ASSERT(0 != br->buffer);
  93275. *val = 0;
  93276. while(1) {
  93277. if(!FLAC__bitreader_read_bit(br, &bit))
  93278. return false;
  93279. if(bit)
  93280. break;
  93281. else
  93282. *val++;
  93283. }
  93284. return true;
  93285. }
  93286. #else
  93287. {
  93288. unsigned i;
  93289. FLAC__ASSERT(0 != br);
  93290. FLAC__ASSERT(0 != br->buffer);
  93291. *val = 0;
  93292. while(1) {
  93293. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93294. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93295. if(b) {
  93296. i = COUNT_ZERO_MSBS(b);
  93297. *val += i;
  93298. i++;
  93299. br->consumed_bits += i;
  93300. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93301. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93302. br->consumed_words++;
  93303. br->consumed_bits = 0;
  93304. }
  93305. return true;
  93306. }
  93307. else {
  93308. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93309. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93310. br->consumed_words++;
  93311. br->consumed_bits = 0;
  93312. /* didn't find stop bit yet, have to keep going... */
  93313. }
  93314. }
  93315. /* at this point we've eaten up all the whole words; have to try
  93316. * reading through any tail bytes before calling the read callback.
  93317. * this is a repeat of the above logic adjusted for the fact we
  93318. * don't have a whole word. note though if the client is feeding
  93319. * us data a byte at a time (unlikely), br->consumed_bits may not
  93320. * be zero.
  93321. */
  93322. if(br->bytes) {
  93323. const unsigned end = br->bytes * 8;
  93324. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93325. if(b) {
  93326. i = COUNT_ZERO_MSBS(b);
  93327. *val += i;
  93328. i++;
  93329. br->consumed_bits += i;
  93330. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93331. return true;
  93332. }
  93333. else {
  93334. *val += end - br->consumed_bits;
  93335. br->consumed_bits += end;
  93336. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93337. /* didn't find stop bit yet, have to keep going... */
  93338. }
  93339. }
  93340. if(!bitreader_read_from_client_(br))
  93341. return false;
  93342. }
  93343. }
  93344. #endif
  93345. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93346. {
  93347. FLAC__uint32 lsbs = 0, msbs = 0;
  93348. unsigned uval;
  93349. FLAC__ASSERT(0 != br);
  93350. FLAC__ASSERT(0 != br->buffer);
  93351. FLAC__ASSERT(parameter <= 31);
  93352. /* read the unary MSBs and end bit */
  93353. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93354. return false;
  93355. /* read the binary LSBs */
  93356. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93357. return false;
  93358. /* compose the value */
  93359. uval = (msbs << parameter) | lsbs;
  93360. if(uval & 1)
  93361. *val = -((int)(uval >> 1)) - 1;
  93362. else
  93363. *val = (int)(uval >> 1);
  93364. return true;
  93365. }
  93366. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93367. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93368. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93369. /* OPT: possibly faster version for use with MSVC */
  93370. #ifdef _MSC_VER
  93371. {
  93372. unsigned i;
  93373. unsigned uval = 0;
  93374. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93375. /* try and get br->consumed_words and br->consumed_bits into register;
  93376. * must remember to flush them back to *br before calling other
  93377. * bitwriter functions that use them, and before returning */
  93378. register unsigned cwords;
  93379. register unsigned cbits;
  93380. FLAC__ASSERT(0 != br);
  93381. FLAC__ASSERT(0 != br->buffer);
  93382. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93383. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93384. FLAC__ASSERT(parameter < 32);
  93385. /* 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 */
  93386. if(nvals == 0)
  93387. return true;
  93388. cbits = br->consumed_bits;
  93389. cwords = br->consumed_words;
  93390. while(1) {
  93391. /* read unary part */
  93392. while(1) {
  93393. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93394. brword b = br->buffer[cwords] << cbits;
  93395. if(b) {
  93396. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93397. __asm {
  93398. bsr eax, b
  93399. not eax
  93400. and eax, 31
  93401. mov i, eax
  93402. }
  93403. #else
  93404. i = COUNT_ZERO_MSBS(b);
  93405. #endif
  93406. uval += i;
  93407. bits = parameter;
  93408. i++;
  93409. cbits += i;
  93410. if(cbits == FLAC__BITS_PER_WORD) {
  93411. crc16_update_word_(br, br->buffer[cwords]);
  93412. cwords++;
  93413. cbits = 0;
  93414. }
  93415. goto break1;
  93416. }
  93417. else {
  93418. uval += FLAC__BITS_PER_WORD - cbits;
  93419. crc16_update_word_(br, br->buffer[cwords]);
  93420. cwords++;
  93421. cbits = 0;
  93422. /* didn't find stop bit yet, have to keep going... */
  93423. }
  93424. }
  93425. /* at this point we've eaten up all the whole words; have to try
  93426. * reading through any tail bytes before calling the read callback.
  93427. * this is a repeat of the above logic adjusted for the fact we
  93428. * don't have a whole word. note though if the client is feeding
  93429. * us data a byte at a time (unlikely), br->consumed_bits may not
  93430. * be zero.
  93431. */
  93432. if(br->bytes) {
  93433. const unsigned end = br->bytes * 8;
  93434. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93435. if(b) {
  93436. i = COUNT_ZERO_MSBS(b);
  93437. uval += i;
  93438. bits = parameter;
  93439. i++;
  93440. cbits += i;
  93441. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93442. goto break1;
  93443. }
  93444. else {
  93445. uval += end - cbits;
  93446. cbits += end;
  93447. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93448. /* didn't find stop bit yet, have to keep going... */
  93449. }
  93450. }
  93451. /* flush registers and read; bitreader_read_from_client_() does
  93452. * not touch br->consumed_bits at all but we still need to set
  93453. * it in case it fails and we have to return false.
  93454. */
  93455. br->consumed_bits = cbits;
  93456. br->consumed_words = cwords;
  93457. if(!bitreader_read_from_client_(br))
  93458. return false;
  93459. cwords = br->consumed_words;
  93460. }
  93461. break1:
  93462. /* read binary part */
  93463. FLAC__ASSERT(cwords <= br->words);
  93464. if(bits) {
  93465. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93466. /* flush registers and read; bitreader_read_from_client_() does
  93467. * not touch br->consumed_bits at all but we still need to set
  93468. * it in case it fails and we have to return false.
  93469. */
  93470. br->consumed_bits = cbits;
  93471. br->consumed_words = cwords;
  93472. if(!bitreader_read_from_client_(br))
  93473. return false;
  93474. cwords = br->consumed_words;
  93475. }
  93476. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93477. if(cbits) {
  93478. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93479. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93480. const brword word = br->buffer[cwords];
  93481. if(bits < n) {
  93482. uval <<= bits;
  93483. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93484. cbits += bits;
  93485. goto break2;
  93486. }
  93487. uval <<= n;
  93488. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93489. bits -= n;
  93490. crc16_update_word_(br, word);
  93491. cwords++;
  93492. cbits = 0;
  93493. 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 */
  93494. uval <<= bits;
  93495. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93496. cbits = bits;
  93497. }
  93498. goto break2;
  93499. }
  93500. else {
  93501. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93502. uval <<= bits;
  93503. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93504. cbits = bits;
  93505. goto break2;
  93506. }
  93507. }
  93508. else {
  93509. /* in this case we're starting our read at a partial tail word;
  93510. * the reader has guaranteed that we have at least 'bits' bits
  93511. * available to read, which makes this case simpler.
  93512. */
  93513. uval <<= bits;
  93514. if(cbits) {
  93515. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93516. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93517. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93518. cbits += bits;
  93519. goto break2;
  93520. }
  93521. else {
  93522. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93523. cbits += bits;
  93524. goto break2;
  93525. }
  93526. }
  93527. }
  93528. break2:
  93529. /* compose the value */
  93530. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93531. /* are we done? */
  93532. --nvals;
  93533. if(nvals == 0) {
  93534. br->consumed_bits = cbits;
  93535. br->consumed_words = cwords;
  93536. return true;
  93537. }
  93538. uval = 0;
  93539. ++vals;
  93540. }
  93541. }
  93542. #else
  93543. {
  93544. unsigned i;
  93545. unsigned uval = 0;
  93546. /* try and get br->consumed_words and br->consumed_bits into register;
  93547. * must remember to flush them back to *br before calling other
  93548. * bitwriter functions that use them, and before returning */
  93549. register unsigned cwords;
  93550. register unsigned cbits;
  93551. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93552. FLAC__ASSERT(0 != br);
  93553. FLAC__ASSERT(0 != br->buffer);
  93554. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93555. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93556. FLAC__ASSERT(parameter < 32);
  93557. /* 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 */
  93558. if(nvals == 0)
  93559. return true;
  93560. cbits = br->consumed_bits;
  93561. cwords = br->consumed_words;
  93562. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93563. while(1) {
  93564. /* read unary part */
  93565. while(1) {
  93566. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93567. brword b = br->buffer[cwords] << cbits;
  93568. if(b) {
  93569. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93570. asm volatile (
  93571. "bsrl %1, %0;"
  93572. "notl %0;"
  93573. "andl $31, %0;"
  93574. : "=r"(i)
  93575. : "r"(b)
  93576. );
  93577. #else
  93578. i = COUNT_ZERO_MSBS(b);
  93579. #endif
  93580. uval += i;
  93581. cbits += i;
  93582. cbits++; /* skip over stop bit */
  93583. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93584. crc16_update_word_(br, br->buffer[cwords]);
  93585. cwords++;
  93586. cbits = 0;
  93587. }
  93588. goto break1;
  93589. }
  93590. else {
  93591. uval += FLAC__BITS_PER_WORD - cbits;
  93592. crc16_update_word_(br, br->buffer[cwords]);
  93593. cwords++;
  93594. cbits = 0;
  93595. /* didn't find stop bit yet, have to keep going... */
  93596. }
  93597. }
  93598. /* at this point we've eaten up all the whole words; have to try
  93599. * reading through any tail bytes before calling the read callback.
  93600. * this is a repeat of the above logic adjusted for the fact we
  93601. * don't have a whole word. note though if the client is feeding
  93602. * us data a byte at a time (unlikely), br->consumed_bits may not
  93603. * be zero.
  93604. */
  93605. if(br->bytes) {
  93606. const unsigned end = br->bytes * 8;
  93607. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93608. if(b) {
  93609. i = COUNT_ZERO_MSBS(b);
  93610. uval += i;
  93611. cbits += i;
  93612. cbits++; /* skip over stop bit */
  93613. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93614. goto break1;
  93615. }
  93616. else {
  93617. uval += end - cbits;
  93618. cbits += end;
  93619. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93620. /* didn't find stop bit yet, have to keep going... */
  93621. }
  93622. }
  93623. /* flush registers and read; bitreader_read_from_client_() does
  93624. * not touch br->consumed_bits at all but we still need to set
  93625. * it in case it fails and we have to return false.
  93626. */
  93627. br->consumed_bits = cbits;
  93628. br->consumed_words = cwords;
  93629. if(!bitreader_read_from_client_(br))
  93630. return false;
  93631. cwords = br->consumed_words;
  93632. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93633. /* + uval to offset our count by the # of unary bits already
  93634. * consumed before the read, because we will add these back
  93635. * in all at once at break1
  93636. */
  93637. }
  93638. break1:
  93639. ucbits -= uval;
  93640. ucbits--; /* account for stop bit */
  93641. /* read binary part */
  93642. FLAC__ASSERT(cwords <= br->words);
  93643. if(parameter) {
  93644. while(ucbits < parameter) {
  93645. /* flush registers and read; bitreader_read_from_client_() does
  93646. * not touch br->consumed_bits at all but we still need to set
  93647. * it in case it fails and we have to return false.
  93648. */
  93649. br->consumed_bits = cbits;
  93650. br->consumed_words = cwords;
  93651. if(!bitreader_read_from_client_(br))
  93652. return false;
  93653. cwords = br->consumed_words;
  93654. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93655. }
  93656. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93657. if(cbits) {
  93658. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93659. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93660. const brword word = br->buffer[cwords];
  93661. if(parameter < n) {
  93662. uval <<= parameter;
  93663. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93664. cbits += parameter;
  93665. }
  93666. else {
  93667. uval <<= n;
  93668. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93669. crc16_update_word_(br, word);
  93670. cwords++;
  93671. cbits = parameter - n;
  93672. 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 */
  93673. uval <<= cbits;
  93674. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  93675. }
  93676. }
  93677. }
  93678. else {
  93679. cbits = parameter;
  93680. uval <<= parameter;
  93681. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93682. }
  93683. }
  93684. else {
  93685. /* in this case we're starting our read at a partial tail word;
  93686. * the reader has guaranteed that we have at least 'parameter'
  93687. * bits available to read, which makes this case simpler.
  93688. */
  93689. uval <<= parameter;
  93690. if(cbits) {
  93691. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93692. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  93693. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  93694. cbits += parameter;
  93695. }
  93696. else {
  93697. cbits = parameter;
  93698. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  93699. }
  93700. }
  93701. }
  93702. ucbits -= parameter;
  93703. /* compose the value */
  93704. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93705. /* are we done? */
  93706. --nvals;
  93707. if(nvals == 0) {
  93708. br->consumed_bits = cbits;
  93709. br->consumed_words = cwords;
  93710. return true;
  93711. }
  93712. uval = 0;
  93713. ++vals;
  93714. }
  93715. }
  93716. #endif
  93717. #if 0 /* UNUSED */
  93718. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93719. {
  93720. FLAC__uint32 lsbs = 0, msbs = 0;
  93721. unsigned bit, uval, k;
  93722. FLAC__ASSERT(0 != br);
  93723. FLAC__ASSERT(0 != br->buffer);
  93724. k = FLAC__bitmath_ilog2(parameter);
  93725. /* read the unary MSBs and end bit */
  93726. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93727. return false;
  93728. /* read the binary LSBs */
  93729. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93730. return false;
  93731. if(parameter == 1u<<k) {
  93732. /* compose the value */
  93733. uval = (msbs << k) | lsbs;
  93734. }
  93735. else {
  93736. unsigned d = (1 << (k+1)) - parameter;
  93737. if(lsbs >= d) {
  93738. if(!FLAC__bitreader_read_bit(br, &bit))
  93739. return false;
  93740. lsbs <<= 1;
  93741. lsbs |= bit;
  93742. lsbs -= d;
  93743. }
  93744. /* compose the value */
  93745. uval = msbs * parameter + lsbs;
  93746. }
  93747. /* unfold unsigned to signed */
  93748. if(uval & 1)
  93749. *val = -((int)(uval >> 1)) - 1;
  93750. else
  93751. *val = (int)(uval >> 1);
  93752. return true;
  93753. }
  93754. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  93755. {
  93756. FLAC__uint32 lsbs, msbs = 0;
  93757. unsigned bit, k;
  93758. FLAC__ASSERT(0 != br);
  93759. FLAC__ASSERT(0 != br->buffer);
  93760. k = FLAC__bitmath_ilog2(parameter);
  93761. /* read the unary MSBs and end bit */
  93762. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  93763. return false;
  93764. /* read the binary LSBs */
  93765. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  93766. return false;
  93767. if(parameter == 1u<<k) {
  93768. /* compose the value */
  93769. *val = (msbs << k) | lsbs;
  93770. }
  93771. else {
  93772. unsigned d = (1 << (k+1)) - parameter;
  93773. if(lsbs >= d) {
  93774. if(!FLAC__bitreader_read_bit(br, &bit))
  93775. return false;
  93776. lsbs <<= 1;
  93777. lsbs |= bit;
  93778. lsbs -= d;
  93779. }
  93780. /* compose the value */
  93781. *val = msbs * parameter + lsbs;
  93782. }
  93783. return true;
  93784. }
  93785. #endif /* UNUSED */
  93786. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93787. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  93788. {
  93789. FLAC__uint32 v = 0;
  93790. FLAC__uint32 x;
  93791. unsigned i;
  93792. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93793. return false;
  93794. if(raw)
  93795. raw[(*rawlen)++] = (FLAC__byte)x;
  93796. if(!(x & 0x80)) { /* 0xxxxxxx */
  93797. v = x;
  93798. i = 0;
  93799. }
  93800. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93801. v = x & 0x1F;
  93802. i = 1;
  93803. }
  93804. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93805. v = x & 0x0F;
  93806. i = 2;
  93807. }
  93808. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93809. v = x & 0x07;
  93810. i = 3;
  93811. }
  93812. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93813. v = x & 0x03;
  93814. i = 4;
  93815. }
  93816. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93817. v = x & 0x01;
  93818. i = 5;
  93819. }
  93820. else {
  93821. *val = 0xffffffff;
  93822. return true;
  93823. }
  93824. for( ; i; i--) {
  93825. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93826. return false;
  93827. if(raw)
  93828. raw[(*rawlen)++] = (FLAC__byte)x;
  93829. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93830. *val = 0xffffffff;
  93831. return true;
  93832. }
  93833. v <<= 6;
  93834. v |= (x & 0x3F);
  93835. }
  93836. *val = v;
  93837. return true;
  93838. }
  93839. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  93840. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  93841. {
  93842. FLAC__uint64 v = 0;
  93843. FLAC__uint32 x;
  93844. unsigned i;
  93845. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93846. return false;
  93847. if(raw)
  93848. raw[(*rawlen)++] = (FLAC__byte)x;
  93849. if(!(x & 0x80)) { /* 0xxxxxxx */
  93850. v = x;
  93851. i = 0;
  93852. }
  93853. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  93854. v = x & 0x1F;
  93855. i = 1;
  93856. }
  93857. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  93858. v = x & 0x0F;
  93859. i = 2;
  93860. }
  93861. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  93862. v = x & 0x07;
  93863. i = 3;
  93864. }
  93865. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  93866. v = x & 0x03;
  93867. i = 4;
  93868. }
  93869. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  93870. v = x & 0x01;
  93871. i = 5;
  93872. }
  93873. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  93874. v = 0;
  93875. i = 6;
  93876. }
  93877. else {
  93878. *val = FLAC__U64L(0xffffffffffffffff);
  93879. return true;
  93880. }
  93881. for( ; i; i--) {
  93882. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93883. return false;
  93884. if(raw)
  93885. raw[(*rawlen)++] = (FLAC__byte)x;
  93886. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  93887. *val = FLAC__U64L(0xffffffffffffffff);
  93888. return true;
  93889. }
  93890. v <<= 6;
  93891. v |= (x & 0x3F);
  93892. }
  93893. *val = v;
  93894. return true;
  93895. }
  93896. #endif
  93897. /*** End of inlined file: bitreader.c ***/
  93898. /*** Start of inlined file: bitwriter.c ***/
  93899. /*** Start of inlined file: juce_FlacHeader.h ***/
  93900. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93901. // tasks..
  93902. #define VERSION "1.2.1"
  93903. #define FLAC__NO_DLL 1
  93904. #if JUCE_MSVC
  93905. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93906. #endif
  93907. #if JUCE_MAC
  93908. #define FLAC__SYS_DARWIN 1
  93909. #endif
  93910. /*** End of inlined file: juce_FlacHeader.h ***/
  93911. #if JUCE_USE_FLAC
  93912. #if HAVE_CONFIG_H
  93913. # include <config.h>
  93914. #endif
  93915. #include <stdlib.h> /* for malloc() */
  93916. #include <string.h> /* for memcpy(), memset() */
  93917. #ifdef _MSC_VER
  93918. #include <winsock.h> /* for ntohl() */
  93919. #elif defined FLAC__SYS_DARWIN
  93920. #include <machine/endian.h> /* for ntohl() */
  93921. #elif defined __MINGW32__
  93922. #include <winsock.h> /* for ntohl() */
  93923. #else
  93924. #include <netinet/in.h> /* for ntohl() */
  93925. #endif
  93926. #if 0 /* UNUSED */
  93927. #endif
  93928. /*** Start of inlined file: bitwriter.h ***/
  93929. #ifndef FLAC__PRIVATE__BITWRITER_H
  93930. #define FLAC__PRIVATE__BITWRITER_H
  93931. #include <stdio.h> /* for FILE */
  93932. /*
  93933. * opaque structure definition
  93934. */
  93935. struct FLAC__BitWriter;
  93936. typedef struct FLAC__BitWriter FLAC__BitWriter;
  93937. /*
  93938. * construction, deletion, initialization, etc functions
  93939. */
  93940. FLAC__BitWriter *FLAC__bitwriter_new(void);
  93941. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  93942. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  93943. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  93944. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  93945. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  93946. /*
  93947. * CRC functions
  93948. *
  93949. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  93950. */
  93951. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  93952. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  93953. /*
  93954. * info functions
  93955. */
  93956. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  93957. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  93958. /*
  93959. * direct buffer access
  93960. *
  93961. * there may be no calls on the bitwriter between get and release.
  93962. * the bitwriter continues to own the returned buffer.
  93963. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  93964. */
  93965. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  93966. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  93967. /*
  93968. * write functions
  93969. */
  93970. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  93971. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  93972. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  93973. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  93974. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  93975. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  93976. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  93977. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  93978. #if 0 /* UNUSED */
  93979. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  93980. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  93981. #endif
  93982. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  93983. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  93984. #if 0 /* UNUSED */
  93985. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  93986. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  93987. #endif
  93988. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  93989. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  93990. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  93991. #endif
  93992. /*** End of inlined file: bitwriter.h ***/
  93993. /*** Start of inlined file: alloc.h ***/
  93994. #ifndef FLAC__SHARE__ALLOC_H
  93995. #define FLAC__SHARE__ALLOC_H
  93996. #if HAVE_CONFIG_H
  93997. # include <config.h>
  93998. #endif
  93999. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94000. * before #including this file, otherwise SIZE_MAX might not be defined
  94001. */
  94002. #include <limits.h> /* for SIZE_MAX */
  94003. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94004. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94005. #endif
  94006. #include <stdlib.h> /* for size_t, malloc(), etc */
  94007. #ifndef SIZE_MAX
  94008. # ifndef SIZE_T_MAX
  94009. # ifdef _MSC_VER
  94010. # define SIZE_T_MAX UINT_MAX
  94011. # else
  94012. # error
  94013. # endif
  94014. # endif
  94015. # define SIZE_MAX SIZE_T_MAX
  94016. #endif
  94017. #ifndef FLaC__INLINE
  94018. #define FLaC__INLINE
  94019. #endif
  94020. /* avoid malloc()ing 0 bytes, see:
  94021. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94022. */
  94023. static FLaC__INLINE void *safe_malloc_(size_t size)
  94024. {
  94025. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94026. if(!size)
  94027. size++;
  94028. return malloc(size);
  94029. }
  94030. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94031. {
  94032. if(!nmemb || !size)
  94033. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94034. return calloc(nmemb, size);
  94035. }
  94036. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94037. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94038. {
  94039. size2 += size1;
  94040. if(size2 < size1)
  94041. return 0;
  94042. return safe_malloc_(size2);
  94043. }
  94044. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94045. {
  94046. size2 += size1;
  94047. if(size2 < size1)
  94048. return 0;
  94049. size3 += size2;
  94050. if(size3 < size2)
  94051. return 0;
  94052. return safe_malloc_(size3);
  94053. }
  94054. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94055. {
  94056. size2 += size1;
  94057. if(size2 < size1)
  94058. return 0;
  94059. size3 += size2;
  94060. if(size3 < size2)
  94061. return 0;
  94062. size4 += size3;
  94063. if(size4 < size3)
  94064. return 0;
  94065. return safe_malloc_(size4);
  94066. }
  94067. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94068. #if 0
  94069. needs support for cases where sizeof(size_t) != 4
  94070. {
  94071. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94072. if(sizeof(size_t) == 4) {
  94073. if ((double)size1 * (double)size2 < 4294967296.0)
  94074. return malloc(size1*size2);
  94075. }
  94076. return 0;
  94077. }
  94078. #else
  94079. /* better? */
  94080. {
  94081. if(!size1 || !size2)
  94082. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94083. if(size1 > SIZE_MAX / size2)
  94084. return 0;
  94085. return malloc(size1*size2);
  94086. }
  94087. #endif
  94088. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94089. {
  94090. if(!size1 || !size2 || !size3)
  94091. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94092. if(size1 > SIZE_MAX / size2)
  94093. return 0;
  94094. size1 *= size2;
  94095. if(size1 > SIZE_MAX / size3)
  94096. return 0;
  94097. return malloc(size1*size3);
  94098. }
  94099. /* size1*size2 + size3 */
  94100. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94101. {
  94102. if(!size1 || !size2)
  94103. return safe_malloc_(size3);
  94104. if(size1 > SIZE_MAX / size2)
  94105. return 0;
  94106. return safe_malloc_add_2op_(size1*size2, size3);
  94107. }
  94108. /* size1 * (size2 + size3) */
  94109. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94110. {
  94111. if(!size1 || (!size2 && !size3))
  94112. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94113. size2 += size3;
  94114. if(size2 < size3)
  94115. return 0;
  94116. return safe_malloc_mul_2op_(size1, size2);
  94117. }
  94118. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94119. {
  94120. size2 += size1;
  94121. if(size2 < size1)
  94122. return 0;
  94123. return realloc(ptr, size2);
  94124. }
  94125. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94126. {
  94127. size2 += size1;
  94128. if(size2 < size1)
  94129. return 0;
  94130. size3 += size2;
  94131. if(size3 < size2)
  94132. return 0;
  94133. return realloc(ptr, size3);
  94134. }
  94135. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94136. {
  94137. size2 += size1;
  94138. if(size2 < size1)
  94139. return 0;
  94140. size3 += size2;
  94141. if(size3 < size2)
  94142. return 0;
  94143. size4 += size3;
  94144. if(size4 < size3)
  94145. return 0;
  94146. return realloc(ptr, size4);
  94147. }
  94148. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94149. {
  94150. if(!size1 || !size2)
  94151. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94152. if(size1 > SIZE_MAX / size2)
  94153. return 0;
  94154. return realloc(ptr, size1*size2);
  94155. }
  94156. /* size1 * (size2 + size3) */
  94157. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94158. {
  94159. if(!size1 || (!size2 && !size3))
  94160. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94161. size2 += size3;
  94162. if(size2 < size3)
  94163. return 0;
  94164. return safe_realloc_mul_2op_(ptr, size1, size2);
  94165. }
  94166. #endif
  94167. /*** End of inlined file: alloc.h ***/
  94168. /* Things should be fastest when this matches the machine word size */
  94169. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94170. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94171. typedef FLAC__uint32 bwword;
  94172. #define FLAC__BYTES_PER_WORD 4
  94173. #define FLAC__BITS_PER_WORD 32
  94174. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94175. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94176. #if WORDS_BIGENDIAN
  94177. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94178. #else
  94179. #ifdef _MSC_VER
  94180. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94181. #else
  94182. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94183. #endif
  94184. #endif
  94185. /*
  94186. * The default capacity here doesn't matter too much. The buffer always grows
  94187. * to hold whatever is written to it. Usually the encoder will stop adding at
  94188. * a frame or metadata block, then write that out and clear the buffer for the
  94189. * next one.
  94190. */
  94191. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94192. /* When growing, increment 4K at a time */
  94193. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94194. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94195. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94196. #ifdef min
  94197. #undef min
  94198. #endif
  94199. #define min(x,y) ((x)<(y)?(x):(y))
  94200. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94201. #ifdef _MSC_VER
  94202. #define FLAC__U64L(x) x
  94203. #else
  94204. #define FLAC__U64L(x) x##LLU
  94205. #endif
  94206. #ifndef FLaC__INLINE
  94207. #define FLaC__INLINE
  94208. #endif
  94209. struct FLAC__BitWriter {
  94210. bwword *buffer;
  94211. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94212. unsigned capacity; /* capacity of buffer in words */
  94213. unsigned words; /* # of complete words in buffer */
  94214. unsigned bits; /* # of used bits in accum */
  94215. };
  94216. /* * WATCHOUT: The current implementation only grows the buffer. */
  94217. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94218. {
  94219. unsigned new_capacity;
  94220. bwword *new_buffer;
  94221. FLAC__ASSERT(0 != bw);
  94222. FLAC__ASSERT(0 != bw->buffer);
  94223. /* calculate total words needed to store 'bits_to_add' additional bits */
  94224. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94225. /* it's possible (due to pessimism in the growth estimation that
  94226. * leads to this call) that we don't actually need to grow
  94227. */
  94228. if(bw->capacity >= new_capacity)
  94229. return true;
  94230. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94231. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94232. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94233. /* make sure we got everything right */
  94234. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94235. FLAC__ASSERT(new_capacity > bw->capacity);
  94236. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94237. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94238. if(new_buffer == 0)
  94239. return false;
  94240. bw->buffer = new_buffer;
  94241. bw->capacity = new_capacity;
  94242. return true;
  94243. }
  94244. /***********************************************************************
  94245. *
  94246. * Class constructor/destructor
  94247. *
  94248. ***********************************************************************/
  94249. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94250. {
  94251. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94252. /* note that calloc() sets all members to 0 for us */
  94253. return bw;
  94254. }
  94255. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94256. {
  94257. FLAC__ASSERT(0 != bw);
  94258. FLAC__bitwriter_free(bw);
  94259. free(bw);
  94260. }
  94261. /***********************************************************************
  94262. *
  94263. * Public class methods
  94264. *
  94265. ***********************************************************************/
  94266. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94267. {
  94268. FLAC__ASSERT(0 != bw);
  94269. bw->words = bw->bits = 0;
  94270. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94271. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94272. if(bw->buffer == 0)
  94273. return false;
  94274. return true;
  94275. }
  94276. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94277. {
  94278. FLAC__ASSERT(0 != bw);
  94279. if(0 != bw->buffer)
  94280. free(bw->buffer);
  94281. bw->buffer = 0;
  94282. bw->capacity = 0;
  94283. bw->words = bw->bits = 0;
  94284. }
  94285. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94286. {
  94287. bw->words = bw->bits = 0;
  94288. }
  94289. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94290. {
  94291. unsigned i, j;
  94292. if(bw == 0) {
  94293. fprintf(out, "bitwriter is NULL\n");
  94294. }
  94295. else {
  94296. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94297. for(i = 0; i < bw->words; i++) {
  94298. fprintf(out, "%08X: ", i);
  94299. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94300. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94301. fprintf(out, "\n");
  94302. }
  94303. if(bw->bits > 0) {
  94304. fprintf(out, "%08X: ", i);
  94305. for(j = 0; j < bw->bits; j++)
  94306. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94307. fprintf(out, "\n");
  94308. }
  94309. }
  94310. }
  94311. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94312. {
  94313. const FLAC__byte *buffer;
  94314. size_t bytes;
  94315. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94316. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94317. return false;
  94318. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94319. FLAC__bitwriter_release_buffer(bw);
  94320. return true;
  94321. }
  94322. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94323. {
  94324. const FLAC__byte *buffer;
  94325. size_t bytes;
  94326. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94327. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94328. return false;
  94329. *crc = FLAC__crc8(buffer, bytes);
  94330. FLAC__bitwriter_release_buffer(bw);
  94331. return true;
  94332. }
  94333. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94334. {
  94335. return ((bw->bits & 7) == 0);
  94336. }
  94337. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94338. {
  94339. return FLAC__TOTAL_BITS(bw);
  94340. }
  94341. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94342. {
  94343. FLAC__ASSERT((bw->bits & 7) == 0);
  94344. /* double protection */
  94345. if(bw->bits & 7)
  94346. return false;
  94347. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94348. if(bw->bits) {
  94349. FLAC__ASSERT(bw->words <= bw->capacity);
  94350. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94351. return false;
  94352. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94353. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94354. }
  94355. /* now we can just return what we have */
  94356. *buffer = (FLAC__byte*)bw->buffer;
  94357. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94358. return true;
  94359. }
  94360. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94361. {
  94362. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94363. * get-mode' flag could be added everywhere and then cleared here
  94364. */
  94365. (void)bw;
  94366. }
  94367. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94368. {
  94369. unsigned n;
  94370. FLAC__ASSERT(0 != bw);
  94371. FLAC__ASSERT(0 != bw->buffer);
  94372. if(bits == 0)
  94373. return true;
  94374. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94375. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94376. return false;
  94377. /* first part gets to word alignment */
  94378. if(bw->bits) {
  94379. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94380. bw->accum <<= n;
  94381. bits -= n;
  94382. bw->bits += n;
  94383. if(bw->bits == FLAC__BITS_PER_WORD) {
  94384. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94385. bw->bits = 0;
  94386. }
  94387. else
  94388. return true;
  94389. }
  94390. /* do whole words */
  94391. while(bits >= FLAC__BITS_PER_WORD) {
  94392. bw->buffer[bw->words++] = 0;
  94393. bits -= FLAC__BITS_PER_WORD;
  94394. }
  94395. /* do any leftovers */
  94396. if(bits > 0) {
  94397. bw->accum = 0;
  94398. bw->bits = bits;
  94399. }
  94400. return true;
  94401. }
  94402. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94403. {
  94404. register unsigned left;
  94405. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94406. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94407. FLAC__ASSERT(0 != bw);
  94408. FLAC__ASSERT(0 != bw->buffer);
  94409. FLAC__ASSERT(bits <= 32);
  94410. if(bits == 0)
  94411. return true;
  94412. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94413. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94414. return false;
  94415. left = FLAC__BITS_PER_WORD - bw->bits;
  94416. if(bits < left) {
  94417. bw->accum <<= bits;
  94418. bw->accum |= val;
  94419. bw->bits += bits;
  94420. }
  94421. 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 */
  94422. bw->accum <<= left;
  94423. bw->accum |= val >> (bw->bits = bits - left);
  94424. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94425. bw->accum = val;
  94426. }
  94427. else {
  94428. bw->accum = val;
  94429. bw->bits = 0;
  94430. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94431. }
  94432. return true;
  94433. }
  94434. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94435. {
  94436. /* zero-out unused bits */
  94437. if(bits < 32)
  94438. val &= (~(0xffffffff << bits));
  94439. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94440. }
  94441. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94442. {
  94443. /* this could be a little faster but it's not used for much */
  94444. if(bits > 32) {
  94445. return
  94446. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94447. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94448. }
  94449. else
  94450. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94451. }
  94452. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94453. {
  94454. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94455. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94456. return false;
  94457. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94458. return false;
  94459. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94460. return false;
  94461. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94462. return false;
  94463. return true;
  94464. }
  94465. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94466. {
  94467. unsigned i;
  94468. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94469. for(i = 0; i < nvals; i++) {
  94470. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94471. return false;
  94472. }
  94473. return true;
  94474. }
  94475. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94476. {
  94477. if(val < 32)
  94478. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94479. else
  94480. return
  94481. FLAC__bitwriter_write_zeroes(bw, val) &&
  94482. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94483. }
  94484. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94485. {
  94486. FLAC__uint32 uval;
  94487. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94488. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94489. uval = (val<<1) ^ (val>>31);
  94490. return 1 + parameter + (uval >> parameter);
  94491. }
  94492. #if 0 /* UNUSED */
  94493. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94494. {
  94495. unsigned bits, msbs, uval;
  94496. unsigned k;
  94497. FLAC__ASSERT(parameter > 0);
  94498. /* fold signed to unsigned */
  94499. if(val < 0)
  94500. uval = (unsigned)(((-(++val)) << 1) + 1);
  94501. else
  94502. uval = (unsigned)(val << 1);
  94503. k = FLAC__bitmath_ilog2(parameter);
  94504. if(parameter == 1u<<k) {
  94505. FLAC__ASSERT(k <= 30);
  94506. msbs = uval >> k;
  94507. bits = 1 + k + msbs;
  94508. }
  94509. else {
  94510. unsigned q, r, d;
  94511. d = (1 << (k+1)) - parameter;
  94512. q = uval / parameter;
  94513. r = uval - (q * parameter);
  94514. bits = 1 + q + k;
  94515. if(r >= d)
  94516. bits++;
  94517. }
  94518. return bits;
  94519. }
  94520. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94521. {
  94522. unsigned bits, msbs;
  94523. unsigned k;
  94524. FLAC__ASSERT(parameter > 0);
  94525. k = FLAC__bitmath_ilog2(parameter);
  94526. if(parameter == 1u<<k) {
  94527. FLAC__ASSERT(k <= 30);
  94528. msbs = uval >> k;
  94529. bits = 1 + k + msbs;
  94530. }
  94531. else {
  94532. unsigned q, r, d;
  94533. d = (1 << (k+1)) - parameter;
  94534. q = uval / parameter;
  94535. r = uval - (q * parameter);
  94536. bits = 1 + q + k;
  94537. if(r >= d)
  94538. bits++;
  94539. }
  94540. return bits;
  94541. }
  94542. #endif /* UNUSED */
  94543. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94544. {
  94545. unsigned total_bits, interesting_bits, msbs;
  94546. FLAC__uint32 uval, pattern;
  94547. FLAC__ASSERT(0 != bw);
  94548. FLAC__ASSERT(0 != bw->buffer);
  94549. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94550. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94551. uval = (val<<1) ^ (val>>31);
  94552. msbs = uval >> parameter;
  94553. interesting_bits = 1 + parameter;
  94554. total_bits = interesting_bits + msbs;
  94555. pattern = 1 << parameter; /* the unary end bit */
  94556. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94557. if(total_bits <= 32)
  94558. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94559. else
  94560. return
  94561. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94562. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94563. }
  94564. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94565. {
  94566. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94567. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94568. FLAC__uint32 uval;
  94569. unsigned left;
  94570. const unsigned lsbits = 1 + parameter;
  94571. unsigned msbits;
  94572. FLAC__ASSERT(0 != bw);
  94573. FLAC__ASSERT(0 != bw->buffer);
  94574. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94575. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94576. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94577. while(nvals) {
  94578. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94579. uval = (*vals<<1) ^ (*vals>>31);
  94580. msbits = uval >> parameter;
  94581. #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) */
  94582. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94583. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94584. bw->bits = bw->bits + msbits + lsbits;
  94585. uval |= mask1; /* set stop bit */
  94586. uval &= mask2; /* mask off unused top bits */
  94587. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94588. bw->accum <<= msbits;
  94589. bw->accum <<= lsbits;
  94590. bw->accum |= uval;
  94591. if(bw->bits == FLAC__BITS_PER_WORD) {
  94592. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94593. bw->bits = 0;
  94594. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94595. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94596. FLAC__ASSERT(bw->capacity == bw->words);
  94597. return false;
  94598. }
  94599. }
  94600. }
  94601. else {
  94602. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94603. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94604. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94605. bw->bits = bw->bits + msbits + lsbits;
  94606. uval |= mask1; /* set stop bit */
  94607. uval &= mask2; /* mask off unused top bits */
  94608. bw->accum <<= msbits + lsbits;
  94609. bw->accum |= uval;
  94610. }
  94611. else {
  94612. #endif
  94613. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94614. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94615. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94616. return false;
  94617. if(msbits) {
  94618. /* first part gets to word alignment */
  94619. if(bw->bits) {
  94620. left = FLAC__BITS_PER_WORD - bw->bits;
  94621. if(msbits < left) {
  94622. bw->accum <<= msbits;
  94623. bw->bits += msbits;
  94624. goto break1;
  94625. }
  94626. else {
  94627. bw->accum <<= left;
  94628. msbits -= left;
  94629. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94630. bw->bits = 0;
  94631. }
  94632. }
  94633. /* do whole words */
  94634. while(msbits >= FLAC__BITS_PER_WORD) {
  94635. bw->buffer[bw->words++] = 0;
  94636. msbits -= FLAC__BITS_PER_WORD;
  94637. }
  94638. /* do any leftovers */
  94639. if(msbits > 0) {
  94640. bw->accum = 0;
  94641. bw->bits = msbits;
  94642. }
  94643. }
  94644. break1:
  94645. uval |= mask1; /* set stop bit */
  94646. uval &= mask2; /* mask off unused top bits */
  94647. left = FLAC__BITS_PER_WORD - bw->bits;
  94648. if(lsbits < left) {
  94649. bw->accum <<= lsbits;
  94650. bw->accum |= uval;
  94651. bw->bits += lsbits;
  94652. }
  94653. else {
  94654. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94655. * be > lsbits (because of previous assertions) so it would have
  94656. * triggered the (lsbits<left) case above.
  94657. */
  94658. FLAC__ASSERT(bw->bits);
  94659. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94660. bw->accum <<= left;
  94661. bw->accum |= uval >> (bw->bits = lsbits - left);
  94662. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94663. bw->accum = uval;
  94664. }
  94665. #if 1
  94666. }
  94667. #endif
  94668. vals++;
  94669. nvals--;
  94670. }
  94671. return true;
  94672. }
  94673. #if 0 /* UNUSED */
  94674. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  94675. {
  94676. unsigned total_bits, msbs, uval;
  94677. unsigned k;
  94678. FLAC__ASSERT(0 != bw);
  94679. FLAC__ASSERT(0 != bw->buffer);
  94680. FLAC__ASSERT(parameter > 0);
  94681. /* fold signed to unsigned */
  94682. if(val < 0)
  94683. uval = (unsigned)(((-(++val)) << 1) + 1);
  94684. else
  94685. uval = (unsigned)(val << 1);
  94686. k = FLAC__bitmath_ilog2(parameter);
  94687. if(parameter == 1u<<k) {
  94688. unsigned pattern;
  94689. FLAC__ASSERT(k <= 30);
  94690. msbs = uval >> k;
  94691. total_bits = 1 + k + msbs;
  94692. pattern = 1 << k; /* the unary end bit */
  94693. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94694. if(total_bits <= 32) {
  94695. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94696. return false;
  94697. }
  94698. else {
  94699. /* write the unary MSBs */
  94700. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94701. return false;
  94702. /* write the unary end bit and binary LSBs */
  94703. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94704. return false;
  94705. }
  94706. }
  94707. else {
  94708. unsigned q, r, d;
  94709. d = (1 << (k+1)) - parameter;
  94710. q = uval / parameter;
  94711. r = uval - (q * parameter);
  94712. /* write the unary MSBs */
  94713. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94714. return false;
  94715. /* write the unary end bit */
  94716. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94717. return false;
  94718. /* write the binary LSBs */
  94719. if(r >= d) {
  94720. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94721. return false;
  94722. }
  94723. else {
  94724. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94725. return false;
  94726. }
  94727. }
  94728. return true;
  94729. }
  94730. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  94731. {
  94732. unsigned total_bits, msbs;
  94733. unsigned k;
  94734. FLAC__ASSERT(0 != bw);
  94735. FLAC__ASSERT(0 != bw->buffer);
  94736. FLAC__ASSERT(parameter > 0);
  94737. k = FLAC__bitmath_ilog2(parameter);
  94738. if(parameter == 1u<<k) {
  94739. unsigned pattern;
  94740. FLAC__ASSERT(k <= 30);
  94741. msbs = uval >> k;
  94742. total_bits = 1 + k + msbs;
  94743. pattern = 1 << k; /* the unary end bit */
  94744. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  94745. if(total_bits <= 32) {
  94746. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  94747. return false;
  94748. }
  94749. else {
  94750. /* write the unary MSBs */
  94751. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  94752. return false;
  94753. /* write the unary end bit and binary LSBs */
  94754. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  94755. return false;
  94756. }
  94757. }
  94758. else {
  94759. unsigned q, r, d;
  94760. d = (1 << (k+1)) - parameter;
  94761. q = uval / parameter;
  94762. r = uval - (q * parameter);
  94763. /* write the unary MSBs */
  94764. if(!FLAC__bitwriter_write_zeroes(bw, q))
  94765. return false;
  94766. /* write the unary end bit */
  94767. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  94768. return false;
  94769. /* write the binary LSBs */
  94770. if(r >= d) {
  94771. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  94772. return false;
  94773. }
  94774. else {
  94775. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  94776. return false;
  94777. }
  94778. }
  94779. return true;
  94780. }
  94781. #endif /* UNUSED */
  94782. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  94783. {
  94784. FLAC__bool ok = 1;
  94785. FLAC__ASSERT(0 != bw);
  94786. FLAC__ASSERT(0 != bw->buffer);
  94787. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  94788. if(val < 0x80) {
  94789. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  94790. }
  94791. else if(val < 0x800) {
  94792. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  94793. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94794. }
  94795. else if(val < 0x10000) {
  94796. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  94797. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94798. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94799. }
  94800. else if(val < 0x200000) {
  94801. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  94802. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94803. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94804. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94805. }
  94806. else if(val < 0x4000000) {
  94807. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  94808. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94809. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94810. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94811. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94812. }
  94813. else {
  94814. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  94815. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  94816. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  94817. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  94818. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  94819. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  94820. }
  94821. return ok;
  94822. }
  94823. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  94824. {
  94825. FLAC__bool ok = 1;
  94826. FLAC__ASSERT(0 != bw);
  94827. FLAC__ASSERT(0 != bw->buffer);
  94828. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  94829. if(val < 0x80) {
  94830. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  94831. }
  94832. else if(val < 0x800) {
  94833. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  94834. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94835. }
  94836. else if(val < 0x10000) {
  94837. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  94838. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94839. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94840. }
  94841. else if(val < 0x200000) {
  94842. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  94843. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94844. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94845. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94846. }
  94847. else if(val < 0x4000000) {
  94848. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  94849. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94850. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94851. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94852. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94853. }
  94854. else if(val < 0x80000000) {
  94855. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  94856. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94857. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94858. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94859. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94860. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94861. }
  94862. else {
  94863. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  94864. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  94865. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  94866. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  94867. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  94868. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  94869. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  94870. }
  94871. return ok;
  94872. }
  94873. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  94874. {
  94875. /* 0-pad to byte boundary */
  94876. if(bw->bits & 7u)
  94877. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  94878. else
  94879. return true;
  94880. }
  94881. #endif
  94882. /*** End of inlined file: bitwriter.c ***/
  94883. /*** Start of inlined file: cpu.c ***/
  94884. /*** Start of inlined file: juce_FlacHeader.h ***/
  94885. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94886. // tasks..
  94887. #define VERSION "1.2.1"
  94888. #define FLAC__NO_DLL 1
  94889. #if JUCE_MSVC
  94890. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94891. #endif
  94892. #if JUCE_MAC
  94893. #define FLAC__SYS_DARWIN 1
  94894. #endif
  94895. /*** End of inlined file: juce_FlacHeader.h ***/
  94896. #if JUCE_USE_FLAC
  94897. #if HAVE_CONFIG_H
  94898. # include <config.h>
  94899. #endif
  94900. #include <stdlib.h>
  94901. #include <stdio.h>
  94902. #if defined FLAC__CPU_IA32
  94903. # include <signal.h>
  94904. #elif defined FLAC__CPU_PPC
  94905. # if !defined FLAC__NO_ASM
  94906. # if defined FLAC__SYS_DARWIN
  94907. # include <sys/sysctl.h>
  94908. # include <mach/mach.h>
  94909. # include <mach/mach_host.h>
  94910. # include <mach/host_info.h>
  94911. # include <mach/machine.h>
  94912. # ifndef CPU_SUBTYPE_POWERPC_970
  94913. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  94914. # endif
  94915. # else /* FLAC__SYS_DARWIN */
  94916. # include <signal.h>
  94917. # include <setjmp.h>
  94918. static sigjmp_buf jmpbuf;
  94919. static volatile sig_atomic_t canjump = 0;
  94920. static void sigill_handler (int sig)
  94921. {
  94922. if (!canjump) {
  94923. signal (sig, SIG_DFL);
  94924. raise (sig);
  94925. }
  94926. canjump = 0;
  94927. siglongjmp (jmpbuf, 1);
  94928. }
  94929. # endif /* FLAC__SYS_DARWIN */
  94930. # endif /* FLAC__NO_ASM */
  94931. #endif /* FLAC__CPU_PPC */
  94932. #if defined (__NetBSD__) || defined(__OpenBSD__)
  94933. #include <sys/param.h>
  94934. #include <sys/sysctl.h>
  94935. #include <machine/cpu.h>
  94936. #endif
  94937. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  94938. #include <sys/types.h>
  94939. #include <sys/sysctl.h>
  94940. #endif
  94941. #if defined(__APPLE__)
  94942. /* how to get sysctlbyname()? */
  94943. #endif
  94944. /* these are flags in EDX of CPUID AX=00000001 */
  94945. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  94946. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  94947. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  94948. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  94949. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  94950. /* these are flags in ECX of CPUID AX=00000001 */
  94951. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  94952. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  94953. /* these are flags in EDX of CPUID AX=80000001 */
  94954. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  94955. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  94956. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  94957. /*
  94958. * Extra stuff needed for detection of OS support for SSE on IA-32
  94959. */
  94960. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  94961. # if defined(__linux__)
  94962. /*
  94963. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  94964. * modify the return address to jump over the offending SSE instruction
  94965. * and also the operation following it that indicates the instruction
  94966. * executed successfully. In this way we use no global variables and
  94967. * stay thread-safe.
  94968. *
  94969. * 3 + 3 + 6:
  94970. * 3 bytes for "xorps xmm0,xmm0"
  94971. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  94972. * 6 bytes extra in case our estimate is wrong
  94973. * 12 bytes puts us in the NOP "landing zone"
  94974. */
  94975. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  94976. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  94977. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  94978. {
  94979. (void)signal;
  94980. sc.eip += 3 + 3 + 6;
  94981. }
  94982. # else
  94983. # include <sys/ucontext.h>
  94984. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  94985. {
  94986. (void)signal, (void)si;
  94987. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  94988. }
  94989. # endif
  94990. # elif defined(_MSC_VER)
  94991. # include <windows.h>
  94992. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  94993. # ifdef USE_TRY_CATCH_FLAVOR
  94994. # else
  94995. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  94996. {
  94997. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  94998. ep->ContextRecord->Eip += 3 + 3 + 6;
  94999. return EXCEPTION_CONTINUE_EXECUTION;
  95000. }
  95001. return EXCEPTION_CONTINUE_SEARCH;
  95002. }
  95003. # endif
  95004. # endif
  95005. #endif
  95006. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95007. {
  95008. /*
  95009. * IA32-specific
  95010. */
  95011. #ifdef FLAC__CPU_IA32
  95012. info->type = FLAC__CPUINFO_TYPE_IA32;
  95013. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95014. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95015. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95016. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95017. info->data.ia32.cmov = false;
  95018. info->data.ia32.mmx = false;
  95019. info->data.ia32.fxsr = false;
  95020. info->data.ia32.sse = false;
  95021. info->data.ia32.sse2 = false;
  95022. info->data.ia32.sse3 = false;
  95023. info->data.ia32.ssse3 = false;
  95024. info->data.ia32._3dnow = false;
  95025. info->data.ia32.ext3dnow = false;
  95026. info->data.ia32.extmmx = false;
  95027. if(info->data.ia32.cpuid) {
  95028. /* http://www.sandpile.org/ia32/cpuid.htm */
  95029. FLAC__uint32 flags_edx, flags_ecx;
  95030. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95031. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95032. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95033. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95034. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95035. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95036. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95037. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95038. #ifdef FLAC__USE_3DNOW
  95039. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95040. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95041. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95042. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95043. #else
  95044. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95045. #endif
  95046. #ifdef DEBUG
  95047. fprintf(stderr, "CPU info (IA-32):\n");
  95048. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95049. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95050. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95051. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95052. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95053. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95054. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95055. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95056. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95057. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95058. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95059. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95060. #endif
  95061. /*
  95062. * now have to check for OS support of SSE/SSE2
  95063. */
  95064. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95065. #if defined FLAC__NO_SSE_OS
  95066. /* assume user knows better than us; turn it off */
  95067. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95068. #elif defined FLAC__SSE_OS
  95069. /* assume user knows better than us; leave as detected above */
  95070. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95071. int sse = 0;
  95072. size_t len;
  95073. /* at least one of these must work: */
  95074. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95075. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95076. if(!sse)
  95077. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95078. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95079. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95080. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95081. size_t len = sizeof(val);
  95082. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95083. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95084. else { /* double-check SSE2 */
  95085. mib[1] = CPU_SSE2;
  95086. len = sizeof(val);
  95087. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95088. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95089. }
  95090. # else
  95091. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95092. # endif
  95093. #elif defined(__linux__)
  95094. int sse = 0;
  95095. struct sigaction sigill_save;
  95096. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95097. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95098. #else
  95099. struct sigaction sigill_sse;
  95100. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95101. __sigemptyset(&sigill_sse.sa_mask);
  95102. 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 */
  95103. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95104. #endif
  95105. {
  95106. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95107. /* see sigill_handler_sse_os() for an explanation of the following: */
  95108. asm volatile (
  95109. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95110. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95111. "incl %0\n\t" /* SIGILL handler will jump over this */
  95112. /* landing zone */
  95113. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95114. "nop\n\t"
  95115. "nop\n\t"
  95116. "nop\n\t"
  95117. "nop\n\t"
  95118. "nop\n\t"
  95119. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95120. "nop\n\t"
  95121. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95122. : "=r"(sse)
  95123. : "r"(sse)
  95124. );
  95125. sigaction(SIGILL, &sigill_save, NULL);
  95126. }
  95127. if(!sse)
  95128. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95129. #elif defined(_MSC_VER)
  95130. # ifdef USE_TRY_CATCH_FLAVOR
  95131. _try {
  95132. __asm {
  95133. # if _MSC_VER <= 1200
  95134. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95135. _emit 0x0F
  95136. _emit 0x57
  95137. _emit 0xC0
  95138. # else
  95139. xorps xmm0,xmm0
  95140. # endif
  95141. }
  95142. }
  95143. _except(EXCEPTION_EXECUTE_HANDLER) {
  95144. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95145. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95146. }
  95147. # else
  95148. int sse = 0;
  95149. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95150. /* see GCC version above for explanation */
  95151. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95152. /* http://www.codeproject.com/cpp/gccasm.asp */
  95153. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95154. __asm {
  95155. # if _MSC_VER <= 1200
  95156. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95157. _emit 0x0F
  95158. _emit 0x57
  95159. _emit 0xC0
  95160. # else
  95161. xorps xmm0,xmm0
  95162. # endif
  95163. inc sse
  95164. nop
  95165. nop
  95166. nop
  95167. nop
  95168. nop
  95169. nop
  95170. nop
  95171. nop
  95172. nop
  95173. }
  95174. SetUnhandledExceptionFilter(save);
  95175. if(!sse)
  95176. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95177. # endif
  95178. #else
  95179. /* no way to test, disable to be safe */
  95180. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95181. #endif
  95182. #ifdef DEBUG
  95183. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95184. #endif
  95185. }
  95186. }
  95187. #else
  95188. info->use_asm = false;
  95189. #endif
  95190. /*
  95191. * PPC-specific
  95192. */
  95193. #elif defined FLAC__CPU_PPC
  95194. info->type = FLAC__CPUINFO_TYPE_PPC;
  95195. # if !defined FLAC__NO_ASM
  95196. info->use_asm = true;
  95197. # ifdef FLAC__USE_ALTIVEC
  95198. # if defined FLAC__SYS_DARWIN
  95199. {
  95200. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95201. size_t len = sizeof(val);
  95202. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95203. }
  95204. {
  95205. host_basic_info_data_t hostInfo;
  95206. mach_msg_type_number_t infoCount;
  95207. infoCount = HOST_BASIC_INFO_COUNT;
  95208. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95209. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95210. }
  95211. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95212. {
  95213. /* no Darwin, do it the brute-force way */
  95214. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95215. info->data.ppc.altivec = 0;
  95216. info->data.ppc.ppc64 = 0;
  95217. signal (SIGILL, sigill_handler);
  95218. canjump = 0;
  95219. if (!sigsetjmp (jmpbuf, 1)) {
  95220. canjump = 1;
  95221. asm volatile (
  95222. "mtspr 256, %0\n\t"
  95223. "vand %%v0, %%v0, %%v0"
  95224. :
  95225. : "r" (-1)
  95226. );
  95227. info->data.ppc.altivec = 1;
  95228. }
  95229. canjump = 0;
  95230. if (!sigsetjmp (jmpbuf, 1)) {
  95231. int x = 0;
  95232. canjump = 1;
  95233. /* PPC64 hardware implements the cntlzd instruction */
  95234. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95235. info->data.ppc.ppc64 = 1;
  95236. }
  95237. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95238. }
  95239. # endif
  95240. # else /* !FLAC__USE_ALTIVEC */
  95241. info->data.ppc.altivec = 0;
  95242. info->data.ppc.ppc64 = 0;
  95243. # endif
  95244. # else
  95245. info->use_asm = false;
  95246. # endif
  95247. /*
  95248. * unknown CPI
  95249. */
  95250. #else
  95251. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95252. info->use_asm = false;
  95253. #endif
  95254. }
  95255. #endif
  95256. /*** End of inlined file: cpu.c ***/
  95257. /*** Start of inlined file: crc.c ***/
  95258. /*** Start of inlined file: juce_FlacHeader.h ***/
  95259. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95260. // tasks..
  95261. #define VERSION "1.2.1"
  95262. #define FLAC__NO_DLL 1
  95263. #if JUCE_MSVC
  95264. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95265. #endif
  95266. #if JUCE_MAC
  95267. #define FLAC__SYS_DARWIN 1
  95268. #endif
  95269. /*** End of inlined file: juce_FlacHeader.h ***/
  95270. #if JUCE_USE_FLAC
  95271. #if HAVE_CONFIG_H
  95272. # include <config.h>
  95273. #endif
  95274. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95275. FLAC__byte const FLAC__crc8_table[256] = {
  95276. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95277. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95278. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95279. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95280. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95281. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95282. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95283. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95284. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95285. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95286. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95287. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95288. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95289. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95290. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95291. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95292. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95293. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95294. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95295. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95296. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95297. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95298. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95299. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95300. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95301. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95302. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95303. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95304. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95305. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95306. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95307. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95308. };
  95309. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95310. unsigned FLAC__crc16_table[256] = {
  95311. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95312. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95313. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95314. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95315. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95316. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95317. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95318. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95319. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95320. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95321. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95322. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95323. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95324. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95325. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95326. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95327. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95328. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95329. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95330. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95331. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95332. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95333. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95334. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95335. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95336. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95337. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95338. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95339. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95340. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95341. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95342. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95343. };
  95344. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95345. {
  95346. *crc = FLAC__crc8_table[*crc ^ data];
  95347. }
  95348. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95349. {
  95350. while(len--)
  95351. *crc = FLAC__crc8_table[*crc ^ *data++];
  95352. }
  95353. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95354. {
  95355. FLAC__uint8 crc = 0;
  95356. while(len--)
  95357. crc = FLAC__crc8_table[crc ^ *data++];
  95358. return crc;
  95359. }
  95360. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95361. {
  95362. unsigned crc = 0;
  95363. while(len--)
  95364. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95365. return crc;
  95366. }
  95367. #endif
  95368. /*** End of inlined file: crc.c ***/
  95369. /*** Start of inlined file: fixed.c ***/
  95370. /*** Start of inlined file: juce_FlacHeader.h ***/
  95371. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95372. // tasks..
  95373. #define VERSION "1.2.1"
  95374. #define FLAC__NO_DLL 1
  95375. #if JUCE_MSVC
  95376. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95377. #endif
  95378. #if JUCE_MAC
  95379. #define FLAC__SYS_DARWIN 1
  95380. #endif
  95381. /*** End of inlined file: juce_FlacHeader.h ***/
  95382. #if JUCE_USE_FLAC
  95383. #if HAVE_CONFIG_H
  95384. # include <config.h>
  95385. #endif
  95386. #include <math.h>
  95387. #include <string.h>
  95388. /*** Start of inlined file: fixed.h ***/
  95389. #ifndef FLAC__PRIVATE__FIXED_H
  95390. #define FLAC__PRIVATE__FIXED_H
  95391. #ifdef HAVE_CONFIG_H
  95392. #include <config.h>
  95393. #endif
  95394. /*** Start of inlined file: float.h ***/
  95395. #ifndef FLAC__PRIVATE__FLOAT_H
  95396. #define FLAC__PRIVATE__FLOAT_H
  95397. #ifdef HAVE_CONFIG_H
  95398. #include <config.h>
  95399. #endif
  95400. /*
  95401. * These typedefs make it easier to ensure that integer versions of
  95402. * the library really only contain integer operations. All the code
  95403. * in libFLAC should use FLAC__float and FLAC__double in place of
  95404. * float and double, and be protected by checks of the macro
  95405. * FLAC__INTEGER_ONLY_LIBRARY.
  95406. *
  95407. * FLAC__real is the basic floating point type used in LPC analysis.
  95408. */
  95409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95410. typedef double FLAC__double;
  95411. typedef float FLAC__float;
  95412. /*
  95413. * WATCHOUT: changing FLAC__real will change the signatures of many
  95414. * functions that have assembly language equivalents and break them.
  95415. */
  95416. typedef float FLAC__real;
  95417. #else
  95418. /*
  95419. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95420. * for the integer part and lower 16 bits for the fractional part.
  95421. */
  95422. typedef FLAC__int32 FLAC__fixedpoint;
  95423. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95424. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95425. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95426. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95427. extern const FLAC__fixedpoint FLAC__FP_E;
  95428. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95429. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95430. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95431. /*
  95432. * FLAC__fixedpoint_log2()
  95433. * --------------------------------------------------------------------
  95434. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95435. * algorithm by Knuth for x >= 1.0
  95436. *
  95437. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95438. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95439. *
  95440. * 'precision' roughly limits the number of iterations that are done;
  95441. * use (unsigned)(-1) for maximum precision.
  95442. *
  95443. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95444. * function will punt and return 0.
  95445. *
  95446. * The return value will also have 'fracbits' fractional bits.
  95447. */
  95448. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95449. #endif
  95450. #endif
  95451. /*** End of inlined file: float.h ***/
  95452. /*** Start of inlined file: format.h ***/
  95453. #ifndef FLAC__PRIVATE__FORMAT_H
  95454. #define FLAC__PRIVATE__FORMAT_H
  95455. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95456. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95457. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95458. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95459. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95460. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95461. #endif
  95462. /*** End of inlined file: format.h ***/
  95463. /*
  95464. * FLAC__fixed_compute_best_predictor()
  95465. * --------------------------------------------------------------------
  95466. * Compute the best fixed predictor and the expected bits-per-sample
  95467. * of the residual signal for each order. The _wide() version uses
  95468. * 64-bit integers which is statistically necessary when bits-per-
  95469. * sample + log2(blocksize) > 30
  95470. *
  95471. * IN data[0,data_len-1]
  95472. * IN data_len
  95473. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95474. */
  95475. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95476. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95477. # ifndef FLAC__NO_ASM
  95478. # ifdef FLAC__CPU_IA32
  95479. # ifdef FLAC__HAS_NASM
  95480. 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]);
  95481. # endif
  95482. # endif
  95483. # endif
  95484. 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]);
  95485. #else
  95486. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95487. 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]);
  95488. #endif
  95489. /*
  95490. * FLAC__fixed_compute_residual()
  95491. * --------------------------------------------------------------------
  95492. * Compute the residual signal obtained from sutracting the predicted
  95493. * signal from the original.
  95494. *
  95495. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95496. * IN data_len length of original signal
  95497. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95498. * OUT residual[0,data_len-1] residual signal
  95499. */
  95500. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95501. /*
  95502. * FLAC__fixed_restore_signal()
  95503. * --------------------------------------------------------------------
  95504. * Restore the original signal by summing the residual and the
  95505. * predictor.
  95506. *
  95507. * IN residual[0,data_len-1] residual signal
  95508. * IN data_len length of original signal
  95509. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95510. * *** IMPORTANT: the caller must pass in the historical samples:
  95511. * IN data[-order,-1] previously-reconstructed historical samples
  95512. * OUT data[0,data_len-1] original signal
  95513. */
  95514. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95515. #endif
  95516. /*** End of inlined file: fixed.h ***/
  95517. #ifndef M_LN2
  95518. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95519. #define M_LN2 0.69314718055994530942
  95520. #endif
  95521. #ifdef min
  95522. #undef min
  95523. #endif
  95524. #define min(x,y) ((x) < (y)? (x) : (y))
  95525. #ifdef local_abs
  95526. #undef local_abs
  95527. #endif
  95528. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95529. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95530. /* rbps stands for residual bits per sample
  95531. *
  95532. * (ln(2) * err)
  95533. * rbps = log (-----------)
  95534. * 2 ( n )
  95535. */
  95536. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95537. {
  95538. FLAC__uint32 rbps;
  95539. unsigned bits; /* the number of bits required to represent a number */
  95540. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95541. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95542. FLAC__ASSERT(err > 0);
  95543. FLAC__ASSERT(n > 0);
  95544. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95545. if(err <= n)
  95546. return 0;
  95547. /*
  95548. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95549. * These allow us later to know we won't lose too much precision in the
  95550. * fixed-point division (err<<fracbits)/n.
  95551. */
  95552. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95553. err <<= fracbits;
  95554. err /= n;
  95555. /* err now holds err/n with fracbits fractional bits */
  95556. /*
  95557. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95558. * our purposes.
  95559. */
  95560. FLAC__ASSERT(err > 0);
  95561. bits = FLAC__bitmath_ilog2(err)+1;
  95562. if(bits > 16) {
  95563. err >>= (bits-16);
  95564. fracbits -= (bits-16);
  95565. }
  95566. rbps = (FLAC__uint32)err;
  95567. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95568. rbps *= FLAC__FP_LN2;
  95569. fracbits += 16;
  95570. FLAC__ASSERT(fracbits >= 0);
  95571. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95572. {
  95573. const int f = fracbits & 3;
  95574. if(f) {
  95575. rbps >>= f;
  95576. fracbits -= f;
  95577. }
  95578. }
  95579. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95580. if(rbps == 0)
  95581. return 0;
  95582. /*
  95583. * The return value must have 16 fractional bits. Since the whole part
  95584. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95585. * must be >= -3, these assertion allows us to be able to shift rbps
  95586. * left if necessary to get 16 fracbits without losing any bits of the
  95587. * whole part of rbps.
  95588. *
  95589. * There is a slight chance due to accumulated error that the whole part
  95590. * will require 6 bits, so we use 6 in the assertion. Really though as
  95591. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95592. */
  95593. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95594. FLAC__ASSERT(fracbits >= -3);
  95595. /* now shift the decimal point into place */
  95596. if(fracbits < 16)
  95597. return rbps << (16-fracbits);
  95598. else if(fracbits > 16)
  95599. return rbps >> (fracbits-16);
  95600. else
  95601. return rbps;
  95602. }
  95603. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95604. {
  95605. FLAC__uint32 rbps;
  95606. unsigned bits; /* the number of bits required to represent a number */
  95607. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95608. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95609. FLAC__ASSERT(err > 0);
  95610. FLAC__ASSERT(n > 0);
  95611. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95612. if(err <= n)
  95613. return 0;
  95614. /*
  95615. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95616. * These allow us later to know we won't lose too much precision in the
  95617. * fixed-point division (err<<fracbits)/n.
  95618. */
  95619. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95620. err <<= fracbits;
  95621. err /= n;
  95622. /* err now holds err/n with fracbits fractional bits */
  95623. /*
  95624. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95625. * our purposes.
  95626. */
  95627. FLAC__ASSERT(err > 0);
  95628. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95629. if(bits > 16) {
  95630. err >>= (bits-16);
  95631. fracbits -= (bits-16);
  95632. }
  95633. rbps = (FLAC__uint32)err;
  95634. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95635. rbps *= FLAC__FP_LN2;
  95636. fracbits += 16;
  95637. FLAC__ASSERT(fracbits >= 0);
  95638. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95639. {
  95640. const int f = fracbits & 3;
  95641. if(f) {
  95642. rbps >>= f;
  95643. fracbits -= f;
  95644. }
  95645. }
  95646. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95647. if(rbps == 0)
  95648. return 0;
  95649. /*
  95650. * The return value must have 16 fractional bits. Since the whole part
  95651. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95652. * must be >= -3, these assertion allows us to be able to shift rbps
  95653. * left if necessary to get 16 fracbits without losing any bits of the
  95654. * whole part of rbps.
  95655. *
  95656. * There is a slight chance due to accumulated error that the whole part
  95657. * will require 6 bits, so we use 6 in the assertion. Really though as
  95658. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95659. */
  95660. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95661. FLAC__ASSERT(fracbits >= -3);
  95662. /* now shift the decimal point into place */
  95663. if(fracbits < 16)
  95664. return rbps << (16-fracbits);
  95665. else if(fracbits > 16)
  95666. return rbps >> (fracbits-16);
  95667. else
  95668. return rbps;
  95669. }
  95670. #endif
  95671. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95672. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95673. #else
  95674. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95675. #endif
  95676. {
  95677. FLAC__int32 last_error_0 = data[-1];
  95678. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95679. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95680. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95681. FLAC__int32 error, save;
  95682. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95683. unsigned i, order;
  95684. for(i = 0; i < data_len; i++) {
  95685. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95686. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95687. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95688. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95689. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95690. }
  95691. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95692. order = 0;
  95693. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95694. order = 1;
  95695. else if(total_error_2 < min(total_error_3, total_error_4))
  95696. order = 2;
  95697. else if(total_error_3 < total_error_4)
  95698. order = 3;
  95699. else
  95700. order = 4;
  95701. /* Estimate the expected number of bits per residual signal sample. */
  95702. /* 'total_error*' is linearly related to the variance of the residual */
  95703. /* signal, so we use it directly to compute E(|x|) */
  95704. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95705. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95706. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95707. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95708. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95709. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95710. 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);
  95711. 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);
  95712. 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);
  95713. 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);
  95714. 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);
  95715. #else
  95716. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  95717. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  95718. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  95719. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  95720. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  95721. #endif
  95722. return order;
  95723. }
  95724. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95725. 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])
  95726. #else
  95727. unsigned FLAC__fixed_compute_best_predictor_wide(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  95728. #endif
  95729. {
  95730. FLAC__int32 last_error_0 = data[-1];
  95731. FLAC__int32 last_error_1 = data[-1] - data[-2];
  95732. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  95733. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  95734. FLAC__int32 error, save;
  95735. /* total_error_* are 64-bits to avoid overflow when encoding
  95736. * erratic signals when the bits-per-sample and blocksize are
  95737. * large.
  95738. */
  95739. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  95740. unsigned i, order;
  95741. for(i = 0; i < data_len; i++) {
  95742. error = data[i] ; total_error_0 += local_abs(error); save = error;
  95743. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  95744. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  95745. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  95746. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  95747. }
  95748. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  95749. order = 0;
  95750. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  95751. order = 1;
  95752. else if(total_error_2 < min(total_error_3, total_error_4))
  95753. order = 2;
  95754. else if(total_error_3 < total_error_4)
  95755. order = 3;
  95756. else
  95757. order = 4;
  95758. /* Estimate the expected number of bits per residual signal sample. */
  95759. /* 'total_error*' is linearly related to the variance of the residual */
  95760. /* signal, so we use it directly to compute E(|x|) */
  95761. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  95762. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  95763. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  95764. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  95765. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  95766. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95767. #if defined _MSC_VER || defined __MINGW32__
  95768. /* with MSVC you have to spoon feed it the casting */
  95769. 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);
  95770. 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);
  95771. 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);
  95772. 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);
  95773. 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);
  95774. #else
  95775. 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);
  95776. 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);
  95777. 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);
  95778. 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);
  95779. 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);
  95780. #endif
  95781. #else
  95782. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  95783. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  95784. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  95785. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  95786. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  95787. #endif
  95788. return order;
  95789. }
  95790. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  95791. {
  95792. const int idata_len = (int)data_len;
  95793. int i;
  95794. switch(order) {
  95795. case 0:
  95796. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95797. memcpy(residual, data, sizeof(residual[0])*data_len);
  95798. break;
  95799. case 1:
  95800. for(i = 0; i < idata_len; i++)
  95801. residual[i] = data[i] - data[i-1];
  95802. break;
  95803. case 2:
  95804. for(i = 0; i < idata_len; i++)
  95805. #if 1 /* OPT: may be faster with some compilers on some systems */
  95806. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  95807. #else
  95808. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  95809. #endif
  95810. break;
  95811. case 3:
  95812. for(i = 0; i < idata_len; i++)
  95813. #if 1 /* OPT: may be faster with some compilers on some systems */
  95814. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  95815. #else
  95816. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  95817. #endif
  95818. break;
  95819. case 4:
  95820. for(i = 0; i < idata_len; i++)
  95821. #if 1 /* OPT: may be faster with some compilers on some systems */
  95822. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  95823. #else
  95824. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  95825. #endif
  95826. break;
  95827. default:
  95828. FLAC__ASSERT(0);
  95829. }
  95830. }
  95831. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  95832. {
  95833. int i, idata_len = (int)data_len;
  95834. switch(order) {
  95835. case 0:
  95836. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  95837. memcpy(data, residual, sizeof(residual[0])*data_len);
  95838. break;
  95839. case 1:
  95840. for(i = 0; i < idata_len; i++)
  95841. data[i] = residual[i] + data[i-1];
  95842. break;
  95843. case 2:
  95844. for(i = 0; i < idata_len; i++)
  95845. #if 1 /* OPT: may be faster with some compilers on some systems */
  95846. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  95847. #else
  95848. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  95849. #endif
  95850. break;
  95851. case 3:
  95852. for(i = 0; i < idata_len; i++)
  95853. #if 1 /* OPT: may be faster with some compilers on some systems */
  95854. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  95855. #else
  95856. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  95857. #endif
  95858. break;
  95859. case 4:
  95860. for(i = 0; i < idata_len; i++)
  95861. #if 1 /* OPT: may be faster with some compilers on some systems */
  95862. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  95863. #else
  95864. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  95865. #endif
  95866. break;
  95867. default:
  95868. FLAC__ASSERT(0);
  95869. }
  95870. }
  95871. #endif
  95872. /*** End of inlined file: fixed.c ***/
  95873. /*** Start of inlined file: float.c ***/
  95874. /*** Start of inlined file: juce_FlacHeader.h ***/
  95875. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95876. // tasks..
  95877. #define VERSION "1.2.1"
  95878. #define FLAC__NO_DLL 1
  95879. #if JUCE_MSVC
  95880. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95881. #endif
  95882. #if JUCE_MAC
  95883. #define FLAC__SYS_DARWIN 1
  95884. #endif
  95885. /*** End of inlined file: juce_FlacHeader.h ***/
  95886. #if JUCE_USE_FLAC
  95887. #if HAVE_CONFIG_H
  95888. # include <config.h>
  95889. #endif
  95890. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95891. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95892. #ifdef _MSC_VER
  95893. #define FLAC__U64L(x) x
  95894. #else
  95895. #define FLAC__U64L(x) x##LLU
  95896. #endif
  95897. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  95898. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  95899. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  95900. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  95901. const FLAC__fixedpoint FLAC__FP_E = 178145;
  95902. /* Lookup tables for Knuth's logarithm algorithm */
  95903. #define LOG2_LOOKUP_PRECISION 16
  95904. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  95905. {
  95906. /*
  95907. * 0 fraction bits
  95908. */
  95909. /* undefined */ 0x00000000,
  95910. /* lg(2/1) = */ 0x00000001,
  95911. /* lg(4/3) = */ 0x00000000,
  95912. /* lg(8/7) = */ 0x00000000,
  95913. /* lg(16/15) = */ 0x00000000,
  95914. /* lg(32/31) = */ 0x00000000,
  95915. /* lg(64/63) = */ 0x00000000,
  95916. /* lg(128/127) = */ 0x00000000,
  95917. /* lg(256/255) = */ 0x00000000,
  95918. /* lg(512/511) = */ 0x00000000,
  95919. /* lg(1024/1023) = */ 0x00000000,
  95920. /* lg(2048/2047) = */ 0x00000000,
  95921. /* lg(4096/4095) = */ 0x00000000,
  95922. /* lg(8192/8191) = */ 0x00000000,
  95923. /* lg(16384/16383) = */ 0x00000000,
  95924. /* lg(32768/32767) = */ 0x00000000
  95925. },
  95926. {
  95927. /*
  95928. * 4 fraction bits
  95929. */
  95930. /* undefined */ 0x00000000,
  95931. /* lg(2/1) = */ 0x00000010,
  95932. /* lg(4/3) = */ 0x00000007,
  95933. /* lg(8/7) = */ 0x00000003,
  95934. /* lg(16/15) = */ 0x00000001,
  95935. /* lg(32/31) = */ 0x00000001,
  95936. /* lg(64/63) = */ 0x00000000,
  95937. /* lg(128/127) = */ 0x00000000,
  95938. /* lg(256/255) = */ 0x00000000,
  95939. /* lg(512/511) = */ 0x00000000,
  95940. /* lg(1024/1023) = */ 0x00000000,
  95941. /* lg(2048/2047) = */ 0x00000000,
  95942. /* lg(4096/4095) = */ 0x00000000,
  95943. /* lg(8192/8191) = */ 0x00000000,
  95944. /* lg(16384/16383) = */ 0x00000000,
  95945. /* lg(32768/32767) = */ 0x00000000
  95946. },
  95947. {
  95948. /*
  95949. * 8 fraction bits
  95950. */
  95951. /* undefined */ 0x00000000,
  95952. /* lg(2/1) = */ 0x00000100,
  95953. /* lg(4/3) = */ 0x0000006a,
  95954. /* lg(8/7) = */ 0x00000031,
  95955. /* lg(16/15) = */ 0x00000018,
  95956. /* lg(32/31) = */ 0x0000000c,
  95957. /* lg(64/63) = */ 0x00000006,
  95958. /* lg(128/127) = */ 0x00000003,
  95959. /* lg(256/255) = */ 0x00000001,
  95960. /* lg(512/511) = */ 0x00000001,
  95961. /* lg(1024/1023) = */ 0x00000000,
  95962. /* lg(2048/2047) = */ 0x00000000,
  95963. /* lg(4096/4095) = */ 0x00000000,
  95964. /* lg(8192/8191) = */ 0x00000000,
  95965. /* lg(16384/16383) = */ 0x00000000,
  95966. /* lg(32768/32767) = */ 0x00000000
  95967. },
  95968. {
  95969. /*
  95970. * 12 fraction bits
  95971. */
  95972. /* undefined */ 0x00000000,
  95973. /* lg(2/1) = */ 0x00001000,
  95974. /* lg(4/3) = */ 0x000006a4,
  95975. /* lg(8/7) = */ 0x00000315,
  95976. /* lg(16/15) = */ 0x0000017d,
  95977. /* lg(32/31) = */ 0x000000bc,
  95978. /* lg(64/63) = */ 0x0000005d,
  95979. /* lg(128/127) = */ 0x0000002e,
  95980. /* lg(256/255) = */ 0x00000017,
  95981. /* lg(512/511) = */ 0x0000000c,
  95982. /* lg(1024/1023) = */ 0x00000006,
  95983. /* lg(2048/2047) = */ 0x00000003,
  95984. /* lg(4096/4095) = */ 0x00000001,
  95985. /* lg(8192/8191) = */ 0x00000001,
  95986. /* lg(16384/16383) = */ 0x00000000,
  95987. /* lg(32768/32767) = */ 0x00000000
  95988. },
  95989. {
  95990. /*
  95991. * 16 fraction bits
  95992. */
  95993. /* undefined */ 0x00000000,
  95994. /* lg(2/1) = */ 0x00010000,
  95995. /* lg(4/3) = */ 0x00006a40,
  95996. /* lg(8/7) = */ 0x00003151,
  95997. /* lg(16/15) = */ 0x000017d6,
  95998. /* lg(32/31) = */ 0x00000bba,
  95999. /* lg(64/63) = */ 0x000005d1,
  96000. /* lg(128/127) = */ 0x000002e6,
  96001. /* lg(256/255) = */ 0x00000172,
  96002. /* lg(512/511) = */ 0x000000b9,
  96003. /* lg(1024/1023) = */ 0x0000005c,
  96004. /* lg(2048/2047) = */ 0x0000002e,
  96005. /* lg(4096/4095) = */ 0x00000017,
  96006. /* lg(8192/8191) = */ 0x0000000c,
  96007. /* lg(16384/16383) = */ 0x00000006,
  96008. /* lg(32768/32767) = */ 0x00000003
  96009. },
  96010. {
  96011. /*
  96012. * 20 fraction bits
  96013. */
  96014. /* undefined */ 0x00000000,
  96015. /* lg(2/1) = */ 0x00100000,
  96016. /* lg(4/3) = */ 0x0006a3fe,
  96017. /* lg(8/7) = */ 0x00031513,
  96018. /* lg(16/15) = */ 0x00017d60,
  96019. /* lg(32/31) = */ 0x0000bb9d,
  96020. /* lg(64/63) = */ 0x00005d10,
  96021. /* lg(128/127) = */ 0x00002e59,
  96022. /* lg(256/255) = */ 0x00001721,
  96023. /* lg(512/511) = */ 0x00000b8e,
  96024. /* lg(1024/1023) = */ 0x000005c6,
  96025. /* lg(2048/2047) = */ 0x000002e3,
  96026. /* lg(4096/4095) = */ 0x00000171,
  96027. /* lg(8192/8191) = */ 0x000000b9,
  96028. /* lg(16384/16383) = */ 0x0000005c,
  96029. /* lg(32768/32767) = */ 0x0000002e
  96030. },
  96031. {
  96032. /*
  96033. * 24 fraction bits
  96034. */
  96035. /* undefined */ 0x00000000,
  96036. /* lg(2/1) = */ 0x01000000,
  96037. /* lg(4/3) = */ 0x006a3fe6,
  96038. /* lg(8/7) = */ 0x00315130,
  96039. /* lg(16/15) = */ 0x0017d605,
  96040. /* lg(32/31) = */ 0x000bb9ca,
  96041. /* lg(64/63) = */ 0x0005d0fc,
  96042. /* lg(128/127) = */ 0x0002e58f,
  96043. /* lg(256/255) = */ 0x0001720e,
  96044. /* lg(512/511) = */ 0x0000b8d8,
  96045. /* lg(1024/1023) = */ 0x00005c61,
  96046. /* lg(2048/2047) = */ 0x00002e2d,
  96047. /* lg(4096/4095) = */ 0x00001716,
  96048. /* lg(8192/8191) = */ 0x00000b8b,
  96049. /* lg(16384/16383) = */ 0x000005c5,
  96050. /* lg(32768/32767) = */ 0x000002e3
  96051. },
  96052. {
  96053. /*
  96054. * 28 fraction bits
  96055. */
  96056. /* undefined */ 0x00000000,
  96057. /* lg(2/1) = */ 0x10000000,
  96058. /* lg(4/3) = */ 0x06a3fe5c,
  96059. /* lg(8/7) = */ 0x03151301,
  96060. /* lg(16/15) = */ 0x017d6049,
  96061. /* lg(32/31) = */ 0x00bb9ca6,
  96062. /* lg(64/63) = */ 0x005d0fba,
  96063. /* lg(128/127) = */ 0x002e58f7,
  96064. /* lg(256/255) = */ 0x001720da,
  96065. /* lg(512/511) = */ 0x000b8d87,
  96066. /* lg(1024/1023) = */ 0x0005c60b,
  96067. /* lg(2048/2047) = */ 0x0002e2d7,
  96068. /* lg(4096/4095) = */ 0x00017160,
  96069. /* lg(8192/8191) = */ 0x0000b8ad,
  96070. /* lg(16384/16383) = */ 0x00005c56,
  96071. /* lg(32768/32767) = */ 0x00002e2b
  96072. }
  96073. };
  96074. #if 0
  96075. static const FLAC__uint64 log2_lookup_wide[] = {
  96076. {
  96077. /*
  96078. * 32 fraction bits
  96079. */
  96080. /* undefined */ 0x00000000,
  96081. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96082. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96083. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96084. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96085. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96086. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96087. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96088. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96089. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96090. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96091. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96092. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96093. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96094. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96095. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96096. },
  96097. {
  96098. /*
  96099. * 48 fraction bits
  96100. */
  96101. /* undefined */ 0x00000000,
  96102. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96103. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96104. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96105. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96106. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96107. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96108. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96109. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96110. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96111. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96112. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96113. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96114. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96115. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96116. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96117. }
  96118. };
  96119. #endif
  96120. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96121. {
  96122. const FLAC__uint32 ONE = (1u << fracbits);
  96123. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96124. FLAC__ASSERT(fracbits < 32);
  96125. FLAC__ASSERT((fracbits & 0x3) == 0);
  96126. if(x < ONE)
  96127. return 0;
  96128. if(precision > LOG2_LOOKUP_PRECISION)
  96129. precision = LOG2_LOOKUP_PRECISION;
  96130. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96131. {
  96132. FLAC__uint32 y = 0;
  96133. FLAC__uint32 z = x >> 1, k = 1;
  96134. while (x > ONE && k < precision) {
  96135. if (x - z >= ONE) {
  96136. x -= z;
  96137. z = x >> k;
  96138. y += table[k];
  96139. }
  96140. else {
  96141. z >>= 1;
  96142. k++;
  96143. }
  96144. }
  96145. return y;
  96146. }
  96147. }
  96148. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96149. #endif
  96150. /*** End of inlined file: float.c ***/
  96151. /*** Start of inlined file: format.c ***/
  96152. /*** Start of inlined file: juce_FlacHeader.h ***/
  96153. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96154. // tasks..
  96155. #define VERSION "1.2.1"
  96156. #define FLAC__NO_DLL 1
  96157. #if JUCE_MSVC
  96158. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96159. #endif
  96160. #if JUCE_MAC
  96161. #define FLAC__SYS_DARWIN 1
  96162. #endif
  96163. /*** End of inlined file: juce_FlacHeader.h ***/
  96164. #if JUCE_USE_FLAC
  96165. #if HAVE_CONFIG_H
  96166. # include <config.h>
  96167. #endif
  96168. #include <stdio.h>
  96169. #include <stdlib.h> /* for qsort() */
  96170. #include <string.h> /* for memset() */
  96171. #ifndef FLaC__INLINE
  96172. #define FLaC__INLINE
  96173. #endif
  96174. #ifdef min
  96175. #undef min
  96176. #endif
  96177. #define min(a,b) ((a)<(b)?(a):(b))
  96178. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96179. #ifdef _MSC_VER
  96180. #define FLAC__U64L(x) x
  96181. #else
  96182. #define FLAC__U64L(x) x##LLU
  96183. #endif
  96184. /* VERSION should come from configure */
  96185. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96186. ;
  96187. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96188. /* yet one more hack because of MSVC6: */
  96189. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96190. #else
  96191. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96192. #endif
  96193. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96194. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96195. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96196. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96197. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96198. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96199. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96200. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96201. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96202. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96203. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96204. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96205. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96206. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96207. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96208. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96209. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96210. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96211. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96212. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96213. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96214. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96215. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96216. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96217. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96218. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96219. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96220. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96221. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96222. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96223. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96224. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96225. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96226. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96227. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96228. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96229. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96230. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96231. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96232. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96233. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96234. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96235. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96236. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96237. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96238. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96239. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96240. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96241. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96242. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96243. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96244. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96245. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96246. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96247. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96248. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96249. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96250. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96251. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96252. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96253. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96254. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96255. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96256. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96257. "PARTITIONED_RICE",
  96258. "PARTITIONED_RICE2"
  96259. };
  96260. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96261. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96262. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96263. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96264. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96265. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96266. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96267. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96268. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96269. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96270. "CONSTANT",
  96271. "VERBATIM",
  96272. "FIXED",
  96273. "LPC"
  96274. };
  96275. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96276. "INDEPENDENT",
  96277. "LEFT_SIDE",
  96278. "RIGHT_SIDE",
  96279. "MID_SIDE"
  96280. };
  96281. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96282. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96283. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96284. };
  96285. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96286. "STREAMINFO",
  96287. "PADDING",
  96288. "APPLICATION",
  96289. "SEEKTABLE",
  96290. "VORBIS_COMMENT",
  96291. "CUESHEET",
  96292. "PICTURE"
  96293. };
  96294. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96295. "Other",
  96296. "32x32 pixels 'file icon' (PNG only)",
  96297. "Other file icon",
  96298. "Cover (front)",
  96299. "Cover (back)",
  96300. "Leaflet page",
  96301. "Media (e.g. label side of CD)",
  96302. "Lead artist/lead performer/soloist",
  96303. "Artist/performer",
  96304. "Conductor",
  96305. "Band/Orchestra",
  96306. "Composer",
  96307. "Lyricist/text writer",
  96308. "Recording Location",
  96309. "During recording",
  96310. "During performance",
  96311. "Movie/video screen capture",
  96312. "A bright coloured fish",
  96313. "Illustration",
  96314. "Band/artist logotype",
  96315. "Publisher/Studio logotype"
  96316. };
  96317. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96318. {
  96319. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96320. return false;
  96321. }
  96322. else
  96323. return true;
  96324. }
  96325. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96326. {
  96327. if(
  96328. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96329. (
  96330. sample_rate >= (1u << 16) &&
  96331. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96332. )
  96333. ) {
  96334. return false;
  96335. }
  96336. else
  96337. return true;
  96338. }
  96339. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96340. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96341. {
  96342. unsigned i;
  96343. FLAC__uint64 prev_sample_number = 0;
  96344. FLAC__bool got_prev = false;
  96345. FLAC__ASSERT(0 != seek_table);
  96346. for(i = 0; i < seek_table->num_points; i++) {
  96347. if(got_prev) {
  96348. if(
  96349. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96350. seek_table->points[i].sample_number <= prev_sample_number
  96351. )
  96352. return false;
  96353. }
  96354. prev_sample_number = seek_table->points[i].sample_number;
  96355. got_prev = true;
  96356. }
  96357. return true;
  96358. }
  96359. /* used as the sort predicate for qsort() */
  96360. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96361. {
  96362. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96363. if(l->sample_number == r->sample_number)
  96364. return 0;
  96365. else if(l->sample_number < r->sample_number)
  96366. return -1;
  96367. else
  96368. return 1;
  96369. }
  96370. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96371. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96372. {
  96373. unsigned i, j;
  96374. FLAC__bool first;
  96375. FLAC__ASSERT(0 != seek_table);
  96376. /* sort the seekpoints */
  96377. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96378. /* uniquify the seekpoints */
  96379. first = true;
  96380. for(i = j = 0; i < seek_table->num_points; i++) {
  96381. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96382. if(!first) {
  96383. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96384. continue;
  96385. }
  96386. }
  96387. first = false;
  96388. seek_table->points[j++] = seek_table->points[i];
  96389. }
  96390. for(i = j; i < seek_table->num_points; i++) {
  96391. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96392. seek_table->points[i].stream_offset = 0;
  96393. seek_table->points[i].frame_samples = 0;
  96394. }
  96395. return j;
  96396. }
  96397. /*
  96398. * also disallows non-shortest-form encodings, c.f.
  96399. * http://www.unicode.org/versions/corrigendum1.html
  96400. * and a more clear explanation at the end of this section:
  96401. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96402. */
  96403. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96404. {
  96405. FLAC__ASSERT(0 != utf8);
  96406. if ((utf8[0] & 0x80) == 0) {
  96407. return 1;
  96408. }
  96409. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96410. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96411. return 0;
  96412. return 2;
  96413. }
  96414. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96415. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96416. return 0;
  96417. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96418. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96419. return 0;
  96420. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96421. return 0;
  96422. return 3;
  96423. }
  96424. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96425. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96426. return 0;
  96427. return 4;
  96428. }
  96429. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96430. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96431. return 0;
  96432. return 5;
  96433. }
  96434. 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) {
  96435. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96436. return 0;
  96437. return 6;
  96438. }
  96439. else {
  96440. return 0;
  96441. }
  96442. }
  96443. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96444. {
  96445. char c;
  96446. for(c = *name; c; c = *(++name))
  96447. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96448. return false;
  96449. return true;
  96450. }
  96451. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96452. {
  96453. if(length == (unsigned)(-1)) {
  96454. while(*value) {
  96455. unsigned n = utf8len_(value);
  96456. if(n == 0)
  96457. return false;
  96458. value += n;
  96459. }
  96460. }
  96461. else {
  96462. const FLAC__byte *end = value + length;
  96463. while(value < end) {
  96464. unsigned n = utf8len_(value);
  96465. if(n == 0)
  96466. return false;
  96467. value += n;
  96468. }
  96469. if(value != end)
  96470. return false;
  96471. }
  96472. return true;
  96473. }
  96474. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96475. {
  96476. const FLAC__byte *s, *end;
  96477. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96478. if(*s < 0x20 || *s > 0x7D)
  96479. return false;
  96480. }
  96481. if(s == end)
  96482. return false;
  96483. s++; /* skip '=' */
  96484. while(s < end) {
  96485. unsigned n = utf8len_(s);
  96486. if(n == 0)
  96487. return false;
  96488. s += n;
  96489. }
  96490. if(s != end)
  96491. return false;
  96492. return true;
  96493. }
  96494. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96495. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96496. {
  96497. unsigned i, j;
  96498. if(check_cd_da_subset) {
  96499. if(cue_sheet->lead_in < 2 * 44100) {
  96500. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96501. return false;
  96502. }
  96503. if(cue_sheet->lead_in % 588 != 0) {
  96504. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96505. return false;
  96506. }
  96507. }
  96508. if(cue_sheet->num_tracks == 0) {
  96509. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96510. return false;
  96511. }
  96512. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96513. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96514. return false;
  96515. }
  96516. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96517. if(cue_sheet->tracks[i].number == 0) {
  96518. if(violation) *violation = "cue sheet may not have a track number 0";
  96519. return false;
  96520. }
  96521. if(check_cd_da_subset) {
  96522. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96523. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96524. return false;
  96525. }
  96526. }
  96527. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96528. if(violation) {
  96529. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96530. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96531. else
  96532. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96533. }
  96534. return false;
  96535. }
  96536. if(i < cue_sheet->num_tracks - 1) {
  96537. if(cue_sheet->tracks[i].num_indices == 0) {
  96538. if(violation) *violation = "cue sheet track must have at least one index point";
  96539. return false;
  96540. }
  96541. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96542. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96543. return false;
  96544. }
  96545. }
  96546. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96547. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96548. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96549. return false;
  96550. }
  96551. if(j > 0) {
  96552. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96553. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96554. return false;
  96555. }
  96556. }
  96557. }
  96558. }
  96559. return true;
  96560. }
  96561. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96562. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96563. {
  96564. char *p;
  96565. FLAC__byte *b;
  96566. for(p = picture->mime_type; *p; p++) {
  96567. if(*p < 0x20 || *p > 0x7e) {
  96568. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96569. return false;
  96570. }
  96571. }
  96572. for(b = picture->description; *b; ) {
  96573. unsigned n = utf8len_(b);
  96574. if(n == 0) {
  96575. if(violation) *violation = "description string must be valid UTF-8";
  96576. return false;
  96577. }
  96578. b += n;
  96579. }
  96580. return true;
  96581. }
  96582. /*
  96583. * These routines are private to libFLAC
  96584. */
  96585. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96586. {
  96587. return
  96588. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96589. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96590. blocksize,
  96591. predictor_order
  96592. );
  96593. }
  96594. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96595. {
  96596. unsigned max_rice_partition_order = 0;
  96597. while(!(blocksize & 1)) {
  96598. max_rice_partition_order++;
  96599. blocksize >>= 1;
  96600. }
  96601. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96602. }
  96603. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96604. {
  96605. unsigned max_rice_partition_order = limit;
  96606. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96607. max_rice_partition_order--;
  96608. FLAC__ASSERT(
  96609. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96610. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96611. );
  96612. return max_rice_partition_order;
  96613. }
  96614. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96615. {
  96616. FLAC__ASSERT(0 != object);
  96617. object->parameters = 0;
  96618. object->raw_bits = 0;
  96619. object->capacity_by_order = 0;
  96620. }
  96621. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96622. {
  96623. FLAC__ASSERT(0 != object);
  96624. if(0 != object->parameters)
  96625. free(object->parameters);
  96626. if(0 != object->raw_bits)
  96627. free(object->raw_bits);
  96628. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96629. }
  96630. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96631. {
  96632. FLAC__ASSERT(0 != object);
  96633. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96634. if(object->capacity_by_order < max_partition_order) {
  96635. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96636. return false;
  96637. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96638. return false;
  96639. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96640. object->capacity_by_order = max_partition_order;
  96641. }
  96642. return true;
  96643. }
  96644. #endif
  96645. /*** End of inlined file: format.c ***/
  96646. /*** Start of inlined file: lpc_flac.c ***/
  96647. /*** Start of inlined file: juce_FlacHeader.h ***/
  96648. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96649. // tasks..
  96650. #define VERSION "1.2.1"
  96651. #define FLAC__NO_DLL 1
  96652. #if JUCE_MSVC
  96653. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96654. #endif
  96655. #if JUCE_MAC
  96656. #define FLAC__SYS_DARWIN 1
  96657. #endif
  96658. /*** End of inlined file: juce_FlacHeader.h ***/
  96659. #if JUCE_USE_FLAC
  96660. #if HAVE_CONFIG_H
  96661. # include <config.h>
  96662. #endif
  96663. #include <math.h>
  96664. /*** Start of inlined file: lpc.h ***/
  96665. #ifndef FLAC__PRIVATE__LPC_H
  96666. #define FLAC__PRIVATE__LPC_H
  96667. #ifdef HAVE_CONFIG_H
  96668. #include <config.h>
  96669. #endif
  96670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96671. /*
  96672. * FLAC__lpc_window_data()
  96673. * --------------------------------------------------------------------
  96674. * Applies the given window to the data.
  96675. * OPT: asm implementation
  96676. *
  96677. * IN in[0,data_len-1]
  96678. * IN window[0,data_len-1]
  96679. * OUT out[0,lag-1]
  96680. * IN data_len
  96681. */
  96682. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  96683. /*
  96684. * FLAC__lpc_compute_autocorrelation()
  96685. * --------------------------------------------------------------------
  96686. * Compute the autocorrelation for lags between 0 and lag-1.
  96687. * Assumes data[] outside of [0,data_len-1] == 0.
  96688. * Asserts that lag > 0.
  96689. *
  96690. * IN data[0,data_len-1]
  96691. * IN data_len
  96692. * IN 0 < lag <= data_len
  96693. * OUT autoc[0,lag-1]
  96694. */
  96695. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96696. #ifndef FLAC__NO_ASM
  96697. # ifdef FLAC__CPU_IA32
  96698. # ifdef FLAC__HAS_NASM
  96699. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96700. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96701. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96702. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96703. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  96704. # endif
  96705. # endif
  96706. #endif
  96707. /*
  96708. * FLAC__lpc_compute_lp_coefficients()
  96709. * --------------------------------------------------------------------
  96710. * Computes LP coefficients for orders 1..max_order.
  96711. * Do not call if autoc[0] == 0.0. This means the signal is zero
  96712. * and there is no point in calculating a predictor.
  96713. *
  96714. * IN autoc[0,max_order] autocorrelation values
  96715. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  96716. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  96717. * *** IMPORTANT:
  96718. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  96719. * OUT error[0,max_order-1] error for each order (more
  96720. * specifically, the variance of
  96721. * the error signal times # of
  96722. * samples in the signal)
  96723. *
  96724. * Example: if max_order is 9, the LP coefficients for order 9 will be
  96725. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  96726. * in lp_coeff[7][0,7], etc.
  96727. */
  96728. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  96729. /*
  96730. * FLAC__lpc_quantize_coefficients()
  96731. * --------------------------------------------------------------------
  96732. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  96733. * must be less than 32 (sizeof(FLAC__int32)*8).
  96734. *
  96735. * IN lp_coeff[0,order-1] LP coefficients
  96736. * IN order LP order
  96737. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  96738. * desired precision (in bits, including sign
  96739. * bit) of largest coefficient
  96740. * OUT qlp_coeff[0,order-1] quantized coefficients
  96741. * OUT shift # of bits to shift right to get approximated
  96742. * LP coefficients. NOTE: could be negative.
  96743. * RETURN 0 => quantization OK
  96744. * 1 => coefficients require too much shifting for *shift to
  96745. * fit in the LPC subframe header. 'shift' is unset.
  96746. * 2 => coefficients are all zero, which is bad. 'shift' is
  96747. * unset.
  96748. */
  96749. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  96750. /*
  96751. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  96752. * --------------------------------------------------------------------
  96753. * Compute the residual signal obtained from sutracting the predicted
  96754. * signal from the original.
  96755. *
  96756. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96757. * IN data_len length of original signal
  96758. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96759. * IN order > 0 LP order
  96760. * IN lp_quantization quantization of LP coefficients in bits
  96761. * OUT residual[0,data_len-1] residual signal
  96762. */
  96763. 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[]);
  96764. 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[]);
  96765. #ifndef FLAC__NO_ASM
  96766. # ifdef FLAC__CPU_IA32
  96767. # ifdef FLAC__HAS_NASM
  96768. 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[]);
  96769. 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[]);
  96770. # endif
  96771. # endif
  96772. #endif
  96773. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96774. /*
  96775. * FLAC__lpc_restore_signal()
  96776. * --------------------------------------------------------------------
  96777. * Restore the original signal by summing the residual and the
  96778. * predictor.
  96779. *
  96780. * IN residual[0,data_len-1] residual signal
  96781. * IN data_len length of original signal
  96782. * IN qlp_coeff[0,order-1] quantized LP coefficients
  96783. * IN order > 0 LP order
  96784. * IN lp_quantization quantization of LP coefficients in bits
  96785. * *** IMPORTANT: the caller must pass in the historical samples:
  96786. * IN data[-order,-1] previously-reconstructed historical samples
  96787. * OUT data[0,data_len-1] original signal
  96788. */
  96789. 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[]);
  96790. 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[]);
  96791. #ifndef FLAC__NO_ASM
  96792. # ifdef FLAC__CPU_IA32
  96793. # ifdef FLAC__HAS_NASM
  96794. 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[]);
  96795. 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[]);
  96796. # endif /* FLAC__HAS_NASM */
  96797. # elif defined FLAC__CPU_PPC
  96798. 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[]);
  96799. 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[]);
  96800. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  96801. #endif /* FLAC__NO_ASM */
  96802. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96803. /*
  96804. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  96805. * --------------------------------------------------------------------
  96806. * Compute the expected number of bits per residual signal sample
  96807. * based on the LP error (which is related to the residual variance).
  96808. *
  96809. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  96810. * IN total_samples > 0 # of samples in residual signal
  96811. * RETURN expected bits per sample
  96812. */
  96813. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  96814. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  96815. /*
  96816. * FLAC__lpc_compute_best_order()
  96817. * --------------------------------------------------------------------
  96818. * Compute the best order from the array of signal errors returned
  96819. * during coefficient computation.
  96820. *
  96821. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  96822. * IN max_order > 0 max LP order
  96823. * IN total_samples > 0 # of samples in residual signal
  96824. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  96825. * (includes warmup sample size and quantized LP coefficient)
  96826. * RETURN [1,max_order] best order
  96827. */
  96828. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  96829. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  96830. #endif
  96831. /*** End of inlined file: lpc.h ***/
  96832. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  96833. #include <stdio.h>
  96834. #endif
  96835. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96836. #ifndef M_LN2
  96837. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96838. #define M_LN2 0.69314718055994530942
  96839. #endif
  96840. /* OPT: #undef'ing this may improve the speed on some architectures */
  96841. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  96842. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  96843. {
  96844. unsigned i;
  96845. for(i = 0; i < data_len; i++)
  96846. out[i] = in[i] * window[i];
  96847. }
  96848. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  96849. {
  96850. /* a readable, but slower, version */
  96851. #if 0
  96852. FLAC__real d;
  96853. unsigned i;
  96854. FLAC__ASSERT(lag > 0);
  96855. FLAC__ASSERT(lag <= data_len);
  96856. /*
  96857. * Technically we should subtract the mean first like so:
  96858. * for(i = 0; i < data_len; i++)
  96859. * data[i] -= mean;
  96860. * but it appears not to make enough of a difference to matter, and
  96861. * most signals are already closely centered around zero
  96862. */
  96863. while(lag--) {
  96864. for(i = lag, d = 0.0; i < data_len; i++)
  96865. d += data[i] * data[i - lag];
  96866. autoc[lag] = d;
  96867. }
  96868. #endif
  96869. /*
  96870. * this version tends to run faster because of better data locality
  96871. * ('data_len' is usually much larger than 'lag')
  96872. */
  96873. FLAC__real d;
  96874. unsigned sample, coeff;
  96875. const unsigned limit = data_len - lag;
  96876. FLAC__ASSERT(lag > 0);
  96877. FLAC__ASSERT(lag <= data_len);
  96878. for(coeff = 0; coeff < lag; coeff++)
  96879. autoc[coeff] = 0.0;
  96880. for(sample = 0; sample <= limit; sample++) {
  96881. d = data[sample];
  96882. for(coeff = 0; coeff < lag; coeff++)
  96883. autoc[coeff] += d * data[sample+coeff];
  96884. }
  96885. for(; sample < data_len; sample++) {
  96886. d = data[sample];
  96887. for(coeff = 0; coeff < data_len - sample; coeff++)
  96888. autoc[coeff] += d * data[sample+coeff];
  96889. }
  96890. }
  96891. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  96892. {
  96893. unsigned i, j;
  96894. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  96895. FLAC__ASSERT(0 != max_order);
  96896. FLAC__ASSERT(0 < *max_order);
  96897. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  96898. FLAC__ASSERT(autoc[0] != 0.0);
  96899. err = autoc[0];
  96900. for(i = 0; i < *max_order; i++) {
  96901. /* Sum up this iteration's reflection coefficient. */
  96902. r = -autoc[i+1];
  96903. for(j = 0; j < i; j++)
  96904. r -= lpc[j] * autoc[i-j];
  96905. ref[i] = (r/=err);
  96906. /* Update LPC coefficients and total error. */
  96907. lpc[i]=r;
  96908. for(j = 0; j < (i>>1); j++) {
  96909. FLAC__double tmp = lpc[j];
  96910. lpc[j] += r * lpc[i-1-j];
  96911. lpc[i-1-j] += r * tmp;
  96912. }
  96913. if(i & 1)
  96914. lpc[j] += lpc[j] * r;
  96915. err *= (1.0 - r * r);
  96916. /* save this order */
  96917. for(j = 0; j <= i; j++)
  96918. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  96919. error[i] = err;
  96920. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  96921. if(err == 0.0) {
  96922. *max_order = i+1;
  96923. return;
  96924. }
  96925. }
  96926. }
  96927. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  96928. {
  96929. unsigned i;
  96930. FLAC__double cmax;
  96931. FLAC__int32 qmax, qmin;
  96932. FLAC__ASSERT(precision > 0);
  96933. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  96934. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  96935. precision--;
  96936. qmax = 1 << precision;
  96937. qmin = -qmax;
  96938. qmax--;
  96939. /* calc cmax = max( |lp_coeff[i]| ) */
  96940. cmax = 0.0;
  96941. for(i = 0; i < order; i++) {
  96942. const FLAC__double d = fabs(lp_coeff[i]);
  96943. if(d > cmax)
  96944. cmax = d;
  96945. }
  96946. if(cmax <= 0.0) {
  96947. /* => coefficients are all 0, which means our constant-detect didn't work */
  96948. return 2;
  96949. }
  96950. else {
  96951. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  96952. const int min_shiftlimit = -max_shiftlimit - 1;
  96953. int log2cmax;
  96954. (void)frexp(cmax, &log2cmax);
  96955. log2cmax--;
  96956. *shift = (int)precision - log2cmax - 1;
  96957. if(*shift > max_shiftlimit)
  96958. *shift = max_shiftlimit;
  96959. else if(*shift < min_shiftlimit)
  96960. return 1;
  96961. }
  96962. if(*shift >= 0) {
  96963. FLAC__double error = 0.0;
  96964. FLAC__int32 q;
  96965. for(i = 0; i < order; i++) {
  96966. error += lp_coeff[i] * (1 << *shift);
  96967. #if 1 /* unfortunately lround() is C99 */
  96968. if(error >= 0.0)
  96969. q = (FLAC__int32)(error + 0.5);
  96970. else
  96971. q = (FLAC__int32)(error - 0.5);
  96972. #else
  96973. q = lround(error);
  96974. #endif
  96975. #ifdef FLAC__OVERFLOW_DETECT
  96976. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  96977. 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]);
  96978. else if(q < qmin)
  96979. 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]);
  96980. #endif
  96981. if(q > qmax)
  96982. q = qmax;
  96983. else if(q < qmin)
  96984. q = qmin;
  96985. error -= q;
  96986. qlp_coeff[i] = q;
  96987. }
  96988. }
  96989. /* negative shift is very rare but due to design flaw, negative shift is
  96990. * a NOP in the decoder, so it must be handled specially by scaling down
  96991. * coeffs
  96992. */
  96993. else {
  96994. const int nshift = -(*shift);
  96995. FLAC__double error = 0.0;
  96996. FLAC__int32 q;
  96997. #ifdef DEBUG
  96998. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  96999. #endif
  97000. for(i = 0; i < order; i++) {
  97001. error += lp_coeff[i] / (1 << nshift);
  97002. #if 1 /* unfortunately lround() is C99 */
  97003. if(error >= 0.0)
  97004. q = (FLAC__int32)(error + 0.5);
  97005. else
  97006. q = (FLAC__int32)(error - 0.5);
  97007. #else
  97008. q = lround(error);
  97009. #endif
  97010. #ifdef FLAC__OVERFLOW_DETECT
  97011. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97012. 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]);
  97013. else if(q < qmin)
  97014. 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]);
  97015. #endif
  97016. if(q > qmax)
  97017. q = qmax;
  97018. else if(q < qmin)
  97019. q = qmin;
  97020. error -= q;
  97021. qlp_coeff[i] = q;
  97022. }
  97023. *shift = 0;
  97024. }
  97025. return 0;
  97026. }
  97027. 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[])
  97028. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97029. {
  97030. FLAC__int64 sumo;
  97031. unsigned i, j;
  97032. FLAC__int32 sum;
  97033. const FLAC__int32 *history;
  97034. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97035. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97036. for(i=0;i<order;i++)
  97037. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97038. fprintf(stderr,"\n");
  97039. #endif
  97040. FLAC__ASSERT(order > 0);
  97041. for(i = 0; i < data_len; i++) {
  97042. sumo = 0;
  97043. sum = 0;
  97044. history = data;
  97045. for(j = 0; j < order; j++) {
  97046. sum += qlp_coeff[j] * (*(--history));
  97047. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97048. #if defined _MSC_VER
  97049. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97050. 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);
  97051. #else
  97052. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97053. 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);
  97054. #endif
  97055. }
  97056. *(residual++) = *(data++) - (sum >> lp_quantization);
  97057. }
  97058. /* Here's a slower but clearer version:
  97059. for(i = 0; i < data_len; i++) {
  97060. sum = 0;
  97061. for(j = 0; j < order; j++)
  97062. sum += qlp_coeff[j] * data[i-j-1];
  97063. residual[i] = data[i] - (sum >> lp_quantization);
  97064. }
  97065. */
  97066. }
  97067. #else /* fully unrolled version for normal use */
  97068. {
  97069. int i;
  97070. FLAC__int32 sum;
  97071. FLAC__ASSERT(order > 0);
  97072. FLAC__ASSERT(order <= 32);
  97073. /*
  97074. * We do unique versions up to 12th order since that's the subset limit.
  97075. * Also they are roughly ordered to match frequency of occurrence to
  97076. * minimize branching.
  97077. */
  97078. if(order <= 12) {
  97079. if(order > 8) {
  97080. if(order > 10) {
  97081. if(order == 12) {
  97082. for(i = 0; i < (int)data_len; i++) {
  97083. sum = 0;
  97084. sum += qlp_coeff[11] * data[i-12];
  97085. sum += qlp_coeff[10] * data[i-11];
  97086. sum += qlp_coeff[9] * data[i-10];
  97087. sum += qlp_coeff[8] * data[i-9];
  97088. sum += qlp_coeff[7] * data[i-8];
  97089. sum += qlp_coeff[6] * data[i-7];
  97090. sum += qlp_coeff[5] * data[i-6];
  97091. sum += qlp_coeff[4] * data[i-5];
  97092. sum += qlp_coeff[3] * data[i-4];
  97093. sum += qlp_coeff[2] * data[i-3];
  97094. sum += qlp_coeff[1] * data[i-2];
  97095. sum += qlp_coeff[0] * data[i-1];
  97096. residual[i] = data[i] - (sum >> lp_quantization);
  97097. }
  97098. }
  97099. else { /* order == 11 */
  97100. for(i = 0; i < (int)data_len; i++) {
  97101. sum = 0;
  97102. sum += qlp_coeff[10] * data[i-11];
  97103. sum += qlp_coeff[9] * data[i-10];
  97104. sum += qlp_coeff[8] * data[i-9];
  97105. sum += qlp_coeff[7] * data[i-8];
  97106. sum += qlp_coeff[6] * data[i-7];
  97107. sum += qlp_coeff[5] * data[i-6];
  97108. sum += qlp_coeff[4] * data[i-5];
  97109. sum += qlp_coeff[3] * data[i-4];
  97110. sum += qlp_coeff[2] * data[i-3];
  97111. sum += qlp_coeff[1] * data[i-2];
  97112. sum += qlp_coeff[0] * data[i-1];
  97113. residual[i] = data[i] - (sum >> lp_quantization);
  97114. }
  97115. }
  97116. }
  97117. else {
  97118. if(order == 10) {
  97119. for(i = 0; i < (int)data_len; i++) {
  97120. sum = 0;
  97121. sum += qlp_coeff[9] * data[i-10];
  97122. sum += qlp_coeff[8] * data[i-9];
  97123. sum += qlp_coeff[7] * data[i-8];
  97124. sum += qlp_coeff[6] * data[i-7];
  97125. sum += qlp_coeff[5] * data[i-6];
  97126. sum += qlp_coeff[4] * data[i-5];
  97127. sum += qlp_coeff[3] * data[i-4];
  97128. sum += qlp_coeff[2] * data[i-3];
  97129. sum += qlp_coeff[1] * data[i-2];
  97130. sum += qlp_coeff[0] * data[i-1];
  97131. residual[i] = data[i] - (sum >> lp_quantization);
  97132. }
  97133. }
  97134. else { /* order == 9 */
  97135. for(i = 0; i < (int)data_len; i++) {
  97136. sum = 0;
  97137. sum += qlp_coeff[8] * data[i-9];
  97138. sum += qlp_coeff[7] * data[i-8];
  97139. sum += qlp_coeff[6] * data[i-7];
  97140. sum += qlp_coeff[5] * data[i-6];
  97141. sum += qlp_coeff[4] * data[i-5];
  97142. sum += qlp_coeff[3] * data[i-4];
  97143. sum += qlp_coeff[2] * data[i-3];
  97144. sum += qlp_coeff[1] * data[i-2];
  97145. sum += qlp_coeff[0] * data[i-1];
  97146. residual[i] = data[i] - (sum >> lp_quantization);
  97147. }
  97148. }
  97149. }
  97150. }
  97151. else if(order > 4) {
  97152. if(order > 6) {
  97153. if(order == 8) {
  97154. for(i = 0; i < (int)data_len; i++) {
  97155. sum = 0;
  97156. sum += qlp_coeff[7] * data[i-8];
  97157. sum += qlp_coeff[6] * data[i-7];
  97158. sum += qlp_coeff[5] * data[i-6];
  97159. sum += qlp_coeff[4] * data[i-5];
  97160. sum += qlp_coeff[3] * data[i-4];
  97161. sum += qlp_coeff[2] * data[i-3];
  97162. sum += qlp_coeff[1] * data[i-2];
  97163. sum += qlp_coeff[0] * data[i-1];
  97164. residual[i] = data[i] - (sum >> lp_quantization);
  97165. }
  97166. }
  97167. else { /* order == 7 */
  97168. for(i = 0; i < (int)data_len; i++) {
  97169. sum = 0;
  97170. sum += qlp_coeff[6] * data[i-7];
  97171. sum += qlp_coeff[5] * data[i-6];
  97172. sum += qlp_coeff[4] * data[i-5];
  97173. sum += qlp_coeff[3] * data[i-4];
  97174. sum += qlp_coeff[2] * data[i-3];
  97175. sum += qlp_coeff[1] * data[i-2];
  97176. sum += qlp_coeff[0] * data[i-1];
  97177. residual[i] = data[i] - (sum >> lp_quantization);
  97178. }
  97179. }
  97180. }
  97181. else {
  97182. if(order == 6) {
  97183. for(i = 0; i < (int)data_len; i++) {
  97184. sum = 0;
  97185. sum += qlp_coeff[5] * data[i-6];
  97186. sum += qlp_coeff[4] * data[i-5];
  97187. sum += qlp_coeff[3] * data[i-4];
  97188. sum += qlp_coeff[2] * data[i-3];
  97189. sum += qlp_coeff[1] * data[i-2];
  97190. sum += qlp_coeff[0] * data[i-1];
  97191. residual[i] = data[i] - (sum >> lp_quantization);
  97192. }
  97193. }
  97194. else { /* order == 5 */
  97195. for(i = 0; i < (int)data_len; i++) {
  97196. sum = 0;
  97197. sum += qlp_coeff[4] * data[i-5];
  97198. sum += qlp_coeff[3] * data[i-4];
  97199. sum += qlp_coeff[2] * data[i-3];
  97200. sum += qlp_coeff[1] * data[i-2];
  97201. sum += qlp_coeff[0] * data[i-1];
  97202. residual[i] = data[i] - (sum >> lp_quantization);
  97203. }
  97204. }
  97205. }
  97206. }
  97207. else {
  97208. if(order > 2) {
  97209. if(order == 4) {
  97210. for(i = 0; i < (int)data_len; i++) {
  97211. sum = 0;
  97212. sum += qlp_coeff[3] * data[i-4];
  97213. sum += qlp_coeff[2] * data[i-3];
  97214. sum += qlp_coeff[1] * data[i-2];
  97215. sum += qlp_coeff[0] * data[i-1];
  97216. residual[i] = data[i] - (sum >> lp_quantization);
  97217. }
  97218. }
  97219. else { /* order == 3 */
  97220. for(i = 0; i < (int)data_len; i++) {
  97221. sum = 0;
  97222. sum += qlp_coeff[2] * data[i-3];
  97223. sum += qlp_coeff[1] * data[i-2];
  97224. sum += qlp_coeff[0] * data[i-1];
  97225. residual[i] = data[i] - (sum >> lp_quantization);
  97226. }
  97227. }
  97228. }
  97229. else {
  97230. if(order == 2) {
  97231. for(i = 0; i < (int)data_len; i++) {
  97232. sum = 0;
  97233. sum += qlp_coeff[1] * data[i-2];
  97234. sum += qlp_coeff[0] * data[i-1];
  97235. residual[i] = data[i] - (sum >> lp_quantization);
  97236. }
  97237. }
  97238. else { /* order == 1 */
  97239. for(i = 0; i < (int)data_len; i++)
  97240. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97241. }
  97242. }
  97243. }
  97244. }
  97245. else { /* order > 12 */
  97246. for(i = 0; i < (int)data_len; i++) {
  97247. sum = 0;
  97248. switch(order) {
  97249. case 32: sum += qlp_coeff[31] * data[i-32];
  97250. case 31: sum += qlp_coeff[30] * data[i-31];
  97251. case 30: sum += qlp_coeff[29] * data[i-30];
  97252. case 29: sum += qlp_coeff[28] * data[i-29];
  97253. case 28: sum += qlp_coeff[27] * data[i-28];
  97254. case 27: sum += qlp_coeff[26] * data[i-27];
  97255. case 26: sum += qlp_coeff[25] * data[i-26];
  97256. case 25: sum += qlp_coeff[24] * data[i-25];
  97257. case 24: sum += qlp_coeff[23] * data[i-24];
  97258. case 23: sum += qlp_coeff[22] * data[i-23];
  97259. case 22: sum += qlp_coeff[21] * data[i-22];
  97260. case 21: sum += qlp_coeff[20] * data[i-21];
  97261. case 20: sum += qlp_coeff[19] * data[i-20];
  97262. case 19: sum += qlp_coeff[18] * data[i-19];
  97263. case 18: sum += qlp_coeff[17] * data[i-18];
  97264. case 17: sum += qlp_coeff[16] * data[i-17];
  97265. case 16: sum += qlp_coeff[15] * data[i-16];
  97266. case 15: sum += qlp_coeff[14] * data[i-15];
  97267. case 14: sum += qlp_coeff[13] * data[i-14];
  97268. case 13: sum += qlp_coeff[12] * data[i-13];
  97269. sum += qlp_coeff[11] * data[i-12];
  97270. sum += qlp_coeff[10] * data[i-11];
  97271. sum += qlp_coeff[ 9] * data[i-10];
  97272. sum += qlp_coeff[ 8] * data[i- 9];
  97273. sum += qlp_coeff[ 7] * data[i- 8];
  97274. sum += qlp_coeff[ 6] * data[i- 7];
  97275. sum += qlp_coeff[ 5] * data[i- 6];
  97276. sum += qlp_coeff[ 4] * data[i- 5];
  97277. sum += qlp_coeff[ 3] * data[i- 4];
  97278. sum += qlp_coeff[ 2] * data[i- 3];
  97279. sum += qlp_coeff[ 1] * data[i- 2];
  97280. sum += qlp_coeff[ 0] * data[i- 1];
  97281. }
  97282. residual[i] = data[i] - (sum >> lp_quantization);
  97283. }
  97284. }
  97285. }
  97286. #endif
  97287. 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[])
  97288. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97289. {
  97290. unsigned i, j;
  97291. FLAC__int64 sum;
  97292. const FLAC__int32 *history;
  97293. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97294. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97295. for(i=0;i<order;i++)
  97296. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97297. fprintf(stderr,"\n");
  97298. #endif
  97299. FLAC__ASSERT(order > 0);
  97300. for(i = 0; i < data_len; i++) {
  97301. sum = 0;
  97302. history = data;
  97303. for(j = 0; j < order; j++)
  97304. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97305. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97306. #if defined _MSC_VER
  97307. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97308. #else
  97309. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97310. #endif
  97311. break;
  97312. }
  97313. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97314. #if defined _MSC_VER
  97315. 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));
  97316. #else
  97317. 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)));
  97318. #endif
  97319. break;
  97320. }
  97321. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97322. }
  97323. }
  97324. #else /* fully unrolled version for normal use */
  97325. {
  97326. int i;
  97327. FLAC__int64 sum;
  97328. FLAC__ASSERT(order > 0);
  97329. FLAC__ASSERT(order <= 32);
  97330. /*
  97331. * We do unique versions up to 12th order since that's the subset limit.
  97332. * Also they are roughly ordered to match frequency of occurrence to
  97333. * minimize branching.
  97334. */
  97335. if(order <= 12) {
  97336. if(order > 8) {
  97337. if(order > 10) {
  97338. if(order == 12) {
  97339. for(i = 0; i < (int)data_len; i++) {
  97340. sum = 0;
  97341. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97342. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97343. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97344. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97345. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97346. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97347. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97348. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97349. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97350. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97351. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97352. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97353. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97354. }
  97355. }
  97356. else { /* order == 11 */
  97357. for(i = 0; i < (int)data_len; i++) {
  97358. sum = 0;
  97359. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97360. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97361. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97362. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97363. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97364. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97365. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97366. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97367. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97368. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97369. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97370. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97371. }
  97372. }
  97373. }
  97374. else {
  97375. if(order == 10) {
  97376. for(i = 0; i < (int)data_len; i++) {
  97377. sum = 0;
  97378. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97379. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97380. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97381. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97382. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97383. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97384. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97385. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97386. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97387. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97388. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97389. }
  97390. }
  97391. else { /* order == 9 */
  97392. for(i = 0; i < (int)data_len; i++) {
  97393. sum = 0;
  97394. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97395. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97396. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97397. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97398. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97399. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97400. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97401. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97402. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97403. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97404. }
  97405. }
  97406. }
  97407. }
  97408. else if(order > 4) {
  97409. if(order > 6) {
  97410. if(order == 8) {
  97411. for(i = 0; i < (int)data_len; i++) {
  97412. sum = 0;
  97413. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97414. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97415. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97416. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97417. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97418. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97419. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97420. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97421. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97422. }
  97423. }
  97424. else { /* order == 7 */
  97425. for(i = 0; i < (int)data_len; i++) {
  97426. sum = 0;
  97427. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97428. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97429. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97430. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97431. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97432. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97433. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97434. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97435. }
  97436. }
  97437. }
  97438. else {
  97439. if(order == 6) {
  97440. for(i = 0; i < (int)data_len; i++) {
  97441. sum = 0;
  97442. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97443. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97444. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97445. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97446. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97447. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97448. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97449. }
  97450. }
  97451. else { /* order == 5 */
  97452. for(i = 0; i < (int)data_len; i++) {
  97453. sum = 0;
  97454. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97455. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97456. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97457. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97458. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97459. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97460. }
  97461. }
  97462. }
  97463. }
  97464. else {
  97465. if(order > 2) {
  97466. if(order == 4) {
  97467. for(i = 0; i < (int)data_len; i++) {
  97468. sum = 0;
  97469. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97470. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97471. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97472. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97473. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97474. }
  97475. }
  97476. else { /* order == 3 */
  97477. for(i = 0; i < (int)data_len; i++) {
  97478. sum = 0;
  97479. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97480. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97481. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97482. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97483. }
  97484. }
  97485. }
  97486. else {
  97487. if(order == 2) {
  97488. for(i = 0; i < (int)data_len; i++) {
  97489. sum = 0;
  97490. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97491. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97492. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97493. }
  97494. }
  97495. else { /* order == 1 */
  97496. for(i = 0; i < (int)data_len; i++)
  97497. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97498. }
  97499. }
  97500. }
  97501. }
  97502. else { /* order > 12 */
  97503. for(i = 0; i < (int)data_len; i++) {
  97504. sum = 0;
  97505. switch(order) {
  97506. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97507. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97508. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97509. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97510. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97511. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97512. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97513. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97514. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97515. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97516. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97517. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97518. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97519. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97520. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97521. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97522. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97523. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97524. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97525. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97526. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97527. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97528. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97529. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97530. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97531. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97532. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97533. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97534. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97535. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97536. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97537. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97538. }
  97539. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97540. }
  97541. }
  97542. }
  97543. #endif
  97544. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97545. 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[])
  97546. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97547. {
  97548. FLAC__int64 sumo;
  97549. unsigned i, j;
  97550. FLAC__int32 sum;
  97551. const FLAC__int32 *r = residual, *history;
  97552. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97553. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97554. for(i=0;i<order;i++)
  97555. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97556. fprintf(stderr,"\n");
  97557. #endif
  97558. FLAC__ASSERT(order > 0);
  97559. for(i = 0; i < data_len; i++) {
  97560. sumo = 0;
  97561. sum = 0;
  97562. history = data;
  97563. for(j = 0; j < order; j++) {
  97564. sum += qlp_coeff[j] * (*(--history));
  97565. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97566. #if defined _MSC_VER
  97567. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97568. 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);
  97569. #else
  97570. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97571. 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);
  97572. #endif
  97573. }
  97574. *(data++) = *(r++) + (sum >> lp_quantization);
  97575. }
  97576. /* Here's a slower but clearer version:
  97577. for(i = 0; i < data_len; i++) {
  97578. sum = 0;
  97579. for(j = 0; j < order; j++)
  97580. sum += qlp_coeff[j] * data[i-j-1];
  97581. data[i] = residual[i] + (sum >> lp_quantization);
  97582. }
  97583. */
  97584. }
  97585. #else /* fully unrolled version for normal use */
  97586. {
  97587. int i;
  97588. FLAC__int32 sum;
  97589. FLAC__ASSERT(order > 0);
  97590. FLAC__ASSERT(order <= 32);
  97591. /*
  97592. * We do unique versions up to 12th order since that's the subset limit.
  97593. * Also they are roughly ordered to match frequency of occurrence to
  97594. * minimize branching.
  97595. */
  97596. if(order <= 12) {
  97597. if(order > 8) {
  97598. if(order > 10) {
  97599. if(order == 12) {
  97600. for(i = 0; i < (int)data_len; i++) {
  97601. sum = 0;
  97602. sum += qlp_coeff[11] * data[i-12];
  97603. sum += qlp_coeff[10] * data[i-11];
  97604. sum += qlp_coeff[9] * data[i-10];
  97605. sum += qlp_coeff[8] * data[i-9];
  97606. sum += qlp_coeff[7] * data[i-8];
  97607. sum += qlp_coeff[6] * data[i-7];
  97608. sum += qlp_coeff[5] * data[i-6];
  97609. sum += qlp_coeff[4] * data[i-5];
  97610. sum += qlp_coeff[3] * data[i-4];
  97611. sum += qlp_coeff[2] * data[i-3];
  97612. sum += qlp_coeff[1] * data[i-2];
  97613. sum += qlp_coeff[0] * data[i-1];
  97614. data[i] = residual[i] + (sum >> lp_quantization);
  97615. }
  97616. }
  97617. else { /* order == 11 */
  97618. for(i = 0; i < (int)data_len; i++) {
  97619. sum = 0;
  97620. sum += qlp_coeff[10] * data[i-11];
  97621. sum += qlp_coeff[9] * data[i-10];
  97622. sum += qlp_coeff[8] * data[i-9];
  97623. sum += qlp_coeff[7] * data[i-8];
  97624. sum += qlp_coeff[6] * data[i-7];
  97625. sum += qlp_coeff[5] * data[i-6];
  97626. sum += qlp_coeff[4] * data[i-5];
  97627. sum += qlp_coeff[3] * data[i-4];
  97628. sum += qlp_coeff[2] * data[i-3];
  97629. sum += qlp_coeff[1] * data[i-2];
  97630. sum += qlp_coeff[0] * data[i-1];
  97631. data[i] = residual[i] + (sum >> lp_quantization);
  97632. }
  97633. }
  97634. }
  97635. else {
  97636. if(order == 10) {
  97637. for(i = 0; i < (int)data_len; i++) {
  97638. sum = 0;
  97639. sum += qlp_coeff[9] * data[i-10];
  97640. sum += qlp_coeff[8] * data[i-9];
  97641. sum += qlp_coeff[7] * data[i-8];
  97642. sum += qlp_coeff[6] * data[i-7];
  97643. sum += qlp_coeff[5] * data[i-6];
  97644. sum += qlp_coeff[4] * data[i-5];
  97645. sum += qlp_coeff[3] * data[i-4];
  97646. sum += qlp_coeff[2] * data[i-3];
  97647. sum += qlp_coeff[1] * data[i-2];
  97648. sum += qlp_coeff[0] * data[i-1];
  97649. data[i] = residual[i] + (sum >> lp_quantization);
  97650. }
  97651. }
  97652. else { /* order == 9 */
  97653. for(i = 0; i < (int)data_len; i++) {
  97654. sum = 0;
  97655. sum += qlp_coeff[8] * data[i-9];
  97656. sum += qlp_coeff[7] * data[i-8];
  97657. sum += qlp_coeff[6] * data[i-7];
  97658. sum += qlp_coeff[5] * data[i-6];
  97659. sum += qlp_coeff[4] * data[i-5];
  97660. sum += qlp_coeff[3] * data[i-4];
  97661. sum += qlp_coeff[2] * data[i-3];
  97662. sum += qlp_coeff[1] * data[i-2];
  97663. sum += qlp_coeff[0] * data[i-1];
  97664. data[i] = residual[i] + (sum >> lp_quantization);
  97665. }
  97666. }
  97667. }
  97668. }
  97669. else if(order > 4) {
  97670. if(order > 6) {
  97671. if(order == 8) {
  97672. for(i = 0; i < (int)data_len; i++) {
  97673. sum = 0;
  97674. sum += qlp_coeff[7] * data[i-8];
  97675. sum += qlp_coeff[6] * data[i-7];
  97676. sum += qlp_coeff[5] * data[i-6];
  97677. sum += qlp_coeff[4] * data[i-5];
  97678. sum += qlp_coeff[3] * data[i-4];
  97679. sum += qlp_coeff[2] * data[i-3];
  97680. sum += qlp_coeff[1] * data[i-2];
  97681. sum += qlp_coeff[0] * data[i-1];
  97682. data[i] = residual[i] + (sum >> lp_quantization);
  97683. }
  97684. }
  97685. else { /* order == 7 */
  97686. for(i = 0; i < (int)data_len; i++) {
  97687. sum = 0;
  97688. sum += qlp_coeff[6] * data[i-7];
  97689. sum += qlp_coeff[5] * data[i-6];
  97690. sum += qlp_coeff[4] * data[i-5];
  97691. sum += qlp_coeff[3] * data[i-4];
  97692. sum += qlp_coeff[2] * data[i-3];
  97693. sum += qlp_coeff[1] * data[i-2];
  97694. sum += qlp_coeff[0] * data[i-1];
  97695. data[i] = residual[i] + (sum >> lp_quantization);
  97696. }
  97697. }
  97698. }
  97699. else {
  97700. if(order == 6) {
  97701. for(i = 0; i < (int)data_len; i++) {
  97702. sum = 0;
  97703. sum += qlp_coeff[5] * data[i-6];
  97704. sum += qlp_coeff[4] * data[i-5];
  97705. sum += qlp_coeff[3] * data[i-4];
  97706. sum += qlp_coeff[2] * data[i-3];
  97707. sum += qlp_coeff[1] * data[i-2];
  97708. sum += qlp_coeff[0] * data[i-1];
  97709. data[i] = residual[i] + (sum >> lp_quantization);
  97710. }
  97711. }
  97712. else { /* order == 5 */
  97713. for(i = 0; i < (int)data_len; i++) {
  97714. sum = 0;
  97715. sum += qlp_coeff[4] * data[i-5];
  97716. sum += qlp_coeff[3] * data[i-4];
  97717. sum += qlp_coeff[2] * data[i-3];
  97718. sum += qlp_coeff[1] * data[i-2];
  97719. sum += qlp_coeff[0] * data[i-1];
  97720. data[i] = residual[i] + (sum >> lp_quantization);
  97721. }
  97722. }
  97723. }
  97724. }
  97725. else {
  97726. if(order > 2) {
  97727. if(order == 4) {
  97728. for(i = 0; i < (int)data_len; i++) {
  97729. sum = 0;
  97730. sum += qlp_coeff[3] * data[i-4];
  97731. sum += qlp_coeff[2] * data[i-3];
  97732. sum += qlp_coeff[1] * data[i-2];
  97733. sum += qlp_coeff[0] * data[i-1];
  97734. data[i] = residual[i] + (sum >> lp_quantization);
  97735. }
  97736. }
  97737. else { /* order == 3 */
  97738. for(i = 0; i < (int)data_len; i++) {
  97739. sum = 0;
  97740. sum += qlp_coeff[2] * data[i-3];
  97741. sum += qlp_coeff[1] * data[i-2];
  97742. sum += qlp_coeff[0] * data[i-1];
  97743. data[i] = residual[i] + (sum >> lp_quantization);
  97744. }
  97745. }
  97746. }
  97747. else {
  97748. if(order == 2) {
  97749. for(i = 0; i < (int)data_len; i++) {
  97750. sum = 0;
  97751. sum += qlp_coeff[1] * data[i-2];
  97752. sum += qlp_coeff[0] * data[i-1];
  97753. data[i] = residual[i] + (sum >> lp_quantization);
  97754. }
  97755. }
  97756. else { /* order == 1 */
  97757. for(i = 0; i < (int)data_len; i++)
  97758. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97759. }
  97760. }
  97761. }
  97762. }
  97763. else { /* order > 12 */
  97764. for(i = 0; i < (int)data_len; i++) {
  97765. sum = 0;
  97766. switch(order) {
  97767. case 32: sum += qlp_coeff[31] * data[i-32];
  97768. case 31: sum += qlp_coeff[30] * data[i-31];
  97769. case 30: sum += qlp_coeff[29] * data[i-30];
  97770. case 29: sum += qlp_coeff[28] * data[i-29];
  97771. case 28: sum += qlp_coeff[27] * data[i-28];
  97772. case 27: sum += qlp_coeff[26] * data[i-27];
  97773. case 26: sum += qlp_coeff[25] * data[i-26];
  97774. case 25: sum += qlp_coeff[24] * data[i-25];
  97775. case 24: sum += qlp_coeff[23] * data[i-24];
  97776. case 23: sum += qlp_coeff[22] * data[i-23];
  97777. case 22: sum += qlp_coeff[21] * data[i-22];
  97778. case 21: sum += qlp_coeff[20] * data[i-21];
  97779. case 20: sum += qlp_coeff[19] * data[i-20];
  97780. case 19: sum += qlp_coeff[18] * data[i-19];
  97781. case 18: sum += qlp_coeff[17] * data[i-18];
  97782. case 17: sum += qlp_coeff[16] * data[i-17];
  97783. case 16: sum += qlp_coeff[15] * data[i-16];
  97784. case 15: sum += qlp_coeff[14] * data[i-15];
  97785. case 14: sum += qlp_coeff[13] * data[i-14];
  97786. case 13: sum += qlp_coeff[12] * data[i-13];
  97787. sum += qlp_coeff[11] * data[i-12];
  97788. sum += qlp_coeff[10] * data[i-11];
  97789. sum += qlp_coeff[ 9] * data[i-10];
  97790. sum += qlp_coeff[ 8] * data[i- 9];
  97791. sum += qlp_coeff[ 7] * data[i- 8];
  97792. sum += qlp_coeff[ 6] * data[i- 7];
  97793. sum += qlp_coeff[ 5] * data[i- 6];
  97794. sum += qlp_coeff[ 4] * data[i- 5];
  97795. sum += qlp_coeff[ 3] * data[i- 4];
  97796. sum += qlp_coeff[ 2] * data[i- 3];
  97797. sum += qlp_coeff[ 1] * data[i- 2];
  97798. sum += qlp_coeff[ 0] * data[i- 1];
  97799. }
  97800. data[i] = residual[i] + (sum >> lp_quantization);
  97801. }
  97802. }
  97803. }
  97804. #endif
  97805. 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[])
  97806. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97807. {
  97808. unsigned i, j;
  97809. FLAC__int64 sum;
  97810. const FLAC__int32 *r = residual, *history;
  97811. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97812. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97813. for(i=0;i<order;i++)
  97814. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97815. fprintf(stderr,"\n");
  97816. #endif
  97817. FLAC__ASSERT(order > 0);
  97818. for(i = 0; i < data_len; i++) {
  97819. sum = 0;
  97820. history = data;
  97821. for(j = 0; j < order; j++)
  97822. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97823. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97824. #ifdef _MSC_VER
  97825. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97826. #else
  97827. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97828. #endif
  97829. break;
  97830. }
  97831. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  97832. #ifdef _MSC_VER
  97833. 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));
  97834. #else
  97835. 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)));
  97836. #endif
  97837. break;
  97838. }
  97839. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  97840. }
  97841. }
  97842. #else /* fully unrolled version for normal use */
  97843. {
  97844. int i;
  97845. FLAC__int64 sum;
  97846. FLAC__ASSERT(order > 0);
  97847. FLAC__ASSERT(order <= 32);
  97848. /*
  97849. * We do unique versions up to 12th order since that's the subset limit.
  97850. * Also they are roughly ordered to match frequency of occurrence to
  97851. * minimize branching.
  97852. */
  97853. if(order <= 12) {
  97854. if(order > 8) {
  97855. if(order > 10) {
  97856. if(order == 12) {
  97857. for(i = 0; i < (int)data_len; i++) {
  97858. sum = 0;
  97859. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97860. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97861. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97862. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97863. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97864. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97865. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97866. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97867. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97868. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97869. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97870. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97871. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97872. }
  97873. }
  97874. else { /* order == 11 */
  97875. for(i = 0; i < (int)data_len; i++) {
  97876. sum = 0;
  97877. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97878. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97879. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97880. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97881. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97882. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97883. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97884. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97885. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97886. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97887. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97888. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97889. }
  97890. }
  97891. }
  97892. else {
  97893. if(order == 10) {
  97894. for(i = 0; i < (int)data_len; i++) {
  97895. sum = 0;
  97896. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97897. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97898. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97899. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97900. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97901. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97902. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97903. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97904. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97905. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97906. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97907. }
  97908. }
  97909. else { /* order == 9 */
  97910. for(i = 0; i < (int)data_len; i++) {
  97911. sum = 0;
  97912. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97913. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97914. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97915. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97916. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97917. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97918. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97919. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97920. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97921. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97922. }
  97923. }
  97924. }
  97925. }
  97926. else if(order > 4) {
  97927. if(order > 6) {
  97928. if(order == 8) {
  97929. for(i = 0; i < (int)data_len; i++) {
  97930. sum = 0;
  97931. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97932. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97933. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97934. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97935. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97936. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97937. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97938. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97939. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97940. }
  97941. }
  97942. else { /* order == 7 */
  97943. for(i = 0; i < (int)data_len; i++) {
  97944. sum = 0;
  97945. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97946. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97947. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97948. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97949. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97950. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97951. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97952. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97953. }
  97954. }
  97955. }
  97956. else {
  97957. if(order == 6) {
  97958. for(i = 0; i < (int)data_len; i++) {
  97959. sum = 0;
  97960. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97961. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97962. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97963. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97964. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97965. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97966. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97967. }
  97968. }
  97969. else { /* order == 5 */
  97970. for(i = 0; i < (int)data_len; i++) {
  97971. sum = 0;
  97972. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97973. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97974. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97975. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97976. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97977. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97978. }
  97979. }
  97980. }
  97981. }
  97982. else {
  97983. if(order > 2) {
  97984. if(order == 4) {
  97985. for(i = 0; i < (int)data_len; i++) {
  97986. sum = 0;
  97987. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97988. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97989. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97990. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97991. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  97992. }
  97993. }
  97994. else { /* order == 3 */
  97995. for(i = 0; i < (int)data_len; i++) {
  97996. sum = 0;
  97997. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97998. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97999. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98000. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98001. }
  98002. }
  98003. }
  98004. else {
  98005. if(order == 2) {
  98006. for(i = 0; i < (int)data_len; i++) {
  98007. sum = 0;
  98008. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98009. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98010. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98011. }
  98012. }
  98013. else { /* order == 1 */
  98014. for(i = 0; i < (int)data_len; i++)
  98015. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98016. }
  98017. }
  98018. }
  98019. }
  98020. else { /* order > 12 */
  98021. for(i = 0; i < (int)data_len; i++) {
  98022. sum = 0;
  98023. switch(order) {
  98024. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98025. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98026. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98027. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98028. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98029. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98030. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98031. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98032. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98033. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98034. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98035. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98036. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98037. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98038. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98039. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98040. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98041. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98042. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98043. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98044. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98045. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98046. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98047. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98048. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98049. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98050. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98051. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98052. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98053. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98054. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98055. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98056. }
  98057. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98058. }
  98059. }
  98060. }
  98061. #endif
  98062. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98063. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98064. {
  98065. FLAC__double error_scale;
  98066. FLAC__ASSERT(total_samples > 0);
  98067. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98068. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98069. }
  98070. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98071. {
  98072. if(lpc_error > 0.0) {
  98073. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98074. if(bps >= 0.0)
  98075. return bps;
  98076. else
  98077. return 0.0;
  98078. }
  98079. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98080. return 1e32;
  98081. }
  98082. else {
  98083. return 0.0;
  98084. }
  98085. }
  98086. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98087. {
  98088. 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 */
  98089. FLAC__double bits, best_bits, error_scale;
  98090. FLAC__ASSERT(max_order > 0);
  98091. FLAC__ASSERT(total_samples > 0);
  98092. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98093. best_index = 0;
  98094. best_bits = (unsigned)(-1);
  98095. for(index = 0, order = 1; index < max_order; index++, order++) {
  98096. 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);
  98097. if(bits < best_bits) {
  98098. best_index = index;
  98099. best_bits = bits;
  98100. }
  98101. }
  98102. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98103. }
  98104. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98105. #endif
  98106. /*** End of inlined file: lpc_flac.c ***/
  98107. /*** Start of inlined file: md5.c ***/
  98108. /*** Start of inlined file: juce_FlacHeader.h ***/
  98109. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98110. // tasks..
  98111. #define VERSION "1.2.1"
  98112. #define FLAC__NO_DLL 1
  98113. #if JUCE_MSVC
  98114. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98115. #endif
  98116. #if JUCE_MAC
  98117. #define FLAC__SYS_DARWIN 1
  98118. #endif
  98119. /*** End of inlined file: juce_FlacHeader.h ***/
  98120. #if JUCE_USE_FLAC
  98121. #if HAVE_CONFIG_H
  98122. # include <config.h>
  98123. #endif
  98124. #include <stdlib.h> /* for malloc() */
  98125. #include <string.h> /* for memcpy() */
  98126. /*** Start of inlined file: md5.h ***/
  98127. #ifndef FLAC__PRIVATE__MD5_H
  98128. #define FLAC__PRIVATE__MD5_H
  98129. /*
  98130. * This is the header file for the MD5 message-digest algorithm.
  98131. * The algorithm is due to Ron Rivest. This code was
  98132. * written by Colin Plumb in 1993, no copyright is claimed.
  98133. * This code is in the public domain; do with it what you wish.
  98134. *
  98135. * Equivalent code is available from RSA Data Security, Inc.
  98136. * This code has been tested against that, and is equivalent,
  98137. * except that you don't need to include two pages of legalese
  98138. * with every copy.
  98139. *
  98140. * To compute the message digest of a chunk of bytes, declare an
  98141. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98142. * needed on buffers full of bytes, and then call MD5Final, which
  98143. * will fill a supplied 16-byte array with the digest.
  98144. *
  98145. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98146. * header definitions; now uses stuff from dpkg's config.h
  98147. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98148. * Still in the public domain.
  98149. *
  98150. * Josh Coalson: made some changes to integrate with libFLAC.
  98151. * Still in the public domain, with no warranty.
  98152. */
  98153. typedef struct {
  98154. FLAC__uint32 in[16];
  98155. FLAC__uint32 buf[4];
  98156. FLAC__uint32 bytes[2];
  98157. FLAC__byte *internal_buf;
  98158. size_t capacity;
  98159. } FLAC__MD5Context;
  98160. void FLAC__MD5Init(FLAC__MD5Context *context);
  98161. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98162. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98163. #endif
  98164. /*** End of inlined file: md5.h ***/
  98165. #ifndef FLaC__INLINE
  98166. #define FLaC__INLINE
  98167. #endif
  98168. /*
  98169. * This code implements the MD5 message-digest algorithm.
  98170. * The algorithm is due to Ron Rivest. This code was
  98171. * written by Colin Plumb in 1993, no copyright is claimed.
  98172. * This code is in the public domain; do with it what you wish.
  98173. *
  98174. * Equivalent code is available from RSA Data Security, Inc.
  98175. * This code has been tested against that, and is equivalent,
  98176. * except that you don't need to include two pages of legalese
  98177. * with every copy.
  98178. *
  98179. * To compute the message digest of a chunk of bytes, declare an
  98180. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98181. * needed on buffers full of bytes, and then call MD5Final, which
  98182. * will fill a supplied 16-byte array with the digest.
  98183. *
  98184. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98185. * definitions; now uses stuff from dpkg's config.h.
  98186. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98187. * Still in the public domain.
  98188. *
  98189. * Josh Coalson: made some changes to integrate with libFLAC.
  98190. * Still in the public domain.
  98191. */
  98192. /* The four core functions - F1 is optimized somewhat */
  98193. /* #define F1(x, y, z) (x & y | ~x & z) */
  98194. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98195. #define F2(x, y, z) F1(z, x, y)
  98196. #define F3(x, y, z) (x ^ y ^ z)
  98197. #define F4(x, y, z) (y ^ (x | ~z))
  98198. /* This is the central step in the MD5 algorithm. */
  98199. #define MD5STEP(f,w,x,y,z,in,s) \
  98200. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98201. /*
  98202. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98203. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98204. * the data and converts bytes into longwords for this routine.
  98205. */
  98206. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98207. {
  98208. register FLAC__uint32 a, b, c, d;
  98209. a = buf[0];
  98210. b = buf[1];
  98211. c = buf[2];
  98212. d = buf[3];
  98213. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98214. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98215. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98216. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98217. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98218. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98219. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98220. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98221. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98222. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98223. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98224. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98225. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98226. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98227. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98228. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98229. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98230. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98231. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98232. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98233. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98234. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98235. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98236. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98237. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98238. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98239. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98240. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98241. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98242. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98243. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98244. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98245. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98246. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98247. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98248. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98249. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98250. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98251. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98252. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98253. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98254. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98255. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98256. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98257. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98258. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98259. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98260. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98261. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98262. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98263. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98264. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98265. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98266. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98267. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98268. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98269. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98270. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98271. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98272. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98273. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98274. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98275. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98276. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98277. buf[0] += a;
  98278. buf[1] += b;
  98279. buf[2] += c;
  98280. buf[3] += d;
  98281. }
  98282. #if WORDS_BIGENDIAN
  98283. //@@@@@@ OPT: use bswap/intrinsics
  98284. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98285. {
  98286. register FLAC__uint32 x;
  98287. do {
  98288. x = *buf;
  98289. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98290. *buf++ = (x >> 16) | (x << 16);
  98291. } while (--words);
  98292. }
  98293. static void byteSwapX16(FLAC__uint32 *buf)
  98294. {
  98295. register FLAC__uint32 x;
  98296. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98297. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98298. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98299. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98300. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98301. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98302. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98303. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98304. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98305. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98306. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98307. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98308. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98309. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98310. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98311. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98312. }
  98313. #else
  98314. #define byteSwap(buf, words)
  98315. #define byteSwapX16(buf)
  98316. #endif
  98317. /*
  98318. * Update context to reflect the concatenation of another buffer full
  98319. * of bytes.
  98320. */
  98321. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98322. {
  98323. FLAC__uint32 t;
  98324. /* Update byte count */
  98325. t = ctx->bytes[0];
  98326. if ((ctx->bytes[0] = t + len) < t)
  98327. ctx->bytes[1]++; /* Carry from low to high */
  98328. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98329. if (t > len) {
  98330. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98331. return;
  98332. }
  98333. /* First chunk is an odd size */
  98334. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98335. byteSwapX16(ctx->in);
  98336. FLAC__MD5Transform(ctx->buf, ctx->in);
  98337. buf += t;
  98338. len -= t;
  98339. /* Process data in 64-byte chunks */
  98340. while (len >= 64) {
  98341. memcpy(ctx->in, buf, 64);
  98342. byteSwapX16(ctx->in);
  98343. FLAC__MD5Transform(ctx->buf, ctx->in);
  98344. buf += 64;
  98345. len -= 64;
  98346. }
  98347. /* Handle any remaining bytes of data. */
  98348. memcpy(ctx->in, buf, len);
  98349. }
  98350. /*
  98351. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98352. * initialization constants.
  98353. */
  98354. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98355. {
  98356. ctx->buf[0] = 0x67452301;
  98357. ctx->buf[1] = 0xefcdab89;
  98358. ctx->buf[2] = 0x98badcfe;
  98359. ctx->buf[3] = 0x10325476;
  98360. ctx->bytes[0] = 0;
  98361. ctx->bytes[1] = 0;
  98362. ctx->internal_buf = 0;
  98363. ctx->capacity = 0;
  98364. }
  98365. /*
  98366. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98367. * 1 0* (64-bit count of bits processed, MSB-first)
  98368. */
  98369. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98370. {
  98371. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98372. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98373. /* Set the first char of padding to 0x80. There is always room. */
  98374. *p++ = 0x80;
  98375. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98376. count = 56 - 1 - count;
  98377. if (count < 0) { /* Padding forces an extra block */
  98378. memset(p, 0, count + 8);
  98379. byteSwapX16(ctx->in);
  98380. FLAC__MD5Transform(ctx->buf, ctx->in);
  98381. p = (FLAC__byte *)ctx->in;
  98382. count = 56;
  98383. }
  98384. memset(p, 0, count);
  98385. byteSwap(ctx->in, 14);
  98386. /* Append length in bits and transform */
  98387. ctx->in[14] = ctx->bytes[0] << 3;
  98388. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98389. FLAC__MD5Transform(ctx->buf, ctx->in);
  98390. byteSwap(ctx->buf, 4);
  98391. memcpy(digest, ctx->buf, 16);
  98392. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98393. if(0 != ctx->internal_buf) {
  98394. free(ctx->internal_buf);
  98395. ctx->internal_buf = 0;
  98396. ctx->capacity = 0;
  98397. }
  98398. }
  98399. /*
  98400. * Convert the incoming audio signal to a byte stream
  98401. */
  98402. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98403. {
  98404. unsigned channel, sample;
  98405. register FLAC__int32 a_word;
  98406. register FLAC__byte *buf_ = buf;
  98407. #if WORDS_BIGENDIAN
  98408. #else
  98409. if(channels == 2 && bytes_per_sample == 2) {
  98410. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98411. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98412. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98413. *buf1_ = (FLAC__int16)signal[1][sample];
  98414. }
  98415. else if(channels == 1 && bytes_per_sample == 2) {
  98416. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98417. for(sample = 0; sample < samples; sample++)
  98418. *buf1_++ = (FLAC__int16)signal[0][sample];
  98419. }
  98420. else
  98421. #endif
  98422. if(bytes_per_sample == 2) {
  98423. if(channels == 2) {
  98424. for(sample = 0; sample < samples; sample++) {
  98425. a_word = signal[0][sample];
  98426. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98427. *buf_++ = (FLAC__byte)a_word;
  98428. a_word = signal[1][sample];
  98429. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98430. *buf_++ = (FLAC__byte)a_word;
  98431. }
  98432. }
  98433. else if(channels == 1) {
  98434. for(sample = 0; sample < samples; sample++) {
  98435. a_word = signal[0][sample];
  98436. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98437. *buf_++ = (FLAC__byte)a_word;
  98438. }
  98439. }
  98440. else {
  98441. for(sample = 0; sample < samples; sample++) {
  98442. for(channel = 0; channel < channels; channel++) {
  98443. a_word = signal[channel][sample];
  98444. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98445. *buf_++ = (FLAC__byte)a_word;
  98446. }
  98447. }
  98448. }
  98449. }
  98450. else if(bytes_per_sample == 3) {
  98451. if(channels == 2) {
  98452. for(sample = 0; sample < samples; sample++) {
  98453. a_word = signal[0][sample];
  98454. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98455. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98456. *buf_++ = (FLAC__byte)a_word;
  98457. a_word = signal[1][sample];
  98458. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98459. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98460. *buf_++ = (FLAC__byte)a_word;
  98461. }
  98462. }
  98463. else if(channels == 1) {
  98464. for(sample = 0; sample < samples; sample++) {
  98465. a_word = signal[0][sample];
  98466. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98467. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98468. *buf_++ = (FLAC__byte)a_word;
  98469. }
  98470. }
  98471. else {
  98472. for(sample = 0; sample < samples; sample++) {
  98473. for(channel = 0; channel < channels; channel++) {
  98474. a_word = signal[channel][sample];
  98475. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98476. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98477. *buf_++ = (FLAC__byte)a_word;
  98478. }
  98479. }
  98480. }
  98481. }
  98482. else if(bytes_per_sample == 1) {
  98483. if(channels == 2) {
  98484. for(sample = 0; sample < samples; sample++) {
  98485. a_word = signal[0][sample];
  98486. *buf_++ = (FLAC__byte)a_word;
  98487. a_word = signal[1][sample];
  98488. *buf_++ = (FLAC__byte)a_word;
  98489. }
  98490. }
  98491. else if(channels == 1) {
  98492. for(sample = 0; sample < samples; sample++) {
  98493. a_word = signal[0][sample];
  98494. *buf_++ = (FLAC__byte)a_word;
  98495. }
  98496. }
  98497. else {
  98498. for(sample = 0; sample < samples; sample++) {
  98499. for(channel = 0; channel < channels; channel++) {
  98500. a_word = signal[channel][sample];
  98501. *buf_++ = (FLAC__byte)a_word;
  98502. }
  98503. }
  98504. }
  98505. }
  98506. else { /* bytes_per_sample == 4, maybe optimize more later */
  98507. for(sample = 0; sample < samples; sample++) {
  98508. for(channel = 0; channel < channels; channel++) {
  98509. a_word = signal[channel][sample];
  98510. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98511. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98512. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98513. *buf_++ = (FLAC__byte)a_word;
  98514. }
  98515. }
  98516. }
  98517. }
  98518. /*
  98519. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98520. */
  98521. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98522. {
  98523. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98524. /* overflow check */
  98525. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98526. return false;
  98527. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98528. return false;
  98529. if(ctx->capacity < bytes_needed) {
  98530. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98531. if(0 == tmp) {
  98532. free(ctx->internal_buf);
  98533. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98534. return false;
  98535. }
  98536. ctx->internal_buf = tmp;
  98537. ctx->capacity = bytes_needed;
  98538. }
  98539. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98540. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98541. return true;
  98542. }
  98543. #endif
  98544. /*** End of inlined file: md5.c ***/
  98545. /*** Start of inlined file: memory.c ***/
  98546. /*** Start of inlined file: juce_FlacHeader.h ***/
  98547. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98548. // tasks..
  98549. #define VERSION "1.2.1"
  98550. #define FLAC__NO_DLL 1
  98551. #if JUCE_MSVC
  98552. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98553. #endif
  98554. #if JUCE_MAC
  98555. #define FLAC__SYS_DARWIN 1
  98556. #endif
  98557. /*** End of inlined file: juce_FlacHeader.h ***/
  98558. #if JUCE_USE_FLAC
  98559. #if HAVE_CONFIG_H
  98560. # include <config.h>
  98561. #endif
  98562. /*** Start of inlined file: memory.h ***/
  98563. #ifndef FLAC__PRIVATE__MEMORY_H
  98564. #define FLAC__PRIVATE__MEMORY_H
  98565. #ifdef HAVE_CONFIG_H
  98566. #include <config.h>
  98567. #endif
  98568. #include <stdlib.h> /* for size_t */
  98569. /* Returns the unaligned address returned by malloc.
  98570. * Use free() on this address to deallocate.
  98571. */
  98572. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98573. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98574. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98575. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98576. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98577. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98578. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98579. #endif
  98580. #endif
  98581. /*** End of inlined file: memory.h ***/
  98582. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98583. {
  98584. void *x;
  98585. FLAC__ASSERT(0 != aligned_address);
  98586. #ifdef FLAC__ALIGN_MALLOC_DATA
  98587. /* align on 32-byte (256-bit) boundary */
  98588. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98589. #ifdef SIZEOF_VOIDP
  98590. #if SIZEOF_VOIDP == 4
  98591. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98592. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98593. #elif SIZEOF_VOIDP == 8
  98594. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98595. #else
  98596. # error Unsupported sizeof(void*)
  98597. #endif
  98598. #else
  98599. /* there's got to be a better way to do this right for all archs */
  98600. if(sizeof(void*) == sizeof(unsigned))
  98601. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98602. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98603. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98604. else
  98605. return 0;
  98606. #endif
  98607. #else
  98608. x = safe_malloc_(bytes);
  98609. *aligned_address = x;
  98610. #endif
  98611. return x;
  98612. }
  98613. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98614. {
  98615. FLAC__int32 *pu; /* unaligned pointer */
  98616. union { /* union needed to comply with C99 pointer aliasing rules */
  98617. FLAC__int32 *pa; /* aligned pointer */
  98618. void *pv; /* aligned pointer alias */
  98619. } u;
  98620. FLAC__ASSERT(elements > 0);
  98621. FLAC__ASSERT(0 != unaligned_pointer);
  98622. FLAC__ASSERT(0 != aligned_pointer);
  98623. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98624. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98625. if(0 == pu) {
  98626. return false;
  98627. }
  98628. else {
  98629. if(*unaligned_pointer != 0)
  98630. free(*unaligned_pointer);
  98631. *unaligned_pointer = pu;
  98632. *aligned_pointer = u.pa;
  98633. return true;
  98634. }
  98635. }
  98636. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98637. {
  98638. FLAC__uint32 *pu; /* unaligned pointer */
  98639. union { /* union needed to comply with C99 pointer aliasing rules */
  98640. FLAC__uint32 *pa; /* aligned pointer */
  98641. void *pv; /* aligned pointer alias */
  98642. } u;
  98643. FLAC__ASSERT(elements > 0);
  98644. FLAC__ASSERT(0 != unaligned_pointer);
  98645. FLAC__ASSERT(0 != aligned_pointer);
  98646. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98647. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98648. if(0 == pu) {
  98649. return false;
  98650. }
  98651. else {
  98652. if(*unaligned_pointer != 0)
  98653. free(*unaligned_pointer);
  98654. *unaligned_pointer = pu;
  98655. *aligned_pointer = u.pa;
  98656. return true;
  98657. }
  98658. }
  98659. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98660. {
  98661. FLAC__uint64 *pu; /* unaligned pointer */
  98662. union { /* union needed to comply with C99 pointer aliasing rules */
  98663. FLAC__uint64 *pa; /* aligned pointer */
  98664. void *pv; /* aligned pointer alias */
  98665. } u;
  98666. FLAC__ASSERT(elements > 0);
  98667. FLAC__ASSERT(0 != unaligned_pointer);
  98668. FLAC__ASSERT(0 != aligned_pointer);
  98669. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98670. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98671. if(0 == pu) {
  98672. return false;
  98673. }
  98674. else {
  98675. if(*unaligned_pointer != 0)
  98676. free(*unaligned_pointer);
  98677. *unaligned_pointer = pu;
  98678. *aligned_pointer = u.pa;
  98679. return true;
  98680. }
  98681. }
  98682. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  98683. {
  98684. unsigned *pu; /* unaligned pointer */
  98685. union { /* union needed to comply with C99 pointer aliasing rules */
  98686. unsigned *pa; /* aligned pointer */
  98687. void *pv; /* aligned pointer alias */
  98688. } u;
  98689. FLAC__ASSERT(elements > 0);
  98690. FLAC__ASSERT(0 != unaligned_pointer);
  98691. FLAC__ASSERT(0 != aligned_pointer);
  98692. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98693. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98694. if(0 == pu) {
  98695. return false;
  98696. }
  98697. else {
  98698. if(*unaligned_pointer != 0)
  98699. free(*unaligned_pointer);
  98700. *unaligned_pointer = pu;
  98701. *aligned_pointer = u.pa;
  98702. return true;
  98703. }
  98704. }
  98705. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98706. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  98707. {
  98708. FLAC__real *pu; /* unaligned pointer */
  98709. union { /* union needed to comply with C99 pointer aliasing rules */
  98710. FLAC__real *pa; /* aligned pointer */
  98711. void *pv; /* aligned pointer alias */
  98712. } u;
  98713. FLAC__ASSERT(elements > 0);
  98714. FLAC__ASSERT(0 != unaligned_pointer);
  98715. FLAC__ASSERT(0 != aligned_pointer);
  98716. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98717. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98718. if(0 == pu) {
  98719. return false;
  98720. }
  98721. else {
  98722. if(*unaligned_pointer != 0)
  98723. free(*unaligned_pointer);
  98724. *unaligned_pointer = pu;
  98725. *aligned_pointer = u.pa;
  98726. return true;
  98727. }
  98728. }
  98729. #endif
  98730. #endif
  98731. /*** End of inlined file: memory.c ***/
  98732. /*** Start of inlined file: stream_decoder.c ***/
  98733. /*** Start of inlined file: juce_FlacHeader.h ***/
  98734. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98735. // tasks..
  98736. #define VERSION "1.2.1"
  98737. #define FLAC__NO_DLL 1
  98738. #if JUCE_MSVC
  98739. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98740. #endif
  98741. #if JUCE_MAC
  98742. #define FLAC__SYS_DARWIN 1
  98743. #endif
  98744. /*** End of inlined file: juce_FlacHeader.h ***/
  98745. #if JUCE_USE_FLAC
  98746. #if HAVE_CONFIG_H
  98747. # include <config.h>
  98748. #endif
  98749. #if defined _MSC_VER || defined __MINGW32__
  98750. #include <io.h> /* for _setmode() */
  98751. #include <fcntl.h> /* for _O_BINARY */
  98752. #endif
  98753. #if defined __CYGWIN__ || defined __EMX__
  98754. #include <io.h> /* for setmode(), O_BINARY */
  98755. #include <fcntl.h> /* for _O_BINARY */
  98756. #endif
  98757. #include <stdio.h>
  98758. #include <stdlib.h> /* for malloc() */
  98759. #include <string.h> /* for memset/memcpy() */
  98760. #include <sys/stat.h> /* for stat() */
  98761. #include <sys/types.h> /* for off_t */
  98762. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98763. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98764. #define fseeko fseek
  98765. #define ftello ftell
  98766. #endif
  98767. #endif
  98768. /*** Start of inlined file: stream_decoder.h ***/
  98769. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  98770. #define FLAC__PROTECTED__STREAM_DECODER_H
  98771. #if FLAC__HAS_OGG
  98772. #include "include/private/ogg_decoder_aspect.h"
  98773. #endif
  98774. typedef struct FLAC__StreamDecoderProtected {
  98775. FLAC__StreamDecoderState state;
  98776. unsigned channels;
  98777. FLAC__ChannelAssignment channel_assignment;
  98778. unsigned bits_per_sample;
  98779. unsigned sample_rate; /* in Hz */
  98780. unsigned blocksize; /* in samples (per channel) */
  98781. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  98782. #if FLAC__HAS_OGG
  98783. FLAC__OggDecoderAspect ogg_decoder_aspect;
  98784. #endif
  98785. } FLAC__StreamDecoderProtected;
  98786. /*
  98787. * return the number of input bytes consumed
  98788. */
  98789. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  98790. #endif
  98791. /*** End of inlined file: stream_decoder.h ***/
  98792. #ifdef max
  98793. #undef max
  98794. #endif
  98795. #define max(a,b) ((a)>(b)?(a):(b))
  98796. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  98797. #ifdef _MSC_VER
  98798. #define FLAC__U64L(x) x
  98799. #else
  98800. #define FLAC__U64L(x) x##LLU
  98801. #endif
  98802. /* technically this should be in an "export.c" but this is convenient enough */
  98803. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  98804. #if FLAC__HAS_OGG
  98805. 1
  98806. #else
  98807. 0
  98808. #endif
  98809. ;
  98810. /***********************************************************************
  98811. *
  98812. * Private static data
  98813. *
  98814. ***********************************************************************/
  98815. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  98816. /***********************************************************************
  98817. *
  98818. * Private class method prototypes
  98819. *
  98820. ***********************************************************************/
  98821. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  98822. static FILE *get_binary_stdin_(void);
  98823. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  98824. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  98825. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  98826. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  98827. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98828. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  98829. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  98830. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  98831. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  98832. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  98833. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  98834. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  98835. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  98836. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98837. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98838. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98839. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  98840. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  98841. 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);
  98842. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  98843. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  98844. #if FLAC__HAS_OGG
  98845. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  98846. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98847. #endif
  98848. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  98849. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  98850. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98851. #if FLAC__HAS_OGG
  98852. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  98853. #endif
  98854. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98855. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98856. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98857. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  98858. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  98859. /***********************************************************************
  98860. *
  98861. * Private class data
  98862. *
  98863. ***********************************************************************/
  98864. typedef struct FLAC__StreamDecoderPrivate {
  98865. #if FLAC__HAS_OGG
  98866. FLAC__bool is_ogg;
  98867. #endif
  98868. FLAC__StreamDecoderReadCallback read_callback;
  98869. FLAC__StreamDecoderSeekCallback seek_callback;
  98870. FLAC__StreamDecoderTellCallback tell_callback;
  98871. FLAC__StreamDecoderLengthCallback length_callback;
  98872. FLAC__StreamDecoderEofCallback eof_callback;
  98873. FLAC__StreamDecoderWriteCallback write_callback;
  98874. FLAC__StreamDecoderMetadataCallback metadata_callback;
  98875. FLAC__StreamDecoderErrorCallback error_callback;
  98876. /* generic 32-bit datapath: */
  98877. 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[]);
  98878. /* generic 64-bit datapath: */
  98879. 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[]);
  98880. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  98881. 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[]);
  98882. /* 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: */
  98883. 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[]);
  98884. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  98885. void *client_data;
  98886. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  98887. FLAC__BitReader *input;
  98888. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  98889. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  98890. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  98891. unsigned output_capacity, output_channels;
  98892. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  98893. FLAC__uint64 samples_decoded;
  98894. FLAC__bool has_stream_info, has_seek_table;
  98895. FLAC__StreamMetadata stream_info;
  98896. FLAC__StreamMetadata seek_table;
  98897. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  98898. FLAC__byte *metadata_filter_ids;
  98899. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  98900. FLAC__Frame frame;
  98901. FLAC__bool cached; /* true if there is a byte in lookahead */
  98902. FLAC__CPUInfo cpuinfo;
  98903. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  98904. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  98905. /* unaligned (original) pointers to allocated data */
  98906. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  98907. 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 */
  98908. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  98909. FLAC__bool is_seeking;
  98910. FLAC__MD5Context md5context;
  98911. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  98912. /* (the rest of these are only used for seeking) */
  98913. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  98914. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  98915. FLAC__uint64 target_sample;
  98916. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  98917. #if FLAC__HAS_OGG
  98918. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  98919. #endif
  98920. } FLAC__StreamDecoderPrivate;
  98921. /***********************************************************************
  98922. *
  98923. * Public static class data
  98924. *
  98925. ***********************************************************************/
  98926. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  98927. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  98928. "FLAC__STREAM_DECODER_READ_METADATA",
  98929. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  98930. "FLAC__STREAM_DECODER_READ_FRAME",
  98931. "FLAC__STREAM_DECODER_END_OF_STREAM",
  98932. "FLAC__STREAM_DECODER_OGG_ERROR",
  98933. "FLAC__STREAM_DECODER_SEEK_ERROR",
  98934. "FLAC__STREAM_DECODER_ABORTED",
  98935. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  98936. "FLAC__STREAM_DECODER_UNINITIALIZED"
  98937. };
  98938. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  98939. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  98940. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98941. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  98942. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  98943. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  98944. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  98945. };
  98946. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  98947. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  98948. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  98949. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  98950. };
  98951. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  98952. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  98953. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  98954. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  98955. };
  98956. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  98957. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  98958. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  98959. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  98960. };
  98961. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  98962. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  98963. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  98964. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  98965. };
  98966. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  98967. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  98968. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  98969. };
  98970. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  98971. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  98972. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  98973. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  98974. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  98975. };
  98976. /***********************************************************************
  98977. *
  98978. * Class constructor/destructor
  98979. *
  98980. ***********************************************************************/
  98981. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  98982. {
  98983. FLAC__StreamDecoder *decoder;
  98984. unsigned i;
  98985. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98986. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  98987. if(decoder == 0) {
  98988. return 0;
  98989. }
  98990. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  98991. if(decoder->protected_ == 0) {
  98992. free(decoder);
  98993. return 0;
  98994. }
  98995. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  98996. if(decoder->private_ == 0) {
  98997. free(decoder->protected_);
  98998. free(decoder);
  98999. return 0;
  99000. }
  99001. decoder->private_->input = FLAC__bitreader_new();
  99002. if(decoder->private_->input == 0) {
  99003. free(decoder->private_);
  99004. free(decoder->protected_);
  99005. free(decoder);
  99006. return 0;
  99007. }
  99008. decoder->private_->metadata_filter_ids_capacity = 16;
  99009. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99010. FLAC__bitreader_delete(decoder->private_->input);
  99011. free(decoder->private_);
  99012. free(decoder->protected_);
  99013. free(decoder);
  99014. return 0;
  99015. }
  99016. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99017. decoder->private_->output[i] = 0;
  99018. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99019. }
  99020. decoder->private_->output_capacity = 0;
  99021. decoder->private_->output_channels = 0;
  99022. decoder->private_->has_seek_table = false;
  99023. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99024. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99025. decoder->private_->file = 0;
  99026. set_defaults_dec(decoder);
  99027. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99028. return decoder;
  99029. }
  99030. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99031. {
  99032. unsigned i;
  99033. FLAC__ASSERT(0 != decoder);
  99034. FLAC__ASSERT(0 != decoder->protected_);
  99035. FLAC__ASSERT(0 != decoder->private_);
  99036. FLAC__ASSERT(0 != decoder->private_->input);
  99037. (void)FLAC__stream_decoder_finish(decoder);
  99038. if(0 != decoder->private_->metadata_filter_ids)
  99039. free(decoder->private_->metadata_filter_ids);
  99040. FLAC__bitreader_delete(decoder->private_->input);
  99041. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99042. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99043. free(decoder->private_);
  99044. free(decoder->protected_);
  99045. free(decoder);
  99046. }
  99047. /***********************************************************************
  99048. *
  99049. * Public class methods
  99050. *
  99051. ***********************************************************************/
  99052. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99053. FLAC__StreamDecoder *decoder,
  99054. FLAC__StreamDecoderReadCallback read_callback,
  99055. FLAC__StreamDecoderSeekCallback seek_callback,
  99056. FLAC__StreamDecoderTellCallback tell_callback,
  99057. FLAC__StreamDecoderLengthCallback length_callback,
  99058. FLAC__StreamDecoderEofCallback eof_callback,
  99059. FLAC__StreamDecoderWriteCallback write_callback,
  99060. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99061. FLAC__StreamDecoderErrorCallback error_callback,
  99062. void *client_data,
  99063. FLAC__bool is_ogg
  99064. )
  99065. {
  99066. FLAC__ASSERT(0 != decoder);
  99067. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99068. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99069. #if !FLAC__HAS_OGG
  99070. if(is_ogg)
  99071. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99072. #endif
  99073. if(
  99074. 0 == read_callback ||
  99075. 0 == write_callback ||
  99076. 0 == error_callback ||
  99077. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99078. )
  99079. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99080. #if FLAC__HAS_OGG
  99081. decoder->private_->is_ogg = is_ogg;
  99082. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99083. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99084. #endif
  99085. /*
  99086. * get the CPU info and set the function pointers
  99087. */
  99088. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99089. /* first default to the non-asm routines */
  99090. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99091. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99092. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99093. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99094. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99095. /* now override with asm where appropriate */
  99096. #ifndef FLAC__NO_ASM
  99097. if(decoder->private_->cpuinfo.use_asm) {
  99098. #ifdef FLAC__CPU_IA32
  99099. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99100. #ifdef FLAC__HAS_NASM
  99101. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99102. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99103. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99104. #endif
  99105. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99106. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99107. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99108. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99109. }
  99110. else {
  99111. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99112. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99113. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99114. }
  99115. #endif
  99116. #elif defined FLAC__CPU_PPC
  99117. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99118. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99119. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99120. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99121. }
  99122. #endif
  99123. }
  99124. #endif
  99125. /* from here on, errors are fatal */
  99126. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99127. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99128. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99129. }
  99130. decoder->private_->read_callback = read_callback;
  99131. decoder->private_->seek_callback = seek_callback;
  99132. decoder->private_->tell_callback = tell_callback;
  99133. decoder->private_->length_callback = length_callback;
  99134. decoder->private_->eof_callback = eof_callback;
  99135. decoder->private_->write_callback = write_callback;
  99136. decoder->private_->metadata_callback = metadata_callback;
  99137. decoder->private_->error_callback = error_callback;
  99138. decoder->private_->client_data = client_data;
  99139. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99140. decoder->private_->samples_decoded = 0;
  99141. decoder->private_->has_stream_info = false;
  99142. decoder->private_->cached = false;
  99143. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99144. decoder->private_->is_seeking = false;
  99145. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99146. if(!FLAC__stream_decoder_reset(decoder)) {
  99147. /* above call sets the state for us */
  99148. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99149. }
  99150. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99151. }
  99152. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99153. FLAC__StreamDecoder *decoder,
  99154. FLAC__StreamDecoderReadCallback read_callback,
  99155. FLAC__StreamDecoderSeekCallback seek_callback,
  99156. FLAC__StreamDecoderTellCallback tell_callback,
  99157. FLAC__StreamDecoderLengthCallback length_callback,
  99158. FLAC__StreamDecoderEofCallback eof_callback,
  99159. FLAC__StreamDecoderWriteCallback write_callback,
  99160. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99161. FLAC__StreamDecoderErrorCallback error_callback,
  99162. void *client_data
  99163. )
  99164. {
  99165. return init_stream_internal_dec(
  99166. decoder,
  99167. read_callback,
  99168. seek_callback,
  99169. tell_callback,
  99170. length_callback,
  99171. eof_callback,
  99172. write_callback,
  99173. metadata_callback,
  99174. error_callback,
  99175. client_data,
  99176. /*is_ogg=*/false
  99177. );
  99178. }
  99179. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99180. FLAC__StreamDecoder *decoder,
  99181. FLAC__StreamDecoderReadCallback read_callback,
  99182. FLAC__StreamDecoderSeekCallback seek_callback,
  99183. FLAC__StreamDecoderTellCallback tell_callback,
  99184. FLAC__StreamDecoderLengthCallback length_callback,
  99185. FLAC__StreamDecoderEofCallback eof_callback,
  99186. FLAC__StreamDecoderWriteCallback write_callback,
  99187. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99188. FLAC__StreamDecoderErrorCallback error_callback,
  99189. void *client_data
  99190. )
  99191. {
  99192. return init_stream_internal_dec(
  99193. decoder,
  99194. read_callback,
  99195. seek_callback,
  99196. tell_callback,
  99197. length_callback,
  99198. eof_callback,
  99199. write_callback,
  99200. metadata_callback,
  99201. error_callback,
  99202. client_data,
  99203. /*is_ogg=*/true
  99204. );
  99205. }
  99206. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99207. FLAC__StreamDecoder *decoder,
  99208. FILE *file,
  99209. FLAC__StreamDecoderWriteCallback write_callback,
  99210. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99211. FLAC__StreamDecoderErrorCallback error_callback,
  99212. void *client_data,
  99213. FLAC__bool is_ogg
  99214. )
  99215. {
  99216. FLAC__ASSERT(0 != decoder);
  99217. FLAC__ASSERT(0 != file);
  99218. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99219. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99220. if(0 == write_callback || 0 == error_callback)
  99221. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99222. /*
  99223. * To make sure that our file does not go unclosed after an error, we
  99224. * must assign the FILE pointer before any further error can occur in
  99225. * this routine.
  99226. */
  99227. if(file == stdin)
  99228. file = get_binary_stdin_(); /* just to be safe */
  99229. decoder->private_->file = file;
  99230. return init_stream_internal_dec(
  99231. decoder,
  99232. file_read_callback_dec,
  99233. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99234. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99235. decoder->private_->file == stdin? 0: file_length_callback_,
  99236. file_eof_callback_,
  99237. write_callback,
  99238. metadata_callback,
  99239. error_callback,
  99240. client_data,
  99241. is_ogg
  99242. );
  99243. }
  99244. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99245. FLAC__StreamDecoder *decoder,
  99246. FILE *file,
  99247. FLAC__StreamDecoderWriteCallback write_callback,
  99248. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99249. FLAC__StreamDecoderErrorCallback error_callback,
  99250. void *client_data
  99251. )
  99252. {
  99253. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99254. }
  99255. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99256. FLAC__StreamDecoder *decoder,
  99257. FILE *file,
  99258. FLAC__StreamDecoderWriteCallback write_callback,
  99259. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99260. FLAC__StreamDecoderErrorCallback error_callback,
  99261. void *client_data
  99262. )
  99263. {
  99264. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99265. }
  99266. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99267. FLAC__StreamDecoder *decoder,
  99268. const char *filename,
  99269. FLAC__StreamDecoderWriteCallback write_callback,
  99270. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99271. FLAC__StreamDecoderErrorCallback error_callback,
  99272. void *client_data,
  99273. FLAC__bool is_ogg
  99274. )
  99275. {
  99276. FILE *file;
  99277. FLAC__ASSERT(0 != decoder);
  99278. /*
  99279. * To make sure that our file does not go unclosed after an error, we
  99280. * have to do the same entrance checks here that are later performed
  99281. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99282. */
  99283. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99284. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99285. if(0 == write_callback || 0 == error_callback)
  99286. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99287. file = filename? fopen(filename, "rb") : stdin;
  99288. if(0 == file)
  99289. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99290. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99291. }
  99292. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99293. FLAC__StreamDecoder *decoder,
  99294. const char *filename,
  99295. FLAC__StreamDecoderWriteCallback write_callback,
  99296. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99297. FLAC__StreamDecoderErrorCallback error_callback,
  99298. void *client_data
  99299. )
  99300. {
  99301. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99302. }
  99303. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99304. FLAC__StreamDecoder *decoder,
  99305. const char *filename,
  99306. FLAC__StreamDecoderWriteCallback write_callback,
  99307. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99308. FLAC__StreamDecoderErrorCallback error_callback,
  99309. void *client_data
  99310. )
  99311. {
  99312. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99313. }
  99314. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99315. {
  99316. FLAC__bool md5_failed = false;
  99317. unsigned i;
  99318. FLAC__ASSERT(0 != decoder);
  99319. FLAC__ASSERT(0 != decoder->private_);
  99320. FLAC__ASSERT(0 != decoder->protected_);
  99321. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99322. return true;
  99323. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99324. * always call FLAC__MD5Final()
  99325. */
  99326. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99327. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99328. free(decoder->private_->seek_table.data.seek_table.points);
  99329. decoder->private_->seek_table.data.seek_table.points = 0;
  99330. decoder->private_->has_seek_table = false;
  99331. }
  99332. FLAC__bitreader_free(decoder->private_->input);
  99333. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99334. /* WATCHOUT:
  99335. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99336. * output arrays have a buffer of up to 3 zeroes in front
  99337. * (at negative indices) for alignment purposes; we use 4
  99338. * to keep the data well-aligned.
  99339. */
  99340. if(0 != decoder->private_->output[i]) {
  99341. free(decoder->private_->output[i]-4);
  99342. decoder->private_->output[i] = 0;
  99343. }
  99344. if(0 != decoder->private_->residual_unaligned[i]) {
  99345. free(decoder->private_->residual_unaligned[i]);
  99346. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99347. }
  99348. }
  99349. decoder->private_->output_capacity = 0;
  99350. decoder->private_->output_channels = 0;
  99351. #if FLAC__HAS_OGG
  99352. if(decoder->private_->is_ogg)
  99353. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99354. #endif
  99355. if(0 != decoder->private_->file) {
  99356. if(decoder->private_->file != stdin)
  99357. fclose(decoder->private_->file);
  99358. decoder->private_->file = 0;
  99359. }
  99360. if(decoder->private_->do_md5_checking) {
  99361. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99362. md5_failed = true;
  99363. }
  99364. decoder->private_->is_seeking = false;
  99365. set_defaults_dec(decoder);
  99366. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99367. return !md5_failed;
  99368. }
  99369. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99370. {
  99371. FLAC__ASSERT(0 != decoder);
  99372. FLAC__ASSERT(0 != decoder->private_);
  99373. FLAC__ASSERT(0 != decoder->protected_);
  99374. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99375. return false;
  99376. #if FLAC__HAS_OGG
  99377. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99378. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99379. return true;
  99380. #else
  99381. (void)value;
  99382. return false;
  99383. #endif
  99384. }
  99385. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99386. {
  99387. FLAC__ASSERT(0 != decoder);
  99388. FLAC__ASSERT(0 != decoder->protected_);
  99389. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99390. return false;
  99391. decoder->protected_->md5_checking = value;
  99392. return true;
  99393. }
  99394. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99395. {
  99396. FLAC__ASSERT(0 != decoder);
  99397. FLAC__ASSERT(0 != decoder->private_);
  99398. FLAC__ASSERT(0 != decoder->protected_);
  99399. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99400. /* double protection */
  99401. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99402. return false;
  99403. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99404. return false;
  99405. decoder->private_->metadata_filter[type] = true;
  99406. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99407. decoder->private_->metadata_filter_ids_count = 0;
  99408. return true;
  99409. }
  99410. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99411. {
  99412. FLAC__ASSERT(0 != decoder);
  99413. FLAC__ASSERT(0 != decoder->private_);
  99414. FLAC__ASSERT(0 != decoder->protected_);
  99415. FLAC__ASSERT(0 != id);
  99416. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99417. return false;
  99418. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99419. return true;
  99420. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99421. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99422. 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))) {
  99423. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99424. return false;
  99425. }
  99426. decoder->private_->metadata_filter_ids_capacity *= 2;
  99427. }
  99428. 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));
  99429. decoder->private_->metadata_filter_ids_count++;
  99430. return true;
  99431. }
  99432. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99433. {
  99434. unsigned i;
  99435. FLAC__ASSERT(0 != decoder);
  99436. FLAC__ASSERT(0 != decoder->private_);
  99437. FLAC__ASSERT(0 != decoder->protected_);
  99438. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99439. return false;
  99440. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99441. decoder->private_->metadata_filter[i] = true;
  99442. decoder->private_->metadata_filter_ids_count = 0;
  99443. return true;
  99444. }
  99445. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99446. {
  99447. FLAC__ASSERT(0 != decoder);
  99448. FLAC__ASSERT(0 != decoder->private_);
  99449. FLAC__ASSERT(0 != decoder->protected_);
  99450. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99451. /* double protection */
  99452. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99453. return false;
  99454. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99455. return false;
  99456. decoder->private_->metadata_filter[type] = false;
  99457. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99458. decoder->private_->metadata_filter_ids_count = 0;
  99459. return true;
  99460. }
  99461. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99462. {
  99463. FLAC__ASSERT(0 != decoder);
  99464. FLAC__ASSERT(0 != decoder->private_);
  99465. FLAC__ASSERT(0 != decoder->protected_);
  99466. FLAC__ASSERT(0 != id);
  99467. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99468. return false;
  99469. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99470. return true;
  99471. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99472. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99473. 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))) {
  99474. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99475. return false;
  99476. }
  99477. decoder->private_->metadata_filter_ids_capacity *= 2;
  99478. }
  99479. 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));
  99480. decoder->private_->metadata_filter_ids_count++;
  99481. return true;
  99482. }
  99483. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99484. {
  99485. FLAC__ASSERT(0 != decoder);
  99486. FLAC__ASSERT(0 != decoder->private_);
  99487. FLAC__ASSERT(0 != decoder->protected_);
  99488. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99489. return false;
  99490. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99491. decoder->private_->metadata_filter_ids_count = 0;
  99492. return true;
  99493. }
  99494. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99495. {
  99496. FLAC__ASSERT(0 != decoder);
  99497. FLAC__ASSERT(0 != decoder->protected_);
  99498. return decoder->protected_->state;
  99499. }
  99500. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99501. {
  99502. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99503. }
  99504. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99505. {
  99506. FLAC__ASSERT(0 != decoder);
  99507. FLAC__ASSERT(0 != decoder->protected_);
  99508. return decoder->protected_->md5_checking;
  99509. }
  99510. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99511. {
  99512. FLAC__ASSERT(0 != decoder);
  99513. FLAC__ASSERT(0 != decoder->protected_);
  99514. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99515. }
  99516. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99517. {
  99518. FLAC__ASSERT(0 != decoder);
  99519. FLAC__ASSERT(0 != decoder->protected_);
  99520. return decoder->protected_->channels;
  99521. }
  99522. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99523. {
  99524. FLAC__ASSERT(0 != decoder);
  99525. FLAC__ASSERT(0 != decoder->protected_);
  99526. return decoder->protected_->channel_assignment;
  99527. }
  99528. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99529. {
  99530. FLAC__ASSERT(0 != decoder);
  99531. FLAC__ASSERT(0 != decoder->protected_);
  99532. return decoder->protected_->bits_per_sample;
  99533. }
  99534. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99535. {
  99536. FLAC__ASSERT(0 != decoder);
  99537. FLAC__ASSERT(0 != decoder->protected_);
  99538. return decoder->protected_->sample_rate;
  99539. }
  99540. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99541. {
  99542. FLAC__ASSERT(0 != decoder);
  99543. FLAC__ASSERT(0 != decoder->protected_);
  99544. return decoder->protected_->blocksize;
  99545. }
  99546. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99547. {
  99548. FLAC__ASSERT(0 != decoder);
  99549. FLAC__ASSERT(0 != decoder->private_);
  99550. FLAC__ASSERT(0 != position);
  99551. #if FLAC__HAS_OGG
  99552. if(decoder->private_->is_ogg)
  99553. return false;
  99554. #endif
  99555. if(0 == decoder->private_->tell_callback)
  99556. return false;
  99557. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99558. return false;
  99559. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99560. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99561. return false;
  99562. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99563. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99564. return true;
  99565. }
  99566. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99567. {
  99568. FLAC__ASSERT(0 != decoder);
  99569. FLAC__ASSERT(0 != decoder->private_);
  99570. FLAC__ASSERT(0 != decoder->protected_);
  99571. decoder->private_->samples_decoded = 0;
  99572. decoder->private_->do_md5_checking = false;
  99573. #if FLAC__HAS_OGG
  99574. if(decoder->private_->is_ogg)
  99575. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99576. #endif
  99577. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99578. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99579. return false;
  99580. }
  99581. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99582. return true;
  99583. }
  99584. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99585. {
  99586. FLAC__ASSERT(0 != decoder);
  99587. FLAC__ASSERT(0 != decoder->private_);
  99588. FLAC__ASSERT(0 != decoder->protected_);
  99589. if(!FLAC__stream_decoder_flush(decoder)) {
  99590. /* above call sets the state for us */
  99591. return false;
  99592. }
  99593. #if FLAC__HAS_OGG
  99594. /*@@@ could go in !internal_reset_hack block below */
  99595. if(decoder->private_->is_ogg)
  99596. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99597. #endif
  99598. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99599. * (internal_reset_hack) don't try to rewind since we are already at
  99600. * the beginning of the stream and don't want to fail if the input is
  99601. * not seekable.
  99602. */
  99603. if(!decoder->private_->internal_reset_hack) {
  99604. if(decoder->private_->file == stdin)
  99605. return false; /* can't rewind stdin, reset fails */
  99606. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99607. return false; /* seekable and seek fails, reset fails */
  99608. }
  99609. else
  99610. decoder->private_->internal_reset_hack = false;
  99611. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99612. decoder->private_->has_stream_info = false;
  99613. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99614. free(decoder->private_->seek_table.data.seek_table.points);
  99615. decoder->private_->seek_table.data.seek_table.points = 0;
  99616. decoder->private_->has_seek_table = false;
  99617. }
  99618. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99619. /*
  99620. * This goes in reset() and not flush() because according to the spec, a
  99621. * fixed-blocksize stream must stay that way through the whole stream.
  99622. */
  99623. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99624. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99625. * is because md5 checking may be turned on to start and then turned off if
  99626. * a seek occurs. So we init the context here and finalize it in
  99627. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99628. * properly.
  99629. */
  99630. FLAC__MD5Init(&decoder->private_->md5context);
  99631. decoder->private_->first_frame_offset = 0;
  99632. decoder->private_->unparseable_frame_count = 0;
  99633. return true;
  99634. }
  99635. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99636. {
  99637. FLAC__bool got_a_frame;
  99638. FLAC__ASSERT(0 != decoder);
  99639. FLAC__ASSERT(0 != decoder->protected_);
  99640. while(1) {
  99641. switch(decoder->protected_->state) {
  99642. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99643. if(!find_metadata_(decoder))
  99644. return false; /* above function sets the status for us */
  99645. break;
  99646. case FLAC__STREAM_DECODER_READ_METADATA:
  99647. if(!read_metadata_(decoder))
  99648. return false; /* above function sets the status for us */
  99649. else
  99650. return true;
  99651. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99652. if(!frame_sync_(decoder))
  99653. return true; /* above function sets the status for us */
  99654. break;
  99655. case FLAC__STREAM_DECODER_READ_FRAME:
  99656. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99657. return false; /* above function sets the status for us */
  99658. if(got_a_frame)
  99659. return true; /* above function sets the status for us */
  99660. break;
  99661. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99662. case FLAC__STREAM_DECODER_ABORTED:
  99663. return true;
  99664. default:
  99665. FLAC__ASSERT(0);
  99666. return false;
  99667. }
  99668. }
  99669. }
  99670. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  99671. {
  99672. FLAC__ASSERT(0 != decoder);
  99673. FLAC__ASSERT(0 != decoder->protected_);
  99674. while(1) {
  99675. switch(decoder->protected_->state) {
  99676. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99677. if(!find_metadata_(decoder))
  99678. return false; /* above function sets the status for us */
  99679. break;
  99680. case FLAC__STREAM_DECODER_READ_METADATA:
  99681. if(!read_metadata_(decoder))
  99682. return false; /* above function sets the status for us */
  99683. break;
  99684. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99685. case FLAC__STREAM_DECODER_READ_FRAME:
  99686. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99687. case FLAC__STREAM_DECODER_ABORTED:
  99688. return true;
  99689. default:
  99690. FLAC__ASSERT(0);
  99691. return false;
  99692. }
  99693. }
  99694. }
  99695. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  99696. {
  99697. FLAC__bool dummy;
  99698. FLAC__ASSERT(0 != decoder);
  99699. FLAC__ASSERT(0 != decoder->protected_);
  99700. while(1) {
  99701. switch(decoder->protected_->state) {
  99702. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99703. if(!find_metadata_(decoder))
  99704. return false; /* above function sets the status for us */
  99705. break;
  99706. case FLAC__STREAM_DECODER_READ_METADATA:
  99707. if(!read_metadata_(decoder))
  99708. return false; /* above function sets the status for us */
  99709. break;
  99710. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99711. if(!frame_sync_(decoder))
  99712. return true; /* above function sets the status for us */
  99713. break;
  99714. case FLAC__STREAM_DECODER_READ_FRAME:
  99715. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  99716. return false; /* above function sets the status for us */
  99717. break;
  99718. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99719. case FLAC__STREAM_DECODER_ABORTED:
  99720. return true;
  99721. default:
  99722. FLAC__ASSERT(0);
  99723. return false;
  99724. }
  99725. }
  99726. }
  99727. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  99728. {
  99729. FLAC__bool got_a_frame;
  99730. FLAC__ASSERT(0 != decoder);
  99731. FLAC__ASSERT(0 != decoder->protected_);
  99732. while(1) {
  99733. switch(decoder->protected_->state) {
  99734. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99735. case FLAC__STREAM_DECODER_READ_METADATA:
  99736. return false; /* above function sets the status for us */
  99737. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99738. if(!frame_sync_(decoder))
  99739. return true; /* above function sets the status for us */
  99740. break;
  99741. case FLAC__STREAM_DECODER_READ_FRAME:
  99742. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  99743. return false; /* above function sets the status for us */
  99744. if(got_a_frame)
  99745. return true; /* above function sets the status for us */
  99746. break;
  99747. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99748. case FLAC__STREAM_DECODER_ABORTED:
  99749. return true;
  99750. default:
  99751. FLAC__ASSERT(0);
  99752. return false;
  99753. }
  99754. }
  99755. }
  99756. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  99757. {
  99758. FLAC__uint64 length;
  99759. FLAC__ASSERT(0 != decoder);
  99760. if(
  99761. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  99762. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  99763. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  99764. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  99765. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  99766. )
  99767. return false;
  99768. if(0 == decoder->private_->seek_callback)
  99769. return false;
  99770. FLAC__ASSERT(decoder->private_->seek_callback);
  99771. FLAC__ASSERT(decoder->private_->tell_callback);
  99772. FLAC__ASSERT(decoder->private_->length_callback);
  99773. FLAC__ASSERT(decoder->private_->eof_callback);
  99774. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  99775. return false;
  99776. decoder->private_->is_seeking = true;
  99777. /* turn off md5 checking if a seek is attempted */
  99778. decoder->private_->do_md5_checking = false;
  99779. /* 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) */
  99780. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  99781. decoder->private_->is_seeking = false;
  99782. return false;
  99783. }
  99784. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  99785. if(
  99786. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  99787. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  99788. ) {
  99789. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  99790. /* above call sets the state for us */
  99791. decoder->private_->is_seeking = false;
  99792. return false;
  99793. }
  99794. /* check this again in case we didn't know total_samples the first time */
  99795. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  99796. decoder->private_->is_seeking = false;
  99797. return false;
  99798. }
  99799. }
  99800. {
  99801. const FLAC__bool ok =
  99802. #if FLAC__HAS_OGG
  99803. decoder->private_->is_ogg?
  99804. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  99805. #endif
  99806. seek_to_absolute_sample_(decoder, length, sample)
  99807. ;
  99808. decoder->private_->is_seeking = false;
  99809. return ok;
  99810. }
  99811. }
  99812. /***********************************************************************
  99813. *
  99814. * Protected class methods
  99815. *
  99816. ***********************************************************************/
  99817. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  99818. {
  99819. FLAC__ASSERT(0 != decoder);
  99820. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99821. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  99822. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  99823. }
  99824. /***********************************************************************
  99825. *
  99826. * Private class methods
  99827. *
  99828. ***********************************************************************/
  99829. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  99830. {
  99831. #if FLAC__HAS_OGG
  99832. decoder->private_->is_ogg = false;
  99833. #endif
  99834. decoder->private_->read_callback = 0;
  99835. decoder->private_->seek_callback = 0;
  99836. decoder->private_->tell_callback = 0;
  99837. decoder->private_->length_callback = 0;
  99838. decoder->private_->eof_callback = 0;
  99839. decoder->private_->write_callback = 0;
  99840. decoder->private_->metadata_callback = 0;
  99841. decoder->private_->error_callback = 0;
  99842. decoder->private_->client_data = 0;
  99843. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99844. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  99845. decoder->private_->metadata_filter_ids_count = 0;
  99846. decoder->protected_->md5_checking = false;
  99847. #if FLAC__HAS_OGG
  99848. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  99849. #endif
  99850. }
  99851. /*
  99852. * This will forcibly set stdin to binary mode (for OSes that require it)
  99853. */
  99854. FILE *get_binary_stdin_(void)
  99855. {
  99856. /* if something breaks here it is probably due to the presence or
  99857. * absence of an underscore before the identifiers 'setmode',
  99858. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99859. */
  99860. #if defined _MSC_VER || defined __MINGW32__
  99861. _setmode(_fileno(stdin), _O_BINARY);
  99862. #elif defined __CYGWIN__
  99863. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99864. setmode(_fileno(stdin), _O_BINARY);
  99865. #elif defined __EMX__
  99866. setmode(fileno(stdin), O_BINARY);
  99867. #endif
  99868. return stdin;
  99869. }
  99870. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  99871. {
  99872. unsigned i;
  99873. FLAC__int32 *tmp;
  99874. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  99875. return true;
  99876. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  99877. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99878. if(0 != decoder->private_->output[i]) {
  99879. free(decoder->private_->output[i]-4);
  99880. decoder->private_->output[i] = 0;
  99881. }
  99882. if(0 != decoder->private_->residual_unaligned[i]) {
  99883. free(decoder->private_->residual_unaligned[i]);
  99884. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99885. }
  99886. }
  99887. for(i = 0; i < channels; i++) {
  99888. /* WATCHOUT:
  99889. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99890. * output arrays have a buffer of up to 3 zeroes in front
  99891. * (at negative indices) for alignment purposes; we use 4
  99892. * to keep the data well-aligned.
  99893. */
  99894. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  99895. if(tmp == 0) {
  99896. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99897. return false;
  99898. }
  99899. memset(tmp, 0, sizeof(FLAC__int32)*4);
  99900. decoder->private_->output[i] = tmp + 4;
  99901. /* WATCHOUT:
  99902. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  99903. */
  99904. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  99905. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99906. return false;
  99907. }
  99908. }
  99909. decoder->private_->output_capacity = size;
  99910. decoder->private_->output_channels = channels;
  99911. return true;
  99912. }
  99913. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  99914. {
  99915. size_t i;
  99916. FLAC__ASSERT(0 != decoder);
  99917. FLAC__ASSERT(0 != decoder->private_);
  99918. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  99919. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  99920. return true;
  99921. return false;
  99922. }
  99923. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  99924. {
  99925. FLAC__uint32 x;
  99926. unsigned i, id_;
  99927. FLAC__bool first = true;
  99928. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99929. for(i = id_ = 0; i < 4; ) {
  99930. if(decoder->private_->cached) {
  99931. x = (FLAC__uint32)decoder->private_->lookahead;
  99932. decoder->private_->cached = false;
  99933. }
  99934. else {
  99935. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99936. return false; /* read_callback_ sets the state for us */
  99937. }
  99938. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  99939. first = true;
  99940. i++;
  99941. id_ = 0;
  99942. continue;
  99943. }
  99944. if(x == ID3V2_TAG_[id_]) {
  99945. id_++;
  99946. i = 0;
  99947. if(id_ == 3) {
  99948. if(!skip_id3v2_tag_(decoder))
  99949. return false; /* skip_id3v2_tag_ sets the state for us */
  99950. }
  99951. continue;
  99952. }
  99953. id_ = 0;
  99954. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99955. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  99956. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  99957. return false; /* read_callback_ sets the state for us */
  99958. /* 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 */
  99959. /* else we have to check if the second byte is the end of a sync code */
  99960. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  99961. decoder->private_->lookahead = (FLAC__byte)x;
  99962. decoder->private_->cached = true;
  99963. }
  99964. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  99965. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  99966. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  99967. return true;
  99968. }
  99969. }
  99970. i = 0;
  99971. if(first) {
  99972. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  99973. first = false;
  99974. }
  99975. }
  99976. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  99977. return true;
  99978. }
  99979. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  99980. {
  99981. FLAC__bool is_last;
  99982. FLAC__uint32 i, x, type, length;
  99983. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  99984. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99985. return false; /* read_callback_ sets the state for us */
  99986. is_last = x? true : false;
  99987. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  99988. return false; /* read_callback_ sets the state for us */
  99989. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  99990. return false; /* read_callback_ sets the state for us */
  99991. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  99992. if(!read_metadata_streaminfo_(decoder, is_last, length))
  99993. return false;
  99994. decoder->private_->has_stream_info = true;
  99995. 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))
  99996. decoder->private_->do_md5_checking = false;
  99997. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  99998. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  99999. }
  100000. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100001. if(!read_metadata_seektable_(decoder, is_last, length))
  100002. return false;
  100003. decoder->private_->has_seek_table = true;
  100004. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100005. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100006. }
  100007. else {
  100008. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100009. unsigned real_length = length;
  100010. FLAC__StreamMetadata block;
  100011. block.is_last = is_last;
  100012. block.type = (FLAC__MetadataType)type;
  100013. block.length = length;
  100014. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100015. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100016. return false; /* read_callback_ sets the state for us */
  100017. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100018. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100019. return false;
  100020. }
  100021. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100022. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100023. skip_it = !skip_it;
  100024. }
  100025. if(skip_it) {
  100026. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100027. return false; /* read_callback_ sets the state for us */
  100028. }
  100029. else {
  100030. switch(type) {
  100031. case FLAC__METADATA_TYPE_PADDING:
  100032. /* skip the padding bytes */
  100033. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100034. return false; /* read_callback_ sets the state for us */
  100035. break;
  100036. case FLAC__METADATA_TYPE_APPLICATION:
  100037. /* remember, we read the ID already */
  100038. if(real_length > 0) {
  100039. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100040. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100041. return false;
  100042. }
  100043. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100044. return false; /* read_callback_ sets the state for us */
  100045. }
  100046. else
  100047. block.data.application.data = 0;
  100048. break;
  100049. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100050. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100051. return false;
  100052. break;
  100053. case FLAC__METADATA_TYPE_CUESHEET:
  100054. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100055. return false;
  100056. break;
  100057. case FLAC__METADATA_TYPE_PICTURE:
  100058. if(!read_metadata_picture_(decoder, &block.data.picture))
  100059. return false;
  100060. break;
  100061. case FLAC__METADATA_TYPE_STREAMINFO:
  100062. case FLAC__METADATA_TYPE_SEEKTABLE:
  100063. FLAC__ASSERT(0);
  100064. break;
  100065. default:
  100066. if(real_length > 0) {
  100067. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100068. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100069. return false;
  100070. }
  100071. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100072. return false; /* read_callback_ sets the state for us */
  100073. }
  100074. else
  100075. block.data.unknown.data = 0;
  100076. break;
  100077. }
  100078. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100079. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100080. /* now we have to free any malloc()ed data in the block */
  100081. switch(type) {
  100082. case FLAC__METADATA_TYPE_PADDING:
  100083. break;
  100084. case FLAC__METADATA_TYPE_APPLICATION:
  100085. if(0 != block.data.application.data)
  100086. free(block.data.application.data);
  100087. break;
  100088. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100089. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100090. free(block.data.vorbis_comment.vendor_string.entry);
  100091. if(block.data.vorbis_comment.num_comments > 0)
  100092. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100093. if(0 != block.data.vorbis_comment.comments[i].entry)
  100094. free(block.data.vorbis_comment.comments[i].entry);
  100095. if(0 != block.data.vorbis_comment.comments)
  100096. free(block.data.vorbis_comment.comments);
  100097. break;
  100098. case FLAC__METADATA_TYPE_CUESHEET:
  100099. if(block.data.cue_sheet.num_tracks > 0)
  100100. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100101. if(0 != block.data.cue_sheet.tracks[i].indices)
  100102. free(block.data.cue_sheet.tracks[i].indices);
  100103. if(0 != block.data.cue_sheet.tracks)
  100104. free(block.data.cue_sheet.tracks);
  100105. break;
  100106. case FLAC__METADATA_TYPE_PICTURE:
  100107. if(0 != block.data.picture.mime_type)
  100108. free(block.data.picture.mime_type);
  100109. if(0 != block.data.picture.description)
  100110. free(block.data.picture.description);
  100111. if(0 != block.data.picture.data)
  100112. free(block.data.picture.data);
  100113. break;
  100114. case FLAC__METADATA_TYPE_STREAMINFO:
  100115. case FLAC__METADATA_TYPE_SEEKTABLE:
  100116. FLAC__ASSERT(0);
  100117. default:
  100118. if(0 != block.data.unknown.data)
  100119. free(block.data.unknown.data);
  100120. break;
  100121. }
  100122. }
  100123. }
  100124. if(is_last) {
  100125. /* if this fails, it's OK, it's just a hint for the seek routine */
  100126. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100127. decoder->private_->first_frame_offset = 0;
  100128. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100129. }
  100130. return true;
  100131. }
  100132. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100133. {
  100134. FLAC__uint32 x;
  100135. unsigned bits, used_bits = 0;
  100136. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100137. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100138. decoder->private_->stream_info.is_last = is_last;
  100139. decoder->private_->stream_info.length = length;
  100140. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100141. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100142. return false; /* read_callback_ sets the state for us */
  100143. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100144. used_bits += bits;
  100145. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100146. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100147. return false; /* read_callback_ sets the state for us */
  100148. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100149. used_bits += bits;
  100150. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100151. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100152. return false; /* read_callback_ sets the state for us */
  100153. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100154. used_bits += bits;
  100155. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100156. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100157. return false; /* read_callback_ sets the state for us */
  100158. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100159. used_bits += bits;
  100160. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100161. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100162. return false; /* read_callback_ sets the state for us */
  100163. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100164. used_bits += bits;
  100165. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100166. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100167. return false; /* read_callback_ sets the state for us */
  100168. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100169. used_bits += bits;
  100170. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100171. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100172. return false; /* read_callback_ sets the state for us */
  100173. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100174. used_bits += bits;
  100175. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100176. 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))
  100177. return false; /* read_callback_ sets the state for us */
  100178. used_bits += bits;
  100179. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100180. return false; /* read_callback_ sets the state for us */
  100181. used_bits += 16*8;
  100182. /* skip the rest of the block */
  100183. FLAC__ASSERT(used_bits % 8 == 0);
  100184. length -= (used_bits / 8);
  100185. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100186. return false; /* read_callback_ sets the state for us */
  100187. return true;
  100188. }
  100189. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100190. {
  100191. FLAC__uint32 i, x;
  100192. FLAC__uint64 xx;
  100193. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100194. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100195. decoder->private_->seek_table.is_last = is_last;
  100196. decoder->private_->seek_table.length = length;
  100197. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100198. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100199. 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)))) {
  100200. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100201. return false;
  100202. }
  100203. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100204. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100205. return false; /* read_callback_ sets the state for us */
  100206. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100207. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100208. return false; /* read_callback_ sets the state for us */
  100209. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100210. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100211. return false; /* read_callback_ sets the state for us */
  100212. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100213. }
  100214. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100215. /* if there is a partial point left, skip over it */
  100216. if(length > 0) {
  100217. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100218. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100219. return false; /* read_callback_ sets the state for us */
  100220. }
  100221. return true;
  100222. }
  100223. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100224. {
  100225. FLAC__uint32 i;
  100226. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100227. /* read vendor string */
  100228. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100229. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100230. return false; /* read_callback_ sets the state for us */
  100231. if(obj->vendor_string.length > 0) {
  100232. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100233. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100234. return false;
  100235. }
  100236. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100237. return false; /* read_callback_ sets the state for us */
  100238. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100239. }
  100240. else
  100241. obj->vendor_string.entry = 0;
  100242. /* read num comments */
  100243. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100244. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100245. return false; /* read_callback_ sets the state for us */
  100246. /* read comments */
  100247. if(obj->num_comments > 0) {
  100248. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100249. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100250. return false;
  100251. }
  100252. for(i = 0; i < obj->num_comments; i++) {
  100253. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100254. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100255. return false; /* read_callback_ sets the state for us */
  100256. if(obj->comments[i].length > 0) {
  100257. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100258. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100259. return false;
  100260. }
  100261. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100262. return false; /* read_callback_ sets the state for us */
  100263. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100264. }
  100265. else
  100266. obj->comments[i].entry = 0;
  100267. }
  100268. }
  100269. else {
  100270. obj->comments = 0;
  100271. }
  100272. return true;
  100273. }
  100274. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100275. {
  100276. FLAC__uint32 i, j, x;
  100277. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100278. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100279. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100280. 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))
  100281. return false; /* read_callback_ sets the state for us */
  100282. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100283. return false; /* read_callback_ sets the state for us */
  100284. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100285. return false; /* read_callback_ sets the state for us */
  100286. obj->is_cd = x? true : false;
  100287. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100288. return false; /* read_callback_ sets the state for us */
  100289. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100290. return false; /* read_callback_ sets the state for us */
  100291. obj->num_tracks = x;
  100292. if(obj->num_tracks > 0) {
  100293. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100294. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100295. return false;
  100296. }
  100297. for(i = 0; i < obj->num_tracks; i++) {
  100298. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100299. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100300. return false; /* read_callback_ sets the state for us */
  100301. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100302. return false; /* read_callback_ sets the state for us */
  100303. track->number = (FLAC__byte)x;
  100304. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100305. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100306. return false; /* read_callback_ sets the state for us */
  100307. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100308. return false; /* read_callback_ sets the state for us */
  100309. track->type = x;
  100310. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100311. return false; /* read_callback_ sets the state for us */
  100312. track->pre_emphasis = x;
  100313. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100314. return false; /* read_callback_ sets the state for us */
  100315. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100316. return false; /* read_callback_ sets the state for us */
  100317. track->num_indices = (FLAC__byte)x;
  100318. if(track->num_indices > 0) {
  100319. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100320. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100321. return false;
  100322. }
  100323. for(j = 0; j < track->num_indices; j++) {
  100324. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100325. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100326. return false; /* read_callback_ sets the state for us */
  100327. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100328. return false; /* read_callback_ sets the state for us */
  100329. index->number = (FLAC__byte)x;
  100330. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100331. return false; /* read_callback_ sets the state for us */
  100332. }
  100333. }
  100334. }
  100335. }
  100336. return true;
  100337. }
  100338. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100339. {
  100340. FLAC__uint32 x;
  100341. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100342. /* read type */
  100343. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100344. return false; /* read_callback_ sets the state for us */
  100345. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100346. /* read MIME type */
  100347. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100348. return false; /* read_callback_ sets the state for us */
  100349. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100350. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100351. return false;
  100352. }
  100353. if(x > 0) {
  100354. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100355. return false; /* read_callback_ sets the state for us */
  100356. }
  100357. obj->mime_type[x] = '\0';
  100358. /* read description */
  100359. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100360. return false; /* read_callback_ sets the state for us */
  100361. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100362. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100363. return false;
  100364. }
  100365. if(x > 0) {
  100366. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100367. return false; /* read_callback_ sets the state for us */
  100368. }
  100369. obj->description[x] = '\0';
  100370. /* read width */
  100371. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100372. return false; /* read_callback_ sets the state for us */
  100373. /* read height */
  100374. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100375. return false; /* read_callback_ sets the state for us */
  100376. /* read depth */
  100377. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100378. return false; /* read_callback_ sets the state for us */
  100379. /* read colors */
  100380. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100381. return false; /* read_callback_ sets the state for us */
  100382. /* read data */
  100383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100384. return false; /* read_callback_ sets the state for us */
  100385. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100386. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100387. return false;
  100388. }
  100389. if(obj->data_length > 0) {
  100390. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100391. return false; /* read_callback_ sets the state for us */
  100392. }
  100393. return true;
  100394. }
  100395. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100396. {
  100397. FLAC__uint32 x;
  100398. unsigned i, skip;
  100399. /* skip the version and flags bytes */
  100400. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100401. return false; /* read_callback_ sets the state for us */
  100402. /* get the size (in bytes) to skip */
  100403. skip = 0;
  100404. for(i = 0; i < 4; i++) {
  100405. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100406. return false; /* read_callback_ sets the state for us */
  100407. skip <<= 7;
  100408. skip |= (x & 0x7f);
  100409. }
  100410. /* skip the rest of the tag */
  100411. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100412. return false; /* read_callback_ sets the state for us */
  100413. return true;
  100414. }
  100415. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100416. {
  100417. FLAC__uint32 x;
  100418. FLAC__bool first = true;
  100419. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100420. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100421. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100422. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100423. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100424. return true;
  100425. }
  100426. }
  100427. /* make sure we're byte aligned */
  100428. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100429. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100430. return false; /* read_callback_ sets the state for us */
  100431. }
  100432. while(1) {
  100433. if(decoder->private_->cached) {
  100434. x = (FLAC__uint32)decoder->private_->lookahead;
  100435. decoder->private_->cached = false;
  100436. }
  100437. else {
  100438. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100439. return false; /* read_callback_ sets the state for us */
  100440. }
  100441. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100442. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100443. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100444. return false; /* read_callback_ sets the state for us */
  100445. /* 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 */
  100446. /* else we have to check if the second byte is the end of a sync code */
  100447. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100448. decoder->private_->lookahead = (FLAC__byte)x;
  100449. decoder->private_->cached = true;
  100450. }
  100451. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100452. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100453. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100454. return true;
  100455. }
  100456. }
  100457. if(first) {
  100458. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100459. first = false;
  100460. }
  100461. }
  100462. return true;
  100463. }
  100464. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100465. {
  100466. unsigned channel;
  100467. unsigned i;
  100468. FLAC__int32 mid, side;
  100469. unsigned frame_crc; /* the one we calculate from the input stream */
  100470. FLAC__uint32 x;
  100471. *got_a_frame = false;
  100472. /* init the CRC */
  100473. frame_crc = 0;
  100474. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100475. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100476. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100477. if(!read_frame_header_(decoder))
  100478. return false;
  100479. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100480. return true;
  100481. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100482. return false;
  100483. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100484. /*
  100485. * first figure the correct bits-per-sample of the subframe
  100486. */
  100487. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100488. switch(decoder->private_->frame.header.channel_assignment) {
  100489. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100490. /* no adjustment needed */
  100491. break;
  100492. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100493. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100494. if(channel == 1)
  100495. bps++;
  100496. break;
  100497. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100498. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100499. if(channel == 0)
  100500. bps++;
  100501. break;
  100502. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100503. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100504. if(channel == 1)
  100505. bps++;
  100506. break;
  100507. default:
  100508. FLAC__ASSERT(0);
  100509. }
  100510. /*
  100511. * now read it
  100512. */
  100513. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100514. return false;
  100515. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100516. return true;
  100517. }
  100518. if(!read_zero_padding_(decoder))
  100519. return false;
  100520. 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) */
  100521. return true;
  100522. /*
  100523. * Read the frame CRC-16 from the footer and check
  100524. */
  100525. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100526. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100527. return false; /* read_callback_ sets the state for us */
  100528. if(frame_crc == x) {
  100529. if(do_full_decode) {
  100530. /* Undo any special channel coding */
  100531. switch(decoder->private_->frame.header.channel_assignment) {
  100532. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100533. /* do nothing */
  100534. break;
  100535. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100536. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100537. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100538. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100539. break;
  100540. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100541. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100542. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100543. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100544. break;
  100545. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100546. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100547. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100548. #if 1
  100549. mid = decoder->private_->output[0][i];
  100550. side = decoder->private_->output[1][i];
  100551. mid <<= 1;
  100552. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100553. decoder->private_->output[0][i] = (mid + side) >> 1;
  100554. decoder->private_->output[1][i] = (mid - side) >> 1;
  100555. #else
  100556. /* OPT: without 'side' temp variable */
  100557. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100558. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100559. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100560. #endif
  100561. }
  100562. break;
  100563. default:
  100564. FLAC__ASSERT(0);
  100565. break;
  100566. }
  100567. }
  100568. }
  100569. else {
  100570. /* Bad frame, emit error and zero the output signal */
  100571. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100572. if(do_full_decode) {
  100573. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100574. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100575. }
  100576. }
  100577. }
  100578. *got_a_frame = true;
  100579. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100580. if(decoder->private_->next_fixed_block_size)
  100581. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100582. /* put the latest values into the public section of the decoder instance */
  100583. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100584. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100585. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100586. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100587. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100588. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100589. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100590. /* write it */
  100591. if(do_full_decode) {
  100592. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100593. return false;
  100594. }
  100595. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100596. return true;
  100597. }
  100598. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100599. {
  100600. FLAC__uint32 x;
  100601. FLAC__uint64 xx;
  100602. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100603. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100604. unsigned raw_header_len;
  100605. FLAC__bool is_unparseable = false;
  100606. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100607. /* init the raw header with the saved bits from synchronization */
  100608. raw_header[0] = decoder->private_->header_warmup[0];
  100609. raw_header[1] = decoder->private_->header_warmup[1];
  100610. raw_header_len = 2;
  100611. /* check to make sure that reserved bit is 0 */
  100612. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100613. is_unparseable = true;
  100614. /*
  100615. * Note that along the way as we read the header, we look for a sync
  100616. * code inside. If we find one it would indicate that our original
  100617. * sync was bad since there cannot be a sync code in a valid header.
  100618. *
  100619. * Three kinds of things can go wrong when reading the frame header:
  100620. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100621. * If we don't find a sync code, it can end up looking like we read
  100622. * a valid but unparseable header, until getting to the frame header
  100623. * CRC. Even then we could get a false positive on the CRC.
  100624. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100625. * future encoder).
  100626. * 3) We may be on a damaged frame which appears valid but unparseable.
  100627. *
  100628. * For all these reasons, we try and read a complete frame header as
  100629. * long as it seems valid, even if unparseable, up until the frame
  100630. * header CRC.
  100631. */
  100632. /*
  100633. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100634. */
  100635. for(i = 0; i < 2; i++) {
  100636. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100637. return false; /* read_callback_ sets the state for us */
  100638. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100639. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100640. decoder->private_->lookahead = (FLAC__byte)x;
  100641. decoder->private_->cached = true;
  100642. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100643. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100644. return true;
  100645. }
  100646. raw_header[raw_header_len++] = (FLAC__byte)x;
  100647. }
  100648. switch(x = raw_header[2] >> 4) {
  100649. case 0:
  100650. is_unparseable = true;
  100651. break;
  100652. case 1:
  100653. decoder->private_->frame.header.blocksize = 192;
  100654. break;
  100655. case 2:
  100656. case 3:
  100657. case 4:
  100658. case 5:
  100659. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100660. break;
  100661. case 6:
  100662. case 7:
  100663. blocksize_hint = x;
  100664. break;
  100665. case 8:
  100666. case 9:
  100667. case 10:
  100668. case 11:
  100669. case 12:
  100670. case 13:
  100671. case 14:
  100672. case 15:
  100673. decoder->private_->frame.header.blocksize = 256 << (x-8);
  100674. break;
  100675. default:
  100676. FLAC__ASSERT(0);
  100677. break;
  100678. }
  100679. switch(x = raw_header[2] & 0x0f) {
  100680. case 0:
  100681. if(decoder->private_->has_stream_info)
  100682. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  100683. else
  100684. is_unparseable = true;
  100685. break;
  100686. case 1:
  100687. decoder->private_->frame.header.sample_rate = 88200;
  100688. break;
  100689. case 2:
  100690. decoder->private_->frame.header.sample_rate = 176400;
  100691. break;
  100692. case 3:
  100693. decoder->private_->frame.header.sample_rate = 192000;
  100694. break;
  100695. case 4:
  100696. decoder->private_->frame.header.sample_rate = 8000;
  100697. break;
  100698. case 5:
  100699. decoder->private_->frame.header.sample_rate = 16000;
  100700. break;
  100701. case 6:
  100702. decoder->private_->frame.header.sample_rate = 22050;
  100703. break;
  100704. case 7:
  100705. decoder->private_->frame.header.sample_rate = 24000;
  100706. break;
  100707. case 8:
  100708. decoder->private_->frame.header.sample_rate = 32000;
  100709. break;
  100710. case 9:
  100711. decoder->private_->frame.header.sample_rate = 44100;
  100712. break;
  100713. case 10:
  100714. decoder->private_->frame.header.sample_rate = 48000;
  100715. break;
  100716. case 11:
  100717. decoder->private_->frame.header.sample_rate = 96000;
  100718. break;
  100719. case 12:
  100720. case 13:
  100721. case 14:
  100722. sample_rate_hint = x;
  100723. break;
  100724. case 15:
  100725. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100726. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100727. return true;
  100728. default:
  100729. FLAC__ASSERT(0);
  100730. }
  100731. x = (unsigned)(raw_header[3] >> 4);
  100732. if(x & 8) {
  100733. decoder->private_->frame.header.channels = 2;
  100734. switch(x & 7) {
  100735. case 0:
  100736. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  100737. break;
  100738. case 1:
  100739. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  100740. break;
  100741. case 2:
  100742. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  100743. break;
  100744. default:
  100745. is_unparseable = true;
  100746. break;
  100747. }
  100748. }
  100749. else {
  100750. decoder->private_->frame.header.channels = (unsigned)x + 1;
  100751. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100752. }
  100753. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  100754. case 0:
  100755. if(decoder->private_->has_stream_info)
  100756. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  100757. else
  100758. is_unparseable = true;
  100759. break;
  100760. case 1:
  100761. decoder->private_->frame.header.bits_per_sample = 8;
  100762. break;
  100763. case 2:
  100764. decoder->private_->frame.header.bits_per_sample = 12;
  100765. break;
  100766. case 4:
  100767. decoder->private_->frame.header.bits_per_sample = 16;
  100768. break;
  100769. case 5:
  100770. decoder->private_->frame.header.bits_per_sample = 20;
  100771. break;
  100772. case 6:
  100773. decoder->private_->frame.header.bits_per_sample = 24;
  100774. break;
  100775. case 3:
  100776. case 7:
  100777. is_unparseable = true;
  100778. break;
  100779. default:
  100780. FLAC__ASSERT(0);
  100781. break;
  100782. }
  100783. /* check to make sure that reserved bit is 0 */
  100784. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  100785. is_unparseable = true;
  100786. /* read the frame's starting sample number (or frame number as the case may be) */
  100787. if(
  100788. raw_header[1] & 0x01 ||
  100789. /*@@@ 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 */
  100790. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  100791. ) { /* variable blocksize */
  100792. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  100793. return false; /* read_callback_ sets the state for us */
  100794. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  100795. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100796. decoder->private_->cached = true;
  100797. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100798. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100799. return true;
  100800. }
  100801. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100802. decoder->private_->frame.header.number.sample_number = xx;
  100803. }
  100804. else { /* fixed blocksize */
  100805. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  100806. return false; /* read_callback_ sets the state for us */
  100807. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  100808. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  100809. decoder->private_->cached = true;
  100810. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100811. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100812. return true;
  100813. }
  100814. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100815. decoder->private_->frame.header.number.frame_number = x;
  100816. }
  100817. if(blocksize_hint) {
  100818. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100819. return false; /* read_callback_ sets the state for us */
  100820. raw_header[raw_header_len++] = (FLAC__byte)x;
  100821. if(blocksize_hint == 7) {
  100822. FLAC__uint32 _x;
  100823. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100824. return false; /* read_callback_ sets the state for us */
  100825. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100826. x = (x << 8) | _x;
  100827. }
  100828. decoder->private_->frame.header.blocksize = x+1;
  100829. }
  100830. if(sample_rate_hint) {
  100831. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100832. return false; /* read_callback_ sets the state for us */
  100833. raw_header[raw_header_len++] = (FLAC__byte)x;
  100834. if(sample_rate_hint != 12) {
  100835. FLAC__uint32 _x;
  100836. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  100837. return false; /* read_callback_ sets the state for us */
  100838. raw_header[raw_header_len++] = (FLAC__byte)_x;
  100839. x = (x << 8) | _x;
  100840. }
  100841. if(sample_rate_hint == 12)
  100842. decoder->private_->frame.header.sample_rate = x*1000;
  100843. else if(sample_rate_hint == 13)
  100844. decoder->private_->frame.header.sample_rate = x;
  100845. else
  100846. decoder->private_->frame.header.sample_rate = x*10;
  100847. }
  100848. /* read the CRC-8 byte */
  100849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100850. return false; /* read_callback_ sets the state for us */
  100851. crc8 = (FLAC__byte)x;
  100852. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  100853. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100854. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100855. return true;
  100856. }
  100857. /* calculate the sample number from the frame number if needed */
  100858. decoder->private_->next_fixed_block_size = 0;
  100859. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  100860. x = decoder->private_->frame.header.number.frame_number;
  100861. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  100862. if(decoder->private_->fixed_block_size)
  100863. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  100864. else if(decoder->private_->has_stream_info) {
  100865. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  100866. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  100867. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  100868. }
  100869. else
  100870. is_unparseable = true;
  100871. }
  100872. else if(x == 0) {
  100873. decoder->private_->frame.header.number.sample_number = 0;
  100874. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  100875. }
  100876. else {
  100877. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  100878. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  100879. }
  100880. }
  100881. if(is_unparseable) {
  100882. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100883. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100884. return true;
  100885. }
  100886. return true;
  100887. }
  100888. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100889. {
  100890. FLAC__uint32 x;
  100891. FLAC__bool wasted_bits;
  100892. unsigned i;
  100893. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  100894. return false; /* read_callback_ sets the state for us */
  100895. wasted_bits = (x & 1);
  100896. x &= 0xfe;
  100897. if(wasted_bits) {
  100898. unsigned u;
  100899. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  100900. return false; /* read_callback_ sets the state for us */
  100901. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  100902. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  100903. }
  100904. else
  100905. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  100906. /*
  100907. * Lots of magic numbers here
  100908. */
  100909. if(x & 0x80) {
  100910. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100911. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100912. return true;
  100913. }
  100914. else if(x == 0) {
  100915. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  100916. return false;
  100917. }
  100918. else if(x == 2) {
  100919. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  100920. return false;
  100921. }
  100922. else if(x < 16) {
  100923. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100924. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100925. return true;
  100926. }
  100927. else if(x <= 24) {
  100928. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  100929. return false;
  100930. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100931. return true;
  100932. }
  100933. else if(x < 64) {
  100934. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100935. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100936. return true;
  100937. }
  100938. else {
  100939. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  100940. return false;
  100941. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100942. return true;
  100943. }
  100944. if(wasted_bits && do_full_decode) {
  100945. x = decoder->private_->frame.subframes[channel].wasted_bits;
  100946. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100947. decoder->private_->output[channel][i] <<= x;
  100948. }
  100949. return true;
  100950. }
  100951. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  100952. {
  100953. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  100954. FLAC__int32 x;
  100955. unsigned i;
  100956. FLAC__int32 *output = decoder->private_->output[channel];
  100957. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100958. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  100959. return false; /* read_callback_ sets the state for us */
  100960. subframe->value = x;
  100961. /* decode the subframe */
  100962. if(do_full_decode) {
  100963. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100964. output[i] = x;
  100965. }
  100966. return true;
  100967. }
  100968. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  100969. {
  100970. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  100971. FLAC__int32 i32;
  100972. FLAC__uint32 u32;
  100973. unsigned u;
  100974. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  100975. subframe->residual = decoder->private_->residual[channel];
  100976. subframe->order = order;
  100977. /* read warm-up samples */
  100978. for(u = 0; u < order; u++) {
  100979. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  100980. return false; /* read_callback_ sets the state for us */
  100981. subframe->warmup[u] = i32;
  100982. }
  100983. /* read entropy coding method info */
  100984. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  100985. return false; /* read_callback_ sets the state for us */
  100986. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  100987. switch(subframe->entropy_coding_method.type) {
  100988. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  100989. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  100990. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  100991. return false; /* read_callback_ sets the state for us */
  100992. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  100993. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  100994. break;
  100995. default:
  100996. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  100997. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100998. return true;
  100999. }
  101000. /* read residual */
  101001. switch(subframe->entropy_coding_method.type) {
  101002. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101003. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101004. 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))
  101005. return false;
  101006. break;
  101007. default:
  101008. FLAC__ASSERT(0);
  101009. }
  101010. /* decode the subframe */
  101011. if(do_full_decode) {
  101012. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101013. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101014. }
  101015. return true;
  101016. }
  101017. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101018. {
  101019. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101020. FLAC__int32 i32;
  101021. FLAC__uint32 u32;
  101022. unsigned u;
  101023. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101024. subframe->residual = decoder->private_->residual[channel];
  101025. subframe->order = order;
  101026. /* read warm-up samples */
  101027. for(u = 0; u < order; u++) {
  101028. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101029. return false; /* read_callback_ sets the state for us */
  101030. subframe->warmup[u] = i32;
  101031. }
  101032. /* read qlp coeff precision */
  101033. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101034. return false; /* read_callback_ sets the state for us */
  101035. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101036. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101037. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101038. return true;
  101039. }
  101040. subframe->qlp_coeff_precision = u32+1;
  101041. /* read qlp shift */
  101042. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101043. return false; /* read_callback_ sets the state for us */
  101044. subframe->quantization_level = i32;
  101045. /* read quantized lp coefficiencts */
  101046. for(u = 0; u < order; u++) {
  101047. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101048. return false; /* read_callback_ sets the state for us */
  101049. subframe->qlp_coeff[u] = i32;
  101050. }
  101051. /* read entropy coding method info */
  101052. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101053. return false; /* read_callback_ sets the state for us */
  101054. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101055. switch(subframe->entropy_coding_method.type) {
  101056. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101057. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101058. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101059. return false; /* read_callback_ sets the state for us */
  101060. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101061. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101062. break;
  101063. default:
  101064. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101065. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101066. return true;
  101067. }
  101068. /* read residual */
  101069. switch(subframe->entropy_coding_method.type) {
  101070. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101071. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101072. 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))
  101073. return false;
  101074. break;
  101075. default:
  101076. FLAC__ASSERT(0);
  101077. }
  101078. /* decode the subframe */
  101079. if(do_full_decode) {
  101080. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101081. /*@@@@@@ technically not pessimistic enough, should be more like
  101082. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101083. */
  101084. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101085. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101086. if(order <= 8)
  101087. 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);
  101088. else
  101089. 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);
  101090. }
  101091. else
  101092. 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);
  101093. else
  101094. 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);
  101095. }
  101096. return true;
  101097. }
  101098. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101099. {
  101100. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101101. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101102. unsigned i;
  101103. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101104. subframe->data = residual;
  101105. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101106. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101107. return false; /* read_callback_ sets the state for us */
  101108. residual[i] = x;
  101109. }
  101110. /* decode the subframe */
  101111. if(do_full_decode)
  101112. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101113. return true;
  101114. }
  101115. 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)
  101116. {
  101117. FLAC__uint32 rice_parameter;
  101118. int i;
  101119. unsigned partition, sample, u;
  101120. const unsigned partitions = 1u << partition_order;
  101121. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101122. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101123. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101124. /* sanity checks */
  101125. if(partition_order == 0) {
  101126. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101127. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101128. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101129. return true;
  101130. }
  101131. }
  101132. else {
  101133. if(partition_samples < predictor_order) {
  101134. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101135. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101136. return true;
  101137. }
  101138. }
  101139. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101140. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101141. return false;
  101142. }
  101143. sample = 0;
  101144. for(partition = 0; partition < partitions; partition++) {
  101145. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101146. return false; /* read_callback_ sets the state for us */
  101147. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101148. if(rice_parameter < pesc) {
  101149. partitioned_rice_contents->raw_bits[partition] = 0;
  101150. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101151. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101152. return false; /* read_callback_ sets the state for us */
  101153. sample += u;
  101154. }
  101155. else {
  101156. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101157. return false; /* read_callback_ sets the state for us */
  101158. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101159. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101160. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101161. return false; /* read_callback_ sets the state for us */
  101162. residual[sample] = i;
  101163. }
  101164. }
  101165. }
  101166. return true;
  101167. }
  101168. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101169. {
  101170. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101171. FLAC__uint32 zero = 0;
  101172. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101173. return false; /* read_callback_ sets the state for us */
  101174. if(zero != 0) {
  101175. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101176. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101177. }
  101178. }
  101179. return true;
  101180. }
  101181. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101182. {
  101183. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101184. if(
  101185. #if FLAC__HAS_OGG
  101186. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101187. !decoder->private_->is_ogg &&
  101188. #endif
  101189. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101190. ) {
  101191. *bytes = 0;
  101192. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101193. return false;
  101194. }
  101195. else if(*bytes > 0) {
  101196. /* While seeking, it is possible for our seek to land in the
  101197. * middle of audio data that looks exactly like a frame header
  101198. * from a future version of an encoder. When that happens, our
  101199. * error callback will get an
  101200. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101201. * unparseable_frame_count. But there is a remote possibility
  101202. * that it is properly synced at such a "future-codec frame",
  101203. * so to make sure, we wait to see many "unparseable" errors in
  101204. * a row before bailing out.
  101205. */
  101206. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101207. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101208. return false;
  101209. }
  101210. else {
  101211. const FLAC__StreamDecoderReadStatus status =
  101212. #if FLAC__HAS_OGG
  101213. decoder->private_->is_ogg?
  101214. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101215. #endif
  101216. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101217. ;
  101218. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101219. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101220. return false;
  101221. }
  101222. else if(*bytes == 0) {
  101223. if(
  101224. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101225. (
  101226. #if FLAC__HAS_OGG
  101227. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101228. !decoder->private_->is_ogg &&
  101229. #endif
  101230. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101231. )
  101232. ) {
  101233. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101234. return false;
  101235. }
  101236. else
  101237. return true;
  101238. }
  101239. else
  101240. return true;
  101241. }
  101242. }
  101243. else {
  101244. /* abort to avoid a deadlock */
  101245. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101246. return false;
  101247. }
  101248. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101249. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101250. * and at the same time hit the end of the stream (for example, seeking
  101251. * to a point that is after the beginning of the last Ogg page). There
  101252. * is no way to report an Ogg sync loss through the callbacks (see note
  101253. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101254. * So to keep the decoder from stopping at this point we gate the call
  101255. * to the eof_callback and let the Ogg decoder aspect set the
  101256. * end-of-stream state when it is needed.
  101257. */
  101258. }
  101259. #if FLAC__HAS_OGG
  101260. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101261. {
  101262. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101263. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101264. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101265. /* we don't really have a way to handle lost sync via read
  101266. * callback so we'll let it pass and let the underlying
  101267. * FLAC decoder catch the error
  101268. */
  101269. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101270. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101271. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101272. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101273. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101274. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101275. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101276. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101277. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101278. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101279. default:
  101280. FLAC__ASSERT(0);
  101281. /* double protection */
  101282. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101283. }
  101284. }
  101285. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101286. {
  101287. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101288. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101289. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101290. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101291. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101292. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101293. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101294. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101295. default:
  101296. /* double protection: */
  101297. FLAC__ASSERT(0);
  101298. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101299. }
  101300. }
  101301. #endif
  101302. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101303. {
  101304. if(decoder->private_->is_seeking) {
  101305. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101306. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101307. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101308. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101309. #if FLAC__HAS_OGG
  101310. decoder->private_->got_a_frame = true;
  101311. #endif
  101312. decoder->private_->last_frame = *frame; /* save the frame */
  101313. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101314. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101315. /* kick out of seek mode */
  101316. decoder->private_->is_seeking = false;
  101317. /* shift out the samples before target_sample */
  101318. if(delta > 0) {
  101319. unsigned channel;
  101320. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101321. for(channel = 0; channel < frame->header.channels; channel++)
  101322. newbuffer[channel] = buffer[channel] + delta;
  101323. decoder->private_->last_frame.header.blocksize -= delta;
  101324. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101325. /* write the relevant samples */
  101326. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101327. }
  101328. else {
  101329. /* write the relevant samples */
  101330. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101331. }
  101332. }
  101333. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101334. }
  101335. /*
  101336. * If we never got STREAMINFO, turn off MD5 checking to save
  101337. * cycles since we don't have a sum to compare to anyway
  101338. */
  101339. if(!decoder->private_->has_stream_info)
  101340. decoder->private_->do_md5_checking = false;
  101341. if(decoder->private_->do_md5_checking) {
  101342. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101343. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101344. }
  101345. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101346. }
  101347. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101348. {
  101349. if(!decoder->private_->is_seeking)
  101350. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101351. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101352. decoder->private_->unparseable_frame_count++;
  101353. }
  101354. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101355. {
  101356. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101357. FLAC__int64 pos = -1;
  101358. int i;
  101359. unsigned approx_bytes_per_frame;
  101360. FLAC__bool first_seek = true;
  101361. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101362. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101363. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101364. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101365. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101366. /* take these from the current frame in case they've changed mid-stream */
  101367. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101368. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101369. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101370. /* use values from stream info if we didn't decode a frame */
  101371. if(channels == 0)
  101372. channels = decoder->private_->stream_info.data.stream_info.channels;
  101373. if(bps == 0)
  101374. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101375. /* we are just guessing here */
  101376. if(max_framesize > 0)
  101377. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101378. /*
  101379. * Check if it's a known fixed-blocksize stream. Note that though
  101380. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101381. * never get a STREAMINFO block when decoding so the value of
  101382. * min_blocksize might be zero.
  101383. */
  101384. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101385. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101386. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101387. }
  101388. else
  101389. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101390. /*
  101391. * First, we set an upper and lower bound on where in the
  101392. * stream we will search. For now we assume the worst case
  101393. * scenario, which is our best guess at the beginning of
  101394. * the first frame and end of the stream.
  101395. */
  101396. lower_bound = first_frame_offset;
  101397. lower_bound_sample = 0;
  101398. upper_bound = stream_length;
  101399. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101400. /*
  101401. * Now we refine the bounds if we have a seektable with
  101402. * suitable points. Note that according to the spec they
  101403. * must be ordered by ascending sample number.
  101404. *
  101405. * Note: to protect against invalid seek tables we will ignore points
  101406. * that have frame_samples==0 or sample_number>=total_samples
  101407. */
  101408. if(seek_table) {
  101409. FLAC__uint64 new_lower_bound = lower_bound;
  101410. FLAC__uint64 new_upper_bound = upper_bound;
  101411. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101412. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101413. /* find the closest seek point <= target_sample, if it exists */
  101414. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101415. if(
  101416. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101417. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101418. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101419. seek_table->points[i].sample_number <= target_sample
  101420. )
  101421. break;
  101422. }
  101423. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101424. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101425. new_lower_bound_sample = seek_table->points[i].sample_number;
  101426. }
  101427. /* find the closest seek point > target_sample, if it exists */
  101428. for(i = 0; i < (int)seek_table->num_points; i++) {
  101429. if(
  101430. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101431. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101432. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101433. seek_table->points[i].sample_number > target_sample
  101434. )
  101435. break;
  101436. }
  101437. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101438. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101439. new_upper_bound_sample = seek_table->points[i].sample_number;
  101440. }
  101441. /* final protection against unsorted seek tables; keep original values if bogus */
  101442. if(new_upper_bound >= new_lower_bound) {
  101443. lower_bound = new_lower_bound;
  101444. upper_bound = new_upper_bound;
  101445. lower_bound_sample = new_lower_bound_sample;
  101446. upper_bound_sample = new_upper_bound_sample;
  101447. }
  101448. }
  101449. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101450. /* there are 2 insidious ways that the following equality occurs, which
  101451. * we need to fix:
  101452. * 1) total_samples is 0 (unknown) and target_sample is 0
  101453. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101454. * exactly equal to the last seek point in the seek table; this
  101455. * means there is no seek point above it, and upper_bound_samples
  101456. * remains equal to the estimate (of target_samples) we made above
  101457. * in either case it does not hurt to move upper_bound_sample up by 1
  101458. */
  101459. if(upper_bound_sample == lower_bound_sample)
  101460. upper_bound_sample++;
  101461. decoder->private_->target_sample = target_sample;
  101462. while(1) {
  101463. /* check if the bounds are still ok */
  101464. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101465. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101466. return false;
  101467. }
  101468. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101469. #if defined _MSC_VER || defined __MINGW32__
  101470. /* with VC++ you have to spoon feed it the casting */
  101471. 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;
  101472. #else
  101473. 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;
  101474. #endif
  101475. #else
  101476. /* a little less accurate: */
  101477. if(upper_bound - lower_bound < 0xffffffff)
  101478. 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;
  101479. else /* @@@ WATCHOUT, ~2TB limit */
  101480. 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;
  101481. #endif
  101482. if(pos >= (FLAC__int64)upper_bound)
  101483. pos = (FLAC__int64)upper_bound - 1;
  101484. if(pos < (FLAC__int64)lower_bound)
  101485. pos = (FLAC__int64)lower_bound;
  101486. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101487. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101488. return false;
  101489. }
  101490. if(!FLAC__stream_decoder_flush(decoder)) {
  101491. /* above call sets the state for us */
  101492. return false;
  101493. }
  101494. /* Now we need to get a frame. First we need to reset our
  101495. * unparseable_frame_count; if we get too many unparseable
  101496. * frames in a row, the read callback will return
  101497. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101498. * FLAC__stream_decoder_process_single() to return false.
  101499. */
  101500. decoder->private_->unparseable_frame_count = 0;
  101501. if(!FLAC__stream_decoder_process_single(decoder)) {
  101502. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101503. return false;
  101504. }
  101505. /* our write callback will change the state when it gets to the target frame */
  101506. /* 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 */
  101507. #if 0
  101508. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101509. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101510. break;
  101511. #endif
  101512. if(!decoder->private_->is_seeking)
  101513. break;
  101514. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101515. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101516. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101517. if (pos == (FLAC__int64)lower_bound) {
  101518. /* can't move back any more than the first frame, something is fatally wrong */
  101519. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101520. return false;
  101521. }
  101522. /* our last move backwards wasn't big enough, try again */
  101523. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101524. continue;
  101525. }
  101526. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101527. first_seek = false;
  101528. /* make sure we are not seeking in corrupted stream */
  101529. if (this_frame_sample < lower_bound_sample) {
  101530. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101531. return false;
  101532. }
  101533. /* we need to narrow the search */
  101534. if(target_sample < this_frame_sample) {
  101535. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101536. /*@@@@@@ what will decode position be if at end of stream? */
  101537. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101538. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101539. return false;
  101540. }
  101541. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101542. }
  101543. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101544. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101545. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101546. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101547. return false;
  101548. }
  101549. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101550. }
  101551. }
  101552. return true;
  101553. }
  101554. #if FLAC__HAS_OGG
  101555. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101556. {
  101557. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101558. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101559. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101560. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101561. FLAC__bool did_a_seek;
  101562. unsigned iteration = 0;
  101563. /* In the first iterations, we will calculate the target byte position
  101564. * by the distance from the target sample to left_sample and
  101565. * right_sample (let's call it "proportional search"). After that, we
  101566. * will switch to binary search.
  101567. */
  101568. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101569. /* We will switch to a linear search once our current sample is less
  101570. * than this number of samples ahead of the target sample
  101571. */
  101572. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101573. /* If the total number of samples is unknown, use a large value, and
  101574. * force binary search immediately.
  101575. */
  101576. if(right_sample == 0) {
  101577. right_sample = (FLAC__uint64)(-1);
  101578. BINARY_SEARCH_AFTER_ITERATION = 0;
  101579. }
  101580. decoder->private_->target_sample = target_sample;
  101581. for( ; ; iteration++) {
  101582. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101583. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101584. pos = (right_pos + left_pos) / 2;
  101585. }
  101586. else {
  101587. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101588. #if defined _MSC_VER || defined __MINGW32__
  101589. /* with MSVC you have to spoon feed it the casting */
  101590. 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));
  101591. #else
  101592. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101593. #endif
  101594. #else
  101595. /* a little less accurate: */
  101596. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101597. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101598. else /* @@@ WATCHOUT, ~2TB limit */
  101599. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101600. #endif
  101601. /* @@@ TODO: might want to limit pos to some distance
  101602. * before EOF, to make sure we land before the last frame,
  101603. * thereby getting a this_frame_sample and so having a better
  101604. * estimate.
  101605. */
  101606. }
  101607. /* physical seek */
  101608. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101609. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101610. return false;
  101611. }
  101612. if(!FLAC__stream_decoder_flush(decoder)) {
  101613. /* above call sets the state for us */
  101614. return false;
  101615. }
  101616. did_a_seek = true;
  101617. }
  101618. else
  101619. did_a_seek = false;
  101620. decoder->private_->got_a_frame = false;
  101621. if(!FLAC__stream_decoder_process_single(decoder)) {
  101622. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101623. return false;
  101624. }
  101625. if(!decoder->private_->got_a_frame) {
  101626. if(did_a_seek) {
  101627. /* this can happen if we seek to a point after the last frame; we drop
  101628. * to binary search right away in this case to avoid any wasted
  101629. * iterations of proportional search.
  101630. */
  101631. right_pos = pos;
  101632. BINARY_SEARCH_AFTER_ITERATION = 0;
  101633. }
  101634. else {
  101635. /* this can probably only happen if total_samples is unknown and the
  101636. * target_sample is past the end of the stream
  101637. */
  101638. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101639. return false;
  101640. }
  101641. }
  101642. /* our write callback will change the state when it gets to the target frame */
  101643. else if(!decoder->private_->is_seeking) {
  101644. break;
  101645. }
  101646. else {
  101647. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101648. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101649. if (did_a_seek) {
  101650. if (this_frame_sample <= target_sample) {
  101651. /* The 'equal' case should not happen, since
  101652. * FLAC__stream_decoder_process_single()
  101653. * should recognize that it has hit the
  101654. * target sample and we would exit through
  101655. * the 'break' above.
  101656. */
  101657. FLAC__ASSERT(this_frame_sample != target_sample);
  101658. left_sample = this_frame_sample;
  101659. /* sanity check to avoid infinite loop */
  101660. if (left_pos == pos) {
  101661. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101662. return false;
  101663. }
  101664. left_pos = pos;
  101665. }
  101666. else if(this_frame_sample > target_sample) {
  101667. right_sample = this_frame_sample;
  101668. /* sanity check to avoid infinite loop */
  101669. if (right_pos == pos) {
  101670. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101671. return false;
  101672. }
  101673. right_pos = pos;
  101674. }
  101675. }
  101676. }
  101677. }
  101678. return true;
  101679. }
  101680. #endif
  101681. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101682. {
  101683. (void)client_data;
  101684. if(*bytes > 0) {
  101685. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  101686. if(ferror(decoder->private_->file))
  101687. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101688. else if(*bytes == 0)
  101689. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101690. else
  101691. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101692. }
  101693. else
  101694. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  101695. }
  101696. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101697. {
  101698. (void)client_data;
  101699. if(decoder->private_->file == stdin)
  101700. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  101701. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101702. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  101703. else
  101704. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  101705. }
  101706. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101707. {
  101708. off_t pos;
  101709. (void)client_data;
  101710. if(decoder->private_->file == stdin)
  101711. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  101712. else if((pos = ftello(decoder->private_->file)) < 0)
  101713. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  101714. else {
  101715. *absolute_byte_offset = (FLAC__uint64)pos;
  101716. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  101717. }
  101718. }
  101719. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  101720. {
  101721. struct stat filestats;
  101722. (void)client_data;
  101723. if(decoder->private_->file == stdin)
  101724. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  101725. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  101726. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  101727. else {
  101728. *stream_length = (FLAC__uint64)filestats.st_size;
  101729. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  101730. }
  101731. }
  101732. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  101733. {
  101734. (void)client_data;
  101735. return feof(decoder->private_->file)? true : false;
  101736. }
  101737. #endif
  101738. /*** End of inlined file: stream_decoder.c ***/
  101739. /*** Start of inlined file: stream_encoder.c ***/
  101740. /*** Start of inlined file: juce_FlacHeader.h ***/
  101741. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101742. // tasks..
  101743. #define VERSION "1.2.1"
  101744. #define FLAC__NO_DLL 1
  101745. #if JUCE_MSVC
  101746. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101747. #endif
  101748. #if JUCE_MAC
  101749. #define FLAC__SYS_DARWIN 1
  101750. #endif
  101751. /*** End of inlined file: juce_FlacHeader.h ***/
  101752. #if JUCE_USE_FLAC
  101753. #if HAVE_CONFIG_H
  101754. # include <config.h>
  101755. #endif
  101756. #if defined _MSC_VER || defined __MINGW32__
  101757. #include <io.h> /* for _setmode() */
  101758. #include <fcntl.h> /* for _O_BINARY */
  101759. #endif
  101760. #if defined __CYGWIN__ || defined __EMX__
  101761. #include <io.h> /* for setmode(), O_BINARY */
  101762. #include <fcntl.h> /* for _O_BINARY */
  101763. #endif
  101764. #include <limits.h>
  101765. #include <stdio.h>
  101766. #include <stdlib.h> /* for malloc() */
  101767. #include <string.h> /* for memcpy() */
  101768. #include <sys/types.h> /* for off_t */
  101769. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  101770. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  101771. #define fseeko fseek
  101772. #define ftello ftell
  101773. #endif
  101774. #endif
  101775. /*** Start of inlined file: stream_encoder.h ***/
  101776. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  101777. #define FLAC__PROTECTED__STREAM_ENCODER_H
  101778. #if FLAC__HAS_OGG
  101779. #include "private/ogg_encoder_aspect.h"
  101780. #endif
  101781. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101782. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  101783. typedef enum {
  101784. FLAC__APODIZATION_BARTLETT,
  101785. FLAC__APODIZATION_BARTLETT_HANN,
  101786. FLAC__APODIZATION_BLACKMAN,
  101787. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  101788. FLAC__APODIZATION_CONNES,
  101789. FLAC__APODIZATION_FLATTOP,
  101790. FLAC__APODIZATION_GAUSS,
  101791. FLAC__APODIZATION_HAMMING,
  101792. FLAC__APODIZATION_HANN,
  101793. FLAC__APODIZATION_KAISER_BESSEL,
  101794. FLAC__APODIZATION_NUTTALL,
  101795. FLAC__APODIZATION_RECTANGLE,
  101796. FLAC__APODIZATION_TRIANGLE,
  101797. FLAC__APODIZATION_TUKEY,
  101798. FLAC__APODIZATION_WELCH
  101799. } FLAC__ApodizationFunction;
  101800. typedef struct {
  101801. FLAC__ApodizationFunction type;
  101802. union {
  101803. struct {
  101804. FLAC__real stddev;
  101805. } gauss;
  101806. struct {
  101807. FLAC__real p;
  101808. } tukey;
  101809. } parameters;
  101810. } FLAC__ApodizationSpecification;
  101811. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101812. typedef struct FLAC__StreamEncoderProtected {
  101813. FLAC__StreamEncoderState state;
  101814. FLAC__bool verify;
  101815. FLAC__bool streamable_subset;
  101816. FLAC__bool do_md5;
  101817. FLAC__bool do_mid_side_stereo;
  101818. FLAC__bool loose_mid_side_stereo;
  101819. unsigned channels;
  101820. unsigned bits_per_sample;
  101821. unsigned sample_rate;
  101822. unsigned blocksize;
  101823. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101824. unsigned num_apodizations;
  101825. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  101826. #endif
  101827. unsigned max_lpc_order;
  101828. unsigned qlp_coeff_precision;
  101829. FLAC__bool do_qlp_coeff_prec_search;
  101830. FLAC__bool do_exhaustive_model_search;
  101831. FLAC__bool do_escape_coding;
  101832. unsigned min_residual_partition_order;
  101833. unsigned max_residual_partition_order;
  101834. unsigned rice_parameter_search_dist;
  101835. FLAC__uint64 total_samples_estimate;
  101836. FLAC__StreamMetadata **metadata;
  101837. unsigned num_metadata_blocks;
  101838. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  101839. #if FLAC__HAS_OGG
  101840. FLAC__OggEncoderAspect ogg_encoder_aspect;
  101841. #endif
  101842. } FLAC__StreamEncoderProtected;
  101843. #endif
  101844. /*** End of inlined file: stream_encoder.h ***/
  101845. #if FLAC__HAS_OGG
  101846. #include "include/private/ogg_helper.h"
  101847. #include "include/private/ogg_mapping.h"
  101848. #endif
  101849. /*** Start of inlined file: stream_encoder_framing.h ***/
  101850. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101851. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  101852. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  101853. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  101854. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101855. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101856. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101857. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  101858. #endif
  101859. /*** End of inlined file: stream_encoder_framing.h ***/
  101860. /*** Start of inlined file: window.h ***/
  101861. #ifndef FLAC__PRIVATE__WINDOW_H
  101862. #define FLAC__PRIVATE__WINDOW_H
  101863. #ifdef HAVE_CONFIG_H
  101864. #include <config.h>
  101865. #endif
  101866. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101867. /*
  101868. * FLAC__window_*()
  101869. * --------------------------------------------------------------------
  101870. * Calculates window coefficients according to different apodization
  101871. * functions.
  101872. *
  101873. * OUT window[0,L-1]
  101874. * IN L (number of points in window)
  101875. */
  101876. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  101877. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  101878. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  101879. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  101880. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  101881. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  101882. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  101883. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  101884. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  101885. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  101886. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  101887. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  101888. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  101889. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  101890. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  101891. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101892. #endif
  101893. /*** End of inlined file: window.h ***/
  101894. #ifndef FLaC__INLINE
  101895. #define FLaC__INLINE
  101896. #endif
  101897. #ifdef min
  101898. #undef min
  101899. #endif
  101900. #define min(x,y) ((x)<(y)?(x):(y))
  101901. #ifdef max
  101902. #undef max
  101903. #endif
  101904. #define max(x,y) ((x)>(y)?(x):(y))
  101905. /* Exact Rice codeword length calculation is off by default. The simple
  101906. * (and fast) estimation (of how many bits a residual value will be
  101907. * encoded with) in this encoder is very good, almost always yielding
  101908. * compression within 0.1% of exact calculation.
  101909. */
  101910. #undef EXACT_RICE_BITS_CALCULATION
  101911. /* Rice parameter searching is off by default. The simple (and fast)
  101912. * parameter estimation in this encoder is very good, almost always
  101913. * yielding compression within 0.1% of the optimal parameters.
  101914. */
  101915. #undef ENABLE_RICE_PARAMETER_SEARCH
  101916. typedef struct {
  101917. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  101918. unsigned size; /* of each data[] in samples */
  101919. unsigned tail;
  101920. } verify_input_fifo;
  101921. typedef struct {
  101922. const FLAC__byte *data;
  101923. unsigned capacity;
  101924. unsigned bytes;
  101925. } verify_output;
  101926. typedef enum {
  101927. ENCODER_IN_MAGIC = 0,
  101928. ENCODER_IN_METADATA = 1,
  101929. ENCODER_IN_AUDIO = 2
  101930. } EncoderStateHint;
  101931. static struct CompressionLevels {
  101932. FLAC__bool do_mid_side_stereo;
  101933. FLAC__bool loose_mid_side_stereo;
  101934. unsigned max_lpc_order;
  101935. unsigned qlp_coeff_precision;
  101936. FLAC__bool do_qlp_coeff_prec_search;
  101937. FLAC__bool do_escape_coding;
  101938. FLAC__bool do_exhaustive_model_search;
  101939. unsigned min_residual_partition_order;
  101940. unsigned max_residual_partition_order;
  101941. unsigned rice_parameter_search_dist;
  101942. } compression_levels_[] = {
  101943. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  101944. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  101945. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  101946. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  101947. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  101948. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  101949. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  101950. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  101951. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  101952. };
  101953. /***********************************************************************
  101954. *
  101955. * Private class method prototypes
  101956. *
  101957. ***********************************************************************/
  101958. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  101959. static void free_(FLAC__StreamEncoder *encoder);
  101960. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  101961. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  101962. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  101963. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  101964. #if FLAC__HAS_OGG
  101965. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  101966. #endif
  101967. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  101968. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  101969. static FLAC__bool process_subframe_(
  101970. FLAC__StreamEncoder *encoder,
  101971. unsigned min_partition_order,
  101972. unsigned max_partition_order,
  101973. const FLAC__FrameHeader *frame_header,
  101974. unsigned subframe_bps,
  101975. const FLAC__int32 integer_signal[],
  101976. FLAC__Subframe *subframe[2],
  101977. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101978. FLAC__int32 *residual[2],
  101979. unsigned *best_subframe,
  101980. unsigned *best_bits
  101981. );
  101982. static FLAC__bool add_subframe_(
  101983. FLAC__StreamEncoder *encoder,
  101984. unsigned blocksize,
  101985. unsigned subframe_bps,
  101986. const FLAC__Subframe *subframe,
  101987. FLAC__BitWriter *frame
  101988. );
  101989. static unsigned evaluate_constant_subframe_(
  101990. FLAC__StreamEncoder *encoder,
  101991. const FLAC__int32 signal,
  101992. unsigned blocksize,
  101993. unsigned subframe_bps,
  101994. FLAC__Subframe *subframe
  101995. );
  101996. static unsigned evaluate_fixed_subframe_(
  101997. FLAC__StreamEncoder *encoder,
  101998. const FLAC__int32 signal[],
  101999. FLAC__int32 residual[],
  102000. FLAC__uint64 abs_residual_partition_sums[],
  102001. unsigned raw_bits_per_partition[],
  102002. unsigned blocksize,
  102003. unsigned subframe_bps,
  102004. unsigned order,
  102005. unsigned rice_parameter,
  102006. unsigned rice_parameter_limit,
  102007. unsigned min_partition_order,
  102008. unsigned max_partition_order,
  102009. FLAC__bool do_escape_coding,
  102010. unsigned rice_parameter_search_dist,
  102011. FLAC__Subframe *subframe,
  102012. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102013. );
  102014. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102015. static unsigned evaluate_lpc_subframe_(
  102016. FLAC__StreamEncoder *encoder,
  102017. const FLAC__int32 signal[],
  102018. FLAC__int32 residual[],
  102019. FLAC__uint64 abs_residual_partition_sums[],
  102020. unsigned raw_bits_per_partition[],
  102021. const FLAC__real lp_coeff[],
  102022. unsigned blocksize,
  102023. unsigned subframe_bps,
  102024. unsigned order,
  102025. unsigned qlp_coeff_precision,
  102026. unsigned rice_parameter,
  102027. unsigned rice_parameter_limit,
  102028. unsigned min_partition_order,
  102029. unsigned max_partition_order,
  102030. FLAC__bool do_escape_coding,
  102031. unsigned rice_parameter_search_dist,
  102032. FLAC__Subframe *subframe,
  102033. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102034. );
  102035. #endif
  102036. static unsigned evaluate_verbatim_subframe_(
  102037. FLAC__StreamEncoder *encoder,
  102038. const FLAC__int32 signal[],
  102039. unsigned blocksize,
  102040. unsigned subframe_bps,
  102041. FLAC__Subframe *subframe
  102042. );
  102043. static unsigned find_best_partition_order_(
  102044. struct FLAC__StreamEncoderPrivate *private_,
  102045. const FLAC__int32 residual[],
  102046. FLAC__uint64 abs_residual_partition_sums[],
  102047. unsigned raw_bits_per_partition[],
  102048. unsigned residual_samples,
  102049. unsigned predictor_order,
  102050. unsigned rice_parameter,
  102051. unsigned rice_parameter_limit,
  102052. unsigned min_partition_order,
  102053. unsigned max_partition_order,
  102054. unsigned bps,
  102055. FLAC__bool do_escape_coding,
  102056. unsigned rice_parameter_search_dist,
  102057. FLAC__EntropyCodingMethod *best_ecm
  102058. );
  102059. static void precompute_partition_info_sums_(
  102060. const FLAC__int32 residual[],
  102061. FLAC__uint64 abs_residual_partition_sums[],
  102062. unsigned residual_samples,
  102063. unsigned predictor_order,
  102064. unsigned min_partition_order,
  102065. unsigned max_partition_order,
  102066. unsigned bps
  102067. );
  102068. static void precompute_partition_info_escapes_(
  102069. const FLAC__int32 residual[],
  102070. unsigned raw_bits_per_partition[],
  102071. unsigned residual_samples,
  102072. unsigned predictor_order,
  102073. unsigned min_partition_order,
  102074. unsigned max_partition_order
  102075. );
  102076. static FLAC__bool set_partitioned_rice_(
  102077. #ifdef EXACT_RICE_BITS_CALCULATION
  102078. const FLAC__int32 residual[],
  102079. #endif
  102080. const FLAC__uint64 abs_residual_partition_sums[],
  102081. const unsigned raw_bits_per_partition[],
  102082. const unsigned residual_samples,
  102083. const unsigned predictor_order,
  102084. const unsigned suggested_rice_parameter,
  102085. const unsigned rice_parameter_limit,
  102086. const unsigned rice_parameter_search_dist,
  102087. const unsigned partition_order,
  102088. const FLAC__bool search_for_escapes,
  102089. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102090. unsigned *bits
  102091. );
  102092. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102093. /* verify-related routines: */
  102094. static void append_to_verify_fifo_(
  102095. verify_input_fifo *fifo,
  102096. const FLAC__int32 * const input[],
  102097. unsigned input_offset,
  102098. unsigned channels,
  102099. unsigned wide_samples
  102100. );
  102101. static void append_to_verify_fifo_interleaved_(
  102102. verify_input_fifo *fifo,
  102103. const FLAC__int32 input[],
  102104. unsigned input_offset,
  102105. unsigned channels,
  102106. unsigned wide_samples
  102107. );
  102108. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102109. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102110. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102111. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102112. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102113. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102114. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102115. 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);
  102116. static FILE *get_binary_stdout_(void);
  102117. /***********************************************************************
  102118. *
  102119. * Private class data
  102120. *
  102121. ***********************************************************************/
  102122. typedef struct FLAC__StreamEncoderPrivate {
  102123. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102124. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102125. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102126. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102127. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102128. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102129. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102130. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102131. #endif
  102132. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102133. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102134. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102135. FLAC__int32 *residual_workspace_mid_side[2][2];
  102136. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102137. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102138. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102139. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102140. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102141. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102142. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102143. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102144. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102145. unsigned best_subframe_mid_side[2];
  102146. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102147. unsigned best_subframe_bits_mid_side[2];
  102148. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102149. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102150. FLAC__BitWriter *frame; /* the current frame being worked on */
  102151. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102152. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102153. FLAC__ChannelAssignment last_channel_assignment;
  102154. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102155. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102156. unsigned current_sample_number;
  102157. unsigned current_frame_number;
  102158. FLAC__MD5Context md5context;
  102159. FLAC__CPUInfo cpuinfo;
  102160. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102161. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102162. #else
  102163. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102164. #endif
  102165. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102166. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102167. 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[]);
  102168. 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[]);
  102169. 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[]);
  102170. #endif
  102171. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102172. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102173. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102174. FLAC__bool disable_constant_subframes;
  102175. FLAC__bool disable_fixed_subframes;
  102176. FLAC__bool disable_verbatim_subframes;
  102177. #if FLAC__HAS_OGG
  102178. FLAC__bool is_ogg;
  102179. #endif
  102180. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102181. FLAC__StreamEncoderSeekCallback seek_callback;
  102182. FLAC__StreamEncoderTellCallback tell_callback;
  102183. FLAC__StreamEncoderWriteCallback write_callback;
  102184. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102185. FLAC__StreamEncoderProgressCallback progress_callback;
  102186. void *client_data;
  102187. unsigned first_seekpoint_to_check;
  102188. FILE *file; /* only used when encoding to a file */
  102189. FLAC__uint64 bytes_written;
  102190. FLAC__uint64 samples_written;
  102191. unsigned frames_written;
  102192. unsigned total_frames_estimate;
  102193. /* unaligned (original) pointers to allocated data */
  102194. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102195. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102196. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102197. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102198. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102199. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102200. FLAC__real *windowed_signal_unaligned;
  102201. #endif
  102202. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102203. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102204. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102205. unsigned *raw_bits_per_partition_unaligned;
  102206. /*
  102207. * These fields have been moved here from private function local
  102208. * declarations merely to save stack space during encoding.
  102209. */
  102210. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102211. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102212. #endif
  102213. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102214. /*
  102215. * The data for the verify section
  102216. */
  102217. struct {
  102218. FLAC__StreamDecoder *decoder;
  102219. EncoderStateHint state_hint;
  102220. FLAC__bool needs_magic_hack;
  102221. verify_input_fifo input_fifo;
  102222. verify_output output;
  102223. struct {
  102224. FLAC__uint64 absolute_sample;
  102225. unsigned frame_number;
  102226. unsigned channel;
  102227. unsigned sample;
  102228. FLAC__int32 expected;
  102229. FLAC__int32 got;
  102230. } error_stats;
  102231. } verify;
  102232. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102233. } FLAC__StreamEncoderPrivate;
  102234. /***********************************************************************
  102235. *
  102236. * Public static class data
  102237. *
  102238. ***********************************************************************/
  102239. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102240. "FLAC__STREAM_ENCODER_OK",
  102241. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102242. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102243. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102244. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102245. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102246. "FLAC__STREAM_ENCODER_IO_ERROR",
  102247. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102248. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102249. };
  102250. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102251. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102252. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102253. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102254. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102255. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102256. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102257. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102258. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102259. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102260. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102261. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102262. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102263. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102264. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102265. };
  102266. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102267. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102268. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102269. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102270. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102271. };
  102272. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102273. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102274. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102275. };
  102276. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102277. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102278. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102279. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102280. };
  102281. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102282. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102283. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102284. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102285. };
  102286. /* Number of samples that will be overread to watch for end of stream. By
  102287. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102288. * always try to read blocksize+1 samples before encoding a block, so that
  102289. * even if the stream has a total sample count that is an integral multiple
  102290. * of the blocksize, we will still notice when we are encoding the last
  102291. * block. This is needed, for example, to correctly set the end-of-stream
  102292. * marker in Ogg FLAC.
  102293. *
  102294. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102295. * not really any reason to change it.
  102296. */
  102297. static const unsigned OVERREAD_ = 1;
  102298. /***********************************************************************
  102299. *
  102300. * Class constructor/destructor
  102301. *
  102302. */
  102303. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102304. {
  102305. FLAC__StreamEncoder *encoder;
  102306. unsigned i;
  102307. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102308. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102309. if(encoder == 0) {
  102310. return 0;
  102311. }
  102312. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102313. if(encoder->protected_ == 0) {
  102314. free(encoder);
  102315. return 0;
  102316. }
  102317. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102318. if(encoder->private_ == 0) {
  102319. free(encoder->protected_);
  102320. free(encoder);
  102321. return 0;
  102322. }
  102323. encoder->private_->frame = FLAC__bitwriter_new();
  102324. if(encoder->private_->frame == 0) {
  102325. free(encoder->private_);
  102326. free(encoder->protected_);
  102327. free(encoder);
  102328. return 0;
  102329. }
  102330. encoder->private_->file = 0;
  102331. set_defaults_enc(encoder);
  102332. encoder->private_->is_being_deleted = false;
  102333. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102334. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102335. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102336. }
  102337. for(i = 0; i < 2; i++) {
  102338. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102339. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102340. }
  102341. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102342. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102343. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102344. }
  102345. for(i = 0; i < 2; i++) {
  102346. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102347. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102348. }
  102349. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102350. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102351. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102352. }
  102353. for(i = 0; i < 2; i++) {
  102354. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102355. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102356. }
  102357. for(i = 0; i < 2; i++)
  102358. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102359. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102360. return encoder;
  102361. }
  102362. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102363. {
  102364. unsigned i;
  102365. FLAC__ASSERT(0 != encoder);
  102366. FLAC__ASSERT(0 != encoder->protected_);
  102367. FLAC__ASSERT(0 != encoder->private_);
  102368. FLAC__ASSERT(0 != encoder->private_->frame);
  102369. encoder->private_->is_being_deleted = true;
  102370. (void)FLAC__stream_encoder_finish(encoder);
  102371. if(0 != encoder->private_->verify.decoder)
  102372. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102373. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102374. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102375. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102376. }
  102377. for(i = 0; i < 2; i++) {
  102378. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102379. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102380. }
  102381. for(i = 0; i < 2; i++)
  102382. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102383. FLAC__bitwriter_delete(encoder->private_->frame);
  102384. free(encoder->private_);
  102385. free(encoder->protected_);
  102386. free(encoder);
  102387. }
  102388. /***********************************************************************
  102389. *
  102390. * Public class methods
  102391. *
  102392. ***********************************************************************/
  102393. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102394. FLAC__StreamEncoder *encoder,
  102395. FLAC__StreamEncoderReadCallback read_callback,
  102396. FLAC__StreamEncoderWriteCallback write_callback,
  102397. FLAC__StreamEncoderSeekCallback seek_callback,
  102398. FLAC__StreamEncoderTellCallback tell_callback,
  102399. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102400. void *client_data,
  102401. FLAC__bool is_ogg
  102402. )
  102403. {
  102404. unsigned i;
  102405. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102406. FLAC__ASSERT(0 != encoder);
  102407. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102408. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102409. #if !FLAC__HAS_OGG
  102410. if(is_ogg)
  102411. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102412. #endif
  102413. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102414. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102415. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102416. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102417. if(encoder->protected_->channels != 2) {
  102418. encoder->protected_->do_mid_side_stereo = false;
  102419. encoder->protected_->loose_mid_side_stereo = false;
  102420. }
  102421. else if(!encoder->protected_->do_mid_side_stereo)
  102422. encoder->protected_->loose_mid_side_stereo = false;
  102423. if(encoder->protected_->bits_per_sample >= 32)
  102424. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102425. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102426. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102427. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102428. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102429. if(encoder->protected_->blocksize == 0) {
  102430. if(encoder->protected_->max_lpc_order == 0)
  102431. encoder->protected_->blocksize = 1152;
  102432. else
  102433. encoder->protected_->blocksize = 4096;
  102434. }
  102435. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102436. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102437. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102438. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102439. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102440. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102441. if(encoder->protected_->qlp_coeff_precision == 0) {
  102442. if(encoder->protected_->bits_per_sample < 16) {
  102443. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102444. /* @@@ until then we'll make a guess */
  102445. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102446. }
  102447. else if(encoder->protected_->bits_per_sample == 16) {
  102448. if(encoder->protected_->blocksize <= 192)
  102449. encoder->protected_->qlp_coeff_precision = 7;
  102450. else if(encoder->protected_->blocksize <= 384)
  102451. encoder->protected_->qlp_coeff_precision = 8;
  102452. else if(encoder->protected_->blocksize <= 576)
  102453. encoder->protected_->qlp_coeff_precision = 9;
  102454. else if(encoder->protected_->blocksize <= 1152)
  102455. encoder->protected_->qlp_coeff_precision = 10;
  102456. else if(encoder->protected_->blocksize <= 2304)
  102457. encoder->protected_->qlp_coeff_precision = 11;
  102458. else if(encoder->protected_->blocksize <= 4608)
  102459. encoder->protected_->qlp_coeff_precision = 12;
  102460. else
  102461. encoder->protected_->qlp_coeff_precision = 13;
  102462. }
  102463. else {
  102464. if(encoder->protected_->blocksize <= 384)
  102465. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102466. else if(encoder->protected_->blocksize <= 1152)
  102467. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102468. else
  102469. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102470. }
  102471. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102472. }
  102473. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102474. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102475. if(encoder->protected_->streamable_subset) {
  102476. if(
  102477. encoder->protected_->blocksize != 192 &&
  102478. encoder->protected_->blocksize != 576 &&
  102479. encoder->protected_->blocksize != 1152 &&
  102480. encoder->protected_->blocksize != 2304 &&
  102481. encoder->protected_->blocksize != 4608 &&
  102482. encoder->protected_->blocksize != 256 &&
  102483. encoder->protected_->blocksize != 512 &&
  102484. encoder->protected_->blocksize != 1024 &&
  102485. encoder->protected_->blocksize != 2048 &&
  102486. encoder->protected_->blocksize != 4096 &&
  102487. encoder->protected_->blocksize != 8192 &&
  102488. encoder->protected_->blocksize != 16384
  102489. )
  102490. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102491. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102492. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102493. if(
  102494. encoder->protected_->bits_per_sample != 8 &&
  102495. encoder->protected_->bits_per_sample != 12 &&
  102496. encoder->protected_->bits_per_sample != 16 &&
  102497. encoder->protected_->bits_per_sample != 20 &&
  102498. encoder->protected_->bits_per_sample != 24
  102499. )
  102500. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102501. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102502. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102503. if(
  102504. encoder->protected_->sample_rate <= 48000 &&
  102505. (
  102506. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102507. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102508. )
  102509. ) {
  102510. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102511. }
  102512. }
  102513. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102514. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102515. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102516. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102517. #if FLAC__HAS_OGG
  102518. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102519. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102520. unsigned i;
  102521. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102522. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102523. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102524. for( ; i > 0; i--)
  102525. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102526. encoder->protected_->metadata[0] = vc;
  102527. break;
  102528. }
  102529. }
  102530. }
  102531. #endif
  102532. /* keep track of any SEEKTABLE block */
  102533. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102534. unsigned i;
  102535. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102536. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102537. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102538. break; /* take only the first one */
  102539. }
  102540. }
  102541. }
  102542. /* validate metadata */
  102543. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102544. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102545. metadata_has_seektable = false;
  102546. metadata_has_vorbis_comment = false;
  102547. metadata_picture_has_type1 = false;
  102548. metadata_picture_has_type2 = false;
  102549. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102550. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102551. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102552. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102553. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102554. if(metadata_has_seektable) /* only one is allowed */
  102555. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102556. metadata_has_seektable = true;
  102557. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102558. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102559. }
  102560. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102561. if(metadata_has_vorbis_comment) /* only one is allowed */
  102562. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102563. metadata_has_vorbis_comment = true;
  102564. }
  102565. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102566. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102567. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102568. }
  102569. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102570. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102571. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102572. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102573. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102574. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102575. metadata_picture_has_type1 = true;
  102576. /* standard icon must be 32x32 pixel PNG */
  102577. if(
  102578. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102579. (
  102580. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102581. m->data.picture.width != 32 ||
  102582. m->data.picture.height != 32
  102583. )
  102584. )
  102585. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102586. }
  102587. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102588. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102589. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102590. metadata_picture_has_type2 = true;
  102591. }
  102592. }
  102593. }
  102594. encoder->private_->input_capacity = 0;
  102595. for(i = 0; i < encoder->protected_->channels; i++) {
  102596. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102597. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102598. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102599. #endif
  102600. }
  102601. for(i = 0; i < 2; i++) {
  102602. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102603. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102604. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102605. #endif
  102606. }
  102607. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102608. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102609. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102610. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102611. #endif
  102612. for(i = 0; i < encoder->protected_->channels; i++) {
  102613. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102614. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102615. encoder->private_->best_subframe[i] = 0;
  102616. }
  102617. for(i = 0; i < 2; i++) {
  102618. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102619. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102620. encoder->private_->best_subframe_mid_side[i] = 0;
  102621. }
  102622. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102623. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102624. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102625. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102626. #else
  102627. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102628. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102629. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102630. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102631. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102632. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102633. 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);
  102634. #endif
  102635. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102636. encoder->private_->loose_mid_side_stereo_frames = 1;
  102637. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102638. encoder->private_->current_sample_number = 0;
  102639. encoder->private_->current_frame_number = 0;
  102640. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102641. 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? */
  102642. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102643. /*
  102644. * get the CPU info and set the function pointers
  102645. */
  102646. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102647. /* first default to the non-asm routines */
  102648. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102649. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102650. #endif
  102651. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102652. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102653. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102654. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102655. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102656. #endif
  102657. /* now override with asm where appropriate */
  102658. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102659. # ifndef FLAC__NO_ASM
  102660. if(encoder->private_->cpuinfo.use_asm) {
  102661. # ifdef FLAC__CPU_IA32
  102662. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102663. # ifdef FLAC__HAS_NASM
  102664. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102665. if(encoder->protected_->max_lpc_order < 4)
  102666. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102667. else if(encoder->protected_->max_lpc_order < 8)
  102668. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  102669. else if(encoder->protected_->max_lpc_order < 12)
  102670. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  102671. else
  102672. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102673. }
  102674. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  102675. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  102676. else
  102677. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  102678. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  102679. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102680. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  102681. }
  102682. else {
  102683. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102684. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  102685. }
  102686. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  102687. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  102688. # endif /* FLAC__HAS_NASM */
  102689. # endif /* FLAC__CPU_IA32 */
  102690. }
  102691. # endif /* !FLAC__NO_ASM */
  102692. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  102693. /* finally override based on wide-ness if necessary */
  102694. if(encoder->private_->use_wide_by_block) {
  102695. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  102696. }
  102697. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  102698. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  102699. #if FLAC__HAS_OGG
  102700. encoder->private_->is_ogg = is_ogg;
  102701. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  102702. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  102703. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102704. }
  102705. #endif
  102706. encoder->private_->read_callback = read_callback;
  102707. encoder->private_->write_callback = write_callback;
  102708. encoder->private_->seek_callback = seek_callback;
  102709. encoder->private_->tell_callback = tell_callback;
  102710. encoder->private_->metadata_callback = metadata_callback;
  102711. encoder->private_->client_data = client_data;
  102712. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  102713. /* the above function sets the state for us in case of an error */
  102714. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102715. }
  102716. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  102717. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102718. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102719. }
  102720. /*
  102721. * Set up the verify stuff if necessary
  102722. */
  102723. if(encoder->protected_->verify) {
  102724. /*
  102725. * First, set up the fifo which will hold the
  102726. * original signal to compare against
  102727. */
  102728. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  102729. for(i = 0; i < encoder->protected_->channels; i++) {
  102730. 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))) {
  102731. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  102732. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102733. }
  102734. }
  102735. encoder->private_->verify.input_fifo.tail = 0;
  102736. /*
  102737. * Now set up a stream decoder for verification
  102738. */
  102739. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  102740. if(0 == encoder->private_->verify.decoder) {
  102741. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102742. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102743. }
  102744. 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) {
  102745. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102746. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102747. }
  102748. }
  102749. encoder->private_->verify.error_stats.absolute_sample = 0;
  102750. encoder->private_->verify.error_stats.frame_number = 0;
  102751. encoder->private_->verify.error_stats.channel = 0;
  102752. encoder->private_->verify.error_stats.sample = 0;
  102753. encoder->private_->verify.error_stats.expected = 0;
  102754. encoder->private_->verify.error_stats.got = 0;
  102755. /*
  102756. * These must be done before we write any metadata, because that
  102757. * calls the write_callback, which uses these values.
  102758. */
  102759. encoder->private_->first_seekpoint_to_check = 0;
  102760. encoder->private_->samples_written = 0;
  102761. encoder->protected_->streaminfo_offset = 0;
  102762. encoder->protected_->seektable_offset = 0;
  102763. encoder->protected_->audio_offset = 0;
  102764. /*
  102765. * write the stream header
  102766. */
  102767. if(encoder->protected_->verify)
  102768. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  102769. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  102770. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102771. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102772. }
  102773. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102774. /* the above function sets the state for us in case of an error */
  102775. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102776. }
  102777. /*
  102778. * write the STREAMINFO metadata block
  102779. */
  102780. if(encoder->protected_->verify)
  102781. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  102782. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  102783. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  102784. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  102785. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  102786. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  102787. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  102788. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  102789. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  102790. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  102791. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  102792. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  102793. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  102794. if(encoder->protected_->do_md5)
  102795. FLAC__MD5Init(&encoder->private_->md5context);
  102796. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  102797. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102798. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102799. }
  102800. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102801. /* the above function sets the state for us in case of an error */
  102802. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102803. }
  102804. /*
  102805. * Now that the STREAMINFO block is written, we can init this to an
  102806. * absurdly-high value...
  102807. */
  102808. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  102809. /* ... and clear this to 0 */
  102810. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  102811. /*
  102812. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  102813. * if not, we will write an empty one (FLAC__add_metadata_block()
  102814. * automatically supplies the vendor string).
  102815. *
  102816. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  102817. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  102818. * true it will have already insured that the metadata list is properly
  102819. * ordered.)
  102820. */
  102821. if(!metadata_has_vorbis_comment) {
  102822. FLAC__StreamMetadata vorbis_comment;
  102823. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  102824. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  102825. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  102826. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  102827. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  102828. vorbis_comment.data.vorbis_comment.num_comments = 0;
  102829. vorbis_comment.data.vorbis_comment.comments = 0;
  102830. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  102831. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102832. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102833. }
  102834. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102835. /* the above function sets the state for us in case of an error */
  102836. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102837. }
  102838. }
  102839. /*
  102840. * write the user's metadata blocks
  102841. */
  102842. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102843. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  102844. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  102845. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  102846. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102847. }
  102848. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  102849. /* the above function sets the state for us in case of an error */
  102850. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102851. }
  102852. }
  102853. /* now that all the metadata is written, we save the stream offset */
  102854. 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 */
  102855. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  102856. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102857. }
  102858. if(encoder->protected_->verify)
  102859. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  102860. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102861. }
  102862. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  102863. FLAC__StreamEncoder *encoder,
  102864. FLAC__StreamEncoderWriteCallback write_callback,
  102865. FLAC__StreamEncoderSeekCallback seek_callback,
  102866. FLAC__StreamEncoderTellCallback tell_callback,
  102867. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102868. void *client_data
  102869. )
  102870. {
  102871. return init_stream_internal_enc(
  102872. encoder,
  102873. /*read_callback=*/0,
  102874. write_callback,
  102875. seek_callback,
  102876. tell_callback,
  102877. metadata_callback,
  102878. client_data,
  102879. /*is_ogg=*/false
  102880. );
  102881. }
  102882. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  102883. FLAC__StreamEncoder *encoder,
  102884. FLAC__StreamEncoderReadCallback read_callback,
  102885. FLAC__StreamEncoderWriteCallback write_callback,
  102886. FLAC__StreamEncoderSeekCallback seek_callback,
  102887. FLAC__StreamEncoderTellCallback tell_callback,
  102888. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102889. void *client_data
  102890. )
  102891. {
  102892. return init_stream_internal_enc(
  102893. encoder,
  102894. read_callback,
  102895. write_callback,
  102896. seek_callback,
  102897. tell_callback,
  102898. metadata_callback,
  102899. client_data,
  102900. /*is_ogg=*/true
  102901. );
  102902. }
  102903. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  102904. FLAC__StreamEncoder *encoder,
  102905. FILE *file,
  102906. FLAC__StreamEncoderProgressCallback progress_callback,
  102907. void *client_data,
  102908. FLAC__bool is_ogg
  102909. )
  102910. {
  102911. FLAC__StreamEncoderInitStatus init_status;
  102912. FLAC__ASSERT(0 != encoder);
  102913. FLAC__ASSERT(0 != file);
  102914. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102915. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102916. /* double protection */
  102917. if(file == 0) {
  102918. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102919. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102920. }
  102921. /*
  102922. * To make sure that our file does not go unclosed after an error, we
  102923. * must assign the FILE pointer before any further error can occur in
  102924. * this routine.
  102925. */
  102926. if(file == stdout)
  102927. file = get_binary_stdout_(); /* just to be safe */
  102928. encoder->private_->file = file;
  102929. encoder->private_->progress_callback = progress_callback;
  102930. encoder->private_->bytes_written = 0;
  102931. encoder->private_->samples_written = 0;
  102932. encoder->private_->frames_written = 0;
  102933. init_status = init_stream_internal_enc(
  102934. encoder,
  102935. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  102936. file_write_callback_,
  102937. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  102938. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  102939. /*metadata_callback=*/0,
  102940. client_data,
  102941. is_ogg
  102942. );
  102943. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  102944. /* the above function sets the state for us in case of an error */
  102945. return init_status;
  102946. }
  102947. {
  102948. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  102949. FLAC__ASSERT(blocksize != 0);
  102950. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  102951. }
  102952. return init_status;
  102953. }
  102954. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  102955. FLAC__StreamEncoder *encoder,
  102956. FILE *file,
  102957. FLAC__StreamEncoderProgressCallback progress_callback,
  102958. void *client_data
  102959. )
  102960. {
  102961. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  102962. }
  102963. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  102964. FLAC__StreamEncoder *encoder,
  102965. FILE *file,
  102966. FLAC__StreamEncoderProgressCallback progress_callback,
  102967. void *client_data
  102968. )
  102969. {
  102970. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  102971. }
  102972. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  102973. FLAC__StreamEncoder *encoder,
  102974. const char *filename,
  102975. FLAC__StreamEncoderProgressCallback progress_callback,
  102976. void *client_data,
  102977. FLAC__bool is_ogg
  102978. )
  102979. {
  102980. FILE *file;
  102981. FLAC__ASSERT(0 != encoder);
  102982. /*
  102983. * To make sure that our file does not go unclosed after an error, we
  102984. * have to do the same entrance checks here that are later performed
  102985. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  102986. */
  102987. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102988. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102989. file = filename? fopen(filename, "w+b") : stdout;
  102990. if(file == 0) {
  102991. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  102992. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  102993. }
  102994. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  102995. }
  102996. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  102997. FLAC__StreamEncoder *encoder,
  102998. const char *filename,
  102999. FLAC__StreamEncoderProgressCallback progress_callback,
  103000. void *client_data
  103001. )
  103002. {
  103003. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103004. }
  103005. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103006. FLAC__StreamEncoder *encoder,
  103007. const char *filename,
  103008. FLAC__StreamEncoderProgressCallback progress_callback,
  103009. void *client_data
  103010. )
  103011. {
  103012. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103013. }
  103014. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103015. {
  103016. FLAC__bool error = false;
  103017. FLAC__ASSERT(0 != encoder);
  103018. FLAC__ASSERT(0 != encoder->private_);
  103019. FLAC__ASSERT(0 != encoder->protected_);
  103020. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103021. return true;
  103022. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103023. if(encoder->private_->current_sample_number != 0) {
  103024. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103025. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103026. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103027. error = true;
  103028. }
  103029. }
  103030. if(encoder->protected_->do_md5)
  103031. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103032. if(!encoder->private_->is_being_deleted) {
  103033. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103034. if(encoder->private_->seek_callback) {
  103035. #if FLAC__HAS_OGG
  103036. if(encoder->private_->is_ogg)
  103037. update_ogg_metadata_(encoder);
  103038. else
  103039. #endif
  103040. update_metadata_(encoder);
  103041. /* check if an error occurred while updating metadata */
  103042. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103043. error = true;
  103044. }
  103045. if(encoder->private_->metadata_callback)
  103046. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103047. }
  103048. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103049. if(!error)
  103050. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103051. error = true;
  103052. }
  103053. }
  103054. if(0 != encoder->private_->file) {
  103055. if(encoder->private_->file != stdout)
  103056. fclose(encoder->private_->file);
  103057. encoder->private_->file = 0;
  103058. }
  103059. #if FLAC__HAS_OGG
  103060. if(encoder->private_->is_ogg)
  103061. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103062. #endif
  103063. free_(encoder);
  103064. set_defaults_enc(encoder);
  103065. if(!error)
  103066. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103067. return !error;
  103068. }
  103069. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103070. {
  103071. FLAC__ASSERT(0 != encoder);
  103072. FLAC__ASSERT(0 != encoder->private_);
  103073. FLAC__ASSERT(0 != encoder->protected_);
  103074. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103075. return false;
  103076. #if FLAC__HAS_OGG
  103077. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103078. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103079. return true;
  103080. #else
  103081. (void)value;
  103082. return false;
  103083. #endif
  103084. }
  103085. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103086. {
  103087. FLAC__ASSERT(0 != encoder);
  103088. FLAC__ASSERT(0 != encoder->private_);
  103089. FLAC__ASSERT(0 != encoder->protected_);
  103090. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103091. return false;
  103092. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103093. encoder->protected_->verify = value;
  103094. #endif
  103095. return true;
  103096. }
  103097. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103098. {
  103099. FLAC__ASSERT(0 != encoder);
  103100. FLAC__ASSERT(0 != encoder->private_);
  103101. FLAC__ASSERT(0 != encoder->protected_);
  103102. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103103. return false;
  103104. encoder->protected_->streamable_subset = value;
  103105. return true;
  103106. }
  103107. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103108. {
  103109. FLAC__ASSERT(0 != encoder);
  103110. FLAC__ASSERT(0 != encoder->private_);
  103111. FLAC__ASSERT(0 != encoder->protected_);
  103112. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103113. return false;
  103114. encoder->protected_->do_md5 = value;
  103115. return true;
  103116. }
  103117. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103118. {
  103119. FLAC__ASSERT(0 != encoder);
  103120. FLAC__ASSERT(0 != encoder->private_);
  103121. FLAC__ASSERT(0 != encoder->protected_);
  103122. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103123. return false;
  103124. encoder->protected_->channels = value;
  103125. return true;
  103126. }
  103127. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103128. {
  103129. FLAC__ASSERT(0 != encoder);
  103130. FLAC__ASSERT(0 != encoder->private_);
  103131. FLAC__ASSERT(0 != encoder->protected_);
  103132. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103133. return false;
  103134. encoder->protected_->bits_per_sample = value;
  103135. return true;
  103136. }
  103137. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103138. {
  103139. FLAC__ASSERT(0 != encoder);
  103140. FLAC__ASSERT(0 != encoder->private_);
  103141. FLAC__ASSERT(0 != encoder->protected_);
  103142. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103143. return false;
  103144. encoder->protected_->sample_rate = value;
  103145. return true;
  103146. }
  103147. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103148. {
  103149. FLAC__bool ok = true;
  103150. FLAC__ASSERT(0 != encoder);
  103151. FLAC__ASSERT(0 != encoder->private_);
  103152. FLAC__ASSERT(0 != encoder->protected_);
  103153. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103154. return false;
  103155. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103156. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103157. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103158. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103159. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103160. #if 0
  103161. /* was: */
  103162. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103163. /* but it's too hard to specify the string in a locale-specific way */
  103164. #else
  103165. encoder->protected_->num_apodizations = 1;
  103166. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103167. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103168. #endif
  103169. #endif
  103170. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103171. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103172. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103173. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103174. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103175. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103176. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103177. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103178. return ok;
  103179. }
  103180. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103181. {
  103182. FLAC__ASSERT(0 != encoder);
  103183. FLAC__ASSERT(0 != encoder->private_);
  103184. FLAC__ASSERT(0 != encoder->protected_);
  103185. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103186. return false;
  103187. encoder->protected_->blocksize = value;
  103188. return true;
  103189. }
  103190. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103191. {
  103192. FLAC__ASSERT(0 != encoder);
  103193. FLAC__ASSERT(0 != encoder->private_);
  103194. FLAC__ASSERT(0 != encoder->protected_);
  103195. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103196. return false;
  103197. encoder->protected_->do_mid_side_stereo = value;
  103198. return true;
  103199. }
  103200. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103201. {
  103202. FLAC__ASSERT(0 != encoder);
  103203. FLAC__ASSERT(0 != encoder->private_);
  103204. FLAC__ASSERT(0 != encoder->protected_);
  103205. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103206. return false;
  103207. encoder->protected_->loose_mid_side_stereo = value;
  103208. return true;
  103209. }
  103210. /*@@@@add to tests*/
  103211. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103212. {
  103213. FLAC__ASSERT(0 != encoder);
  103214. FLAC__ASSERT(0 != encoder->private_);
  103215. FLAC__ASSERT(0 != encoder->protected_);
  103216. FLAC__ASSERT(0 != specification);
  103217. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103218. return false;
  103219. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103220. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103221. #else
  103222. encoder->protected_->num_apodizations = 0;
  103223. while(1) {
  103224. const char *s = strchr(specification, ';');
  103225. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103226. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103227. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103228. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103229. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103230. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103231. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103232. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103233. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103234. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103235. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103236. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103237. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103238. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103239. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103240. if (stddev > 0.0 && stddev <= 0.5) {
  103241. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103242. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103243. }
  103244. }
  103245. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103246. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103247. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103248. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103249. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103250. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103251. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103252. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103253. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103254. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103255. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103256. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103257. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103258. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103259. if (p >= 0.0 && p <= 1.0) {
  103260. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103261. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103262. }
  103263. }
  103264. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103265. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103266. if (encoder->protected_->num_apodizations == 32)
  103267. break;
  103268. if (s)
  103269. specification = s+1;
  103270. else
  103271. break;
  103272. }
  103273. if(encoder->protected_->num_apodizations == 0) {
  103274. encoder->protected_->num_apodizations = 1;
  103275. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103276. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103277. }
  103278. #endif
  103279. return true;
  103280. }
  103281. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103282. {
  103283. FLAC__ASSERT(0 != encoder);
  103284. FLAC__ASSERT(0 != encoder->private_);
  103285. FLAC__ASSERT(0 != encoder->protected_);
  103286. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103287. return false;
  103288. encoder->protected_->max_lpc_order = value;
  103289. return true;
  103290. }
  103291. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103292. {
  103293. FLAC__ASSERT(0 != encoder);
  103294. FLAC__ASSERT(0 != encoder->private_);
  103295. FLAC__ASSERT(0 != encoder->protected_);
  103296. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103297. return false;
  103298. encoder->protected_->qlp_coeff_precision = value;
  103299. return true;
  103300. }
  103301. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103302. {
  103303. FLAC__ASSERT(0 != encoder);
  103304. FLAC__ASSERT(0 != encoder->private_);
  103305. FLAC__ASSERT(0 != encoder->protected_);
  103306. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103307. return false;
  103308. encoder->protected_->do_qlp_coeff_prec_search = value;
  103309. return true;
  103310. }
  103311. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103312. {
  103313. FLAC__ASSERT(0 != encoder);
  103314. FLAC__ASSERT(0 != encoder->private_);
  103315. FLAC__ASSERT(0 != encoder->protected_);
  103316. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103317. return false;
  103318. #if 0
  103319. /*@@@ deprecated: */
  103320. encoder->protected_->do_escape_coding = value;
  103321. #else
  103322. (void)value;
  103323. #endif
  103324. return true;
  103325. }
  103326. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103327. {
  103328. FLAC__ASSERT(0 != encoder);
  103329. FLAC__ASSERT(0 != encoder->private_);
  103330. FLAC__ASSERT(0 != encoder->protected_);
  103331. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103332. return false;
  103333. encoder->protected_->do_exhaustive_model_search = value;
  103334. return true;
  103335. }
  103336. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103337. {
  103338. FLAC__ASSERT(0 != encoder);
  103339. FLAC__ASSERT(0 != encoder->private_);
  103340. FLAC__ASSERT(0 != encoder->protected_);
  103341. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103342. return false;
  103343. encoder->protected_->min_residual_partition_order = value;
  103344. return true;
  103345. }
  103346. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103347. {
  103348. FLAC__ASSERT(0 != encoder);
  103349. FLAC__ASSERT(0 != encoder->private_);
  103350. FLAC__ASSERT(0 != encoder->protected_);
  103351. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103352. return false;
  103353. encoder->protected_->max_residual_partition_order = value;
  103354. return true;
  103355. }
  103356. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103357. {
  103358. FLAC__ASSERT(0 != encoder);
  103359. FLAC__ASSERT(0 != encoder->private_);
  103360. FLAC__ASSERT(0 != encoder->protected_);
  103361. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103362. return false;
  103363. #if 0
  103364. /*@@@ deprecated: */
  103365. encoder->protected_->rice_parameter_search_dist = value;
  103366. #else
  103367. (void)value;
  103368. #endif
  103369. return true;
  103370. }
  103371. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103372. {
  103373. FLAC__ASSERT(0 != encoder);
  103374. FLAC__ASSERT(0 != encoder->private_);
  103375. FLAC__ASSERT(0 != encoder->protected_);
  103376. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103377. return false;
  103378. encoder->protected_->total_samples_estimate = value;
  103379. return true;
  103380. }
  103381. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103382. {
  103383. FLAC__ASSERT(0 != encoder);
  103384. FLAC__ASSERT(0 != encoder->private_);
  103385. FLAC__ASSERT(0 != encoder->protected_);
  103386. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103387. return false;
  103388. if(0 == metadata)
  103389. num_blocks = 0;
  103390. if(0 == num_blocks)
  103391. metadata = 0;
  103392. /* realloc() does not do exactly what we want so... */
  103393. if(encoder->protected_->metadata) {
  103394. free(encoder->protected_->metadata);
  103395. encoder->protected_->metadata = 0;
  103396. encoder->protected_->num_metadata_blocks = 0;
  103397. }
  103398. if(num_blocks) {
  103399. FLAC__StreamMetadata **m;
  103400. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103401. return false;
  103402. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103403. encoder->protected_->metadata = m;
  103404. encoder->protected_->num_metadata_blocks = num_blocks;
  103405. }
  103406. #if FLAC__HAS_OGG
  103407. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103408. return false;
  103409. #endif
  103410. return true;
  103411. }
  103412. /*
  103413. * These three functions are not static, but not publically exposed in
  103414. * include/FLAC/ either. They are used by the test suite.
  103415. */
  103416. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103417. {
  103418. FLAC__ASSERT(0 != encoder);
  103419. FLAC__ASSERT(0 != encoder->private_);
  103420. FLAC__ASSERT(0 != encoder->protected_);
  103421. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103422. return false;
  103423. encoder->private_->disable_constant_subframes = value;
  103424. return true;
  103425. }
  103426. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103427. {
  103428. FLAC__ASSERT(0 != encoder);
  103429. FLAC__ASSERT(0 != encoder->private_);
  103430. FLAC__ASSERT(0 != encoder->protected_);
  103431. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103432. return false;
  103433. encoder->private_->disable_fixed_subframes = value;
  103434. return true;
  103435. }
  103436. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103437. {
  103438. FLAC__ASSERT(0 != encoder);
  103439. FLAC__ASSERT(0 != encoder->private_);
  103440. FLAC__ASSERT(0 != encoder->protected_);
  103441. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103442. return false;
  103443. encoder->private_->disable_verbatim_subframes = value;
  103444. return true;
  103445. }
  103446. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103447. {
  103448. FLAC__ASSERT(0 != encoder);
  103449. FLAC__ASSERT(0 != encoder->private_);
  103450. FLAC__ASSERT(0 != encoder->protected_);
  103451. return encoder->protected_->state;
  103452. }
  103453. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103454. {
  103455. FLAC__ASSERT(0 != encoder);
  103456. FLAC__ASSERT(0 != encoder->private_);
  103457. FLAC__ASSERT(0 != encoder->protected_);
  103458. if(encoder->protected_->verify)
  103459. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103460. else
  103461. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103462. }
  103463. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103464. {
  103465. FLAC__ASSERT(0 != encoder);
  103466. FLAC__ASSERT(0 != encoder->private_);
  103467. FLAC__ASSERT(0 != encoder->protected_);
  103468. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103469. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103470. else
  103471. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103472. }
  103473. 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)
  103474. {
  103475. FLAC__ASSERT(0 != encoder);
  103476. FLAC__ASSERT(0 != encoder->private_);
  103477. FLAC__ASSERT(0 != encoder->protected_);
  103478. if(0 != absolute_sample)
  103479. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103480. if(0 != frame_number)
  103481. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103482. if(0 != channel)
  103483. *channel = encoder->private_->verify.error_stats.channel;
  103484. if(0 != sample)
  103485. *sample = encoder->private_->verify.error_stats.sample;
  103486. if(0 != expected)
  103487. *expected = encoder->private_->verify.error_stats.expected;
  103488. if(0 != got)
  103489. *got = encoder->private_->verify.error_stats.got;
  103490. }
  103491. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103492. {
  103493. FLAC__ASSERT(0 != encoder);
  103494. FLAC__ASSERT(0 != encoder->private_);
  103495. FLAC__ASSERT(0 != encoder->protected_);
  103496. return encoder->protected_->verify;
  103497. }
  103498. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103499. {
  103500. FLAC__ASSERT(0 != encoder);
  103501. FLAC__ASSERT(0 != encoder->private_);
  103502. FLAC__ASSERT(0 != encoder->protected_);
  103503. return encoder->protected_->streamable_subset;
  103504. }
  103505. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103506. {
  103507. FLAC__ASSERT(0 != encoder);
  103508. FLAC__ASSERT(0 != encoder->private_);
  103509. FLAC__ASSERT(0 != encoder->protected_);
  103510. return encoder->protected_->do_md5;
  103511. }
  103512. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103513. {
  103514. FLAC__ASSERT(0 != encoder);
  103515. FLAC__ASSERT(0 != encoder->private_);
  103516. FLAC__ASSERT(0 != encoder->protected_);
  103517. return encoder->protected_->channels;
  103518. }
  103519. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103520. {
  103521. FLAC__ASSERT(0 != encoder);
  103522. FLAC__ASSERT(0 != encoder->private_);
  103523. FLAC__ASSERT(0 != encoder->protected_);
  103524. return encoder->protected_->bits_per_sample;
  103525. }
  103526. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103527. {
  103528. FLAC__ASSERT(0 != encoder);
  103529. FLAC__ASSERT(0 != encoder->private_);
  103530. FLAC__ASSERT(0 != encoder->protected_);
  103531. return encoder->protected_->sample_rate;
  103532. }
  103533. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103534. {
  103535. FLAC__ASSERT(0 != encoder);
  103536. FLAC__ASSERT(0 != encoder->private_);
  103537. FLAC__ASSERT(0 != encoder->protected_);
  103538. return encoder->protected_->blocksize;
  103539. }
  103540. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103541. {
  103542. FLAC__ASSERT(0 != encoder);
  103543. FLAC__ASSERT(0 != encoder->private_);
  103544. FLAC__ASSERT(0 != encoder->protected_);
  103545. return encoder->protected_->do_mid_side_stereo;
  103546. }
  103547. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103548. {
  103549. FLAC__ASSERT(0 != encoder);
  103550. FLAC__ASSERT(0 != encoder->private_);
  103551. FLAC__ASSERT(0 != encoder->protected_);
  103552. return encoder->protected_->loose_mid_side_stereo;
  103553. }
  103554. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103555. {
  103556. FLAC__ASSERT(0 != encoder);
  103557. FLAC__ASSERT(0 != encoder->private_);
  103558. FLAC__ASSERT(0 != encoder->protected_);
  103559. return encoder->protected_->max_lpc_order;
  103560. }
  103561. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103562. {
  103563. FLAC__ASSERT(0 != encoder);
  103564. FLAC__ASSERT(0 != encoder->private_);
  103565. FLAC__ASSERT(0 != encoder->protected_);
  103566. return encoder->protected_->qlp_coeff_precision;
  103567. }
  103568. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103569. {
  103570. FLAC__ASSERT(0 != encoder);
  103571. FLAC__ASSERT(0 != encoder->private_);
  103572. FLAC__ASSERT(0 != encoder->protected_);
  103573. return encoder->protected_->do_qlp_coeff_prec_search;
  103574. }
  103575. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103576. {
  103577. FLAC__ASSERT(0 != encoder);
  103578. FLAC__ASSERT(0 != encoder->private_);
  103579. FLAC__ASSERT(0 != encoder->protected_);
  103580. return encoder->protected_->do_escape_coding;
  103581. }
  103582. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103583. {
  103584. FLAC__ASSERT(0 != encoder);
  103585. FLAC__ASSERT(0 != encoder->private_);
  103586. FLAC__ASSERT(0 != encoder->protected_);
  103587. return encoder->protected_->do_exhaustive_model_search;
  103588. }
  103589. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103590. {
  103591. FLAC__ASSERT(0 != encoder);
  103592. FLAC__ASSERT(0 != encoder->private_);
  103593. FLAC__ASSERT(0 != encoder->protected_);
  103594. return encoder->protected_->min_residual_partition_order;
  103595. }
  103596. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103597. {
  103598. FLAC__ASSERT(0 != encoder);
  103599. FLAC__ASSERT(0 != encoder->private_);
  103600. FLAC__ASSERT(0 != encoder->protected_);
  103601. return encoder->protected_->max_residual_partition_order;
  103602. }
  103603. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103604. {
  103605. FLAC__ASSERT(0 != encoder);
  103606. FLAC__ASSERT(0 != encoder->private_);
  103607. FLAC__ASSERT(0 != encoder->protected_);
  103608. return encoder->protected_->rice_parameter_search_dist;
  103609. }
  103610. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103611. {
  103612. FLAC__ASSERT(0 != encoder);
  103613. FLAC__ASSERT(0 != encoder->private_);
  103614. FLAC__ASSERT(0 != encoder->protected_);
  103615. return encoder->protected_->total_samples_estimate;
  103616. }
  103617. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103618. {
  103619. unsigned i, j = 0, channel;
  103620. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103621. FLAC__ASSERT(0 != encoder);
  103622. FLAC__ASSERT(0 != encoder->private_);
  103623. FLAC__ASSERT(0 != encoder->protected_);
  103624. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103625. do {
  103626. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103627. if(encoder->protected_->verify)
  103628. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103629. for(channel = 0; channel < channels; channel++)
  103630. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103631. if(encoder->protected_->do_mid_side_stereo) {
  103632. FLAC__ASSERT(channels == 2);
  103633. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103634. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103635. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103636. 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' ! */
  103637. }
  103638. }
  103639. else
  103640. j += n;
  103641. encoder->private_->current_sample_number += n;
  103642. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103643. if(encoder->private_->current_sample_number > blocksize) {
  103644. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103645. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103646. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103647. return false;
  103648. /* move unprocessed overread samples to beginnings of arrays */
  103649. for(channel = 0; channel < channels; channel++)
  103650. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103651. if(encoder->protected_->do_mid_side_stereo) {
  103652. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103653. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103654. }
  103655. encoder->private_->current_sample_number = 1;
  103656. }
  103657. } while(j < samples);
  103658. return true;
  103659. }
  103660. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103661. {
  103662. unsigned i, j, k, channel;
  103663. FLAC__int32 x, mid, side;
  103664. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103665. FLAC__ASSERT(0 != encoder);
  103666. FLAC__ASSERT(0 != encoder->private_);
  103667. FLAC__ASSERT(0 != encoder->protected_);
  103668. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103669. j = k = 0;
  103670. /*
  103671. * we have several flavors of the same basic loop, optimized for
  103672. * different conditions:
  103673. */
  103674. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  103675. /*
  103676. * stereo coding: unroll channel loop
  103677. */
  103678. do {
  103679. if(encoder->protected_->verify)
  103680. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103681. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103682. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103683. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  103684. x = buffer[k++];
  103685. encoder->private_->integer_signal[1][i] = x;
  103686. mid += x;
  103687. side -= x;
  103688. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  103689. encoder->private_->integer_signal_mid_side[1][i] = side;
  103690. encoder->private_->integer_signal_mid_side[0][i] = mid;
  103691. }
  103692. encoder->private_->current_sample_number = i;
  103693. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103694. if(i > blocksize) {
  103695. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103696. return false;
  103697. /* move unprocessed overread samples to beginnings of arrays */
  103698. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103699. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103700. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  103701. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  103702. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103703. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103704. encoder->private_->current_sample_number = 1;
  103705. }
  103706. } while(j < samples);
  103707. }
  103708. else {
  103709. /*
  103710. * independent channel coding: buffer each channel in inner loop
  103711. */
  103712. do {
  103713. if(encoder->protected_->verify)
  103714. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  103715. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103716. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103717. for(channel = 0; channel < channels; channel++)
  103718. encoder->private_->integer_signal[channel][i] = buffer[k++];
  103719. }
  103720. encoder->private_->current_sample_number = i;
  103721. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103722. if(i > blocksize) {
  103723. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103724. return false;
  103725. /* move unprocessed overread samples to beginnings of arrays */
  103726. FLAC__ASSERT(i == blocksize+OVERREAD_);
  103727. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103728. for(channel = 0; channel < channels; channel++)
  103729. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103730. encoder->private_->current_sample_number = 1;
  103731. }
  103732. } while(j < samples);
  103733. }
  103734. return true;
  103735. }
  103736. /***********************************************************************
  103737. *
  103738. * Private class methods
  103739. *
  103740. ***********************************************************************/
  103741. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  103742. {
  103743. FLAC__ASSERT(0 != encoder);
  103744. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103745. encoder->protected_->verify = true;
  103746. #else
  103747. encoder->protected_->verify = false;
  103748. #endif
  103749. encoder->protected_->streamable_subset = true;
  103750. encoder->protected_->do_md5 = true;
  103751. encoder->protected_->do_mid_side_stereo = false;
  103752. encoder->protected_->loose_mid_side_stereo = false;
  103753. encoder->protected_->channels = 2;
  103754. encoder->protected_->bits_per_sample = 16;
  103755. encoder->protected_->sample_rate = 44100;
  103756. encoder->protected_->blocksize = 0;
  103757. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103758. encoder->protected_->num_apodizations = 1;
  103759. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103760. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103761. #endif
  103762. encoder->protected_->max_lpc_order = 0;
  103763. encoder->protected_->qlp_coeff_precision = 0;
  103764. encoder->protected_->do_qlp_coeff_prec_search = false;
  103765. encoder->protected_->do_exhaustive_model_search = false;
  103766. encoder->protected_->do_escape_coding = false;
  103767. encoder->protected_->min_residual_partition_order = 0;
  103768. encoder->protected_->max_residual_partition_order = 0;
  103769. encoder->protected_->rice_parameter_search_dist = 0;
  103770. encoder->protected_->total_samples_estimate = 0;
  103771. encoder->protected_->metadata = 0;
  103772. encoder->protected_->num_metadata_blocks = 0;
  103773. encoder->private_->seek_table = 0;
  103774. encoder->private_->disable_constant_subframes = false;
  103775. encoder->private_->disable_fixed_subframes = false;
  103776. encoder->private_->disable_verbatim_subframes = false;
  103777. #if FLAC__HAS_OGG
  103778. encoder->private_->is_ogg = false;
  103779. #endif
  103780. encoder->private_->read_callback = 0;
  103781. encoder->private_->write_callback = 0;
  103782. encoder->private_->seek_callback = 0;
  103783. encoder->private_->tell_callback = 0;
  103784. encoder->private_->metadata_callback = 0;
  103785. encoder->private_->progress_callback = 0;
  103786. encoder->private_->client_data = 0;
  103787. #if FLAC__HAS_OGG
  103788. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  103789. #endif
  103790. }
  103791. void free_(FLAC__StreamEncoder *encoder)
  103792. {
  103793. unsigned i, channel;
  103794. FLAC__ASSERT(0 != encoder);
  103795. if(encoder->protected_->metadata) {
  103796. free(encoder->protected_->metadata);
  103797. encoder->protected_->metadata = 0;
  103798. encoder->protected_->num_metadata_blocks = 0;
  103799. }
  103800. for(i = 0; i < encoder->protected_->channels; i++) {
  103801. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  103802. free(encoder->private_->integer_signal_unaligned[i]);
  103803. encoder->private_->integer_signal_unaligned[i] = 0;
  103804. }
  103805. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103806. if(0 != encoder->private_->real_signal_unaligned[i]) {
  103807. free(encoder->private_->real_signal_unaligned[i]);
  103808. encoder->private_->real_signal_unaligned[i] = 0;
  103809. }
  103810. #endif
  103811. }
  103812. for(i = 0; i < 2; i++) {
  103813. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  103814. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  103815. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  103816. }
  103817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103818. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  103819. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  103820. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  103821. }
  103822. #endif
  103823. }
  103824. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103825. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  103826. if(0 != encoder->private_->window_unaligned[i]) {
  103827. free(encoder->private_->window_unaligned[i]);
  103828. encoder->private_->window_unaligned[i] = 0;
  103829. }
  103830. }
  103831. if(0 != encoder->private_->windowed_signal_unaligned) {
  103832. free(encoder->private_->windowed_signal_unaligned);
  103833. encoder->private_->windowed_signal_unaligned = 0;
  103834. }
  103835. #endif
  103836. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  103837. for(i = 0; i < 2; i++) {
  103838. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  103839. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  103840. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  103841. }
  103842. }
  103843. }
  103844. for(channel = 0; channel < 2; channel++) {
  103845. for(i = 0; i < 2; i++) {
  103846. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  103847. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  103848. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  103849. }
  103850. }
  103851. }
  103852. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  103853. free(encoder->private_->abs_residual_partition_sums_unaligned);
  103854. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  103855. }
  103856. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  103857. free(encoder->private_->raw_bits_per_partition_unaligned);
  103858. encoder->private_->raw_bits_per_partition_unaligned = 0;
  103859. }
  103860. if(encoder->protected_->verify) {
  103861. for(i = 0; i < encoder->protected_->channels; i++) {
  103862. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  103863. free(encoder->private_->verify.input_fifo.data[i]);
  103864. encoder->private_->verify.input_fifo.data[i] = 0;
  103865. }
  103866. }
  103867. }
  103868. FLAC__bitwriter_free(encoder->private_->frame);
  103869. }
  103870. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  103871. {
  103872. FLAC__bool ok;
  103873. unsigned i, channel;
  103874. FLAC__ASSERT(new_blocksize > 0);
  103875. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103876. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  103877. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  103878. if(new_blocksize <= encoder->private_->input_capacity)
  103879. return true;
  103880. ok = true;
  103881. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  103882. * requires that the input arrays (in our case the integer signals)
  103883. * have a buffer of up to 3 zeroes in front (at negative indices) for
  103884. * alignment purposes; we use 4 in front to keep the data well-aligned.
  103885. */
  103886. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  103887. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  103888. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  103889. encoder->private_->integer_signal[i] += 4;
  103890. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103891. #if 0 /* @@@ currently unused */
  103892. if(encoder->protected_->max_lpc_order > 0)
  103893. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  103894. #endif
  103895. #endif
  103896. }
  103897. for(i = 0; ok && i < 2; i++) {
  103898. 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]);
  103899. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  103900. encoder->private_->integer_signal_mid_side[i] += 4;
  103901. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103902. #if 0 /* @@@ currently unused */
  103903. if(encoder->protected_->max_lpc_order > 0)
  103904. 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]);
  103905. #endif
  103906. #endif
  103907. }
  103908. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103909. if(ok && encoder->protected_->max_lpc_order > 0) {
  103910. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  103911. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  103912. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  103913. }
  103914. #endif
  103915. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  103916. for(i = 0; ok && i < 2; i++) {
  103917. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  103918. }
  103919. }
  103920. for(channel = 0; ok && channel < 2; channel++) {
  103921. for(i = 0; ok && i < 2; i++) {
  103922. 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]);
  103923. }
  103924. }
  103925. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  103926. /*@@@ 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) */
  103927. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  103928. if(encoder->protected_->do_escape_coding)
  103929. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  103930. /* now adjust the windows if the blocksize has changed */
  103931. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103932. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  103933. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  103934. switch(encoder->protected_->apodizations[i].type) {
  103935. case FLAC__APODIZATION_BARTLETT:
  103936. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  103937. break;
  103938. case FLAC__APODIZATION_BARTLETT_HANN:
  103939. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  103940. break;
  103941. case FLAC__APODIZATION_BLACKMAN:
  103942. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  103943. break;
  103944. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  103945. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  103946. break;
  103947. case FLAC__APODIZATION_CONNES:
  103948. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  103949. break;
  103950. case FLAC__APODIZATION_FLATTOP:
  103951. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  103952. break;
  103953. case FLAC__APODIZATION_GAUSS:
  103954. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  103955. break;
  103956. case FLAC__APODIZATION_HAMMING:
  103957. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  103958. break;
  103959. case FLAC__APODIZATION_HANN:
  103960. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103961. break;
  103962. case FLAC__APODIZATION_KAISER_BESSEL:
  103963. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  103964. break;
  103965. case FLAC__APODIZATION_NUTTALL:
  103966. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  103967. break;
  103968. case FLAC__APODIZATION_RECTANGLE:
  103969. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  103970. break;
  103971. case FLAC__APODIZATION_TRIANGLE:
  103972. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  103973. break;
  103974. case FLAC__APODIZATION_TUKEY:
  103975. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  103976. break;
  103977. case FLAC__APODIZATION_WELCH:
  103978. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  103979. break;
  103980. default:
  103981. FLAC__ASSERT(0);
  103982. /* double protection */
  103983. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  103984. break;
  103985. }
  103986. }
  103987. }
  103988. #endif
  103989. if(ok)
  103990. encoder->private_->input_capacity = new_blocksize;
  103991. else
  103992. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103993. return ok;
  103994. }
  103995. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  103996. {
  103997. const FLAC__byte *buffer;
  103998. size_t bytes;
  103999. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104000. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104001. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104002. return false;
  104003. }
  104004. if(encoder->protected_->verify) {
  104005. encoder->private_->verify.output.data = buffer;
  104006. encoder->private_->verify.output.bytes = bytes;
  104007. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104008. encoder->private_->verify.needs_magic_hack = true;
  104009. }
  104010. else {
  104011. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104012. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104013. FLAC__bitwriter_clear(encoder->private_->frame);
  104014. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104015. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104016. return false;
  104017. }
  104018. }
  104019. }
  104020. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104021. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104022. FLAC__bitwriter_clear(encoder->private_->frame);
  104023. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104024. return false;
  104025. }
  104026. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104027. FLAC__bitwriter_clear(encoder->private_->frame);
  104028. if(samples > 0) {
  104029. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104030. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104031. }
  104032. return true;
  104033. }
  104034. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104035. {
  104036. FLAC__StreamEncoderWriteStatus status;
  104037. FLAC__uint64 output_position = 0;
  104038. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104039. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104040. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104041. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104042. }
  104043. /*
  104044. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104045. */
  104046. if(samples == 0) {
  104047. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104048. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104049. encoder->protected_->streaminfo_offset = output_position;
  104050. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104051. encoder->protected_->seektable_offset = output_position;
  104052. }
  104053. /*
  104054. * Mark the current seek point if hit (if audio_offset == 0 that
  104055. * means we're still writing metadata and haven't hit the first
  104056. * frame yet)
  104057. */
  104058. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104059. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104060. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104061. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104062. FLAC__uint64 test_sample;
  104063. unsigned i;
  104064. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104065. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104066. if(test_sample > frame_last_sample) {
  104067. break;
  104068. }
  104069. else if(test_sample >= frame_first_sample) {
  104070. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104071. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104072. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104073. encoder->private_->first_seekpoint_to_check++;
  104074. /* DO NOT: "break;" and here's why:
  104075. * The seektable template may contain more than one target
  104076. * sample for any given frame; we will keep looping, generating
  104077. * duplicate seekpoints for them, and we'll clean it up later,
  104078. * just before writing the seektable back to the metadata.
  104079. */
  104080. }
  104081. else {
  104082. encoder->private_->first_seekpoint_to_check++;
  104083. }
  104084. }
  104085. }
  104086. #if FLAC__HAS_OGG
  104087. if(encoder->private_->is_ogg) {
  104088. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104089. &encoder->protected_->ogg_encoder_aspect,
  104090. buffer,
  104091. bytes,
  104092. samples,
  104093. encoder->private_->current_frame_number,
  104094. is_last_block,
  104095. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104096. encoder,
  104097. encoder->private_->client_data
  104098. );
  104099. }
  104100. else
  104101. #endif
  104102. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104103. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104104. encoder->private_->bytes_written += bytes;
  104105. encoder->private_->samples_written += samples;
  104106. /* we keep a high watermark on the number of frames written because
  104107. * when the encoder goes back to write metadata, 'current_frame'
  104108. * will drop back to 0.
  104109. */
  104110. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104111. }
  104112. else
  104113. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104114. return status;
  104115. }
  104116. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104117. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104118. {
  104119. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104120. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104121. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104122. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104123. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104124. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104125. FLAC__StreamEncoderSeekStatus seek_status;
  104126. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104127. /* All this is based on intimate knowledge of the stream header
  104128. * layout, but a change to the header format that would break this
  104129. * would also break all streams encoded in the previous format.
  104130. */
  104131. /*
  104132. * Write MD5 signature
  104133. */
  104134. {
  104135. const unsigned md5_offset =
  104136. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104137. (
  104138. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104139. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104140. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104141. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104142. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104143. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104144. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104145. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104146. ) / 8;
  104147. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104148. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104149. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104150. return;
  104151. }
  104152. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104153. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104154. return;
  104155. }
  104156. }
  104157. /*
  104158. * Write total samples
  104159. */
  104160. {
  104161. const unsigned total_samples_byte_offset =
  104162. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104163. (
  104164. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104165. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104166. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104167. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104168. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104169. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104170. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104171. - 4
  104172. ) / 8;
  104173. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104174. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104175. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104176. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104177. b[4] = (FLAC__byte)(samples & 0xFF);
  104178. 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) {
  104179. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104180. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104181. return;
  104182. }
  104183. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104184. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104185. return;
  104186. }
  104187. }
  104188. /*
  104189. * Write min/max framesize
  104190. */
  104191. {
  104192. const unsigned min_framesize_offset =
  104193. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104194. (
  104195. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104196. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104197. ) / 8;
  104198. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104199. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104200. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104201. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104202. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104203. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104204. 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) {
  104205. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104206. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104207. return;
  104208. }
  104209. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104210. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104211. return;
  104212. }
  104213. }
  104214. /*
  104215. * Write seektable
  104216. */
  104217. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104218. unsigned i;
  104219. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104220. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104221. 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) {
  104222. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104223. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104224. return;
  104225. }
  104226. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104227. FLAC__uint64 xx;
  104228. unsigned x;
  104229. xx = encoder->private_->seek_table->points[i].sample_number;
  104230. b[7] = (FLAC__byte)xx; xx >>= 8;
  104231. b[6] = (FLAC__byte)xx; xx >>= 8;
  104232. b[5] = (FLAC__byte)xx; xx >>= 8;
  104233. b[4] = (FLAC__byte)xx; xx >>= 8;
  104234. b[3] = (FLAC__byte)xx; xx >>= 8;
  104235. b[2] = (FLAC__byte)xx; xx >>= 8;
  104236. b[1] = (FLAC__byte)xx; xx >>= 8;
  104237. b[0] = (FLAC__byte)xx; xx >>= 8;
  104238. xx = encoder->private_->seek_table->points[i].stream_offset;
  104239. b[15] = (FLAC__byte)xx; xx >>= 8;
  104240. b[14] = (FLAC__byte)xx; xx >>= 8;
  104241. b[13] = (FLAC__byte)xx; xx >>= 8;
  104242. b[12] = (FLAC__byte)xx; xx >>= 8;
  104243. b[11] = (FLAC__byte)xx; xx >>= 8;
  104244. b[10] = (FLAC__byte)xx; xx >>= 8;
  104245. b[9] = (FLAC__byte)xx; xx >>= 8;
  104246. b[8] = (FLAC__byte)xx; xx >>= 8;
  104247. x = encoder->private_->seek_table->points[i].frame_samples;
  104248. b[17] = (FLAC__byte)x; x >>= 8;
  104249. b[16] = (FLAC__byte)x; x >>= 8;
  104250. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104251. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104252. return;
  104253. }
  104254. }
  104255. }
  104256. }
  104257. #if FLAC__HAS_OGG
  104258. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104259. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104260. {
  104261. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104262. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104263. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104264. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104265. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104266. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104267. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104268. FLAC__STREAM_SYNC_LENGTH
  104269. ;
  104270. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104271. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104272. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104273. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104274. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104275. ogg_page page;
  104276. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104277. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104278. /* Pre-check that client supports seeking, since we don't want the
  104279. * ogg_helper code to ever have to deal with this condition.
  104280. */
  104281. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104282. return;
  104283. /* All this is based on intimate knowledge of the stream header
  104284. * layout, but a change to the header format that would break this
  104285. * would also break all streams encoded in the previous format.
  104286. */
  104287. /**
  104288. ** Write STREAMINFO stats
  104289. **/
  104290. simple_ogg_page__init(&page);
  104291. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104292. simple_ogg_page__clear(&page);
  104293. return; /* state already set */
  104294. }
  104295. /*
  104296. * Write MD5 signature
  104297. */
  104298. {
  104299. const unsigned md5_offset =
  104300. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104301. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104302. (
  104303. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104304. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104305. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104306. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104307. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104308. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104309. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104310. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104311. ) / 8;
  104312. if(md5_offset + 16 > (unsigned)page.body_len) {
  104313. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104314. simple_ogg_page__clear(&page);
  104315. return;
  104316. }
  104317. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104318. }
  104319. /*
  104320. * Write total samples
  104321. */
  104322. {
  104323. const unsigned total_samples_byte_offset =
  104324. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104325. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104326. (
  104327. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104328. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104329. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104330. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104331. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104332. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104333. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104334. - 4
  104335. ) / 8;
  104336. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104337. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104338. simple_ogg_page__clear(&page);
  104339. return;
  104340. }
  104341. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104342. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104343. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104344. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104345. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104346. b[4] = (FLAC__byte)(samples & 0xFF);
  104347. memcpy(page.body + total_samples_byte_offset, b, 5);
  104348. }
  104349. /*
  104350. * Write min/max framesize
  104351. */
  104352. {
  104353. const unsigned min_framesize_offset =
  104354. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104355. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104356. (
  104357. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104358. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104359. ) / 8;
  104360. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104361. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104362. simple_ogg_page__clear(&page);
  104363. return;
  104364. }
  104365. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104366. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104367. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104368. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104369. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104370. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104371. memcpy(page.body + min_framesize_offset, b, 6);
  104372. }
  104373. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104374. simple_ogg_page__clear(&page);
  104375. return; /* state already set */
  104376. }
  104377. simple_ogg_page__clear(&page);
  104378. /*
  104379. * Write seektable
  104380. */
  104381. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104382. unsigned i;
  104383. FLAC__byte *p;
  104384. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104385. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104386. simple_ogg_page__init(&page);
  104387. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104388. simple_ogg_page__clear(&page);
  104389. return; /* state already set */
  104390. }
  104391. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104392. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104393. simple_ogg_page__clear(&page);
  104394. return;
  104395. }
  104396. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104397. FLAC__uint64 xx;
  104398. unsigned x;
  104399. xx = encoder->private_->seek_table->points[i].sample_number;
  104400. b[7] = (FLAC__byte)xx; xx >>= 8;
  104401. b[6] = (FLAC__byte)xx; xx >>= 8;
  104402. b[5] = (FLAC__byte)xx; xx >>= 8;
  104403. b[4] = (FLAC__byte)xx; xx >>= 8;
  104404. b[3] = (FLAC__byte)xx; xx >>= 8;
  104405. b[2] = (FLAC__byte)xx; xx >>= 8;
  104406. b[1] = (FLAC__byte)xx; xx >>= 8;
  104407. b[0] = (FLAC__byte)xx; xx >>= 8;
  104408. xx = encoder->private_->seek_table->points[i].stream_offset;
  104409. b[15] = (FLAC__byte)xx; xx >>= 8;
  104410. b[14] = (FLAC__byte)xx; xx >>= 8;
  104411. b[13] = (FLAC__byte)xx; xx >>= 8;
  104412. b[12] = (FLAC__byte)xx; xx >>= 8;
  104413. b[11] = (FLAC__byte)xx; xx >>= 8;
  104414. b[10] = (FLAC__byte)xx; xx >>= 8;
  104415. b[9] = (FLAC__byte)xx; xx >>= 8;
  104416. b[8] = (FLAC__byte)xx; xx >>= 8;
  104417. x = encoder->private_->seek_table->points[i].frame_samples;
  104418. b[17] = (FLAC__byte)x; x >>= 8;
  104419. b[16] = (FLAC__byte)x; x >>= 8;
  104420. memcpy(p, b, 18);
  104421. }
  104422. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104423. simple_ogg_page__clear(&page);
  104424. return; /* state already set */
  104425. }
  104426. simple_ogg_page__clear(&page);
  104427. }
  104428. }
  104429. #endif
  104430. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104431. {
  104432. FLAC__uint16 crc;
  104433. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104434. /*
  104435. * Accumulate raw signal to the MD5 signature
  104436. */
  104437. 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)) {
  104438. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104439. return false;
  104440. }
  104441. /*
  104442. * Process the frame header and subframes into the frame bitbuffer
  104443. */
  104444. if(!process_subframes_(encoder, is_fractional_block)) {
  104445. /* the above function sets the state for us in case of an error */
  104446. return false;
  104447. }
  104448. /*
  104449. * Zero-pad the frame to a byte_boundary
  104450. */
  104451. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104452. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104453. return false;
  104454. }
  104455. /*
  104456. * CRC-16 the whole thing
  104457. */
  104458. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104459. if(
  104460. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104461. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104462. ) {
  104463. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104464. return false;
  104465. }
  104466. /*
  104467. * Write it
  104468. */
  104469. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104470. /* the above function sets the state for us in case of an error */
  104471. return false;
  104472. }
  104473. /*
  104474. * Get ready for the next frame
  104475. */
  104476. encoder->private_->current_sample_number = 0;
  104477. encoder->private_->current_frame_number++;
  104478. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104479. return true;
  104480. }
  104481. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104482. {
  104483. FLAC__FrameHeader frame_header;
  104484. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104485. FLAC__bool do_independent, do_mid_side;
  104486. /*
  104487. * Calculate the min,max Rice partition orders
  104488. */
  104489. if(is_fractional_block) {
  104490. max_partition_order = 0;
  104491. }
  104492. else {
  104493. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104494. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104495. }
  104496. min_partition_order = min(min_partition_order, max_partition_order);
  104497. /*
  104498. * Setup the frame
  104499. */
  104500. frame_header.blocksize = encoder->protected_->blocksize;
  104501. frame_header.sample_rate = encoder->protected_->sample_rate;
  104502. frame_header.channels = encoder->protected_->channels;
  104503. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104504. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104505. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104506. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104507. /*
  104508. * Figure out what channel assignments to try
  104509. */
  104510. if(encoder->protected_->do_mid_side_stereo) {
  104511. if(encoder->protected_->loose_mid_side_stereo) {
  104512. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104513. do_independent = true;
  104514. do_mid_side = true;
  104515. }
  104516. else {
  104517. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104518. do_mid_side = !do_independent;
  104519. }
  104520. }
  104521. else {
  104522. do_independent = true;
  104523. do_mid_side = true;
  104524. }
  104525. }
  104526. else {
  104527. do_independent = true;
  104528. do_mid_side = false;
  104529. }
  104530. FLAC__ASSERT(do_independent || do_mid_side);
  104531. /*
  104532. * Check for wasted bits; set effective bps for each subframe
  104533. */
  104534. if(do_independent) {
  104535. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104536. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104537. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104538. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104539. }
  104540. }
  104541. if(do_mid_side) {
  104542. FLAC__ASSERT(encoder->protected_->channels == 2);
  104543. for(channel = 0; channel < 2; channel++) {
  104544. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104545. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104546. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104547. }
  104548. }
  104549. /*
  104550. * First do a normal encoding pass of each independent channel
  104551. */
  104552. if(do_independent) {
  104553. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104554. if(!
  104555. process_subframe_(
  104556. encoder,
  104557. min_partition_order,
  104558. max_partition_order,
  104559. &frame_header,
  104560. encoder->private_->subframe_bps[channel],
  104561. encoder->private_->integer_signal[channel],
  104562. encoder->private_->subframe_workspace_ptr[channel],
  104563. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104564. encoder->private_->residual_workspace[channel],
  104565. encoder->private_->best_subframe+channel,
  104566. encoder->private_->best_subframe_bits+channel
  104567. )
  104568. )
  104569. return false;
  104570. }
  104571. }
  104572. /*
  104573. * Now do mid and side channels if requested
  104574. */
  104575. if(do_mid_side) {
  104576. FLAC__ASSERT(encoder->protected_->channels == 2);
  104577. for(channel = 0; channel < 2; channel++) {
  104578. if(!
  104579. process_subframe_(
  104580. encoder,
  104581. min_partition_order,
  104582. max_partition_order,
  104583. &frame_header,
  104584. encoder->private_->subframe_bps_mid_side[channel],
  104585. encoder->private_->integer_signal_mid_side[channel],
  104586. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104587. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104588. encoder->private_->residual_workspace_mid_side[channel],
  104589. encoder->private_->best_subframe_mid_side+channel,
  104590. encoder->private_->best_subframe_bits_mid_side+channel
  104591. )
  104592. )
  104593. return false;
  104594. }
  104595. }
  104596. /*
  104597. * Compose the frame bitbuffer
  104598. */
  104599. if(do_mid_side) {
  104600. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104601. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104602. FLAC__ChannelAssignment channel_assignment;
  104603. FLAC__ASSERT(encoder->protected_->channels == 2);
  104604. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104605. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104606. }
  104607. else {
  104608. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104609. unsigned min_bits;
  104610. int ca;
  104611. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104612. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104613. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104614. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104615. FLAC__ASSERT(do_independent && do_mid_side);
  104616. /* We have to figure out which channel assignent results in the smallest frame */
  104617. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104618. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104619. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104620. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104621. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104622. min_bits = bits[channel_assignment];
  104623. for(ca = 1; ca <= 3; ca++) {
  104624. if(bits[ca] < min_bits) {
  104625. min_bits = bits[ca];
  104626. channel_assignment = (FLAC__ChannelAssignment)ca;
  104627. }
  104628. }
  104629. }
  104630. frame_header.channel_assignment = channel_assignment;
  104631. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104632. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104633. return false;
  104634. }
  104635. switch(channel_assignment) {
  104636. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104637. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104638. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104639. break;
  104640. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104641. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104642. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104643. break;
  104644. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104645. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104646. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104647. break;
  104648. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104649. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104650. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104651. break;
  104652. default:
  104653. FLAC__ASSERT(0);
  104654. }
  104655. switch(channel_assignment) {
  104656. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104657. left_bps = encoder->private_->subframe_bps [0];
  104658. right_bps = encoder->private_->subframe_bps [1];
  104659. break;
  104660. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104661. left_bps = encoder->private_->subframe_bps [0];
  104662. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104663. break;
  104664. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104665. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104666. right_bps = encoder->private_->subframe_bps [1];
  104667. break;
  104668. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104669. left_bps = encoder->private_->subframe_bps_mid_side[0];
  104670. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104671. break;
  104672. default:
  104673. FLAC__ASSERT(0);
  104674. }
  104675. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  104676. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  104677. return false;
  104678. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  104679. return false;
  104680. }
  104681. else {
  104682. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104683. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104684. return false;
  104685. }
  104686. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104687. 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)) {
  104688. /* the above function sets the state for us in case of an error */
  104689. return false;
  104690. }
  104691. }
  104692. }
  104693. if(encoder->protected_->loose_mid_side_stereo) {
  104694. encoder->private_->loose_mid_side_stereo_frame_count++;
  104695. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  104696. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  104697. }
  104698. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  104699. return true;
  104700. }
  104701. FLAC__bool process_subframe_(
  104702. FLAC__StreamEncoder *encoder,
  104703. unsigned min_partition_order,
  104704. unsigned max_partition_order,
  104705. const FLAC__FrameHeader *frame_header,
  104706. unsigned subframe_bps,
  104707. const FLAC__int32 integer_signal[],
  104708. FLAC__Subframe *subframe[2],
  104709. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  104710. FLAC__int32 *residual[2],
  104711. unsigned *best_subframe,
  104712. unsigned *best_bits
  104713. )
  104714. {
  104715. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104716. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104717. #else
  104718. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  104719. #endif
  104720. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104721. FLAC__double lpc_residual_bits_per_sample;
  104722. 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 */
  104723. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  104724. unsigned min_lpc_order, max_lpc_order, lpc_order;
  104725. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  104726. #endif
  104727. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  104728. unsigned rice_parameter;
  104729. unsigned _candidate_bits, _best_bits;
  104730. unsigned _best_subframe;
  104731. /* only use RICE2 partitions if stream bps > 16 */
  104732. 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;
  104733. FLAC__ASSERT(frame_header->blocksize > 0);
  104734. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  104735. _best_subframe = 0;
  104736. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  104737. _best_bits = UINT_MAX;
  104738. else
  104739. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104740. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  104741. unsigned signal_is_constant = false;
  104742. 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);
  104743. /* check for constant subframe */
  104744. if(
  104745. !encoder->private_->disable_constant_subframes &&
  104746. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104747. fixed_residual_bits_per_sample[1] == 0.0
  104748. #else
  104749. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  104750. #endif
  104751. ) {
  104752. /* the above means it's possible all samples are the same value; now double-check it: */
  104753. unsigned i;
  104754. signal_is_constant = true;
  104755. for(i = 1; i < frame_header->blocksize; i++) {
  104756. if(integer_signal[0] != integer_signal[i]) {
  104757. signal_is_constant = false;
  104758. break;
  104759. }
  104760. }
  104761. }
  104762. if(signal_is_constant) {
  104763. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  104764. if(_candidate_bits < _best_bits) {
  104765. _best_subframe = !_best_subframe;
  104766. _best_bits = _candidate_bits;
  104767. }
  104768. }
  104769. else {
  104770. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  104771. /* encode fixed */
  104772. if(encoder->protected_->do_exhaustive_model_search) {
  104773. min_fixed_order = 0;
  104774. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  104775. }
  104776. else {
  104777. min_fixed_order = max_fixed_order = guess_fixed_order;
  104778. }
  104779. if(max_fixed_order >= frame_header->blocksize)
  104780. max_fixed_order = frame_header->blocksize - 1;
  104781. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  104782. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104783. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  104784. continue; /* don't even try */
  104785. 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 */
  104786. #else
  104787. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  104788. continue; /* don't even try */
  104789. 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 */
  104790. #endif
  104791. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104792. if(rice_parameter >= rice_parameter_limit) {
  104793. #ifdef DEBUG_VERBOSE
  104794. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  104795. #endif
  104796. rice_parameter = rice_parameter_limit - 1;
  104797. }
  104798. _candidate_bits =
  104799. evaluate_fixed_subframe_(
  104800. encoder,
  104801. integer_signal,
  104802. residual[!_best_subframe],
  104803. encoder->private_->abs_residual_partition_sums,
  104804. encoder->private_->raw_bits_per_partition,
  104805. frame_header->blocksize,
  104806. subframe_bps,
  104807. fixed_order,
  104808. rice_parameter,
  104809. rice_parameter_limit,
  104810. min_partition_order,
  104811. max_partition_order,
  104812. encoder->protected_->do_escape_coding,
  104813. encoder->protected_->rice_parameter_search_dist,
  104814. subframe[!_best_subframe],
  104815. partitioned_rice_contents[!_best_subframe]
  104816. );
  104817. if(_candidate_bits < _best_bits) {
  104818. _best_subframe = !_best_subframe;
  104819. _best_bits = _candidate_bits;
  104820. }
  104821. }
  104822. }
  104823. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104824. /* encode lpc */
  104825. if(encoder->protected_->max_lpc_order > 0) {
  104826. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  104827. max_lpc_order = frame_header->blocksize-1;
  104828. else
  104829. max_lpc_order = encoder->protected_->max_lpc_order;
  104830. if(max_lpc_order > 0) {
  104831. unsigned a;
  104832. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  104833. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  104834. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  104835. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  104836. if(autoc[0] != 0.0) {
  104837. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  104838. if(encoder->protected_->do_exhaustive_model_search) {
  104839. min_lpc_order = 1;
  104840. }
  104841. else {
  104842. const unsigned guess_lpc_order =
  104843. FLAC__lpc_compute_best_order(
  104844. lpc_error,
  104845. max_lpc_order,
  104846. frame_header->blocksize,
  104847. subframe_bps + (
  104848. encoder->protected_->do_qlp_coeff_prec_search?
  104849. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  104850. encoder->protected_->qlp_coeff_precision
  104851. )
  104852. );
  104853. min_lpc_order = max_lpc_order = guess_lpc_order;
  104854. }
  104855. if(max_lpc_order >= frame_header->blocksize)
  104856. max_lpc_order = frame_header->blocksize - 1;
  104857. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  104858. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  104859. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  104860. continue; /* don't even try */
  104861. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  104862. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  104863. if(rice_parameter >= rice_parameter_limit) {
  104864. #ifdef DEBUG_VERBOSE
  104865. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  104866. #endif
  104867. rice_parameter = rice_parameter_limit - 1;
  104868. }
  104869. if(encoder->protected_->do_qlp_coeff_prec_search) {
  104870. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  104871. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  104872. if(subframe_bps <= 17) {
  104873. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  104874. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  104875. }
  104876. else
  104877. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  104878. }
  104879. else {
  104880. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  104881. }
  104882. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  104883. _candidate_bits =
  104884. evaluate_lpc_subframe_(
  104885. encoder,
  104886. integer_signal,
  104887. residual[!_best_subframe],
  104888. encoder->private_->abs_residual_partition_sums,
  104889. encoder->private_->raw_bits_per_partition,
  104890. encoder->private_->lp_coeff[lpc_order-1],
  104891. frame_header->blocksize,
  104892. subframe_bps,
  104893. lpc_order,
  104894. qlp_coeff_precision,
  104895. rice_parameter,
  104896. rice_parameter_limit,
  104897. min_partition_order,
  104898. max_partition_order,
  104899. encoder->protected_->do_escape_coding,
  104900. encoder->protected_->rice_parameter_search_dist,
  104901. subframe[!_best_subframe],
  104902. partitioned_rice_contents[!_best_subframe]
  104903. );
  104904. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  104905. if(_candidate_bits < _best_bits) {
  104906. _best_subframe = !_best_subframe;
  104907. _best_bits = _candidate_bits;
  104908. }
  104909. }
  104910. }
  104911. }
  104912. }
  104913. }
  104914. }
  104915. }
  104916. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  104917. }
  104918. }
  104919. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  104920. if(_best_bits == UINT_MAX) {
  104921. FLAC__ASSERT(_best_subframe == 0);
  104922. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  104923. }
  104924. *best_subframe = _best_subframe;
  104925. *best_bits = _best_bits;
  104926. return true;
  104927. }
  104928. FLAC__bool add_subframe_(
  104929. FLAC__StreamEncoder *encoder,
  104930. unsigned blocksize,
  104931. unsigned subframe_bps,
  104932. const FLAC__Subframe *subframe,
  104933. FLAC__BitWriter *frame
  104934. )
  104935. {
  104936. switch(subframe->type) {
  104937. case FLAC__SUBFRAME_TYPE_CONSTANT:
  104938. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  104939. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104940. return false;
  104941. }
  104942. break;
  104943. case FLAC__SUBFRAME_TYPE_FIXED:
  104944. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  104945. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104946. return false;
  104947. }
  104948. break;
  104949. case FLAC__SUBFRAME_TYPE_LPC:
  104950. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  104951. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104952. return false;
  104953. }
  104954. break;
  104955. case FLAC__SUBFRAME_TYPE_VERBATIM:
  104956. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  104957. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104958. return false;
  104959. }
  104960. break;
  104961. default:
  104962. FLAC__ASSERT(0);
  104963. }
  104964. return true;
  104965. }
  104966. #define SPOTCHECK_ESTIMATE 0
  104967. #if SPOTCHECK_ESTIMATE
  104968. static void spotcheck_subframe_estimate_(
  104969. FLAC__StreamEncoder *encoder,
  104970. unsigned blocksize,
  104971. unsigned subframe_bps,
  104972. const FLAC__Subframe *subframe,
  104973. unsigned estimate
  104974. )
  104975. {
  104976. FLAC__bool ret;
  104977. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  104978. if(frame == 0) {
  104979. fprintf(stderr, "EST: can't allocate frame\n");
  104980. return;
  104981. }
  104982. if(!FLAC__bitwriter_init(frame)) {
  104983. fprintf(stderr, "EST: can't init frame\n");
  104984. return;
  104985. }
  104986. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  104987. FLAC__ASSERT(ret);
  104988. {
  104989. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  104990. if(estimate != actual)
  104991. 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);
  104992. }
  104993. FLAC__bitwriter_delete(frame);
  104994. }
  104995. #endif
  104996. unsigned evaluate_constant_subframe_(
  104997. FLAC__StreamEncoder *encoder,
  104998. const FLAC__int32 signal,
  104999. unsigned blocksize,
  105000. unsigned subframe_bps,
  105001. FLAC__Subframe *subframe
  105002. )
  105003. {
  105004. unsigned estimate;
  105005. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105006. subframe->data.constant.value = signal;
  105007. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105008. #if SPOTCHECK_ESTIMATE
  105009. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105010. #else
  105011. (void)encoder, (void)blocksize;
  105012. #endif
  105013. return estimate;
  105014. }
  105015. unsigned evaluate_fixed_subframe_(
  105016. FLAC__StreamEncoder *encoder,
  105017. const FLAC__int32 signal[],
  105018. FLAC__int32 residual[],
  105019. FLAC__uint64 abs_residual_partition_sums[],
  105020. unsigned raw_bits_per_partition[],
  105021. unsigned blocksize,
  105022. unsigned subframe_bps,
  105023. unsigned order,
  105024. unsigned rice_parameter,
  105025. unsigned rice_parameter_limit,
  105026. unsigned min_partition_order,
  105027. unsigned max_partition_order,
  105028. FLAC__bool do_escape_coding,
  105029. unsigned rice_parameter_search_dist,
  105030. FLAC__Subframe *subframe,
  105031. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105032. )
  105033. {
  105034. unsigned i, residual_bits, estimate;
  105035. const unsigned residual_samples = blocksize - order;
  105036. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105037. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105038. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105039. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105040. subframe->data.fixed.residual = residual;
  105041. residual_bits =
  105042. find_best_partition_order_(
  105043. encoder->private_,
  105044. residual,
  105045. abs_residual_partition_sums,
  105046. raw_bits_per_partition,
  105047. residual_samples,
  105048. order,
  105049. rice_parameter,
  105050. rice_parameter_limit,
  105051. min_partition_order,
  105052. max_partition_order,
  105053. subframe_bps,
  105054. do_escape_coding,
  105055. rice_parameter_search_dist,
  105056. &subframe->data.fixed.entropy_coding_method
  105057. );
  105058. subframe->data.fixed.order = order;
  105059. for(i = 0; i < order; i++)
  105060. subframe->data.fixed.warmup[i] = signal[i];
  105061. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105062. #if SPOTCHECK_ESTIMATE
  105063. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105064. #endif
  105065. return estimate;
  105066. }
  105067. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105068. unsigned evaluate_lpc_subframe_(
  105069. FLAC__StreamEncoder *encoder,
  105070. const FLAC__int32 signal[],
  105071. FLAC__int32 residual[],
  105072. FLAC__uint64 abs_residual_partition_sums[],
  105073. unsigned raw_bits_per_partition[],
  105074. const FLAC__real lp_coeff[],
  105075. unsigned blocksize,
  105076. unsigned subframe_bps,
  105077. unsigned order,
  105078. unsigned qlp_coeff_precision,
  105079. unsigned rice_parameter,
  105080. unsigned rice_parameter_limit,
  105081. unsigned min_partition_order,
  105082. unsigned max_partition_order,
  105083. FLAC__bool do_escape_coding,
  105084. unsigned rice_parameter_search_dist,
  105085. FLAC__Subframe *subframe,
  105086. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105087. )
  105088. {
  105089. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105090. unsigned i, residual_bits, estimate;
  105091. int quantization, ret;
  105092. const unsigned residual_samples = blocksize - order;
  105093. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105094. if(subframe_bps <= 16) {
  105095. FLAC__ASSERT(order > 0);
  105096. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105097. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105098. }
  105099. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105100. if(ret != 0)
  105101. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105102. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105103. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105104. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105105. else
  105106. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105107. else
  105108. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105109. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105110. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105111. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105112. subframe->data.lpc.residual = residual;
  105113. residual_bits =
  105114. find_best_partition_order_(
  105115. encoder->private_,
  105116. residual,
  105117. abs_residual_partition_sums,
  105118. raw_bits_per_partition,
  105119. residual_samples,
  105120. order,
  105121. rice_parameter,
  105122. rice_parameter_limit,
  105123. min_partition_order,
  105124. max_partition_order,
  105125. subframe_bps,
  105126. do_escape_coding,
  105127. rice_parameter_search_dist,
  105128. &subframe->data.lpc.entropy_coding_method
  105129. );
  105130. subframe->data.lpc.order = order;
  105131. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105132. subframe->data.lpc.quantization_level = quantization;
  105133. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105134. for(i = 0; i < order; i++)
  105135. subframe->data.lpc.warmup[i] = signal[i];
  105136. 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;
  105137. #if SPOTCHECK_ESTIMATE
  105138. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105139. #endif
  105140. return estimate;
  105141. }
  105142. #endif
  105143. unsigned evaluate_verbatim_subframe_(
  105144. FLAC__StreamEncoder *encoder,
  105145. const FLAC__int32 signal[],
  105146. unsigned blocksize,
  105147. unsigned subframe_bps,
  105148. FLAC__Subframe *subframe
  105149. )
  105150. {
  105151. unsigned estimate;
  105152. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105153. subframe->data.verbatim.data = signal;
  105154. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105155. #if SPOTCHECK_ESTIMATE
  105156. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105157. #else
  105158. (void)encoder;
  105159. #endif
  105160. return estimate;
  105161. }
  105162. unsigned find_best_partition_order_(
  105163. FLAC__StreamEncoderPrivate *private_,
  105164. const FLAC__int32 residual[],
  105165. FLAC__uint64 abs_residual_partition_sums[],
  105166. unsigned raw_bits_per_partition[],
  105167. unsigned residual_samples,
  105168. unsigned predictor_order,
  105169. unsigned rice_parameter,
  105170. unsigned rice_parameter_limit,
  105171. unsigned min_partition_order,
  105172. unsigned max_partition_order,
  105173. unsigned bps,
  105174. FLAC__bool do_escape_coding,
  105175. unsigned rice_parameter_search_dist,
  105176. FLAC__EntropyCodingMethod *best_ecm
  105177. )
  105178. {
  105179. unsigned residual_bits, best_residual_bits = 0;
  105180. unsigned best_parameters_index = 0;
  105181. unsigned best_partition_order = 0;
  105182. const unsigned blocksize = residual_samples + predictor_order;
  105183. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105184. min_partition_order = min(min_partition_order, max_partition_order);
  105185. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105186. if(do_escape_coding)
  105187. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105188. {
  105189. int partition_order;
  105190. unsigned sum;
  105191. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105192. if(!
  105193. set_partitioned_rice_(
  105194. #ifdef EXACT_RICE_BITS_CALCULATION
  105195. residual,
  105196. #endif
  105197. abs_residual_partition_sums+sum,
  105198. raw_bits_per_partition+sum,
  105199. residual_samples,
  105200. predictor_order,
  105201. rice_parameter,
  105202. rice_parameter_limit,
  105203. rice_parameter_search_dist,
  105204. (unsigned)partition_order,
  105205. do_escape_coding,
  105206. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105207. &residual_bits
  105208. )
  105209. )
  105210. {
  105211. FLAC__ASSERT(best_residual_bits != 0);
  105212. break;
  105213. }
  105214. sum += 1u << partition_order;
  105215. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105216. best_residual_bits = residual_bits;
  105217. best_parameters_index = !best_parameters_index;
  105218. best_partition_order = partition_order;
  105219. }
  105220. }
  105221. }
  105222. best_ecm->data.partitioned_rice.order = best_partition_order;
  105223. {
  105224. /*
  105225. * We are allowed to de-const the pointer based on our special
  105226. * knowledge; it is const to the outside world.
  105227. */
  105228. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105229. unsigned partition;
  105230. /* save best parameters and raw_bits */
  105231. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105232. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105233. if(do_escape_coding)
  105234. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105235. /*
  105236. * Now need to check if the type should be changed to
  105237. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105238. * size of the rice parameters.
  105239. */
  105240. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105241. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105242. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105243. break;
  105244. }
  105245. }
  105246. }
  105247. return best_residual_bits;
  105248. }
  105249. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105250. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105251. const FLAC__int32 residual[],
  105252. FLAC__uint64 abs_residual_partition_sums[],
  105253. unsigned blocksize,
  105254. unsigned predictor_order,
  105255. unsigned min_partition_order,
  105256. unsigned max_partition_order
  105257. );
  105258. #endif
  105259. void precompute_partition_info_sums_(
  105260. const FLAC__int32 residual[],
  105261. FLAC__uint64 abs_residual_partition_sums[],
  105262. unsigned residual_samples,
  105263. unsigned predictor_order,
  105264. unsigned min_partition_order,
  105265. unsigned max_partition_order,
  105266. unsigned bps
  105267. )
  105268. {
  105269. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105270. unsigned partitions = 1u << max_partition_order;
  105271. FLAC__ASSERT(default_partition_samples > predictor_order);
  105272. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105273. /* slightly pessimistic but still catches all common cases */
  105274. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105275. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105276. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105277. return;
  105278. }
  105279. #endif
  105280. /* first do max_partition_order */
  105281. {
  105282. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105283. /* slightly pessimistic but still catches all common cases */
  105284. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105285. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105286. FLAC__uint32 abs_residual_partition_sum;
  105287. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105288. end += default_partition_samples;
  105289. abs_residual_partition_sum = 0;
  105290. for( ; residual_sample < end; residual_sample++)
  105291. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105292. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105293. }
  105294. }
  105295. else { /* have to pessimistically use 64 bits for accumulator */
  105296. FLAC__uint64 abs_residual_partition_sum;
  105297. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105298. end += default_partition_samples;
  105299. abs_residual_partition_sum = 0;
  105300. for( ; residual_sample < end; residual_sample++)
  105301. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105302. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105303. }
  105304. }
  105305. }
  105306. /* now merge partitions for lower orders */
  105307. {
  105308. unsigned from_partition = 0, to_partition = partitions;
  105309. int partition_order;
  105310. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105311. unsigned i;
  105312. partitions >>= 1;
  105313. for(i = 0; i < partitions; i++) {
  105314. abs_residual_partition_sums[to_partition++] =
  105315. abs_residual_partition_sums[from_partition ] +
  105316. abs_residual_partition_sums[from_partition+1];
  105317. from_partition += 2;
  105318. }
  105319. }
  105320. }
  105321. }
  105322. void precompute_partition_info_escapes_(
  105323. const FLAC__int32 residual[],
  105324. unsigned raw_bits_per_partition[],
  105325. unsigned residual_samples,
  105326. unsigned predictor_order,
  105327. unsigned min_partition_order,
  105328. unsigned max_partition_order
  105329. )
  105330. {
  105331. int partition_order;
  105332. unsigned from_partition, to_partition = 0;
  105333. const unsigned blocksize = residual_samples + predictor_order;
  105334. /* first do max_partition_order */
  105335. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105336. FLAC__int32 r;
  105337. FLAC__uint32 rmax;
  105338. unsigned partition, partition_sample, partition_samples, residual_sample;
  105339. const unsigned partitions = 1u << partition_order;
  105340. const unsigned default_partition_samples = blocksize >> partition_order;
  105341. FLAC__ASSERT(default_partition_samples > predictor_order);
  105342. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105343. partition_samples = default_partition_samples;
  105344. if(partition == 0)
  105345. partition_samples -= predictor_order;
  105346. rmax = 0;
  105347. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105348. r = residual[residual_sample++];
  105349. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105350. if(r < 0)
  105351. rmax |= ~r;
  105352. else
  105353. rmax |= r;
  105354. }
  105355. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105356. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105357. }
  105358. to_partition = partitions;
  105359. break; /*@@@ yuck, should remove the 'for' loop instead */
  105360. }
  105361. /* now merge partitions for lower orders */
  105362. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105363. unsigned m;
  105364. unsigned i;
  105365. const unsigned partitions = 1u << partition_order;
  105366. for(i = 0; i < partitions; i++) {
  105367. m = raw_bits_per_partition[from_partition];
  105368. from_partition++;
  105369. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105370. from_partition++;
  105371. to_partition++;
  105372. }
  105373. }
  105374. }
  105375. #ifdef EXACT_RICE_BITS_CALCULATION
  105376. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105377. const unsigned rice_parameter,
  105378. const unsigned partition_samples,
  105379. const FLAC__int32 *residual
  105380. )
  105381. {
  105382. unsigned i, partition_bits =
  105383. 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 */
  105384. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105385. ;
  105386. for(i = 0; i < partition_samples; i++)
  105387. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105388. return partition_bits;
  105389. }
  105390. #else
  105391. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105392. const unsigned rice_parameter,
  105393. const unsigned partition_samples,
  105394. const FLAC__uint64 abs_residual_partition_sum
  105395. )
  105396. {
  105397. return
  105398. 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 */
  105399. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105400. (
  105401. rice_parameter?
  105402. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105403. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105404. )
  105405. - (partition_samples >> 1)
  105406. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105407. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105408. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105409. * So the subtraction term tries to guess how many extra bits were contributed.
  105410. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105411. */
  105412. ;
  105413. }
  105414. #endif
  105415. FLAC__bool set_partitioned_rice_(
  105416. #ifdef EXACT_RICE_BITS_CALCULATION
  105417. const FLAC__int32 residual[],
  105418. #endif
  105419. const FLAC__uint64 abs_residual_partition_sums[],
  105420. const unsigned raw_bits_per_partition[],
  105421. const unsigned residual_samples,
  105422. const unsigned predictor_order,
  105423. const unsigned suggested_rice_parameter,
  105424. const unsigned rice_parameter_limit,
  105425. const unsigned rice_parameter_search_dist,
  105426. const unsigned partition_order,
  105427. const FLAC__bool search_for_escapes,
  105428. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105429. unsigned *bits
  105430. )
  105431. {
  105432. unsigned rice_parameter, partition_bits;
  105433. unsigned best_partition_bits, best_rice_parameter = 0;
  105434. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105435. unsigned *parameters, *raw_bits;
  105436. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105437. unsigned min_rice_parameter, max_rice_parameter;
  105438. #else
  105439. (void)rice_parameter_search_dist;
  105440. #endif
  105441. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105442. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105443. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105444. parameters = partitioned_rice_contents->parameters;
  105445. raw_bits = partitioned_rice_contents->raw_bits;
  105446. if(partition_order == 0) {
  105447. best_partition_bits = (unsigned)(-1);
  105448. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105449. if(rice_parameter_search_dist) {
  105450. if(suggested_rice_parameter < rice_parameter_search_dist)
  105451. min_rice_parameter = 0;
  105452. else
  105453. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105454. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105455. if(max_rice_parameter >= rice_parameter_limit) {
  105456. #ifdef DEBUG_VERBOSE
  105457. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105458. #endif
  105459. max_rice_parameter = rice_parameter_limit - 1;
  105460. }
  105461. }
  105462. else
  105463. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105464. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105465. #else
  105466. rice_parameter = suggested_rice_parameter;
  105467. #endif
  105468. #ifdef EXACT_RICE_BITS_CALCULATION
  105469. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105470. #else
  105471. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105472. #endif
  105473. if(partition_bits < best_partition_bits) {
  105474. best_rice_parameter = rice_parameter;
  105475. best_partition_bits = partition_bits;
  105476. }
  105477. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105478. }
  105479. #endif
  105480. if(search_for_escapes) {
  105481. 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;
  105482. if(partition_bits <= best_partition_bits) {
  105483. raw_bits[0] = raw_bits_per_partition[0];
  105484. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105485. best_partition_bits = partition_bits;
  105486. }
  105487. else
  105488. raw_bits[0] = 0;
  105489. }
  105490. parameters[0] = best_rice_parameter;
  105491. bits_ += best_partition_bits;
  105492. }
  105493. else {
  105494. unsigned partition, residual_sample;
  105495. unsigned partition_samples;
  105496. FLAC__uint64 mean, k;
  105497. const unsigned partitions = 1u << partition_order;
  105498. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105499. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105500. if(partition == 0) {
  105501. if(partition_samples <= predictor_order)
  105502. return false;
  105503. else
  105504. partition_samples -= predictor_order;
  105505. }
  105506. mean = abs_residual_partition_sums[partition];
  105507. /* we are basically calculating the size in bits of the
  105508. * average residual magnitude in the partition:
  105509. * rice_parameter = floor(log2(mean/partition_samples))
  105510. * 'mean' is not a good name for the variable, it is
  105511. * actually the sum of magnitudes of all residual values
  105512. * in the partition, so the actual mean is
  105513. * mean/partition_samples
  105514. */
  105515. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105516. ;
  105517. if(rice_parameter >= rice_parameter_limit) {
  105518. #ifdef DEBUG_VERBOSE
  105519. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105520. #endif
  105521. rice_parameter = rice_parameter_limit - 1;
  105522. }
  105523. best_partition_bits = (unsigned)(-1);
  105524. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105525. if(rice_parameter_search_dist) {
  105526. if(rice_parameter < rice_parameter_search_dist)
  105527. min_rice_parameter = 0;
  105528. else
  105529. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105530. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105531. if(max_rice_parameter >= rice_parameter_limit) {
  105532. #ifdef DEBUG_VERBOSE
  105533. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105534. #endif
  105535. max_rice_parameter = rice_parameter_limit - 1;
  105536. }
  105537. }
  105538. else
  105539. min_rice_parameter = max_rice_parameter = rice_parameter;
  105540. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105541. #endif
  105542. #ifdef EXACT_RICE_BITS_CALCULATION
  105543. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105544. #else
  105545. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105546. #endif
  105547. if(partition_bits < best_partition_bits) {
  105548. best_rice_parameter = rice_parameter;
  105549. best_partition_bits = partition_bits;
  105550. }
  105551. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105552. }
  105553. #endif
  105554. if(search_for_escapes) {
  105555. 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;
  105556. if(partition_bits <= best_partition_bits) {
  105557. raw_bits[partition] = raw_bits_per_partition[partition];
  105558. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105559. best_partition_bits = partition_bits;
  105560. }
  105561. else
  105562. raw_bits[partition] = 0;
  105563. }
  105564. parameters[partition] = best_rice_parameter;
  105565. bits_ += best_partition_bits;
  105566. residual_sample += partition_samples;
  105567. }
  105568. }
  105569. *bits = bits_;
  105570. return true;
  105571. }
  105572. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105573. {
  105574. unsigned i, shift;
  105575. FLAC__int32 x = 0;
  105576. for(i = 0; i < samples && !(x&1); i++)
  105577. x |= signal[i];
  105578. if(x == 0) {
  105579. shift = 0;
  105580. }
  105581. else {
  105582. for(shift = 0; !(x&1); shift++)
  105583. x >>= 1;
  105584. }
  105585. if(shift > 0) {
  105586. for(i = 0; i < samples; i++)
  105587. signal[i] >>= shift;
  105588. }
  105589. return shift;
  105590. }
  105591. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105592. {
  105593. unsigned channel;
  105594. for(channel = 0; channel < channels; channel++)
  105595. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105596. fifo->tail += wide_samples;
  105597. FLAC__ASSERT(fifo->tail <= fifo->size);
  105598. }
  105599. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105600. {
  105601. unsigned channel;
  105602. unsigned sample, wide_sample;
  105603. unsigned tail = fifo->tail;
  105604. sample = input_offset * channels;
  105605. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105606. for(channel = 0; channel < channels; channel++)
  105607. fifo->data[channel][tail] = input[sample++];
  105608. tail++;
  105609. }
  105610. fifo->tail = tail;
  105611. FLAC__ASSERT(fifo->tail <= fifo->size);
  105612. }
  105613. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105614. {
  105615. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105616. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105617. (void)decoder;
  105618. if(encoder->private_->verify.needs_magic_hack) {
  105619. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105620. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105621. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105622. encoder->private_->verify.needs_magic_hack = false;
  105623. }
  105624. else {
  105625. if(encoded_bytes == 0) {
  105626. /*
  105627. * If we get here, a FIFO underflow has occurred,
  105628. * which means there is a bug somewhere.
  105629. */
  105630. FLAC__ASSERT(0);
  105631. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105632. }
  105633. else if(encoded_bytes < *bytes)
  105634. *bytes = encoded_bytes;
  105635. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105636. encoder->private_->verify.output.data += *bytes;
  105637. encoder->private_->verify.output.bytes -= *bytes;
  105638. }
  105639. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105640. }
  105641. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105642. {
  105643. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105644. unsigned channel;
  105645. const unsigned channels = frame->header.channels;
  105646. const unsigned blocksize = frame->header.blocksize;
  105647. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105648. (void)decoder;
  105649. for(channel = 0; channel < channels; channel++) {
  105650. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105651. unsigned i, sample = 0;
  105652. FLAC__int32 expect = 0, got = 0;
  105653. for(i = 0; i < blocksize; i++) {
  105654. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105655. sample = i;
  105656. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105657. got = (FLAC__int32)buffer[channel][i];
  105658. break;
  105659. }
  105660. }
  105661. FLAC__ASSERT(i < blocksize);
  105662. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105663. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105664. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105665. encoder->private_->verify.error_stats.channel = channel;
  105666. encoder->private_->verify.error_stats.sample = sample;
  105667. encoder->private_->verify.error_stats.expected = expect;
  105668. encoder->private_->verify.error_stats.got = got;
  105669. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  105670. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  105671. }
  105672. }
  105673. /* dequeue the frame from the fifo */
  105674. encoder->private_->verify.input_fifo.tail -= blocksize;
  105675. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  105676. for(channel = 0; channel < channels; channel++)
  105677. 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]));
  105678. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  105679. }
  105680. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  105681. {
  105682. (void)decoder, (void)metadata, (void)client_data;
  105683. }
  105684. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  105685. {
  105686. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105687. (void)decoder, (void)status;
  105688. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  105689. }
  105690. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105691. {
  105692. (void)client_data;
  105693. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  105694. if (*bytes == 0) {
  105695. if (feof(encoder->private_->file))
  105696. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  105697. else if (ferror(encoder->private_->file))
  105698. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  105699. }
  105700. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  105701. }
  105702. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  105703. {
  105704. (void)client_data;
  105705. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  105706. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  105707. else
  105708. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  105709. }
  105710. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  105711. {
  105712. off_t offset;
  105713. (void)client_data;
  105714. offset = ftello(encoder->private_->file);
  105715. if(offset < 0) {
  105716. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  105717. }
  105718. else {
  105719. *absolute_byte_offset = (FLAC__uint64)offset;
  105720. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  105721. }
  105722. }
  105723. #ifdef FLAC__VALGRIND_TESTING
  105724. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  105725. {
  105726. size_t ret = fwrite(ptr, size, nmemb, stream);
  105727. if(!ferror(stream))
  105728. fflush(stream);
  105729. return ret;
  105730. }
  105731. #else
  105732. #define local__fwrite fwrite
  105733. #endif
  105734. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  105735. {
  105736. (void)client_data, (void)current_frame;
  105737. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  105738. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  105739. #if FLAC__HAS_OGG
  105740. /* We would like to be able to use 'samples > 0' in the
  105741. * clause here but currently because of the nature of our
  105742. * Ogg writing implementation, 'samples' is always 0 (see
  105743. * ogg_encoder_aspect.c). The downside is extra progress
  105744. * callbacks.
  105745. */
  105746. encoder->private_->is_ogg? true :
  105747. #endif
  105748. samples > 0
  105749. );
  105750. if(call_it) {
  105751. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  105752. * because at this point in the callback chain, the stats
  105753. * have not been updated. Only after we return and control
  105754. * gets back to write_frame_() are the stats updated
  105755. */
  105756. 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);
  105757. }
  105758. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  105759. }
  105760. else
  105761. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  105762. }
  105763. /*
  105764. * This will forcibly set stdout to binary mode (for OSes that require it)
  105765. */
  105766. FILE *get_binary_stdout_(void)
  105767. {
  105768. /* if something breaks here it is probably due to the presence or
  105769. * absence of an underscore before the identifiers 'setmode',
  105770. * 'fileno', and/or 'O_BINARY'; check your system header files.
  105771. */
  105772. #if defined _MSC_VER || defined __MINGW32__
  105773. _setmode(_fileno(stdout), _O_BINARY);
  105774. #elif defined __CYGWIN__
  105775. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  105776. setmode(_fileno(stdout), _O_BINARY);
  105777. #elif defined __EMX__
  105778. setmode(fileno(stdout), O_BINARY);
  105779. #endif
  105780. return stdout;
  105781. }
  105782. #endif
  105783. /*** End of inlined file: stream_encoder.c ***/
  105784. /*** Start of inlined file: stream_encoder_framing.c ***/
  105785. /*** Start of inlined file: juce_FlacHeader.h ***/
  105786. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  105787. // tasks..
  105788. #define VERSION "1.2.1"
  105789. #define FLAC__NO_DLL 1
  105790. #if JUCE_MSVC
  105791. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  105792. #endif
  105793. #if JUCE_MAC
  105794. #define FLAC__SYS_DARWIN 1
  105795. #endif
  105796. /*** End of inlined file: juce_FlacHeader.h ***/
  105797. #if JUCE_USE_FLAC
  105798. #if HAVE_CONFIG_H
  105799. # include <config.h>
  105800. #endif
  105801. #include <stdio.h>
  105802. #include <string.h> /* for strlen() */
  105803. #ifdef max
  105804. #undef max
  105805. #endif
  105806. #define max(x,y) ((x)>(y)?(x):(y))
  105807. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  105808. 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);
  105809. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  105810. {
  105811. unsigned i, j;
  105812. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  105813. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  105814. return false;
  105815. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  105816. return false;
  105817. /*
  105818. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  105819. */
  105820. i = metadata->length;
  105821. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  105822. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  105823. i -= metadata->data.vorbis_comment.vendor_string.length;
  105824. i += vendor_string_length;
  105825. }
  105826. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  105827. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  105828. return false;
  105829. switch(metadata->type) {
  105830. case FLAC__METADATA_TYPE_STREAMINFO:
  105831. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  105832. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  105833. return false;
  105834. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  105835. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  105836. return false;
  105837. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  105838. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  105839. return false;
  105840. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  105841. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  105842. return false;
  105843. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  105844. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  105845. return false;
  105846. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  105847. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  105848. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  105849. return false;
  105850. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  105851. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  105852. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  105853. return false;
  105854. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  105855. return false;
  105856. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  105857. return false;
  105858. break;
  105859. case FLAC__METADATA_TYPE_PADDING:
  105860. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  105861. return false;
  105862. break;
  105863. case FLAC__METADATA_TYPE_APPLICATION:
  105864. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  105865. return false;
  105866. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  105867. return false;
  105868. break;
  105869. case FLAC__METADATA_TYPE_SEEKTABLE:
  105870. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  105871. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  105872. return false;
  105873. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  105874. return false;
  105875. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  105876. return false;
  105877. }
  105878. break;
  105879. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  105880. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  105881. return false;
  105882. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  105883. return false;
  105884. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  105885. return false;
  105886. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  105887. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  105888. return false;
  105889. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  105890. return false;
  105891. }
  105892. break;
  105893. case FLAC__METADATA_TYPE_CUESHEET:
  105894. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  105895. 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))
  105896. return false;
  105897. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  105898. return false;
  105899. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  105900. return false;
  105901. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  105902. return false;
  105903. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  105904. return false;
  105905. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  105906. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  105907. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  105908. return false;
  105909. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  105910. return false;
  105911. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  105912. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  105913. return false;
  105914. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  105915. return false;
  105916. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  105917. return false;
  105918. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  105919. return false;
  105920. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  105921. return false;
  105922. for(j = 0; j < track->num_indices; j++) {
  105923. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  105924. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  105925. return false;
  105926. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  105927. return false;
  105928. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  105929. return false;
  105930. }
  105931. }
  105932. break;
  105933. case FLAC__METADATA_TYPE_PICTURE:
  105934. {
  105935. size_t len;
  105936. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  105937. return false;
  105938. len = strlen(metadata->data.picture.mime_type);
  105939. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  105940. return false;
  105941. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  105942. return false;
  105943. len = strlen((const char *)metadata->data.picture.description);
  105944. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  105945. return false;
  105946. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  105947. return false;
  105948. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  105949. return false;
  105950. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  105951. return false;
  105952. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  105953. return false;
  105954. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  105955. return false;
  105956. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  105957. return false;
  105958. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  105959. return false;
  105960. }
  105961. break;
  105962. default:
  105963. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  105964. return false;
  105965. break;
  105966. }
  105967. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105968. return true;
  105969. }
  105970. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  105971. {
  105972. unsigned u, blocksize_hint, sample_rate_hint;
  105973. FLAC__byte crc;
  105974. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  105975. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  105976. return false;
  105977. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  105978. return false;
  105979. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  105980. return false;
  105981. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  105982. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  105983. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  105984. blocksize_hint = 0;
  105985. switch(header->blocksize) {
  105986. case 192: u = 1; break;
  105987. case 576: u = 2; break;
  105988. case 1152: u = 3; break;
  105989. case 2304: u = 4; break;
  105990. case 4608: u = 5; break;
  105991. case 256: u = 8; break;
  105992. case 512: u = 9; break;
  105993. case 1024: u = 10; break;
  105994. case 2048: u = 11; break;
  105995. case 4096: u = 12; break;
  105996. case 8192: u = 13; break;
  105997. case 16384: u = 14; break;
  105998. case 32768: u = 15; break;
  105999. default:
  106000. if(header->blocksize <= 0x100)
  106001. blocksize_hint = u = 6;
  106002. else
  106003. blocksize_hint = u = 7;
  106004. break;
  106005. }
  106006. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106007. return false;
  106008. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106009. sample_rate_hint = 0;
  106010. switch(header->sample_rate) {
  106011. case 88200: u = 1; break;
  106012. case 176400: u = 2; break;
  106013. case 192000: u = 3; break;
  106014. case 8000: u = 4; break;
  106015. case 16000: u = 5; break;
  106016. case 22050: u = 6; break;
  106017. case 24000: u = 7; break;
  106018. case 32000: u = 8; break;
  106019. case 44100: u = 9; break;
  106020. case 48000: u = 10; break;
  106021. case 96000: u = 11; break;
  106022. default:
  106023. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106024. sample_rate_hint = u = 12;
  106025. else if(header->sample_rate % 10 == 0)
  106026. sample_rate_hint = u = 14;
  106027. else if(header->sample_rate <= 0xffff)
  106028. sample_rate_hint = u = 13;
  106029. else
  106030. u = 0;
  106031. break;
  106032. }
  106033. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106034. return false;
  106035. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106036. switch(header->channel_assignment) {
  106037. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106038. u = header->channels - 1;
  106039. break;
  106040. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106041. FLAC__ASSERT(header->channels == 2);
  106042. u = 8;
  106043. break;
  106044. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106045. FLAC__ASSERT(header->channels == 2);
  106046. u = 9;
  106047. break;
  106048. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106049. FLAC__ASSERT(header->channels == 2);
  106050. u = 10;
  106051. break;
  106052. default:
  106053. FLAC__ASSERT(0);
  106054. }
  106055. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106056. return false;
  106057. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106058. switch(header->bits_per_sample) {
  106059. case 8 : u = 1; break;
  106060. case 12: u = 2; break;
  106061. case 16: u = 4; break;
  106062. case 20: u = 5; break;
  106063. case 24: u = 6; break;
  106064. default: u = 0; break;
  106065. }
  106066. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106067. return false;
  106068. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106069. return false;
  106070. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106071. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106072. return false;
  106073. }
  106074. else {
  106075. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106076. return false;
  106077. }
  106078. if(blocksize_hint)
  106079. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106080. return false;
  106081. switch(sample_rate_hint) {
  106082. case 12:
  106083. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106084. return false;
  106085. break;
  106086. case 13:
  106087. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106088. return false;
  106089. break;
  106090. case 14:
  106091. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106092. return false;
  106093. break;
  106094. }
  106095. /* write the CRC */
  106096. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106097. return false;
  106098. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106099. return false;
  106100. return true;
  106101. }
  106102. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106103. {
  106104. FLAC__bool ok;
  106105. ok =
  106106. 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) &&
  106107. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106108. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106109. ;
  106110. return ok;
  106111. }
  106112. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106113. {
  106114. unsigned i;
  106115. 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))
  106116. return false;
  106117. if(wasted_bits)
  106118. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106119. return false;
  106120. for(i = 0; i < subframe->order; i++)
  106121. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106122. return false;
  106123. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106124. return false;
  106125. switch(subframe->entropy_coding_method.type) {
  106126. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106127. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106128. if(!add_residual_partitioned_rice_(
  106129. bw,
  106130. subframe->residual,
  106131. residual_samples,
  106132. subframe->order,
  106133. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106134. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106135. subframe->entropy_coding_method.data.partitioned_rice.order,
  106136. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106137. ))
  106138. return false;
  106139. break;
  106140. default:
  106141. FLAC__ASSERT(0);
  106142. }
  106143. return true;
  106144. }
  106145. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106146. {
  106147. unsigned i;
  106148. 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))
  106149. return false;
  106150. if(wasted_bits)
  106151. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106152. return false;
  106153. for(i = 0; i < subframe->order; i++)
  106154. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106155. return false;
  106156. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106157. return false;
  106158. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106159. return false;
  106160. for(i = 0; i < subframe->order; i++)
  106161. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106162. return false;
  106163. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106164. return false;
  106165. switch(subframe->entropy_coding_method.type) {
  106166. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106167. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106168. if(!add_residual_partitioned_rice_(
  106169. bw,
  106170. subframe->residual,
  106171. residual_samples,
  106172. subframe->order,
  106173. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106174. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106175. subframe->entropy_coding_method.data.partitioned_rice.order,
  106176. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106177. ))
  106178. return false;
  106179. break;
  106180. default:
  106181. FLAC__ASSERT(0);
  106182. }
  106183. return true;
  106184. }
  106185. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106186. {
  106187. unsigned i;
  106188. const FLAC__int32 *signal = subframe->data;
  106189. 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))
  106190. return false;
  106191. if(wasted_bits)
  106192. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106193. return false;
  106194. for(i = 0; i < samples; i++)
  106195. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106196. return false;
  106197. return true;
  106198. }
  106199. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106200. {
  106201. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106202. return false;
  106203. switch(method->type) {
  106204. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106205. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106206. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106207. return false;
  106208. break;
  106209. default:
  106210. FLAC__ASSERT(0);
  106211. }
  106212. return true;
  106213. }
  106214. 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)
  106215. {
  106216. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106217. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106218. if(partition_order == 0) {
  106219. unsigned i;
  106220. if(raw_bits[0] == 0) {
  106221. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106222. return false;
  106223. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106224. return false;
  106225. }
  106226. else {
  106227. FLAC__ASSERT(rice_parameters[0] == 0);
  106228. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106229. return false;
  106230. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106231. return false;
  106232. for(i = 0; i < residual_samples; i++) {
  106233. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106234. return false;
  106235. }
  106236. }
  106237. return true;
  106238. }
  106239. else {
  106240. unsigned i, j, k = 0, k_last = 0;
  106241. unsigned partition_samples;
  106242. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106243. for(i = 0; i < (1u<<partition_order); i++) {
  106244. partition_samples = default_partition_samples;
  106245. if(i == 0)
  106246. partition_samples -= predictor_order;
  106247. k += partition_samples;
  106248. if(raw_bits[i] == 0) {
  106249. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106250. return false;
  106251. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106252. return false;
  106253. }
  106254. else {
  106255. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106256. return false;
  106257. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106258. return false;
  106259. for(j = k_last; j < k; j++) {
  106260. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106261. return false;
  106262. }
  106263. }
  106264. k_last = k;
  106265. }
  106266. return true;
  106267. }
  106268. }
  106269. #endif
  106270. /*** End of inlined file: stream_encoder_framing.c ***/
  106271. /*** Start of inlined file: window_flac.c ***/
  106272. /*** Start of inlined file: juce_FlacHeader.h ***/
  106273. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106274. // tasks..
  106275. #define VERSION "1.2.1"
  106276. #define FLAC__NO_DLL 1
  106277. #if JUCE_MSVC
  106278. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106279. #endif
  106280. #if JUCE_MAC
  106281. #define FLAC__SYS_DARWIN 1
  106282. #endif
  106283. /*** End of inlined file: juce_FlacHeader.h ***/
  106284. #if JUCE_USE_FLAC
  106285. #if HAVE_CONFIG_H
  106286. # include <config.h>
  106287. #endif
  106288. #include <math.h>
  106289. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106290. #ifndef M_PI
  106291. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106292. #define M_PI 3.14159265358979323846
  106293. #endif
  106294. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106295. {
  106296. const FLAC__int32 N = L - 1;
  106297. FLAC__int32 n;
  106298. if (L & 1) {
  106299. for (n = 0; n <= N/2; n++)
  106300. window[n] = 2.0f * n / (float)N;
  106301. for (; n <= N; n++)
  106302. window[n] = 2.0f - 2.0f * n / (float)N;
  106303. }
  106304. else {
  106305. for (n = 0; n <= L/2-1; n++)
  106306. window[n] = 2.0f * n / (float)N;
  106307. for (; n <= N; n++)
  106308. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106309. }
  106310. }
  106311. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106312. {
  106313. const FLAC__int32 N = L - 1;
  106314. FLAC__int32 n;
  106315. for (n = 0; n < L; n++)
  106316. 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)));
  106317. }
  106318. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106319. {
  106320. const FLAC__int32 N = L - 1;
  106321. FLAC__int32 n;
  106322. for (n = 0; n < L; n++)
  106323. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106324. }
  106325. /* 4-term -92dB side-lobe */
  106326. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106327. {
  106328. const FLAC__int32 N = L - 1;
  106329. FLAC__int32 n;
  106330. for (n = 0; n <= N; n++)
  106331. 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));
  106332. }
  106333. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106334. {
  106335. const FLAC__int32 N = L - 1;
  106336. const double N2 = (double)N / 2.;
  106337. FLAC__int32 n;
  106338. for (n = 0; n <= N; n++) {
  106339. double k = ((double)n - N2) / N2;
  106340. k = 1.0f - k * k;
  106341. window[n] = (FLAC__real)(k * k);
  106342. }
  106343. }
  106344. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106345. {
  106346. const FLAC__int32 N = L - 1;
  106347. FLAC__int32 n;
  106348. for (n = 0; n < L; n++)
  106349. 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));
  106350. }
  106351. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106352. {
  106353. const FLAC__int32 N = L - 1;
  106354. const double N2 = (double)N / 2.;
  106355. FLAC__int32 n;
  106356. for (n = 0; n <= N; n++) {
  106357. const double k = ((double)n - N2) / (stddev * N2);
  106358. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106359. }
  106360. }
  106361. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106362. {
  106363. const FLAC__int32 N = L - 1;
  106364. FLAC__int32 n;
  106365. for (n = 0; n < L; n++)
  106366. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106367. }
  106368. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106369. {
  106370. const FLAC__int32 N = L - 1;
  106371. FLAC__int32 n;
  106372. for (n = 0; n < L; n++)
  106373. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106374. }
  106375. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106376. {
  106377. const FLAC__int32 N = L - 1;
  106378. FLAC__int32 n;
  106379. for (n = 0; n < L; n++)
  106380. 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));
  106381. }
  106382. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106383. {
  106384. const FLAC__int32 N = L - 1;
  106385. FLAC__int32 n;
  106386. for (n = 0; n < L; n++)
  106387. 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));
  106388. }
  106389. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106390. {
  106391. FLAC__int32 n;
  106392. for (n = 0; n < L; n++)
  106393. window[n] = 1.0f;
  106394. }
  106395. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106396. {
  106397. FLAC__int32 n;
  106398. if (L & 1) {
  106399. for (n = 1; n <= L+1/2; n++)
  106400. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106401. for (; n <= L; n++)
  106402. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106403. }
  106404. else {
  106405. for (n = 1; n <= L/2; n++)
  106406. window[n-1] = 2.0f * n / (float)L;
  106407. for (; n <= L; n++)
  106408. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106409. }
  106410. }
  106411. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106412. {
  106413. if (p <= 0.0)
  106414. FLAC__window_rectangle(window, L);
  106415. else if (p >= 1.0)
  106416. FLAC__window_hann(window, L);
  106417. else {
  106418. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106419. FLAC__int32 n;
  106420. /* start with rectangle... */
  106421. FLAC__window_rectangle(window, L);
  106422. /* ...replace ends with hann */
  106423. if (Np > 0) {
  106424. for (n = 0; n <= Np; n++) {
  106425. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106426. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106427. }
  106428. }
  106429. }
  106430. }
  106431. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106432. {
  106433. const FLAC__int32 N = L - 1;
  106434. const double N2 = (double)N / 2.;
  106435. FLAC__int32 n;
  106436. for (n = 0; n <= N; n++) {
  106437. const double k = ((double)n - N2) / N2;
  106438. window[n] = (FLAC__real)(1.0f - k * k);
  106439. }
  106440. }
  106441. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106442. #endif
  106443. /*** End of inlined file: window_flac.c ***/
  106444. #else
  106445. #include <FLAC/all.h>
  106446. #endif
  106447. }
  106448. #undef max
  106449. #undef min
  106450. BEGIN_JUCE_NAMESPACE
  106451. static const char* const flacFormatName = "FLAC file";
  106452. static const char* const flacExtensions[] = { ".flac", 0 };
  106453. class FlacReader : public AudioFormatReader
  106454. {
  106455. public:
  106456. FlacReader (InputStream* const in)
  106457. : AudioFormatReader (in, TRANS (flacFormatName)),
  106458. reservoir (2, 0),
  106459. reservoirStart (0),
  106460. samplesInReservoir (0),
  106461. scanningForLength (false)
  106462. {
  106463. using namespace FlacNamespace;
  106464. lengthInSamples = 0;
  106465. decoder = FLAC__stream_decoder_new();
  106466. ok = FLAC__stream_decoder_init_stream (decoder,
  106467. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106468. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106469. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106470. if (ok)
  106471. {
  106472. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106473. if (lengthInSamples == 0 && sampleRate > 0)
  106474. {
  106475. // the length hasn't been stored in the metadata, so we'll need to
  106476. // work it out the length the hard way, by scanning the whole file..
  106477. scanningForLength = true;
  106478. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106479. scanningForLength = false;
  106480. const int64 tempLength = lengthInSamples;
  106481. FLAC__stream_decoder_reset (decoder);
  106482. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106483. lengthInSamples = tempLength;
  106484. }
  106485. }
  106486. }
  106487. ~FlacReader()
  106488. {
  106489. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106490. }
  106491. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106492. {
  106493. sampleRate = info.sample_rate;
  106494. bitsPerSample = info.bits_per_sample;
  106495. lengthInSamples = (unsigned int) info.total_samples;
  106496. numChannels = info.channels;
  106497. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106498. }
  106499. // returns the number of samples read
  106500. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106501. int64 startSampleInFile, int numSamples)
  106502. {
  106503. using namespace FlacNamespace;
  106504. if (! ok)
  106505. return false;
  106506. while (numSamples > 0)
  106507. {
  106508. if (startSampleInFile >= reservoirStart
  106509. && startSampleInFile < reservoirStart + samplesInReservoir)
  106510. {
  106511. const int num = (int) jmin ((int64) numSamples,
  106512. reservoirStart + samplesInReservoir - startSampleInFile);
  106513. jassert (num > 0);
  106514. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106515. if (destSamples[i] != 0)
  106516. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106517. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106518. sizeof (int) * num);
  106519. startOffsetInDestBuffer += num;
  106520. startSampleInFile += num;
  106521. numSamples -= num;
  106522. }
  106523. else
  106524. {
  106525. if (startSampleInFile >= (int) lengthInSamples)
  106526. {
  106527. samplesInReservoir = 0;
  106528. }
  106529. else if (startSampleInFile < reservoirStart
  106530. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106531. {
  106532. // had some problems with flac crashing if the read pos is aligned more
  106533. // accurately than this. Probably fixed in newer versions of the library, though.
  106534. reservoirStart = (int) (startSampleInFile & ~511);
  106535. samplesInReservoir = 0;
  106536. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106537. }
  106538. else
  106539. {
  106540. reservoirStart += samplesInReservoir;
  106541. samplesInReservoir = 0;
  106542. FLAC__stream_decoder_process_single (decoder);
  106543. }
  106544. if (samplesInReservoir == 0)
  106545. break;
  106546. }
  106547. }
  106548. if (numSamples > 0)
  106549. {
  106550. for (int i = numDestChannels; --i >= 0;)
  106551. if (destSamples[i] != 0)
  106552. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106553. sizeof (int) * numSamples);
  106554. }
  106555. return true;
  106556. }
  106557. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106558. {
  106559. if (scanningForLength)
  106560. {
  106561. lengthInSamples += numSamples;
  106562. }
  106563. else
  106564. {
  106565. if (numSamples > reservoir.getNumSamples())
  106566. reservoir.setSize (numChannels, numSamples, false, false, true);
  106567. const int bitsToShift = 32 - bitsPerSample;
  106568. for (int i = 0; i < (int) numChannels; ++i)
  106569. {
  106570. const FlacNamespace::FLAC__int32* src = buffer[i];
  106571. int n = i;
  106572. while (src == 0 && n > 0)
  106573. src = buffer [--n];
  106574. if (src != 0)
  106575. {
  106576. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106577. for (int j = 0; j < numSamples; ++j)
  106578. dest[j] = src[j] << bitsToShift;
  106579. }
  106580. }
  106581. samplesInReservoir = numSamples;
  106582. }
  106583. }
  106584. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106585. {
  106586. using namespace FlacNamespace;
  106587. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106588. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106589. }
  106590. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106591. {
  106592. using namespace FlacNamespace;
  106593. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106594. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106595. }
  106596. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106597. {
  106598. using namespace FlacNamespace;
  106599. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106600. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106601. }
  106602. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106603. {
  106604. using namespace FlacNamespace;
  106605. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106606. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106607. }
  106608. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106609. {
  106610. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106611. }
  106612. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106613. const FlacNamespace::FLAC__Frame* frame,
  106614. const FlacNamespace::FLAC__int32* const buffer[],
  106615. void* client_data)
  106616. {
  106617. using namespace FlacNamespace;
  106618. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106619. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106620. }
  106621. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106622. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106623. void* client_data)
  106624. {
  106625. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106626. }
  106627. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106628. {
  106629. }
  106630. private:
  106631. FlacNamespace::FLAC__StreamDecoder* decoder;
  106632. AudioSampleBuffer reservoir;
  106633. int reservoirStart, samplesInReservoir;
  106634. bool ok, scanningForLength;
  106635. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacReader);
  106636. };
  106637. class FlacWriter : public AudioFormatWriter
  106638. {
  106639. public:
  106640. FlacWriter (OutputStream* const out, double sampleRate_,
  106641. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106642. : AudioFormatWriter (out, TRANS (flacFormatName),
  106643. sampleRate_, numChannels_, bitsPerSample_)
  106644. {
  106645. using namespace FlacNamespace;
  106646. encoder = FLAC__stream_encoder_new();
  106647. if (qualityOptionIndex > 0)
  106648. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106649. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106650. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106651. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106652. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106653. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106654. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106655. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106656. ok = FLAC__stream_encoder_init_stream (encoder,
  106657. encodeWriteCallback, encodeSeekCallback,
  106658. encodeTellCallback, encodeMetadataCallback,
  106659. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106660. }
  106661. ~FlacWriter()
  106662. {
  106663. if (ok)
  106664. {
  106665. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106666. output->flush();
  106667. }
  106668. else
  106669. {
  106670. output = 0; // to stop the base class deleting this, as it needs to be returned
  106671. // to the caller of createWriter()
  106672. }
  106673. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  106674. }
  106675. bool write (const int** samplesToWrite, int numSamples)
  106676. {
  106677. using namespace FlacNamespace;
  106678. if (! ok)
  106679. return false;
  106680. int* buf[3];
  106681. HeapBlock<int> temp;
  106682. const int bitsToShift = 32 - bitsPerSample;
  106683. if (bitsToShift > 0)
  106684. {
  106685. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  106686. temp.malloc (numSamples * numChannelsToWrite);
  106687. buf[0] = temp.getData();
  106688. buf[1] = temp.getData() + numSamples;
  106689. buf[2] = 0;
  106690. for (int i = numChannelsToWrite; --i >= 0;)
  106691. if (samplesToWrite[i] != 0)
  106692. for (int j = 0; j < numSamples; ++j)
  106693. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  106694. samplesToWrite = const_cast<const int**> (buf);
  106695. }
  106696. return FLAC__stream_encoder_process (encoder, (const FLAC__int32**) samplesToWrite, numSamples) != 0;
  106697. }
  106698. bool writeData (const void* const data, const int size) const
  106699. {
  106700. return output->write (data, size);
  106701. }
  106702. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  106703. {
  106704. using namespace FlacNamespace;
  106705. b += bytes;
  106706. for (int i = 0; i < bytes; ++i)
  106707. {
  106708. *(--b) = (FLAC__byte) (val & 0xff);
  106709. val >>= 8;
  106710. }
  106711. }
  106712. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  106713. {
  106714. using namespace FlacNamespace;
  106715. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  106716. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  106717. const unsigned int channelsMinus1 = info.channels - 1;
  106718. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  106719. packUint32 (info.min_blocksize, buffer, 2);
  106720. packUint32 (info.max_blocksize, buffer + 2, 2);
  106721. packUint32 (info.min_framesize, buffer + 4, 3);
  106722. packUint32 (info.max_framesize, buffer + 7, 3);
  106723. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  106724. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  106725. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  106726. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  106727. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  106728. memcpy (buffer + 18, info.md5sum, 16);
  106729. const bool seekOk = output->setPosition (4);
  106730. (void) seekOk;
  106731. // if this fails, you've given it an output stream that can't seek! It needs
  106732. // to be able to seek back to write the header
  106733. jassert (seekOk);
  106734. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106735. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  106736. }
  106737. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  106738. const FlacNamespace::FLAC__byte buffer[],
  106739. size_t bytes,
  106740. unsigned int /*samples*/,
  106741. unsigned int /*current_frame*/,
  106742. void* client_data)
  106743. {
  106744. using namespace FlacNamespace;
  106745. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  106746. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  106747. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106748. }
  106749. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  106750. {
  106751. using namespace FlacNamespace;
  106752. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  106753. }
  106754. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106755. {
  106756. using namespace FlacNamespace;
  106757. if (client_data == 0)
  106758. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  106759. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  106760. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106761. }
  106762. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  106763. {
  106764. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  106765. }
  106766. bool ok;
  106767. private:
  106768. FlacNamespace::FLAC__StreamEncoder* encoder;
  106769. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FlacWriter);
  106770. };
  106771. FlacAudioFormat::FlacAudioFormat()
  106772. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  106773. {
  106774. }
  106775. FlacAudioFormat::~FlacAudioFormat()
  106776. {
  106777. }
  106778. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  106779. {
  106780. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  106781. return Array <int> (rates);
  106782. }
  106783. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  106784. {
  106785. const int depths[] = { 16, 24, 0 };
  106786. return Array <int> (depths);
  106787. }
  106788. bool FlacAudioFormat::canDoStereo() { return true; }
  106789. bool FlacAudioFormat::canDoMono() { return true; }
  106790. bool FlacAudioFormat::isCompressed() { return true; }
  106791. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  106792. const bool deleteStreamIfOpeningFails)
  106793. {
  106794. ScopedPointer<FlacReader> r (new FlacReader (in));
  106795. if (r->sampleRate != 0)
  106796. return r.release();
  106797. if (! deleteStreamIfOpeningFails)
  106798. r->input = 0;
  106799. return 0;
  106800. }
  106801. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  106802. double sampleRate,
  106803. unsigned int numberOfChannels,
  106804. int bitsPerSample,
  106805. const StringPairArray& /*metadataValues*/,
  106806. int qualityOptionIndex)
  106807. {
  106808. if (getPossibleBitDepths().contains (bitsPerSample))
  106809. {
  106810. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  106811. if (w->ok)
  106812. return w.release();
  106813. }
  106814. return 0;
  106815. }
  106816. END_JUCE_NAMESPACE
  106817. #endif
  106818. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  106819. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  106820. #if JUCE_USE_OGGVORBIS
  106821. #if JUCE_MAC
  106822. #define __MACOSX__ 1
  106823. #endif
  106824. namespace OggVorbisNamespace
  106825. {
  106826. #if JUCE_INCLUDE_OGGVORBIS_CODE
  106827. /*** Start of inlined file: vorbisenc.h ***/
  106828. #ifndef _OV_ENC_H_
  106829. #define _OV_ENC_H_
  106830. #ifdef __cplusplus
  106831. extern "C"
  106832. {
  106833. #endif /* __cplusplus */
  106834. /*** Start of inlined file: codec.h ***/
  106835. #ifndef _vorbis_codec_h_
  106836. #define _vorbis_codec_h_
  106837. #ifdef __cplusplus
  106838. extern "C"
  106839. {
  106840. #endif /* __cplusplus */
  106841. /*** Start of inlined file: ogg.h ***/
  106842. #ifndef _OGG_H
  106843. #define _OGG_H
  106844. #ifdef __cplusplus
  106845. extern "C" {
  106846. #endif
  106847. /*** Start of inlined file: os_types.h ***/
  106848. #ifndef _OS_TYPES_H
  106849. #define _OS_TYPES_H
  106850. /* make it easy on the folks that want to compile the libs with a
  106851. different malloc than stdlib */
  106852. #define _ogg_malloc malloc
  106853. #define _ogg_calloc calloc
  106854. #define _ogg_realloc realloc
  106855. #define _ogg_free free
  106856. #if defined(_WIN32)
  106857. # if defined(__CYGWIN__)
  106858. # include <_G_config.h>
  106859. typedef _G_int64_t ogg_int64_t;
  106860. typedef _G_int32_t ogg_int32_t;
  106861. typedef _G_uint32_t ogg_uint32_t;
  106862. typedef _G_int16_t ogg_int16_t;
  106863. typedef _G_uint16_t ogg_uint16_t;
  106864. # elif defined(__MINGW32__)
  106865. typedef short ogg_int16_t;
  106866. typedef unsigned short ogg_uint16_t;
  106867. typedef int ogg_int32_t;
  106868. typedef unsigned int ogg_uint32_t;
  106869. typedef long long ogg_int64_t;
  106870. typedef unsigned long long ogg_uint64_t;
  106871. # elif defined(__MWERKS__)
  106872. typedef long long ogg_int64_t;
  106873. typedef int ogg_int32_t;
  106874. typedef unsigned int ogg_uint32_t;
  106875. typedef short ogg_int16_t;
  106876. typedef unsigned short ogg_uint16_t;
  106877. # else
  106878. /* MSVC/Borland */
  106879. typedef __int64 ogg_int64_t;
  106880. typedef __int32 ogg_int32_t;
  106881. typedef unsigned __int32 ogg_uint32_t;
  106882. typedef __int16 ogg_int16_t;
  106883. typedef unsigned __int16 ogg_uint16_t;
  106884. # endif
  106885. #elif defined(__MACOS__)
  106886. # include <sys/types.h>
  106887. typedef SInt16 ogg_int16_t;
  106888. typedef UInt16 ogg_uint16_t;
  106889. typedef SInt32 ogg_int32_t;
  106890. typedef UInt32 ogg_uint32_t;
  106891. typedef SInt64 ogg_int64_t;
  106892. #elif defined(__MACOSX__) /* MacOS X Framework build */
  106893. # include <sys/types.h>
  106894. typedef int16_t ogg_int16_t;
  106895. typedef u_int16_t ogg_uint16_t;
  106896. typedef int32_t ogg_int32_t;
  106897. typedef u_int32_t ogg_uint32_t;
  106898. typedef int64_t ogg_int64_t;
  106899. #elif defined(__BEOS__)
  106900. /* Be */
  106901. # include <inttypes.h>
  106902. typedef int16_t ogg_int16_t;
  106903. typedef u_int16_t ogg_uint16_t;
  106904. typedef int32_t ogg_int32_t;
  106905. typedef u_int32_t ogg_uint32_t;
  106906. typedef int64_t ogg_int64_t;
  106907. #elif defined (__EMX__)
  106908. /* OS/2 GCC */
  106909. typedef short ogg_int16_t;
  106910. typedef unsigned short ogg_uint16_t;
  106911. typedef int ogg_int32_t;
  106912. typedef unsigned int ogg_uint32_t;
  106913. typedef long long ogg_int64_t;
  106914. #elif defined (DJGPP)
  106915. /* DJGPP */
  106916. typedef short ogg_int16_t;
  106917. typedef int ogg_int32_t;
  106918. typedef unsigned int ogg_uint32_t;
  106919. typedef long long ogg_int64_t;
  106920. #elif defined(R5900)
  106921. /* PS2 EE */
  106922. typedef long ogg_int64_t;
  106923. typedef int ogg_int32_t;
  106924. typedef unsigned ogg_uint32_t;
  106925. typedef short ogg_int16_t;
  106926. #elif defined(__SYMBIAN32__)
  106927. /* Symbian GCC */
  106928. typedef signed short ogg_int16_t;
  106929. typedef unsigned short ogg_uint16_t;
  106930. typedef signed int ogg_int32_t;
  106931. typedef unsigned int ogg_uint32_t;
  106932. typedef long long int ogg_int64_t;
  106933. #else
  106934. # include <sys/types.h>
  106935. /*** Start of inlined file: config_types.h ***/
  106936. #ifndef __CONFIG_TYPES_H__
  106937. #define __CONFIG_TYPES_H__
  106938. typedef int16_t ogg_int16_t;
  106939. typedef unsigned short ogg_uint16_t;
  106940. typedef int32_t ogg_int32_t;
  106941. typedef unsigned int ogg_uint32_t;
  106942. typedef int64_t ogg_int64_t;
  106943. #endif
  106944. /*** End of inlined file: config_types.h ***/
  106945. #endif
  106946. #endif /* _OS_TYPES_H */
  106947. /*** End of inlined file: os_types.h ***/
  106948. typedef struct {
  106949. long endbyte;
  106950. int endbit;
  106951. unsigned char *buffer;
  106952. unsigned char *ptr;
  106953. long storage;
  106954. } oggpack_buffer;
  106955. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  106956. typedef struct {
  106957. unsigned char *header;
  106958. long header_len;
  106959. unsigned char *body;
  106960. long body_len;
  106961. } ogg_page;
  106962. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  106963. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  106964. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  106965. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  106966. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  106967. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  106968. }
  106969. /* ogg_stream_state contains the current encode/decode state of a logical
  106970. Ogg bitstream **********************************************************/
  106971. typedef struct {
  106972. unsigned char *body_data; /* bytes from packet bodies */
  106973. long body_storage; /* storage elements allocated */
  106974. long body_fill; /* elements stored; fill mark */
  106975. long body_returned; /* elements of fill returned */
  106976. int *lacing_vals; /* The values that will go to the segment table */
  106977. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  106978. this way, but it is simple coupled to the
  106979. lacing fifo */
  106980. long lacing_storage;
  106981. long lacing_fill;
  106982. long lacing_packet;
  106983. long lacing_returned;
  106984. unsigned char header[282]; /* working space for header encode */
  106985. int header_fill;
  106986. int e_o_s; /* set when we have buffered the last packet in the
  106987. logical bitstream */
  106988. int b_o_s; /* set after we've written the initial page
  106989. of a logical bitstream */
  106990. long serialno;
  106991. long pageno;
  106992. ogg_int64_t packetno; /* sequence number for decode; the framing
  106993. knows where there's a hole in the data,
  106994. but we need coupling so that the codec
  106995. (which is in a seperate abstraction
  106996. layer) also knows about the gap */
  106997. ogg_int64_t granulepos;
  106998. } ogg_stream_state;
  106999. /* ogg_packet is used to encapsulate the data and metadata belonging
  107000. to a single raw Ogg/Vorbis packet *************************************/
  107001. typedef struct {
  107002. unsigned char *packet;
  107003. long bytes;
  107004. long b_o_s;
  107005. long e_o_s;
  107006. ogg_int64_t granulepos;
  107007. ogg_int64_t packetno; /* sequence number for decode; the framing
  107008. knows where there's a hole in the data,
  107009. but we need coupling so that the codec
  107010. (which is in a seperate abstraction
  107011. layer) also knows about the gap */
  107012. } ogg_packet;
  107013. typedef struct {
  107014. unsigned char *data;
  107015. int storage;
  107016. int fill;
  107017. int returned;
  107018. int unsynced;
  107019. int headerbytes;
  107020. int bodybytes;
  107021. } ogg_sync_state;
  107022. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107023. extern void oggpack_writeinit(oggpack_buffer *b);
  107024. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107025. extern void oggpack_writealign(oggpack_buffer *b);
  107026. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107027. extern void oggpack_reset(oggpack_buffer *b);
  107028. extern void oggpack_writeclear(oggpack_buffer *b);
  107029. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107030. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107031. extern long oggpack_look(oggpack_buffer *b,int bits);
  107032. extern long oggpack_look1(oggpack_buffer *b);
  107033. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107034. extern void oggpack_adv1(oggpack_buffer *b);
  107035. extern long oggpack_read(oggpack_buffer *b,int bits);
  107036. extern long oggpack_read1(oggpack_buffer *b);
  107037. extern long oggpack_bytes(oggpack_buffer *b);
  107038. extern long oggpack_bits(oggpack_buffer *b);
  107039. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107040. extern void oggpackB_writeinit(oggpack_buffer *b);
  107041. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107042. extern void oggpackB_writealign(oggpack_buffer *b);
  107043. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107044. extern void oggpackB_reset(oggpack_buffer *b);
  107045. extern void oggpackB_writeclear(oggpack_buffer *b);
  107046. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107047. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107048. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107049. extern long oggpackB_look1(oggpack_buffer *b);
  107050. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107051. extern void oggpackB_adv1(oggpack_buffer *b);
  107052. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107053. extern long oggpackB_read1(oggpack_buffer *b);
  107054. extern long oggpackB_bytes(oggpack_buffer *b);
  107055. extern long oggpackB_bits(oggpack_buffer *b);
  107056. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107057. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107058. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107059. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107060. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107061. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107062. extern int ogg_sync_init(ogg_sync_state *oy);
  107063. extern int ogg_sync_clear(ogg_sync_state *oy);
  107064. extern int ogg_sync_reset(ogg_sync_state *oy);
  107065. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107066. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107067. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107068. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107069. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107070. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107071. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107072. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107073. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107074. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107075. extern int ogg_stream_clear(ogg_stream_state *os);
  107076. extern int ogg_stream_reset(ogg_stream_state *os);
  107077. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107078. extern int ogg_stream_destroy(ogg_stream_state *os);
  107079. extern int ogg_stream_eos(ogg_stream_state *os);
  107080. extern void ogg_page_checksum_set(ogg_page *og);
  107081. extern int ogg_page_version(ogg_page *og);
  107082. extern int ogg_page_continued(ogg_page *og);
  107083. extern int ogg_page_bos(ogg_page *og);
  107084. extern int ogg_page_eos(ogg_page *og);
  107085. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107086. extern int ogg_page_serialno(ogg_page *og);
  107087. extern long ogg_page_pageno(ogg_page *og);
  107088. extern int ogg_page_packets(ogg_page *og);
  107089. extern void ogg_packet_clear(ogg_packet *op);
  107090. #ifdef __cplusplus
  107091. }
  107092. #endif
  107093. #endif /* _OGG_H */
  107094. /*** End of inlined file: ogg.h ***/
  107095. typedef struct vorbis_info{
  107096. int version;
  107097. int channels;
  107098. long rate;
  107099. /* The below bitrate declarations are *hints*.
  107100. Combinations of the three values carry the following implications:
  107101. all three set to the same value:
  107102. implies a fixed rate bitstream
  107103. only nominal set:
  107104. implies a VBR stream that averages the nominal bitrate. No hard
  107105. upper/lower limit
  107106. upper and or lower set:
  107107. implies a VBR bitstream that obeys the bitrate limits. nominal
  107108. may also be set to give a nominal rate.
  107109. none set:
  107110. the coder does not care to speculate.
  107111. */
  107112. long bitrate_upper;
  107113. long bitrate_nominal;
  107114. long bitrate_lower;
  107115. long bitrate_window;
  107116. void *codec_setup;
  107117. } vorbis_info;
  107118. /* vorbis_dsp_state buffers the current vorbis audio
  107119. analysis/synthesis state. The DSP state belongs to a specific
  107120. logical bitstream ****************************************************/
  107121. typedef struct vorbis_dsp_state{
  107122. int analysisp;
  107123. vorbis_info *vi;
  107124. float **pcm;
  107125. float **pcmret;
  107126. int pcm_storage;
  107127. int pcm_current;
  107128. int pcm_returned;
  107129. int preextrapolate;
  107130. int eofflag;
  107131. long lW;
  107132. long W;
  107133. long nW;
  107134. long centerW;
  107135. ogg_int64_t granulepos;
  107136. ogg_int64_t sequence;
  107137. ogg_int64_t glue_bits;
  107138. ogg_int64_t time_bits;
  107139. ogg_int64_t floor_bits;
  107140. ogg_int64_t res_bits;
  107141. void *backend_state;
  107142. } vorbis_dsp_state;
  107143. typedef struct vorbis_block{
  107144. /* necessary stream state for linking to the framing abstraction */
  107145. float **pcm; /* this is a pointer into local storage */
  107146. oggpack_buffer opb;
  107147. long lW;
  107148. long W;
  107149. long nW;
  107150. int pcmend;
  107151. int mode;
  107152. int eofflag;
  107153. ogg_int64_t granulepos;
  107154. ogg_int64_t sequence;
  107155. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107156. /* local storage to avoid remallocing; it's up to the mapping to
  107157. structure it */
  107158. void *localstore;
  107159. long localtop;
  107160. long localalloc;
  107161. long totaluse;
  107162. struct alloc_chain *reap;
  107163. /* bitmetrics for the frame */
  107164. long glue_bits;
  107165. long time_bits;
  107166. long floor_bits;
  107167. long res_bits;
  107168. void *internal;
  107169. } vorbis_block;
  107170. /* vorbis_block is a single block of data to be processed as part of
  107171. the analysis/synthesis stream; it belongs to a specific logical
  107172. bitstream, but is independant from other vorbis_blocks belonging to
  107173. that logical bitstream. *************************************************/
  107174. struct alloc_chain{
  107175. void *ptr;
  107176. struct alloc_chain *next;
  107177. };
  107178. /* vorbis_info contains all the setup information specific to the
  107179. specific compression/decompression mode in progress (eg,
  107180. psychoacoustic settings, channel setup, options, codebook
  107181. etc). vorbis_info and substructures are in backends.h.
  107182. *********************************************************************/
  107183. /* the comments are not part of vorbis_info so that vorbis_info can be
  107184. static storage */
  107185. typedef struct vorbis_comment{
  107186. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107187. whatever vendor is set to in encode */
  107188. char **user_comments;
  107189. int *comment_lengths;
  107190. int comments;
  107191. char *vendor;
  107192. } vorbis_comment;
  107193. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107194. and produce a packet (see docs/analysis.txt). The packet is then
  107195. coded into a framed OggSquish bitstream by the second layer (see
  107196. docs/framing.txt). Decode is the reverse process; we sync/frame
  107197. the bitstream and extract individual packets, then decode the
  107198. packet back into PCM audio.
  107199. The extra framing/packetizing is used in streaming formats, such as
  107200. files. Over the net (such as with UDP), the framing and
  107201. packetization aren't necessary as they're provided by the transport
  107202. and the streaming layer is not used */
  107203. /* Vorbis PRIMITIVES: general ***************************************/
  107204. extern void vorbis_info_init(vorbis_info *vi);
  107205. extern void vorbis_info_clear(vorbis_info *vi);
  107206. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107207. extern void vorbis_comment_init(vorbis_comment *vc);
  107208. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107209. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107210. const char *tag, char *contents);
  107211. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107212. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107213. extern void vorbis_comment_clear(vorbis_comment *vc);
  107214. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107215. extern int vorbis_block_clear(vorbis_block *vb);
  107216. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107217. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107218. ogg_int64_t granulepos);
  107219. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107220. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107221. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107222. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107223. vorbis_comment *vc,
  107224. ogg_packet *op,
  107225. ogg_packet *op_comm,
  107226. ogg_packet *op_code);
  107227. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107228. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107229. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107230. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107231. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107232. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107233. ogg_packet *op);
  107234. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107235. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107236. ogg_packet *op);
  107237. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107238. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107239. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107240. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107241. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107242. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107243. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107244. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107245. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107246. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107247. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107248. /* Vorbis ERRORS and return codes ***********************************/
  107249. #define OV_FALSE -1
  107250. #define OV_EOF -2
  107251. #define OV_HOLE -3
  107252. #define OV_EREAD -128
  107253. #define OV_EFAULT -129
  107254. #define OV_EIMPL -130
  107255. #define OV_EINVAL -131
  107256. #define OV_ENOTVORBIS -132
  107257. #define OV_EBADHEADER -133
  107258. #define OV_EVERSION -134
  107259. #define OV_ENOTAUDIO -135
  107260. #define OV_EBADPACKET -136
  107261. #define OV_EBADLINK -137
  107262. #define OV_ENOSEEK -138
  107263. #ifdef __cplusplus
  107264. }
  107265. #endif /* __cplusplus */
  107266. #endif
  107267. /*** End of inlined file: codec.h ***/
  107268. extern int vorbis_encode_init(vorbis_info *vi,
  107269. long channels,
  107270. long rate,
  107271. long max_bitrate,
  107272. long nominal_bitrate,
  107273. long min_bitrate);
  107274. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107275. long channels,
  107276. long rate,
  107277. long max_bitrate,
  107278. long nominal_bitrate,
  107279. long min_bitrate);
  107280. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107281. long channels,
  107282. long rate,
  107283. float quality /* quality level from 0. (lo) to 1. (hi) */
  107284. );
  107285. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107286. long channels,
  107287. long rate,
  107288. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107289. );
  107290. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107291. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107292. /* deprecated rate management supported only for compatability */
  107293. #define OV_ECTL_RATEMANAGE_GET 0x10
  107294. #define OV_ECTL_RATEMANAGE_SET 0x11
  107295. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107296. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107297. struct ovectl_ratemanage_arg {
  107298. int management_active;
  107299. long bitrate_hard_min;
  107300. long bitrate_hard_max;
  107301. double bitrate_hard_window;
  107302. long bitrate_av_lo;
  107303. long bitrate_av_hi;
  107304. double bitrate_av_window;
  107305. double bitrate_av_window_center;
  107306. };
  107307. /* new rate setup */
  107308. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107309. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107310. struct ovectl_ratemanage2_arg {
  107311. int management_active;
  107312. long bitrate_limit_min_kbps;
  107313. long bitrate_limit_max_kbps;
  107314. long bitrate_limit_reservoir_bits;
  107315. double bitrate_limit_reservoir_bias;
  107316. long bitrate_average_kbps;
  107317. double bitrate_average_damping;
  107318. };
  107319. #define OV_ECTL_LOWPASS_GET 0x20
  107320. #define OV_ECTL_LOWPASS_SET 0x21
  107321. #define OV_ECTL_IBLOCK_GET 0x30
  107322. #define OV_ECTL_IBLOCK_SET 0x31
  107323. #ifdef __cplusplus
  107324. }
  107325. #endif /* __cplusplus */
  107326. #endif
  107327. /*** End of inlined file: vorbisenc.h ***/
  107328. /*** Start of inlined file: vorbisfile.h ***/
  107329. #ifndef _OV_FILE_H_
  107330. #define _OV_FILE_H_
  107331. #ifdef __cplusplus
  107332. extern "C"
  107333. {
  107334. #endif /* __cplusplus */
  107335. #include <stdio.h>
  107336. /* The function prototypes for the callbacks are basically the same as for
  107337. * the stdio functions fread, fseek, fclose, ftell.
  107338. * The one difference is that the FILE * arguments have been replaced with
  107339. * a void * - this is to be used as a pointer to whatever internal data these
  107340. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107341. *
  107342. * If you use other functions, check the docs for these functions and return
  107343. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107344. * unseekable
  107345. */
  107346. typedef struct {
  107347. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107348. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107349. int (*close_func) (void *datasource);
  107350. long (*tell_func) (void *datasource);
  107351. } ov_callbacks;
  107352. #define NOTOPEN 0
  107353. #define PARTOPEN 1
  107354. #define OPENED 2
  107355. #define STREAMSET 3
  107356. #define INITSET 4
  107357. typedef struct OggVorbis_File {
  107358. void *datasource; /* Pointer to a FILE *, etc. */
  107359. int seekable;
  107360. ogg_int64_t offset;
  107361. ogg_int64_t end;
  107362. ogg_sync_state oy;
  107363. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107364. stream appears */
  107365. int links;
  107366. ogg_int64_t *offsets;
  107367. ogg_int64_t *dataoffsets;
  107368. long *serialnos;
  107369. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107370. compatability; x2 size, stores both
  107371. beginning and end values */
  107372. vorbis_info *vi;
  107373. vorbis_comment *vc;
  107374. /* Decoding working state local storage */
  107375. ogg_int64_t pcm_offset;
  107376. int ready_state;
  107377. long current_serialno;
  107378. int current_link;
  107379. double bittrack;
  107380. double samptrack;
  107381. ogg_stream_state os; /* take physical pages, weld into a logical
  107382. stream of packets */
  107383. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107384. vorbis_block vb; /* local working space for packet->PCM decode */
  107385. ov_callbacks callbacks;
  107386. } OggVorbis_File;
  107387. extern int ov_clear(OggVorbis_File *vf);
  107388. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107389. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107390. char *initial, long ibytes, ov_callbacks callbacks);
  107391. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107392. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107393. char *initial, long ibytes, ov_callbacks callbacks);
  107394. extern int ov_test_open(OggVorbis_File *vf);
  107395. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107396. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107397. extern long ov_streams(OggVorbis_File *vf);
  107398. extern long ov_seekable(OggVorbis_File *vf);
  107399. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107400. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107401. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107402. extern double ov_time_total(OggVorbis_File *vf,int i);
  107403. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107404. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107405. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107406. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107407. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107408. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107409. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107410. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107411. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107412. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107413. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107414. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107415. extern double ov_time_tell(OggVorbis_File *vf);
  107416. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107417. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107418. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107419. int *bitstream);
  107420. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107421. int bigendianp,int word,int sgned,int *bitstream);
  107422. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107423. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107424. extern int ov_halfrate_p(OggVorbis_File *vf);
  107425. #ifdef __cplusplus
  107426. }
  107427. #endif /* __cplusplus */
  107428. #endif
  107429. /*** End of inlined file: vorbisfile.h ***/
  107430. /*** Start of inlined file: bitwise.c ***/
  107431. /* We're 'LSb' endian; if we write a word but read individual bits,
  107432. then we'll read the lsb first */
  107433. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107434. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107435. // tasks..
  107436. #if JUCE_MSVC
  107437. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107438. #endif
  107439. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107440. #if JUCE_USE_OGGVORBIS
  107441. #include <string.h>
  107442. #include <stdlib.h>
  107443. #define BUFFER_INCREMENT 256
  107444. static const unsigned long mask[]=
  107445. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107446. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107447. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107448. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107449. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107450. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107451. 0x3fffffff,0x7fffffff,0xffffffff };
  107452. static const unsigned int mask8B[]=
  107453. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107454. void oggpack_writeinit(oggpack_buffer *b){
  107455. memset(b,0,sizeof(*b));
  107456. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107457. b->buffer[0]='\0';
  107458. b->storage=BUFFER_INCREMENT;
  107459. }
  107460. void oggpackB_writeinit(oggpack_buffer *b){
  107461. oggpack_writeinit(b);
  107462. }
  107463. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107464. long bytes=bits>>3;
  107465. bits-=bytes*8;
  107466. b->ptr=b->buffer+bytes;
  107467. b->endbit=bits;
  107468. b->endbyte=bytes;
  107469. *b->ptr&=mask[bits];
  107470. }
  107471. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107472. long bytes=bits>>3;
  107473. bits-=bytes*8;
  107474. b->ptr=b->buffer+bytes;
  107475. b->endbit=bits;
  107476. b->endbyte=bytes;
  107477. *b->ptr&=mask8B[bits];
  107478. }
  107479. /* Takes only up to 32 bits. */
  107480. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107481. if(b->endbyte+4>=b->storage){
  107482. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107483. b->storage+=BUFFER_INCREMENT;
  107484. b->ptr=b->buffer+b->endbyte;
  107485. }
  107486. value&=mask[bits];
  107487. bits+=b->endbit;
  107488. b->ptr[0]|=value<<b->endbit;
  107489. if(bits>=8){
  107490. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107491. if(bits>=16){
  107492. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107493. if(bits>=24){
  107494. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107495. if(bits>=32){
  107496. if(b->endbit)
  107497. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107498. else
  107499. b->ptr[4]=0;
  107500. }
  107501. }
  107502. }
  107503. }
  107504. b->endbyte+=bits/8;
  107505. b->ptr+=bits/8;
  107506. b->endbit=bits&7;
  107507. }
  107508. /* Takes only up to 32 bits. */
  107509. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107510. if(b->endbyte+4>=b->storage){
  107511. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107512. b->storage+=BUFFER_INCREMENT;
  107513. b->ptr=b->buffer+b->endbyte;
  107514. }
  107515. value=(value&mask[bits])<<(32-bits);
  107516. bits+=b->endbit;
  107517. b->ptr[0]|=value>>(24+b->endbit);
  107518. if(bits>=8){
  107519. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107520. if(bits>=16){
  107521. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107522. if(bits>=24){
  107523. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107524. if(bits>=32){
  107525. if(b->endbit)
  107526. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107527. else
  107528. b->ptr[4]=0;
  107529. }
  107530. }
  107531. }
  107532. }
  107533. b->endbyte+=bits/8;
  107534. b->ptr+=bits/8;
  107535. b->endbit=bits&7;
  107536. }
  107537. void oggpack_writealign(oggpack_buffer *b){
  107538. int bits=8-b->endbit;
  107539. if(bits<8)
  107540. oggpack_write(b,0,bits);
  107541. }
  107542. void oggpackB_writealign(oggpack_buffer *b){
  107543. int bits=8-b->endbit;
  107544. if(bits<8)
  107545. oggpackB_write(b,0,bits);
  107546. }
  107547. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107548. void *source,
  107549. long bits,
  107550. void (*w)(oggpack_buffer *,
  107551. unsigned long,
  107552. int),
  107553. int msb){
  107554. unsigned char *ptr=(unsigned char *)source;
  107555. long bytes=bits/8;
  107556. bits-=bytes*8;
  107557. if(b->endbit){
  107558. int i;
  107559. /* unaligned copy. Do it the hard way. */
  107560. for(i=0;i<bytes;i++)
  107561. w(b,(unsigned long)(ptr[i]),8);
  107562. }else{
  107563. /* aligned block copy */
  107564. if(b->endbyte+bytes+1>=b->storage){
  107565. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107566. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107567. b->ptr=b->buffer+b->endbyte;
  107568. }
  107569. memmove(b->ptr,source,bytes);
  107570. b->ptr+=bytes;
  107571. b->endbyte+=bytes;
  107572. *b->ptr=0;
  107573. }
  107574. if(bits){
  107575. if(msb)
  107576. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107577. else
  107578. w(b,(unsigned long)(ptr[bytes]),bits);
  107579. }
  107580. }
  107581. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107582. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107583. }
  107584. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107585. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107586. }
  107587. void oggpack_reset(oggpack_buffer *b){
  107588. b->ptr=b->buffer;
  107589. b->buffer[0]=0;
  107590. b->endbit=b->endbyte=0;
  107591. }
  107592. void oggpackB_reset(oggpack_buffer *b){
  107593. oggpack_reset(b);
  107594. }
  107595. void oggpack_writeclear(oggpack_buffer *b){
  107596. _ogg_free(b->buffer);
  107597. memset(b,0,sizeof(*b));
  107598. }
  107599. void oggpackB_writeclear(oggpack_buffer *b){
  107600. oggpack_writeclear(b);
  107601. }
  107602. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107603. memset(b,0,sizeof(*b));
  107604. b->buffer=b->ptr=buf;
  107605. b->storage=bytes;
  107606. }
  107607. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107608. oggpack_readinit(b,buf,bytes);
  107609. }
  107610. /* Read in bits without advancing the bitptr; bits <= 32 */
  107611. long oggpack_look(oggpack_buffer *b,int bits){
  107612. unsigned long ret;
  107613. unsigned long m=mask[bits];
  107614. bits+=b->endbit;
  107615. if(b->endbyte+4>=b->storage){
  107616. /* not the main path */
  107617. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107618. }
  107619. ret=b->ptr[0]>>b->endbit;
  107620. if(bits>8){
  107621. ret|=b->ptr[1]<<(8-b->endbit);
  107622. if(bits>16){
  107623. ret|=b->ptr[2]<<(16-b->endbit);
  107624. if(bits>24){
  107625. ret|=b->ptr[3]<<(24-b->endbit);
  107626. if(bits>32 && b->endbit)
  107627. ret|=b->ptr[4]<<(32-b->endbit);
  107628. }
  107629. }
  107630. }
  107631. return(m&ret);
  107632. }
  107633. /* Read in bits without advancing the bitptr; bits <= 32 */
  107634. long oggpackB_look(oggpack_buffer *b,int bits){
  107635. unsigned long ret;
  107636. int m=32-bits;
  107637. bits+=b->endbit;
  107638. if(b->endbyte+4>=b->storage){
  107639. /* not the main path */
  107640. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107641. }
  107642. ret=b->ptr[0]<<(24+b->endbit);
  107643. if(bits>8){
  107644. ret|=b->ptr[1]<<(16+b->endbit);
  107645. if(bits>16){
  107646. ret|=b->ptr[2]<<(8+b->endbit);
  107647. if(bits>24){
  107648. ret|=b->ptr[3]<<(b->endbit);
  107649. if(bits>32 && b->endbit)
  107650. ret|=b->ptr[4]>>(8-b->endbit);
  107651. }
  107652. }
  107653. }
  107654. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107655. }
  107656. long oggpack_look1(oggpack_buffer *b){
  107657. if(b->endbyte>=b->storage)return(-1);
  107658. return((b->ptr[0]>>b->endbit)&1);
  107659. }
  107660. long oggpackB_look1(oggpack_buffer *b){
  107661. if(b->endbyte>=b->storage)return(-1);
  107662. return((b->ptr[0]>>(7-b->endbit))&1);
  107663. }
  107664. void oggpack_adv(oggpack_buffer *b,int bits){
  107665. bits+=b->endbit;
  107666. b->ptr+=bits/8;
  107667. b->endbyte+=bits/8;
  107668. b->endbit=bits&7;
  107669. }
  107670. void oggpackB_adv(oggpack_buffer *b,int bits){
  107671. oggpack_adv(b,bits);
  107672. }
  107673. void oggpack_adv1(oggpack_buffer *b){
  107674. if(++(b->endbit)>7){
  107675. b->endbit=0;
  107676. b->ptr++;
  107677. b->endbyte++;
  107678. }
  107679. }
  107680. void oggpackB_adv1(oggpack_buffer *b){
  107681. oggpack_adv1(b);
  107682. }
  107683. /* bits <= 32 */
  107684. long oggpack_read(oggpack_buffer *b,int bits){
  107685. long ret;
  107686. unsigned long m=mask[bits];
  107687. bits+=b->endbit;
  107688. if(b->endbyte+4>=b->storage){
  107689. /* not the main path */
  107690. ret=-1L;
  107691. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107692. }
  107693. ret=b->ptr[0]>>b->endbit;
  107694. if(bits>8){
  107695. ret|=b->ptr[1]<<(8-b->endbit);
  107696. if(bits>16){
  107697. ret|=b->ptr[2]<<(16-b->endbit);
  107698. if(bits>24){
  107699. ret|=b->ptr[3]<<(24-b->endbit);
  107700. if(bits>32 && b->endbit){
  107701. ret|=b->ptr[4]<<(32-b->endbit);
  107702. }
  107703. }
  107704. }
  107705. }
  107706. ret&=m;
  107707. overflow:
  107708. b->ptr+=bits/8;
  107709. b->endbyte+=bits/8;
  107710. b->endbit=bits&7;
  107711. return(ret);
  107712. }
  107713. /* bits <= 32 */
  107714. long oggpackB_read(oggpack_buffer *b,int bits){
  107715. long ret;
  107716. long m=32-bits;
  107717. bits+=b->endbit;
  107718. if(b->endbyte+4>=b->storage){
  107719. /* not the main path */
  107720. ret=-1L;
  107721. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  107722. }
  107723. ret=b->ptr[0]<<(24+b->endbit);
  107724. if(bits>8){
  107725. ret|=b->ptr[1]<<(16+b->endbit);
  107726. if(bits>16){
  107727. ret|=b->ptr[2]<<(8+b->endbit);
  107728. if(bits>24){
  107729. ret|=b->ptr[3]<<(b->endbit);
  107730. if(bits>32 && b->endbit)
  107731. ret|=b->ptr[4]>>(8-b->endbit);
  107732. }
  107733. }
  107734. }
  107735. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  107736. overflow:
  107737. b->ptr+=bits/8;
  107738. b->endbyte+=bits/8;
  107739. b->endbit=bits&7;
  107740. return(ret);
  107741. }
  107742. long oggpack_read1(oggpack_buffer *b){
  107743. long ret;
  107744. if(b->endbyte>=b->storage){
  107745. /* not the main path */
  107746. ret=-1L;
  107747. goto overflow;
  107748. }
  107749. ret=(b->ptr[0]>>b->endbit)&1;
  107750. overflow:
  107751. b->endbit++;
  107752. if(b->endbit>7){
  107753. b->endbit=0;
  107754. b->ptr++;
  107755. b->endbyte++;
  107756. }
  107757. return(ret);
  107758. }
  107759. long oggpackB_read1(oggpack_buffer *b){
  107760. long ret;
  107761. if(b->endbyte>=b->storage){
  107762. /* not the main path */
  107763. ret=-1L;
  107764. goto overflow;
  107765. }
  107766. ret=(b->ptr[0]>>(7-b->endbit))&1;
  107767. overflow:
  107768. b->endbit++;
  107769. if(b->endbit>7){
  107770. b->endbit=0;
  107771. b->ptr++;
  107772. b->endbyte++;
  107773. }
  107774. return(ret);
  107775. }
  107776. long oggpack_bytes(oggpack_buffer *b){
  107777. return(b->endbyte+(b->endbit+7)/8);
  107778. }
  107779. long oggpack_bits(oggpack_buffer *b){
  107780. return(b->endbyte*8+b->endbit);
  107781. }
  107782. long oggpackB_bytes(oggpack_buffer *b){
  107783. return oggpack_bytes(b);
  107784. }
  107785. long oggpackB_bits(oggpack_buffer *b){
  107786. return oggpack_bits(b);
  107787. }
  107788. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  107789. return(b->buffer);
  107790. }
  107791. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  107792. return oggpack_get_buffer(b);
  107793. }
  107794. /* Self test of the bitwise routines; everything else is based on
  107795. them, so they damned well better be solid. */
  107796. #ifdef _V_SELFTEST
  107797. #include <stdio.h>
  107798. static int ilog(unsigned int v){
  107799. int ret=0;
  107800. while(v){
  107801. ret++;
  107802. v>>=1;
  107803. }
  107804. return(ret);
  107805. }
  107806. oggpack_buffer o;
  107807. oggpack_buffer r;
  107808. void report(char *in){
  107809. fprintf(stderr,"%s",in);
  107810. exit(1);
  107811. }
  107812. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107813. long bytes,i;
  107814. unsigned char *buffer;
  107815. oggpack_reset(&o);
  107816. for(i=0;i<vals;i++)
  107817. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  107818. buffer=oggpack_get_buffer(&o);
  107819. bytes=oggpack_bytes(&o);
  107820. if(bytes!=compsize)report("wrong number of bytes!\n");
  107821. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107822. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107823. report("wrote incorrect value!\n");
  107824. }
  107825. oggpack_readinit(&r,buffer,bytes);
  107826. for(i=0;i<vals;i++){
  107827. int tbit=bits?bits:ilog(b[i]);
  107828. if(oggpack_look(&r,tbit)==-1)
  107829. report("out of data!\n");
  107830. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  107831. report("looked at incorrect value!\n");
  107832. if(tbit==1)
  107833. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  107834. report("looked at single bit incorrect value!\n");
  107835. if(tbit==1){
  107836. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  107837. report("read incorrect single bit value!\n");
  107838. }else{
  107839. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  107840. report("read incorrect value!\n");
  107841. }
  107842. }
  107843. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107844. }
  107845. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  107846. long bytes,i;
  107847. unsigned char *buffer;
  107848. oggpackB_reset(&o);
  107849. for(i=0;i<vals;i++)
  107850. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  107851. buffer=oggpackB_get_buffer(&o);
  107852. bytes=oggpackB_bytes(&o);
  107853. if(bytes!=compsize)report("wrong number of bytes!\n");
  107854. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  107855. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  107856. report("wrote incorrect value!\n");
  107857. }
  107858. oggpackB_readinit(&r,buffer,bytes);
  107859. for(i=0;i<vals;i++){
  107860. int tbit=bits?bits:ilog(b[i]);
  107861. if(oggpackB_look(&r,tbit)==-1)
  107862. report("out of data!\n");
  107863. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  107864. report("looked at incorrect value!\n");
  107865. if(tbit==1)
  107866. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  107867. report("looked at single bit incorrect value!\n");
  107868. if(tbit==1){
  107869. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  107870. report("read incorrect single bit value!\n");
  107871. }else{
  107872. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  107873. report("read incorrect value!\n");
  107874. }
  107875. }
  107876. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107877. }
  107878. int main(void){
  107879. unsigned char *buffer;
  107880. long bytes,i;
  107881. static unsigned long testbuffer1[]=
  107882. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  107883. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  107884. int test1size=43;
  107885. static unsigned long testbuffer2[]=
  107886. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  107887. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  107888. 85525151,0,12321,1,349528352};
  107889. int test2size=21;
  107890. static unsigned long testbuffer3[]=
  107891. {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,
  107892. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  107893. int test3size=56;
  107894. static unsigned long large[]=
  107895. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  107896. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  107897. 85525151,0,12321,1,2146528352};
  107898. int onesize=33;
  107899. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  107900. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  107901. 223,4};
  107902. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  107903. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  107904. 245,251,128};
  107905. int twosize=6;
  107906. static int two[6]={61,255,255,251,231,29};
  107907. static int twoB[6]={247,63,255,253,249,120};
  107908. int threesize=54;
  107909. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  107910. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  107911. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  107912. 100,52,4,14,18,86,77,1};
  107913. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  107914. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  107915. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  107916. 200,20,254,4,58,106,176,144,0};
  107917. int foursize=38;
  107918. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  107919. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  107920. 28,2,133,0,1};
  107921. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  107922. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  107923. 129,10,4,32};
  107924. int fivesize=45;
  107925. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  107926. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  107927. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  107928. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  107929. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  107930. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  107931. int sixsize=7;
  107932. static int six[7]={17,177,170,242,169,19,148};
  107933. static int sixB[7]={136,141,85,79,149,200,41};
  107934. /* Test read/write together */
  107935. /* Later we test against pregenerated bitstreams */
  107936. oggpack_writeinit(&o);
  107937. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  107938. cliptest(testbuffer1,test1size,0,one,onesize);
  107939. fprintf(stderr,"ok.");
  107940. fprintf(stderr,"\nNull bit call (LSb): ");
  107941. cliptest(testbuffer3,test3size,0,two,twosize);
  107942. fprintf(stderr,"ok.");
  107943. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  107944. cliptest(testbuffer2,test2size,0,three,threesize);
  107945. fprintf(stderr,"ok.");
  107946. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  107947. oggpack_reset(&o);
  107948. for(i=0;i<test2size;i++)
  107949. oggpack_write(&o,large[i],32);
  107950. buffer=oggpack_get_buffer(&o);
  107951. bytes=oggpack_bytes(&o);
  107952. oggpack_readinit(&r,buffer,bytes);
  107953. for(i=0;i<test2size;i++){
  107954. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  107955. if(oggpack_look(&r,32)!=large[i]){
  107956. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  107957. oggpack_look(&r,32),large[i]);
  107958. report("read incorrect value!\n");
  107959. }
  107960. oggpack_adv(&r,32);
  107961. }
  107962. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  107963. fprintf(stderr,"ok.");
  107964. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  107965. cliptest(testbuffer1,test1size,7,four,foursize);
  107966. fprintf(stderr,"ok.");
  107967. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  107968. cliptest(testbuffer2,test2size,17,five,fivesize);
  107969. fprintf(stderr,"ok.");
  107970. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  107971. cliptest(testbuffer3,test3size,1,six,sixsize);
  107972. fprintf(stderr,"ok.");
  107973. fprintf(stderr,"\nTesting read past end (LSb): ");
  107974. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107975. for(i=0;i<64;i++){
  107976. if(oggpack_read(&r,1)!=0){
  107977. fprintf(stderr,"failed; got -1 prematurely.\n");
  107978. exit(1);
  107979. }
  107980. }
  107981. if(oggpack_look(&r,1)!=-1 ||
  107982. oggpack_read(&r,1)!=-1){
  107983. fprintf(stderr,"failed; read past end without -1.\n");
  107984. exit(1);
  107985. }
  107986. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  107987. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  107988. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  107989. exit(1);
  107990. }
  107991. if(oggpack_look(&r,18)!=0 ||
  107992. oggpack_look(&r,18)!=0){
  107993. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  107994. exit(1);
  107995. }
  107996. if(oggpack_look(&r,19)!=-1 ||
  107997. oggpack_look(&r,19)!=-1){
  107998. fprintf(stderr,"failed; read past end without -1.\n");
  107999. exit(1);
  108000. }
  108001. if(oggpack_look(&r,32)!=-1 ||
  108002. oggpack_look(&r,32)!=-1){
  108003. fprintf(stderr,"failed; read past end without -1.\n");
  108004. exit(1);
  108005. }
  108006. oggpack_writeclear(&o);
  108007. fprintf(stderr,"ok.\n");
  108008. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108009. /* Test read/write together */
  108010. /* Later we test against pregenerated bitstreams */
  108011. oggpackB_writeinit(&o);
  108012. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108013. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108014. fprintf(stderr,"ok.");
  108015. fprintf(stderr,"\nNull bit call (MSb): ");
  108016. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108017. fprintf(stderr,"ok.");
  108018. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108019. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108020. fprintf(stderr,"ok.");
  108021. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108022. oggpackB_reset(&o);
  108023. for(i=0;i<test2size;i++)
  108024. oggpackB_write(&o,large[i],32);
  108025. buffer=oggpackB_get_buffer(&o);
  108026. bytes=oggpackB_bytes(&o);
  108027. oggpackB_readinit(&r,buffer,bytes);
  108028. for(i=0;i<test2size;i++){
  108029. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108030. if(oggpackB_look(&r,32)!=large[i]){
  108031. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108032. oggpackB_look(&r,32),large[i]);
  108033. report("read incorrect value!\n");
  108034. }
  108035. oggpackB_adv(&r,32);
  108036. }
  108037. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108038. fprintf(stderr,"ok.");
  108039. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108040. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108041. fprintf(stderr,"ok.");
  108042. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108043. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108044. fprintf(stderr,"ok.");
  108045. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108046. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108047. fprintf(stderr,"ok.");
  108048. fprintf(stderr,"\nTesting read past end (MSb): ");
  108049. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108050. for(i=0;i<64;i++){
  108051. if(oggpackB_read(&r,1)!=0){
  108052. fprintf(stderr,"failed; got -1 prematurely.\n");
  108053. exit(1);
  108054. }
  108055. }
  108056. if(oggpackB_look(&r,1)!=-1 ||
  108057. oggpackB_read(&r,1)!=-1){
  108058. fprintf(stderr,"failed; read past end without -1.\n");
  108059. exit(1);
  108060. }
  108061. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108062. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108063. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108064. exit(1);
  108065. }
  108066. if(oggpackB_look(&r,18)!=0 ||
  108067. oggpackB_look(&r,18)!=0){
  108068. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108069. exit(1);
  108070. }
  108071. if(oggpackB_look(&r,19)!=-1 ||
  108072. oggpackB_look(&r,19)!=-1){
  108073. fprintf(stderr,"failed; read past end without -1.\n");
  108074. exit(1);
  108075. }
  108076. if(oggpackB_look(&r,32)!=-1 ||
  108077. oggpackB_look(&r,32)!=-1){
  108078. fprintf(stderr,"failed; read past end without -1.\n");
  108079. exit(1);
  108080. }
  108081. oggpackB_writeclear(&o);
  108082. fprintf(stderr,"ok.\n\n");
  108083. return(0);
  108084. }
  108085. #endif /* _V_SELFTEST */
  108086. #undef BUFFER_INCREMENT
  108087. #endif
  108088. /*** End of inlined file: bitwise.c ***/
  108089. /*** Start of inlined file: framing.c ***/
  108090. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108091. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108092. // tasks..
  108093. #if JUCE_MSVC
  108094. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108095. #endif
  108096. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108097. #if JUCE_USE_OGGVORBIS
  108098. #include <stdlib.h>
  108099. #include <string.h>
  108100. /* A complete description of Ogg framing exists in docs/framing.html */
  108101. int ogg_page_version(ogg_page *og){
  108102. return((int)(og->header[4]));
  108103. }
  108104. int ogg_page_continued(ogg_page *og){
  108105. return((int)(og->header[5]&0x01));
  108106. }
  108107. int ogg_page_bos(ogg_page *og){
  108108. return((int)(og->header[5]&0x02));
  108109. }
  108110. int ogg_page_eos(ogg_page *og){
  108111. return((int)(og->header[5]&0x04));
  108112. }
  108113. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108114. unsigned char *page=og->header;
  108115. ogg_int64_t granulepos=page[13]&(0xff);
  108116. granulepos= (granulepos<<8)|(page[12]&0xff);
  108117. granulepos= (granulepos<<8)|(page[11]&0xff);
  108118. granulepos= (granulepos<<8)|(page[10]&0xff);
  108119. granulepos= (granulepos<<8)|(page[9]&0xff);
  108120. granulepos= (granulepos<<8)|(page[8]&0xff);
  108121. granulepos= (granulepos<<8)|(page[7]&0xff);
  108122. granulepos= (granulepos<<8)|(page[6]&0xff);
  108123. return(granulepos);
  108124. }
  108125. int ogg_page_serialno(ogg_page *og){
  108126. return(og->header[14] |
  108127. (og->header[15]<<8) |
  108128. (og->header[16]<<16) |
  108129. (og->header[17]<<24));
  108130. }
  108131. long ogg_page_pageno(ogg_page *og){
  108132. return(og->header[18] |
  108133. (og->header[19]<<8) |
  108134. (og->header[20]<<16) |
  108135. (og->header[21]<<24));
  108136. }
  108137. /* returns the number of packets that are completed on this page (if
  108138. the leading packet is begun on a previous page, but ends on this
  108139. page, it's counted */
  108140. /* NOTE:
  108141. If a page consists of a packet begun on a previous page, and a new
  108142. packet begun (but not completed) on this page, the return will be:
  108143. ogg_page_packets(page) ==1,
  108144. ogg_page_continued(page) !=0
  108145. If a page happens to be a single packet that was begun on a
  108146. previous page, and spans to the next page (in the case of a three or
  108147. more page packet), the return will be:
  108148. ogg_page_packets(page) ==0,
  108149. ogg_page_continued(page) !=0
  108150. */
  108151. int ogg_page_packets(ogg_page *og){
  108152. int i,n=og->header[26],count=0;
  108153. for(i=0;i<n;i++)
  108154. if(og->header[27+i]<255)count++;
  108155. return(count);
  108156. }
  108157. #if 0
  108158. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108159. use the static init below) */
  108160. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108161. int i;
  108162. unsigned long r;
  108163. r = index << 24;
  108164. for (i=0; i<8; i++)
  108165. if (r & 0x80000000UL)
  108166. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108167. polynomial, although we use an
  108168. unreflected alg and an init/final
  108169. of 0, not 0xffffffff */
  108170. else
  108171. r<<=1;
  108172. return (r & 0xffffffffUL);
  108173. }
  108174. #endif
  108175. static const ogg_uint32_t crc_lookup[256]={
  108176. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108177. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108178. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108179. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108180. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108181. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108182. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108183. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108184. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108185. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108186. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108187. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108188. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108189. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108190. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108191. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108192. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108193. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108194. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108195. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108196. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108197. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108198. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108199. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108200. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108201. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108202. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108203. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108204. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108205. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108206. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108207. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108208. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108209. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108210. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108211. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108212. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108213. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108214. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108215. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108216. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108217. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108218. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108219. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108220. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108221. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108222. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108223. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108224. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108225. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108226. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108227. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108228. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108229. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108230. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108231. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108232. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108233. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108234. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108235. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108236. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108237. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108238. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108239. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108240. /* init the encode/decode logical stream state */
  108241. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108242. if(os){
  108243. memset(os,0,sizeof(*os));
  108244. os->body_storage=16*1024;
  108245. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108246. os->lacing_storage=1024;
  108247. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108248. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108249. os->serialno=serialno;
  108250. return(0);
  108251. }
  108252. return(-1);
  108253. }
  108254. /* _clear does not free os, only the non-flat storage within */
  108255. int ogg_stream_clear(ogg_stream_state *os){
  108256. if(os){
  108257. if(os->body_data)_ogg_free(os->body_data);
  108258. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108259. if(os->granule_vals)_ogg_free(os->granule_vals);
  108260. memset(os,0,sizeof(*os));
  108261. }
  108262. return(0);
  108263. }
  108264. int ogg_stream_destroy(ogg_stream_state *os){
  108265. if(os){
  108266. ogg_stream_clear(os);
  108267. _ogg_free(os);
  108268. }
  108269. return(0);
  108270. }
  108271. /* Helpers for ogg_stream_encode; this keeps the structure and
  108272. what's happening fairly clear */
  108273. static void _os_body_expand(ogg_stream_state *os,int needed){
  108274. if(os->body_storage<=os->body_fill+needed){
  108275. os->body_storage+=(needed+1024);
  108276. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108277. }
  108278. }
  108279. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108280. if(os->lacing_storage<=os->lacing_fill+needed){
  108281. os->lacing_storage+=(needed+32);
  108282. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108283. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108284. }
  108285. }
  108286. /* checksum the page */
  108287. /* Direct table CRC; note that this will be faster in the future if we
  108288. perform the checksum silmultaneously with other copies */
  108289. void ogg_page_checksum_set(ogg_page *og){
  108290. if(og){
  108291. ogg_uint32_t crc_reg=0;
  108292. int i;
  108293. /* safety; needed for API behavior, but not framing code */
  108294. og->header[22]=0;
  108295. og->header[23]=0;
  108296. og->header[24]=0;
  108297. og->header[25]=0;
  108298. for(i=0;i<og->header_len;i++)
  108299. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108300. for(i=0;i<og->body_len;i++)
  108301. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108302. og->header[22]=(unsigned char)(crc_reg&0xff);
  108303. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108304. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108305. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108306. }
  108307. }
  108308. /* submit data to the internal buffer of the framing engine */
  108309. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108310. int lacing_vals=op->bytes/255+1,i;
  108311. if(os->body_returned){
  108312. /* advance packet data according to the body_returned pointer. We
  108313. had to keep it around to return a pointer into the buffer last
  108314. call */
  108315. os->body_fill-=os->body_returned;
  108316. if(os->body_fill)
  108317. memmove(os->body_data,os->body_data+os->body_returned,
  108318. os->body_fill);
  108319. os->body_returned=0;
  108320. }
  108321. /* make sure we have the buffer storage */
  108322. _os_body_expand(os,op->bytes);
  108323. _os_lacing_expand(os,lacing_vals);
  108324. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108325. the liability of overly clean abstraction for the time being. It
  108326. will actually be fairly easy to eliminate the extra copy in the
  108327. future */
  108328. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108329. os->body_fill+=op->bytes;
  108330. /* Store lacing vals for this packet */
  108331. for(i=0;i<lacing_vals-1;i++){
  108332. os->lacing_vals[os->lacing_fill+i]=255;
  108333. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108334. }
  108335. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108336. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108337. /* flag the first segment as the beginning of the packet */
  108338. os->lacing_vals[os->lacing_fill]|= 0x100;
  108339. os->lacing_fill+=lacing_vals;
  108340. /* for the sake of completeness */
  108341. os->packetno++;
  108342. if(op->e_o_s)os->e_o_s=1;
  108343. return(0);
  108344. }
  108345. /* This will flush remaining packets into a page (returning nonzero),
  108346. even if there is not enough data to trigger a flush normally
  108347. (undersized page). If there are no packets or partial packets to
  108348. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108349. try to flush a normal sized page like ogg_stream_pageout; a call to
  108350. ogg_stream_flush does not guarantee that all packets have flushed.
  108351. Only a return value of 0 from ogg_stream_flush indicates all packet
  108352. data is flushed into pages.
  108353. since ogg_stream_flush will flush the last page in a stream even if
  108354. it's undersized, you almost certainly want to use ogg_stream_pageout
  108355. (and *not* ogg_stream_flush) unless you specifically need to flush
  108356. an page regardless of size in the middle of a stream. */
  108357. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108358. int i;
  108359. int vals=0;
  108360. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108361. int bytes=0;
  108362. long acc=0;
  108363. ogg_int64_t granule_pos=-1;
  108364. if(maxvals==0)return(0);
  108365. /* construct a page */
  108366. /* decide how many segments to include */
  108367. /* If this is the initial header case, the first page must only include
  108368. the initial header packet */
  108369. if(os->b_o_s==0){ /* 'initial header page' case */
  108370. granule_pos=0;
  108371. for(vals=0;vals<maxvals;vals++){
  108372. if((os->lacing_vals[vals]&0x0ff)<255){
  108373. vals++;
  108374. break;
  108375. }
  108376. }
  108377. }else{
  108378. for(vals=0;vals<maxvals;vals++){
  108379. if(acc>4096)break;
  108380. acc+=os->lacing_vals[vals]&0x0ff;
  108381. if((os->lacing_vals[vals]&0xff)<255)
  108382. granule_pos=os->granule_vals[vals];
  108383. }
  108384. }
  108385. /* construct the header in temp storage */
  108386. memcpy(os->header,"OggS",4);
  108387. /* stream structure version */
  108388. os->header[4]=0x00;
  108389. /* continued packet flag? */
  108390. os->header[5]=0x00;
  108391. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108392. /* first page flag? */
  108393. if(os->b_o_s==0)os->header[5]|=0x02;
  108394. /* last page flag? */
  108395. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108396. os->b_o_s=1;
  108397. /* 64 bits of PCM position */
  108398. for(i=6;i<14;i++){
  108399. os->header[i]=(unsigned char)(granule_pos&0xff);
  108400. granule_pos>>=8;
  108401. }
  108402. /* 32 bits of stream serial number */
  108403. {
  108404. long serialno=os->serialno;
  108405. for(i=14;i<18;i++){
  108406. os->header[i]=(unsigned char)(serialno&0xff);
  108407. serialno>>=8;
  108408. }
  108409. }
  108410. /* 32 bits of page counter (we have both counter and page header
  108411. because this val can roll over) */
  108412. if(os->pageno==-1)os->pageno=0; /* because someone called
  108413. stream_reset; this would be a
  108414. strange thing to do in an
  108415. encode stream, but it has
  108416. plausible uses */
  108417. {
  108418. long pageno=os->pageno++;
  108419. for(i=18;i<22;i++){
  108420. os->header[i]=(unsigned char)(pageno&0xff);
  108421. pageno>>=8;
  108422. }
  108423. }
  108424. /* zero for computation; filled in later */
  108425. os->header[22]=0;
  108426. os->header[23]=0;
  108427. os->header[24]=0;
  108428. os->header[25]=0;
  108429. /* segment table */
  108430. os->header[26]=(unsigned char)(vals&0xff);
  108431. for(i=0;i<vals;i++)
  108432. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108433. /* set pointers in the ogg_page struct */
  108434. og->header=os->header;
  108435. og->header_len=os->header_fill=vals+27;
  108436. og->body=os->body_data+os->body_returned;
  108437. og->body_len=bytes;
  108438. /* advance the lacing data and set the body_returned pointer */
  108439. os->lacing_fill-=vals;
  108440. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108441. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108442. os->body_returned+=bytes;
  108443. /* calculate the checksum */
  108444. ogg_page_checksum_set(og);
  108445. /* done */
  108446. return(1);
  108447. }
  108448. /* This constructs pages from buffered packet segments. The pointers
  108449. returned are to static buffers; do not free. The returned buffers are
  108450. good only until the next call (using the same ogg_stream_state) */
  108451. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108452. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108453. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108454. os->lacing_fill>=255 || /* 'segment table full' case */
  108455. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108456. return(ogg_stream_flush(os,og));
  108457. }
  108458. /* not enough data to construct a page and not end of stream */
  108459. return(0);
  108460. }
  108461. int ogg_stream_eos(ogg_stream_state *os){
  108462. return os->e_o_s;
  108463. }
  108464. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108465. /* This has two layers to place more of the multi-serialno and paging
  108466. control in the application's hands. First, we expose a data buffer
  108467. using ogg_sync_buffer(). The app either copies into the
  108468. buffer, or passes it directly to read(), etc. We then call
  108469. ogg_sync_wrote() to tell how many bytes we just added.
  108470. Pages are returned (pointers into the buffer in ogg_sync_state)
  108471. by ogg_sync_pageout(). The page is then submitted to
  108472. ogg_stream_pagein() along with the appropriate
  108473. ogg_stream_state* (ie, matching serialno). We then get raw
  108474. packets out calling ogg_stream_packetout() with a
  108475. ogg_stream_state. */
  108476. /* initialize the struct to a known state */
  108477. int ogg_sync_init(ogg_sync_state *oy){
  108478. if(oy){
  108479. memset(oy,0,sizeof(*oy));
  108480. }
  108481. return(0);
  108482. }
  108483. /* clear non-flat storage within */
  108484. int ogg_sync_clear(ogg_sync_state *oy){
  108485. if(oy){
  108486. if(oy->data)_ogg_free(oy->data);
  108487. ogg_sync_init(oy);
  108488. }
  108489. return(0);
  108490. }
  108491. int ogg_sync_destroy(ogg_sync_state *oy){
  108492. if(oy){
  108493. ogg_sync_clear(oy);
  108494. _ogg_free(oy);
  108495. }
  108496. return(0);
  108497. }
  108498. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108499. /* first, clear out any space that has been previously returned */
  108500. if(oy->returned){
  108501. oy->fill-=oy->returned;
  108502. if(oy->fill>0)
  108503. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108504. oy->returned=0;
  108505. }
  108506. if(size>oy->storage-oy->fill){
  108507. /* We need to extend the internal buffer */
  108508. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108509. if(oy->data)
  108510. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108511. else
  108512. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108513. oy->storage=newsize;
  108514. }
  108515. /* expose a segment at least as large as requested at the fill mark */
  108516. return((char *)oy->data+oy->fill);
  108517. }
  108518. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108519. if(oy->fill+bytes>oy->storage)return(-1);
  108520. oy->fill+=bytes;
  108521. return(0);
  108522. }
  108523. /* sync the stream. This is meant to be useful for finding page
  108524. boundaries.
  108525. return values for this:
  108526. -n) skipped n bytes
  108527. 0) page not ready; more data (no bytes skipped)
  108528. n) page synced at current location; page length n bytes
  108529. */
  108530. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108531. unsigned char *page=oy->data+oy->returned;
  108532. unsigned char *next;
  108533. long bytes=oy->fill-oy->returned;
  108534. if(oy->headerbytes==0){
  108535. int headerbytes,i;
  108536. if(bytes<27)return(0); /* not enough for a header */
  108537. /* verify capture pattern */
  108538. if(memcmp(page,"OggS",4))goto sync_fail;
  108539. headerbytes=page[26]+27;
  108540. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108541. /* count up body length in the segment table */
  108542. for(i=0;i<page[26];i++)
  108543. oy->bodybytes+=page[27+i];
  108544. oy->headerbytes=headerbytes;
  108545. }
  108546. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108547. /* The whole test page is buffered. Verify the checksum */
  108548. {
  108549. /* Grab the checksum bytes, set the header field to zero */
  108550. char chksum[4];
  108551. ogg_page log;
  108552. memcpy(chksum,page+22,4);
  108553. memset(page+22,0,4);
  108554. /* set up a temp page struct and recompute the checksum */
  108555. log.header=page;
  108556. log.header_len=oy->headerbytes;
  108557. log.body=page+oy->headerbytes;
  108558. log.body_len=oy->bodybytes;
  108559. ogg_page_checksum_set(&log);
  108560. /* Compare */
  108561. if(memcmp(chksum,page+22,4)){
  108562. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108563. at all) */
  108564. /* replace the computed checksum with the one actually read in */
  108565. memcpy(page+22,chksum,4);
  108566. /* Bad checksum. Lose sync */
  108567. goto sync_fail;
  108568. }
  108569. }
  108570. /* yes, have a whole page all ready to go */
  108571. {
  108572. unsigned char *page=oy->data+oy->returned;
  108573. long bytes;
  108574. if(og){
  108575. og->header=page;
  108576. og->header_len=oy->headerbytes;
  108577. og->body=page+oy->headerbytes;
  108578. og->body_len=oy->bodybytes;
  108579. }
  108580. oy->unsynced=0;
  108581. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108582. oy->headerbytes=0;
  108583. oy->bodybytes=0;
  108584. return(bytes);
  108585. }
  108586. sync_fail:
  108587. oy->headerbytes=0;
  108588. oy->bodybytes=0;
  108589. /* search for possible capture */
  108590. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108591. if(!next)
  108592. next=oy->data+oy->fill;
  108593. oy->returned=next-oy->data;
  108594. return(-(next-page));
  108595. }
  108596. /* sync the stream and get a page. Keep trying until we find a page.
  108597. Supress 'sync errors' after reporting the first.
  108598. return values:
  108599. -1) recapture (hole in data)
  108600. 0) need more data
  108601. 1) page returned
  108602. Returns pointers into buffered data; invalidated by next call to
  108603. _stream, _clear, _init, or _buffer */
  108604. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108605. /* all we need to do is verify a page at the head of the stream
  108606. buffer. If it doesn't verify, we look for the next potential
  108607. frame */
  108608. for(;;){
  108609. long ret=ogg_sync_pageseek(oy,og);
  108610. if(ret>0){
  108611. /* have a page */
  108612. return(1);
  108613. }
  108614. if(ret==0){
  108615. /* need more data */
  108616. return(0);
  108617. }
  108618. /* head did not start a synced page... skipped some bytes */
  108619. if(!oy->unsynced){
  108620. oy->unsynced=1;
  108621. return(-1);
  108622. }
  108623. /* loop. keep looking */
  108624. }
  108625. }
  108626. /* add the incoming page to the stream state; we decompose the page
  108627. into packet segments here as well. */
  108628. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108629. unsigned char *header=og->header;
  108630. unsigned char *body=og->body;
  108631. long bodysize=og->body_len;
  108632. int segptr=0;
  108633. int version=ogg_page_version(og);
  108634. int continued=ogg_page_continued(og);
  108635. int bos=ogg_page_bos(og);
  108636. int eos=ogg_page_eos(og);
  108637. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108638. int serialno=ogg_page_serialno(og);
  108639. long pageno=ogg_page_pageno(og);
  108640. int segments=header[26];
  108641. /* clean up 'returned data' */
  108642. {
  108643. long lr=os->lacing_returned;
  108644. long br=os->body_returned;
  108645. /* body data */
  108646. if(br){
  108647. os->body_fill-=br;
  108648. if(os->body_fill)
  108649. memmove(os->body_data,os->body_data+br,os->body_fill);
  108650. os->body_returned=0;
  108651. }
  108652. if(lr){
  108653. /* segment table */
  108654. if(os->lacing_fill-lr){
  108655. memmove(os->lacing_vals,os->lacing_vals+lr,
  108656. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108657. memmove(os->granule_vals,os->granule_vals+lr,
  108658. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108659. }
  108660. os->lacing_fill-=lr;
  108661. os->lacing_packet-=lr;
  108662. os->lacing_returned=0;
  108663. }
  108664. }
  108665. /* check the serial number */
  108666. if(serialno!=os->serialno)return(-1);
  108667. if(version>0)return(-1);
  108668. _os_lacing_expand(os,segments+1);
  108669. /* are we in sequence? */
  108670. if(pageno!=os->pageno){
  108671. int i;
  108672. /* unroll previous partial packet (if any) */
  108673. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  108674. os->body_fill-=os->lacing_vals[i]&0xff;
  108675. os->lacing_fill=os->lacing_packet;
  108676. /* make a note of dropped data in segment table */
  108677. if(os->pageno!=-1){
  108678. os->lacing_vals[os->lacing_fill++]=0x400;
  108679. os->lacing_packet++;
  108680. }
  108681. }
  108682. /* are we a 'continued packet' page? If so, we may need to skip
  108683. some segments */
  108684. if(continued){
  108685. if(os->lacing_fill<1 ||
  108686. os->lacing_vals[os->lacing_fill-1]==0x400){
  108687. bos=0;
  108688. for(;segptr<segments;segptr++){
  108689. int val=header[27+segptr];
  108690. body+=val;
  108691. bodysize-=val;
  108692. if(val<255){
  108693. segptr++;
  108694. break;
  108695. }
  108696. }
  108697. }
  108698. }
  108699. if(bodysize){
  108700. _os_body_expand(os,bodysize);
  108701. memcpy(os->body_data+os->body_fill,body,bodysize);
  108702. os->body_fill+=bodysize;
  108703. }
  108704. {
  108705. int saved=-1;
  108706. while(segptr<segments){
  108707. int val=header[27+segptr];
  108708. os->lacing_vals[os->lacing_fill]=val;
  108709. os->granule_vals[os->lacing_fill]=-1;
  108710. if(bos){
  108711. os->lacing_vals[os->lacing_fill]|=0x100;
  108712. bos=0;
  108713. }
  108714. if(val<255)saved=os->lacing_fill;
  108715. os->lacing_fill++;
  108716. segptr++;
  108717. if(val<255)os->lacing_packet=os->lacing_fill;
  108718. }
  108719. /* set the granulepos on the last granuleval of the last full packet */
  108720. if(saved!=-1){
  108721. os->granule_vals[saved]=granulepos;
  108722. }
  108723. }
  108724. if(eos){
  108725. os->e_o_s=1;
  108726. if(os->lacing_fill>0)
  108727. os->lacing_vals[os->lacing_fill-1]|=0x200;
  108728. }
  108729. os->pageno=pageno+1;
  108730. return(0);
  108731. }
  108732. /* clear things to an initial state. Good to call, eg, before seeking */
  108733. int ogg_sync_reset(ogg_sync_state *oy){
  108734. oy->fill=0;
  108735. oy->returned=0;
  108736. oy->unsynced=0;
  108737. oy->headerbytes=0;
  108738. oy->bodybytes=0;
  108739. return(0);
  108740. }
  108741. int ogg_stream_reset(ogg_stream_state *os){
  108742. os->body_fill=0;
  108743. os->body_returned=0;
  108744. os->lacing_fill=0;
  108745. os->lacing_packet=0;
  108746. os->lacing_returned=0;
  108747. os->header_fill=0;
  108748. os->e_o_s=0;
  108749. os->b_o_s=0;
  108750. os->pageno=-1;
  108751. os->packetno=0;
  108752. os->granulepos=0;
  108753. return(0);
  108754. }
  108755. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  108756. ogg_stream_reset(os);
  108757. os->serialno=serialno;
  108758. return(0);
  108759. }
  108760. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  108761. /* The last part of decode. We have the stream broken into packet
  108762. segments. Now we need to group them into packets (or return the
  108763. out of sync markers) */
  108764. int ptr=os->lacing_returned;
  108765. if(os->lacing_packet<=ptr)return(0);
  108766. if(os->lacing_vals[ptr]&0x400){
  108767. /* we need to tell the codec there's a gap; it might need to
  108768. handle previous packet dependencies. */
  108769. os->lacing_returned++;
  108770. os->packetno++;
  108771. return(-1);
  108772. }
  108773. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  108774. to ask if there's a whole packet
  108775. waiting */
  108776. /* Gather the whole packet. We'll have no holes or a partial packet */
  108777. {
  108778. int size=os->lacing_vals[ptr]&0xff;
  108779. int bytes=size;
  108780. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  108781. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  108782. while(size==255){
  108783. int val=os->lacing_vals[++ptr];
  108784. size=val&0xff;
  108785. if(val&0x200)eos=0x200;
  108786. bytes+=size;
  108787. }
  108788. if(op){
  108789. op->e_o_s=eos;
  108790. op->b_o_s=bos;
  108791. op->packet=os->body_data+os->body_returned;
  108792. op->packetno=os->packetno;
  108793. op->granulepos=os->granule_vals[ptr];
  108794. op->bytes=bytes;
  108795. }
  108796. if(adv){
  108797. os->body_returned+=bytes;
  108798. os->lacing_returned=ptr+1;
  108799. os->packetno++;
  108800. }
  108801. }
  108802. return(1);
  108803. }
  108804. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  108805. return _packetout(os,op,1);
  108806. }
  108807. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  108808. return _packetout(os,op,0);
  108809. }
  108810. void ogg_packet_clear(ogg_packet *op) {
  108811. _ogg_free(op->packet);
  108812. memset(op, 0, sizeof(*op));
  108813. }
  108814. #ifdef _V_SELFTEST
  108815. #include <stdio.h>
  108816. ogg_stream_state os_en, os_de;
  108817. ogg_sync_state oy;
  108818. void checkpacket(ogg_packet *op,int len, int no, int pos){
  108819. long j;
  108820. static int sequence=0;
  108821. static int lastno=0;
  108822. if(op->bytes!=len){
  108823. fprintf(stderr,"incorrect packet length!\n");
  108824. exit(1);
  108825. }
  108826. if(op->granulepos!=pos){
  108827. fprintf(stderr,"incorrect packet position!\n");
  108828. exit(1);
  108829. }
  108830. /* packet number just follows sequence/gap; adjust the input number
  108831. for that */
  108832. if(no==0){
  108833. sequence=0;
  108834. }else{
  108835. sequence++;
  108836. if(no>lastno+1)
  108837. sequence++;
  108838. }
  108839. lastno=no;
  108840. if(op->packetno!=sequence){
  108841. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  108842. (long)(op->packetno),sequence);
  108843. exit(1);
  108844. }
  108845. /* Test data */
  108846. for(j=0;j<op->bytes;j++)
  108847. if(op->packet[j]!=((j+no)&0xff)){
  108848. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  108849. j,op->packet[j],(j+no)&0xff);
  108850. exit(1);
  108851. }
  108852. }
  108853. void check_page(unsigned char *data,const int *header,ogg_page *og){
  108854. long j;
  108855. /* Test data */
  108856. for(j=0;j<og->body_len;j++)
  108857. if(og->body[j]!=data[j]){
  108858. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  108859. j,data[j],og->body[j]);
  108860. exit(1);
  108861. }
  108862. /* Test header */
  108863. for(j=0;j<og->header_len;j++){
  108864. if(og->header[j]!=header[j]){
  108865. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  108866. for(j=0;j<header[26]+27;j++)
  108867. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  108868. fprintf(stderr,"\n");
  108869. exit(1);
  108870. }
  108871. }
  108872. if(og->header_len!=header[26]+27){
  108873. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  108874. og->header_len,header[26]+27);
  108875. exit(1);
  108876. }
  108877. }
  108878. void print_header(ogg_page *og){
  108879. int j;
  108880. fprintf(stderr,"\nHEADER:\n");
  108881. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  108882. og->header[0],og->header[1],og->header[2],og->header[3],
  108883. (int)og->header[4],(int)og->header[5]);
  108884. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  108885. (og->header[9]<<24)|(og->header[8]<<16)|
  108886. (og->header[7]<<8)|og->header[6],
  108887. (og->header[17]<<24)|(og->header[16]<<16)|
  108888. (og->header[15]<<8)|og->header[14],
  108889. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  108890. (og->header[19]<<8)|og->header[18]);
  108891. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  108892. (int)og->header[22],(int)og->header[23],
  108893. (int)og->header[24],(int)og->header[25],
  108894. (int)og->header[26]);
  108895. for(j=27;j<og->header_len;j++)
  108896. fprintf(stderr,"%d ",(int)og->header[j]);
  108897. fprintf(stderr,")\n\n");
  108898. }
  108899. void copy_page(ogg_page *og){
  108900. unsigned char *temp=_ogg_malloc(og->header_len);
  108901. memcpy(temp,og->header,og->header_len);
  108902. og->header=temp;
  108903. temp=_ogg_malloc(og->body_len);
  108904. memcpy(temp,og->body,og->body_len);
  108905. og->body=temp;
  108906. }
  108907. void free_page(ogg_page *og){
  108908. _ogg_free (og->header);
  108909. _ogg_free (og->body);
  108910. }
  108911. void error(void){
  108912. fprintf(stderr,"error!\n");
  108913. exit(1);
  108914. }
  108915. /* 17 only */
  108916. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  108917. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108918. 0x01,0x02,0x03,0x04,0,0,0,0,
  108919. 0x15,0xed,0xec,0x91,
  108920. 1,
  108921. 17};
  108922. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  108923. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108924. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108925. 0x01,0x02,0x03,0x04,0,0,0,0,
  108926. 0x59,0x10,0x6c,0x2c,
  108927. 1,
  108928. 17};
  108929. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108930. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  108931. 0x01,0x02,0x03,0x04,1,0,0,0,
  108932. 0x89,0x33,0x85,0xce,
  108933. 13,
  108934. 254,255,0,255,1,255,245,255,255,0,
  108935. 255,255,90};
  108936. /* nil packets; beginning,middle,end */
  108937. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108938. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108939. 0x01,0x02,0x03,0x04,0,0,0,0,
  108940. 0xff,0x7b,0x23,0x17,
  108941. 1,
  108942. 0};
  108943. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108944. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  108945. 0x01,0x02,0x03,0x04,1,0,0,0,
  108946. 0x5c,0x3f,0x66,0xcb,
  108947. 17,
  108948. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  108949. 255,255,90,0};
  108950. /* large initial packet */
  108951. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108952. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108953. 0x01,0x02,0x03,0x04,0,0,0,0,
  108954. 0x01,0x27,0x31,0xaa,
  108955. 18,
  108956. 255,255,255,255,255,255,255,255,
  108957. 255,255,255,255,255,255,255,255,255,10};
  108958. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  108959. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  108960. 0x01,0x02,0x03,0x04,1,0,0,0,
  108961. 0x7f,0x4e,0x8a,0xd2,
  108962. 4,
  108963. 255,4,255,0};
  108964. /* continuing packet test */
  108965. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108966. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108967. 0x01,0x02,0x03,0x04,0,0,0,0,
  108968. 0xff,0x7b,0x23,0x17,
  108969. 1,
  108970. 0};
  108971. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108972. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  108973. 0x01,0x02,0x03,0x04,1,0,0,0,
  108974. 0x54,0x05,0x51,0xc8,
  108975. 17,
  108976. 255,255,255,255,255,255,255,255,
  108977. 255,255,255,255,255,255,255,255,255};
  108978. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  108979. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  108980. 0x01,0x02,0x03,0x04,2,0,0,0,
  108981. 0xc8,0xc3,0xcb,0xed,
  108982. 5,
  108983. 10,255,4,255,0};
  108984. /* page with the 255 segment limit */
  108985. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  108986. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  108987. 0x01,0x02,0x03,0x04,0,0,0,0,
  108988. 0xff,0x7b,0x23,0x17,
  108989. 1,
  108990. 0};
  108991. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  108992. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  108993. 0x01,0x02,0x03,0x04,1,0,0,0,
  108994. 0xed,0x2a,0x2e,0xa7,
  108995. 255,
  108996. 10,10,10,10,10,10,10,10,
  108997. 10,10,10,10,10,10,10,10,
  108998. 10,10,10,10,10,10,10,10,
  108999. 10,10,10,10,10,10,10,10,
  109000. 10,10,10,10,10,10,10,10,
  109001. 10,10,10,10,10,10,10,10,
  109002. 10,10,10,10,10,10,10,10,
  109003. 10,10,10,10,10,10,10,10,
  109004. 10,10,10,10,10,10,10,10,
  109005. 10,10,10,10,10,10,10,10,
  109006. 10,10,10,10,10,10,10,10,
  109007. 10,10,10,10,10,10,10,10,
  109008. 10,10,10,10,10,10,10,10,
  109009. 10,10,10,10,10,10,10,10,
  109010. 10,10,10,10,10,10,10,10,
  109011. 10,10,10,10,10,10,10,10,
  109012. 10,10,10,10,10,10,10,10,
  109013. 10,10,10,10,10,10,10,10,
  109014. 10,10,10,10,10,10,10,10,
  109015. 10,10,10,10,10,10,10,10,
  109016. 10,10,10,10,10,10,10,10,
  109017. 10,10,10,10,10,10,10,10,
  109018. 10,10,10,10,10,10,10,10,
  109019. 10,10,10,10,10,10,10,10,
  109020. 10,10,10,10,10,10,10,10,
  109021. 10,10,10,10,10,10,10,10,
  109022. 10,10,10,10,10,10,10,10,
  109023. 10,10,10,10,10,10,10,10,
  109024. 10,10,10,10,10,10,10,10,
  109025. 10,10,10,10,10,10,10,10,
  109026. 10,10,10,10,10,10,10,10,
  109027. 10,10,10,10,10,10,10};
  109028. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109029. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109030. 0x01,0x02,0x03,0x04,2,0,0,0,
  109031. 0x6c,0x3b,0x82,0x3d,
  109032. 1,
  109033. 50};
  109034. /* packet that overspans over an entire page */
  109035. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109036. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109037. 0x01,0x02,0x03,0x04,0,0,0,0,
  109038. 0xff,0x7b,0x23,0x17,
  109039. 1,
  109040. 0};
  109041. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109042. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109043. 0x01,0x02,0x03,0x04,1,0,0,0,
  109044. 0x3c,0xd9,0x4d,0x3f,
  109045. 17,
  109046. 100,255,255,255,255,255,255,255,255,
  109047. 255,255,255,255,255,255,255,255};
  109048. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109049. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109050. 0x01,0x02,0x03,0x04,2,0,0,0,
  109051. 0x01,0xd2,0xe5,0xe5,
  109052. 17,
  109053. 255,255,255,255,255,255,255,255,
  109054. 255,255,255,255,255,255,255,255,255};
  109055. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109056. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109057. 0x01,0x02,0x03,0x04,3,0,0,0,
  109058. 0xef,0xdd,0x88,0xde,
  109059. 7,
  109060. 255,255,75,255,4,255,0};
  109061. /* packet that overspans over an entire page */
  109062. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109063. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109064. 0x01,0x02,0x03,0x04,0,0,0,0,
  109065. 0xff,0x7b,0x23,0x17,
  109066. 1,
  109067. 0};
  109068. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109069. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109070. 0x01,0x02,0x03,0x04,1,0,0,0,
  109071. 0x3c,0xd9,0x4d,0x3f,
  109072. 17,
  109073. 100,255,255,255,255,255,255,255,255,
  109074. 255,255,255,255,255,255,255,255};
  109075. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109076. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109077. 0x01,0x02,0x03,0x04,2,0,0,0,
  109078. 0xd4,0xe0,0x60,0xe5,
  109079. 1,0};
  109080. void test_pack(const int *pl, const int **headers, int byteskip,
  109081. int pageskip, int packetskip){
  109082. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109083. long inptr=0;
  109084. long outptr=0;
  109085. long deptr=0;
  109086. long depacket=0;
  109087. long granule_pos=7,pageno=0;
  109088. int i,j,packets,pageout=pageskip;
  109089. int eosflag=0;
  109090. int bosflag=0;
  109091. int byteskipcount=0;
  109092. ogg_stream_reset(&os_en);
  109093. ogg_stream_reset(&os_de);
  109094. ogg_sync_reset(&oy);
  109095. for(packets=0;packets<packetskip;packets++)
  109096. depacket+=pl[packets];
  109097. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109098. for(i=0;i<packets;i++){
  109099. /* construct a test packet */
  109100. ogg_packet op;
  109101. int len=pl[i];
  109102. op.packet=data+inptr;
  109103. op.bytes=len;
  109104. op.e_o_s=(pl[i+1]<0?1:0);
  109105. op.granulepos=granule_pos;
  109106. granule_pos+=1024;
  109107. for(j=0;j<len;j++)data[inptr++]=i+j;
  109108. /* submit the test packet */
  109109. ogg_stream_packetin(&os_en,&op);
  109110. /* retrieve any finished pages */
  109111. {
  109112. ogg_page og;
  109113. while(ogg_stream_pageout(&os_en,&og)){
  109114. /* We have a page. Check it carefully */
  109115. fprintf(stderr,"%ld, ",pageno);
  109116. if(headers[pageno]==NULL){
  109117. fprintf(stderr,"coded too many pages!\n");
  109118. exit(1);
  109119. }
  109120. check_page(data+outptr,headers[pageno],&og);
  109121. outptr+=og.body_len;
  109122. pageno++;
  109123. if(pageskip){
  109124. bosflag=1;
  109125. pageskip--;
  109126. deptr+=og.body_len;
  109127. }
  109128. /* have a complete page; submit it to sync/decode */
  109129. {
  109130. ogg_page og_de;
  109131. ogg_packet op_de,op_de2;
  109132. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109133. char *next=buf;
  109134. byteskipcount+=og.header_len;
  109135. if(byteskipcount>byteskip){
  109136. memcpy(next,og.header,byteskipcount-byteskip);
  109137. next+=byteskipcount-byteskip;
  109138. byteskipcount=byteskip;
  109139. }
  109140. byteskipcount+=og.body_len;
  109141. if(byteskipcount>byteskip){
  109142. memcpy(next,og.body,byteskipcount-byteskip);
  109143. next+=byteskipcount-byteskip;
  109144. byteskipcount=byteskip;
  109145. }
  109146. ogg_sync_wrote(&oy,next-buf);
  109147. while(1){
  109148. int ret=ogg_sync_pageout(&oy,&og_de);
  109149. if(ret==0)break;
  109150. if(ret<0)continue;
  109151. /* got a page. Happy happy. Verify that it's good. */
  109152. fprintf(stderr,"(%ld), ",pageout);
  109153. check_page(data+deptr,headers[pageout],&og_de);
  109154. deptr+=og_de.body_len;
  109155. pageout++;
  109156. /* submit it to deconstitution */
  109157. ogg_stream_pagein(&os_de,&og_de);
  109158. /* packets out? */
  109159. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109160. ogg_stream_packetpeek(&os_de,NULL);
  109161. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109162. /* verify peek and out match */
  109163. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109164. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109165. depacket);
  109166. exit(1);
  109167. }
  109168. /* verify the packet! */
  109169. /* check data */
  109170. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109171. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109172. depacket);
  109173. exit(1);
  109174. }
  109175. /* check bos flag */
  109176. if(bosflag==0 && op_de.b_o_s==0){
  109177. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109178. exit(1);
  109179. }
  109180. if(bosflag && op_de.b_o_s){
  109181. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109182. exit(1);
  109183. }
  109184. bosflag=1;
  109185. depacket+=op_de.bytes;
  109186. /* check eos flag */
  109187. if(eosflag){
  109188. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109189. exit(1);
  109190. }
  109191. if(op_de.e_o_s)eosflag=1;
  109192. /* check granulepos flag */
  109193. if(op_de.granulepos!=-1){
  109194. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109195. }
  109196. }
  109197. }
  109198. }
  109199. }
  109200. }
  109201. }
  109202. _ogg_free(data);
  109203. if(headers[pageno]!=NULL){
  109204. fprintf(stderr,"did not write last page!\n");
  109205. exit(1);
  109206. }
  109207. if(headers[pageout]!=NULL){
  109208. fprintf(stderr,"did not decode last page!\n");
  109209. exit(1);
  109210. }
  109211. if(inptr!=outptr){
  109212. fprintf(stderr,"encoded page data incomplete!\n");
  109213. exit(1);
  109214. }
  109215. if(inptr!=deptr){
  109216. fprintf(stderr,"decoded page data incomplete!\n");
  109217. exit(1);
  109218. }
  109219. if(inptr!=depacket){
  109220. fprintf(stderr,"decoded packet data incomplete!\n");
  109221. exit(1);
  109222. }
  109223. if(!eosflag){
  109224. fprintf(stderr,"Never got a packet with EOS set!\n");
  109225. exit(1);
  109226. }
  109227. fprintf(stderr,"ok.\n");
  109228. }
  109229. int main(void){
  109230. ogg_stream_init(&os_en,0x04030201);
  109231. ogg_stream_init(&os_de,0x04030201);
  109232. ogg_sync_init(&oy);
  109233. /* Exercise each code path in the framing code. Also verify that
  109234. the checksums are working. */
  109235. {
  109236. /* 17 only */
  109237. const int packets[]={17, -1};
  109238. const int *headret[]={head1_0,NULL};
  109239. fprintf(stderr,"testing single page encoding... ");
  109240. test_pack(packets,headret,0,0,0);
  109241. }
  109242. {
  109243. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109244. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109245. const int *headret[]={head1_1,head2_1,NULL};
  109246. fprintf(stderr,"testing basic page encoding... ");
  109247. test_pack(packets,headret,0,0,0);
  109248. }
  109249. {
  109250. /* nil packets; beginning,middle,end */
  109251. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109252. const int *headret[]={head1_2,head2_2,NULL};
  109253. fprintf(stderr,"testing basic nil packets... ");
  109254. test_pack(packets,headret,0,0,0);
  109255. }
  109256. {
  109257. /* large initial packet */
  109258. const int packets[]={4345,259,255,-1};
  109259. const int *headret[]={head1_3,head2_3,NULL};
  109260. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109261. test_pack(packets,headret,0,0,0);
  109262. }
  109263. {
  109264. /* continuing packet test */
  109265. const int packets[]={0,4345,259,255,-1};
  109266. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109267. fprintf(stderr,"testing single packet page span... ");
  109268. test_pack(packets,headret,0,0,0);
  109269. }
  109270. /* page with the 255 segment limit */
  109271. {
  109272. const int packets[]={0,10,10,10,10,10,10,10,10,
  109273. 10,10,10,10,10,10,10,10,
  109274. 10,10,10,10,10,10,10,10,
  109275. 10,10,10,10,10,10,10,10,
  109276. 10,10,10,10,10,10,10,10,
  109277. 10,10,10,10,10,10,10,10,
  109278. 10,10,10,10,10,10,10,10,
  109279. 10,10,10,10,10,10,10,10,
  109280. 10,10,10,10,10,10,10,10,
  109281. 10,10,10,10,10,10,10,10,
  109282. 10,10,10,10,10,10,10,10,
  109283. 10,10,10,10,10,10,10,10,
  109284. 10,10,10,10,10,10,10,10,
  109285. 10,10,10,10,10,10,10,10,
  109286. 10,10,10,10,10,10,10,10,
  109287. 10,10,10,10,10,10,10,10,
  109288. 10,10,10,10,10,10,10,10,
  109289. 10,10,10,10,10,10,10,10,
  109290. 10,10,10,10,10,10,10,10,
  109291. 10,10,10,10,10,10,10,10,
  109292. 10,10,10,10,10,10,10,10,
  109293. 10,10,10,10,10,10,10,10,
  109294. 10,10,10,10,10,10,10,10,
  109295. 10,10,10,10,10,10,10,10,
  109296. 10,10,10,10,10,10,10,10,
  109297. 10,10,10,10,10,10,10,10,
  109298. 10,10,10,10,10,10,10,10,
  109299. 10,10,10,10,10,10,10,10,
  109300. 10,10,10,10,10,10,10,10,
  109301. 10,10,10,10,10,10,10,10,
  109302. 10,10,10,10,10,10,10,10,
  109303. 10,10,10,10,10,10,10,50,-1};
  109304. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109305. fprintf(stderr,"testing max packet segments... ");
  109306. test_pack(packets,headret,0,0,0);
  109307. }
  109308. {
  109309. /* packet that overspans over an entire page */
  109310. const int packets[]={0,100,9000,259,255,-1};
  109311. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109312. fprintf(stderr,"testing very large packets... ");
  109313. test_pack(packets,headret,0,0,0);
  109314. }
  109315. {
  109316. /* test for the libogg 1.1.1 resync in large continuation bug
  109317. found by Josh Coalson) */
  109318. const int packets[]={0,100,9000,259,255,-1};
  109319. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109320. fprintf(stderr,"testing continuation resync in very large packets... ");
  109321. test_pack(packets,headret,100,2,3);
  109322. }
  109323. {
  109324. /* term only page. why not? */
  109325. const int packets[]={0,100,4080,-1};
  109326. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109327. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109328. test_pack(packets,headret,0,0,0);
  109329. }
  109330. {
  109331. /* build a bunch of pages for testing */
  109332. unsigned char *data=_ogg_malloc(1024*1024);
  109333. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109334. int inptr=0,i,j;
  109335. ogg_page og[5];
  109336. ogg_stream_reset(&os_en);
  109337. for(i=0;pl[i]!=-1;i++){
  109338. ogg_packet op;
  109339. int len=pl[i];
  109340. op.packet=data+inptr;
  109341. op.bytes=len;
  109342. op.e_o_s=(pl[i+1]<0?1:0);
  109343. op.granulepos=(i+1)*1000;
  109344. for(j=0;j<len;j++)data[inptr++]=i+j;
  109345. ogg_stream_packetin(&os_en,&op);
  109346. }
  109347. _ogg_free(data);
  109348. /* retrieve finished pages */
  109349. for(i=0;i<5;i++){
  109350. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109351. fprintf(stderr,"Too few pages output building sync tests!\n");
  109352. exit(1);
  109353. }
  109354. copy_page(&og[i]);
  109355. }
  109356. /* Test lost pages on pagein/packetout: no rollback */
  109357. {
  109358. ogg_page temp;
  109359. ogg_packet test;
  109360. fprintf(stderr,"Testing loss of pages... ");
  109361. ogg_sync_reset(&oy);
  109362. ogg_stream_reset(&os_de);
  109363. for(i=0;i<5;i++){
  109364. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109365. og[i].header_len);
  109366. ogg_sync_wrote(&oy,og[i].header_len);
  109367. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109368. ogg_sync_wrote(&oy,og[i].body_len);
  109369. }
  109370. ogg_sync_pageout(&oy,&temp);
  109371. ogg_stream_pagein(&os_de,&temp);
  109372. ogg_sync_pageout(&oy,&temp);
  109373. ogg_stream_pagein(&os_de,&temp);
  109374. ogg_sync_pageout(&oy,&temp);
  109375. /* skip */
  109376. ogg_sync_pageout(&oy,&temp);
  109377. ogg_stream_pagein(&os_de,&temp);
  109378. /* do we get the expected results/packets? */
  109379. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109380. checkpacket(&test,0,0,0);
  109381. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109382. checkpacket(&test,100,1,-1);
  109383. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109384. checkpacket(&test,4079,2,3000);
  109385. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109386. fprintf(stderr,"Error: loss of page did not return error\n");
  109387. exit(1);
  109388. }
  109389. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109390. checkpacket(&test,76,5,-1);
  109391. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109392. checkpacket(&test,34,6,-1);
  109393. fprintf(stderr,"ok.\n");
  109394. }
  109395. /* Test lost pages on pagein/packetout: rollback with continuation */
  109396. {
  109397. ogg_page temp;
  109398. ogg_packet test;
  109399. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109400. ogg_sync_reset(&oy);
  109401. ogg_stream_reset(&os_de);
  109402. for(i=0;i<5;i++){
  109403. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109404. og[i].header_len);
  109405. ogg_sync_wrote(&oy,og[i].header_len);
  109406. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109407. ogg_sync_wrote(&oy,og[i].body_len);
  109408. }
  109409. ogg_sync_pageout(&oy,&temp);
  109410. ogg_stream_pagein(&os_de,&temp);
  109411. ogg_sync_pageout(&oy,&temp);
  109412. ogg_stream_pagein(&os_de,&temp);
  109413. ogg_sync_pageout(&oy,&temp);
  109414. ogg_stream_pagein(&os_de,&temp);
  109415. ogg_sync_pageout(&oy,&temp);
  109416. /* skip */
  109417. ogg_sync_pageout(&oy,&temp);
  109418. ogg_stream_pagein(&os_de,&temp);
  109419. /* do we get the expected results/packets? */
  109420. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109421. checkpacket(&test,0,0,0);
  109422. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109423. checkpacket(&test,100,1,-1);
  109424. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109425. checkpacket(&test,4079,2,3000);
  109426. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109427. checkpacket(&test,2956,3,4000);
  109428. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109429. fprintf(stderr,"Error: loss of page did not return error\n");
  109430. exit(1);
  109431. }
  109432. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109433. checkpacket(&test,300,13,14000);
  109434. fprintf(stderr,"ok.\n");
  109435. }
  109436. /* the rest only test sync */
  109437. {
  109438. ogg_page og_de;
  109439. /* Test fractional page inputs: incomplete capture */
  109440. fprintf(stderr,"Testing sync on partial inputs... ");
  109441. ogg_sync_reset(&oy);
  109442. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109443. 3);
  109444. ogg_sync_wrote(&oy,3);
  109445. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109446. /* Test fractional page inputs: incomplete fixed header */
  109447. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109448. 20);
  109449. ogg_sync_wrote(&oy,20);
  109450. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109451. /* Test fractional page inputs: incomplete header */
  109452. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109453. 5);
  109454. ogg_sync_wrote(&oy,5);
  109455. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109456. /* Test fractional page inputs: incomplete body */
  109457. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109458. og[1].header_len-28);
  109459. ogg_sync_wrote(&oy,og[1].header_len-28);
  109460. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109461. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109462. ogg_sync_wrote(&oy,1000);
  109463. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109464. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109465. og[1].body_len-1000);
  109466. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109467. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109468. fprintf(stderr,"ok.\n");
  109469. }
  109470. /* Test fractional page inputs: page + incomplete capture */
  109471. {
  109472. ogg_page og_de;
  109473. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109474. ogg_sync_reset(&oy);
  109475. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109476. og[1].header_len);
  109477. ogg_sync_wrote(&oy,og[1].header_len);
  109478. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109479. og[1].body_len);
  109480. ogg_sync_wrote(&oy,og[1].body_len);
  109481. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109482. 20);
  109483. ogg_sync_wrote(&oy,20);
  109484. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109485. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109486. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109487. og[1].header_len-20);
  109488. ogg_sync_wrote(&oy,og[1].header_len-20);
  109489. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109490. og[1].body_len);
  109491. ogg_sync_wrote(&oy,og[1].body_len);
  109492. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109493. fprintf(stderr,"ok.\n");
  109494. }
  109495. /* Test recapture: garbage + page */
  109496. {
  109497. ogg_page og_de;
  109498. fprintf(stderr,"Testing search for capture... ");
  109499. ogg_sync_reset(&oy);
  109500. /* 'garbage' */
  109501. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109502. og[1].body_len);
  109503. ogg_sync_wrote(&oy,og[1].body_len);
  109504. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109505. og[1].header_len);
  109506. ogg_sync_wrote(&oy,og[1].header_len);
  109507. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109508. og[1].body_len);
  109509. ogg_sync_wrote(&oy,og[1].body_len);
  109510. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109511. 20);
  109512. ogg_sync_wrote(&oy,20);
  109513. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109514. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109515. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109516. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109517. og[2].header_len-20);
  109518. ogg_sync_wrote(&oy,og[2].header_len-20);
  109519. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109520. og[2].body_len);
  109521. ogg_sync_wrote(&oy,og[2].body_len);
  109522. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109523. fprintf(stderr,"ok.\n");
  109524. }
  109525. /* Test recapture: page + garbage + page */
  109526. {
  109527. ogg_page og_de;
  109528. fprintf(stderr,"Testing recapture... ");
  109529. ogg_sync_reset(&oy);
  109530. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109531. og[1].header_len);
  109532. ogg_sync_wrote(&oy,og[1].header_len);
  109533. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109534. og[1].body_len);
  109535. ogg_sync_wrote(&oy,og[1].body_len);
  109536. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109537. og[2].header_len);
  109538. ogg_sync_wrote(&oy,og[2].header_len);
  109539. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109540. og[2].header_len);
  109541. ogg_sync_wrote(&oy,og[2].header_len);
  109542. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109543. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109544. og[2].body_len-5);
  109545. ogg_sync_wrote(&oy,og[2].body_len-5);
  109546. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109547. og[3].header_len);
  109548. ogg_sync_wrote(&oy,og[3].header_len);
  109549. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109550. og[3].body_len);
  109551. ogg_sync_wrote(&oy,og[3].body_len);
  109552. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109553. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109554. fprintf(stderr,"ok.\n");
  109555. }
  109556. /* Free page data that was previously copied */
  109557. {
  109558. for(i=0;i<5;i++){
  109559. free_page(&og[i]);
  109560. }
  109561. }
  109562. }
  109563. return(0);
  109564. }
  109565. #endif
  109566. #endif
  109567. /*** End of inlined file: framing.c ***/
  109568. /*** Start of inlined file: analysis.c ***/
  109569. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109570. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109571. // tasks..
  109572. #if JUCE_MSVC
  109573. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109574. #endif
  109575. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109576. #if JUCE_USE_OGGVORBIS
  109577. #include <stdio.h>
  109578. #include <string.h>
  109579. #include <math.h>
  109580. /*** Start of inlined file: codec_internal.h ***/
  109581. #ifndef _V_CODECI_H_
  109582. #define _V_CODECI_H_
  109583. /*** Start of inlined file: envelope.h ***/
  109584. #ifndef _V_ENVELOPE_
  109585. #define _V_ENVELOPE_
  109586. /*** Start of inlined file: mdct.h ***/
  109587. #ifndef _OGG_mdct_H_
  109588. #define _OGG_mdct_H_
  109589. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109590. #ifdef MDCT_INTEGERIZED
  109591. #define DATA_TYPE int
  109592. #define REG_TYPE register int
  109593. #define TRIGBITS 14
  109594. #define cPI3_8 6270
  109595. #define cPI2_8 11585
  109596. #define cPI1_8 15137
  109597. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109598. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109599. #define HALVE(x) ((x)>>1)
  109600. #else
  109601. #define DATA_TYPE float
  109602. #define REG_TYPE float
  109603. #define cPI3_8 .38268343236508977175F
  109604. #define cPI2_8 .70710678118654752441F
  109605. #define cPI1_8 .92387953251128675613F
  109606. #define FLOAT_CONV(x) (x)
  109607. #define MULT_NORM(x) (x)
  109608. #define HALVE(x) ((x)*.5f)
  109609. #endif
  109610. typedef struct {
  109611. int n;
  109612. int log2n;
  109613. DATA_TYPE *trig;
  109614. int *bitrev;
  109615. DATA_TYPE scale;
  109616. } mdct_lookup;
  109617. extern void mdct_init(mdct_lookup *lookup,int n);
  109618. extern void mdct_clear(mdct_lookup *l);
  109619. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109620. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109621. #endif
  109622. /*** End of inlined file: mdct.h ***/
  109623. #define VE_PRE 16
  109624. #define VE_WIN 4
  109625. #define VE_POST 2
  109626. #define VE_AMP (VE_PRE+VE_POST-1)
  109627. #define VE_BANDS 7
  109628. #define VE_NEARDC 15
  109629. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109630. #define VE_MAXSTRETCH 12 /* one-third full block */
  109631. typedef struct {
  109632. float ampbuf[VE_AMP];
  109633. int ampptr;
  109634. float nearDC[VE_NEARDC];
  109635. float nearDC_acc;
  109636. float nearDC_partialacc;
  109637. int nearptr;
  109638. } envelope_filter_state;
  109639. typedef struct {
  109640. int begin;
  109641. int end;
  109642. float *window;
  109643. float total;
  109644. } envelope_band;
  109645. typedef struct {
  109646. int ch;
  109647. int winlength;
  109648. int searchstep;
  109649. float minenergy;
  109650. mdct_lookup mdct;
  109651. float *mdct_win;
  109652. envelope_band band[VE_BANDS];
  109653. envelope_filter_state *filter;
  109654. int stretch;
  109655. int *mark;
  109656. long storage;
  109657. long current;
  109658. long curmark;
  109659. long cursor;
  109660. } envelope_lookup;
  109661. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  109662. extern void _ve_envelope_clear(envelope_lookup *e);
  109663. extern long _ve_envelope_search(vorbis_dsp_state *v);
  109664. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  109665. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  109666. #endif
  109667. /*** End of inlined file: envelope.h ***/
  109668. /*** Start of inlined file: codebook.h ***/
  109669. #ifndef _V_CODEBOOK_H_
  109670. #define _V_CODEBOOK_H_
  109671. /* This structure encapsulates huffman and VQ style encoding books; it
  109672. doesn't do anything specific to either.
  109673. valuelist/quantlist are nonNULL (and q_* significant) only if
  109674. there's entry->value mapping to be done.
  109675. If encode-side mapping must be done (and thus the entry needs to be
  109676. hunted), the auxiliary encode pointer will point to a decision
  109677. tree. This is true of both VQ and huffman, but is mostly useful
  109678. with VQ.
  109679. */
  109680. typedef struct static_codebook{
  109681. long dim; /* codebook dimensions (elements per vector) */
  109682. long entries; /* codebook entries */
  109683. long *lengthlist; /* codeword lengths in bits */
  109684. /* mapping ***************************************************************/
  109685. int maptype; /* 0=none
  109686. 1=implicitly populated values from map column
  109687. 2=listed arbitrary values */
  109688. /* The below does a linear, single monotonic sequence mapping. */
  109689. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  109690. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  109691. int q_quant; /* bits: 0 < quant <= 16 */
  109692. int q_sequencep; /* bitflag */
  109693. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  109694. map == 2: list of dim*entries quantized entry vals
  109695. */
  109696. /* encode helpers ********************************************************/
  109697. struct encode_aux_nearestmatch *nearest_tree;
  109698. struct encode_aux_threshmatch *thresh_tree;
  109699. struct encode_aux_pigeonhole *pigeon_tree;
  109700. int allocedp;
  109701. } static_codebook;
  109702. /* this structures an arbitrary trained book to quickly find the
  109703. nearest cell match */
  109704. typedef struct encode_aux_nearestmatch{
  109705. /* pre-calculated partitioning tree */
  109706. long *ptr0;
  109707. long *ptr1;
  109708. long *p; /* decision points (each is an entry) */
  109709. long *q; /* decision points (each is an entry) */
  109710. long aux; /* number of tree entries */
  109711. long alloc;
  109712. } encode_aux_nearestmatch;
  109713. /* assumes a maptype of 1; encode side only, so that's OK */
  109714. typedef struct encode_aux_threshmatch{
  109715. float *quantthresh;
  109716. long *quantmap;
  109717. int quantvals;
  109718. int threshvals;
  109719. } encode_aux_threshmatch;
  109720. typedef struct encode_aux_pigeonhole{
  109721. float min;
  109722. float del;
  109723. int mapentries;
  109724. int quantvals;
  109725. long *pigeonmap;
  109726. long fittotal;
  109727. long *fitlist;
  109728. long *fitmap;
  109729. long *fitlength;
  109730. } encode_aux_pigeonhole;
  109731. typedef struct codebook{
  109732. long dim; /* codebook dimensions (elements per vector) */
  109733. long entries; /* codebook entries */
  109734. long used_entries; /* populated codebook entries */
  109735. const static_codebook *c;
  109736. /* for encode, the below are entry-ordered, fully populated */
  109737. /* for decode, the below are ordered by bitreversed codeword and only
  109738. used entries are populated */
  109739. float *valuelist; /* list of dim*entries actual entry values */
  109740. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  109741. int *dec_index; /* only used if sparseness collapsed */
  109742. char *dec_codelengths;
  109743. ogg_uint32_t *dec_firsttable;
  109744. int dec_firsttablen;
  109745. int dec_maxlength;
  109746. } codebook;
  109747. extern void vorbis_staticbook_clear(static_codebook *b);
  109748. extern void vorbis_staticbook_destroy(static_codebook *b);
  109749. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  109750. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  109751. extern void vorbis_book_clear(codebook *b);
  109752. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  109753. extern float *_book_logdist(const static_codebook *b,float *vals);
  109754. extern float _float32_unpack(long val);
  109755. extern long _float32_pack(float val);
  109756. extern int _best(codebook *book, float *a, int step);
  109757. extern int _ilog(unsigned int v);
  109758. extern long _book_maptype1_quantvals(const static_codebook *b);
  109759. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  109760. extern long vorbis_book_codeword(codebook *book,int entry);
  109761. extern long vorbis_book_codelen(codebook *book,int entry);
  109762. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  109763. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  109764. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  109765. extern int vorbis_book_errorv(codebook *book, float *a);
  109766. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  109767. oggpack_buffer *b);
  109768. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  109769. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  109770. oggpack_buffer *b,int n);
  109771. extern long vorbis_book_decodev_set(codebook *book, float *a,
  109772. oggpack_buffer *b,int n);
  109773. extern long vorbis_book_decodev_add(codebook *book, float *a,
  109774. oggpack_buffer *b,int n);
  109775. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  109776. long off,int ch,
  109777. oggpack_buffer *b,int n);
  109778. #endif
  109779. /*** End of inlined file: codebook.h ***/
  109780. #define BLOCKTYPE_IMPULSE 0
  109781. #define BLOCKTYPE_PADDING 1
  109782. #define BLOCKTYPE_TRANSITION 0
  109783. #define BLOCKTYPE_LONG 1
  109784. #define PACKETBLOBS 15
  109785. typedef struct vorbis_block_internal{
  109786. float **pcmdelay; /* this is a pointer into local storage */
  109787. float ampmax;
  109788. int blocktype;
  109789. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  109790. blob [PACKETBLOBS/2] points to
  109791. the oggpack_buffer in the
  109792. main vorbis_block */
  109793. } vorbis_block_internal;
  109794. typedef void vorbis_look_floor;
  109795. typedef void vorbis_look_residue;
  109796. typedef void vorbis_look_transform;
  109797. /* mode ************************************************************/
  109798. typedef struct {
  109799. int blockflag;
  109800. int windowtype;
  109801. int transformtype;
  109802. int mapping;
  109803. } vorbis_info_mode;
  109804. typedef void vorbis_info_floor;
  109805. typedef void vorbis_info_residue;
  109806. typedef void vorbis_info_mapping;
  109807. /*** Start of inlined file: psy.h ***/
  109808. #ifndef _V_PSY_H_
  109809. #define _V_PSY_H_
  109810. /*** Start of inlined file: smallft.h ***/
  109811. #ifndef _V_SMFT_H_
  109812. #define _V_SMFT_H_
  109813. typedef struct {
  109814. int n;
  109815. float *trigcache;
  109816. int *splitcache;
  109817. } drft_lookup;
  109818. extern void drft_forward(drft_lookup *l,float *data);
  109819. extern void drft_backward(drft_lookup *l,float *data);
  109820. extern void drft_init(drft_lookup *l,int n);
  109821. extern void drft_clear(drft_lookup *l);
  109822. #endif
  109823. /*** End of inlined file: smallft.h ***/
  109824. /*** Start of inlined file: backends.h ***/
  109825. /* this is exposed up here because we need it for static modes.
  109826. Lookups for each backend aren't exposed because there's no reason
  109827. to do so */
  109828. #ifndef _vorbis_backend_h_
  109829. #define _vorbis_backend_h_
  109830. /* this would all be simpler/shorter with templates, but.... */
  109831. /* Floor backend generic *****************************************/
  109832. typedef struct{
  109833. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  109834. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  109835. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  109836. void (*free_info) (vorbis_info_floor *);
  109837. void (*free_look) (vorbis_look_floor *);
  109838. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  109839. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  109840. void *buffer,float *);
  109841. } vorbis_func_floor;
  109842. typedef struct{
  109843. int order;
  109844. long rate;
  109845. long barkmap;
  109846. int ampbits;
  109847. int ampdB;
  109848. int numbooks; /* <= 16 */
  109849. int books[16];
  109850. float lessthan; /* encode-only config setting hacks for libvorbis */
  109851. float greaterthan; /* encode-only config setting hacks for libvorbis */
  109852. } vorbis_info_floor0;
  109853. #define VIF_POSIT 63
  109854. #define VIF_CLASS 16
  109855. #define VIF_PARTS 31
  109856. typedef struct{
  109857. int partitions; /* 0 to 31 */
  109858. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  109859. int class_dim[VIF_CLASS]; /* 1 to 8 */
  109860. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  109861. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  109862. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  109863. int mult; /* 1 2 3 or 4 */
  109864. int postlist[VIF_POSIT+2]; /* first two implicit */
  109865. /* encode side analysis parameters */
  109866. float maxover;
  109867. float maxunder;
  109868. float maxerr;
  109869. float twofitweight;
  109870. float twofitatten;
  109871. int n;
  109872. } vorbis_info_floor1;
  109873. /* Residue backend generic *****************************************/
  109874. typedef struct{
  109875. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  109876. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  109877. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  109878. vorbis_info_residue *);
  109879. void (*free_info) (vorbis_info_residue *);
  109880. void (*free_look) (vorbis_look_residue *);
  109881. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  109882. float **,int *,int);
  109883. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  109884. vorbis_look_residue *,
  109885. float **,float **,int *,int,long **);
  109886. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  109887. float **,int *,int);
  109888. } vorbis_func_residue;
  109889. typedef struct vorbis_info_residue0{
  109890. /* block-partitioned VQ coded straight residue */
  109891. long begin;
  109892. long end;
  109893. /* first stage (lossless partitioning) */
  109894. int grouping; /* group n vectors per partition */
  109895. int partitions; /* possible codebooks for a partition */
  109896. int groupbook; /* huffbook for partitioning */
  109897. int secondstages[64]; /* expanded out to pointers in lookup */
  109898. int booklist[256]; /* list of second stage books */
  109899. float classmetric1[64];
  109900. float classmetric2[64];
  109901. } vorbis_info_residue0;
  109902. /* Mapping backend generic *****************************************/
  109903. typedef struct{
  109904. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  109905. oggpack_buffer *);
  109906. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  109907. void (*free_info) (vorbis_info_mapping *);
  109908. int (*forward) (struct vorbis_block *vb);
  109909. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  109910. } vorbis_func_mapping;
  109911. typedef struct vorbis_info_mapping0{
  109912. int submaps; /* <= 16 */
  109913. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  109914. int floorsubmap[16]; /* [mux] submap to floors */
  109915. int residuesubmap[16]; /* [mux] submap to residue */
  109916. int coupling_steps;
  109917. int coupling_mag[256];
  109918. int coupling_ang[256];
  109919. } vorbis_info_mapping0;
  109920. #endif
  109921. /*** End of inlined file: backends.h ***/
  109922. #ifndef EHMER_MAX
  109923. #define EHMER_MAX 56
  109924. #endif
  109925. /* psychoacoustic setup ********************************************/
  109926. #define P_BANDS 17 /* 62Hz to 16kHz */
  109927. #define P_LEVELS 8 /* 30dB to 100dB */
  109928. #define P_LEVEL_0 30. /* 30 dB */
  109929. #define P_NOISECURVES 3
  109930. #define NOISE_COMPAND_LEVELS 40
  109931. typedef struct vorbis_info_psy{
  109932. int blockflag;
  109933. float ath_adjatt;
  109934. float ath_maxatt;
  109935. float tone_masteratt[P_NOISECURVES];
  109936. float tone_centerboost;
  109937. float tone_decay;
  109938. float tone_abs_limit;
  109939. float toneatt[P_BANDS];
  109940. int noisemaskp;
  109941. float noisemaxsupp;
  109942. float noisewindowlo;
  109943. float noisewindowhi;
  109944. int noisewindowlomin;
  109945. int noisewindowhimin;
  109946. int noisewindowfixed;
  109947. float noiseoff[P_NOISECURVES][P_BANDS];
  109948. float noisecompand[NOISE_COMPAND_LEVELS];
  109949. float max_curve_dB;
  109950. int normal_channel_p;
  109951. int normal_point_p;
  109952. int normal_start;
  109953. int normal_partition;
  109954. double normal_thresh;
  109955. } vorbis_info_psy;
  109956. typedef struct{
  109957. int eighth_octave_lines;
  109958. /* for block long/short tuning; encode only */
  109959. float preecho_thresh[VE_BANDS];
  109960. float postecho_thresh[VE_BANDS];
  109961. float stretch_penalty;
  109962. float preecho_minenergy;
  109963. float ampmax_att_per_sec;
  109964. /* channel coupling config */
  109965. int coupling_pkHz[PACKETBLOBS];
  109966. int coupling_pointlimit[2][PACKETBLOBS];
  109967. int coupling_prepointamp[PACKETBLOBS];
  109968. int coupling_postpointamp[PACKETBLOBS];
  109969. int sliding_lowpass[2][PACKETBLOBS];
  109970. } vorbis_info_psy_global;
  109971. typedef struct {
  109972. float ampmax;
  109973. int channels;
  109974. vorbis_info_psy_global *gi;
  109975. int coupling_pointlimit[2][P_NOISECURVES];
  109976. } vorbis_look_psy_global;
  109977. typedef struct {
  109978. int n;
  109979. struct vorbis_info_psy *vi;
  109980. float ***tonecurves;
  109981. float **noiseoffset;
  109982. float *ath;
  109983. long *octave; /* in n.ocshift format */
  109984. long *bark;
  109985. long firstoc;
  109986. long shiftoc;
  109987. int eighth_octave_lines; /* power of two, please */
  109988. int total_octave_lines;
  109989. long rate; /* cache it */
  109990. float m_val; /* Masking compensation value */
  109991. } vorbis_look_psy;
  109992. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  109993. vorbis_info_psy_global *gi,int n,long rate);
  109994. extern void _vp_psy_clear(vorbis_look_psy *p);
  109995. extern void *_vi_psy_dup(void *source);
  109996. extern void _vi_psy_free(vorbis_info_psy *i);
  109997. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  109998. extern void _vp_remove_floor(vorbis_look_psy *p,
  109999. float *mdct,
  110000. int *icodedflr,
  110001. float *residue,
  110002. int sliding_lowpass);
  110003. extern void _vp_noisemask(vorbis_look_psy *p,
  110004. float *logmdct,
  110005. float *logmask);
  110006. extern void _vp_tonemask(vorbis_look_psy *p,
  110007. float *logfft,
  110008. float *logmask,
  110009. float global_specmax,
  110010. float local_specmax);
  110011. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110012. float *noise,
  110013. float *tone,
  110014. int offset_select,
  110015. float *logmask,
  110016. float *mdct,
  110017. float *logmdct);
  110018. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110019. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110020. vorbis_info_psy_global *g,
  110021. vorbis_look_psy *p,
  110022. vorbis_info_mapping0 *vi,
  110023. float **mdct);
  110024. extern void _vp_couple(int blobno,
  110025. vorbis_info_psy_global *g,
  110026. vorbis_look_psy *p,
  110027. vorbis_info_mapping0 *vi,
  110028. float **res,
  110029. float **mag_memo,
  110030. int **mag_sort,
  110031. int **ifloor,
  110032. int *nonzero,
  110033. int sliding_lowpass);
  110034. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110035. float *in,float *out,int *sortedindex);
  110036. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110037. float *magnitudes,int *sortedindex);
  110038. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110039. vorbis_look_psy *p,
  110040. vorbis_info_mapping0 *vi,
  110041. float **mags);
  110042. extern void hf_reduction(vorbis_info_psy_global *g,
  110043. vorbis_look_psy *p,
  110044. vorbis_info_mapping0 *vi,
  110045. float **mdct);
  110046. #endif
  110047. /*** End of inlined file: psy.h ***/
  110048. /*** Start of inlined file: bitrate.h ***/
  110049. #ifndef _V_BITRATE_H_
  110050. #define _V_BITRATE_H_
  110051. /*** Start of inlined file: os.h ***/
  110052. #ifndef _OS_H
  110053. #define _OS_H
  110054. /********************************************************************
  110055. * *
  110056. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110057. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110058. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110059. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110060. * *
  110061. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110062. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110063. * *
  110064. ********************************************************************
  110065. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110066. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110067. ********************************************************************/
  110068. #ifdef HAVE_CONFIG_H
  110069. #include "config.h"
  110070. #endif
  110071. #include <math.h>
  110072. /*** Start of inlined file: misc.h ***/
  110073. #ifndef _V_RANDOM_H_
  110074. #define _V_RANDOM_H_
  110075. extern int analysis_noisy;
  110076. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110077. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110078. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110079. ogg_int64_t off);
  110080. #ifdef DEBUG_MALLOC
  110081. #define _VDBG_GRAPHFILE "malloc.m"
  110082. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110083. extern void _VDBG_free(void *ptr,char *file,long line);
  110084. #ifndef MISC_C
  110085. #undef _ogg_malloc
  110086. #undef _ogg_calloc
  110087. #undef _ogg_realloc
  110088. #undef _ogg_free
  110089. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110090. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110091. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110092. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110093. #endif
  110094. #endif
  110095. #endif
  110096. /*** End of inlined file: misc.h ***/
  110097. #ifndef _V_IFDEFJAIL_H_
  110098. # define _V_IFDEFJAIL_H_
  110099. # ifdef __GNUC__
  110100. # define STIN static __inline__
  110101. # elif _WIN32
  110102. # define STIN static __inline
  110103. # else
  110104. # define STIN static
  110105. # endif
  110106. #ifdef DJGPP
  110107. # define rint(x) (floor((x)+0.5f))
  110108. #endif
  110109. #ifndef M_PI
  110110. # define M_PI (3.1415926536f)
  110111. #endif
  110112. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110113. # include <malloc.h>
  110114. # define rint(x) (floor((x)+0.5f))
  110115. # define NO_FLOAT_MATH_LIB
  110116. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110117. #endif
  110118. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110119. void *_alloca(size_t size);
  110120. # define alloca _alloca
  110121. #endif
  110122. #ifndef FAST_HYPOT
  110123. # define FAST_HYPOT hypot
  110124. #endif
  110125. #endif
  110126. #ifdef HAVE_ALLOCA_H
  110127. # include <alloca.h>
  110128. #endif
  110129. #ifdef USE_MEMORY_H
  110130. # include <memory.h>
  110131. #endif
  110132. #ifndef min
  110133. # define min(x,y) ((x)>(y)?(y):(x))
  110134. #endif
  110135. #ifndef max
  110136. # define max(x,y) ((x)<(y)?(y):(x))
  110137. #endif
  110138. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110139. # define VORBIS_FPU_CONTROL
  110140. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110141. Because of encapsulation constraints (GCC can't see inside the asm
  110142. block and so we end up doing stupid things like a store/load that
  110143. is collectively a noop), we do it this way */
  110144. /* we must set up the fpu before this works!! */
  110145. typedef ogg_int16_t vorbis_fpu_control;
  110146. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110147. ogg_int16_t ret;
  110148. ogg_int16_t temp;
  110149. __asm__ __volatile__("fnstcw %0\n\t"
  110150. "movw %0,%%dx\n\t"
  110151. "orw $62463,%%dx\n\t"
  110152. "movw %%dx,%1\n\t"
  110153. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110154. *fpu=ret;
  110155. }
  110156. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110157. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110158. }
  110159. /* assumes the FPU is in round mode! */
  110160. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110161. we get extra fst/fld to
  110162. truncate precision */
  110163. int i;
  110164. __asm__("fistl %0": "=m"(i) : "t"(f));
  110165. return(i);
  110166. }
  110167. #endif
  110168. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110169. # define VORBIS_FPU_CONTROL
  110170. typedef ogg_int16_t vorbis_fpu_control;
  110171. static __inline int vorbis_ftoi(double f){
  110172. int i;
  110173. __asm{
  110174. fld f
  110175. fistp i
  110176. }
  110177. return i;
  110178. }
  110179. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110180. }
  110181. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110182. }
  110183. #endif
  110184. #ifndef VORBIS_FPU_CONTROL
  110185. typedef int vorbis_fpu_control;
  110186. static int vorbis_ftoi(double f){
  110187. return (int)(f+.5);
  110188. }
  110189. /* We don't have special code for this compiler/arch, so do it the slow way */
  110190. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110191. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110192. #endif
  110193. #endif /* _OS_H */
  110194. /*** End of inlined file: os.h ***/
  110195. /* encode side bitrate tracking */
  110196. typedef struct bitrate_manager_state {
  110197. int managed;
  110198. long avg_reservoir;
  110199. long minmax_reservoir;
  110200. long avg_bitsper;
  110201. long min_bitsper;
  110202. long max_bitsper;
  110203. long short_per_long;
  110204. double avgfloat;
  110205. vorbis_block *vb;
  110206. int choice;
  110207. } bitrate_manager_state;
  110208. typedef struct bitrate_manager_info{
  110209. long avg_rate;
  110210. long min_rate;
  110211. long max_rate;
  110212. long reservoir_bits;
  110213. double reservoir_bias;
  110214. double slew_damp;
  110215. } bitrate_manager_info;
  110216. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110217. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110218. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110219. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110220. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110221. #endif
  110222. /*** End of inlined file: bitrate.h ***/
  110223. static int ilog(unsigned int v){
  110224. int ret=0;
  110225. while(v){
  110226. ret++;
  110227. v>>=1;
  110228. }
  110229. return(ret);
  110230. }
  110231. static int ilog2(unsigned int v){
  110232. int ret=0;
  110233. if(v)--v;
  110234. while(v){
  110235. ret++;
  110236. v>>=1;
  110237. }
  110238. return(ret);
  110239. }
  110240. typedef struct private_state {
  110241. /* local lookup storage */
  110242. envelope_lookup *ve; /* envelope lookup */
  110243. int window[2];
  110244. vorbis_look_transform **transform[2]; /* block, type */
  110245. drft_lookup fft_look[2];
  110246. int modebits;
  110247. vorbis_look_floor **flr;
  110248. vorbis_look_residue **residue;
  110249. vorbis_look_psy *psy;
  110250. vorbis_look_psy_global *psy_g_look;
  110251. /* local storage, only used on the encoding side. This way the
  110252. application does not need to worry about freeing some packets'
  110253. memory and not others'; packet storage is always tracked.
  110254. Cleared next call to a _dsp_ function */
  110255. unsigned char *header;
  110256. unsigned char *header1;
  110257. unsigned char *header2;
  110258. bitrate_manager_state bms;
  110259. ogg_int64_t sample_count;
  110260. } private_state;
  110261. /* codec_setup_info contains all the setup information specific to the
  110262. specific compression/decompression mode in progress (eg,
  110263. psychoacoustic settings, channel setup, options, codebook
  110264. etc).
  110265. *********************************************************************/
  110266. /*** Start of inlined file: highlevel.h ***/
  110267. typedef struct highlevel_byblocktype {
  110268. double tone_mask_setting;
  110269. double tone_peaklimit_setting;
  110270. double noise_bias_setting;
  110271. double noise_compand_setting;
  110272. } highlevel_byblocktype;
  110273. typedef struct highlevel_encode_setup {
  110274. void *setup;
  110275. int set_in_stone;
  110276. double base_setting;
  110277. double long_setting;
  110278. double short_setting;
  110279. double impulse_noisetune;
  110280. int managed;
  110281. long bitrate_min;
  110282. long bitrate_av;
  110283. double bitrate_av_damp;
  110284. long bitrate_max;
  110285. long bitrate_reservoir;
  110286. double bitrate_reservoir_bias;
  110287. int impulse_block_p;
  110288. int noise_normalize_p;
  110289. double stereo_point_setting;
  110290. double lowpass_kHz;
  110291. double ath_floating_dB;
  110292. double ath_absolute_dB;
  110293. double amplitude_track_dBpersec;
  110294. double trigger_setting;
  110295. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110296. } highlevel_encode_setup;
  110297. /*** End of inlined file: highlevel.h ***/
  110298. typedef struct codec_setup_info {
  110299. /* Vorbis supports only short and long blocks, but allows the
  110300. encoder to choose the sizes */
  110301. long blocksizes[2];
  110302. /* modes are the primary means of supporting on-the-fly different
  110303. blocksizes, different channel mappings (LR or M/A),
  110304. different residue backends, etc. Each mode consists of a
  110305. blocksize flag and a mapping (along with the mapping setup */
  110306. int modes;
  110307. int maps;
  110308. int floors;
  110309. int residues;
  110310. int books;
  110311. int psys; /* encode only */
  110312. vorbis_info_mode *mode_param[64];
  110313. int map_type[64];
  110314. vorbis_info_mapping *map_param[64];
  110315. int floor_type[64];
  110316. vorbis_info_floor *floor_param[64];
  110317. int residue_type[64];
  110318. vorbis_info_residue *residue_param[64];
  110319. static_codebook *book_param[256];
  110320. codebook *fullbooks;
  110321. vorbis_info_psy *psy_param[4]; /* encode only */
  110322. vorbis_info_psy_global psy_g_param;
  110323. bitrate_manager_info bi;
  110324. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110325. highly redundant structure, but
  110326. improves clarity of program flow. */
  110327. int halfrate_flag; /* painless downsample for decode */
  110328. } codec_setup_info;
  110329. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110330. extern void _vp_global_free(vorbis_look_psy_global *look);
  110331. #endif
  110332. /*** End of inlined file: codec_internal.h ***/
  110333. /*** Start of inlined file: registry.h ***/
  110334. #ifndef _V_REG_H_
  110335. #define _V_REG_H_
  110336. #define VI_TRANSFORMB 1
  110337. #define VI_WINDOWB 1
  110338. #define VI_TIMEB 1
  110339. #define VI_FLOORB 2
  110340. #define VI_RESB 3
  110341. #define VI_MAPB 1
  110342. extern vorbis_func_floor *_floor_P[];
  110343. extern vorbis_func_residue *_residue_P[];
  110344. extern vorbis_func_mapping *_mapping_P[];
  110345. #endif
  110346. /*** End of inlined file: registry.h ***/
  110347. /*** Start of inlined file: scales.h ***/
  110348. #ifndef _V_SCALES_H_
  110349. #define _V_SCALES_H_
  110350. #include <math.h>
  110351. /* 20log10(x) */
  110352. #define VORBIS_IEEE_FLOAT32 1
  110353. #ifdef VORBIS_IEEE_FLOAT32
  110354. static float unitnorm(float x){
  110355. union {
  110356. ogg_uint32_t i;
  110357. float f;
  110358. } ix;
  110359. ix.f = x;
  110360. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110361. return ix.f;
  110362. }
  110363. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110364. static float todB(const float *x){
  110365. union {
  110366. ogg_uint32_t i;
  110367. float f;
  110368. } ix;
  110369. ix.f = *x;
  110370. ix.i = ix.i&0x7fffffff;
  110371. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110372. }
  110373. #define todB_nn(x) todB(x)
  110374. #else
  110375. static float unitnorm(float x){
  110376. if(x<0)return(-1.f);
  110377. return(1.f);
  110378. }
  110379. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110380. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110381. #endif
  110382. #define fromdB(x) (exp((x)*.11512925f))
  110383. /* The bark scale equations are approximations, since the original
  110384. table was somewhat hand rolled. The below are chosen to have the
  110385. best possible fit to the rolled tables, thus their somewhat odd
  110386. appearance (these are more accurate and over a longer range than
  110387. the oft-quoted bark equations found in the texts I have). The
  110388. approximations are valid from 0 - 30kHz (nyquist) or so.
  110389. all f in Hz, z in Bark */
  110390. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110391. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110392. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110393. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110394. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110395. 0.0 */
  110396. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110397. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110398. #endif
  110399. /*** End of inlined file: scales.h ***/
  110400. int analysis_noisy=1;
  110401. /* decides between modes, dispatches to the appropriate mapping. */
  110402. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110403. int ret,i;
  110404. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110405. vb->glue_bits=0;
  110406. vb->time_bits=0;
  110407. vb->floor_bits=0;
  110408. vb->res_bits=0;
  110409. /* first things first. Make sure encode is ready */
  110410. for(i=0;i<PACKETBLOBS;i++)
  110411. oggpack_reset(vbi->packetblob[i]);
  110412. /* we only have one mapping type (0), and we let the mapping code
  110413. itself figure out what soft mode to use. This allows easier
  110414. bitrate management */
  110415. if((ret=_mapping_P[0]->forward(vb)))
  110416. return(ret);
  110417. if(op){
  110418. if(vorbis_bitrate_managed(vb))
  110419. /* The app is using a bitmanaged mode... but not using the
  110420. bitrate management interface. */
  110421. return(OV_EINVAL);
  110422. op->packet=oggpack_get_buffer(&vb->opb);
  110423. op->bytes=oggpack_bytes(&vb->opb);
  110424. op->b_o_s=0;
  110425. op->e_o_s=vb->eofflag;
  110426. op->granulepos=vb->granulepos;
  110427. op->packetno=vb->sequence; /* for sake of completeness */
  110428. }
  110429. return(0);
  110430. }
  110431. /* there was no great place to put this.... */
  110432. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110433. int j;
  110434. FILE *of;
  110435. char buffer[80];
  110436. /* if(i==5870){*/
  110437. sprintf(buffer,"%s_%d.m",base,i);
  110438. of=fopen(buffer,"w");
  110439. if(!of)perror("failed to open data dump file");
  110440. for(j=0;j<n;j++){
  110441. if(bark){
  110442. float b=toBARK((4000.f*j/n)+.25);
  110443. fprintf(of,"%f ",b);
  110444. }else
  110445. if(off!=0)
  110446. fprintf(of,"%f ",(double)(j+off)/8000.);
  110447. else
  110448. fprintf(of,"%f ",(double)j);
  110449. if(dB){
  110450. float val;
  110451. if(v[j]==0.)
  110452. val=-140.;
  110453. else
  110454. val=todB(v+j);
  110455. fprintf(of,"%f\n",val);
  110456. }else{
  110457. fprintf(of,"%f\n",v[j]);
  110458. }
  110459. }
  110460. fclose(of);
  110461. /* } */
  110462. }
  110463. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110464. ogg_int64_t off){
  110465. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110466. }
  110467. #endif
  110468. /*** End of inlined file: analysis.c ***/
  110469. /*** Start of inlined file: bitrate.c ***/
  110470. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110471. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110472. // tasks..
  110473. #if JUCE_MSVC
  110474. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110475. #endif
  110476. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110477. #if JUCE_USE_OGGVORBIS
  110478. #include <stdlib.h>
  110479. #include <string.h>
  110480. #include <math.h>
  110481. /* compute bitrate tracking setup */
  110482. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110483. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110484. bitrate_manager_info *bi=&ci->bi;
  110485. memset(bm,0,sizeof(*bm));
  110486. if(bi && (bi->reservoir_bits>0)){
  110487. long ratesamples=vi->rate;
  110488. int halfsamples=ci->blocksizes[0]>>1;
  110489. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110490. bm->managed=1;
  110491. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110492. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110493. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110494. bm->avgfloat=PACKETBLOBS/2;
  110495. /* not a necessary fix, but one that leads to a more balanced
  110496. typical initialization */
  110497. {
  110498. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110499. bm->minmax_reservoir=desired_fill;
  110500. bm->avg_reservoir=desired_fill;
  110501. }
  110502. }
  110503. }
  110504. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110505. memset(bm,0,sizeof(*bm));
  110506. return;
  110507. }
  110508. int vorbis_bitrate_managed(vorbis_block *vb){
  110509. vorbis_dsp_state *vd=vb->vd;
  110510. private_state *b=(private_state*)vd->backend_state;
  110511. bitrate_manager_state *bm=&b->bms;
  110512. if(bm && bm->managed)return(1);
  110513. return(0);
  110514. }
  110515. /* finish taking in the block we just processed */
  110516. int vorbis_bitrate_addblock(vorbis_block *vb){
  110517. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110518. vorbis_dsp_state *vd=vb->vd;
  110519. private_state *b=(private_state*)vd->backend_state;
  110520. bitrate_manager_state *bm=&b->bms;
  110521. vorbis_info *vi=vd->vi;
  110522. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110523. bitrate_manager_info *bi=&ci->bi;
  110524. int choice=rint(bm->avgfloat);
  110525. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110526. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110527. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110528. int samples=ci->blocksizes[vb->W]>>1;
  110529. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110530. if(!bm->managed){
  110531. /* not a bitrate managed stream, but for API simplicity, we'll
  110532. buffer the packet to keep the code path clean */
  110533. if(bm->vb)return(-1); /* one has been submitted without
  110534. being claimed */
  110535. bm->vb=vb;
  110536. return(0);
  110537. }
  110538. bm->vb=vb;
  110539. /* look ahead for avg floater */
  110540. if(bm->avg_bitsper>0){
  110541. double slew=0.;
  110542. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110543. double slewlimit= 15./bi->slew_damp;
  110544. /* choosing a new floater:
  110545. if we're over target, we slew down
  110546. if we're under target, we slew up
  110547. choose slew as follows: look through packetblobs of this frame
  110548. and set slew as the first in the appropriate direction that
  110549. gives us the slew we want. This may mean no slew if delta is
  110550. already favorable.
  110551. Then limit slew to slew max */
  110552. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110553. while(choice>0 && this_bits>avg_target_bits &&
  110554. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110555. choice--;
  110556. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110557. }
  110558. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110559. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110560. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110561. choice++;
  110562. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110563. }
  110564. }
  110565. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110566. if(slew<-slewlimit)slew=-slewlimit;
  110567. if(slew>slewlimit)slew=slewlimit;
  110568. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110569. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110570. }
  110571. /* enforce min(if used) on the current floater (if used) */
  110572. if(bm->min_bitsper>0){
  110573. /* do we need to force the bitrate up? */
  110574. if(this_bits<min_target_bits){
  110575. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110576. choice++;
  110577. if(choice>=PACKETBLOBS)break;
  110578. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110579. }
  110580. }
  110581. }
  110582. /* enforce max (if used) on the current floater (if used) */
  110583. if(bm->max_bitsper>0){
  110584. /* do we need to force the bitrate down? */
  110585. if(this_bits>max_target_bits){
  110586. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110587. choice--;
  110588. if(choice<0)break;
  110589. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110590. }
  110591. }
  110592. }
  110593. /* Choice of packetblobs now made based on floater, and min/max
  110594. requirements. Now boundary check extreme choices */
  110595. if(choice<0){
  110596. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110597. frame will need to be truncated */
  110598. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110599. bm->choice=choice=0;
  110600. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110601. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110602. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110603. }
  110604. }else{
  110605. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110606. if(choice>=PACKETBLOBS)
  110607. choice=PACKETBLOBS-1;
  110608. bm->choice=choice;
  110609. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110610. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110611. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110612. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110613. }
  110614. /* now we have the final packet and the final packet size. Update statistics */
  110615. /* min and max reservoir */
  110616. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110617. if(max_target_bits>0 && this_bits>max_target_bits){
  110618. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110619. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110620. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110621. }else{
  110622. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110623. if(bm->minmax_reservoir>desired_fill){
  110624. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110625. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110626. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110627. }else{
  110628. bm->minmax_reservoir=desired_fill;
  110629. }
  110630. }else{
  110631. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110632. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110633. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110634. }else{
  110635. bm->minmax_reservoir=desired_fill;
  110636. }
  110637. }
  110638. }
  110639. }
  110640. /* avg reservoir */
  110641. if(bm->avg_bitsper>0){
  110642. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110643. bm->avg_reservoir+=this_bits-avg_target_bits;
  110644. }
  110645. return(0);
  110646. }
  110647. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110648. private_state *b=(private_state*)vd->backend_state;
  110649. bitrate_manager_state *bm=&b->bms;
  110650. vorbis_block *vb=bm->vb;
  110651. int choice=PACKETBLOBS/2;
  110652. if(!vb)return 0;
  110653. if(op){
  110654. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110655. if(vorbis_bitrate_managed(vb))
  110656. choice=bm->choice;
  110657. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110658. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110659. op->b_o_s=0;
  110660. op->e_o_s=vb->eofflag;
  110661. op->granulepos=vb->granulepos;
  110662. op->packetno=vb->sequence; /* for sake of completeness */
  110663. }
  110664. bm->vb=0;
  110665. return(1);
  110666. }
  110667. #endif
  110668. /*** End of inlined file: bitrate.c ***/
  110669. /*** Start of inlined file: block.c ***/
  110670. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110671. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110672. // tasks..
  110673. #if JUCE_MSVC
  110674. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110675. #endif
  110676. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110677. #if JUCE_USE_OGGVORBIS
  110678. #include <stdio.h>
  110679. #include <stdlib.h>
  110680. #include <string.h>
  110681. /*** Start of inlined file: window.h ***/
  110682. #ifndef _V_WINDOW_
  110683. #define _V_WINDOW_
  110684. extern float *_vorbis_window_get(int n);
  110685. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  110686. int lW,int W,int nW);
  110687. #endif
  110688. /*** End of inlined file: window.h ***/
  110689. /*** Start of inlined file: lpc.h ***/
  110690. #ifndef _V_LPC_H_
  110691. #define _V_LPC_H_
  110692. /* simple linear scale LPC code */
  110693. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  110694. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  110695. float *data,long n);
  110696. #endif
  110697. /*** End of inlined file: lpc.h ***/
  110698. /* pcm accumulator examples (not exhaustive):
  110699. <-------------- lW ---------------->
  110700. <--------------- W ---------------->
  110701. : .....|..... _______________ |
  110702. : .''' | '''_--- | |\ |
  110703. :.....''' |_____--- '''......| | \_______|
  110704. :.................|__________________|_______|__|______|
  110705. |<------ Sl ------>| > Sr < |endW
  110706. |beginSl |endSl | |endSr
  110707. |beginW |endlW |beginSr
  110708. |< lW >|
  110709. <--------------- W ---------------->
  110710. | | .. ______________ |
  110711. | | ' `/ | ---_ |
  110712. |___.'___/`. | ---_____|
  110713. |_______|__|_______|_________________|
  110714. | >|Sl|< |<------ Sr ----->|endW
  110715. | | |endSl |beginSr |endSr
  110716. |beginW | |endlW
  110717. mult[0] |beginSl mult[n]
  110718. <-------------- lW ----------------->
  110719. |<--W-->|
  110720. : .............. ___ | |
  110721. : .''' |`/ \ | |
  110722. :.....''' |/`....\|...|
  110723. :.........................|___|___|___|
  110724. |Sl |Sr |endW
  110725. | | |endSr
  110726. | |beginSr
  110727. | |endSl
  110728. |beginSl
  110729. |beginW
  110730. */
  110731. /* block abstraction setup *********************************************/
  110732. #ifndef WORD_ALIGN
  110733. #define WORD_ALIGN 8
  110734. #endif
  110735. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  110736. int i;
  110737. memset(vb,0,sizeof(*vb));
  110738. vb->vd=v;
  110739. vb->localalloc=0;
  110740. vb->localstore=NULL;
  110741. if(v->analysisp){
  110742. vorbis_block_internal *vbi=(vorbis_block_internal*)
  110743. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  110744. vbi->ampmax=-9999;
  110745. for(i=0;i<PACKETBLOBS;i++){
  110746. if(i==PACKETBLOBS/2){
  110747. vbi->packetblob[i]=&vb->opb;
  110748. }else{
  110749. vbi->packetblob[i]=
  110750. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  110751. }
  110752. oggpack_writeinit(vbi->packetblob[i]);
  110753. }
  110754. }
  110755. return(0);
  110756. }
  110757. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  110758. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  110759. if(bytes+vb->localtop>vb->localalloc){
  110760. /* can't just _ogg_realloc... there are outstanding pointers */
  110761. if(vb->localstore){
  110762. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  110763. vb->totaluse+=vb->localtop;
  110764. link->next=vb->reap;
  110765. link->ptr=vb->localstore;
  110766. vb->reap=link;
  110767. }
  110768. /* highly conservative */
  110769. vb->localalloc=bytes;
  110770. vb->localstore=_ogg_malloc(vb->localalloc);
  110771. vb->localtop=0;
  110772. }
  110773. {
  110774. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  110775. vb->localtop+=bytes;
  110776. return ret;
  110777. }
  110778. }
  110779. /* reap the chain, pull the ripcord */
  110780. void _vorbis_block_ripcord(vorbis_block *vb){
  110781. /* reap the chain */
  110782. struct alloc_chain *reap=vb->reap;
  110783. while(reap){
  110784. struct alloc_chain *next=reap->next;
  110785. _ogg_free(reap->ptr);
  110786. memset(reap,0,sizeof(*reap));
  110787. _ogg_free(reap);
  110788. reap=next;
  110789. }
  110790. /* consolidate storage */
  110791. if(vb->totaluse){
  110792. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  110793. vb->localalloc+=vb->totaluse;
  110794. vb->totaluse=0;
  110795. }
  110796. /* pull the ripcord */
  110797. vb->localtop=0;
  110798. vb->reap=NULL;
  110799. }
  110800. int vorbis_block_clear(vorbis_block *vb){
  110801. int i;
  110802. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110803. _vorbis_block_ripcord(vb);
  110804. if(vb->localstore)_ogg_free(vb->localstore);
  110805. if(vbi){
  110806. for(i=0;i<PACKETBLOBS;i++){
  110807. oggpack_writeclear(vbi->packetblob[i]);
  110808. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  110809. }
  110810. _ogg_free(vbi);
  110811. }
  110812. memset(vb,0,sizeof(*vb));
  110813. return(0);
  110814. }
  110815. /* Analysis side code, but directly related to blocking. Thus it's
  110816. here and not in analysis.c (which is for analysis transforms only).
  110817. The init is here because some of it is shared */
  110818. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  110819. int i;
  110820. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110821. private_state *b=NULL;
  110822. int hs;
  110823. if(ci==NULL) return 1;
  110824. hs=ci->halfrate_flag;
  110825. memset(v,0,sizeof(*v));
  110826. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  110827. v->vi=vi;
  110828. b->modebits=ilog2(ci->modes);
  110829. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  110830. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  110831. /* MDCT is tranform 0 */
  110832. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110833. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  110834. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  110835. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  110836. /* Vorbis I uses only window type 0 */
  110837. b->window[0]=ilog2(ci->blocksizes[0])-6;
  110838. b->window[1]=ilog2(ci->blocksizes[1])-6;
  110839. if(encp){ /* encode/decode differ here */
  110840. /* analysis always needs an fft */
  110841. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  110842. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  110843. /* finish the codebooks */
  110844. if(!ci->fullbooks){
  110845. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110846. for(i=0;i<ci->books;i++)
  110847. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  110848. }
  110849. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  110850. for(i=0;i<ci->psys;i++){
  110851. _vp_psy_init(b->psy+i,
  110852. ci->psy_param[i],
  110853. &ci->psy_g_param,
  110854. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  110855. vi->rate);
  110856. }
  110857. v->analysisp=1;
  110858. }else{
  110859. /* finish the codebooks */
  110860. if(!ci->fullbooks){
  110861. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  110862. for(i=0;i<ci->books;i++){
  110863. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  110864. /* decode codebooks are now standalone after init */
  110865. vorbis_staticbook_destroy(ci->book_param[i]);
  110866. ci->book_param[i]=NULL;
  110867. }
  110868. }
  110869. }
  110870. /* initialize the storage vectors. blocksize[1] is small for encode,
  110871. but the correct size for decode */
  110872. v->pcm_storage=ci->blocksizes[1];
  110873. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  110874. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  110875. {
  110876. int i;
  110877. for(i=0;i<vi->channels;i++)
  110878. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  110879. }
  110880. /* all 1 (large block) or 0 (small block) */
  110881. /* explicitly set for the sake of clarity */
  110882. v->lW=0; /* previous window size */
  110883. v->W=0; /* current window size */
  110884. /* all vector indexes */
  110885. v->centerW=ci->blocksizes[1]/2;
  110886. v->pcm_current=v->centerW;
  110887. /* initialize all the backend lookups */
  110888. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  110889. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  110890. for(i=0;i<ci->floors;i++)
  110891. b->flr[i]=_floor_P[ci->floor_type[i]]->
  110892. look(v,ci->floor_param[i]);
  110893. for(i=0;i<ci->residues;i++)
  110894. b->residue[i]=_residue_P[ci->residue_type[i]]->
  110895. look(v,ci->residue_param[i]);
  110896. return 0;
  110897. }
  110898. /* arbitrary settings and spec-mandated numbers get filled in here */
  110899. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  110900. private_state *b=NULL;
  110901. if(_vds_shared_init(v,vi,1))return 1;
  110902. b=(private_state*)v->backend_state;
  110903. b->psy_g_look=_vp_global_look(vi);
  110904. /* Initialize the envelope state storage */
  110905. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  110906. _ve_envelope_init(b->ve,vi);
  110907. vorbis_bitrate_init(vi,&b->bms);
  110908. /* compressed audio packets start after the headers
  110909. with sequence number 3 */
  110910. v->sequence=3;
  110911. return(0);
  110912. }
  110913. void vorbis_dsp_clear(vorbis_dsp_state *v){
  110914. int i;
  110915. if(v){
  110916. vorbis_info *vi=v->vi;
  110917. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  110918. private_state *b=(private_state*)v->backend_state;
  110919. if(b){
  110920. if(b->ve){
  110921. _ve_envelope_clear(b->ve);
  110922. _ogg_free(b->ve);
  110923. }
  110924. if(b->transform[0]){
  110925. mdct_clear((mdct_lookup*) b->transform[0][0]);
  110926. _ogg_free(b->transform[0][0]);
  110927. _ogg_free(b->transform[0]);
  110928. }
  110929. if(b->transform[1]){
  110930. mdct_clear((mdct_lookup*) b->transform[1][0]);
  110931. _ogg_free(b->transform[1][0]);
  110932. _ogg_free(b->transform[1]);
  110933. }
  110934. if(b->flr){
  110935. for(i=0;i<ci->floors;i++)
  110936. _floor_P[ci->floor_type[i]]->
  110937. free_look(b->flr[i]);
  110938. _ogg_free(b->flr);
  110939. }
  110940. if(b->residue){
  110941. for(i=0;i<ci->residues;i++)
  110942. _residue_P[ci->residue_type[i]]->
  110943. free_look(b->residue[i]);
  110944. _ogg_free(b->residue);
  110945. }
  110946. if(b->psy){
  110947. for(i=0;i<ci->psys;i++)
  110948. _vp_psy_clear(b->psy+i);
  110949. _ogg_free(b->psy);
  110950. }
  110951. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  110952. vorbis_bitrate_clear(&b->bms);
  110953. drft_clear(&b->fft_look[0]);
  110954. drft_clear(&b->fft_look[1]);
  110955. }
  110956. if(v->pcm){
  110957. for(i=0;i<vi->channels;i++)
  110958. if(v->pcm[i])_ogg_free(v->pcm[i]);
  110959. _ogg_free(v->pcm);
  110960. if(v->pcmret)_ogg_free(v->pcmret);
  110961. }
  110962. if(b){
  110963. /* free header, header1, header2 */
  110964. if(b->header)_ogg_free(b->header);
  110965. if(b->header1)_ogg_free(b->header1);
  110966. if(b->header2)_ogg_free(b->header2);
  110967. _ogg_free(b);
  110968. }
  110969. memset(v,0,sizeof(*v));
  110970. }
  110971. }
  110972. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  110973. int i;
  110974. vorbis_info *vi=v->vi;
  110975. private_state *b=(private_state*)v->backend_state;
  110976. /* free header, header1, header2 */
  110977. if(b->header)_ogg_free(b->header);b->header=NULL;
  110978. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  110979. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  110980. /* Do we have enough storage space for the requested buffer? If not,
  110981. expand the PCM (and envelope) storage */
  110982. if(v->pcm_current+vals>=v->pcm_storage){
  110983. v->pcm_storage=v->pcm_current+vals*2;
  110984. for(i=0;i<vi->channels;i++){
  110985. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  110986. }
  110987. }
  110988. for(i=0;i<vi->channels;i++)
  110989. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  110990. return(v->pcmret);
  110991. }
  110992. static void _preextrapolate_helper(vorbis_dsp_state *v){
  110993. int i;
  110994. int order=32;
  110995. float *lpc=(float*)alloca(order*sizeof(*lpc));
  110996. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  110997. long j;
  110998. v->preextrapolate=1;
  110999. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111000. for(i=0;i<v->vi->channels;i++){
  111001. /* need to run the extrapolation in reverse! */
  111002. for(j=0;j<v->pcm_current;j++)
  111003. work[j]=v->pcm[i][v->pcm_current-j-1];
  111004. /* prime as above */
  111005. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111006. /* run the predictor filter */
  111007. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111008. order,
  111009. work+v->pcm_current-v->centerW,
  111010. v->centerW);
  111011. for(j=0;j<v->pcm_current;j++)
  111012. v->pcm[i][v->pcm_current-j-1]=work[j];
  111013. }
  111014. }
  111015. }
  111016. /* call with val<=0 to set eof */
  111017. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111018. vorbis_info *vi=v->vi;
  111019. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111020. if(vals<=0){
  111021. int order=32;
  111022. int i;
  111023. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111024. /* if it wasn't done earlier (very short sample) */
  111025. if(!v->preextrapolate)
  111026. _preextrapolate_helper(v);
  111027. /* We're encoding the end of the stream. Just make sure we have
  111028. [at least] a few full blocks of zeroes at the end. */
  111029. /* actually, we don't want zeroes; that could drop a large
  111030. amplitude off a cliff, creating spread spectrum noise that will
  111031. suck to encode. Extrapolate for the sake of cleanliness. */
  111032. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111033. v->eofflag=v->pcm_current;
  111034. v->pcm_current+=ci->blocksizes[1]*3;
  111035. for(i=0;i<vi->channels;i++){
  111036. if(v->eofflag>order*2){
  111037. /* extrapolate with LPC to fill in */
  111038. long n;
  111039. /* make a predictor filter */
  111040. n=v->eofflag;
  111041. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111042. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111043. /* run the predictor filter */
  111044. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111045. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111046. }else{
  111047. /* not enough data to extrapolate (unlikely to happen due to
  111048. guarding the overlap, but bulletproof in case that
  111049. assumtion goes away). zeroes will do. */
  111050. memset(v->pcm[i]+v->eofflag,0,
  111051. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111052. }
  111053. }
  111054. }else{
  111055. if(v->pcm_current+vals>v->pcm_storage)
  111056. return(OV_EINVAL);
  111057. v->pcm_current+=vals;
  111058. /* we may want to reverse extrapolate the beginning of a stream
  111059. too... in case we're beginning on a cliff! */
  111060. /* clumsy, but simple. It only runs once, so simple is good. */
  111061. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111062. _preextrapolate_helper(v);
  111063. }
  111064. return(0);
  111065. }
  111066. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111067. the next block on which to continue analysis */
  111068. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111069. int i;
  111070. vorbis_info *vi=v->vi;
  111071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111072. private_state *b=(private_state*)v->backend_state;
  111073. vorbis_look_psy_global *g=b->psy_g_look;
  111074. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111075. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111076. /* check to see if we're started... */
  111077. if(!v->preextrapolate)return(0);
  111078. /* check to see if we're done... */
  111079. if(v->eofflag==-1)return(0);
  111080. /* By our invariant, we have lW, W and centerW set. Search for
  111081. the next boundary so we can determine nW (the next window size)
  111082. which lets us compute the shape of the current block's window */
  111083. /* we do an envelope search even on a single blocksize; we may still
  111084. be throwing more bits at impulses, and envelope search handles
  111085. marking impulses too. */
  111086. {
  111087. long bp=_ve_envelope_search(v);
  111088. if(bp==-1){
  111089. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111090. full long block */
  111091. v->nW=0;
  111092. }else{
  111093. if(ci->blocksizes[0]==ci->blocksizes[1])
  111094. v->nW=0;
  111095. else
  111096. v->nW=bp;
  111097. }
  111098. }
  111099. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111100. {
  111101. /* center of next block + next block maximum right side. */
  111102. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111103. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111104. although this check is
  111105. less strict that the
  111106. _ve_envelope_search,
  111107. the search is not run
  111108. if we only use one
  111109. block size */
  111110. }
  111111. /* fill in the block. Note that for a short window, lW and nW are *short*
  111112. regardless of actual settings in the stream */
  111113. _vorbis_block_ripcord(vb);
  111114. vb->lW=v->lW;
  111115. vb->W=v->W;
  111116. vb->nW=v->nW;
  111117. if(v->W){
  111118. if(!v->lW || !v->nW){
  111119. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111120. /*fprintf(stderr,"-");*/
  111121. }else{
  111122. vbi->blocktype=BLOCKTYPE_LONG;
  111123. /*fprintf(stderr,"_");*/
  111124. }
  111125. }else{
  111126. if(_ve_envelope_mark(v)){
  111127. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111128. /*fprintf(stderr,"|");*/
  111129. }else{
  111130. vbi->blocktype=BLOCKTYPE_PADDING;
  111131. /*fprintf(stderr,".");*/
  111132. }
  111133. }
  111134. vb->vd=v;
  111135. vb->sequence=v->sequence++;
  111136. vb->granulepos=v->granulepos;
  111137. vb->pcmend=ci->blocksizes[v->W];
  111138. /* copy the vectors; this uses the local storage in vb */
  111139. /* this tracks 'strongest peak' for later psychoacoustics */
  111140. /* moved to the global psy state; clean this mess up */
  111141. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111142. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111143. vbi->ampmax=g->ampmax;
  111144. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111145. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111146. for(i=0;i<vi->channels;i++){
  111147. vbi->pcmdelay[i]=
  111148. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111149. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111150. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111151. /* before we added the delay
  111152. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111153. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111154. */
  111155. }
  111156. /* handle eof detection: eof==0 means that we've not yet received EOF
  111157. eof>0 marks the last 'real' sample in pcm[]
  111158. eof<0 'no more to do'; doesn't get here */
  111159. if(v->eofflag){
  111160. if(v->centerW>=v->eofflag){
  111161. v->eofflag=-1;
  111162. vb->eofflag=1;
  111163. return(1);
  111164. }
  111165. }
  111166. /* advance storage vectors and clean up */
  111167. {
  111168. int new_centerNext=ci->blocksizes[1]/2;
  111169. int movementW=centerNext-new_centerNext;
  111170. if(movementW>0){
  111171. _ve_envelope_shift(b->ve,movementW);
  111172. v->pcm_current-=movementW;
  111173. for(i=0;i<vi->channels;i++)
  111174. memmove(v->pcm[i],v->pcm[i]+movementW,
  111175. v->pcm_current*sizeof(*v->pcm[i]));
  111176. v->lW=v->W;
  111177. v->W=v->nW;
  111178. v->centerW=new_centerNext;
  111179. if(v->eofflag){
  111180. v->eofflag-=movementW;
  111181. if(v->eofflag<=0)v->eofflag=-1;
  111182. /* do not add padding to end of stream! */
  111183. if(v->centerW>=v->eofflag){
  111184. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111185. }else{
  111186. v->granulepos+=movementW;
  111187. }
  111188. }else{
  111189. v->granulepos+=movementW;
  111190. }
  111191. }
  111192. }
  111193. /* done */
  111194. return(1);
  111195. }
  111196. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111197. vorbis_info *vi=v->vi;
  111198. codec_setup_info *ci;
  111199. int hs;
  111200. if(!v->backend_state)return -1;
  111201. if(!vi)return -1;
  111202. ci=(codec_setup_info*) vi->codec_setup;
  111203. if(!ci)return -1;
  111204. hs=ci->halfrate_flag;
  111205. v->centerW=ci->blocksizes[1]>>(hs+1);
  111206. v->pcm_current=v->centerW>>hs;
  111207. v->pcm_returned=-1;
  111208. v->granulepos=-1;
  111209. v->sequence=-1;
  111210. v->eofflag=0;
  111211. ((private_state *)(v->backend_state))->sample_count=-1;
  111212. return(0);
  111213. }
  111214. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111215. if(_vds_shared_init(v,vi,0)) return 1;
  111216. vorbis_synthesis_restart(v);
  111217. return 0;
  111218. }
  111219. /* Unlike in analysis, the window is only partially applied for each
  111220. block. The time domain envelope is not yet handled at the point of
  111221. calling (as it relies on the previous block). */
  111222. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111223. vorbis_info *vi=v->vi;
  111224. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111225. private_state *b=(private_state*)v->backend_state;
  111226. int hs=ci->halfrate_flag;
  111227. int i,j;
  111228. if(!vb)return(OV_EINVAL);
  111229. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111230. v->lW=v->W;
  111231. v->W=vb->W;
  111232. v->nW=-1;
  111233. if((v->sequence==-1)||
  111234. (v->sequence+1 != vb->sequence)){
  111235. v->granulepos=-1; /* out of sequence; lose count */
  111236. b->sample_count=-1;
  111237. }
  111238. v->sequence=vb->sequence;
  111239. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111240. was called on block */
  111241. int n=ci->blocksizes[v->W]>>(hs+1);
  111242. int n0=ci->blocksizes[0]>>(hs+1);
  111243. int n1=ci->blocksizes[1]>>(hs+1);
  111244. int thisCenter;
  111245. int prevCenter;
  111246. v->glue_bits+=vb->glue_bits;
  111247. v->time_bits+=vb->time_bits;
  111248. v->floor_bits+=vb->floor_bits;
  111249. v->res_bits+=vb->res_bits;
  111250. if(v->centerW){
  111251. thisCenter=n1;
  111252. prevCenter=0;
  111253. }else{
  111254. thisCenter=0;
  111255. prevCenter=n1;
  111256. }
  111257. /* v->pcm is now used like a two-stage double buffer. We don't want
  111258. to have to constantly shift *or* adjust memory usage. Don't
  111259. accept a new block until the old is shifted out */
  111260. for(j=0;j<vi->channels;j++){
  111261. /* the overlap/add section */
  111262. if(v->lW){
  111263. if(v->W){
  111264. /* large/large */
  111265. float *w=_vorbis_window_get(b->window[1]-hs);
  111266. float *pcm=v->pcm[j]+prevCenter;
  111267. float *p=vb->pcm[j];
  111268. for(i=0;i<n1;i++)
  111269. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111270. }else{
  111271. /* large/small */
  111272. float *w=_vorbis_window_get(b->window[0]-hs);
  111273. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111274. float *p=vb->pcm[j];
  111275. for(i=0;i<n0;i++)
  111276. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111277. }
  111278. }else{
  111279. if(v->W){
  111280. /* small/large */
  111281. float *w=_vorbis_window_get(b->window[0]-hs);
  111282. float *pcm=v->pcm[j]+prevCenter;
  111283. float *p=vb->pcm[j]+n1/2-n0/2;
  111284. for(i=0;i<n0;i++)
  111285. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111286. for(;i<n1/2+n0/2;i++)
  111287. pcm[i]=p[i];
  111288. }else{
  111289. /* small/small */
  111290. float *w=_vorbis_window_get(b->window[0]-hs);
  111291. float *pcm=v->pcm[j]+prevCenter;
  111292. float *p=vb->pcm[j];
  111293. for(i=0;i<n0;i++)
  111294. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111295. }
  111296. }
  111297. /* the copy section */
  111298. {
  111299. float *pcm=v->pcm[j]+thisCenter;
  111300. float *p=vb->pcm[j]+n;
  111301. for(i=0;i<n;i++)
  111302. pcm[i]=p[i];
  111303. }
  111304. }
  111305. if(v->centerW)
  111306. v->centerW=0;
  111307. else
  111308. v->centerW=n1;
  111309. /* deal with initial packet state; we do this using the explicit
  111310. pcm_returned==-1 flag otherwise we're sensitive to first block
  111311. being short or long */
  111312. if(v->pcm_returned==-1){
  111313. v->pcm_returned=thisCenter;
  111314. v->pcm_current=thisCenter;
  111315. }else{
  111316. v->pcm_returned=prevCenter;
  111317. v->pcm_current=prevCenter+
  111318. ((ci->blocksizes[v->lW]/4+
  111319. ci->blocksizes[v->W]/4)>>hs);
  111320. }
  111321. }
  111322. /* track the frame number... This is for convenience, but also
  111323. making sure our last packet doesn't end with added padding. If
  111324. the last packet is partial, the number of samples we'll have to
  111325. return will be past the vb->granulepos.
  111326. This is not foolproof! It will be confused if we begin
  111327. decoding at the last page after a seek or hole. In that case,
  111328. we don't have a starting point to judge where the last frame
  111329. is. For this reason, vorbisfile will always try to make sure
  111330. it reads the last two marked pages in proper sequence */
  111331. if(b->sample_count==-1){
  111332. b->sample_count=0;
  111333. }else{
  111334. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111335. }
  111336. if(v->granulepos==-1){
  111337. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111338. v->granulepos=vb->granulepos;
  111339. /* is this a short page? */
  111340. if(b->sample_count>v->granulepos){
  111341. /* corner case; if this is both the first and last audio page,
  111342. then spec says the end is cut, not beginning */
  111343. if(vb->eofflag){
  111344. /* trim the end */
  111345. /* no preceeding granulepos; assume we started at zero (we'd
  111346. have to in a short single-page stream) */
  111347. /* granulepos could be -1 due to a seek, but that would result
  111348. in a long count, not short count */
  111349. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111350. }else{
  111351. /* trim the beginning */
  111352. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111353. if(v->pcm_returned>v->pcm_current)
  111354. v->pcm_returned=v->pcm_current;
  111355. }
  111356. }
  111357. }
  111358. }else{
  111359. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111360. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111361. if(v->granulepos>vb->granulepos){
  111362. long extra=v->granulepos-vb->granulepos;
  111363. if(extra)
  111364. if(vb->eofflag){
  111365. /* partial last frame. Strip the extra samples off */
  111366. v->pcm_current-=extra>>hs;
  111367. } /* else {Shouldn't happen *unless* the bitstream is out of
  111368. spec. Either way, believe the bitstream } */
  111369. } /* else {Shouldn't happen *unless* the bitstream is out of
  111370. spec. Either way, believe the bitstream } */
  111371. v->granulepos=vb->granulepos;
  111372. }
  111373. }
  111374. /* Update, cleanup */
  111375. if(vb->eofflag)v->eofflag=1;
  111376. return(0);
  111377. }
  111378. /* pcm==NULL indicates we just want the pending samples, no more */
  111379. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111380. vorbis_info *vi=v->vi;
  111381. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111382. if(pcm){
  111383. int i;
  111384. for(i=0;i<vi->channels;i++)
  111385. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111386. *pcm=v->pcmret;
  111387. }
  111388. return(v->pcm_current-v->pcm_returned);
  111389. }
  111390. return(0);
  111391. }
  111392. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111393. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111394. v->pcm_returned+=n;
  111395. return(0);
  111396. }
  111397. /* intended for use with a specific vorbisfile feature; we want access
  111398. to the [usually synthetic/postextrapolated] buffer and lapping at
  111399. the end of a decode cycle, specifically, a half-short-block worth.
  111400. This funtion works like pcmout above, except it will also expose
  111401. this implicit buffer data not normally decoded. */
  111402. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111403. vorbis_info *vi=v->vi;
  111404. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111405. int hs=ci->halfrate_flag;
  111406. int n=ci->blocksizes[v->W]>>(hs+1);
  111407. int n0=ci->blocksizes[0]>>(hs+1);
  111408. int n1=ci->blocksizes[1]>>(hs+1);
  111409. int i,j;
  111410. if(v->pcm_returned<0)return 0;
  111411. /* our returned data ends at pcm_returned; because the synthesis pcm
  111412. buffer is a two-fragment ring, that means our data block may be
  111413. fragmented by buffering, wrapping or a short block not filling
  111414. out a buffer. To simplify things, we unfragment if it's at all
  111415. possibly needed. Otherwise, we'd need to call lapout more than
  111416. once as well as hold additional dsp state. Opt for
  111417. simplicity. */
  111418. /* centerW was advanced by blockin; it would be the center of the
  111419. *next* block */
  111420. if(v->centerW==n1){
  111421. /* the data buffer wraps; swap the halves */
  111422. /* slow, sure, small */
  111423. for(j=0;j<vi->channels;j++){
  111424. float *p=v->pcm[j];
  111425. for(i=0;i<n1;i++){
  111426. float temp=p[i];
  111427. p[i]=p[i+n1];
  111428. p[i+n1]=temp;
  111429. }
  111430. }
  111431. v->pcm_current-=n1;
  111432. v->pcm_returned-=n1;
  111433. v->centerW=0;
  111434. }
  111435. /* solidify buffer into contiguous space */
  111436. if((v->lW^v->W)==1){
  111437. /* long/short or short/long */
  111438. for(j=0;j<vi->channels;j++){
  111439. float *s=v->pcm[j];
  111440. float *d=v->pcm[j]+(n1-n0)/2;
  111441. for(i=(n1+n0)/2-1;i>=0;--i)
  111442. d[i]=s[i];
  111443. }
  111444. v->pcm_returned+=(n1-n0)/2;
  111445. v->pcm_current+=(n1-n0)/2;
  111446. }else{
  111447. if(v->lW==0){
  111448. /* short/short */
  111449. for(j=0;j<vi->channels;j++){
  111450. float *s=v->pcm[j];
  111451. float *d=v->pcm[j]+n1-n0;
  111452. for(i=n0-1;i>=0;--i)
  111453. d[i]=s[i];
  111454. }
  111455. v->pcm_returned+=n1-n0;
  111456. v->pcm_current+=n1-n0;
  111457. }
  111458. }
  111459. if(pcm){
  111460. int i;
  111461. for(i=0;i<vi->channels;i++)
  111462. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111463. *pcm=v->pcmret;
  111464. }
  111465. return(n1+n-v->pcm_returned);
  111466. }
  111467. float *vorbis_window(vorbis_dsp_state *v,int W){
  111468. vorbis_info *vi=v->vi;
  111469. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111470. int hs=ci->halfrate_flag;
  111471. private_state *b=(private_state*)v->backend_state;
  111472. if(b->window[W]-1<0)return NULL;
  111473. return _vorbis_window_get(b->window[W]-hs);
  111474. }
  111475. #endif
  111476. /*** End of inlined file: block.c ***/
  111477. /*** Start of inlined file: codebook.c ***/
  111478. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111479. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111480. // tasks..
  111481. #if JUCE_MSVC
  111482. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111483. #endif
  111484. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111485. #if JUCE_USE_OGGVORBIS
  111486. #include <stdlib.h>
  111487. #include <string.h>
  111488. #include <math.h>
  111489. /* packs the given codebook into the bitstream **************************/
  111490. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111491. long i,j;
  111492. int ordered=0;
  111493. /* first the basic parameters */
  111494. oggpack_write(opb,0x564342,24);
  111495. oggpack_write(opb,c->dim,16);
  111496. oggpack_write(opb,c->entries,24);
  111497. /* pack the codewords. There are two packings; length ordered and
  111498. length random. Decide between the two now. */
  111499. for(i=1;i<c->entries;i++)
  111500. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111501. if(i==c->entries)ordered=1;
  111502. if(ordered){
  111503. /* length ordered. We only need to say how many codewords of
  111504. each length. The actual codewords are generated
  111505. deterministically */
  111506. long count=0;
  111507. oggpack_write(opb,1,1); /* ordered */
  111508. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111509. for(i=1;i<c->entries;i++){
  111510. long thisx=c->lengthlist[i];
  111511. long last=c->lengthlist[i-1];
  111512. if(thisx>last){
  111513. for(j=last;j<thisx;j++){
  111514. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111515. count=i;
  111516. }
  111517. }
  111518. }
  111519. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111520. }else{
  111521. /* length random. Again, we don't code the codeword itself, just
  111522. the length. This time, though, we have to encode each length */
  111523. oggpack_write(opb,0,1); /* unordered */
  111524. /* algortihmic mapping has use for 'unused entries', which we tag
  111525. here. The algorithmic mapping happens as usual, but the unused
  111526. entry has no codeword. */
  111527. for(i=0;i<c->entries;i++)
  111528. if(c->lengthlist[i]==0)break;
  111529. if(i==c->entries){
  111530. oggpack_write(opb,0,1); /* no unused entries */
  111531. for(i=0;i<c->entries;i++)
  111532. oggpack_write(opb,c->lengthlist[i]-1,5);
  111533. }else{
  111534. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111535. for(i=0;i<c->entries;i++){
  111536. if(c->lengthlist[i]==0){
  111537. oggpack_write(opb,0,1);
  111538. }else{
  111539. oggpack_write(opb,1,1);
  111540. oggpack_write(opb,c->lengthlist[i]-1,5);
  111541. }
  111542. }
  111543. }
  111544. }
  111545. /* is the entry number the desired return value, or do we have a
  111546. mapping? If we have a mapping, what type? */
  111547. oggpack_write(opb,c->maptype,4);
  111548. switch(c->maptype){
  111549. case 0:
  111550. /* no mapping */
  111551. break;
  111552. case 1:case 2:
  111553. /* implicitly populated value mapping */
  111554. /* explicitly populated value mapping */
  111555. if(!c->quantlist){
  111556. /* no quantlist? error */
  111557. return(-1);
  111558. }
  111559. /* values that define the dequantization */
  111560. oggpack_write(opb,c->q_min,32);
  111561. oggpack_write(opb,c->q_delta,32);
  111562. oggpack_write(opb,c->q_quant-1,4);
  111563. oggpack_write(opb,c->q_sequencep,1);
  111564. {
  111565. int quantvals;
  111566. switch(c->maptype){
  111567. case 1:
  111568. /* a single column of (c->entries/c->dim) quantized values for
  111569. building a full value list algorithmically (square lattice) */
  111570. quantvals=_book_maptype1_quantvals(c);
  111571. break;
  111572. case 2:
  111573. /* every value (c->entries*c->dim total) specified explicitly */
  111574. quantvals=c->entries*c->dim;
  111575. break;
  111576. default: /* NOT_REACHABLE */
  111577. quantvals=-1;
  111578. }
  111579. /* quantized values */
  111580. for(i=0;i<quantvals;i++)
  111581. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111582. }
  111583. break;
  111584. default:
  111585. /* error case; we don't have any other map types now */
  111586. return(-1);
  111587. }
  111588. return(0);
  111589. }
  111590. /* unpacks a codebook from the packet buffer into the codebook struct,
  111591. readies the codebook auxiliary structures for decode *************/
  111592. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111593. long i,j;
  111594. memset(s,0,sizeof(*s));
  111595. s->allocedp=1;
  111596. /* make sure alignment is correct */
  111597. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111598. /* first the basic parameters */
  111599. s->dim=oggpack_read(opb,16);
  111600. s->entries=oggpack_read(opb,24);
  111601. if(s->entries==-1)goto _eofout;
  111602. /* codeword ordering.... length ordered or unordered? */
  111603. switch((int)oggpack_read(opb,1)){
  111604. case 0:
  111605. /* unordered */
  111606. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111607. /* allocated but unused entries? */
  111608. if(oggpack_read(opb,1)){
  111609. /* yes, unused entries */
  111610. for(i=0;i<s->entries;i++){
  111611. if(oggpack_read(opb,1)){
  111612. long num=oggpack_read(opb,5);
  111613. if(num==-1)goto _eofout;
  111614. s->lengthlist[i]=num+1;
  111615. }else
  111616. s->lengthlist[i]=0;
  111617. }
  111618. }else{
  111619. /* all entries used; no tagging */
  111620. for(i=0;i<s->entries;i++){
  111621. long num=oggpack_read(opb,5);
  111622. if(num==-1)goto _eofout;
  111623. s->lengthlist[i]=num+1;
  111624. }
  111625. }
  111626. break;
  111627. case 1:
  111628. /* ordered */
  111629. {
  111630. long length=oggpack_read(opb,5)+1;
  111631. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111632. for(i=0;i<s->entries;){
  111633. long num=oggpack_read(opb,_ilog(s->entries-i));
  111634. if(num==-1)goto _eofout;
  111635. for(j=0;j<num && i<s->entries;j++,i++)
  111636. s->lengthlist[i]=length;
  111637. length++;
  111638. }
  111639. }
  111640. break;
  111641. default:
  111642. /* EOF */
  111643. return(-1);
  111644. }
  111645. /* Do we have a mapping to unpack? */
  111646. switch((s->maptype=oggpack_read(opb,4))){
  111647. case 0:
  111648. /* no mapping */
  111649. break;
  111650. case 1: case 2:
  111651. /* implicitly populated value mapping */
  111652. /* explicitly populated value mapping */
  111653. s->q_min=oggpack_read(opb,32);
  111654. s->q_delta=oggpack_read(opb,32);
  111655. s->q_quant=oggpack_read(opb,4)+1;
  111656. s->q_sequencep=oggpack_read(opb,1);
  111657. {
  111658. int quantvals=0;
  111659. switch(s->maptype){
  111660. case 1:
  111661. quantvals=_book_maptype1_quantvals(s);
  111662. break;
  111663. case 2:
  111664. quantvals=s->entries*s->dim;
  111665. break;
  111666. }
  111667. /* quantized values */
  111668. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  111669. for(i=0;i<quantvals;i++)
  111670. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  111671. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  111672. }
  111673. break;
  111674. default:
  111675. goto _errout;
  111676. }
  111677. /* all set */
  111678. return(0);
  111679. _errout:
  111680. _eofout:
  111681. vorbis_staticbook_clear(s);
  111682. return(-1);
  111683. }
  111684. /* returns the number of bits ************************************************/
  111685. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  111686. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  111687. return(book->c->lengthlist[a]);
  111688. }
  111689. /* One the encode side, our vector writers are each designed for a
  111690. specific purpose, and the encoder is not flexible without modification:
  111691. The LSP vector coder uses a single stage nearest-match with no
  111692. interleave, so no step and no error return. This is specced by floor0
  111693. and doesn't change.
  111694. Residue0 encoding interleaves, uses multiple stages, and each stage
  111695. peels of a specific amount of resolution from a lattice (thus we want
  111696. to match by threshold, not nearest match). Residue doesn't *have* to
  111697. be encoded that way, but to change it, one will need to add more
  111698. infrastructure on the encode side (decode side is specced and simpler) */
  111699. /* floor0 LSP (single stage, non interleaved, nearest match) */
  111700. /* returns entry number and *modifies a* to the quantization value *****/
  111701. int vorbis_book_errorv(codebook *book,float *a){
  111702. int dim=book->dim,k;
  111703. int best=_best(book,a,1);
  111704. for(k=0;k<dim;k++)
  111705. a[k]=(book->valuelist+best*dim)[k];
  111706. return(best);
  111707. }
  111708. /* returns the number of bits and *modifies a* to the quantization value *****/
  111709. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  111710. int k,dim=book->dim;
  111711. for(k=0;k<dim;k++)
  111712. a[k]=(book->valuelist+best*dim)[k];
  111713. return(vorbis_book_encode(book,best,b));
  111714. }
  111715. /* the 'eliminate the decode tree' optimization actually requires the
  111716. codewords to be MSb first, not LSb. This is an annoying inelegancy
  111717. (and one of the first places where carefully thought out design
  111718. turned out to be wrong; Vorbis II and future Ogg codecs should go
  111719. to an MSb bitpacker), but not actually the huge hit it appears to
  111720. be. The first-stage decode table catches most words so that
  111721. bitreverse is not in the main execution path. */
  111722. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  111723. int read=book->dec_maxlength;
  111724. long lo,hi;
  111725. long lok = oggpack_look(b,book->dec_firsttablen);
  111726. if (lok >= 0) {
  111727. long entry = book->dec_firsttable[lok];
  111728. if(entry&0x80000000UL){
  111729. lo=(entry>>15)&0x7fff;
  111730. hi=book->used_entries-(entry&0x7fff);
  111731. }else{
  111732. oggpack_adv(b, book->dec_codelengths[entry-1]);
  111733. return(entry-1);
  111734. }
  111735. }else{
  111736. lo=0;
  111737. hi=book->used_entries;
  111738. }
  111739. lok = oggpack_look(b, read);
  111740. while(lok<0 && read>1)
  111741. lok = oggpack_look(b, --read);
  111742. if(lok<0)return -1;
  111743. /* bisect search for the codeword in the ordered list */
  111744. {
  111745. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  111746. while(hi-lo>1){
  111747. long p=(hi-lo)>>1;
  111748. long test=book->codelist[lo+p]>testword;
  111749. lo+=p&(test-1);
  111750. hi-=p&(-test);
  111751. }
  111752. if(book->dec_codelengths[lo]<=read){
  111753. oggpack_adv(b, book->dec_codelengths[lo]);
  111754. return(lo);
  111755. }
  111756. }
  111757. oggpack_adv(b, read);
  111758. return(-1);
  111759. }
  111760. /* Decode side is specced and easier, because we don't need to find
  111761. matches using different criteria; we simply read and map. There are
  111762. two things we need to do 'depending':
  111763. We may need to support interleave. We don't really, but it's
  111764. convenient to do it here rather than rebuild the vector later.
  111765. Cascades may be additive or multiplicitive; this is not inherent in
  111766. the codebook, but set in the code using the codebook. Like
  111767. interleaving, it's easiest to do it here.
  111768. addmul==0 -> declarative (set the value)
  111769. addmul==1 -> additive
  111770. addmul==2 -> multiplicitive */
  111771. /* returns the [original, not compacted] entry number or -1 on eof *********/
  111772. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  111773. long packed_entry=decode_packed_entry_number(book,b);
  111774. if(packed_entry>=0)
  111775. return(book->dec_index[packed_entry]);
  111776. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  111777. return(packed_entry);
  111778. }
  111779. /* returns 0 on OK or -1 on eof *************************************/
  111780. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111781. int step=n/book->dim;
  111782. long *entry = (long*)alloca(sizeof(*entry)*step);
  111783. float **t = (float**)alloca(sizeof(*t)*step);
  111784. int i,j,o;
  111785. for (i = 0; i < step; i++) {
  111786. entry[i]=decode_packed_entry_number(book,b);
  111787. if(entry[i]==-1)return(-1);
  111788. t[i] = book->valuelist+entry[i]*book->dim;
  111789. }
  111790. for(i=0,o=0;i<book->dim;i++,o+=step)
  111791. for (j=0;j<step;j++)
  111792. a[o+j]+=t[j][i];
  111793. return(0);
  111794. }
  111795. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  111796. int i,j,entry;
  111797. float *t;
  111798. if(book->dim>8){
  111799. for(i=0;i<n;){
  111800. entry = decode_packed_entry_number(book,b);
  111801. if(entry==-1)return(-1);
  111802. t = book->valuelist+entry*book->dim;
  111803. for (j=0;j<book->dim;)
  111804. a[i++]+=t[j++];
  111805. }
  111806. }else{
  111807. for(i=0;i<n;){
  111808. entry = decode_packed_entry_number(book,b);
  111809. if(entry==-1)return(-1);
  111810. t = book->valuelist+entry*book->dim;
  111811. j=0;
  111812. switch((int)book->dim){
  111813. case 8:
  111814. a[i++]+=t[j++];
  111815. case 7:
  111816. a[i++]+=t[j++];
  111817. case 6:
  111818. a[i++]+=t[j++];
  111819. case 5:
  111820. a[i++]+=t[j++];
  111821. case 4:
  111822. a[i++]+=t[j++];
  111823. case 3:
  111824. a[i++]+=t[j++];
  111825. case 2:
  111826. a[i++]+=t[j++];
  111827. case 1:
  111828. a[i++]+=t[j++];
  111829. case 0:
  111830. break;
  111831. }
  111832. }
  111833. }
  111834. return(0);
  111835. }
  111836. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  111837. int i,j,entry;
  111838. float *t;
  111839. for(i=0;i<n;){
  111840. entry = decode_packed_entry_number(book,b);
  111841. if(entry==-1)return(-1);
  111842. t = book->valuelist+entry*book->dim;
  111843. for (j=0;j<book->dim;)
  111844. a[i++]=t[j++];
  111845. }
  111846. return(0);
  111847. }
  111848. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  111849. oggpack_buffer *b,int n){
  111850. long i,j,entry;
  111851. int chptr=0;
  111852. for(i=offset/ch;i<(offset+n)/ch;){
  111853. entry = decode_packed_entry_number(book,b);
  111854. if(entry==-1)return(-1);
  111855. {
  111856. const float *t = book->valuelist+entry*book->dim;
  111857. for (j=0;j<book->dim;j++){
  111858. a[chptr++][i]+=t[j];
  111859. if(chptr==ch){
  111860. chptr=0;
  111861. i++;
  111862. }
  111863. }
  111864. }
  111865. }
  111866. return(0);
  111867. }
  111868. #ifdef _V_SELFTEST
  111869. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  111870. number of vectors through (keeping track of the quantized values),
  111871. and decode using the unpacked book. quantized version of in should
  111872. exactly equal out */
  111873. #include <stdio.h>
  111874. #include "vorbis/book/lsp20_0.vqh"
  111875. #include "vorbis/book/res0a_13.vqh"
  111876. #define TESTSIZE 40
  111877. float test1[TESTSIZE]={
  111878. 0.105939f,
  111879. 0.215373f,
  111880. 0.429117f,
  111881. 0.587974f,
  111882. 0.181173f,
  111883. 0.296583f,
  111884. 0.515707f,
  111885. 0.715261f,
  111886. 0.162327f,
  111887. 0.263834f,
  111888. 0.342876f,
  111889. 0.406025f,
  111890. 0.103571f,
  111891. 0.223561f,
  111892. 0.368513f,
  111893. 0.540313f,
  111894. 0.136672f,
  111895. 0.395882f,
  111896. 0.587183f,
  111897. 0.652476f,
  111898. 0.114338f,
  111899. 0.417300f,
  111900. 0.525486f,
  111901. 0.698679f,
  111902. 0.147492f,
  111903. 0.324481f,
  111904. 0.643089f,
  111905. 0.757582f,
  111906. 0.139556f,
  111907. 0.215795f,
  111908. 0.324559f,
  111909. 0.399387f,
  111910. 0.120236f,
  111911. 0.267420f,
  111912. 0.446940f,
  111913. 0.608760f,
  111914. 0.115587f,
  111915. 0.287234f,
  111916. 0.571081f,
  111917. 0.708603f,
  111918. };
  111919. float test3[TESTSIZE]={
  111920. 0,1,-2,3,4,-5,6,7,8,9,
  111921. 8,-2,7,-1,4,6,8,3,1,-9,
  111922. 10,11,12,13,14,15,26,17,18,19,
  111923. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  111924. static_codebook *testlist[]={&_vq_book_lsp20_0,
  111925. &_vq_book_res0a_13,NULL};
  111926. float *testvec[]={test1,test3};
  111927. int main(){
  111928. oggpack_buffer write;
  111929. oggpack_buffer read;
  111930. long ptr=0,i;
  111931. oggpack_writeinit(&write);
  111932. fprintf(stderr,"Testing codebook abstraction...:\n");
  111933. while(testlist[ptr]){
  111934. codebook c;
  111935. static_codebook s;
  111936. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  111937. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  111938. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  111939. memset(iv,0,sizeof(*iv)*TESTSIZE);
  111940. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  111941. /* pack the codebook, write the testvector */
  111942. oggpack_reset(&write);
  111943. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  111944. we can write */
  111945. vorbis_staticbook_pack(testlist[ptr],&write);
  111946. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  111947. for(i=0;i<TESTSIZE;i+=c.dim){
  111948. int best=_best(&c,qv+i,1);
  111949. vorbis_book_encodev(&c,best,qv+i,&write);
  111950. }
  111951. vorbis_book_clear(&c);
  111952. fprintf(stderr,"OK.\n");
  111953. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  111954. /* transfer the write data to a read buffer and unpack/read */
  111955. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  111956. if(vorbis_staticbook_unpack(&read,&s)){
  111957. fprintf(stderr,"Error unpacking codebook.\n");
  111958. exit(1);
  111959. }
  111960. if(vorbis_book_init_decode(&c,&s)){
  111961. fprintf(stderr,"Error initializing codebook.\n");
  111962. exit(1);
  111963. }
  111964. for(i=0;i<TESTSIZE;i+=c.dim)
  111965. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  111966. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  111967. exit(1);
  111968. }
  111969. for(i=0;i<TESTSIZE;i++)
  111970. if(fabs(qv[i]-iv[i])>.000001){
  111971. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  111972. iv[i],qv[i],i);
  111973. exit(1);
  111974. }
  111975. fprintf(stderr,"OK\n");
  111976. ptr++;
  111977. }
  111978. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  111979. exit(0);
  111980. }
  111981. #endif
  111982. #endif
  111983. /*** End of inlined file: codebook.c ***/
  111984. /*** Start of inlined file: envelope.c ***/
  111985. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111986. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111987. // tasks..
  111988. #if JUCE_MSVC
  111989. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111990. #endif
  111991. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111992. #if JUCE_USE_OGGVORBIS
  111993. #include <stdlib.h>
  111994. #include <string.h>
  111995. #include <stdio.h>
  111996. #include <math.h>
  111997. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  111998. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111999. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112000. int ch=vi->channels;
  112001. int i,j;
  112002. int n=e->winlength=128;
  112003. e->searchstep=64; /* not random */
  112004. e->minenergy=gi->preecho_minenergy;
  112005. e->ch=ch;
  112006. e->storage=128;
  112007. e->cursor=ci->blocksizes[1]/2;
  112008. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112009. mdct_init(&e->mdct,n);
  112010. for(i=0;i<n;i++){
  112011. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112012. e->mdct_win[i]*=e->mdct_win[i];
  112013. }
  112014. /* magic follows */
  112015. e->band[0].begin=2; e->band[0].end=4;
  112016. e->band[1].begin=4; e->band[1].end=5;
  112017. e->band[2].begin=6; e->band[2].end=6;
  112018. e->band[3].begin=9; e->band[3].end=8;
  112019. e->band[4].begin=13; e->band[4].end=8;
  112020. e->band[5].begin=17; e->band[5].end=8;
  112021. e->band[6].begin=22; e->band[6].end=8;
  112022. for(j=0;j<VE_BANDS;j++){
  112023. n=e->band[j].end;
  112024. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112025. for(i=0;i<n;i++){
  112026. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112027. e->band[j].total+=e->band[j].window[i];
  112028. }
  112029. e->band[j].total=1./e->band[j].total;
  112030. }
  112031. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112032. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112033. }
  112034. void _ve_envelope_clear(envelope_lookup *e){
  112035. int i;
  112036. mdct_clear(&e->mdct);
  112037. for(i=0;i<VE_BANDS;i++)
  112038. _ogg_free(e->band[i].window);
  112039. _ogg_free(e->mdct_win);
  112040. _ogg_free(e->filter);
  112041. _ogg_free(e->mark);
  112042. memset(e,0,sizeof(*e));
  112043. }
  112044. /* fairly straight threshhold-by-band based until we find something
  112045. that works better and isn't patented. */
  112046. static int _ve_amp(envelope_lookup *ve,
  112047. vorbis_info_psy_global *gi,
  112048. float *data,
  112049. envelope_band *bands,
  112050. envelope_filter_state *filters,
  112051. long pos){
  112052. long n=ve->winlength;
  112053. int ret=0;
  112054. long i,j;
  112055. float decay;
  112056. /* we want to have a 'minimum bar' for energy, else we're just
  112057. basing blocks on quantization noise that outweighs the signal
  112058. itself (for low power signals) */
  112059. float minV=ve->minenergy;
  112060. float *vec=(float*) alloca(n*sizeof(*vec));
  112061. /* stretch is used to gradually lengthen the number of windows
  112062. considered prevoius-to-potential-trigger */
  112063. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112064. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112065. if(penalty<0.f)penalty=0.f;
  112066. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112067. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112068. totalshift+pos*ve->searchstep);*/
  112069. /* window and transform */
  112070. for(i=0;i<n;i++)
  112071. vec[i]=data[i]*ve->mdct_win[i];
  112072. mdct_forward(&ve->mdct,vec,vec);
  112073. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112074. /* near-DC spreading function; this has nothing to do with
  112075. psychoacoustics, just sidelobe leakage and window size */
  112076. {
  112077. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112078. int ptr=filters->nearptr;
  112079. /* the accumulation is regularly refreshed from scratch to avoid
  112080. floating point creep */
  112081. if(ptr==0){
  112082. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112083. filters->nearDC_partialacc=temp;
  112084. }else{
  112085. decay=filters->nearDC_acc+=temp;
  112086. filters->nearDC_partialacc+=temp;
  112087. }
  112088. filters->nearDC_acc-=filters->nearDC[ptr];
  112089. filters->nearDC[ptr]=temp;
  112090. decay*=(1./(VE_NEARDC+1));
  112091. filters->nearptr++;
  112092. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112093. decay=todB(&decay)*.5-15.f;
  112094. }
  112095. /* perform spreading and limiting, also smooth the spectrum. yes,
  112096. the MDCT results in all real coefficients, but it still *behaves*
  112097. like real/imaginary pairs */
  112098. for(i=0;i<n/2;i+=2){
  112099. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112100. val=todB(&val)*.5f;
  112101. if(val<decay)val=decay;
  112102. if(val<minV)val=minV;
  112103. vec[i>>1]=val;
  112104. decay-=8.;
  112105. }
  112106. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112107. /* perform preecho/postecho triggering by band */
  112108. for(j=0;j<VE_BANDS;j++){
  112109. float acc=0.;
  112110. float valmax,valmin;
  112111. /* accumulate amplitude */
  112112. for(i=0;i<bands[j].end;i++)
  112113. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112114. acc*=bands[j].total;
  112115. /* convert amplitude to delta */
  112116. {
  112117. int p,thisx=filters[j].ampptr;
  112118. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112119. p=thisx;
  112120. p--;
  112121. if(p<0)p+=VE_AMP;
  112122. postmax=max(acc,filters[j].ampbuf[p]);
  112123. postmin=min(acc,filters[j].ampbuf[p]);
  112124. for(i=0;i<stretch;i++){
  112125. p--;
  112126. if(p<0)p+=VE_AMP;
  112127. premax=max(premax,filters[j].ampbuf[p]);
  112128. premin=min(premin,filters[j].ampbuf[p]);
  112129. }
  112130. valmin=postmin-premin;
  112131. valmax=postmax-premax;
  112132. /*filters[j].markers[pos]=valmax;*/
  112133. filters[j].ampbuf[thisx]=acc;
  112134. filters[j].ampptr++;
  112135. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112136. }
  112137. /* look at min/max, decide trigger */
  112138. if(valmax>gi->preecho_thresh[j]+penalty){
  112139. ret|=1;
  112140. ret|=4;
  112141. }
  112142. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112143. }
  112144. return(ret);
  112145. }
  112146. #if 0
  112147. static int seq=0;
  112148. static ogg_int64_t totalshift=-1024;
  112149. #endif
  112150. long _ve_envelope_search(vorbis_dsp_state *v){
  112151. vorbis_info *vi=v->vi;
  112152. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112153. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112154. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112155. long i,j;
  112156. int first=ve->current/ve->searchstep;
  112157. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112158. if(first<0)first=0;
  112159. /* make sure we have enough storage to match the PCM */
  112160. if(last+VE_WIN+VE_POST>ve->storage){
  112161. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112162. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112163. }
  112164. for(j=first;j<last;j++){
  112165. int ret=0;
  112166. ve->stretch++;
  112167. if(ve->stretch>VE_MAXSTRETCH*2)
  112168. ve->stretch=VE_MAXSTRETCH*2;
  112169. for(i=0;i<ve->ch;i++){
  112170. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112171. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112172. }
  112173. ve->mark[j+VE_POST]=0;
  112174. if(ret&1){
  112175. ve->mark[j]=1;
  112176. ve->mark[j+1]=1;
  112177. }
  112178. if(ret&2){
  112179. ve->mark[j]=1;
  112180. if(j>0)ve->mark[j-1]=1;
  112181. }
  112182. if(ret&4)ve->stretch=-1;
  112183. }
  112184. ve->current=last*ve->searchstep;
  112185. {
  112186. long centerW=v->centerW;
  112187. long testW=
  112188. centerW+
  112189. ci->blocksizes[v->W]/4+
  112190. ci->blocksizes[1]/2+
  112191. ci->blocksizes[0]/4;
  112192. j=ve->cursor;
  112193. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112194. working back one window */
  112195. if(j>=testW)return(1);
  112196. ve->cursor=j;
  112197. if(ve->mark[j/ve->searchstep]){
  112198. if(j>centerW){
  112199. #if 0
  112200. if(j>ve->curmark){
  112201. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112202. int l,m;
  112203. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112204. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112205. seq,
  112206. (totalshift+ve->cursor)/44100.,
  112207. (totalshift+j)/44100.);
  112208. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112209. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112210. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112211. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112212. for(m=0;m<VE_BANDS;m++){
  112213. char buf[80];
  112214. sprintf(buf,"delL%d",m);
  112215. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112216. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112217. }
  112218. for(m=0;m<VE_BANDS;m++){
  112219. char buf[80];
  112220. sprintf(buf,"delR%d",m);
  112221. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112222. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112223. }
  112224. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112225. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112226. seq++;
  112227. }
  112228. #endif
  112229. ve->curmark=j;
  112230. if(j>=testW)return(1);
  112231. return(0);
  112232. }
  112233. }
  112234. j+=ve->searchstep;
  112235. }
  112236. }
  112237. return(-1);
  112238. }
  112239. int _ve_envelope_mark(vorbis_dsp_state *v){
  112240. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112241. vorbis_info *vi=v->vi;
  112242. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112243. long centerW=v->centerW;
  112244. long beginW=centerW-ci->blocksizes[v->W]/4;
  112245. long endW=centerW+ci->blocksizes[v->W]/4;
  112246. if(v->W){
  112247. beginW-=ci->blocksizes[v->lW]/4;
  112248. endW+=ci->blocksizes[v->nW]/4;
  112249. }else{
  112250. beginW-=ci->blocksizes[0]/4;
  112251. endW+=ci->blocksizes[0]/4;
  112252. }
  112253. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112254. {
  112255. long first=beginW/ve->searchstep;
  112256. long last=endW/ve->searchstep;
  112257. long i;
  112258. for(i=first;i<last;i++)
  112259. if(ve->mark[i])return(1);
  112260. }
  112261. return(0);
  112262. }
  112263. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112264. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112265. ahead of ve->current */
  112266. int smallshift=shift/e->searchstep;
  112267. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112268. #if 0
  112269. for(i=0;i<VE_BANDS*e->ch;i++)
  112270. memmove(e->filter[i].markers,
  112271. e->filter[i].markers+smallshift,
  112272. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112273. totalshift+=shift;
  112274. #endif
  112275. e->current-=shift;
  112276. if(e->curmark>=0)
  112277. e->curmark-=shift;
  112278. e->cursor-=shift;
  112279. }
  112280. #endif
  112281. /*** End of inlined file: envelope.c ***/
  112282. /*** Start of inlined file: floor0.c ***/
  112283. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112284. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112285. // tasks..
  112286. #if JUCE_MSVC
  112287. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112288. #endif
  112289. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112290. #if JUCE_USE_OGGVORBIS
  112291. #include <stdlib.h>
  112292. #include <string.h>
  112293. #include <math.h>
  112294. /*** Start of inlined file: lsp.h ***/
  112295. #ifndef _V_LSP_H_
  112296. #define _V_LSP_H_
  112297. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112298. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112299. float *lsp,int m,
  112300. float amp,float ampoffset);
  112301. #endif
  112302. /*** End of inlined file: lsp.h ***/
  112303. #include <stdio.h>
  112304. typedef struct {
  112305. int ln;
  112306. int m;
  112307. int **linearmap;
  112308. int n[2];
  112309. vorbis_info_floor0 *vi;
  112310. long bits;
  112311. long frames;
  112312. } vorbis_look_floor0;
  112313. /***********************************************/
  112314. static void floor0_free_info(vorbis_info_floor *i){
  112315. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112316. if(info){
  112317. memset(info,0,sizeof(*info));
  112318. _ogg_free(info);
  112319. }
  112320. }
  112321. static void floor0_free_look(vorbis_look_floor *i){
  112322. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112323. if(look){
  112324. if(look->linearmap){
  112325. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112326. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112327. _ogg_free(look->linearmap);
  112328. }
  112329. memset(look,0,sizeof(*look));
  112330. _ogg_free(look);
  112331. }
  112332. }
  112333. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112334. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112335. int j;
  112336. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112337. info->order=oggpack_read(opb,8);
  112338. info->rate=oggpack_read(opb,16);
  112339. info->barkmap=oggpack_read(opb,16);
  112340. info->ampbits=oggpack_read(opb,6);
  112341. info->ampdB=oggpack_read(opb,8);
  112342. info->numbooks=oggpack_read(opb,4)+1;
  112343. if(info->order<1)goto err_out;
  112344. if(info->rate<1)goto err_out;
  112345. if(info->barkmap<1)goto err_out;
  112346. if(info->numbooks<1)goto err_out;
  112347. for(j=0;j<info->numbooks;j++){
  112348. info->books[j]=oggpack_read(opb,8);
  112349. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112350. }
  112351. return(info);
  112352. err_out:
  112353. floor0_free_info(info);
  112354. return(NULL);
  112355. }
  112356. /* initialize Bark scale and normalization lookups. We could do this
  112357. with static tables, but Vorbis allows a number of possible
  112358. combinations, so it's best to do it computationally.
  112359. The below is authoritative in terms of defining scale mapping.
  112360. Note that the scale depends on the sampling rate as well as the
  112361. linear block and mapping sizes */
  112362. static void floor0_map_lazy_init(vorbis_block *vb,
  112363. vorbis_info_floor *infoX,
  112364. vorbis_look_floor0 *look){
  112365. if(!look->linearmap[vb->W]){
  112366. vorbis_dsp_state *vd=vb->vd;
  112367. vorbis_info *vi=vd->vi;
  112368. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112369. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112370. int W=vb->W;
  112371. int n=ci->blocksizes[W]/2,j;
  112372. /* we choose a scaling constant so that:
  112373. floor(bark(rate/2-1)*C)=mapped-1
  112374. floor(bark(rate/2)*C)=mapped */
  112375. float scale=look->ln/toBARK(info->rate/2.f);
  112376. /* the mapping from a linear scale to a smaller bark scale is
  112377. straightforward. We do *not* make sure that the linear mapping
  112378. does not skip bark-scale bins; the decoder simply skips them and
  112379. the encoder may do what it wishes in filling them. They're
  112380. necessary in some mapping combinations to keep the scale spacing
  112381. accurate */
  112382. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112383. for(j=0;j<n;j++){
  112384. int val=floor( toBARK((info->rate/2.f)/n*j)
  112385. *scale); /* bark numbers represent band edges */
  112386. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112387. look->linearmap[W][j]=val;
  112388. }
  112389. look->linearmap[W][j]=-1;
  112390. look->n[W]=n;
  112391. }
  112392. }
  112393. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112394. vorbis_info_floor *i){
  112395. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112396. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112397. look->m=info->order;
  112398. look->ln=info->barkmap;
  112399. look->vi=info;
  112400. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112401. return look;
  112402. }
  112403. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112404. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112405. vorbis_info_floor0 *info=look->vi;
  112406. int j,k;
  112407. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112408. if(ampraw>0){ /* also handles the -1 out of data case */
  112409. long maxval=(1<<info->ampbits)-1;
  112410. float amp=(float)ampraw/maxval*info->ampdB;
  112411. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112412. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112413. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112414. codebook *b=ci->fullbooks+info->books[booknum];
  112415. float last=0.f;
  112416. /* the additional b->dim is a guard against any possible stack
  112417. smash; b->dim is provably more than we can overflow the
  112418. vector */
  112419. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112420. for(j=0;j<look->m;j+=b->dim)
  112421. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112422. for(j=0;j<look->m;){
  112423. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112424. last=lsp[j-1];
  112425. }
  112426. lsp[look->m]=amp;
  112427. return(lsp);
  112428. }
  112429. }
  112430. eop:
  112431. return(NULL);
  112432. }
  112433. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112434. void *memo,float *out){
  112435. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112436. vorbis_info_floor0 *info=look->vi;
  112437. floor0_map_lazy_init(vb,info,look);
  112438. if(memo){
  112439. float *lsp=(float *)memo;
  112440. float amp=lsp[look->m];
  112441. /* take the coefficients back to a spectral envelope curve */
  112442. vorbis_lsp_to_curve(out,
  112443. look->linearmap[vb->W],
  112444. look->n[vb->W],
  112445. look->ln,
  112446. lsp,look->m,amp,(float)info->ampdB);
  112447. return(1);
  112448. }
  112449. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112450. return(0);
  112451. }
  112452. /* export hooks */
  112453. vorbis_func_floor floor0_exportbundle={
  112454. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112455. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112456. };
  112457. #endif
  112458. /*** End of inlined file: floor0.c ***/
  112459. /*** Start of inlined file: floor1.c ***/
  112460. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112461. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112462. // tasks..
  112463. #if JUCE_MSVC
  112464. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112465. #endif
  112466. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112467. #if JUCE_USE_OGGVORBIS
  112468. #include <stdlib.h>
  112469. #include <string.h>
  112470. #include <math.h>
  112471. #include <stdio.h>
  112472. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112473. typedef struct {
  112474. int sorted_index[VIF_POSIT+2];
  112475. int forward_index[VIF_POSIT+2];
  112476. int reverse_index[VIF_POSIT+2];
  112477. int hineighbor[VIF_POSIT];
  112478. int loneighbor[VIF_POSIT];
  112479. int posts;
  112480. int n;
  112481. int quant_q;
  112482. vorbis_info_floor1 *vi;
  112483. long phrasebits;
  112484. long postbits;
  112485. long frames;
  112486. } vorbis_look_floor1;
  112487. typedef struct lsfit_acc{
  112488. long x0;
  112489. long x1;
  112490. long xa;
  112491. long ya;
  112492. long x2a;
  112493. long y2a;
  112494. long xya;
  112495. long an;
  112496. } lsfit_acc;
  112497. /***********************************************/
  112498. static void floor1_free_info(vorbis_info_floor *i){
  112499. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112500. if(info){
  112501. memset(info,0,sizeof(*info));
  112502. _ogg_free(info);
  112503. }
  112504. }
  112505. static void floor1_free_look(vorbis_look_floor *i){
  112506. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112507. if(look){
  112508. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112509. (float)look->phrasebits/look->frames,
  112510. (float)look->postbits/look->frames,
  112511. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112512. memset(look,0,sizeof(*look));
  112513. _ogg_free(look);
  112514. }
  112515. }
  112516. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112517. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112518. int j,k;
  112519. int count=0;
  112520. int rangebits;
  112521. int maxposit=info->postlist[1];
  112522. int maxclass=-1;
  112523. /* save out partitions */
  112524. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112525. for(j=0;j<info->partitions;j++){
  112526. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112527. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112528. }
  112529. /* save out partition classes */
  112530. for(j=0;j<maxclass+1;j++){
  112531. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112532. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112533. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112534. for(k=0;k<(1<<info->class_subs[j]);k++)
  112535. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112536. }
  112537. /* save out the post list */
  112538. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112539. oggpack_write(opb,ilog2(maxposit),4);
  112540. rangebits=ilog2(maxposit);
  112541. for(j=0,k=0;j<info->partitions;j++){
  112542. count+=info->class_dim[info->partitionclass[j]];
  112543. for(;k<count;k++)
  112544. oggpack_write(opb,info->postlist[k+2],rangebits);
  112545. }
  112546. }
  112547. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112548. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112549. int j,k,count=0,maxclass=-1,rangebits;
  112550. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112551. /* read partitions */
  112552. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112553. for(j=0;j<info->partitions;j++){
  112554. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112555. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112556. }
  112557. /* read partition classes */
  112558. for(j=0;j<maxclass+1;j++){
  112559. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112560. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112561. if(info->class_subs[j]<0)
  112562. goto err_out;
  112563. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112564. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112565. goto err_out;
  112566. for(k=0;k<(1<<info->class_subs[j]);k++){
  112567. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112568. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112569. goto err_out;
  112570. }
  112571. }
  112572. /* read the post list */
  112573. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112574. rangebits=oggpack_read(opb,4);
  112575. for(j=0,k=0;j<info->partitions;j++){
  112576. count+=info->class_dim[info->partitionclass[j]];
  112577. for(;k<count;k++){
  112578. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112579. if(t<0 || t>=(1<<rangebits))
  112580. goto err_out;
  112581. }
  112582. }
  112583. info->postlist[0]=0;
  112584. info->postlist[1]=1<<rangebits;
  112585. return(info);
  112586. err_out:
  112587. floor1_free_info(info);
  112588. return(NULL);
  112589. }
  112590. static int JUCE_CDECL icomp(const void *a,const void *b){
  112591. return(**(int **)a-**(int **)b);
  112592. }
  112593. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112594. vorbis_info_floor *in){
  112595. int *sortpointer[VIF_POSIT+2];
  112596. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112597. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112598. int i,j,n=0;
  112599. look->vi=info;
  112600. look->n=info->postlist[1];
  112601. /* we drop each position value in-between already decoded values,
  112602. and use linear interpolation to predict each new value past the
  112603. edges. The positions are read in the order of the position
  112604. list... we precompute the bounding positions in the lookup. Of
  112605. course, the neighbors can change (if a position is declined), but
  112606. this is an initial mapping */
  112607. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112608. n+=2;
  112609. look->posts=n;
  112610. /* also store a sorted position index */
  112611. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112612. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112613. /* points from sort order back to range number */
  112614. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112615. /* points from range order to sorted position */
  112616. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112617. /* we actually need the post values too */
  112618. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112619. /* quantize values to multiplier spec */
  112620. switch(info->mult){
  112621. case 1: /* 1024 -> 256 */
  112622. look->quant_q=256;
  112623. break;
  112624. case 2: /* 1024 -> 128 */
  112625. look->quant_q=128;
  112626. break;
  112627. case 3: /* 1024 -> 86 */
  112628. look->quant_q=86;
  112629. break;
  112630. case 4: /* 1024 -> 64 */
  112631. look->quant_q=64;
  112632. break;
  112633. }
  112634. /* discover our neighbors for decode where we don't use fit flags
  112635. (that would push the neighbors outward) */
  112636. for(i=0;i<n-2;i++){
  112637. int lo=0;
  112638. int hi=1;
  112639. int lx=0;
  112640. int hx=look->n;
  112641. int currentx=info->postlist[i+2];
  112642. for(j=0;j<i+2;j++){
  112643. int x=info->postlist[j];
  112644. if(x>lx && x<currentx){
  112645. lo=j;
  112646. lx=x;
  112647. }
  112648. if(x<hx && x>currentx){
  112649. hi=j;
  112650. hx=x;
  112651. }
  112652. }
  112653. look->loneighbor[i]=lo;
  112654. look->hineighbor[i]=hi;
  112655. }
  112656. return(look);
  112657. }
  112658. static int render_point(int x0,int x1,int y0,int y1,int x){
  112659. y0&=0x7fff; /* mask off flag */
  112660. y1&=0x7fff;
  112661. {
  112662. int dy=y1-y0;
  112663. int adx=x1-x0;
  112664. int ady=abs(dy);
  112665. int err=ady*(x-x0);
  112666. int off=err/adx;
  112667. if(dy<0)return(y0-off);
  112668. return(y0+off);
  112669. }
  112670. }
  112671. static int vorbis_dBquant(const float *x){
  112672. int i= *x*7.3142857f+1023.5f;
  112673. if(i>1023)return(1023);
  112674. if(i<0)return(0);
  112675. return i;
  112676. }
  112677. static float FLOOR1_fromdB_LOOKUP[256]={
  112678. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  112679. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  112680. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  112681. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  112682. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  112683. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  112684. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  112685. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  112686. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  112687. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  112688. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  112689. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  112690. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  112691. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  112692. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  112693. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  112694. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  112695. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  112696. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  112697. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  112698. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  112699. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  112700. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  112701. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  112702. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  112703. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  112704. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  112705. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  112706. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  112707. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  112708. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  112709. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  112710. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  112711. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  112712. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  112713. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  112714. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  112715. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  112716. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  112717. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  112718. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  112719. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  112720. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  112721. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  112722. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  112723. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  112724. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  112725. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  112726. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  112727. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  112728. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  112729. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  112730. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  112731. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  112732. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  112733. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  112734. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  112735. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  112736. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  112737. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  112738. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  112739. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  112740. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  112741. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  112742. };
  112743. static void render_line(int x0,int x1,int y0,int y1,float *d){
  112744. int dy=y1-y0;
  112745. int adx=x1-x0;
  112746. int ady=abs(dy);
  112747. int base=dy/adx;
  112748. int sy=(dy<0?base-1:base+1);
  112749. int x=x0;
  112750. int y=y0;
  112751. int err=0;
  112752. ady-=abs(base*adx);
  112753. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112754. while(++x<x1){
  112755. err=err+ady;
  112756. if(err>=adx){
  112757. err-=adx;
  112758. y+=sy;
  112759. }else{
  112760. y+=base;
  112761. }
  112762. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  112763. }
  112764. }
  112765. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  112766. int dy=y1-y0;
  112767. int adx=x1-x0;
  112768. int ady=abs(dy);
  112769. int base=dy/adx;
  112770. int sy=(dy<0?base-1:base+1);
  112771. int x=x0;
  112772. int y=y0;
  112773. int err=0;
  112774. ady-=abs(base*adx);
  112775. d[x]=y;
  112776. while(++x<x1){
  112777. err=err+ady;
  112778. if(err>=adx){
  112779. err-=adx;
  112780. y+=sy;
  112781. }else{
  112782. y+=base;
  112783. }
  112784. d[x]=y;
  112785. }
  112786. }
  112787. /* the floor has already been filtered to only include relevant sections */
  112788. static int accumulate_fit(const float *flr,const float *mdct,
  112789. int x0, int x1,lsfit_acc *a,
  112790. int n,vorbis_info_floor1 *info){
  112791. long i;
  112792. 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;
  112793. memset(a,0,sizeof(*a));
  112794. a->x0=x0;
  112795. a->x1=x1;
  112796. if(x1>=n)x1=n-1;
  112797. for(i=x0;i<=x1;i++){
  112798. int quantized=vorbis_dBquant(flr+i);
  112799. if(quantized){
  112800. if(mdct[i]+info->twofitatten>=flr[i]){
  112801. xa += i;
  112802. ya += quantized;
  112803. x2a += i*i;
  112804. y2a += quantized*quantized;
  112805. xya += i*quantized;
  112806. na++;
  112807. }else{
  112808. xb += i;
  112809. yb += quantized;
  112810. x2b += i*i;
  112811. y2b += quantized*quantized;
  112812. xyb += i*quantized;
  112813. nb++;
  112814. }
  112815. }
  112816. }
  112817. xb+=xa;
  112818. yb+=ya;
  112819. x2b+=x2a;
  112820. y2b+=y2a;
  112821. xyb+=xya;
  112822. nb+=na;
  112823. /* weight toward the actually used frequencies if we meet the threshhold */
  112824. {
  112825. int weight=nb*info->twofitweight/(na+1);
  112826. a->xa=xa*weight+xb;
  112827. a->ya=ya*weight+yb;
  112828. a->x2a=x2a*weight+x2b;
  112829. a->y2a=y2a*weight+y2b;
  112830. a->xya=xya*weight+xyb;
  112831. a->an=na*weight+nb;
  112832. }
  112833. return(na);
  112834. }
  112835. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  112836. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  112837. long x0=a[0].x0;
  112838. long x1=a[fits-1].x1;
  112839. for(i=0;i<fits;i++){
  112840. x+=a[i].xa;
  112841. y+=a[i].ya;
  112842. x2+=a[i].x2a;
  112843. y2+=a[i].y2a;
  112844. xy+=a[i].xya;
  112845. an+=a[i].an;
  112846. }
  112847. if(*y0>=0){
  112848. x+= x0;
  112849. y+= *y0;
  112850. x2+= x0 * x0;
  112851. y2+= *y0 * *y0;
  112852. xy+= *y0 * x0;
  112853. an++;
  112854. }
  112855. if(*y1>=0){
  112856. x+= x1;
  112857. y+= *y1;
  112858. x2+= x1 * x1;
  112859. y2+= *y1 * *y1;
  112860. xy+= *y1 * x1;
  112861. an++;
  112862. }
  112863. if(an){
  112864. /* need 64 bit multiplies, which C doesn't give portably as int */
  112865. double fx=x;
  112866. double fy=y;
  112867. double fx2=x2;
  112868. double fxy=xy;
  112869. double denom=1./(an*fx2-fx*fx);
  112870. double a=(fy*fx2-fxy*fx)*denom;
  112871. double b=(an*fxy-fx*fy)*denom;
  112872. *y0=rint(a+b*x0);
  112873. *y1=rint(a+b*x1);
  112874. /* limit to our range! */
  112875. if(*y0>1023)*y0=1023;
  112876. if(*y1>1023)*y1=1023;
  112877. if(*y0<0)*y0=0;
  112878. if(*y1<0)*y1=0;
  112879. }else{
  112880. *y0=0;
  112881. *y1=0;
  112882. }
  112883. }
  112884. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  112885. long y=0;
  112886. int i;
  112887. for(i=0;i<fits && y==0;i++)
  112888. y+=a[i].ya;
  112889. *y0=*y1=y;
  112890. }*/
  112891. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  112892. const float *mdct,
  112893. vorbis_info_floor1 *info){
  112894. int dy=y1-y0;
  112895. int adx=x1-x0;
  112896. int ady=abs(dy);
  112897. int base=dy/adx;
  112898. int sy=(dy<0?base-1:base+1);
  112899. int x=x0;
  112900. int y=y0;
  112901. int err=0;
  112902. int val=vorbis_dBquant(mask+x);
  112903. int mse=0;
  112904. int n=0;
  112905. ady-=abs(base*adx);
  112906. mse=(y-val);
  112907. mse*=mse;
  112908. n++;
  112909. if(mdct[x]+info->twofitatten>=mask[x]){
  112910. if(y+info->maxover<val)return(1);
  112911. if(y-info->maxunder>val)return(1);
  112912. }
  112913. while(++x<x1){
  112914. err=err+ady;
  112915. if(err>=adx){
  112916. err-=adx;
  112917. y+=sy;
  112918. }else{
  112919. y+=base;
  112920. }
  112921. val=vorbis_dBquant(mask+x);
  112922. mse+=((y-val)*(y-val));
  112923. n++;
  112924. if(mdct[x]+info->twofitatten>=mask[x]){
  112925. if(val){
  112926. if(y+info->maxover<val)return(1);
  112927. if(y-info->maxunder>val)return(1);
  112928. }
  112929. }
  112930. }
  112931. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  112932. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  112933. if(mse/n>info->maxerr)return(1);
  112934. return(0);
  112935. }
  112936. static int post_Y(int *A,int *B,int pos){
  112937. if(A[pos]<0)
  112938. return B[pos];
  112939. if(B[pos]<0)
  112940. return A[pos];
  112941. return (A[pos]+B[pos])>>1;
  112942. }
  112943. int *floor1_fit(vorbis_block *vb,void *look_,
  112944. const float *logmdct, /* in */
  112945. const float *logmask){
  112946. long i,j;
  112947. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  112948. vorbis_info_floor1 *info=look->vi;
  112949. long n=look->n;
  112950. long posts=look->posts;
  112951. long nonzero=0;
  112952. lsfit_acc fits[VIF_POSIT+1];
  112953. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  112954. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  112955. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  112956. int hineighbor[VIF_POSIT+2];
  112957. int *output=NULL;
  112958. int memo[VIF_POSIT+2];
  112959. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  112960. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  112961. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  112962. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  112963. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  112964. /* quantize the relevant floor points and collect them into line fit
  112965. structures (one per minimal division) at the same time */
  112966. if(posts==0){
  112967. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  112968. }else{
  112969. for(i=0;i<posts-1;i++)
  112970. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  112971. look->sorted_index[i+1],fits+i,
  112972. n,info);
  112973. }
  112974. if(nonzero){
  112975. /* start by fitting the implicit base case.... */
  112976. int y0=-200;
  112977. int y1=-200;
  112978. fit_line(fits,posts-1,&y0,&y1);
  112979. fit_valueA[0]=y0;
  112980. fit_valueB[0]=y0;
  112981. fit_valueB[1]=y1;
  112982. fit_valueA[1]=y1;
  112983. /* Non degenerate case */
  112984. /* start progressive splitting. This is a greedy, non-optimal
  112985. algorithm, but simple and close enough to the best
  112986. answer. */
  112987. for(i=2;i<posts;i++){
  112988. int sortpos=look->reverse_index[i];
  112989. int ln=loneighbor[sortpos];
  112990. int hn=hineighbor[sortpos];
  112991. /* eliminate repeat searches of a particular range with a memo */
  112992. if(memo[ln]!=hn){
  112993. /* haven't performed this error search yet */
  112994. int lsortpos=look->reverse_index[ln];
  112995. int hsortpos=look->reverse_index[hn];
  112996. memo[ln]=hn;
  112997. {
  112998. /* A note: we want to bound/minimize *local*, not global, error */
  112999. int lx=info->postlist[ln];
  113000. int hx=info->postlist[hn];
  113001. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113002. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113003. if(ly==-1 || hy==-1){
  113004. exit(1);
  113005. }
  113006. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113007. /* outside error bounds/begin search area. Split it. */
  113008. int ly0=-200;
  113009. int ly1=-200;
  113010. int hy0=-200;
  113011. int hy1=-200;
  113012. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113013. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113014. /* store new edge values */
  113015. fit_valueB[ln]=ly0;
  113016. if(ln==0)fit_valueA[ln]=ly0;
  113017. fit_valueA[i]=ly1;
  113018. fit_valueB[i]=hy0;
  113019. fit_valueA[hn]=hy1;
  113020. if(hn==1)fit_valueB[hn]=hy1;
  113021. if(ly1>=0 || hy0>=0){
  113022. /* store new neighbor values */
  113023. for(j=sortpos-1;j>=0;j--)
  113024. if(hineighbor[j]==hn)
  113025. hineighbor[j]=i;
  113026. else
  113027. break;
  113028. for(j=sortpos+1;j<posts;j++)
  113029. if(loneighbor[j]==ln)
  113030. loneighbor[j]=i;
  113031. else
  113032. break;
  113033. }
  113034. }else{
  113035. fit_valueA[i]=-200;
  113036. fit_valueB[i]=-200;
  113037. }
  113038. }
  113039. }
  113040. }
  113041. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113042. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113043. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113044. /* fill in posts marked as not using a fit; we will zero
  113045. back out to 'unused' when encoding them so long as curve
  113046. interpolation doesn't force them into use */
  113047. for(i=2;i<posts;i++){
  113048. int ln=look->loneighbor[i-2];
  113049. int hn=look->hineighbor[i-2];
  113050. int x0=info->postlist[ln];
  113051. int x1=info->postlist[hn];
  113052. int y0=output[ln];
  113053. int y1=output[hn];
  113054. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113055. int vx=post_Y(fit_valueA,fit_valueB,i);
  113056. if(vx>=0 && predicted!=vx){
  113057. output[i]=vx;
  113058. }else{
  113059. output[i]= predicted|0x8000;
  113060. }
  113061. }
  113062. }
  113063. return(output);
  113064. }
  113065. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113066. int *A,int *B,
  113067. int del){
  113068. long i;
  113069. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113070. long posts=look->posts;
  113071. int *output=NULL;
  113072. if(A && B){
  113073. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113074. for(i=0;i<posts;i++){
  113075. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113076. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113077. }
  113078. }
  113079. return(output);
  113080. }
  113081. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113082. void*look_,
  113083. int *post,int *ilogmask){
  113084. long i,j;
  113085. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113086. vorbis_info_floor1 *info=look->vi;
  113087. long posts=look->posts;
  113088. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113089. int out[VIF_POSIT+2];
  113090. static_codebook **sbooks=ci->book_param;
  113091. codebook *books=ci->fullbooks;
  113092. static long seq=0;
  113093. /* quantize values to multiplier spec */
  113094. if(post){
  113095. for(i=0;i<posts;i++){
  113096. int val=post[i]&0x7fff;
  113097. switch(info->mult){
  113098. case 1: /* 1024 -> 256 */
  113099. val>>=2;
  113100. break;
  113101. case 2: /* 1024 -> 128 */
  113102. val>>=3;
  113103. break;
  113104. case 3: /* 1024 -> 86 */
  113105. val/=12;
  113106. break;
  113107. case 4: /* 1024 -> 64 */
  113108. val>>=4;
  113109. break;
  113110. }
  113111. post[i]=val | (post[i]&0x8000);
  113112. }
  113113. out[0]=post[0];
  113114. out[1]=post[1];
  113115. /* find prediction values for each post and subtract them */
  113116. for(i=2;i<posts;i++){
  113117. int ln=look->loneighbor[i-2];
  113118. int hn=look->hineighbor[i-2];
  113119. int x0=info->postlist[ln];
  113120. int x1=info->postlist[hn];
  113121. int y0=post[ln];
  113122. int y1=post[hn];
  113123. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113124. if((post[i]&0x8000) || (predicted==post[i])){
  113125. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113126. in interpolation */
  113127. out[i]=0;
  113128. }else{
  113129. int headroom=(look->quant_q-predicted<predicted?
  113130. look->quant_q-predicted:predicted);
  113131. int val=post[i]-predicted;
  113132. /* at this point the 'deviation' value is in the range +/- max
  113133. range, but the real, unique range can always be mapped to
  113134. only [0-maxrange). So we want to wrap the deviation into
  113135. this limited range, but do it in the way that least screws
  113136. an essentially gaussian probability distribution. */
  113137. if(val<0)
  113138. if(val<-headroom)
  113139. val=headroom-val-1;
  113140. else
  113141. val=-1-(val<<1);
  113142. else
  113143. if(val>=headroom)
  113144. val= val+headroom;
  113145. else
  113146. val<<=1;
  113147. out[i]=val;
  113148. post[ln]&=0x7fff;
  113149. post[hn]&=0x7fff;
  113150. }
  113151. }
  113152. /* we have everything we need. pack it out */
  113153. /* mark nontrivial floor */
  113154. oggpack_write(opb,1,1);
  113155. /* beginning/end post */
  113156. look->frames++;
  113157. look->postbits+=ilog(look->quant_q-1)*2;
  113158. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113159. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113160. /* partition by partition */
  113161. for(i=0,j=2;i<info->partitions;i++){
  113162. int classx=info->partitionclass[i];
  113163. int cdim=info->class_dim[classx];
  113164. int csubbits=info->class_subs[classx];
  113165. int csub=1<<csubbits;
  113166. int bookas[8]={0,0,0,0,0,0,0,0};
  113167. int cval=0;
  113168. int cshift=0;
  113169. int k,l;
  113170. /* generate the partition's first stage cascade value */
  113171. if(csubbits){
  113172. int maxval[8];
  113173. for(k=0;k<csub;k++){
  113174. int booknum=info->class_subbook[classx][k];
  113175. if(booknum<0){
  113176. maxval[k]=1;
  113177. }else{
  113178. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113179. }
  113180. }
  113181. for(k=0;k<cdim;k++){
  113182. for(l=0;l<csub;l++){
  113183. int val=out[j+k];
  113184. if(val<maxval[l]){
  113185. bookas[k]=l;
  113186. break;
  113187. }
  113188. }
  113189. cval|= bookas[k]<<cshift;
  113190. cshift+=csubbits;
  113191. }
  113192. /* write it */
  113193. look->phrasebits+=
  113194. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113195. #ifdef TRAIN_FLOOR1
  113196. {
  113197. FILE *of;
  113198. char buffer[80];
  113199. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113200. vb->pcmend/2,posts-2,class);
  113201. of=fopen(buffer,"a");
  113202. fprintf(of,"%d\n",cval);
  113203. fclose(of);
  113204. }
  113205. #endif
  113206. }
  113207. /* write post values */
  113208. for(k=0;k<cdim;k++){
  113209. int book=info->class_subbook[classx][bookas[k]];
  113210. if(book>=0){
  113211. /* hack to allow training with 'bad' books */
  113212. if(out[j+k]<(books+book)->entries)
  113213. look->postbits+=vorbis_book_encode(books+book,
  113214. out[j+k],opb);
  113215. /*else
  113216. fprintf(stderr,"+!");*/
  113217. #ifdef TRAIN_FLOOR1
  113218. {
  113219. FILE *of;
  113220. char buffer[80];
  113221. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113222. vb->pcmend/2,posts-2,class,bookas[k]);
  113223. of=fopen(buffer,"a");
  113224. fprintf(of,"%d\n",out[j+k]);
  113225. fclose(of);
  113226. }
  113227. #endif
  113228. }
  113229. }
  113230. j+=cdim;
  113231. }
  113232. {
  113233. /* generate quantized floor equivalent to what we'd unpack in decode */
  113234. /* render the lines */
  113235. int hx=0;
  113236. int lx=0;
  113237. int ly=post[0]*info->mult;
  113238. for(j=1;j<look->posts;j++){
  113239. int current=look->forward_index[j];
  113240. int hy=post[current]&0x7fff;
  113241. if(hy==post[current]){
  113242. hy*=info->mult;
  113243. hx=info->postlist[current];
  113244. render_line0(lx,hx,ly,hy,ilogmask);
  113245. lx=hx;
  113246. ly=hy;
  113247. }
  113248. }
  113249. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113250. seq++;
  113251. return(1);
  113252. }
  113253. }else{
  113254. oggpack_write(opb,0,1);
  113255. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113256. seq++;
  113257. return(0);
  113258. }
  113259. }
  113260. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113261. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113262. vorbis_info_floor1 *info=look->vi;
  113263. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113264. int i,j,k;
  113265. codebook *books=ci->fullbooks;
  113266. /* unpack wrapped/predicted values from stream */
  113267. if(oggpack_read(&vb->opb,1)==1){
  113268. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113269. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113270. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113271. /* partition by partition */
  113272. for(i=0,j=2;i<info->partitions;i++){
  113273. int classx=info->partitionclass[i];
  113274. int cdim=info->class_dim[classx];
  113275. int csubbits=info->class_subs[classx];
  113276. int csub=1<<csubbits;
  113277. int cval=0;
  113278. /* decode the partition's first stage cascade value */
  113279. if(csubbits){
  113280. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113281. if(cval==-1)goto eop;
  113282. }
  113283. for(k=0;k<cdim;k++){
  113284. int book=info->class_subbook[classx][cval&(csub-1)];
  113285. cval>>=csubbits;
  113286. if(book>=0){
  113287. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113288. goto eop;
  113289. }else{
  113290. fit_value[j+k]=0;
  113291. }
  113292. }
  113293. j+=cdim;
  113294. }
  113295. /* unwrap positive values and reconsitute via linear interpolation */
  113296. for(i=2;i<look->posts;i++){
  113297. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113298. info->postlist[look->hineighbor[i-2]],
  113299. fit_value[look->loneighbor[i-2]],
  113300. fit_value[look->hineighbor[i-2]],
  113301. info->postlist[i]);
  113302. int hiroom=look->quant_q-predicted;
  113303. int loroom=predicted;
  113304. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113305. int val=fit_value[i];
  113306. if(val){
  113307. if(val>=room){
  113308. if(hiroom>loroom){
  113309. val = val-loroom;
  113310. }else{
  113311. val = -1-(val-hiroom);
  113312. }
  113313. }else{
  113314. if(val&1){
  113315. val= -((val+1)>>1);
  113316. }else{
  113317. val>>=1;
  113318. }
  113319. }
  113320. fit_value[i]=val+predicted;
  113321. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113322. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113323. }else{
  113324. fit_value[i]=predicted|0x8000;
  113325. }
  113326. }
  113327. return(fit_value);
  113328. }
  113329. eop:
  113330. return(NULL);
  113331. }
  113332. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113333. float *out){
  113334. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113335. vorbis_info_floor1 *info=look->vi;
  113336. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113337. int n=ci->blocksizes[vb->W]/2;
  113338. int j;
  113339. if(memo){
  113340. /* render the lines */
  113341. int *fit_value=(int *)memo;
  113342. int hx=0;
  113343. int lx=0;
  113344. int ly=fit_value[0]*info->mult;
  113345. for(j=1;j<look->posts;j++){
  113346. int current=look->forward_index[j];
  113347. int hy=fit_value[current]&0x7fff;
  113348. if(hy==fit_value[current]){
  113349. hy*=info->mult;
  113350. hx=info->postlist[current];
  113351. render_line(lx,hx,ly,hy,out);
  113352. lx=hx;
  113353. ly=hy;
  113354. }
  113355. }
  113356. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113357. return(1);
  113358. }
  113359. memset(out,0,sizeof(*out)*n);
  113360. return(0);
  113361. }
  113362. /* export hooks */
  113363. vorbis_func_floor floor1_exportbundle={
  113364. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113365. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113366. };
  113367. #endif
  113368. /*** End of inlined file: floor1.c ***/
  113369. /*** Start of inlined file: info.c ***/
  113370. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113371. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113372. // tasks..
  113373. #if JUCE_MSVC
  113374. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113375. #endif
  113376. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113377. #if JUCE_USE_OGGVORBIS
  113378. /* general handling of the header and the vorbis_info structure (and
  113379. substructures) */
  113380. #include <stdlib.h>
  113381. #include <string.h>
  113382. #include <ctype.h>
  113383. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113384. while(bytes--){
  113385. oggpack_write(o,*s++,8);
  113386. }
  113387. }
  113388. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113389. while(bytes--){
  113390. *buf++=oggpack_read(o,8);
  113391. }
  113392. }
  113393. void vorbis_comment_init(vorbis_comment *vc){
  113394. memset(vc,0,sizeof(*vc));
  113395. }
  113396. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113397. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113398. (vc->comments+2)*sizeof(*vc->user_comments));
  113399. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113400. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113401. vc->comment_lengths[vc->comments]=strlen(comment);
  113402. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113403. strcpy(vc->user_comments[vc->comments], comment);
  113404. vc->comments++;
  113405. vc->user_comments[vc->comments]=NULL;
  113406. }
  113407. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113408. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113409. strcpy(comment, tag);
  113410. strcat(comment, "=");
  113411. strcat(comment, contents);
  113412. vorbis_comment_add(vc, comment);
  113413. }
  113414. /* This is more or less the same as strncasecmp - but that doesn't exist
  113415. * everywhere, and this is a fairly trivial function, so we include it */
  113416. static int tagcompare(const char *s1, const char *s2, int n){
  113417. int c=0;
  113418. while(c < n){
  113419. if(toupper(s1[c]) != toupper(s2[c]))
  113420. return !0;
  113421. c++;
  113422. }
  113423. return 0;
  113424. }
  113425. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113426. long i;
  113427. int found = 0;
  113428. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113429. char *fulltag = (char*)alloca(taglen+ 1);
  113430. strcpy(fulltag, tag);
  113431. strcat(fulltag, "=");
  113432. for(i=0;i<vc->comments;i++){
  113433. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113434. if(count == found)
  113435. /* We return a pointer to the data, not a copy */
  113436. return vc->user_comments[i] + taglen;
  113437. else
  113438. found++;
  113439. }
  113440. }
  113441. return NULL; /* didn't find anything */
  113442. }
  113443. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113444. int i,count=0;
  113445. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113446. char *fulltag = (char*)alloca(taglen+1);
  113447. strcpy(fulltag,tag);
  113448. strcat(fulltag, "=");
  113449. for(i=0;i<vc->comments;i++){
  113450. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113451. count++;
  113452. }
  113453. return count;
  113454. }
  113455. void vorbis_comment_clear(vorbis_comment *vc){
  113456. if(vc){
  113457. long i;
  113458. for(i=0;i<vc->comments;i++)
  113459. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113460. if(vc->user_comments)_ogg_free(vc->user_comments);
  113461. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113462. if(vc->vendor)_ogg_free(vc->vendor);
  113463. }
  113464. memset(vc,0,sizeof(*vc));
  113465. }
  113466. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113467. They may be equal, but short will never ge greater than long */
  113468. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113469. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113470. return ci ? ci->blocksizes[zo] : -1;
  113471. }
  113472. /* used by synthesis, which has a full, alloced vi */
  113473. void vorbis_info_init(vorbis_info *vi){
  113474. memset(vi,0,sizeof(*vi));
  113475. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113476. }
  113477. void vorbis_info_clear(vorbis_info *vi){
  113478. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113479. int i;
  113480. if(ci){
  113481. for(i=0;i<ci->modes;i++)
  113482. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113483. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113484. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113485. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113486. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113487. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113488. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113489. for(i=0;i<ci->books;i++){
  113490. if(ci->book_param[i]){
  113491. /* knows if the book was not alloced */
  113492. vorbis_staticbook_destroy(ci->book_param[i]);
  113493. }
  113494. if(ci->fullbooks)
  113495. vorbis_book_clear(ci->fullbooks+i);
  113496. }
  113497. if(ci->fullbooks)
  113498. _ogg_free(ci->fullbooks);
  113499. for(i=0;i<ci->psys;i++)
  113500. _vi_psy_free(ci->psy_param[i]);
  113501. _ogg_free(ci);
  113502. }
  113503. memset(vi,0,sizeof(*vi));
  113504. }
  113505. /* Header packing/unpacking ********************************************/
  113506. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113507. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113508. if(!ci)return(OV_EFAULT);
  113509. vi->version=oggpack_read(opb,32);
  113510. if(vi->version!=0)return(OV_EVERSION);
  113511. vi->channels=oggpack_read(opb,8);
  113512. vi->rate=oggpack_read(opb,32);
  113513. vi->bitrate_upper=oggpack_read(opb,32);
  113514. vi->bitrate_nominal=oggpack_read(opb,32);
  113515. vi->bitrate_lower=oggpack_read(opb,32);
  113516. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113517. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113518. if(vi->rate<1)goto err_out;
  113519. if(vi->channels<1)goto err_out;
  113520. if(ci->blocksizes[0]<8)goto err_out;
  113521. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113522. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113523. return(0);
  113524. err_out:
  113525. vorbis_info_clear(vi);
  113526. return(OV_EBADHEADER);
  113527. }
  113528. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113529. int i;
  113530. int vendorlen=oggpack_read(opb,32);
  113531. if(vendorlen<0)goto err_out;
  113532. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113533. _v_readstring(opb,vc->vendor,vendorlen);
  113534. vc->comments=oggpack_read(opb,32);
  113535. if(vc->comments<0)goto err_out;
  113536. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113537. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113538. for(i=0;i<vc->comments;i++){
  113539. int len=oggpack_read(opb,32);
  113540. if(len<0)goto err_out;
  113541. vc->comment_lengths[i]=len;
  113542. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113543. _v_readstring(opb,vc->user_comments[i],len);
  113544. }
  113545. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113546. return(0);
  113547. err_out:
  113548. vorbis_comment_clear(vc);
  113549. return(OV_EBADHEADER);
  113550. }
  113551. /* all of the real encoding details are here. The modes, books,
  113552. everything */
  113553. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113554. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113555. int i;
  113556. if(!ci)return(OV_EFAULT);
  113557. /* codebooks */
  113558. ci->books=oggpack_read(opb,8)+1;
  113559. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113560. for(i=0;i<ci->books;i++){
  113561. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113562. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113563. }
  113564. /* time backend settings; hooks are unused */
  113565. {
  113566. int times=oggpack_read(opb,6)+1;
  113567. for(i=0;i<times;i++){
  113568. int test=oggpack_read(opb,16);
  113569. if(test<0 || test>=VI_TIMEB)goto err_out;
  113570. }
  113571. }
  113572. /* floor backend settings */
  113573. ci->floors=oggpack_read(opb,6)+1;
  113574. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113575. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113576. for(i=0;i<ci->floors;i++){
  113577. ci->floor_type[i]=oggpack_read(opb,16);
  113578. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113579. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113580. if(!ci->floor_param[i])goto err_out;
  113581. }
  113582. /* residue backend settings */
  113583. ci->residues=oggpack_read(opb,6)+1;
  113584. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113585. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113586. for(i=0;i<ci->residues;i++){
  113587. ci->residue_type[i]=oggpack_read(opb,16);
  113588. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113589. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113590. if(!ci->residue_param[i])goto err_out;
  113591. }
  113592. /* map backend settings */
  113593. ci->maps=oggpack_read(opb,6)+1;
  113594. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113595. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113596. for(i=0;i<ci->maps;i++){
  113597. ci->map_type[i]=oggpack_read(opb,16);
  113598. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113599. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113600. if(!ci->map_param[i])goto err_out;
  113601. }
  113602. /* mode settings */
  113603. ci->modes=oggpack_read(opb,6)+1;
  113604. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113605. for(i=0;i<ci->modes;i++){
  113606. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113607. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113608. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113609. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113610. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113611. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113612. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113613. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113614. }
  113615. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113616. return(0);
  113617. err_out:
  113618. vorbis_info_clear(vi);
  113619. return(OV_EBADHEADER);
  113620. }
  113621. /* The Vorbis header is in three packets; the initial small packet in
  113622. the first page that identifies basic parameters, a second packet
  113623. with bitstream comments and a third packet that holds the
  113624. codebook. */
  113625. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113626. oggpack_buffer opb;
  113627. if(op){
  113628. oggpack_readinit(&opb,op->packet,op->bytes);
  113629. /* Which of the three types of header is this? */
  113630. /* Also verify header-ness, vorbis */
  113631. {
  113632. char buffer[6];
  113633. int packtype=oggpack_read(&opb,8);
  113634. memset(buffer,0,6);
  113635. _v_readstring(&opb,buffer,6);
  113636. if(memcmp(buffer,"vorbis",6)){
  113637. /* not a vorbis header */
  113638. return(OV_ENOTVORBIS);
  113639. }
  113640. switch(packtype){
  113641. case 0x01: /* least significant *bit* is read first */
  113642. if(!op->b_o_s){
  113643. /* Not the initial packet */
  113644. return(OV_EBADHEADER);
  113645. }
  113646. if(vi->rate!=0){
  113647. /* previously initialized info header */
  113648. return(OV_EBADHEADER);
  113649. }
  113650. return(_vorbis_unpack_info(vi,&opb));
  113651. case 0x03: /* least significant *bit* is read first */
  113652. if(vi->rate==0){
  113653. /* um... we didn't get the initial header */
  113654. return(OV_EBADHEADER);
  113655. }
  113656. return(_vorbis_unpack_comment(vc,&opb));
  113657. case 0x05: /* least significant *bit* is read first */
  113658. if(vi->rate==0 || vc->vendor==NULL){
  113659. /* um... we didn;t get the initial header or comments yet */
  113660. return(OV_EBADHEADER);
  113661. }
  113662. return(_vorbis_unpack_books(vi,&opb));
  113663. default:
  113664. /* Not a valid vorbis header type */
  113665. return(OV_EBADHEADER);
  113666. break;
  113667. }
  113668. }
  113669. }
  113670. return(OV_EBADHEADER);
  113671. }
  113672. /* pack side **********************************************************/
  113673. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  113674. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113675. if(!ci)return(OV_EFAULT);
  113676. /* preamble */
  113677. oggpack_write(opb,0x01,8);
  113678. _v_writestring(opb,"vorbis", 6);
  113679. /* basic information about the stream */
  113680. oggpack_write(opb,0x00,32);
  113681. oggpack_write(opb,vi->channels,8);
  113682. oggpack_write(opb,vi->rate,32);
  113683. oggpack_write(opb,vi->bitrate_upper,32);
  113684. oggpack_write(opb,vi->bitrate_nominal,32);
  113685. oggpack_write(opb,vi->bitrate_lower,32);
  113686. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  113687. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  113688. oggpack_write(opb,1,1);
  113689. return(0);
  113690. }
  113691. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  113692. char temp[]="Xiph.Org libVorbis I 20050304";
  113693. int bytes = strlen(temp);
  113694. /* preamble */
  113695. oggpack_write(opb,0x03,8);
  113696. _v_writestring(opb,"vorbis", 6);
  113697. /* vendor */
  113698. oggpack_write(opb,bytes,32);
  113699. _v_writestring(opb,temp, bytes);
  113700. /* comments */
  113701. oggpack_write(opb,vc->comments,32);
  113702. if(vc->comments){
  113703. int i;
  113704. for(i=0;i<vc->comments;i++){
  113705. if(vc->user_comments[i]){
  113706. oggpack_write(opb,vc->comment_lengths[i],32);
  113707. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  113708. }else{
  113709. oggpack_write(opb,0,32);
  113710. }
  113711. }
  113712. }
  113713. oggpack_write(opb,1,1);
  113714. return(0);
  113715. }
  113716. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  113717. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113718. int i;
  113719. if(!ci)return(OV_EFAULT);
  113720. oggpack_write(opb,0x05,8);
  113721. _v_writestring(opb,"vorbis", 6);
  113722. /* books */
  113723. oggpack_write(opb,ci->books-1,8);
  113724. for(i=0;i<ci->books;i++)
  113725. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  113726. /* times; hook placeholders */
  113727. oggpack_write(opb,0,6);
  113728. oggpack_write(opb,0,16);
  113729. /* floors */
  113730. oggpack_write(opb,ci->floors-1,6);
  113731. for(i=0;i<ci->floors;i++){
  113732. oggpack_write(opb,ci->floor_type[i],16);
  113733. if(_floor_P[ci->floor_type[i]]->pack)
  113734. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  113735. else
  113736. goto err_out;
  113737. }
  113738. /* residues */
  113739. oggpack_write(opb,ci->residues-1,6);
  113740. for(i=0;i<ci->residues;i++){
  113741. oggpack_write(opb,ci->residue_type[i],16);
  113742. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  113743. }
  113744. /* maps */
  113745. oggpack_write(opb,ci->maps-1,6);
  113746. for(i=0;i<ci->maps;i++){
  113747. oggpack_write(opb,ci->map_type[i],16);
  113748. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  113749. }
  113750. /* modes */
  113751. oggpack_write(opb,ci->modes-1,6);
  113752. for(i=0;i<ci->modes;i++){
  113753. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  113754. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  113755. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  113756. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  113757. }
  113758. oggpack_write(opb,1,1);
  113759. return(0);
  113760. err_out:
  113761. return(-1);
  113762. }
  113763. int vorbis_commentheader_out(vorbis_comment *vc,
  113764. ogg_packet *op){
  113765. oggpack_buffer opb;
  113766. oggpack_writeinit(&opb);
  113767. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  113768. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113769. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  113770. op->bytes=oggpack_bytes(&opb);
  113771. op->b_o_s=0;
  113772. op->e_o_s=0;
  113773. op->granulepos=0;
  113774. op->packetno=1;
  113775. return 0;
  113776. }
  113777. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  113778. vorbis_comment *vc,
  113779. ogg_packet *op,
  113780. ogg_packet *op_comm,
  113781. ogg_packet *op_code){
  113782. int ret=OV_EIMPL;
  113783. vorbis_info *vi=v->vi;
  113784. oggpack_buffer opb;
  113785. private_state *b=(private_state*)v->backend_state;
  113786. if(!b){
  113787. ret=OV_EFAULT;
  113788. goto err_out;
  113789. }
  113790. /* first header packet **********************************************/
  113791. oggpack_writeinit(&opb);
  113792. if(_vorbis_pack_info(&opb,vi))goto err_out;
  113793. /* build the packet */
  113794. if(b->header)_ogg_free(b->header);
  113795. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113796. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  113797. op->packet=b->header;
  113798. op->bytes=oggpack_bytes(&opb);
  113799. op->b_o_s=1;
  113800. op->e_o_s=0;
  113801. op->granulepos=0;
  113802. op->packetno=0;
  113803. /* second header packet (comments) **********************************/
  113804. oggpack_reset(&opb);
  113805. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  113806. if(b->header1)_ogg_free(b->header1);
  113807. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113808. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  113809. op_comm->packet=b->header1;
  113810. op_comm->bytes=oggpack_bytes(&opb);
  113811. op_comm->b_o_s=0;
  113812. op_comm->e_o_s=0;
  113813. op_comm->granulepos=0;
  113814. op_comm->packetno=1;
  113815. /* third header packet (modes/codebooks) ****************************/
  113816. oggpack_reset(&opb);
  113817. if(_vorbis_pack_books(&opb,vi))goto err_out;
  113818. if(b->header2)_ogg_free(b->header2);
  113819. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  113820. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  113821. op_code->packet=b->header2;
  113822. op_code->bytes=oggpack_bytes(&opb);
  113823. op_code->b_o_s=0;
  113824. op_code->e_o_s=0;
  113825. op_code->granulepos=0;
  113826. op_code->packetno=2;
  113827. oggpack_writeclear(&opb);
  113828. return(0);
  113829. err_out:
  113830. oggpack_writeclear(&opb);
  113831. memset(op,0,sizeof(*op));
  113832. memset(op_comm,0,sizeof(*op_comm));
  113833. memset(op_code,0,sizeof(*op_code));
  113834. if(b->header)_ogg_free(b->header);
  113835. if(b->header1)_ogg_free(b->header1);
  113836. if(b->header2)_ogg_free(b->header2);
  113837. b->header=NULL;
  113838. b->header1=NULL;
  113839. b->header2=NULL;
  113840. return(ret);
  113841. }
  113842. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  113843. if(granulepos>=0)
  113844. return((double)granulepos/v->vi->rate);
  113845. return(-1);
  113846. }
  113847. #endif
  113848. /*** End of inlined file: info.c ***/
  113849. /*** Start of inlined file: lpc.c ***/
  113850. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  113851. are derived from code written by Jutta Degener and Carsten Bormann;
  113852. thus we include their copyright below. The entirety of this file
  113853. is freely redistributable on the condition that both of these
  113854. copyright notices are preserved without modification. */
  113855. /* Preserved Copyright: *********************************************/
  113856. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  113857. Technische Universita"t Berlin
  113858. Any use of this software is permitted provided that this notice is not
  113859. removed and that neither the authors nor the Technische Universita"t
  113860. Berlin are deemed to have made any representations as to the
  113861. suitability of this software for any purpose nor are held responsible
  113862. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  113863. THIS SOFTWARE.
  113864. As a matter of courtesy, the authors request to be informed about uses
  113865. this software has found, about bugs in this software, and about any
  113866. improvements that may be of general interest.
  113867. Berlin, 28.11.1994
  113868. Jutta Degener
  113869. Carsten Bormann
  113870. *********************************************************************/
  113871. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113872. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113873. // tasks..
  113874. #if JUCE_MSVC
  113875. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113876. #endif
  113877. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113878. #if JUCE_USE_OGGVORBIS
  113879. #include <stdlib.h>
  113880. #include <string.h>
  113881. #include <math.h>
  113882. /* Autocorrelation LPC coeff generation algorithm invented by
  113883. N. Levinson in 1947, modified by J. Durbin in 1959. */
  113884. /* Input : n elements of time doamin data
  113885. Output: m lpc coefficients, excitation energy */
  113886. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  113887. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  113888. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  113889. double error;
  113890. int i,j;
  113891. /* autocorrelation, p+1 lag coefficients */
  113892. j=m+1;
  113893. while(j--){
  113894. double d=0; /* double needed for accumulator depth */
  113895. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113896. aut[j]=d;
  113897. }
  113898. /* Generate lpc coefficients from autocorr values */
  113899. error=aut[0];
  113900. for(i=0;i<m;i++){
  113901. double r= -aut[i+1];
  113902. if(error==0){
  113903. memset(lpci,0,m*sizeof(*lpci));
  113904. return 0;
  113905. }
  113906. /* Sum up this iteration's reflection coefficient; note that in
  113907. Vorbis we don't save it. If anyone wants to recycle this code
  113908. and needs reflection coefficients, save the results of 'r' from
  113909. each iteration. */
  113910. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113911. r/=error;
  113912. /* Update LPC coefficients and total error */
  113913. lpc[i]=r;
  113914. for(j=0;j<i/2;j++){
  113915. double tmp=lpc[j];
  113916. lpc[j]+=r*lpc[i-1-j];
  113917. lpc[i-1-j]+=r*tmp;
  113918. }
  113919. if(i%2)lpc[j]+=lpc[j]*r;
  113920. error*=1.f-r*r;
  113921. }
  113922. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113923. /* we need the error value to know how big an impulse to hit the
  113924. filter with later */
  113925. return error;
  113926. }
  113927. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113928. float *data,long n){
  113929. /* in: coeff[0...m-1] LPC coefficients
  113930. prime[0...m-1] initial values (allocated size of n+m-1)
  113931. out: data[0...n-1] data samples */
  113932. long i,j,o,p;
  113933. float y;
  113934. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113935. if(!prime)
  113936. for(i=0;i<m;i++)
  113937. work[i]=0.f;
  113938. else
  113939. for(i=0;i<m;i++)
  113940. work[i]=prime[i];
  113941. for(i=0;i<n;i++){
  113942. y=0;
  113943. o=i;
  113944. p=m;
  113945. for(j=0;j<m;j++)
  113946. y-=work[o++]*coeff[--p];
  113947. data[i]=work[o]=y;
  113948. }
  113949. }
  113950. #endif
  113951. /*** End of inlined file: lpc.c ***/
  113952. /*** Start of inlined file: lsp.c ***/
  113953. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113954. an iterative root polisher (CACM algorithm 283). It *is* possible
  113955. to confuse this algorithm into not converging; that should only
  113956. happen with absurdly closely spaced roots (very sharp peaks in the
  113957. LPC f response) which in turn should be impossible in our use of
  113958. the code. If this *does* happen anyway, it's a bug in the floor
  113959. finder; find the cause of the confusion (probably a single bin
  113960. spike or accidental near-float-limit resolution problems) and
  113961. correct it. */
  113962. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113963. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113964. // tasks..
  113965. #if JUCE_MSVC
  113966. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113967. #endif
  113968. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113969. #if JUCE_USE_OGGVORBIS
  113970. #include <math.h>
  113971. #include <string.h>
  113972. #include <stdlib.h>
  113973. /*** Start of inlined file: lookup.h ***/
  113974. #ifndef _V_LOOKUP_H_
  113975. #ifdef FLOAT_LOOKUP
  113976. extern float vorbis_coslook(float a);
  113977. extern float vorbis_invsqlook(float a);
  113978. extern float vorbis_invsq2explook(int a);
  113979. extern float vorbis_fromdBlook(float a);
  113980. #endif
  113981. #ifdef INT_LOOKUP
  113982. extern long vorbis_invsqlook_i(long a,long e);
  113983. extern long vorbis_coslook_i(long a);
  113984. extern float vorbis_fromdBlook_i(long a);
  113985. #endif
  113986. #endif
  113987. /*** End of inlined file: lookup.h ***/
  113988. /* three possible LSP to f curve functions; the exact computation
  113989. (float), a lookup based float implementation, and an integer
  113990. implementation. The float lookup is likely the optimal choice on
  113991. any machine with an FPU. The integer implementation is *not* fixed
  113992. point (due to the need for a large dynamic range and thus a
  113993. seperately tracked exponent) and thus much more complex than the
  113994. relatively simple float implementations. It's mostly for future
  113995. work on a fully fixed point implementation for processors like the
  113996. ARM family. */
  113997. /* undefine both for the 'old' but more precise implementation */
  113998. #define FLOAT_LOOKUP
  113999. #undef INT_LOOKUP
  114000. #ifdef FLOAT_LOOKUP
  114001. /*** Start of inlined file: lookup.c ***/
  114002. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114003. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114004. // tasks..
  114005. #if JUCE_MSVC
  114006. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114007. #endif
  114008. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114009. #if JUCE_USE_OGGVORBIS
  114010. #include <math.h>
  114011. /*** Start of inlined file: lookup.h ***/
  114012. #ifndef _V_LOOKUP_H_
  114013. #ifdef FLOAT_LOOKUP
  114014. extern float vorbis_coslook(float a);
  114015. extern float vorbis_invsqlook(float a);
  114016. extern float vorbis_invsq2explook(int a);
  114017. extern float vorbis_fromdBlook(float a);
  114018. #endif
  114019. #ifdef INT_LOOKUP
  114020. extern long vorbis_invsqlook_i(long a,long e);
  114021. extern long vorbis_coslook_i(long a);
  114022. extern float vorbis_fromdBlook_i(long a);
  114023. #endif
  114024. #endif
  114025. /*** End of inlined file: lookup.h ***/
  114026. /*** Start of inlined file: lookup_data.h ***/
  114027. #ifndef _V_LOOKUP_DATA_H_
  114028. #ifdef FLOAT_LOOKUP
  114029. #define COS_LOOKUP_SZ 128
  114030. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114031. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114032. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114033. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114034. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114035. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114036. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114037. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114038. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114039. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114040. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114041. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114042. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114043. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114044. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114045. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114046. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114047. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114048. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114049. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114050. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114051. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114052. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114053. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114054. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114055. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114056. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114057. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114058. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114059. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114060. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114061. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114062. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114063. -1.0000000000000f,
  114064. };
  114065. #define INVSQ_LOOKUP_SZ 32
  114066. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114067. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114068. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114069. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114070. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114071. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114072. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114073. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114074. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114075. 1.000000000000f,
  114076. };
  114077. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114078. #define INVSQ2EXP_LOOKUP_MAX 32
  114079. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114080. INVSQ2EXP_LOOKUP_MIN+1]={
  114081. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114082. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114083. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114084. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114085. 256.f, 181.019336f, 128.f, 90.50966799f,
  114086. 64.f, 45.254834f, 32.f, 22.627417f,
  114087. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114088. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114089. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114090. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114091. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114092. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114093. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114094. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114095. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114096. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114097. 1.525878906e-05f,
  114098. };
  114099. #endif
  114100. #define FROMdB_LOOKUP_SZ 35
  114101. #define FROMdB2_LOOKUP_SZ 32
  114102. #define FROMdB_SHIFT 5
  114103. #define FROMdB2_SHIFT 3
  114104. #define FROMdB2_MASK 31
  114105. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114106. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114107. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114108. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114109. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114110. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114111. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114112. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114113. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114114. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114115. };
  114116. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114117. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114118. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114119. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114120. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114121. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114122. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114123. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114124. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114125. };
  114126. #ifdef INT_LOOKUP
  114127. #define INVSQ_LOOKUP_I_SHIFT 10
  114128. #define INVSQ_LOOKUP_I_MASK 1023
  114129. static long INVSQ_LOOKUP_I[64+1]={
  114130. 92682l, 91966l, 91267l, 90583l,
  114131. 89915l, 89261l, 88621l, 87995l,
  114132. 87381l, 86781l, 86192l, 85616l,
  114133. 85051l, 84497l, 83953l, 83420l,
  114134. 82897l, 82384l, 81880l, 81385l,
  114135. 80899l, 80422l, 79953l, 79492l,
  114136. 79039l, 78594l, 78156l, 77726l,
  114137. 77302l, 76885l, 76475l, 76072l,
  114138. 75674l, 75283l, 74898l, 74519l,
  114139. 74146l, 73778l, 73415l, 73058l,
  114140. 72706l, 72359l, 72016l, 71679l,
  114141. 71347l, 71019l, 70695l, 70376l,
  114142. 70061l, 69750l, 69444l, 69141l,
  114143. 68842l, 68548l, 68256l, 67969l,
  114144. 67685l, 67405l, 67128l, 66855l,
  114145. 66585l, 66318l, 66054l, 65794l,
  114146. 65536l,
  114147. };
  114148. #define COS_LOOKUP_I_SHIFT 9
  114149. #define COS_LOOKUP_I_MASK 511
  114150. #define COS_LOOKUP_I_SZ 128
  114151. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114152. 16384l, 16379l, 16364l, 16340l,
  114153. 16305l, 16261l, 16207l, 16143l,
  114154. 16069l, 15986l, 15893l, 15791l,
  114155. 15679l, 15557l, 15426l, 15286l,
  114156. 15137l, 14978l, 14811l, 14635l,
  114157. 14449l, 14256l, 14053l, 13842l,
  114158. 13623l, 13395l, 13160l, 12916l,
  114159. 12665l, 12406l, 12140l, 11866l,
  114160. 11585l, 11297l, 11003l, 10702l,
  114161. 10394l, 10080l, 9760l, 9434l,
  114162. 9102l, 8765l, 8423l, 8076l,
  114163. 7723l, 7366l, 7005l, 6639l,
  114164. 6270l, 5897l, 5520l, 5139l,
  114165. 4756l, 4370l, 3981l, 3590l,
  114166. 3196l, 2801l, 2404l, 2006l,
  114167. 1606l, 1205l, 804l, 402l,
  114168. 0l, -401l, -803l, -1204l,
  114169. -1605l, -2005l, -2403l, -2800l,
  114170. -3195l, -3589l, -3980l, -4369l,
  114171. -4755l, -5138l, -5519l, -5896l,
  114172. -6269l, -6638l, -7004l, -7365l,
  114173. -7722l, -8075l, -8422l, -8764l,
  114174. -9101l, -9433l, -9759l, -10079l,
  114175. -10393l, -10701l, -11002l, -11296l,
  114176. -11584l, -11865l, -12139l, -12405l,
  114177. -12664l, -12915l, -13159l, -13394l,
  114178. -13622l, -13841l, -14052l, -14255l,
  114179. -14448l, -14634l, -14810l, -14977l,
  114180. -15136l, -15285l, -15425l, -15556l,
  114181. -15678l, -15790l, -15892l, -15985l,
  114182. -16068l, -16142l, -16206l, -16260l,
  114183. -16304l, -16339l, -16363l, -16378l,
  114184. -16383l,
  114185. };
  114186. #endif
  114187. #endif
  114188. /*** End of inlined file: lookup_data.h ***/
  114189. #ifdef FLOAT_LOOKUP
  114190. /* interpolated lookup based cos function, domain 0 to PI only */
  114191. float vorbis_coslook(float a){
  114192. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114193. int i=vorbis_ftoi(d-.5);
  114194. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114195. }
  114196. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114197. float vorbis_invsqlook(float a){
  114198. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114199. int i=vorbis_ftoi(d-.5f);
  114200. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114201. }
  114202. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114203. float vorbis_invsq2explook(int a){
  114204. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114205. }
  114206. #include <stdio.h>
  114207. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114208. float vorbis_fromdBlook(float a){
  114209. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114210. return (i<0)?1.f:
  114211. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114212. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114213. }
  114214. #endif
  114215. #ifdef INT_LOOKUP
  114216. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114217. 16.16 format
  114218. returns in m.8 format */
  114219. long vorbis_invsqlook_i(long a,long e){
  114220. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114221. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114222. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114223. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114224. d)>>16); /* result 1.16 */
  114225. e+=32;
  114226. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114227. e=(e>>1)-8;
  114228. return(val>>e);
  114229. }
  114230. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114231. /* a is in n.12 format */
  114232. float vorbis_fromdBlook_i(long a){
  114233. int i=(-a)>>(12-FROMdB2_SHIFT);
  114234. return (i<0)?1.f:
  114235. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114236. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114237. }
  114238. /* interpolated lookup based cos function, domain 0 to PI only */
  114239. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114240. long vorbis_coslook_i(long a){
  114241. int i=a>>COS_LOOKUP_I_SHIFT;
  114242. int d=a&COS_LOOKUP_I_MASK;
  114243. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114244. COS_LOOKUP_I_SHIFT);
  114245. }
  114246. #endif
  114247. #endif
  114248. /*** End of inlined file: lookup.c ***/
  114249. /* catch this in the build system; we #include for
  114250. compilers (like gcc) that can't inline across
  114251. modules */
  114252. /* side effect: changes *lsp to cosines of lsp */
  114253. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114254. float amp,float ampoffset){
  114255. int i;
  114256. float wdel=M_PI/ln;
  114257. vorbis_fpu_control fpu;
  114258. (void) fpu; // to avoid an unused variable warning
  114259. vorbis_fpu_setround(&fpu);
  114260. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114261. i=0;
  114262. while(i<n){
  114263. int k=map[i];
  114264. int qexp;
  114265. float p=.7071067812f;
  114266. float q=.7071067812f;
  114267. float w=vorbis_coslook(wdel*k);
  114268. float *ftmp=lsp;
  114269. int c=m>>1;
  114270. do{
  114271. q*=ftmp[0]-w;
  114272. p*=ftmp[1]-w;
  114273. ftmp+=2;
  114274. }while(--c);
  114275. if(m&1){
  114276. /* odd order filter; slightly assymetric */
  114277. /* the last coefficient */
  114278. q*=ftmp[0]-w;
  114279. q*=q;
  114280. p*=p*(1.f-w*w);
  114281. }else{
  114282. /* even order filter; still symmetric */
  114283. q*=q*(1.f+w);
  114284. p*=p*(1.f-w);
  114285. }
  114286. q=frexp(p+q,&qexp);
  114287. q=vorbis_fromdBlook(amp*
  114288. vorbis_invsqlook(q)*
  114289. vorbis_invsq2explook(qexp+m)-
  114290. ampoffset);
  114291. do{
  114292. curve[i++]*=q;
  114293. }while(map[i]==k);
  114294. }
  114295. vorbis_fpu_restore(fpu);
  114296. }
  114297. #else
  114298. #ifdef INT_LOOKUP
  114299. /*** Start of inlined file: lookup.c ***/
  114300. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114301. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114302. // tasks..
  114303. #if JUCE_MSVC
  114304. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114305. #endif
  114306. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114307. #if JUCE_USE_OGGVORBIS
  114308. #include <math.h>
  114309. /*** Start of inlined file: lookup.h ***/
  114310. #ifndef _V_LOOKUP_H_
  114311. #ifdef FLOAT_LOOKUP
  114312. extern float vorbis_coslook(float a);
  114313. extern float vorbis_invsqlook(float a);
  114314. extern float vorbis_invsq2explook(int a);
  114315. extern float vorbis_fromdBlook(float a);
  114316. #endif
  114317. #ifdef INT_LOOKUP
  114318. extern long vorbis_invsqlook_i(long a,long e);
  114319. extern long vorbis_coslook_i(long a);
  114320. extern float vorbis_fromdBlook_i(long a);
  114321. #endif
  114322. #endif
  114323. /*** End of inlined file: lookup.h ***/
  114324. /*** Start of inlined file: lookup_data.h ***/
  114325. #ifndef _V_LOOKUP_DATA_H_
  114326. #ifdef FLOAT_LOOKUP
  114327. #define COS_LOOKUP_SZ 128
  114328. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114329. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114330. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114331. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114332. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114333. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114334. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114335. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114336. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114337. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114338. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114339. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114340. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114341. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114342. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114343. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114344. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114345. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114346. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114347. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114348. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114349. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114350. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114351. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114352. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114353. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114354. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114355. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114356. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114357. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114358. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114359. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114360. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114361. -1.0000000000000f,
  114362. };
  114363. #define INVSQ_LOOKUP_SZ 32
  114364. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114365. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114366. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114367. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114368. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114369. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114370. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114371. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114372. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114373. 1.000000000000f,
  114374. };
  114375. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114376. #define INVSQ2EXP_LOOKUP_MAX 32
  114377. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114378. INVSQ2EXP_LOOKUP_MIN+1]={
  114379. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114380. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114381. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114382. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114383. 256.f, 181.019336f, 128.f, 90.50966799f,
  114384. 64.f, 45.254834f, 32.f, 22.627417f,
  114385. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114386. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114387. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114388. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114389. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114390. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114391. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114392. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114393. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114394. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114395. 1.525878906e-05f,
  114396. };
  114397. #endif
  114398. #define FROMdB_LOOKUP_SZ 35
  114399. #define FROMdB2_LOOKUP_SZ 32
  114400. #define FROMdB_SHIFT 5
  114401. #define FROMdB2_SHIFT 3
  114402. #define FROMdB2_MASK 31
  114403. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114404. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114405. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114406. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114407. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114408. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114409. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114410. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114411. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114412. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114413. };
  114414. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114415. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114416. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114417. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114418. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114419. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114420. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114421. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114422. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114423. };
  114424. #ifdef INT_LOOKUP
  114425. #define INVSQ_LOOKUP_I_SHIFT 10
  114426. #define INVSQ_LOOKUP_I_MASK 1023
  114427. static long INVSQ_LOOKUP_I[64+1]={
  114428. 92682l, 91966l, 91267l, 90583l,
  114429. 89915l, 89261l, 88621l, 87995l,
  114430. 87381l, 86781l, 86192l, 85616l,
  114431. 85051l, 84497l, 83953l, 83420l,
  114432. 82897l, 82384l, 81880l, 81385l,
  114433. 80899l, 80422l, 79953l, 79492l,
  114434. 79039l, 78594l, 78156l, 77726l,
  114435. 77302l, 76885l, 76475l, 76072l,
  114436. 75674l, 75283l, 74898l, 74519l,
  114437. 74146l, 73778l, 73415l, 73058l,
  114438. 72706l, 72359l, 72016l, 71679l,
  114439. 71347l, 71019l, 70695l, 70376l,
  114440. 70061l, 69750l, 69444l, 69141l,
  114441. 68842l, 68548l, 68256l, 67969l,
  114442. 67685l, 67405l, 67128l, 66855l,
  114443. 66585l, 66318l, 66054l, 65794l,
  114444. 65536l,
  114445. };
  114446. #define COS_LOOKUP_I_SHIFT 9
  114447. #define COS_LOOKUP_I_MASK 511
  114448. #define COS_LOOKUP_I_SZ 128
  114449. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114450. 16384l, 16379l, 16364l, 16340l,
  114451. 16305l, 16261l, 16207l, 16143l,
  114452. 16069l, 15986l, 15893l, 15791l,
  114453. 15679l, 15557l, 15426l, 15286l,
  114454. 15137l, 14978l, 14811l, 14635l,
  114455. 14449l, 14256l, 14053l, 13842l,
  114456. 13623l, 13395l, 13160l, 12916l,
  114457. 12665l, 12406l, 12140l, 11866l,
  114458. 11585l, 11297l, 11003l, 10702l,
  114459. 10394l, 10080l, 9760l, 9434l,
  114460. 9102l, 8765l, 8423l, 8076l,
  114461. 7723l, 7366l, 7005l, 6639l,
  114462. 6270l, 5897l, 5520l, 5139l,
  114463. 4756l, 4370l, 3981l, 3590l,
  114464. 3196l, 2801l, 2404l, 2006l,
  114465. 1606l, 1205l, 804l, 402l,
  114466. 0l, -401l, -803l, -1204l,
  114467. -1605l, -2005l, -2403l, -2800l,
  114468. -3195l, -3589l, -3980l, -4369l,
  114469. -4755l, -5138l, -5519l, -5896l,
  114470. -6269l, -6638l, -7004l, -7365l,
  114471. -7722l, -8075l, -8422l, -8764l,
  114472. -9101l, -9433l, -9759l, -10079l,
  114473. -10393l, -10701l, -11002l, -11296l,
  114474. -11584l, -11865l, -12139l, -12405l,
  114475. -12664l, -12915l, -13159l, -13394l,
  114476. -13622l, -13841l, -14052l, -14255l,
  114477. -14448l, -14634l, -14810l, -14977l,
  114478. -15136l, -15285l, -15425l, -15556l,
  114479. -15678l, -15790l, -15892l, -15985l,
  114480. -16068l, -16142l, -16206l, -16260l,
  114481. -16304l, -16339l, -16363l, -16378l,
  114482. -16383l,
  114483. };
  114484. #endif
  114485. #endif
  114486. /*** End of inlined file: lookup_data.h ***/
  114487. #ifdef FLOAT_LOOKUP
  114488. /* interpolated lookup based cos function, domain 0 to PI only */
  114489. float vorbis_coslook(float a){
  114490. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114491. int i=vorbis_ftoi(d-.5);
  114492. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114493. }
  114494. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114495. float vorbis_invsqlook(float a){
  114496. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114497. int i=vorbis_ftoi(d-.5f);
  114498. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114499. }
  114500. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114501. float vorbis_invsq2explook(int a){
  114502. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114503. }
  114504. #include <stdio.h>
  114505. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114506. float vorbis_fromdBlook(float a){
  114507. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114508. return (i<0)?1.f:
  114509. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114510. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114511. }
  114512. #endif
  114513. #ifdef INT_LOOKUP
  114514. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114515. 16.16 format
  114516. returns in m.8 format */
  114517. long vorbis_invsqlook_i(long a,long e){
  114518. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114519. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114520. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114521. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114522. d)>>16); /* result 1.16 */
  114523. e+=32;
  114524. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114525. e=(e>>1)-8;
  114526. return(val>>e);
  114527. }
  114528. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114529. /* a is in n.12 format */
  114530. float vorbis_fromdBlook_i(long a){
  114531. int i=(-a)>>(12-FROMdB2_SHIFT);
  114532. return (i<0)?1.f:
  114533. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114534. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114535. }
  114536. /* interpolated lookup based cos function, domain 0 to PI only */
  114537. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114538. long vorbis_coslook_i(long a){
  114539. int i=a>>COS_LOOKUP_I_SHIFT;
  114540. int d=a&COS_LOOKUP_I_MASK;
  114541. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114542. COS_LOOKUP_I_SHIFT);
  114543. }
  114544. #endif
  114545. #endif
  114546. /*** End of inlined file: lookup.c ***/
  114547. /* catch this in the build system; we #include for
  114548. compilers (like gcc) that can't inline across
  114549. modules */
  114550. static int MLOOP_1[64]={
  114551. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114552. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114553. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114554. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114555. };
  114556. static int MLOOP_2[64]={
  114557. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114558. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114559. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114560. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114561. };
  114562. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114563. /* side effect: changes *lsp to cosines of lsp */
  114564. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114565. float amp,float ampoffset){
  114566. /* 0 <= m < 256 */
  114567. /* set up for using all int later */
  114568. int i;
  114569. int ampoffseti=rint(ampoffset*4096.f);
  114570. int ampi=rint(amp*16.f);
  114571. long *ilsp=alloca(m*sizeof(*ilsp));
  114572. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114573. i=0;
  114574. while(i<n){
  114575. int j,k=map[i];
  114576. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114577. unsigned long qi=46341;
  114578. int qexp=0,shift;
  114579. long wi=vorbis_coslook_i(k*65536/ln);
  114580. qi*=labs(ilsp[0]-wi);
  114581. pi*=labs(ilsp[1]-wi);
  114582. for(j=3;j<m;j+=2){
  114583. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114584. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114585. shift=MLOOP_3[(pi|qi)>>16];
  114586. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114587. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114588. qexp+=shift;
  114589. }
  114590. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114591. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114592. shift=MLOOP_3[(pi|qi)>>16];
  114593. /* pi,qi normalized collectively, both tracked using qexp */
  114594. if(m&1){
  114595. /* odd order filter; slightly assymetric */
  114596. /* the last coefficient */
  114597. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114598. pi=(pi>>shift)<<14;
  114599. qexp+=shift;
  114600. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114601. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114602. shift=MLOOP_3[(pi|qi)>>16];
  114603. pi>>=shift;
  114604. qi>>=shift;
  114605. qexp+=shift-14*((m+1)>>1);
  114606. pi=((pi*pi)>>16);
  114607. qi=((qi*qi)>>16);
  114608. qexp=qexp*2+m;
  114609. pi*=(1<<14)-((wi*wi)>>14);
  114610. qi+=pi>>14;
  114611. }else{
  114612. /* even order filter; still symmetric */
  114613. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114614. worth tracking step by step */
  114615. pi>>=shift;
  114616. qi>>=shift;
  114617. qexp+=shift-7*m;
  114618. pi=((pi*pi)>>16);
  114619. qi=((qi*qi)>>16);
  114620. qexp=qexp*2+m;
  114621. pi*=(1<<14)-wi;
  114622. qi*=(1<<14)+wi;
  114623. qi=(qi+pi)>>14;
  114624. }
  114625. /* we've let the normalization drift because it wasn't important;
  114626. however, for the lookup, things must be normalized again. We
  114627. need at most one right shift or a number of left shifts */
  114628. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114629. qi>>=1; qexp++;
  114630. }else
  114631. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114632. qi<<=1; qexp--;
  114633. }
  114634. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114635. vorbis_invsqlook_i(qi,qexp)-
  114636. /* m.8, m+n<=8 */
  114637. ampoffseti); /* 8.12[0] */
  114638. curve[i]*=amp;
  114639. while(map[++i]==k)curve[i]*=amp;
  114640. }
  114641. }
  114642. #else
  114643. /* old, nonoptimized but simple version for any poor sap who needs to
  114644. figure out what the hell this code does, or wants the other
  114645. fraction of a dB precision */
  114646. /* side effect: changes *lsp to cosines of lsp */
  114647. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114648. float amp,float ampoffset){
  114649. int i;
  114650. float wdel=M_PI/ln;
  114651. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114652. i=0;
  114653. while(i<n){
  114654. int j,k=map[i];
  114655. float p=.5f;
  114656. float q=.5f;
  114657. float w=2.f*cos(wdel*k);
  114658. for(j=1;j<m;j+=2){
  114659. q *= w-lsp[j-1];
  114660. p *= w-lsp[j];
  114661. }
  114662. if(j==m){
  114663. /* odd order filter; slightly assymetric */
  114664. /* the last coefficient */
  114665. q*=w-lsp[j-1];
  114666. p*=p*(4.f-w*w);
  114667. q*=q;
  114668. }else{
  114669. /* even order filter; still symmetric */
  114670. p*=p*(2.f-w);
  114671. q*=q*(2.f+w);
  114672. }
  114673. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114674. curve[i]*=q;
  114675. while(map[++i]==k)curve[i]*=q;
  114676. }
  114677. }
  114678. #endif
  114679. #endif
  114680. static void cheby(float *g, int ord) {
  114681. int i, j;
  114682. g[0] *= .5f;
  114683. for(i=2; i<= ord; i++) {
  114684. for(j=ord; j >= i; j--) {
  114685. g[j-2] -= g[j];
  114686. g[j] += g[j];
  114687. }
  114688. }
  114689. }
  114690. static int JUCE_CDECL comp(const void *a,const void *b){
  114691. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114692. }
  114693. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114694. but there are root sets for which it gets into limit cycles
  114695. (exacerbated by zero suppression) and fails. We can't afford to
  114696. fail, even if the failure is 1 in 100,000,000, so we now use
  114697. Laguerre and later polish with Newton-Raphson (which can then
  114698. afford to fail) */
  114699. #define EPSILON 10e-7
  114700. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114701. int i,m;
  114702. double lastdelta=0.f;
  114703. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114704. for(i=0;i<=ord;i++)defl[i]=a[i];
  114705. for(m=ord;m>0;m--){
  114706. double newx=0.f,delta;
  114707. /* iterate a root */
  114708. while(1){
  114709. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114710. /* eval the polynomial and its first two derivatives */
  114711. for(i=m;i>0;i--){
  114712. ppp = newx*ppp + pp;
  114713. pp = newx*pp + p;
  114714. p = newx*p + defl[i-1];
  114715. }
  114716. /* Laguerre's method */
  114717. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114718. if(denom<0)
  114719. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114720. if(pp>0){
  114721. denom = pp + sqrt(denom);
  114722. if(denom<EPSILON)denom=EPSILON;
  114723. }else{
  114724. denom = pp - sqrt(denom);
  114725. if(denom>-(EPSILON))denom=-(EPSILON);
  114726. }
  114727. delta = m*p/denom;
  114728. newx -= delta;
  114729. if(delta<0.f)delta*=-1;
  114730. if(fabs(delta/newx)<10e-12)break;
  114731. lastdelta=delta;
  114732. }
  114733. r[m-1]=newx;
  114734. /* forward deflation */
  114735. for(i=m;i>0;i--)
  114736. defl[i-1]+=newx*defl[i];
  114737. defl++;
  114738. }
  114739. return(0);
  114740. }
  114741. /* for spit-and-polish only */
  114742. static int Newton_Raphson(float *a,int ord,float *r){
  114743. int i, k, count=0;
  114744. double error=1.f;
  114745. double *root=(double*)alloca(ord*sizeof(*root));
  114746. for(i=0; i<ord;i++) root[i] = r[i];
  114747. while(error>1e-20){
  114748. error=0;
  114749. for(i=0; i<ord; i++) { /* Update each point. */
  114750. double pp=0.,delta;
  114751. double rooti=root[i];
  114752. double p=a[ord];
  114753. for(k=ord-1; k>= 0; k--) {
  114754. pp= pp* rooti + p;
  114755. p = p * rooti + a[k];
  114756. }
  114757. delta = p/pp;
  114758. root[i] -= delta;
  114759. error+= delta*delta;
  114760. }
  114761. if(count>40)return(-1);
  114762. count++;
  114763. }
  114764. /* Replaced the original bubble sort with a real sort. With your
  114765. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114766. for(i=0; i<ord;i++) r[i] = root[i];
  114767. return(0);
  114768. }
  114769. /* Convert lpc coefficients to lsp coefficients */
  114770. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114771. int order2=(m+1)>>1;
  114772. int g1_order,g2_order;
  114773. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114774. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114775. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114776. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114777. int i;
  114778. /* even and odd are slightly different base cases */
  114779. g1_order=(m+1)>>1;
  114780. g2_order=(m) >>1;
  114781. /* Compute the lengths of the x polynomials. */
  114782. /* Compute the first half of K & R F1 & F2 polynomials. */
  114783. /* Compute half of the symmetric and antisymmetric polynomials. */
  114784. /* Remove the roots at +1 and -1. */
  114785. g1[g1_order] = 1.f;
  114786. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114787. g2[g2_order] = 1.f;
  114788. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114789. if(g1_order>g2_order){
  114790. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114791. }else{
  114792. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114793. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114794. }
  114795. /* Convert into polynomials in cos(alpha) */
  114796. cheby(g1,g1_order);
  114797. cheby(g2,g2_order);
  114798. /* Find the roots of the 2 even polynomials.*/
  114799. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114800. Laguerre_With_Deflation(g2,g2_order,g2r))
  114801. return(-1);
  114802. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114803. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114804. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114805. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114806. for(i=0;i<g1_order;i++)
  114807. lsp[i*2] = acos(g1r[i]);
  114808. for(i=0;i<g2_order;i++)
  114809. lsp[i*2+1] = acos(g2r[i]);
  114810. return(0);
  114811. }
  114812. #endif
  114813. /*** End of inlined file: lsp.c ***/
  114814. /*** Start of inlined file: mapping0.c ***/
  114815. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114816. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114817. // tasks..
  114818. #if JUCE_MSVC
  114819. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114820. #endif
  114821. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114822. #if JUCE_USE_OGGVORBIS
  114823. #include <stdlib.h>
  114824. #include <stdio.h>
  114825. #include <string.h>
  114826. #include <math.h>
  114827. /* simplistic, wasteful way of doing this (unique lookup for each
  114828. mode/submapping); there should be a central repository for
  114829. identical lookups. That will require minor work, so I'm putting it
  114830. off as low priority.
  114831. Why a lookup for each backend in a given mode? Because the
  114832. blocksize is set by the mode, and low backend lookups may require
  114833. parameters from other areas of the mode/mapping */
  114834. static void mapping0_free_info(vorbis_info_mapping *i){
  114835. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114836. if(info){
  114837. memset(info,0,sizeof(*info));
  114838. _ogg_free(info);
  114839. }
  114840. }
  114841. static int ilog3(unsigned int v){
  114842. int ret=0;
  114843. if(v)--v;
  114844. while(v){
  114845. ret++;
  114846. v>>=1;
  114847. }
  114848. return(ret);
  114849. }
  114850. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114851. oggpack_buffer *opb){
  114852. int i;
  114853. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114854. /* another 'we meant to do it this way' hack... up to beta 4, we
  114855. packed 4 binary zeros here to signify one submapping in use. We
  114856. now redefine that to mean four bitflags that indicate use of
  114857. deeper features; bit0:submappings, bit1:coupling,
  114858. bit2,3:reserved. This is backward compatable with all actual uses
  114859. of the beta code. */
  114860. if(info->submaps>1){
  114861. oggpack_write(opb,1,1);
  114862. oggpack_write(opb,info->submaps-1,4);
  114863. }else
  114864. oggpack_write(opb,0,1);
  114865. if(info->coupling_steps>0){
  114866. oggpack_write(opb,1,1);
  114867. oggpack_write(opb,info->coupling_steps-1,8);
  114868. for(i=0;i<info->coupling_steps;i++){
  114869. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114870. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114871. }
  114872. }else
  114873. oggpack_write(opb,0,1);
  114874. oggpack_write(opb,0,2); /* 2,3:reserved */
  114875. /* we don't write the channel submappings if we only have one... */
  114876. if(info->submaps>1){
  114877. for(i=0;i<vi->channels;i++)
  114878. oggpack_write(opb,info->chmuxlist[i],4);
  114879. }
  114880. for(i=0;i<info->submaps;i++){
  114881. oggpack_write(opb,0,8); /* time submap unused */
  114882. oggpack_write(opb,info->floorsubmap[i],8);
  114883. oggpack_write(opb,info->residuesubmap[i],8);
  114884. }
  114885. }
  114886. /* also responsible for range checking */
  114887. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114888. int i;
  114889. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114890. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114891. memset(info,0,sizeof(*info));
  114892. if(oggpack_read(opb,1))
  114893. info->submaps=oggpack_read(opb,4)+1;
  114894. else
  114895. info->submaps=1;
  114896. if(oggpack_read(opb,1)){
  114897. info->coupling_steps=oggpack_read(opb,8)+1;
  114898. for(i=0;i<info->coupling_steps;i++){
  114899. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114900. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114901. if(testM<0 ||
  114902. testA<0 ||
  114903. testM==testA ||
  114904. testM>=vi->channels ||
  114905. testA>=vi->channels) goto err_out;
  114906. }
  114907. }
  114908. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114909. if(info->submaps>1){
  114910. for(i=0;i<vi->channels;i++){
  114911. info->chmuxlist[i]=oggpack_read(opb,4);
  114912. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114913. }
  114914. }
  114915. for(i=0;i<info->submaps;i++){
  114916. oggpack_read(opb,8); /* time submap unused */
  114917. info->floorsubmap[i]=oggpack_read(opb,8);
  114918. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114919. info->residuesubmap[i]=oggpack_read(opb,8);
  114920. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114921. }
  114922. return info;
  114923. err_out:
  114924. mapping0_free_info(info);
  114925. return(NULL);
  114926. }
  114927. #if 0
  114928. static long seq=0;
  114929. static ogg_int64_t total=0;
  114930. static float FLOOR1_fromdB_LOOKUP[256]={
  114931. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114932. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114933. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114934. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114935. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114936. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114937. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114938. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114939. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114940. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114941. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114942. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114943. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114944. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114945. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114946. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114947. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114948. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114949. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114950. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114951. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114952. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114953. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114954. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114955. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114956. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114957. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114958. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114959. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114960. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114961. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114962. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114963. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114964. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114965. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114966. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114967. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114968. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114969. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114970. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114971. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114972. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114973. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114974. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114975. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114976. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114977. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114978. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114979. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114980. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114981. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114982. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114983. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114984. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114985. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114986. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114987. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114988. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114989. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114990. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114991. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114992. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114993. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114994. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114995. };
  114996. #endif
  114997. extern int *floor1_fit(vorbis_block *vb,void *look,
  114998. const float *logmdct, /* in */
  114999. const float *logmask);
  115000. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115001. int *A,int *B,
  115002. int del);
  115003. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115004. void*look,
  115005. int *post,int *ilogmask);
  115006. static int mapping0_forward(vorbis_block *vb){
  115007. vorbis_dsp_state *vd=vb->vd;
  115008. vorbis_info *vi=vd->vi;
  115009. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115010. private_state *b=(private_state*)vb->vd->backend_state;
  115011. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115012. int n=vb->pcmend;
  115013. int i,j,k;
  115014. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115015. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115016. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115017. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115018. float global_ampmax=vbi->ampmax;
  115019. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115020. int blocktype=vbi->blocktype;
  115021. int modenumber=vb->W;
  115022. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115023. vorbis_look_psy *psy_look=
  115024. b->psy+blocktype+(vb->W?2:0);
  115025. vb->mode=modenumber;
  115026. for(i=0;i<vi->channels;i++){
  115027. float scale=4.f/n;
  115028. float scale_dB;
  115029. float *pcm =vb->pcm[i];
  115030. float *logfft =pcm;
  115031. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115032. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115033. todB estimation used on IEEE 754
  115034. compliant machines had a bug that
  115035. returned dB values about a third
  115036. of a decibel too high. The bug
  115037. was harmless because tunings
  115038. implicitly took that into
  115039. account. However, fixing the bug
  115040. in the estimator requires
  115041. changing all the tunings as well.
  115042. For now, it's easier to sync
  115043. things back up here, and
  115044. recalibrate the tunings in the
  115045. next major model upgrade. */
  115046. #if 0
  115047. if(vi->channels==2)
  115048. if(i==0)
  115049. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115050. else
  115051. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115052. #endif
  115053. /* window the PCM data */
  115054. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115055. #if 0
  115056. if(vi->channels==2)
  115057. if(i==0)
  115058. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115059. else
  115060. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115061. #endif
  115062. /* transform the PCM data */
  115063. /* only MDCT right now.... */
  115064. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115065. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115066. drft_forward(&b->fft_look[vb->W],pcm);
  115067. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115068. original todB estimation used on
  115069. IEEE 754 compliant machines had a
  115070. bug that returned dB values about
  115071. a third of a decibel too high.
  115072. The bug was harmless because
  115073. tunings implicitly took that into
  115074. account. However, fixing the bug
  115075. in the estimator requires
  115076. changing all the tunings as well.
  115077. For now, it's easier to sync
  115078. things back up here, and
  115079. recalibrate the tunings in the
  115080. next major model upgrade. */
  115081. local_ampmax[i]=logfft[0];
  115082. for(j=1;j<n-1;j+=2){
  115083. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115084. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115085. .345 is a hack; the original todB
  115086. estimation used on IEEE 754
  115087. compliant machines had a bug that
  115088. returned dB values about a third
  115089. of a decibel too high. The bug
  115090. was harmless because tunings
  115091. implicitly took that into
  115092. account. However, fixing the bug
  115093. in the estimator requires
  115094. changing all the tunings as well.
  115095. For now, it's easier to sync
  115096. things back up here, and
  115097. recalibrate the tunings in the
  115098. next major model upgrade. */
  115099. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115100. }
  115101. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115102. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115103. #if 0
  115104. if(vi->channels==2){
  115105. if(i==0){
  115106. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115107. }else{
  115108. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115109. }
  115110. }
  115111. #endif
  115112. }
  115113. {
  115114. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115115. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115116. for(i=0;i<vi->channels;i++){
  115117. /* the encoder setup assumes that all the modes used by any
  115118. specific bitrate tweaking use the same floor */
  115119. int submap=info->chmuxlist[i];
  115120. /* the following makes things clearer to *me* anyway */
  115121. float *mdct =gmdct[i];
  115122. float *logfft =vb->pcm[i];
  115123. float *logmdct =logfft+n/2;
  115124. float *logmask =logfft;
  115125. vb->mode=modenumber;
  115126. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115127. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115128. for(j=0;j<n/2;j++)
  115129. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115130. todB estimation used on IEEE 754
  115131. compliant machines had a bug that
  115132. returned dB values about a third
  115133. of a decibel too high. The bug
  115134. was harmless because tunings
  115135. implicitly took that into
  115136. account. However, fixing the bug
  115137. in the estimator requires
  115138. changing all the tunings as well.
  115139. For now, it's easier to sync
  115140. things back up here, and
  115141. recalibrate the tunings in the
  115142. next major model upgrade. */
  115143. #if 0
  115144. if(vi->channels==2){
  115145. if(i==0)
  115146. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115147. else
  115148. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115149. }else{
  115150. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115151. }
  115152. #endif
  115153. /* first step; noise masking. Not only does 'noise masking'
  115154. give us curves from which we can decide how much resolution
  115155. to give noise parts of the spectrum, it also implicitly hands
  115156. us a tonality estimate (the larger the value in the
  115157. 'noise_depth' vector, the more tonal that area is) */
  115158. _vp_noisemask(psy_look,
  115159. logmdct,
  115160. noise); /* noise does not have by-frequency offset
  115161. bias applied yet */
  115162. #if 0
  115163. if(vi->channels==2){
  115164. if(i==0)
  115165. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115166. else
  115167. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115168. }
  115169. #endif
  115170. /* second step: 'all the other crap'; all the stuff that isn't
  115171. computed/fit for bitrate management goes in the second psy
  115172. vector. This includes tone masking, peak limiting and ATH */
  115173. _vp_tonemask(psy_look,
  115174. logfft,
  115175. tone,
  115176. global_ampmax,
  115177. local_ampmax[i]);
  115178. #if 0
  115179. if(vi->channels==2){
  115180. if(i==0)
  115181. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115182. else
  115183. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115184. }
  115185. #endif
  115186. /* third step; we offset the noise vectors, overlay tone
  115187. masking. We then do a floor1-specific line fit. If we're
  115188. performing bitrate management, the line fit is performed
  115189. multiple times for up/down tweakage on demand. */
  115190. #if 0
  115191. {
  115192. float aotuv[psy_look->n];
  115193. #endif
  115194. _vp_offset_and_mix(psy_look,
  115195. noise,
  115196. tone,
  115197. 1,
  115198. logmask,
  115199. mdct,
  115200. logmdct);
  115201. #if 0
  115202. if(vi->channels==2){
  115203. if(i==0)
  115204. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115205. else
  115206. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115207. }
  115208. }
  115209. #endif
  115210. #if 0
  115211. if(vi->channels==2){
  115212. if(i==0)
  115213. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115214. else
  115215. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115216. }
  115217. #endif
  115218. /* this algorithm is hardwired to floor 1 for now; abort out if
  115219. we're *not* floor1. This won't happen unless someone has
  115220. broken the encode setup lib. Guard it anyway. */
  115221. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115222. floor_posts[i][PACKETBLOBS/2]=
  115223. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115224. logmdct,
  115225. logmask);
  115226. /* are we managing bitrate? If so, perform two more fits for
  115227. later rate tweaking (fits represent hi/lo) */
  115228. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115229. /* higher rate by way of lower noise curve */
  115230. _vp_offset_and_mix(psy_look,
  115231. noise,
  115232. tone,
  115233. 2,
  115234. logmask,
  115235. mdct,
  115236. logmdct);
  115237. #if 0
  115238. if(vi->channels==2){
  115239. if(i==0)
  115240. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115241. else
  115242. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115243. }
  115244. #endif
  115245. floor_posts[i][PACKETBLOBS-1]=
  115246. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115247. logmdct,
  115248. logmask);
  115249. /* lower rate by way of higher noise curve */
  115250. _vp_offset_and_mix(psy_look,
  115251. noise,
  115252. tone,
  115253. 0,
  115254. logmask,
  115255. mdct,
  115256. logmdct);
  115257. #if 0
  115258. if(vi->channels==2)
  115259. if(i==0)
  115260. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115261. else
  115262. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115263. #endif
  115264. floor_posts[i][0]=
  115265. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115266. logmdct,
  115267. logmask);
  115268. /* we also interpolate a range of intermediate curves for
  115269. intermediate rates */
  115270. for(k=1;k<PACKETBLOBS/2;k++)
  115271. floor_posts[i][k]=
  115272. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115273. floor_posts[i][0],
  115274. floor_posts[i][PACKETBLOBS/2],
  115275. k*65536/(PACKETBLOBS/2));
  115276. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115277. floor_posts[i][k]=
  115278. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115279. floor_posts[i][PACKETBLOBS/2],
  115280. floor_posts[i][PACKETBLOBS-1],
  115281. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115282. }
  115283. }
  115284. }
  115285. vbi->ampmax=global_ampmax;
  115286. /*
  115287. the next phases are performed once for vbr-only and PACKETBLOB
  115288. times for bitrate managed modes.
  115289. 1) encode actual mode being used
  115290. 2) encode the floor for each channel, compute coded mask curve/res
  115291. 3) normalize and couple.
  115292. 4) encode residue
  115293. 5) save packet bytes to the packetblob vector
  115294. */
  115295. /* iterate over the many masking curve fits we've created */
  115296. {
  115297. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115298. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115299. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115300. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115301. float **mag_memo;
  115302. int **mag_sort;
  115303. if(info->coupling_steps){
  115304. mag_memo=_vp_quantize_couple_memo(vb,
  115305. &ci->psy_g_param,
  115306. psy_look,
  115307. info,
  115308. gmdct);
  115309. mag_sort=_vp_quantize_couple_sort(vb,
  115310. psy_look,
  115311. info,
  115312. mag_memo);
  115313. hf_reduction(&ci->psy_g_param,
  115314. psy_look,
  115315. info,
  115316. mag_memo);
  115317. }
  115318. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115319. if(psy_look->vi->normal_channel_p){
  115320. for(i=0;i<vi->channels;i++){
  115321. float *mdct =gmdct[i];
  115322. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115323. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115324. }
  115325. }
  115326. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115327. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115328. k++){
  115329. oggpack_buffer *opb=vbi->packetblob[k];
  115330. /* start out our new packet blob with packet type and mode */
  115331. /* Encode the packet type */
  115332. oggpack_write(opb,0,1);
  115333. /* Encode the modenumber */
  115334. /* Encode frame mode, pre,post windowsize, then dispatch */
  115335. oggpack_write(opb,modenumber,b->modebits);
  115336. if(vb->W){
  115337. oggpack_write(opb,vb->lW,1);
  115338. oggpack_write(opb,vb->nW,1);
  115339. }
  115340. /* encode floor, compute masking curve, sep out residue */
  115341. for(i=0;i<vi->channels;i++){
  115342. int submap=info->chmuxlist[i];
  115343. float *mdct =gmdct[i];
  115344. float *res =vb->pcm[i];
  115345. int *ilogmask=ilogmaskch[i]=
  115346. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115347. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115348. floor_posts[i][k],
  115349. ilogmask);
  115350. #if 0
  115351. {
  115352. char buf[80];
  115353. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115354. float work[n/2];
  115355. for(j=0;j<n/2;j++)
  115356. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115357. _analysis_output(buf,seq,work,n/2,1,1,0);
  115358. }
  115359. #endif
  115360. _vp_remove_floor(psy_look,
  115361. mdct,
  115362. ilogmask,
  115363. res,
  115364. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115365. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115366. #if 0
  115367. {
  115368. char buf[80];
  115369. float work[n/2];
  115370. for(j=0;j<n/2;j++)
  115371. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115372. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115373. _analysis_output(buf,seq,work,n/2,1,1,0);
  115374. }
  115375. #endif
  115376. }
  115377. /* our iteration is now based on masking curve, not prequant and
  115378. coupling. Only one prequant/coupling step */
  115379. /* quantize/couple */
  115380. /* incomplete implementation that assumes the tree is all depth
  115381. one, or no tree at all */
  115382. if(info->coupling_steps){
  115383. _vp_couple(k,
  115384. &ci->psy_g_param,
  115385. psy_look,
  115386. info,
  115387. vb->pcm,
  115388. mag_memo,
  115389. mag_sort,
  115390. ilogmaskch,
  115391. nonzero,
  115392. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115393. }
  115394. /* classify and encode by submap */
  115395. for(i=0;i<info->submaps;i++){
  115396. int ch_in_bundle=0;
  115397. long **classifications;
  115398. int resnum=info->residuesubmap[i];
  115399. for(j=0;j<vi->channels;j++){
  115400. if(info->chmuxlist[j]==i){
  115401. zerobundle[ch_in_bundle]=0;
  115402. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115403. res_bundle[ch_in_bundle]=vb->pcm[j];
  115404. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115405. }
  115406. }
  115407. classifications=_residue_P[ci->residue_type[resnum]]->
  115408. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115409. _residue_P[ci->residue_type[resnum]]->
  115410. forward(opb,vb,b->residue[resnum],
  115411. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115412. }
  115413. /* ok, done encoding. Next protopacket. */
  115414. }
  115415. }
  115416. #if 0
  115417. seq++;
  115418. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115419. #endif
  115420. return(0);
  115421. }
  115422. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115423. vorbis_dsp_state *vd=vb->vd;
  115424. vorbis_info *vi=vd->vi;
  115425. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115426. private_state *b=(private_state*)vd->backend_state;
  115427. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115428. int i,j;
  115429. long n=vb->pcmend=ci->blocksizes[vb->W];
  115430. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115431. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115432. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115433. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115434. /* recover the spectral envelope; store it in the PCM vector for now */
  115435. for(i=0;i<vi->channels;i++){
  115436. int submap=info->chmuxlist[i];
  115437. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115438. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115439. if(floormemo[i])
  115440. nonzero[i]=1;
  115441. else
  115442. nonzero[i]=0;
  115443. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115444. }
  115445. /* channel coupling can 'dirty' the nonzero listing */
  115446. for(i=0;i<info->coupling_steps;i++){
  115447. if(nonzero[info->coupling_mag[i]] ||
  115448. nonzero[info->coupling_ang[i]]){
  115449. nonzero[info->coupling_mag[i]]=1;
  115450. nonzero[info->coupling_ang[i]]=1;
  115451. }
  115452. }
  115453. /* recover the residue into our working vectors */
  115454. for(i=0;i<info->submaps;i++){
  115455. int ch_in_bundle=0;
  115456. for(j=0;j<vi->channels;j++){
  115457. if(info->chmuxlist[j]==i){
  115458. if(nonzero[j])
  115459. zerobundle[ch_in_bundle]=1;
  115460. else
  115461. zerobundle[ch_in_bundle]=0;
  115462. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115463. }
  115464. }
  115465. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115466. inverse(vb,b->residue[info->residuesubmap[i]],
  115467. pcmbundle,zerobundle,ch_in_bundle);
  115468. }
  115469. /* channel coupling */
  115470. for(i=info->coupling_steps-1;i>=0;i--){
  115471. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115472. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115473. for(j=0;j<n/2;j++){
  115474. float mag=pcmM[j];
  115475. float ang=pcmA[j];
  115476. if(mag>0)
  115477. if(ang>0){
  115478. pcmM[j]=mag;
  115479. pcmA[j]=mag-ang;
  115480. }else{
  115481. pcmA[j]=mag;
  115482. pcmM[j]=mag+ang;
  115483. }
  115484. else
  115485. if(ang>0){
  115486. pcmM[j]=mag;
  115487. pcmA[j]=mag+ang;
  115488. }else{
  115489. pcmA[j]=mag;
  115490. pcmM[j]=mag-ang;
  115491. }
  115492. }
  115493. }
  115494. /* compute and apply spectral envelope */
  115495. for(i=0;i<vi->channels;i++){
  115496. float *pcm=vb->pcm[i];
  115497. int submap=info->chmuxlist[i];
  115498. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115499. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115500. floormemo[i],pcm);
  115501. }
  115502. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115503. /* only MDCT right now.... */
  115504. for(i=0;i<vi->channels;i++){
  115505. float *pcm=vb->pcm[i];
  115506. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115507. }
  115508. /* all done! */
  115509. return(0);
  115510. }
  115511. /* export hooks */
  115512. vorbis_func_mapping mapping0_exportbundle={
  115513. &mapping0_pack,
  115514. &mapping0_unpack,
  115515. &mapping0_free_info,
  115516. &mapping0_forward,
  115517. &mapping0_inverse
  115518. };
  115519. #endif
  115520. /*** End of inlined file: mapping0.c ***/
  115521. /*** Start of inlined file: mdct.c ***/
  115522. /* this can also be run as an integer transform by uncommenting a
  115523. define in mdct.h; the integerization is a first pass and although
  115524. it's likely stable for Vorbis, the dynamic range is constrained and
  115525. roundoff isn't done (so it's noisy). Consider it functional, but
  115526. only a starting point. There's no point on a machine with an FPU */
  115527. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115528. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115529. // tasks..
  115530. #if JUCE_MSVC
  115531. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115532. #endif
  115533. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115534. #if JUCE_USE_OGGVORBIS
  115535. #include <stdio.h>
  115536. #include <stdlib.h>
  115537. #include <string.h>
  115538. #include <math.h>
  115539. /* build lookups for trig functions; also pre-figure scaling and
  115540. some window function algebra. */
  115541. void mdct_init(mdct_lookup *lookup,int n){
  115542. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115543. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115544. int i;
  115545. int n2=n>>1;
  115546. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115547. lookup->n=n;
  115548. lookup->trig=T;
  115549. lookup->bitrev=bitrev;
  115550. /* trig lookups... */
  115551. for(i=0;i<n/4;i++){
  115552. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115553. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115554. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115555. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115556. }
  115557. for(i=0;i<n/8;i++){
  115558. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115559. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115560. }
  115561. /* bitreverse lookup... */
  115562. {
  115563. int mask=(1<<(log2n-1))-1,i,j;
  115564. int msb=1<<(log2n-2);
  115565. for(i=0;i<n/8;i++){
  115566. int acc=0;
  115567. for(j=0;msb>>j;j++)
  115568. if((msb>>j)&i)acc|=1<<j;
  115569. bitrev[i*2]=((~acc)&mask)-1;
  115570. bitrev[i*2+1]=acc;
  115571. }
  115572. }
  115573. lookup->scale=FLOAT_CONV(4.f/n);
  115574. }
  115575. /* 8 point butterfly (in place, 4 register) */
  115576. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115577. REG_TYPE r0 = x[6] + x[2];
  115578. REG_TYPE r1 = x[6] - x[2];
  115579. REG_TYPE r2 = x[4] + x[0];
  115580. REG_TYPE r3 = x[4] - x[0];
  115581. x[6] = r0 + r2;
  115582. x[4] = r0 - r2;
  115583. r0 = x[5] - x[1];
  115584. r2 = x[7] - x[3];
  115585. x[0] = r1 + r0;
  115586. x[2] = r1 - r0;
  115587. r0 = x[5] + x[1];
  115588. r1 = x[7] + x[3];
  115589. x[3] = r2 + r3;
  115590. x[1] = r2 - r3;
  115591. x[7] = r1 + r0;
  115592. x[5] = r1 - r0;
  115593. }
  115594. /* 16 point butterfly (in place, 4 register) */
  115595. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115596. REG_TYPE r0 = x[1] - x[9];
  115597. REG_TYPE r1 = x[0] - x[8];
  115598. x[8] += x[0];
  115599. x[9] += x[1];
  115600. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115601. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115602. r0 = x[3] - x[11];
  115603. r1 = x[10] - x[2];
  115604. x[10] += x[2];
  115605. x[11] += x[3];
  115606. x[2] = r0;
  115607. x[3] = r1;
  115608. r0 = x[12] - x[4];
  115609. r1 = x[13] - x[5];
  115610. x[12] += x[4];
  115611. x[13] += x[5];
  115612. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115613. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115614. r0 = x[14] - x[6];
  115615. r1 = x[15] - x[7];
  115616. x[14] += x[6];
  115617. x[15] += x[7];
  115618. x[6] = r0;
  115619. x[7] = r1;
  115620. mdct_butterfly_8(x);
  115621. mdct_butterfly_8(x+8);
  115622. }
  115623. /* 32 point butterfly (in place, 4 register) */
  115624. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115625. REG_TYPE r0 = x[30] - x[14];
  115626. REG_TYPE r1 = x[31] - x[15];
  115627. x[30] += x[14];
  115628. x[31] += x[15];
  115629. x[14] = r0;
  115630. x[15] = r1;
  115631. r0 = x[28] - x[12];
  115632. r1 = x[29] - x[13];
  115633. x[28] += x[12];
  115634. x[29] += x[13];
  115635. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115636. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115637. r0 = x[26] - x[10];
  115638. r1 = x[27] - x[11];
  115639. x[26] += x[10];
  115640. x[27] += x[11];
  115641. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115642. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115643. r0 = x[24] - x[8];
  115644. r1 = x[25] - x[9];
  115645. x[24] += x[8];
  115646. x[25] += x[9];
  115647. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115648. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115649. r0 = x[22] - x[6];
  115650. r1 = x[7] - x[23];
  115651. x[22] += x[6];
  115652. x[23] += x[7];
  115653. x[6] = r1;
  115654. x[7] = r0;
  115655. r0 = x[4] - x[20];
  115656. r1 = x[5] - x[21];
  115657. x[20] += x[4];
  115658. x[21] += x[5];
  115659. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115660. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115661. r0 = x[2] - x[18];
  115662. r1 = x[3] - x[19];
  115663. x[18] += x[2];
  115664. x[19] += x[3];
  115665. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115666. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115667. r0 = x[0] - x[16];
  115668. r1 = x[1] - x[17];
  115669. x[16] += x[0];
  115670. x[17] += x[1];
  115671. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115672. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115673. mdct_butterfly_16(x);
  115674. mdct_butterfly_16(x+16);
  115675. }
  115676. /* N point first stage butterfly (in place, 2 register) */
  115677. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115678. DATA_TYPE *x,
  115679. int points){
  115680. DATA_TYPE *x1 = x + points - 8;
  115681. DATA_TYPE *x2 = x + (points>>1) - 8;
  115682. REG_TYPE r0;
  115683. REG_TYPE r1;
  115684. do{
  115685. r0 = x1[6] - x2[6];
  115686. r1 = x1[7] - x2[7];
  115687. x1[6] += x2[6];
  115688. x1[7] += x2[7];
  115689. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115690. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115691. r0 = x1[4] - x2[4];
  115692. r1 = x1[5] - x2[5];
  115693. x1[4] += x2[4];
  115694. x1[5] += x2[5];
  115695. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115696. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115697. r0 = x1[2] - x2[2];
  115698. r1 = x1[3] - x2[3];
  115699. x1[2] += x2[2];
  115700. x1[3] += x2[3];
  115701. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115702. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115703. r0 = x1[0] - x2[0];
  115704. r1 = x1[1] - x2[1];
  115705. x1[0] += x2[0];
  115706. x1[1] += x2[1];
  115707. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115708. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115709. x1-=8;
  115710. x2-=8;
  115711. T+=16;
  115712. }while(x2>=x);
  115713. }
  115714. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115715. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115716. DATA_TYPE *x,
  115717. int points,
  115718. int trigint){
  115719. DATA_TYPE *x1 = x + points - 8;
  115720. DATA_TYPE *x2 = x + (points>>1) - 8;
  115721. REG_TYPE r0;
  115722. REG_TYPE r1;
  115723. do{
  115724. r0 = x1[6] - x2[6];
  115725. r1 = x1[7] - x2[7];
  115726. x1[6] += x2[6];
  115727. x1[7] += x2[7];
  115728. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115729. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115730. T+=trigint;
  115731. r0 = x1[4] - x2[4];
  115732. r1 = x1[5] - x2[5];
  115733. x1[4] += x2[4];
  115734. x1[5] += x2[5];
  115735. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115736. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115737. T+=trigint;
  115738. r0 = x1[2] - x2[2];
  115739. r1 = x1[3] - x2[3];
  115740. x1[2] += x2[2];
  115741. x1[3] += x2[3];
  115742. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115743. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115744. T+=trigint;
  115745. r0 = x1[0] - x2[0];
  115746. r1 = x1[1] - x2[1];
  115747. x1[0] += x2[0];
  115748. x1[1] += x2[1];
  115749. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115750. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115751. T+=trigint;
  115752. x1-=8;
  115753. x2-=8;
  115754. }while(x2>=x);
  115755. }
  115756. STIN void mdct_butterflies(mdct_lookup *init,
  115757. DATA_TYPE *x,
  115758. int points){
  115759. DATA_TYPE *T=init->trig;
  115760. int stages=init->log2n-5;
  115761. int i,j;
  115762. if(--stages>0){
  115763. mdct_butterfly_first(T,x,points);
  115764. }
  115765. for(i=1;--stages>0;i++){
  115766. for(j=0;j<(1<<i);j++)
  115767. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115768. }
  115769. for(j=0;j<points;j+=32)
  115770. mdct_butterfly_32(x+j);
  115771. }
  115772. void mdct_clear(mdct_lookup *l){
  115773. if(l){
  115774. if(l->trig)_ogg_free(l->trig);
  115775. if(l->bitrev)_ogg_free(l->bitrev);
  115776. memset(l,0,sizeof(*l));
  115777. }
  115778. }
  115779. STIN void mdct_bitreverse(mdct_lookup *init,
  115780. DATA_TYPE *x){
  115781. int n = init->n;
  115782. int *bit = init->bitrev;
  115783. DATA_TYPE *w0 = x;
  115784. DATA_TYPE *w1 = x = w0+(n>>1);
  115785. DATA_TYPE *T = init->trig+n;
  115786. do{
  115787. DATA_TYPE *x0 = x+bit[0];
  115788. DATA_TYPE *x1 = x+bit[1];
  115789. REG_TYPE r0 = x0[1] - x1[1];
  115790. REG_TYPE r1 = x0[0] + x1[0];
  115791. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115792. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115793. w1 -= 4;
  115794. r0 = HALVE(x0[1] + x1[1]);
  115795. r1 = HALVE(x0[0] - x1[0]);
  115796. w0[0] = r0 + r2;
  115797. w1[2] = r0 - r2;
  115798. w0[1] = r1 + r3;
  115799. w1[3] = r3 - r1;
  115800. x0 = x+bit[2];
  115801. x1 = x+bit[3];
  115802. r0 = x0[1] - x1[1];
  115803. r1 = x0[0] + x1[0];
  115804. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115805. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115806. r0 = HALVE(x0[1] + x1[1]);
  115807. r1 = HALVE(x0[0] - x1[0]);
  115808. w0[2] = r0 + r2;
  115809. w1[0] = r0 - r2;
  115810. w0[3] = r1 + r3;
  115811. w1[1] = r3 - r1;
  115812. T += 4;
  115813. bit += 4;
  115814. w0 += 4;
  115815. }while(w0<w1);
  115816. }
  115817. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115818. int n=init->n;
  115819. int n2=n>>1;
  115820. int n4=n>>2;
  115821. /* rotate */
  115822. DATA_TYPE *iX = in+n2-7;
  115823. DATA_TYPE *oX = out+n2+n4;
  115824. DATA_TYPE *T = init->trig+n4;
  115825. do{
  115826. oX -= 4;
  115827. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115828. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115829. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115830. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115831. iX -= 8;
  115832. T += 4;
  115833. }while(iX>=in);
  115834. iX = in+n2-8;
  115835. oX = out+n2+n4;
  115836. T = init->trig+n4;
  115837. do{
  115838. T -= 4;
  115839. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115840. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115841. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115842. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115843. iX -= 8;
  115844. oX += 4;
  115845. }while(iX>=in);
  115846. mdct_butterflies(init,out+n2,n2);
  115847. mdct_bitreverse(init,out);
  115848. /* roatate + window */
  115849. {
  115850. DATA_TYPE *oX1=out+n2+n4;
  115851. DATA_TYPE *oX2=out+n2+n4;
  115852. DATA_TYPE *iX =out;
  115853. T =init->trig+n2;
  115854. do{
  115855. oX1-=4;
  115856. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115857. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115858. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115859. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115860. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115861. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115862. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115863. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115864. oX2+=4;
  115865. iX += 8;
  115866. T += 8;
  115867. }while(iX<oX1);
  115868. iX=out+n2+n4;
  115869. oX1=out+n4;
  115870. oX2=oX1;
  115871. do{
  115872. oX1-=4;
  115873. iX-=4;
  115874. oX2[0] = -(oX1[3] = iX[3]);
  115875. oX2[1] = -(oX1[2] = iX[2]);
  115876. oX2[2] = -(oX1[1] = iX[1]);
  115877. oX2[3] = -(oX1[0] = iX[0]);
  115878. oX2+=4;
  115879. }while(oX2<iX);
  115880. iX=out+n2+n4;
  115881. oX1=out+n2+n4;
  115882. oX2=out+n2;
  115883. do{
  115884. oX1-=4;
  115885. oX1[0]= iX[3];
  115886. oX1[1]= iX[2];
  115887. oX1[2]= iX[1];
  115888. oX1[3]= iX[0];
  115889. iX+=4;
  115890. }while(oX1>oX2);
  115891. }
  115892. }
  115893. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115894. int n=init->n;
  115895. int n2=n>>1;
  115896. int n4=n>>2;
  115897. int n8=n>>3;
  115898. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115899. DATA_TYPE *w2=w+n2;
  115900. /* rotate */
  115901. /* window + rotate + step 1 */
  115902. REG_TYPE r0;
  115903. REG_TYPE r1;
  115904. DATA_TYPE *x0=in+n2+n4;
  115905. DATA_TYPE *x1=x0+1;
  115906. DATA_TYPE *T=init->trig+n2;
  115907. int i=0;
  115908. for(i=0;i<n8;i+=2){
  115909. x0 -=4;
  115910. T-=2;
  115911. r0= x0[2] + x1[0];
  115912. r1= x0[0] + x1[2];
  115913. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115914. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115915. x1 +=4;
  115916. }
  115917. x1=in+1;
  115918. for(;i<n2-n8;i+=2){
  115919. T-=2;
  115920. x0 -=4;
  115921. r0= x0[2] - x1[0];
  115922. r1= x0[0] - x1[2];
  115923. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115924. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115925. x1 +=4;
  115926. }
  115927. x0=in+n;
  115928. for(;i<n2;i+=2){
  115929. T-=2;
  115930. x0 -=4;
  115931. r0= -x0[2] - x1[0];
  115932. r1= -x0[0] - x1[2];
  115933. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115934. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115935. x1 +=4;
  115936. }
  115937. mdct_butterflies(init,w+n2,n2);
  115938. mdct_bitreverse(init,w);
  115939. /* roatate + window */
  115940. T=init->trig+n2;
  115941. x0=out+n2;
  115942. for(i=0;i<n4;i++){
  115943. x0--;
  115944. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115945. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115946. w+=2;
  115947. T+=2;
  115948. }
  115949. }
  115950. #endif
  115951. /*** End of inlined file: mdct.c ***/
  115952. /*** Start of inlined file: psy.c ***/
  115953. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115954. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115955. // tasks..
  115956. #if JUCE_MSVC
  115957. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115958. #endif
  115959. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115960. #if JUCE_USE_OGGVORBIS
  115961. #include <stdlib.h>
  115962. #include <math.h>
  115963. #include <string.h>
  115964. /*** Start of inlined file: masking.h ***/
  115965. #ifndef _V_MASKING_H_
  115966. #define _V_MASKING_H_
  115967. /* more detailed ATH; the bass if flat to save stressing the floor
  115968. overly for only a bin or two of savings. */
  115969. #define MAX_ATH 88
  115970. static float ATH[]={
  115971. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  115972. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  115973. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  115974. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  115975. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  115976. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  115977. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  115978. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  115979. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  115980. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  115981. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  115982. };
  115983. /* The tone masking curves from Ehmer's and Fielder's papers have been
  115984. replaced by an empirically collected data set. The previously
  115985. published values were, far too often, simply on crack. */
  115986. #define EHMER_OFFSET 16
  115987. #define EHMER_MAX 56
  115988. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  115989. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  115990. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  115991. for collection of these curves) */
  115992. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  115993. /* 62.5 Hz */
  115994. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  115995. -60, -60, -60, -60, -62, -62, -65, -73,
  115996. -69, -68, -68, -67, -70, -70, -72, -74,
  115997. -75, -79, -79, -80, -83, -88, -93, -100,
  115998. -110, -999, -999, -999, -999, -999, -999, -999,
  115999. -999, -999, -999, -999, -999, -999, -999, -999,
  116000. -999, -999, -999, -999, -999, -999, -999, -999},
  116001. { -48, -48, -48, -48, -48, -48, -48, -48,
  116002. -48, -48, -48, -48, -48, -53, -61, -66,
  116003. -66, -68, -67, -70, -76, -76, -72, -73,
  116004. -75, -76, -78, -79, -83, -88, -93, -100,
  116005. -110, -999, -999, -999, -999, -999, -999, -999,
  116006. -999, -999, -999, -999, -999, -999, -999, -999,
  116007. -999, -999, -999, -999, -999, -999, -999, -999},
  116008. { -37, -37, -37, -37, -37, -37, -37, -37,
  116009. -38, -40, -42, -46, -48, -53, -55, -62,
  116010. -65, -58, -56, -56, -61, -60, -65, -67,
  116011. -69, -71, -77, -77, -78, -80, -82, -84,
  116012. -88, -93, -98, -106, -112, -999, -999, -999,
  116013. -999, -999, -999, -999, -999, -999, -999, -999,
  116014. -999, -999, -999, -999, -999, -999, -999, -999},
  116015. { -25, -25, -25, -25, -25, -25, -25, -25,
  116016. -25, -26, -27, -29, -32, -38, -48, -52,
  116017. -52, -50, -48, -48, -51, -52, -54, -60,
  116018. -67, -67, -66, -68, -69, -73, -73, -76,
  116019. -80, -81, -81, -85, -85, -86, -88, -93,
  116020. -100, -110, -999, -999, -999, -999, -999, -999,
  116021. -999, -999, -999, -999, -999, -999, -999, -999},
  116022. { -16, -16, -16, -16, -16, -16, -16, -16,
  116023. -17, -19, -20, -22, -26, -28, -31, -40,
  116024. -47, -39, -39, -40, -42, -43, -47, -51,
  116025. -57, -52, -55, -55, -60, -58, -62, -63,
  116026. -70, -67, -69, -72, -73, -77, -80, -82,
  116027. -83, -87, -90, -94, -98, -104, -115, -999,
  116028. -999, -999, -999, -999, -999, -999, -999, -999},
  116029. { -8, -8, -8, -8, -8, -8, -8, -8,
  116030. -8, -8, -10, -11, -15, -19, -25, -30,
  116031. -34, -31, -30, -31, -29, -32, -35, -42,
  116032. -48, -42, -44, -46, -50, -50, -51, -52,
  116033. -59, -54, -55, -55, -58, -62, -63, -66,
  116034. -72, -73, -76, -75, -78, -80, -80, -81,
  116035. -84, -88, -90, -94, -98, -101, -106, -110}},
  116036. /* 88Hz */
  116037. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116038. -66, -66, -66, -66, -66, -67, -67, -67,
  116039. -76, -72, -71, -74, -76, -76, -75, -78,
  116040. -79, -79, -81, -83, -86, -89, -93, -97,
  116041. -100, -105, -110, -999, -999, -999, -999, -999,
  116042. -999, -999, -999, -999, -999, -999, -999, -999,
  116043. -999, -999, -999, -999, -999, -999, -999, -999},
  116044. { -47, -47, -47, -47, -47, -47, -47, -47,
  116045. -47, -47, -47, -48, -51, -55, -59, -66,
  116046. -66, -66, -67, -66, -68, -69, -70, -74,
  116047. -79, -77, -77, -78, -80, -81, -82, -84,
  116048. -86, -88, -91, -95, -100, -108, -116, -999,
  116049. -999, -999, -999, -999, -999, -999, -999, -999,
  116050. -999, -999, -999, -999, -999, -999, -999, -999},
  116051. { -36, -36, -36, -36, -36, -36, -36, -36,
  116052. -36, -37, -37, -41, -44, -48, -51, -58,
  116053. -62, -60, -57, -59, -59, -60, -63, -65,
  116054. -72, -71, -70, -72, -74, -77, -76, -78,
  116055. -81, -81, -80, -83, -86, -91, -96, -100,
  116056. -105, -110, -999, -999, -999, -999, -999, -999,
  116057. -999, -999, -999, -999, -999, -999, -999, -999},
  116058. { -28, -28, -28, -28, -28, -28, -28, -28,
  116059. -28, -30, -32, -32, -33, -35, -41, -49,
  116060. -50, -49, -47, -48, -48, -52, -51, -57,
  116061. -65, -61, -59, -61, -64, -69, -70, -74,
  116062. -77, -77, -78, -81, -84, -85, -87, -90,
  116063. -92, -96, -100, -107, -112, -999, -999, -999,
  116064. -999, -999, -999, -999, -999, -999, -999, -999},
  116065. { -19, -19, -19, -19, -19, -19, -19, -19,
  116066. -20, -21, -23, -27, -30, -35, -36, -41,
  116067. -46, -44, -42, -40, -41, -41, -43, -48,
  116068. -55, -53, -52, -53, -56, -59, -58, -60,
  116069. -67, -66, -69, -71, -72, -75, -79, -81,
  116070. -84, -87, -90, -93, -97, -101, -107, -114,
  116071. -999, -999, -999, -999, -999, -999, -999, -999},
  116072. { -9, -9, -9, -9, -9, -9, -9, -9,
  116073. -11, -12, -12, -15, -16, -20, -23, -30,
  116074. -37, -34, -33, -34, -31, -32, -32, -38,
  116075. -47, -44, -41, -40, -47, -49, -46, -46,
  116076. -58, -50, -50, -54, -58, -62, -64, -67,
  116077. -67, -70, -72, -76, -79, -83, -87, -91,
  116078. -96, -100, -104, -110, -999, -999, -999, -999}},
  116079. /* 125 Hz */
  116080. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116081. -62, -62, -63, -64, -66, -67, -66, -68,
  116082. -75, -72, -76, -75, -76, -78, -79, -82,
  116083. -84, -85, -90, -94, -101, -110, -999, -999,
  116084. -999, -999, -999, -999, -999, -999, -999, -999,
  116085. -999, -999, -999, -999, -999, -999, -999, -999,
  116086. -999, -999, -999, -999, -999, -999, -999, -999},
  116087. { -59, -59, -59, -59, -59, -59, -59, -59,
  116088. -59, -59, -59, -60, -60, -61, -63, -66,
  116089. -71, -68, -70, -70, -71, -72, -72, -75,
  116090. -81, -78, -79, -82, -83, -86, -90, -97,
  116091. -103, -113, -999, -999, -999, -999, -999, -999,
  116092. -999, -999, -999, -999, -999, -999, -999, -999,
  116093. -999, -999, -999, -999, -999, -999, -999, -999},
  116094. { -53, -53, -53, -53, -53, -53, -53, -53,
  116095. -53, -54, -55, -57, -56, -57, -55, -61,
  116096. -65, -60, -60, -62, -63, -63, -66, -68,
  116097. -74, -73, -75, -75, -78, -80, -80, -82,
  116098. -85, -90, -96, -101, -108, -999, -999, -999,
  116099. -999, -999, -999, -999, -999, -999, -999, -999,
  116100. -999, -999, -999, -999, -999, -999, -999, -999},
  116101. { -46, -46, -46, -46, -46, -46, -46, -46,
  116102. -46, -46, -47, -47, -47, -47, -48, -51,
  116103. -57, -51, -49, -50, -51, -53, -54, -59,
  116104. -66, -60, -62, -67, -67, -70, -72, -75,
  116105. -76, -78, -81, -85, -88, -94, -97, -104,
  116106. -112, -999, -999, -999, -999, -999, -999, -999,
  116107. -999, -999, -999, -999, -999, -999, -999, -999},
  116108. { -36, -36, -36, -36, -36, -36, -36, -36,
  116109. -39, -41, -42, -42, -39, -38, -41, -43,
  116110. -52, -44, -40, -39, -37, -37, -40, -47,
  116111. -54, -50, -48, -50, -55, -61, -59, -62,
  116112. -66, -66, -66, -69, -69, -73, -74, -74,
  116113. -75, -77, -79, -82, -87, -91, -95, -100,
  116114. -108, -115, -999, -999, -999, -999, -999, -999},
  116115. { -28, -26, -24, -22, -20, -20, -23, -29,
  116116. -30, -31, -28, -27, -28, -28, -28, -35,
  116117. -40, -33, -32, -29, -30, -30, -30, -37,
  116118. -45, -41, -37, -38, -45, -47, -47, -48,
  116119. -53, -49, -48, -50, -49, -49, -51, -52,
  116120. -58, -56, -57, -56, -60, -61, -62, -70,
  116121. -72, -74, -78, -83, -88, -93, -100, -106}},
  116122. /* 177 Hz */
  116123. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116124. -999, -110, -105, -100, -95, -91, -87, -83,
  116125. -80, -78, -76, -78, -78, -81, -83, -85,
  116126. -86, -85, -86, -87, -90, -97, -107, -999,
  116127. -999, -999, -999, -999, -999, -999, -999, -999,
  116128. -999, -999, -999, -999, -999, -999, -999, -999,
  116129. -999, -999, -999, -999, -999, -999, -999, -999},
  116130. {-999, -999, -999, -110, -105, -100, -95, -90,
  116131. -85, -81, -77, -73, -70, -67, -67, -68,
  116132. -75, -73, -70, -69, -70, -72, -75, -79,
  116133. -84, -83, -84, -86, -88, -89, -89, -93,
  116134. -98, -105, -112, -999, -999, -999, -999, -999,
  116135. -999, -999, -999, -999, -999, -999, -999, -999,
  116136. -999, -999, -999, -999, -999, -999, -999, -999},
  116137. {-105, -100, -95, -90, -85, -80, -76, -71,
  116138. -68, -68, -65, -63, -63, -62, -62, -64,
  116139. -65, -64, -61, -62, -63, -64, -66, -68,
  116140. -73, -73, -74, -75, -76, -81, -83, -85,
  116141. -88, -89, -92, -95, -100, -108, -999, -999,
  116142. -999, -999, -999, -999, -999, -999, -999, -999,
  116143. -999, -999, -999, -999, -999, -999, -999, -999},
  116144. { -80, -75, -71, -68, -65, -63, -62, -61,
  116145. -61, -61, -61, -59, -56, -57, -53, -50,
  116146. -58, -52, -50, -50, -52, -53, -54, -58,
  116147. -67, -63, -67, -68, -72, -75, -78, -80,
  116148. -81, -81, -82, -85, -89, -90, -93, -97,
  116149. -101, -107, -114, -999, -999, -999, -999, -999,
  116150. -999, -999, -999, -999, -999, -999, -999, -999},
  116151. { -65, -61, -59, -57, -56, -55, -55, -56,
  116152. -56, -57, -55, -53, -52, -47, -44, -44,
  116153. -50, -44, -41, -39, -39, -42, -40, -46,
  116154. -51, -49, -50, -53, -54, -63, -60, -61,
  116155. -62, -66, -66, -66, -70, -73, -74, -75,
  116156. -76, -75, -79, -85, -89, -91, -96, -102,
  116157. -110, -999, -999, -999, -999, -999, -999, -999},
  116158. { -52, -50, -49, -49, -48, -48, -48, -49,
  116159. -50, -50, -49, -46, -43, -39, -35, -33,
  116160. -38, -36, -32, -29, -32, -32, -32, -35,
  116161. -44, -39, -38, -38, -46, -50, -45, -46,
  116162. -53, -50, -50, -50, -54, -54, -53, -53,
  116163. -56, -57, -59, -66, -70, -72, -74, -79,
  116164. -83, -85, -90, -97, -114, -999, -999, -999}},
  116165. /* 250 Hz */
  116166. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116167. -100, -95, -90, -86, -80, -75, -75, -79,
  116168. -80, -79, -80, -81, -82, -88, -95, -103,
  116169. -110, -999, -999, -999, -999, -999, -999, -999,
  116170. -999, -999, -999, -999, -999, -999, -999, -999,
  116171. -999, -999, -999, -999, -999, -999, -999, -999,
  116172. -999, -999, -999, -999, -999, -999, -999, -999},
  116173. {-999, -999, -999, -999, -108, -103, -98, -93,
  116174. -88, -83, -79, -78, -75, -71, -67, -68,
  116175. -73, -73, -72, -73, -75, -77, -80, -82,
  116176. -88, -93, -100, -107, -114, -999, -999, -999,
  116177. -999, -999, -999, -999, -999, -999, -999, -999,
  116178. -999, -999, -999, -999, -999, -999, -999, -999,
  116179. -999, -999, -999, -999, -999, -999, -999, -999},
  116180. {-999, -999, -999, -110, -105, -101, -96, -90,
  116181. -86, -81, -77, -73, -69, -66, -61, -62,
  116182. -66, -64, -62, -65, -66, -70, -72, -76,
  116183. -81, -80, -84, -90, -95, -102, -110, -999,
  116184. -999, -999, -999, -999, -999, -999, -999, -999,
  116185. -999, -999, -999, -999, -999, -999, -999, -999,
  116186. -999, -999, -999, -999, -999, -999, -999, -999},
  116187. {-999, -999, -999, -107, -103, -97, -92, -88,
  116188. -83, -79, -74, -70, -66, -59, -53, -58,
  116189. -62, -55, -54, -54, -54, -58, -61, -62,
  116190. -72, -70, -72, -75, -78, -80, -81, -80,
  116191. -83, -83, -88, -93, -100, -107, -115, -999,
  116192. -999, -999, -999, -999, -999, -999, -999, -999,
  116193. -999, -999, -999, -999, -999, -999, -999, -999},
  116194. {-999, -999, -999, -105, -100, -95, -90, -85,
  116195. -80, -75, -70, -66, -62, -56, -48, -44,
  116196. -48, -46, -46, -43, -46, -48, -48, -51,
  116197. -58, -58, -59, -60, -62, -62, -61, -61,
  116198. -65, -64, -65, -68, -70, -74, -75, -78,
  116199. -81, -86, -95, -110, -999, -999, -999, -999,
  116200. -999, -999, -999, -999, -999, -999, -999, -999},
  116201. {-999, -999, -105, -100, -95, -90, -85, -80,
  116202. -75, -70, -65, -61, -55, -49, -39, -33,
  116203. -40, -35, -32, -38, -40, -33, -35, -37,
  116204. -46, -41, -45, -44, -46, -42, -45, -46,
  116205. -52, -50, -50, -50, -54, -54, -55, -57,
  116206. -62, -64, -66, -68, -70, -76, -81, -90,
  116207. -100, -110, -999, -999, -999, -999, -999, -999}},
  116208. /* 354 hz */
  116209. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116210. -105, -98, -90, -85, -82, -83, -80, -78,
  116211. -84, -79, -80, -83, -87, -89, -91, -93,
  116212. -99, -106, -117, -999, -999, -999, -999, -999,
  116213. -999, -999, -999, -999, -999, -999, -999, -999,
  116214. -999, -999, -999, -999, -999, -999, -999, -999,
  116215. -999, -999, -999, -999, -999, -999, -999, -999},
  116216. {-999, -999, -999, -999, -999, -999, -999, -999,
  116217. -105, -98, -90, -85, -80, -75, -70, -68,
  116218. -74, -72, -74, -77, -80, -82, -85, -87,
  116219. -92, -89, -91, -95, -100, -106, -112, -999,
  116220. -999, -999, -999, -999, -999, -999, -999, -999,
  116221. -999, -999, -999, -999, -999, -999, -999, -999,
  116222. -999, -999, -999, -999, -999, -999, -999, -999},
  116223. {-999, -999, -999, -999, -999, -999, -999, -999,
  116224. -105, -98, -90, -83, -75, -71, -63, -64,
  116225. -67, -62, -64, -67, -70, -73, -77, -81,
  116226. -84, -83, -85, -89, -90, -93, -98, -104,
  116227. -109, -114, -999, -999, -999, -999, -999, -999,
  116228. -999, -999, -999, -999, -999, -999, -999, -999,
  116229. -999, -999, -999, -999, -999, -999, -999, -999},
  116230. {-999, -999, -999, -999, -999, -999, -999, -999,
  116231. -103, -96, -88, -81, -75, -68, -58, -54,
  116232. -56, -54, -56, -56, -58, -60, -63, -66,
  116233. -74, -69, -72, -72, -75, -74, -77, -81,
  116234. -81, -82, -84, -87, -93, -96, -99, -104,
  116235. -110, -999, -999, -999, -999, -999, -999, -999,
  116236. -999, -999, -999, -999, -999, -999, -999, -999},
  116237. {-999, -999, -999, -999, -999, -108, -102, -96,
  116238. -91, -85, -80, -74, -68, -60, -51, -46,
  116239. -48, -46, -43, -45, -47, -47, -49, -48,
  116240. -56, -53, -55, -58, -57, -63, -58, -60,
  116241. -66, -64, -67, -70, -70, -74, -77, -84,
  116242. -86, -89, -91, -93, -94, -101, -109, -118,
  116243. -999, -999, -999, -999, -999, -999, -999, -999},
  116244. {-999, -999, -999, -108, -103, -98, -93, -88,
  116245. -83, -78, -73, -68, -60, -53, -44, -35,
  116246. -38, -38, -34, -34, -36, -40, -41, -44,
  116247. -51, -45, -46, -47, -46, -54, -50, -49,
  116248. -50, -50, -50, -51, -54, -57, -58, -60,
  116249. -66, -66, -66, -64, -65, -68, -77, -82,
  116250. -87, -95, -110, -999, -999, -999, -999, -999}},
  116251. /* 500 Hz */
  116252. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116253. -107, -102, -97, -92, -87, -83, -78, -75,
  116254. -82, -79, -83, -85, -89, -92, -95, -98,
  116255. -101, -105, -109, -113, -999, -999, -999, -999,
  116256. -999, -999, -999, -999, -999, -999, -999, -999,
  116257. -999, -999, -999, -999, -999, -999, -999, -999,
  116258. -999, -999, -999, -999, -999, -999, -999, -999},
  116259. {-999, -999, -999, -999, -999, -999, -999, -106,
  116260. -100, -95, -90, -86, -81, -78, -74, -69,
  116261. -74, -74, -76, -79, -83, -84, -86, -89,
  116262. -92, -97, -93, -100, -103, -107, -110, -999,
  116263. -999, -999, -999, -999, -999, -999, -999, -999,
  116264. -999, -999, -999, -999, -999, -999, -999, -999,
  116265. -999, -999, -999, -999, -999, -999, -999, -999},
  116266. {-999, -999, -999, -999, -999, -999, -106, -100,
  116267. -95, -90, -87, -83, -80, -75, -69, -60,
  116268. -66, -66, -68, -70, -74, -78, -79, -81,
  116269. -81, -83, -84, -87, -93, -96, -99, -103,
  116270. -107, -110, -999, -999, -999, -999, -999, -999,
  116271. -999, -999, -999, -999, -999, -999, -999, -999,
  116272. -999, -999, -999, -999, -999, -999, -999, -999},
  116273. {-999, -999, -999, -999, -999, -108, -103, -98,
  116274. -93, -89, -85, -82, -78, -71, -62, -55,
  116275. -58, -58, -54, -54, -55, -59, -61, -62,
  116276. -70, -66, -66, -67, -70, -72, -75, -78,
  116277. -84, -84, -84, -88, -91, -90, -95, -98,
  116278. -102, -103, -106, -110, -999, -999, -999, -999,
  116279. -999, -999, -999, -999, -999, -999, -999, -999},
  116280. {-999, -999, -999, -999, -108, -103, -98, -94,
  116281. -90, -87, -82, -79, -73, -67, -58, -47,
  116282. -50, -45, -41, -45, -48, -44, -44, -49,
  116283. -54, -51, -48, -47, -49, -50, -51, -57,
  116284. -58, -60, -63, -69, -70, -69, -71, -74,
  116285. -78, -82, -90, -95, -101, -105, -110, -999,
  116286. -999, -999, -999, -999, -999, -999, -999, -999},
  116287. {-999, -999, -999, -105, -101, -97, -93, -90,
  116288. -85, -80, -77, -72, -65, -56, -48, -37,
  116289. -40, -36, -34, -40, -50, -47, -38, -41,
  116290. -47, -38, -35, -39, -38, -43, -40, -45,
  116291. -50, -45, -44, -47, -50, -55, -48, -48,
  116292. -52, -66, -70, -76, -82, -90, -97, -105,
  116293. -110, -999, -999, -999, -999, -999, -999, -999}},
  116294. /* 707 Hz */
  116295. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116296. -999, -108, -103, -98, -93, -86, -79, -76,
  116297. -83, -81, -85, -87, -89, -93, -98, -102,
  116298. -107, -112, -999, -999, -999, -999, -999, -999,
  116299. -999, -999, -999, -999, -999, -999, -999, -999,
  116300. -999, -999, -999, -999, -999, -999, -999, -999,
  116301. -999, -999, -999, -999, -999, -999, -999, -999},
  116302. {-999, -999, -999, -999, -999, -999, -999, -999,
  116303. -999, -108, -103, -98, -93, -86, -79, -71,
  116304. -77, -74, -77, -79, -81, -84, -85, -90,
  116305. -92, -93, -92, -98, -101, -108, -112, -999,
  116306. -999, -999, -999, -999, -999, -999, -999, -999,
  116307. -999, -999, -999, -999, -999, -999, -999, -999,
  116308. -999, -999, -999, -999, -999, -999, -999, -999},
  116309. {-999, -999, -999, -999, -999, -999, -999, -999,
  116310. -108, -103, -98, -93, -87, -78, -68, -65,
  116311. -66, -62, -65, -67, -70, -73, -75, -78,
  116312. -82, -82, -83, -84, -91, -93, -98, -102,
  116313. -106, -110, -999, -999, -999, -999, -999, -999,
  116314. -999, -999, -999, -999, -999, -999, -999, -999,
  116315. -999, -999, -999, -999, -999, -999, -999, -999},
  116316. {-999, -999, -999, -999, -999, -999, -999, -999,
  116317. -105, -100, -95, -90, -82, -74, -62, -57,
  116318. -58, -56, -51, -52, -52, -54, -54, -58,
  116319. -66, -59, -60, -63, -66, -69, -73, -79,
  116320. -83, -84, -80, -81, -81, -82, -88, -92,
  116321. -98, -105, -113, -999, -999, -999, -999, -999,
  116322. -999, -999, -999, -999, -999, -999, -999, -999},
  116323. {-999, -999, -999, -999, -999, -999, -999, -107,
  116324. -102, -97, -92, -84, -79, -69, -57, -47,
  116325. -52, -47, -44, -45, -50, -52, -42, -42,
  116326. -53, -43, -43, -48, -51, -56, -55, -52,
  116327. -57, -59, -61, -62, -67, -71, -78, -83,
  116328. -86, -94, -98, -103, -110, -999, -999, -999,
  116329. -999, -999, -999, -999, -999, -999, -999, -999},
  116330. {-999, -999, -999, -999, -999, -999, -105, -100,
  116331. -95, -90, -84, -78, -70, -61, -51, -41,
  116332. -40, -38, -40, -46, -52, -51, -41, -40,
  116333. -46, -40, -38, -38, -41, -46, -41, -46,
  116334. -47, -43, -43, -45, -41, -45, -56, -67,
  116335. -68, -83, -87, -90, -95, -102, -107, -113,
  116336. -999, -999, -999, -999, -999, -999, -999, -999}},
  116337. /* 1000 Hz */
  116338. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116339. -999, -109, -105, -101, -96, -91, -84, -77,
  116340. -82, -82, -85, -89, -94, -100, -106, -110,
  116341. -999, -999, -999, -999, -999, -999, -999, -999,
  116342. -999, -999, -999, -999, -999, -999, -999, -999,
  116343. -999, -999, -999, -999, -999, -999, -999, -999,
  116344. -999, -999, -999, -999, -999, -999, -999, -999},
  116345. {-999, -999, -999, -999, -999, -999, -999, -999,
  116346. -999, -106, -103, -98, -92, -85, -80, -71,
  116347. -75, -72, -76, -80, -84, -86, -89, -93,
  116348. -100, -107, -113, -999, -999, -999, -999, -999,
  116349. -999, -999, -999, -999, -999, -999, -999, -999,
  116350. -999, -999, -999, -999, -999, -999, -999, -999,
  116351. -999, -999, -999, -999, -999, -999, -999, -999},
  116352. {-999, -999, -999, -999, -999, -999, -999, -107,
  116353. -104, -101, -97, -92, -88, -84, -80, -64,
  116354. -66, -63, -64, -66, -69, -73, -77, -83,
  116355. -83, -86, -91, -98, -104, -111, -999, -999,
  116356. -999, -999, -999, -999, -999, -999, -999, -999,
  116357. -999, -999, -999, -999, -999, -999, -999, -999,
  116358. -999, -999, -999, -999, -999, -999, -999, -999},
  116359. {-999, -999, -999, -999, -999, -999, -999, -107,
  116360. -104, -101, -97, -92, -90, -84, -74, -57,
  116361. -58, -52, -55, -54, -50, -52, -50, -52,
  116362. -63, -62, -69, -76, -77, -78, -78, -79,
  116363. -82, -88, -94, -100, -106, -111, -999, -999,
  116364. -999, -999, -999, -999, -999, -999, -999, -999,
  116365. -999, -999, -999, -999, -999, -999, -999, -999},
  116366. {-999, -999, -999, -999, -999, -999, -106, -102,
  116367. -98, -95, -90, -85, -83, -78, -70, -50,
  116368. -50, -41, -44, -49, -47, -50, -50, -44,
  116369. -55, -46, -47, -48, -48, -54, -49, -49,
  116370. -58, -62, -71, -81, -87, -92, -97, -102,
  116371. -108, -114, -999, -999, -999, -999, -999, -999,
  116372. -999, -999, -999, -999, -999, -999, -999, -999},
  116373. {-999, -999, -999, -999, -999, -999, -106, -102,
  116374. -98, -95, -90, -85, -83, -78, -70, -45,
  116375. -43, -41, -47, -50, -51, -50, -49, -45,
  116376. -47, -41, -44, -41, -39, -43, -38, -37,
  116377. -40, -41, -44, -50, -58, -65, -73, -79,
  116378. -85, -92, -97, -101, -105, -109, -113, -999,
  116379. -999, -999, -999, -999, -999, -999, -999, -999}},
  116380. /* 1414 Hz */
  116381. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116382. -999, -999, -999, -107, -100, -95, -87, -81,
  116383. -85, -83, -88, -93, -100, -107, -114, -999,
  116384. -999, -999, -999, -999, -999, -999, -999, -999,
  116385. -999, -999, -999, -999, -999, -999, -999, -999,
  116386. -999, -999, -999, -999, -999, -999, -999, -999,
  116387. -999, -999, -999, -999, -999, -999, -999, -999},
  116388. {-999, -999, -999, -999, -999, -999, -999, -999,
  116389. -999, -999, -107, -101, -95, -88, -83, -76,
  116390. -73, -72, -79, -84, -90, -95, -100, -105,
  116391. -110, -115, -999, -999, -999, -999, -999, -999,
  116392. -999, -999, -999, -999, -999, -999, -999, -999,
  116393. -999, -999, -999, -999, -999, -999, -999, -999,
  116394. -999, -999, -999, -999, -999, -999, -999, -999},
  116395. {-999, -999, -999, -999, -999, -999, -999, -999,
  116396. -999, -999, -104, -98, -92, -87, -81, -70,
  116397. -65, -62, -67, -71, -74, -80, -85, -91,
  116398. -95, -99, -103, -108, -111, -114, -999, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999,
  116400. -999, -999, -999, -999, -999, -999, -999, -999,
  116401. -999, -999, -999, -999, -999, -999, -999, -999},
  116402. {-999, -999, -999, -999, -999, -999, -999, -999,
  116403. -999, -999, -103, -97, -90, -85, -76, -60,
  116404. -56, -54, -60, -62, -61, -56, -63, -65,
  116405. -73, -74, -77, -75, -78, -81, -86, -87,
  116406. -88, -91, -94, -98, -103, -110, -999, -999,
  116407. -999, -999, -999, -999, -999, -999, -999, -999,
  116408. -999, -999, -999, -999, -999, -999, -999, -999},
  116409. {-999, -999, -999, -999, -999, -999, -999, -105,
  116410. -100, -97, -92, -86, -81, -79, -70, -57,
  116411. -51, -47, -51, -58, -60, -56, -53, -50,
  116412. -58, -52, -50, -50, -53, -55, -64, -69,
  116413. -71, -85, -82, -78, -81, -85, -95, -102,
  116414. -112, -999, -999, -999, -999, -999, -999, -999,
  116415. -999, -999, -999, -999, -999, -999, -999, -999},
  116416. {-999, -999, -999, -999, -999, -999, -999, -105,
  116417. -100, -97, -92, -85, -83, -79, -72, -49,
  116418. -40, -43, -43, -54, -56, -51, -50, -40,
  116419. -43, -38, -36, -35, -37, -38, -37, -44,
  116420. -54, -60, -57, -60, -70, -75, -84, -92,
  116421. -103, -112, -999, -999, -999, -999, -999, -999,
  116422. -999, -999, -999, -999, -999, -999, -999, -999}},
  116423. /* 2000 Hz */
  116424. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -110, -102, -95, -89, -82,
  116426. -83, -84, -90, -92, -99, -107, -113, -999,
  116427. -999, -999, -999, -999, -999, -999, -999, -999,
  116428. -999, -999, -999, -999, -999, -999, -999, -999,
  116429. -999, -999, -999, -999, -999, -999, -999, -999,
  116430. -999, -999, -999, -999, -999, -999, -999, -999},
  116431. {-999, -999, -999, -999, -999, -999, -999, -999,
  116432. -999, -999, -107, -101, -95, -89, -83, -72,
  116433. -74, -78, -85, -88, -88, -90, -92, -98,
  116434. -105, -111, -999, -999, -999, -999, -999, -999,
  116435. -999, -999, -999, -999, -999, -999, -999, -999,
  116436. -999, -999, -999, -999, -999, -999, -999, -999,
  116437. -999, -999, -999, -999, -999, -999, -999, -999},
  116438. {-999, -999, -999, -999, -999, -999, -999, -999,
  116439. -999, -109, -103, -97, -93, -87, -81, -70,
  116440. -70, -67, -75, -73, -76, -79, -81, -83,
  116441. -88, -89, -97, -103, -110, -999, -999, -999,
  116442. -999, -999, -999, -999, -999, -999, -999, -999,
  116443. -999, -999, -999, -999, -999, -999, -999, -999,
  116444. -999, -999, -999, -999, -999, -999, -999, -999},
  116445. {-999, -999, -999, -999, -999, -999, -999, -999,
  116446. -999, -107, -100, -94, -88, -83, -75, -63,
  116447. -59, -59, -63, -66, -60, -62, -67, -67,
  116448. -77, -76, -81, -88, -86, -92, -96, -102,
  116449. -109, -116, -999, -999, -999, -999, -999, -999,
  116450. -999, -999, -999, -999, -999, -999, -999, -999,
  116451. -999, -999, -999, -999, -999, -999, -999, -999},
  116452. {-999, -999, -999, -999, -999, -999, -999, -999,
  116453. -999, -105, -98, -92, -86, -81, -73, -56,
  116454. -52, -47, -55, -60, -58, -52, -51, -45,
  116455. -49, -50, -53, -54, -61, -71, -70, -69,
  116456. -78, -79, -87, -90, -96, -104, -112, -999,
  116457. -999, -999, -999, -999, -999, -999, -999, -999,
  116458. -999, -999, -999, -999, -999, -999, -999, -999},
  116459. {-999, -999, -999, -999, -999, -999, -999, -999,
  116460. -999, -103, -96, -90, -86, -78, -70, -51,
  116461. -42, -47, -48, -55, -54, -54, -53, -42,
  116462. -35, -28, -33, -38, -37, -44, -47, -49,
  116463. -54, -63, -68, -78, -82, -89, -94, -99,
  116464. -104, -109, -114, -999, -999, -999, -999, -999,
  116465. -999, -999, -999, -999, -999, -999, -999, -999}},
  116466. /* 2828 Hz */
  116467. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -110, -100, -90, -79,
  116469. -85, -81, -82, -82, -89, -94, -99, -103,
  116470. -109, -115, -999, -999, -999, -999, -999, -999,
  116471. -999, -999, -999, -999, -999, -999, -999, -999,
  116472. -999, -999, -999, -999, -999, -999, -999, -999,
  116473. -999, -999, -999, -999, -999, -999, -999, -999},
  116474. {-999, -999, -999, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -105, -97, -85, -72,
  116476. -74, -70, -70, -70, -76, -85, -91, -93,
  116477. -97, -103, -109, -115, -999, -999, -999, -999,
  116478. -999, -999, -999, -999, -999, -999, -999, -999,
  116479. -999, -999, -999, -999, -999, -999, -999, -999,
  116480. -999, -999, -999, -999, -999, -999, -999, -999},
  116481. {-999, -999, -999, -999, -999, -999, -999, -999,
  116482. -999, -999, -999, -999, -112, -93, -81, -68,
  116483. -62, -60, -60, -57, -63, -70, -77, -82,
  116484. -90, -93, -98, -104, -109, -113, -999, -999,
  116485. -999, -999, -999, -999, -999, -999, -999, -999,
  116486. -999, -999, -999, -999, -999, -999, -999, -999,
  116487. -999, -999, -999, -999, -999, -999, -999, -999},
  116488. {-999, -999, -999, -999, -999, -999, -999, -999,
  116489. -999, -999, -999, -113, -100, -93, -84, -63,
  116490. -58, -48, -53, -54, -52, -52, -57, -64,
  116491. -66, -76, -83, -81, -85, -85, -90, -95,
  116492. -98, -101, -103, -106, -108, -111, -999, -999,
  116493. -999, -999, -999, -999, -999, -999, -999, -999,
  116494. -999, -999, -999, -999, -999, -999, -999, -999},
  116495. {-999, -999, -999, -999, -999, -999, -999, -999,
  116496. -999, -999, -999, -105, -95, -86, -74, -53,
  116497. -50, -38, -43, -49, -43, -42, -39, -39,
  116498. -46, -52, -57, -56, -72, -69, -74, -81,
  116499. -87, -92, -94, -97, -99, -102, -105, -108,
  116500. -999, -999, -999, -999, -999, -999, -999, -999,
  116501. -999, -999, -999, -999, -999, -999, -999, -999},
  116502. {-999, -999, -999, -999, -999, -999, -999, -999,
  116503. -999, -999, -108, -99, -90, -76, -66, -45,
  116504. -43, -41, -44, -47, -43, -47, -40, -30,
  116505. -31, -31, -39, -33, -40, -41, -43, -53,
  116506. -59, -70, -73, -77, -79, -82, -84, -87,
  116507. -999, -999, -999, -999, -999, -999, -999, -999,
  116508. -999, -999, -999, -999, -999, -999, -999, -999}},
  116509. /* 4000 Hz */
  116510. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -110, -91, -76,
  116512. -75, -85, -93, -98, -104, -110, -999, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999,
  116514. -999, -999, -999, -999, -999, -999, -999, -999,
  116515. -999, -999, -999, -999, -999, -999, -999, -999,
  116516. -999, -999, -999, -999, -999, -999, -999, -999},
  116517. {-999, -999, -999, -999, -999, -999, -999, -999,
  116518. -999, -999, -999, -999, -999, -110, -91, -70,
  116519. -70, -75, -86, -89, -94, -98, -101, -106,
  116520. -110, -999, -999, -999, -999, -999, -999, -999,
  116521. -999, -999, -999, -999, -999, -999, -999, -999,
  116522. -999, -999, -999, -999, -999, -999, -999, -999,
  116523. -999, -999, -999, -999, -999, -999, -999, -999},
  116524. {-999, -999, -999, -999, -999, -999, -999, -999,
  116525. -999, -999, -999, -999, -110, -95, -80, -60,
  116526. -65, -64, -74, -83, -88, -91, -95, -99,
  116527. -103, -107, -110, -999, -999, -999, -999, -999,
  116528. -999, -999, -999, -999, -999, -999, -999, -999,
  116529. -999, -999, -999, -999, -999, -999, -999, -999,
  116530. -999, -999, -999, -999, -999, -999, -999, -999},
  116531. {-999, -999, -999, -999, -999, -999, -999, -999,
  116532. -999, -999, -999, -999, -110, -95, -80, -58,
  116533. -55, -49, -66, -68, -71, -78, -78, -80,
  116534. -88, -85, -89, -97, -100, -105, -110, -999,
  116535. -999, -999, -999, -999, -999, -999, -999, -999,
  116536. -999, -999, -999, -999, -999, -999, -999, -999,
  116537. -999, -999, -999, -999, -999, -999, -999, -999},
  116538. {-999, -999, -999, -999, -999, -999, -999, -999,
  116539. -999, -999, -999, -999, -110, -95, -80, -53,
  116540. -52, -41, -59, -59, -49, -58, -56, -63,
  116541. -86, -79, -90, -93, -98, -103, -107, -112,
  116542. -999, -999, -999, -999, -999, -999, -999, -999,
  116543. -999, -999, -999, -999, -999, -999, -999, -999,
  116544. -999, -999, -999, -999, -999, -999, -999, -999},
  116545. {-999, -999, -999, -999, -999, -999, -999, -999,
  116546. -999, -999, -999, -110, -97, -91, -73, -45,
  116547. -40, -33, -53, -61, -49, -54, -50, -50,
  116548. -60, -52, -67, -74, -81, -92, -96, -100,
  116549. -105, -110, -999, -999, -999, -999, -999, -999,
  116550. -999, -999, -999, -999, -999, -999, -999, -999,
  116551. -999, -999, -999, -999, -999, -999, -999, -999}},
  116552. /* 5657 Hz */
  116553. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116554. -999, -999, -999, -113, -106, -99, -92, -77,
  116555. -80, -88, -97, -106, -115, -999, -999, -999,
  116556. -999, -999, -999, -999, -999, -999, -999, -999,
  116557. -999, -999, -999, -999, -999, -999, -999, -999,
  116558. -999, -999, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -999, -999, -999, -999, -999, -999},
  116560. {-999, -999, -999, -999, -999, -999, -999, -999,
  116561. -999, -999, -116, -109, -102, -95, -89, -74,
  116562. -72, -88, -87, -95, -102, -109, -116, -999,
  116563. -999, -999, -999, -999, -999, -999, -999, -999,
  116564. -999, -999, -999, -999, -999, -999, -999, -999,
  116565. -999, -999, -999, -999, -999, -999, -999, -999,
  116566. -999, -999, -999, -999, -999, -999, -999, -999},
  116567. {-999, -999, -999, -999, -999, -999, -999, -999,
  116568. -999, -999, -116, -109, -102, -95, -89, -75,
  116569. -66, -74, -77, -78, -86, -87, -90, -96,
  116570. -105, -115, -999, -999, -999, -999, -999, -999,
  116571. -999, -999, -999, -999, -999, -999, -999, -999,
  116572. -999, -999, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -999, -999, -999, -999, -999},
  116574. {-999, -999, -999, -999, -999, -999, -999, -999,
  116575. -999, -999, -115, -108, -101, -94, -88, -66,
  116576. -56, -61, -70, -65, -78, -72, -83, -84,
  116577. -93, -98, -105, -110, -999, -999, -999, -999,
  116578. -999, -999, -999, -999, -999, -999, -999, -999,
  116579. -999, -999, -999, -999, -999, -999, -999, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999},
  116581. {-999, -999, -999, -999, -999, -999, -999, -999,
  116582. -999, -999, -110, -105, -95, -89, -82, -57,
  116583. -52, -52, -59, -56, -59, -58, -69, -67,
  116584. -88, -82, -82, -89, -94, -100, -108, -999,
  116585. -999, -999, -999, -999, -999, -999, -999, -999,
  116586. -999, -999, -999, -999, -999, -999, -999, -999,
  116587. -999, -999, -999, -999, -999, -999, -999, -999},
  116588. {-999, -999, -999, -999, -999, -999, -999, -999,
  116589. -999, -110, -101, -96, -90, -83, -77, -54,
  116590. -43, -38, -50, -48, -52, -48, -42, -42,
  116591. -51, -52, -53, -59, -65, -71, -78, -85,
  116592. -95, -999, -999, -999, -999, -999, -999, -999,
  116593. -999, -999, -999, -999, -999, -999, -999, -999,
  116594. -999, -999, -999, -999, -999, -999, -999, -999}},
  116595. /* 8000 Hz */
  116596. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116597. -999, -999, -999, -999, -120, -105, -86, -68,
  116598. -78, -79, -90, -100, -110, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999,
  116600. -999, -999, -999, -999, -999, -999, -999, -999,
  116601. -999, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -999, -999, -999, -999, -999},
  116603. {-999, -999, -999, -999, -999, -999, -999, -999,
  116604. -999, -999, -999, -999, -120, -105, -86, -66,
  116605. -73, -77, -88, -96, -105, -115, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999,
  116607. -999, -999, -999, -999, -999, -999, -999, -999,
  116608. -999, -999, -999, -999, -999, -999, -999, -999,
  116609. -999, -999, -999, -999, -999, -999, -999, -999},
  116610. {-999, -999, -999, -999, -999, -999, -999, -999,
  116611. -999, -999, -999, -120, -105, -92, -80, -61,
  116612. -64, -68, -80, -87, -92, -100, -110, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999,
  116614. -999, -999, -999, -999, -999, -999, -999, -999,
  116615. -999, -999, -999, -999, -999, -999, -999, -999,
  116616. -999, -999, -999, -999, -999, -999, -999, -999},
  116617. {-999, -999, -999, -999, -999, -999, -999, -999,
  116618. -999, -999, -999, -120, -104, -91, -79, -52,
  116619. -60, -54, -64, -69, -77, -80, -82, -84,
  116620. -85, -87, -88, -90, -999, -999, -999, -999,
  116621. -999, -999, -999, -999, -999, -999, -999, -999,
  116622. -999, -999, -999, -999, -999, -999, -999, -999,
  116623. -999, -999, -999, -999, -999, -999, -999, -999},
  116624. {-999, -999, -999, -999, -999, -999, -999, -999,
  116625. -999, -999, -999, -118, -100, -87, -77, -49,
  116626. -50, -44, -58, -61, -61, -67, -65, -62,
  116627. -62, -62, -65, -68, -999, -999, -999, -999,
  116628. -999, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999,
  116630. -999, -999, -999, -999, -999, -999, -999, -999},
  116631. {-999, -999, -999, -999, -999, -999, -999, -999,
  116632. -999, -999, -999, -115, -98, -84, -62, -49,
  116633. -44, -38, -46, -49, -49, -46, -39, -37,
  116634. -39, -40, -42, -43, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999,
  116636. -999, -999, -999, -999, -999, -999, -999, -999,
  116637. -999, -999, -999, -999, -999, -999, -999, -999}},
  116638. /* 11314 Hz */
  116639. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -110, -88, -74,
  116641. -77, -82, -82, -85, -90, -94, -99, -104,
  116642. -999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -999, -999, -999, -999, -999, -999, -999,
  116644. -999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -999, -999, -999, -999, -999, -999, -999},
  116646. {-999, -999, -999, -999, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -110, -88, -66,
  116648. -70, -81, -80, -81, -84, -88, -91, -93,
  116649. -999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -999, -999, -999, -999, -999, -999, -999,
  116651. -999, -999, -999, -999, -999, -999, -999, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999},
  116653. {-999, -999, -999, -999, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -110, -88, -61,
  116655. -63, -70, -71, -74, -77, -80, -83, -85,
  116656. -999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -999, -999, -999, -999, -999, -999, -999,
  116658. -999, -999, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -999, -999, -999},
  116660. {-999, -999, -999, -999, -999, -999, -999, -999,
  116661. -999, -999, -999, -999, -999, -110, -86, -62,
  116662. -63, -62, -62, -58, -52, -50, -50, -52,
  116663. -54, -999, -999, -999, -999, -999, -999, -999,
  116664. -999, -999, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -999, -999, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -999, -999, -999},
  116667. {-999, -999, -999, -999, -999, -999, -999, -999,
  116668. -999, -999, -999, -999, -118, -108, -84, -53,
  116669. -50, -50, -50, -55, -47, -45, -40, -40,
  116670. -40, -999, -999, -999, -999, -999, -999, -999,
  116671. -999, -999, -999, -999, -999, -999, -999, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999,
  116673. -999, -999, -999, -999, -999, -999, -999, -999},
  116674. {-999, -999, -999, -999, -999, -999, -999, -999,
  116675. -999, -999, -999, -999, -118, -100, -73, -43,
  116676. -37, -42, -43, -53, -38, -37, -35, -35,
  116677. -38, -999, -999, -999, -999, -999, -999, -999,
  116678. -999, -999, -999, -999, -999, -999, -999, -999,
  116679. -999, -999, -999, -999, -999, -999, -999, -999,
  116680. -999, -999, -999, -999, -999, -999, -999, -999}},
  116681. /* 16000 Hz */
  116682. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -110, -100, -91, -84, -74,
  116684. -80, -80, -80, -80, -80, -999, -999, -999,
  116685. -999, -999, -999, -999, -999, -999, -999, -999,
  116686. -999, -999, -999, -999, -999, -999, -999, -999,
  116687. -999, -999, -999, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -999, -999, -999, -999, -999},
  116689. {-999, -999, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -110, -100, -91, -84, -74,
  116691. -68, -68, -68, -68, -68, -999, -999, -999,
  116692. -999, -999, -999, -999, -999, -999, -999, -999,
  116693. -999, -999, -999, -999, -999, -999, -999, -999,
  116694. -999, -999, -999, -999, -999, -999, -999, -999,
  116695. -999, -999, -999, -999, -999, -999, -999, -999},
  116696. {-999, -999, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -110, -100, -86, -78, -70,
  116698. -60, -45, -30, -21, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999,
  116700. -999, -999, -999, -999, -999, -999, -999, -999,
  116701. -999, -999, -999, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999},
  116703. {-999, -999, -999, -999, -999, -999, -999, -999,
  116704. -999, -999, -999, -110, -100, -87, -78, -67,
  116705. -48, -38, -29, -21, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999,
  116707. -999, -999, -999, -999, -999, -999, -999, -999,
  116708. -999, -999, -999, -999, -999, -999, -999, -999,
  116709. -999, -999, -999, -999, -999, -999, -999, -999},
  116710. {-999, -999, -999, -999, -999, -999, -999, -999,
  116711. -999, -999, -999, -110, -100, -86, -69, -56,
  116712. -45, -35, -33, -29, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999,
  116714. -999, -999, -999, -999, -999, -999, -999, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999,
  116716. -999, -999, -999, -999, -999, -999, -999, -999},
  116717. {-999, -999, -999, -999, -999, -999, -999, -999,
  116718. -999, -999, -999, -110, -100, -83, -71, -48,
  116719. -27, -38, -37, -34, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -999, -999, -999, -999, -999, -999, -999,
  116722. -999, -999, -999, -999, -999, -999, -999, -999,
  116723. -999, -999, -999, -999, -999, -999, -999, -999}}
  116724. };
  116725. #endif
  116726. /*** End of inlined file: masking.h ***/
  116727. #define NEGINF -9999.f
  116728. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116729. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116730. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116731. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116732. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116733. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116734. look->channels=vi->channels;
  116735. look->ampmax=-9999.;
  116736. look->gi=gi;
  116737. return(look);
  116738. }
  116739. void _vp_global_free(vorbis_look_psy_global *look){
  116740. if(look){
  116741. memset(look,0,sizeof(*look));
  116742. _ogg_free(look);
  116743. }
  116744. }
  116745. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116746. if(i){
  116747. memset(i,0,sizeof(*i));
  116748. _ogg_free(i);
  116749. }
  116750. }
  116751. void _vi_psy_free(vorbis_info_psy *i){
  116752. if(i){
  116753. memset(i,0,sizeof(*i));
  116754. _ogg_free(i);
  116755. }
  116756. }
  116757. static void min_curve(float *c,
  116758. float *c2){
  116759. int i;
  116760. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116761. }
  116762. static void max_curve(float *c,
  116763. float *c2){
  116764. int i;
  116765. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116766. }
  116767. static void attenuate_curve(float *c,float att){
  116768. int i;
  116769. for(i=0;i<EHMER_MAX;i++)
  116770. c[i]+=att;
  116771. }
  116772. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116773. float center_boost, float center_decay_rate){
  116774. int i,j,k,m;
  116775. float ath[EHMER_MAX];
  116776. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116777. float athc[P_LEVELS][EHMER_MAX];
  116778. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116779. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116780. memset(workc,0,sizeof(workc));
  116781. for(i=0;i<P_BANDS;i++){
  116782. /* we add back in the ATH to avoid low level curves falling off to
  116783. -infinity and unnecessarily cutting off high level curves in the
  116784. curve limiting (last step). */
  116785. /* A half-band's settings must be valid over the whole band, and
  116786. it's better to mask too little than too much */
  116787. int ath_offset=i*4;
  116788. for(j=0;j<EHMER_MAX;j++){
  116789. float min=999.;
  116790. for(k=0;k<4;k++)
  116791. if(j+k+ath_offset<MAX_ATH){
  116792. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116793. }else{
  116794. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116795. }
  116796. ath[j]=min;
  116797. }
  116798. /* copy curves into working space, replicate the 50dB curve to 30
  116799. and 40, replicate the 100dB curve to 110 */
  116800. for(j=0;j<6;j++)
  116801. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116802. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116803. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116804. /* apply centered curve boost/decay */
  116805. for(j=0;j<P_LEVELS;j++){
  116806. for(k=0;k<EHMER_MAX;k++){
  116807. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116808. if(adj<0. && center_boost>0)adj=0.;
  116809. if(adj>0. && center_boost<0)adj=0.;
  116810. workc[i][j][k]+=adj;
  116811. }
  116812. }
  116813. /* normalize curves so the driving amplitude is 0dB */
  116814. /* make temp curves with the ATH overlayed */
  116815. for(j=0;j<P_LEVELS;j++){
  116816. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116817. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116818. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116819. max_curve(athc[j],workc[i][j]);
  116820. }
  116821. /* Now limit the louder curves.
  116822. the idea is this: We don't know what the playback attenuation
  116823. will be; 0dB SL moves every time the user twiddles the volume
  116824. knob. So that means we have to use a single 'most pessimal' curve
  116825. for all masking amplitudes, right? Wrong. The *loudest* sound
  116826. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116827. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116828. etc... */
  116829. for(j=1;j<P_LEVELS;j++){
  116830. min_curve(athc[j],athc[j-1]);
  116831. min_curve(workc[i][j],athc[j]);
  116832. }
  116833. }
  116834. for(i=0;i<P_BANDS;i++){
  116835. int hi_curve,lo_curve,bin;
  116836. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116837. /* low frequency curves are measured with greater resolution than
  116838. the MDCT/FFT will actually give us; we want the curve applied
  116839. to the tone data to be pessimistic and thus apply the minimum
  116840. masking possible for a given bin. That means that a single bin
  116841. could span more than one octave and that the curve will be a
  116842. composite of multiple octaves. It also may mean that a single
  116843. bin may span > an eighth of an octave and that the eighth
  116844. octave values may also be composited. */
  116845. /* which octave curves will we be compositing? */
  116846. bin=floor(fromOC(i*.5)/binHz);
  116847. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116848. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116849. if(lo_curve>i)lo_curve=i;
  116850. if(lo_curve<0)lo_curve=0;
  116851. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116852. for(m=0;m<P_LEVELS;m++){
  116853. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116854. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116855. /* render the curve into bins, then pull values back into curve.
  116856. The point is that any inherent subsampling aliasing results in
  116857. a safe minimum */
  116858. for(k=lo_curve;k<=hi_curve;k++){
  116859. int l=0;
  116860. for(j=0;j<EHMER_MAX;j++){
  116861. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116862. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116863. if(lo_bin<0)lo_bin=0;
  116864. if(lo_bin>n)lo_bin=n;
  116865. if(lo_bin<l)l=lo_bin;
  116866. if(hi_bin<0)hi_bin=0;
  116867. if(hi_bin>n)hi_bin=n;
  116868. for(;l<hi_bin && l<n;l++)
  116869. if(brute_buffer[l]>workc[k][m][j])
  116870. brute_buffer[l]=workc[k][m][j];
  116871. }
  116872. for(;l<n;l++)
  116873. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116874. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116875. }
  116876. /* be equally paranoid about being valid up to next half ocatve */
  116877. if(i+1<P_BANDS){
  116878. int l=0;
  116879. k=i+1;
  116880. for(j=0;j<EHMER_MAX;j++){
  116881. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116882. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116883. if(lo_bin<0)lo_bin=0;
  116884. if(lo_bin>n)lo_bin=n;
  116885. if(lo_bin<l)l=lo_bin;
  116886. if(hi_bin<0)hi_bin=0;
  116887. if(hi_bin>n)hi_bin=n;
  116888. for(;l<hi_bin && l<n;l++)
  116889. if(brute_buffer[l]>workc[k][m][j])
  116890. brute_buffer[l]=workc[k][m][j];
  116891. }
  116892. for(;l<n;l++)
  116893. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116894. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116895. }
  116896. for(j=0;j<EHMER_MAX;j++){
  116897. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116898. if(bin<0){
  116899. ret[i][m][j+2]=-999.;
  116900. }else{
  116901. if(bin>=n){
  116902. ret[i][m][j+2]=-999.;
  116903. }else{
  116904. ret[i][m][j+2]=brute_buffer[bin];
  116905. }
  116906. }
  116907. }
  116908. /* add fenceposts */
  116909. for(j=0;j<EHMER_OFFSET;j++)
  116910. if(ret[i][m][j+2]>-200.f)break;
  116911. ret[i][m][0]=j;
  116912. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116913. if(ret[i][m][j+2]>-200.f)
  116914. break;
  116915. ret[i][m][1]=j;
  116916. }
  116917. }
  116918. return(ret);
  116919. }
  116920. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116921. vorbis_info_psy_global *gi,int n,long rate){
  116922. long i,j,lo=-99,hi=1;
  116923. long maxoc;
  116924. memset(p,0,sizeof(*p));
  116925. p->eighth_octave_lines=gi->eighth_octave_lines;
  116926. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116927. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116928. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116929. p->total_octave_lines=maxoc-p->firstoc+1;
  116930. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116931. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116932. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116933. p->vi=vi;
  116934. p->n=n;
  116935. p->rate=rate;
  116936. /* AoTuV HF weighting */
  116937. p->m_val = 1.;
  116938. if(rate < 26000) p->m_val = 0;
  116939. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116940. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116941. /* set up the lookups for a given blocksize and sample rate */
  116942. for(i=0,j=0;i<MAX_ATH-1;i++){
  116943. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  116944. float base=ATH[i];
  116945. if(j<endpos){
  116946. float delta=(ATH[i+1]-base)/(endpos-j);
  116947. for(;j<endpos && j<n;j++){
  116948. p->ath[j]=base+100.;
  116949. base+=delta;
  116950. }
  116951. }
  116952. }
  116953. for(i=0;i<n;i++){
  116954. float bark=toBARK(rate/(2*n)*i);
  116955. for(;lo+vi->noisewindowlomin<i &&
  116956. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  116957. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  116958. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  116959. p->bark[i]=((lo-1)<<16)+(hi-1);
  116960. }
  116961. for(i=0;i<n;i++)
  116962. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  116963. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  116964. vi->tone_centerboost,vi->tone_decay);
  116965. /* set up rolling noise median */
  116966. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  116967. for(i=0;i<P_NOISECURVES;i++)
  116968. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  116969. for(i=0;i<n;i++){
  116970. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  116971. int inthalfoc;
  116972. float del;
  116973. if(halfoc<0)halfoc=0;
  116974. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  116975. inthalfoc=(int)halfoc;
  116976. del=halfoc-inthalfoc;
  116977. for(j=0;j<P_NOISECURVES;j++)
  116978. p->noiseoffset[j][i]=
  116979. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  116980. p->vi->noiseoff[j][inthalfoc+1]*del;
  116981. }
  116982. #if 0
  116983. {
  116984. static int ls=0;
  116985. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  116986. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  116987. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  116988. }
  116989. #endif
  116990. }
  116991. void _vp_psy_clear(vorbis_look_psy *p){
  116992. int i,j;
  116993. if(p){
  116994. if(p->ath)_ogg_free(p->ath);
  116995. if(p->octave)_ogg_free(p->octave);
  116996. if(p->bark)_ogg_free(p->bark);
  116997. if(p->tonecurves){
  116998. for(i=0;i<P_BANDS;i++){
  116999. for(j=0;j<P_LEVELS;j++){
  117000. _ogg_free(p->tonecurves[i][j]);
  117001. }
  117002. _ogg_free(p->tonecurves[i]);
  117003. }
  117004. _ogg_free(p->tonecurves);
  117005. }
  117006. if(p->noiseoffset){
  117007. for(i=0;i<P_NOISECURVES;i++){
  117008. _ogg_free(p->noiseoffset[i]);
  117009. }
  117010. _ogg_free(p->noiseoffset);
  117011. }
  117012. memset(p,0,sizeof(*p));
  117013. }
  117014. }
  117015. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117016. static void seed_curve(float *seed,
  117017. const float **curves,
  117018. float amp,
  117019. int oc, int n,
  117020. int linesper,float dBoffset){
  117021. int i,post1;
  117022. int seedptr;
  117023. const float *posts,*curve;
  117024. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117025. choice=max(choice,0);
  117026. choice=min(choice,P_LEVELS-1);
  117027. posts=curves[choice];
  117028. curve=posts+2;
  117029. post1=(int)posts[1];
  117030. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117031. for(i=posts[0];i<post1;i++){
  117032. if(seedptr>0){
  117033. float lin=amp+curve[i];
  117034. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117035. }
  117036. seedptr+=linesper;
  117037. if(seedptr>=n)break;
  117038. }
  117039. }
  117040. static void seed_loop(vorbis_look_psy *p,
  117041. const float ***curves,
  117042. const float *f,
  117043. const float *flr,
  117044. float *seed,
  117045. float specmax){
  117046. vorbis_info_psy *vi=p->vi;
  117047. long n=p->n,i;
  117048. float dBoffset=vi->max_curve_dB-specmax;
  117049. /* prime the working vector with peak values */
  117050. for(i=0;i<n;i++){
  117051. float max=f[i];
  117052. long oc=p->octave[i];
  117053. while(i+1<n && p->octave[i+1]==oc){
  117054. i++;
  117055. if(f[i]>max)max=f[i];
  117056. }
  117057. if(max+6.f>flr[i]){
  117058. oc=oc>>p->shiftoc;
  117059. if(oc>=P_BANDS)oc=P_BANDS-1;
  117060. if(oc<0)oc=0;
  117061. seed_curve(seed,
  117062. curves[oc],
  117063. max,
  117064. p->octave[i]-p->firstoc,
  117065. p->total_octave_lines,
  117066. p->eighth_octave_lines,
  117067. dBoffset);
  117068. }
  117069. }
  117070. }
  117071. static void seed_chase(float *seeds, int linesper, long n){
  117072. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117073. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117074. long stack=0;
  117075. long pos=0;
  117076. long i;
  117077. for(i=0;i<n;i++){
  117078. if(stack<2){
  117079. posstack[stack]=i;
  117080. ampstack[stack++]=seeds[i];
  117081. }else{
  117082. while(1){
  117083. if(seeds[i]<ampstack[stack-1]){
  117084. posstack[stack]=i;
  117085. ampstack[stack++]=seeds[i];
  117086. break;
  117087. }else{
  117088. if(i<posstack[stack-1]+linesper){
  117089. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117090. i<posstack[stack-2]+linesper){
  117091. /* we completely overlap, making stack-1 irrelevant. pop it */
  117092. stack--;
  117093. continue;
  117094. }
  117095. }
  117096. posstack[stack]=i;
  117097. ampstack[stack++]=seeds[i];
  117098. break;
  117099. }
  117100. }
  117101. }
  117102. }
  117103. /* the stack now contains only the positions that are relevant. Scan
  117104. 'em straight through */
  117105. for(i=0;i<stack;i++){
  117106. long endpos;
  117107. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117108. endpos=posstack[i+1];
  117109. }else{
  117110. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117111. discarded in short frames */
  117112. }
  117113. if(endpos>n)endpos=n;
  117114. for(;pos<endpos;pos++)
  117115. seeds[pos]=ampstack[i];
  117116. }
  117117. /* there. Linear time. I now remember this was on a problem set I
  117118. had in Grad Skool... I didn't solve it at the time ;-) */
  117119. }
  117120. /* bleaugh, this is more complicated than it needs to be */
  117121. #include<stdio.h>
  117122. static void max_seeds(vorbis_look_psy *p,
  117123. float *seed,
  117124. float *flr){
  117125. long n=p->total_octave_lines;
  117126. int linesper=p->eighth_octave_lines;
  117127. long linpos=0;
  117128. long pos;
  117129. seed_chase(seed,linesper,n); /* for masking */
  117130. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117131. while(linpos+1<p->n){
  117132. float minV=seed[pos];
  117133. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117134. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117135. while(pos+1<=end){
  117136. pos++;
  117137. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117138. minV=seed[pos];
  117139. }
  117140. end=pos+p->firstoc;
  117141. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117142. if(flr[linpos]<minV)flr[linpos]=minV;
  117143. }
  117144. {
  117145. float minV=seed[p->total_octave_lines-1];
  117146. for(;linpos<p->n;linpos++)
  117147. if(flr[linpos]<minV)flr[linpos]=minV;
  117148. }
  117149. }
  117150. static void bark_noise_hybridmp(int n,const long *b,
  117151. const float *f,
  117152. float *noise,
  117153. const float offset,
  117154. const int fixed){
  117155. float *N=(float*) alloca(n*sizeof(*N));
  117156. float *X=(float*) alloca(n*sizeof(*N));
  117157. float *XX=(float*) alloca(n*sizeof(*N));
  117158. float *Y=(float*) alloca(n*sizeof(*N));
  117159. float *XY=(float*) alloca(n*sizeof(*N));
  117160. float tN, tX, tXX, tY, tXY;
  117161. int i;
  117162. int lo, hi;
  117163. float R, A, B, D;
  117164. float w, x, y;
  117165. tN = tX = tXX = tY = tXY = 0.f;
  117166. y = f[0] + offset;
  117167. if (y < 1.f) y = 1.f;
  117168. w = y * y * .5;
  117169. tN += w;
  117170. tX += w;
  117171. tY += w * y;
  117172. N[0] = tN;
  117173. X[0] = tX;
  117174. XX[0] = tXX;
  117175. Y[0] = tY;
  117176. XY[0] = tXY;
  117177. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117178. y = f[i] + offset;
  117179. if (y < 1.f) y = 1.f;
  117180. w = y * y;
  117181. tN += w;
  117182. tX += w * x;
  117183. tXX += w * x * x;
  117184. tY += w * y;
  117185. tXY += w * x * y;
  117186. N[i] = tN;
  117187. X[i] = tX;
  117188. XX[i] = tXX;
  117189. Y[i] = tY;
  117190. XY[i] = tXY;
  117191. }
  117192. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117193. lo = b[i] >> 16;
  117194. if( lo>=0 ) break;
  117195. hi = b[i] & 0xffff;
  117196. tN = N[hi] + N[-lo];
  117197. tX = X[hi] - X[-lo];
  117198. tXX = XX[hi] + XX[-lo];
  117199. tY = Y[hi] + Y[-lo];
  117200. tXY = XY[hi] - XY[-lo];
  117201. A = tY * tXX - tX * tXY;
  117202. B = tN * tXY - tX * tY;
  117203. D = tN * tXX - tX * tX;
  117204. R = (A + x * B) / D;
  117205. if (R < 0.f)
  117206. R = 0.f;
  117207. noise[i] = R - offset;
  117208. }
  117209. for ( ;; i++, x += 1.f) {
  117210. lo = b[i] >> 16;
  117211. hi = b[i] & 0xffff;
  117212. if(hi>=n)break;
  117213. tN = N[hi] - N[lo];
  117214. tX = X[hi] - X[lo];
  117215. tXX = XX[hi] - XX[lo];
  117216. tY = Y[hi] - Y[lo];
  117217. tXY = XY[hi] - XY[lo];
  117218. A = tY * tXX - tX * tXY;
  117219. B = tN * tXY - tX * tY;
  117220. D = tN * tXX - tX * tX;
  117221. R = (A + x * B) / D;
  117222. if (R < 0.f) R = 0.f;
  117223. noise[i] = R - offset;
  117224. }
  117225. for ( ; i < n; i++, x += 1.f) {
  117226. R = (A + x * B) / D;
  117227. if (R < 0.f) R = 0.f;
  117228. noise[i] = R - offset;
  117229. }
  117230. if (fixed <= 0) return;
  117231. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117232. hi = i + fixed / 2;
  117233. lo = hi - fixed;
  117234. if(lo>=0)break;
  117235. tN = N[hi] + N[-lo];
  117236. tX = X[hi] - X[-lo];
  117237. tXX = XX[hi] + XX[-lo];
  117238. tY = Y[hi] + Y[-lo];
  117239. tXY = XY[hi] - XY[-lo];
  117240. A = tY * tXX - tX * tXY;
  117241. B = tN * tXY - tX * tY;
  117242. D = tN * tXX - tX * tX;
  117243. R = (A + x * B) / D;
  117244. if (R - offset < noise[i]) noise[i] = R - offset;
  117245. }
  117246. for ( ;; i++, x += 1.f) {
  117247. hi = i + fixed / 2;
  117248. lo = hi - fixed;
  117249. if(hi>=n)break;
  117250. tN = N[hi] - N[lo];
  117251. tX = X[hi] - X[lo];
  117252. tXX = XX[hi] - XX[lo];
  117253. tY = Y[hi] - Y[lo];
  117254. tXY = XY[hi] - XY[lo];
  117255. A = tY * tXX - tX * tXY;
  117256. B = tN * tXY - tX * tY;
  117257. D = tN * tXX - tX * tX;
  117258. R = (A + x * B) / D;
  117259. if (R - offset < noise[i]) noise[i] = R - offset;
  117260. }
  117261. for ( ; i < n; i++, x += 1.f) {
  117262. R = (A + x * B) / D;
  117263. if (R - offset < noise[i]) noise[i] = R - offset;
  117264. }
  117265. }
  117266. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117267. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117268. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117269. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117270. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117271. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117272. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117273. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117274. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117275. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117276. 973377.F, 913981.F, 858210.F, 805842.F,
  117277. 756669.F, 710497.F, 667142.F, 626433.F,
  117278. 588208.F, 552316.F, 518613.F, 486967.F,
  117279. 457252.F, 429351.F, 403152.F, 378551.F,
  117280. 355452.F, 333762.F, 313396.F, 294273.F,
  117281. 276316.F, 259455.F, 243623.F, 228757.F,
  117282. 214798.F, 201691.F, 189384.F, 177828.F,
  117283. 166977.F, 156788.F, 147221.F, 138237.F,
  117284. 129802.F, 121881.F, 114444.F, 107461.F,
  117285. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117286. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117287. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117288. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117289. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117290. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117291. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117292. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117293. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117294. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117295. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117296. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117297. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117298. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117299. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117300. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117301. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117302. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117303. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117304. 842.910F, 791.475F, 743.179F, 697.830F,
  117305. 655.249F, 615.265F, 577.722F, 542.469F,
  117306. 509.367F, 478.286F, 449.101F, 421.696F,
  117307. 395.964F, 371.803F, 349.115F, 327.812F,
  117308. 307.809F, 289.026F, 271.390F, 254.830F,
  117309. 239.280F, 224.679F, 210.969F, 198.096F,
  117310. 186.008F, 174.658F, 164.000F, 153.993F,
  117311. 144.596F, 135.773F, 127.488F, 119.708F,
  117312. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117313. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117314. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117315. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117316. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117317. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117318. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117319. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117320. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117321. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117322. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117323. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117324. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117325. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117326. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117327. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117328. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117329. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117330. 1.20790F, 1.13419F, 1.06499F, 1.F
  117331. };
  117332. void _vp_remove_floor(vorbis_look_psy *p,
  117333. float *mdct,
  117334. int *codedflr,
  117335. float *residue,
  117336. int sliding_lowpass){
  117337. int i,n=p->n;
  117338. if(sliding_lowpass>n)sliding_lowpass=n;
  117339. for(i=0;i<sliding_lowpass;i++){
  117340. residue[i]=
  117341. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117342. }
  117343. for(;i<n;i++)
  117344. residue[i]=0.;
  117345. }
  117346. void _vp_noisemask(vorbis_look_psy *p,
  117347. float *logmdct,
  117348. float *logmask){
  117349. int i,n=p->n;
  117350. float *work=(float*) alloca(n*sizeof(*work));
  117351. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117352. 140.,-1);
  117353. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117354. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117355. p->vi->noisewindowfixed);
  117356. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117357. #if 0
  117358. {
  117359. static int seq=0;
  117360. float work2[n];
  117361. for(i=0;i<n;i++){
  117362. work2[i]=logmask[i]+work[i];
  117363. }
  117364. if(seq&1)
  117365. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117366. else
  117367. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117368. if(seq&1)
  117369. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117370. else
  117371. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117372. seq++;
  117373. }
  117374. #endif
  117375. for(i=0;i<n;i++){
  117376. int dB=logmask[i]+.5;
  117377. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117378. if(dB<0)dB=0;
  117379. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117380. }
  117381. }
  117382. void _vp_tonemask(vorbis_look_psy *p,
  117383. float *logfft,
  117384. float *logmask,
  117385. float global_specmax,
  117386. float local_specmax){
  117387. int i,n=p->n;
  117388. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117389. float att=local_specmax+p->vi->ath_adjatt;
  117390. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117391. /* set the ATH (floating below localmax, not global max by a
  117392. specified att) */
  117393. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117394. for(i=0;i<n;i++)
  117395. logmask[i]=p->ath[i]+att;
  117396. /* tone masking */
  117397. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117398. max_seeds(p,seed,logmask);
  117399. }
  117400. void _vp_offset_and_mix(vorbis_look_psy *p,
  117401. float *noise,
  117402. float *tone,
  117403. int offset_select,
  117404. float *logmask,
  117405. float *mdct,
  117406. float *logmdct){
  117407. int i,n=p->n;
  117408. float de, coeffi, cx;/* AoTuV */
  117409. float toneatt=p->vi->tone_masteratt[offset_select];
  117410. cx = p->m_val;
  117411. for(i=0;i<n;i++){
  117412. float val= noise[i]+p->noiseoffset[offset_select][i];
  117413. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117414. logmask[i]=max(val,tone[i]+toneatt);
  117415. /* AoTuV */
  117416. /** @ M1 **
  117417. The following codes improve a noise problem.
  117418. A fundamental idea uses the value of masking and carries out
  117419. the relative compensation of the MDCT.
  117420. However, this code is not perfect and all noise problems cannot be solved.
  117421. by Aoyumi @ 2004/04/18
  117422. */
  117423. if(offset_select == 1) {
  117424. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117425. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117426. if(val > coeffi){
  117427. /* mdct value is > -17.2 dB below floor */
  117428. de = 1.0-((val-coeffi)*0.005*cx);
  117429. /* pro-rated attenuation:
  117430. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117431. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117432. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117433. etc... */
  117434. if(de < 0) de = 0.0001;
  117435. }else
  117436. /* mdct value is <= -17.2 dB below floor */
  117437. de = 1.0-((val-coeffi)*0.0003*cx);
  117438. /* pro-rated attenuation:
  117439. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117440. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117441. etc... */
  117442. mdct[i] *= de;
  117443. }
  117444. }
  117445. }
  117446. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117447. vorbis_info *vi=vd->vi;
  117448. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117449. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117450. int n=ci->blocksizes[vd->W]/2;
  117451. float secs=(float)n/vi->rate;
  117452. amp+=secs*gi->ampmax_att_per_sec;
  117453. if(amp<-9999)amp=-9999;
  117454. return(amp);
  117455. }
  117456. static void couple_lossless(float A, float B,
  117457. float *qA, float *qB){
  117458. int test1=fabs(*qA)>fabs(*qB);
  117459. test1-= fabs(*qA)<fabs(*qB);
  117460. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117461. if(test1==1){
  117462. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117463. }else{
  117464. float temp=*qB;
  117465. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117466. *qA=temp;
  117467. }
  117468. if(*qB>fabs(*qA)*1.9999f){
  117469. *qB= -fabs(*qA)*2.f;
  117470. *qA= -*qA;
  117471. }
  117472. }
  117473. static float hypot_lookup[32]={
  117474. -0.009935, -0.011245, -0.012726, -0.014397,
  117475. -0.016282, -0.018407, -0.020800, -0.023494,
  117476. -0.026522, -0.029923, -0.033737, -0.038010,
  117477. -0.042787, -0.048121, -0.054064, -0.060671,
  117478. -0.068000, -0.076109, -0.085054, -0.094892,
  117479. -0.105675, -0.117451, -0.130260, -0.144134,
  117480. -0.159093, -0.175146, -0.192286, -0.210490,
  117481. -0.229718, -0.249913, -0.271001, -0.292893};
  117482. static void precomputed_couple_point(float premag,
  117483. int floorA,int floorB,
  117484. float *mag, float *ang){
  117485. int test=(floorA>floorB)-1;
  117486. int offset=31-abs(floorA-floorB);
  117487. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117488. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117489. *mag=premag*floormag;
  117490. *ang=0.f;
  117491. }
  117492. /* just like below, this is currently set up to only do
  117493. single-step-depth coupling. Otherwise, we'd have to do more
  117494. copying (which will be inevitable later) */
  117495. /* doing the real circular magnitude calculation is audibly superior
  117496. to (A+B)/sqrt(2) */
  117497. static float dipole_hypot(float a, float b){
  117498. if(a>0.){
  117499. if(b>0.)return sqrt(a*a+b*b);
  117500. if(a>-b)return sqrt(a*a-b*b);
  117501. return -sqrt(b*b-a*a);
  117502. }
  117503. if(b<0.)return -sqrt(a*a+b*b);
  117504. if(-a>b)return -sqrt(a*a-b*b);
  117505. return sqrt(b*b-a*a);
  117506. }
  117507. static float round_hypot(float a, float b){
  117508. if(a>0.){
  117509. if(b>0.)return sqrt(a*a+b*b);
  117510. if(a>-b)return sqrt(a*a+b*b);
  117511. return -sqrt(b*b+a*a);
  117512. }
  117513. if(b<0.)return -sqrt(a*a+b*b);
  117514. if(-a>b)return -sqrt(a*a+b*b);
  117515. return sqrt(b*b+a*a);
  117516. }
  117517. /* revert to round hypot for now */
  117518. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117519. vorbis_info_psy_global *g,
  117520. vorbis_look_psy *p,
  117521. vorbis_info_mapping0 *vi,
  117522. float **mdct){
  117523. int i,j,n=p->n;
  117524. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117525. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117526. for(i=0;i<vi->coupling_steps;i++){
  117527. float *mdctM=mdct[vi->coupling_mag[i]];
  117528. float *mdctA=mdct[vi->coupling_ang[i]];
  117529. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117530. for(j=0;j<limit;j++)
  117531. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117532. for(;j<n;j++)
  117533. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117534. }
  117535. return(ret);
  117536. }
  117537. /* this is for per-channel noise normalization */
  117538. static int JUCE_CDECL apsort(const void *a, const void *b){
  117539. float f1=fabs(**(float**)a);
  117540. float f2=fabs(**(float**)b);
  117541. return (f1<f2)-(f1>f2);
  117542. }
  117543. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117544. vorbis_look_psy *p,
  117545. vorbis_info_mapping0 *vi,
  117546. float **mags){
  117547. if(p->vi->normal_point_p){
  117548. int i,j,k,n=p->n;
  117549. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117550. int partition=p->vi->normal_partition;
  117551. float **work=(float**) alloca(sizeof(*work)*partition);
  117552. for(i=0;i<vi->coupling_steps;i++){
  117553. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117554. for(j=0;j<n;j+=partition){
  117555. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117556. qsort(work,partition,sizeof(*work),apsort);
  117557. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117558. }
  117559. }
  117560. return(ret);
  117561. }
  117562. return(NULL);
  117563. }
  117564. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117565. float *magnitudes,int *sortedindex){
  117566. int i,j,n=p->n;
  117567. vorbis_info_psy *vi=p->vi;
  117568. int partition=vi->normal_partition;
  117569. float **work=(float**) alloca(sizeof(*work)*partition);
  117570. int start=vi->normal_start;
  117571. for(j=start;j<n;j+=partition){
  117572. if(j+partition>n)partition=n-j;
  117573. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117574. qsort(work,partition,sizeof(*work),apsort);
  117575. for(i=0;i<partition;i++){
  117576. sortedindex[i+j-start]=work[i]-magnitudes;
  117577. }
  117578. }
  117579. }
  117580. void _vp_noise_normalize(vorbis_look_psy *p,
  117581. float *in,float *out,int *sortedindex){
  117582. int flag=0,i,j=0,n=p->n;
  117583. vorbis_info_psy *vi=p->vi;
  117584. int partition=vi->normal_partition;
  117585. int start=vi->normal_start;
  117586. if(start>n)start=n;
  117587. if(vi->normal_channel_p){
  117588. for(;j<start;j++)
  117589. out[j]=rint(in[j]);
  117590. for(;j+partition<=n;j+=partition){
  117591. float acc=0.;
  117592. int k;
  117593. for(i=j;i<j+partition;i++)
  117594. acc+=in[i]*in[i];
  117595. for(i=0;i<partition;i++){
  117596. k=sortedindex[i+j-start];
  117597. if(in[k]*in[k]>=.25f){
  117598. out[k]=rint(in[k]);
  117599. acc-=in[k]*in[k];
  117600. flag=1;
  117601. }else{
  117602. if(acc<vi->normal_thresh)break;
  117603. out[k]=unitnorm(in[k]);
  117604. acc-=1.;
  117605. }
  117606. }
  117607. for(;i<partition;i++){
  117608. k=sortedindex[i+j-start];
  117609. out[k]=0.;
  117610. }
  117611. }
  117612. }
  117613. for(;j<n;j++)
  117614. out[j]=rint(in[j]);
  117615. }
  117616. void _vp_couple(int blobno,
  117617. vorbis_info_psy_global *g,
  117618. vorbis_look_psy *p,
  117619. vorbis_info_mapping0 *vi,
  117620. float **res,
  117621. float **mag_memo,
  117622. int **mag_sort,
  117623. int **ifloor,
  117624. int *nonzero,
  117625. int sliding_lowpass){
  117626. int i,j,k,n=p->n;
  117627. /* perform any requested channel coupling */
  117628. /* point stereo can only be used in a first stage (in this encoder)
  117629. because of the dependency on floor lookups */
  117630. for(i=0;i<vi->coupling_steps;i++){
  117631. /* once we're doing multistage coupling in which a channel goes
  117632. through more than one coupling step, the floor vector
  117633. magnitudes will also have to be recalculated an propogated
  117634. along with PCM. Right now, we're not (that will wait until 5.1
  117635. most likely), so the code isn't here yet. The memory management
  117636. here is all assuming single depth couplings anyway. */
  117637. /* make sure coupling a zero and a nonzero channel results in two
  117638. nonzero channels. */
  117639. if(nonzero[vi->coupling_mag[i]] ||
  117640. nonzero[vi->coupling_ang[i]]){
  117641. float *rM=res[vi->coupling_mag[i]];
  117642. float *rA=res[vi->coupling_ang[i]];
  117643. float *qM=rM+n;
  117644. float *qA=rA+n;
  117645. int *floorM=ifloor[vi->coupling_mag[i]];
  117646. int *floorA=ifloor[vi->coupling_ang[i]];
  117647. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117648. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117649. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117650. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117651. int pointlimit=limit;
  117652. nonzero[vi->coupling_mag[i]]=1;
  117653. nonzero[vi->coupling_ang[i]]=1;
  117654. /* The threshold of a stereo is changed with the size of n */
  117655. if(n > 1000)
  117656. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117657. for(j=0;j<p->n;j+=partition){
  117658. float acc=0.f;
  117659. for(k=0;k<partition;k++){
  117660. int l=k+j;
  117661. if(l<sliding_lowpass){
  117662. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117663. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117664. precomputed_couple_point(mag_memo[i][l],
  117665. floorM[l],floorA[l],
  117666. qM+l,qA+l);
  117667. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117668. }else{
  117669. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117670. }
  117671. }else{
  117672. qM[l]=0.;
  117673. qA[l]=0.;
  117674. }
  117675. }
  117676. if(p->vi->normal_point_p){
  117677. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117678. int l=mag_sort[i][j+k];
  117679. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117680. qM[l]=unitnorm(qM[l]);
  117681. acc-=1.f;
  117682. }
  117683. }
  117684. }
  117685. }
  117686. }
  117687. }
  117688. }
  117689. /* AoTuV */
  117690. /** @ M2 **
  117691. The boost problem by the combination of noise normalization and point stereo is eased.
  117692. However, this is a temporary patch.
  117693. by Aoyumi @ 2004/04/18
  117694. */
  117695. void hf_reduction(vorbis_info_psy_global *g,
  117696. vorbis_look_psy *p,
  117697. vorbis_info_mapping0 *vi,
  117698. float **mdct){
  117699. int i,j,n=p->n, de=0.3*p->m_val;
  117700. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117701. for(i=0; i<vi->coupling_steps; i++){
  117702. /* for(j=start; j<limit; j++){} // ???*/
  117703. for(j=limit; j<n; j++)
  117704. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117705. }
  117706. }
  117707. #endif
  117708. /*** End of inlined file: psy.c ***/
  117709. /*** Start of inlined file: registry.c ***/
  117710. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117711. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117712. // tasks..
  117713. #if JUCE_MSVC
  117714. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117715. #endif
  117716. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117717. #if JUCE_USE_OGGVORBIS
  117718. /* seems like major overkill now; the backend numbers will grow into
  117719. the infrastructure soon enough */
  117720. extern vorbis_func_floor floor0_exportbundle;
  117721. extern vorbis_func_floor floor1_exportbundle;
  117722. extern vorbis_func_residue residue0_exportbundle;
  117723. extern vorbis_func_residue residue1_exportbundle;
  117724. extern vorbis_func_residue residue2_exportbundle;
  117725. extern vorbis_func_mapping mapping0_exportbundle;
  117726. vorbis_func_floor *_floor_P[]={
  117727. &floor0_exportbundle,
  117728. &floor1_exportbundle,
  117729. };
  117730. vorbis_func_residue *_residue_P[]={
  117731. &residue0_exportbundle,
  117732. &residue1_exportbundle,
  117733. &residue2_exportbundle,
  117734. };
  117735. vorbis_func_mapping *_mapping_P[]={
  117736. &mapping0_exportbundle,
  117737. };
  117738. #endif
  117739. /*** End of inlined file: registry.c ***/
  117740. /*** Start of inlined file: res0.c ***/
  117741. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117742. encode/decode loops are coded for clarity and performance is not
  117743. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117744. it's slow. */
  117745. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  117746. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117747. // tasks..
  117748. #if JUCE_MSVC
  117749. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117750. #endif
  117751. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  117752. #if JUCE_USE_OGGVORBIS
  117753. #include <stdlib.h>
  117754. #include <string.h>
  117755. #include <math.h>
  117756. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117757. #include <stdio.h>
  117758. #endif
  117759. typedef struct {
  117760. vorbis_info_residue0 *info;
  117761. int parts;
  117762. int stages;
  117763. codebook *fullbooks;
  117764. codebook *phrasebook;
  117765. codebook ***partbooks;
  117766. int partvals;
  117767. int **decodemap;
  117768. long postbits;
  117769. long phrasebits;
  117770. long frames;
  117771. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  117772. int train_seq;
  117773. long *training_data[8][64];
  117774. float training_max[8][64];
  117775. float training_min[8][64];
  117776. float tmin;
  117777. float tmax;
  117778. #endif
  117779. } vorbis_look_residue0;
  117780. void res0_free_info(vorbis_info_residue *i){
  117781. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  117782. if(info){
  117783. memset(info,0,sizeof(*info));
  117784. _ogg_free(info);
  117785. }
  117786. }
  117787. void res0_free_look(vorbis_look_residue *i){
  117788. int j;
  117789. if(i){
  117790. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  117791. #ifdef TRAIN_RES
  117792. {
  117793. int j,k,l;
  117794. for(j=0;j<look->parts;j++){
  117795. /*fprintf(stderr,"partition %d: ",j);*/
  117796. for(k=0;k<8;k++)
  117797. if(look->training_data[k][j]){
  117798. char buffer[80];
  117799. FILE *of;
  117800. codebook *statebook=look->partbooks[j][k];
  117801. /* long and short into the same bucket by current convention */
  117802. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  117803. of=fopen(buffer,"a");
  117804. for(l=0;l<statebook->entries;l++)
  117805. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  117806. fclose(of);
  117807. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  117808. look->training_min[k][j],look->training_max[k][j]);*/
  117809. _ogg_free(look->training_data[k][j]);
  117810. look->training_data[k][j]=NULL;
  117811. }
  117812. /*fprintf(stderr,"\n");*/
  117813. }
  117814. }
  117815. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  117816. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  117817. (float)look->phrasebits/look->frames,
  117818. (float)look->postbits/look->frames,
  117819. (float)(look->postbits+look->phrasebits)/look->frames);*/
  117820. #endif
  117821. /*vorbis_info_residue0 *info=look->info;
  117822. fprintf(stderr,
  117823. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  117824. "(%g/frame) \n",look->frames,look->phrasebits,
  117825. look->resbitsflat,
  117826. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  117827. for(j=0;j<look->parts;j++){
  117828. long acc=0;
  117829. fprintf(stderr,"\t[%d] == ",j);
  117830. for(k=0;k<look->stages;k++)
  117831. if((info->secondstages[j]>>k)&1){
  117832. fprintf(stderr,"%ld,",look->resbits[j][k]);
  117833. acc+=look->resbits[j][k];
  117834. }
  117835. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  117836. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  117837. }
  117838. fprintf(stderr,"\n");*/
  117839. for(j=0;j<look->parts;j++)
  117840. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  117841. _ogg_free(look->partbooks);
  117842. for(j=0;j<look->partvals;j++)
  117843. _ogg_free(look->decodemap[j]);
  117844. _ogg_free(look->decodemap);
  117845. memset(look,0,sizeof(*look));
  117846. _ogg_free(look);
  117847. }
  117848. }
  117849. static int icount(unsigned int v){
  117850. int ret=0;
  117851. while(v){
  117852. ret+=v&1;
  117853. v>>=1;
  117854. }
  117855. return(ret);
  117856. }
  117857. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  117858. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117859. int j,acc=0;
  117860. oggpack_write(opb,info->begin,24);
  117861. oggpack_write(opb,info->end,24);
  117862. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  117863. code with a partitioned book */
  117864. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  117865. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  117866. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  117867. bitmask of one indicates this partition class has bits to write
  117868. this pass */
  117869. for(j=0;j<info->partitions;j++){
  117870. if(ilog(info->secondstages[j])>3){
  117871. /* yes, this is a minor hack due to not thinking ahead */
  117872. oggpack_write(opb,info->secondstages[j],3);
  117873. oggpack_write(opb,1,1);
  117874. oggpack_write(opb,info->secondstages[j]>>3,5);
  117875. }else
  117876. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  117877. acc+=icount(info->secondstages[j]);
  117878. }
  117879. for(j=0;j<acc;j++)
  117880. oggpack_write(opb,info->booklist[j],8);
  117881. }
  117882. /* vorbis_info is for range checking */
  117883. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  117884. int j,acc=0;
  117885. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  117886. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  117887. info->begin=oggpack_read(opb,24);
  117888. info->end=oggpack_read(opb,24);
  117889. info->grouping=oggpack_read(opb,24)+1;
  117890. info->partitions=oggpack_read(opb,6)+1;
  117891. info->groupbook=oggpack_read(opb,8);
  117892. for(j=0;j<info->partitions;j++){
  117893. int cascade=oggpack_read(opb,3);
  117894. if(oggpack_read(opb,1))
  117895. cascade|=(oggpack_read(opb,5)<<3);
  117896. info->secondstages[j]=cascade;
  117897. acc+=icount(cascade);
  117898. }
  117899. for(j=0;j<acc;j++)
  117900. info->booklist[j]=oggpack_read(opb,8);
  117901. if(info->groupbook>=ci->books)goto errout;
  117902. for(j=0;j<acc;j++)
  117903. if(info->booklist[j]>=ci->books)goto errout;
  117904. return(info);
  117905. errout:
  117906. res0_free_info(info);
  117907. return(NULL);
  117908. }
  117909. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  117910. vorbis_info_residue *vr){
  117911. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  117912. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  117913. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  117914. int j,k,acc=0;
  117915. int dim;
  117916. int maxstage=0;
  117917. look->info=info;
  117918. look->parts=info->partitions;
  117919. look->fullbooks=ci->fullbooks;
  117920. look->phrasebook=ci->fullbooks+info->groupbook;
  117921. dim=look->phrasebook->dim;
  117922. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  117923. for(j=0;j<look->parts;j++){
  117924. int stages=ilog(info->secondstages[j]);
  117925. if(stages){
  117926. if(stages>maxstage)maxstage=stages;
  117927. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  117928. for(k=0;k<stages;k++)
  117929. if(info->secondstages[j]&(1<<k)){
  117930. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  117931. #ifdef TRAIN_RES
  117932. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  117933. sizeof(***look->training_data));
  117934. #endif
  117935. }
  117936. }
  117937. }
  117938. look->partvals=rint(pow((float)look->parts,(float)dim));
  117939. look->stages=maxstage;
  117940. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  117941. for(j=0;j<look->partvals;j++){
  117942. long val=j;
  117943. long mult=look->partvals/look->parts;
  117944. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  117945. for(k=0;k<dim;k++){
  117946. long deco=val/mult;
  117947. val-=deco*mult;
  117948. mult/=look->parts;
  117949. look->decodemap[j][k]=deco;
  117950. }
  117951. }
  117952. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  117953. {
  117954. static int train_seq=0;
  117955. look->train_seq=train_seq++;
  117956. }
  117957. #endif
  117958. return(look);
  117959. }
  117960. /* break an abstraction and copy some code for performance purposes */
  117961. static int local_book_besterror(codebook *book,float *a){
  117962. int dim=book->dim,i,k,o;
  117963. int best=0;
  117964. encode_aux_threshmatch *tt=book->c->thresh_tree;
  117965. /* find the quant val of each scalar */
  117966. for(k=0,o=dim;k<dim;++k){
  117967. float val=a[--o];
  117968. i=tt->threshvals>>1;
  117969. if(val<tt->quantthresh[i]){
  117970. if(val<tt->quantthresh[i-1]){
  117971. for(--i;i>0;--i)
  117972. if(val>=tt->quantthresh[i-1])
  117973. break;
  117974. }
  117975. }else{
  117976. for(++i;i<tt->threshvals-1;++i)
  117977. if(val<tt->quantthresh[i])break;
  117978. }
  117979. best=(best*tt->quantvals)+tt->quantmap[i];
  117980. }
  117981. /* regular lattices are easy :-) */
  117982. if(book->c->lengthlist[best]<=0){
  117983. const static_codebook *c=book->c;
  117984. int i,j;
  117985. float bestf=0.f;
  117986. float *e=book->valuelist;
  117987. best=-1;
  117988. for(i=0;i<book->entries;i++){
  117989. if(c->lengthlist[i]>0){
  117990. float thisx=0.f;
  117991. for(j=0;j<dim;j++){
  117992. float val=(e[j]-a[j]);
  117993. thisx+=val*val;
  117994. }
  117995. if(best==-1 || thisx<bestf){
  117996. bestf=thisx;
  117997. best=i;
  117998. }
  117999. }
  118000. e+=dim;
  118001. }
  118002. }
  118003. {
  118004. float *ptr=book->valuelist+best*dim;
  118005. for(i=0;i<dim;i++)
  118006. *a++ -= *ptr++;
  118007. }
  118008. return(best);
  118009. }
  118010. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118011. codebook *book,long *acc){
  118012. int i,bits=0;
  118013. int dim=book->dim;
  118014. int step=n/dim;
  118015. for(i=0;i<step;i++){
  118016. int entry=local_book_besterror(book,vec+i*dim);
  118017. #ifdef TRAIN_RES
  118018. acc[entry]++;
  118019. #endif
  118020. bits+=vorbis_book_encode(book,entry,opb);
  118021. }
  118022. return(bits);
  118023. }
  118024. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118025. float **in,int ch){
  118026. long i,j,k;
  118027. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118028. vorbis_info_residue0 *info=look->info;
  118029. /* move all this setup out later */
  118030. int samples_per_partition=info->grouping;
  118031. int possible_partitions=info->partitions;
  118032. int n=info->end-info->begin;
  118033. int partvals=n/samples_per_partition;
  118034. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118035. float scale=100./samples_per_partition;
  118036. /* we find the partition type for each partition of each
  118037. channel. We'll go back and do the interleaved encoding in a
  118038. bit. For now, clarity */
  118039. for(i=0;i<ch;i++){
  118040. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118041. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118042. }
  118043. for(i=0;i<partvals;i++){
  118044. int offset=i*samples_per_partition+info->begin;
  118045. for(j=0;j<ch;j++){
  118046. float max=0.;
  118047. float ent=0.;
  118048. for(k=0;k<samples_per_partition;k++){
  118049. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118050. ent+=fabs(rint(in[j][offset+k]));
  118051. }
  118052. ent*=scale;
  118053. for(k=0;k<possible_partitions-1;k++)
  118054. if(max<=info->classmetric1[k] &&
  118055. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118056. break;
  118057. partword[j][i]=k;
  118058. }
  118059. }
  118060. #ifdef TRAIN_RESAUX
  118061. {
  118062. FILE *of;
  118063. char buffer[80];
  118064. for(i=0;i<ch;i++){
  118065. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118066. of=fopen(buffer,"a");
  118067. for(j=0;j<partvals;j++)
  118068. fprintf(of,"%ld, ",partword[i][j]);
  118069. fprintf(of,"\n");
  118070. fclose(of);
  118071. }
  118072. }
  118073. #endif
  118074. look->frames++;
  118075. return(partword);
  118076. }
  118077. /* designed for stereo or other modes where the partition size is an
  118078. integer multiple of the number of channels encoded in the current
  118079. submap */
  118080. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118081. int ch){
  118082. long i,j,k,l;
  118083. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118084. vorbis_info_residue0 *info=look->info;
  118085. /* move all this setup out later */
  118086. int samples_per_partition=info->grouping;
  118087. int possible_partitions=info->partitions;
  118088. int n=info->end-info->begin;
  118089. int partvals=n/samples_per_partition;
  118090. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118091. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118092. FILE *of;
  118093. char buffer[80];
  118094. #endif
  118095. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118096. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118097. for(i=0,l=info->begin/ch;i<partvals;i++){
  118098. float magmax=0.f;
  118099. float angmax=0.f;
  118100. for(j=0;j<samples_per_partition;j+=ch){
  118101. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118102. for(k=1;k<ch;k++)
  118103. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118104. l++;
  118105. }
  118106. for(j=0;j<possible_partitions-1;j++)
  118107. if(magmax<=info->classmetric1[j] &&
  118108. angmax<=info->classmetric2[j])
  118109. break;
  118110. partword[0][i]=j;
  118111. }
  118112. #ifdef TRAIN_RESAUX
  118113. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118114. of=fopen(buffer,"a");
  118115. for(i=0;i<partvals;i++)
  118116. fprintf(of,"%ld, ",partword[0][i]);
  118117. fprintf(of,"\n");
  118118. fclose(of);
  118119. #endif
  118120. look->frames++;
  118121. return(partword);
  118122. }
  118123. static int _01forward(oggpack_buffer *opb,
  118124. vorbis_block *vb,vorbis_look_residue *vl,
  118125. float **in,int ch,
  118126. long **partword,
  118127. int (*encode)(oggpack_buffer *,float *,int,
  118128. codebook *,long *)){
  118129. long i,j,k,s;
  118130. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118131. vorbis_info_residue0 *info=look->info;
  118132. /* move all this setup out later */
  118133. int samples_per_partition=info->grouping;
  118134. int possible_partitions=info->partitions;
  118135. int partitions_per_word=look->phrasebook->dim;
  118136. int n=info->end-info->begin;
  118137. int partvals=n/samples_per_partition;
  118138. long resbits[128];
  118139. long resvals[128];
  118140. #ifdef TRAIN_RES
  118141. for(i=0;i<ch;i++)
  118142. for(j=info->begin;j<info->end;j++){
  118143. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118144. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118145. }
  118146. #endif
  118147. memset(resbits,0,sizeof(resbits));
  118148. memset(resvals,0,sizeof(resvals));
  118149. /* we code the partition words for each channel, then the residual
  118150. words for a partition per channel until we've written all the
  118151. residual words for that partition word. Then write the next
  118152. partition channel words... */
  118153. for(s=0;s<look->stages;s++){
  118154. for(i=0;i<partvals;){
  118155. /* first we encode a partition codeword for each channel */
  118156. if(s==0){
  118157. for(j=0;j<ch;j++){
  118158. long val=partword[j][i];
  118159. for(k=1;k<partitions_per_word;k++){
  118160. val*=possible_partitions;
  118161. if(i+k<partvals)
  118162. val+=partword[j][i+k];
  118163. }
  118164. /* training hack */
  118165. if(val<look->phrasebook->entries)
  118166. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118167. #if 0 /*def TRAIN_RES*/
  118168. else
  118169. fprintf(stderr,"!");
  118170. #endif
  118171. }
  118172. }
  118173. /* now we encode interleaved residual values for the partitions */
  118174. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118175. long offset=i*samples_per_partition+info->begin;
  118176. for(j=0;j<ch;j++){
  118177. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118178. if(info->secondstages[partword[j][i]]&(1<<s)){
  118179. codebook *statebook=look->partbooks[partword[j][i]][s];
  118180. if(statebook){
  118181. int ret;
  118182. long *accumulator=NULL;
  118183. #ifdef TRAIN_RES
  118184. accumulator=look->training_data[s][partword[j][i]];
  118185. {
  118186. int l;
  118187. float *samples=in[j]+offset;
  118188. for(l=0;l<samples_per_partition;l++){
  118189. if(samples[l]<look->training_min[s][partword[j][i]])
  118190. look->training_min[s][partword[j][i]]=samples[l];
  118191. if(samples[l]>look->training_max[s][partword[j][i]])
  118192. look->training_max[s][partword[j][i]]=samples[l];
  118193. }
  118194. }
  118195. #endif
  118196. ret=encode(opb,in[j]+offset,samples_per_partition,
  118197. statebook,accumulator);
  118198. look->postbits+=ret;
  118199. resbits[partword[j][i]]+=ret;
  118200. }
  118201. }
  118202. }
  118203. }
  118204. }
  118205. }
  118206. /*{
  118207. long total=0;
  118208. long totalbits=0;
  118209. fprintf(stderr,"%d :: ",vb->mode);
  118210. for(k=0;k<possible_partitions;k++){
  118211. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118212. total+=resvals[k];
  118213. totalbits+=resbits[k];
  118214. }
  118215. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118216. }*/
  118217. return(0);
  118218. }
  118219. /* a truncated packet here just means 'stop working'; it's not an error */
  118220. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118221. float **in,int ch,
  118222. long (*decodepart)(codebook *, float *,
  118223. oggpack_buffer *,int)){
  118224. long i,j,k,l,s;
  118225. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118226. vorbis_info_residue0 *info=look->info;
  118227. /* move all this setup out later */
  118228. int samples_per_partition=info->grouping;
  118229. int partitions_per_word=look->phrasebook->dim;
  118230. int n=info->end-info->begin;
  118231. int partvals=n/samples_per_partition;
  118232. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118233. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118234. for(j=0;j<ch;j++)
  118235. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118236. for(s=0;s<look->stages;s++){
  118237. /* each loop decodes on partition codeword containing
  118238. partitions_pre_word partitions */
  118239. for(i=0,l=0;i<partvals;l++){
  118240. if(s==0){
  118241. /* fetch the partition word for each channel */
  118242. for(j=0;j<ch;j++){
  118243. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118244. if(temp==-1)goto eopbreak;
  118245. partword[j][l]=look->decodemap[temp];
  118246. if(partword[j][l]==NULL)goto errout;
  118247. }
  118248. }
  118249. /* now we decode residual values for the partitions */
  118250. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118251. for(j=0;j<ch;j++){
  118252. long offset=info->begin+i*samples_per_partition;
  118253. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118254. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118255. if(stagebook){
  118256. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118257. samples_per_partition)==-1)goto eopbreak;
  118258. }
  118259. }
  118260. }
  118261. }
  118262. }
  118263. errout:
  118264. eopbreak:
  118265. return(0);
  118266. }
  118267. #if 0
  118268. /* residue 0 and 1 are just slight variants of one another. 0 is
  118269. interleaved, 1 is not */
  118270. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118271. float **in,int *nonzero,int ch){
  118272. /* we encode only the nonzero parts of a bundle */
  118273. int i,used=0;
  118274. for(i=0;i<ch;i++)
  118275. if(nonzero[i])
  118276. in[used++]=in[i];
  118277. if(used)
  118278. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118279. return(_01class(vb,vl,in,used));
  118280. else
  118281. return(0);
  118282. }
  118283. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118284. float **in,float **out,int *nonzero,int ch,
  118285. long **partword){
  118286. /* we encode only the nonzero parts of a bundle */
  118287. int i,j,used=0,n=vb->pcmend/2;
  118288. for(i=0;i<ch;i++)
  118289. if(nonzero[i]){
  118290. if(out)
  118291. for(j=0;j<n;j++)
  118292. out[i][j]+=in[i][j];
  118293. in[used++]=in[i];
  118294. }
  118295. if(used){
  118296. int ret=_01forward(vb,vl,in,used,partword,
  118297. _interleaved_encodepart);
  118298. if(out){
  118299. used=0;
  118300. for(i=0;i<ch;i++)
  118301. if(nonzero[i]){
  118302. for(j=0;j<n;j++)
  118303. out[i][j]-=in[used][j];
  118304. used++;
  118305. }
  118306. }
  118307. return(ret);
  118308. }else{
  118309. return(0);
  118310. }
  118311. }
  118312. #endif
  118313. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118314. float **in,int *nonzero,int ch){
  118315. int i,used=0;
  118316. for(i=0;i<ch;i++)
  118317. if(nonzero[i])
  118318. in[used++]=in[i];
  118319. if(used)
  118320. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118321. else
  118322. return(0);
  118323. }
  118324. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118325. float **in,float **out,int *nonzero,int ch,
  118326. long **partword){
  118327. int i,j,used=0,n=vb->pcmend/2;
  118328. for(i=0;i<ch;i++)
  118329. if(nonzero[i]){
  118330. if(out)
  118331. for(j=0;j<n;j++)
  118332. out[i][j]+=in[i][j];
  118333. in[used++]=in[i];
  118334. }
  118335. if(used){
  118336. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118337. if(out){
  118338. used=0;
  118339. for(i=0;i<ch;i++)
  118340. if(nonzero[i]){
  118341. for(j=0;j<n;j++)
  118342. out[i][j]-=in[used][j];
  118343. used++;
  118344. }
  118345. }
  118346. return(ret);
  118347. }else{
  118348. return(0);
  118349. }
  118350. }
  118351. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118352. float **in,int *nonzero,int ch){
  118353. int i,used=0;
  118354. for(i=0;i<ch;i++)
  118355. if(nonzero[i])
  118356. in[used++]=in[i];
  118357. if(used)
  118358. return(_01class(vb,vl,in,used));
  118359. else
  118360. return(0);
  118361. }
  118362. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118363. float **in,int *nonzero,int ch){
  118364. int i,used=0;
  118365. for(i=0;i<ch;i++)
  118366. if(nonzero[i])
  118367. in[used++]=in[i];
  118368. if(used)
  118369. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118370. else
  118371. return(0);
  118372. }
  118373. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118374. float **in,int *nonzero,int ch){
  118375. int i,used=0;
  118376. for(i=0;i<ch;i++)
  118377. if(nonzero[i])used++;
  118378. if(used)
  118379. return(_2class(vb,vl,in,ch));
  118380. else
  118381. return(0);
  118382. }
  118383. /* res2 is slightly more different; all the channels are interleaved
  118384. into a single vector and encoded. */
  118385. int res2_forward(oggpack_buffer *opb,
  118386. vorbis_block *vb,vorbis_look_residue *vl,
  118387. float **in,float **out,int *nonzero,int ch,
  118388. long **partword){
  118389. long i,j,k,n=vb->pcmend/2,used=0;
  118390. /* don't duplicate the code; use a working vector hack for now and
  118391. reshape ourselves into a single channel res1 */
  118392. /* ugly; reallocs for each coupling pass :-( */
  118393. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118394. for(i=0;i<ch;i++){
  118395. float *pcm=in[i];
  118396. if(nonzero[i])used++;
  118397. for(j=0,k=i;j<n;j++,k+=ch)
  118398. work[k]=pcm[j];
  118399. }
  118400. if(used){
  118401. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118402. /* update the sofar vector */
  118403. if(out){
  118404. for(i=0;i<ch;i++){
  118405. float *pcm=in[i];
  118406. float *sofar=out[i];
  118407. for(j=0,k=i;j<n;j++,k+=ch)
  118408. sofar[j]+=pcm[j]-work[k];
  118409. }
  118410. }
  118411. return(ret);
  118412. }else{
  118413. return(0);
  118414. }
  118415. }
  118416. /* duplicate code here as speed is somewhat more important */
  118417. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118418. float **in,int *nonzero,int ch){
  118419. long i,k,l,s;
  118420. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118421. vorbis_info_residue0 *info=look->info;
  118422. /* move all this setup out later */
  118423. int samples_per_partition=info->grouping;
  118424. int partitions_per_word=look->phrasebook->dim;
  118425. int n=info->end-info->begin;
  118426. int partvals=n/samples_per_partition;
  118427. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118428. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118429. for(i=0;i<ch;i++)if(nonzero[i])break;
  118430. if(i==ch)return(0); /* no nonzero vectors */
  118431. for(s=0;s<look->stages;s++){
  118432. for(i=0,l=0;i<partvals;l++){
  118433. if(s==0){
  118434. /* fetch the partition word */
  118435. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118436. if(temp==-1)goto eopbreak;
  118437. partword[l]=look->decodemap[temp];
  118438. if(partword[l]==NULL)goto errout;
  118439. }
  118440. /* now we decode residual values for the partitions */
  118441. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118442. if(info->secondstages[partword[l][k]]&(1<<s)){
  118443. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118444. if(stagebook){
  118445. if(vorbis_book_decodevv_add(stagebook,in,
  118446. i*samples_per_partition+info->begin,ch,
  118447. &vb->opb,samples_per_partition)==-1)
  118448. goto eopbreak;
  118449. }
  118450. }
  118451. }
  118452. }
  118453. errout:
  118454. eopbreak:
  118455. return(0);
  118456. }
  118457. vorbis_func_residue residue0_exportbundle={
  118458. NULL,
  118459. &res0_unpack,
  118460. &res0_look,
  118461. &res0_free_info,
  118462. &res0_free_look,
  118463. NULL,
  118464. NULL,
  118465. &res0_inverse
  118466. };
  118467. vorbis_func_residue residue1_exportbundle={
  118468. &res0_pack,
  118469. &res0_unpack,
  118470. &res0_look,
  118471. &res0_free_info,
  118472. &res0_free_look,
  118473. &res1_class,
  118474. &res1_forward,
  118475. &res1_inverse
  118476. };
  118477. vorbis_func_residue residue2_exportbundle={
  118478. &res0_pack,
  118479. &res0_unpack,
  118480. &res0_look,
  118481. &res0_free_info,
  118482. &res0_free_look,
  118483. &res2_class,
  118484. &res2_forward,
  118485. &res2_inverse
  118486. };
  118487. #endif
  118488. /*** End of inlined file: res0.c ***/
  118489. /*** Start of inlined file: sharedbook.c ***/
  118490. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118491. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118492. // tasks..
  118493. #if JUCE_MSVC
  118494. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118495. #endif
  118496. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118497. #if JUCE_USE_OGGVORBIS
  118498. #include <stdlib.h>
  118499. #include <math.h>
  118500. #include <string.h>
  118501. /**** pack/unpack helpers ******************************************/
  118502. int _ilog(unsigned int v){
  118503. int ret=0;
  118504. while(v){
  118505. ret++;
  118506. v>>=1;
  118507. }
  118508. return(ret);
  118509. }
  118510. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118511. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118512. Why not IEEE? It's just not that important here. */
  118513. #define VQ_FEXP 10
  118514. #define VQ_FMAN 21
  118515. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118516. /* doesn't currently guard under/overflow */
  118517. long _float32_pack(float val){
  118518. int sign=0;
  118519. long exp;
  118520. long mant;
  118521. if(val<0){
  118522. sign=0x80000000;
  118523. val= -val;
  118524. }
  118525. exp= floor(log(val)/log(2.f));
  118526. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118527. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118528. return(sign|exp|mant);
  118529. }
  118530. float _float32_unpack(long val){
  118531. double mant=val&0x1fffff;
  118532. int sign=val&0x80000000;
  118533. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118534. if(sign)mant= -mant;
  118535. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118536. }
  118537. /* given a list of word lengths, generate a list of codewords. Works
  118538. for length ordered or unordered, always assigns the lowest valued
  118539. codewords first. Extended to handle unused entries (length 0) */
  118540. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118541. long i,j,count=0;
  118542. ogg_uint32_t marker[33];
  118543. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118544. memset(marker,0,sizeof(marker));
  118545. for(i=0;i<n;i++){
  118546. long length=l[i];
  118547. if(length>0){
  118548. ogg_uint32_t entry=marker[length];
  118549. /* when we claim a node for an entry, we also claim the nodes
  118550. below it (pruning off the imagined tree that may have dangled
  118551. from it) as well as blocking the use of any nodes directly
  118552. above for leaves */
  118553. /* update ourself */
  118554. if(length<32 && (entry>>length)){
  118555. /* error condition; the lengths must specify an overpopulated tree */
  118556. _ogg_free(r);
  118557. return(NULL);
  118558. }
  118559. r[count++]=entry;
  118560. /* Look to see if the next shorter marker points to the node
  118561. above. if so, update it and repeat. */
  118562. {
  118563. for(j=length;j>0;j--){
  118564. if(marker[j]&1){
  118565. /* have to jump branches */
  118566. if(j==1)
  118567. marker[1]++;
  118568. else
  118569. marker[j]=marker[j-1]<<1;
  118570. break; /* invariant says next upper marker would already
  118571. have been moved if it was on the same path */
  118572. }
  118573. marker[j]++;
  118574. }
  118575. }
  118576. /* prune the tree; the implicit invariant says all the longer
  118577. markers were dangling from our just-taken node. Dangle them
  118578. from our *new* node. */
  118579. for(j=length+1;j<33;j++)
  118580. if((marker[j]>>1) == entry){
  118581. entry=marker[j];
  118582. marker[j]=marker[j-1]<<1;
  118583. }else
  118584. break;
  118585. }else
  118586. if(sparsecount==0)count++;
  118587. }
  118588. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118589. endian */
  118590. for(i=0,count=0;i<n;i++){
  118591. ogg_uint32_t temp=0;
  118592. for(j=0;j<l[i];j++){
  118593. temp<<=1;
  118594. temp|=(r[count]>>j)&1;
  118595. }
  118596. if(sparsecount){
  118597. if(l[i])
  118598. r[count++]=temp;
  118599. }else
  118600. r[count++]=temp;
  118601. }
  118602. return(r);
  118603. }
  118604. /* there might be a straightforward one-line way to do the below
  118605. that's portable and totally safe against roundoff, but I haven't
  118606. thought of it. Therefore, we opt on the side of caution */
  118607. long _book_maptype1_quantvals(const static_codebook *b){
  118608. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118609. /* the above *should* be reliable, but we'll not assume that FP is
  118610. ever reliable when bitstream sync is at stake; verify via integer
  118611. means that vals really is the greatest value of dim for which
  118612. vals^b->bim <= b->entries */
  118613. /* treat the above as an initial guess */
  118614. while(1){
  118615. long acc=1;
  118616. long acc1=1;
  118617. int i;
  118618. for(i=0;i<b->dim;i++){
  118619. acc*=vals;
  118620. acc1*=vals+1;
  118621. }
  118622. if(acc<=b->entries && acc1>b->entries){
  118623. return(vals);
  118624. }else{
  118625. if(acc>b->entries){
  118626. vals--;
  118627. }else{
  118628. vals++;
  118629. }
  118630. }
  118631. }
  118632. }
  118633. /* unpack the quantized list of values for encode/decode ***********/
  118634. /* we need to deal with two map types: in map type 1, the values are
  118635. generated algorithmically (each column of the vector counts through
  118636. the values in the quant vector). in map type 2, all the values came
  118637. in in an explicit list. Both value lists must be unpacked */
  118638. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118639. long j,k,count=0;
  118640. if(b->maptype==1 || b->maptype==2){
  118641. int quantvals;
  118642. float mindel=_float32_unpack(b->q_min);
  118643. float delta=_float32_unpack(b->q_delta);
  118644. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118645. /* maptype 1 and 2 both use a quantized value vector, but
  118646. different sizes */
  118647. switch(b->maptype){
  118648. case 1:
  118649. /* most of the time, entries%dimensions == 0, but we need to be
  118650. well defined. We define that the possible vales at each
  118651. scalar is values == entries/dim. If entries%dim != 0, we'll
  118652. have 'too few' values (values*dim<entries), which means that
  118653. we'll have 'left over' entries; left over entries use zeroed
  118654. values (and are wasted). So don't generate codebooks like
  118655. that */
  118656. quantvals=_book_maptype1_quantvals(b);
  118657. for(j=0;j<b->entries;j++){
  118658. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118659. float last=0.f;
  118660. int indexdiv=1;
  118661. for(k=0;k<b->dim;k++){
  118662. int index= (j/indexdiv)%quantvals;
  118663. float val=b->quantlist[index];
  118664. val=fabs(val)*delta+mindel+last;
  118665. if(b->q_sequencep)last=val;
  118666. if(sparsemap)
  118667. r[sparsemap[count]*b->dim+k]=val;
  118668. else
  118669. r[count*b->dim+k]=val;
  118670. indexdiv*=quantvals;
  118671. }
  118672. count++;
  118673. }
  118674. }
  118675. break;
  118676. case 2:
  118677. for(j=0;j<b->entries;j++){
  118678. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118679. float last=0.f;
  118680. for(k=0;k<b->dim;k++){
  118681. float val=b->quantlist[j*b->dim+k];
  118682. val=fabs(val)*delta+mindel+last;
  118683. if(b->q_sequencep)last=val;
  118684. if(sparsemap)
  118685. r[sparsemap[count]*b->dim+k]=val;
  118686. else
  118687. r[count*b->dim+k]=val;
  118688. }
  118689. count++;
  118690. }
  118691. }
  118692. break;
  118693. }
  118694. return(r);
  118695. }
  118696. return(NULL);
  118697. }
  118698. void vorbis_staticbook_clear(static_codebook *b){
  118699. if(b->allocedp){
  118700. if(b->quantlist)_ogg_free(b->quantlist);
  118701. if(b->lengthlist)_ogg_free(b->lengthlist);
  118702. if(b->nearest_tree){
  118703. _ogg_free(b->nearest_tree->ptr0);
  118704. _ogg_free(b->nearest_tree->ptr1);
  118705. _ogg_free(b->nearest_tree->p);
  118706. _ogg_free(b->nearest_tree->q);
  118707. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  118708. _ogg_free(b->nearest_tree);
  118709. }
  118710. if(b->thresh_tree){
  118711. _ogg_free(b->thresh_tree->quantthresh);
  118712. _ogg_free(b->thresh_tree->quantmap);
  118713. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  118714. _ogg_free(b->thresh_tree);
  118715. }
  118716. memset(b,0,sizeof(*b));
  118717. }
  118718. }
  118719. void vorbis_staticbook_destroy(static_codebook *b){
  118720. if(b->allocedp){
  118721. vorbis_staticbook_clear(b);
  118722. _ogg_free(b);
  118723. }
  118724. }
  118725. void vorbis_book_clear(codebook *b){
  118726. /* static book is not cleared; we're likely called on the lookup and
  118727. the static codebook belongs to the info struct */
  118728. if(b->valuelist)_ogg_free(b->valuelist);
  118729. if(b->codelist)_ogg_free(b->codelist);
  118730. if(b->dec_index)_ogg_free(b->dec_index);
  118731. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  118732. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  118733. memset(b,0,sizeof(*b));
  118734. }
  118735. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  118736. memset(c,0,sizeof(*c));
  118737. c->c=s;
  118738. c->entries=s->entries;
  118739. c->used_entries=s->entries;
  118740. c->dim=s->dim;
  118741. c->codelist=_make_words(s->lengthlist,s->entries,0);
  118742. c->valuelist=_book_unquantize(s,s->entries,NULL);
  118743. return(0);
  118744. }
  118745. static int JUCE_CDECL sort32a(const void *a,const void *b){
  118746. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  118747. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  118748. }
  118749. /* decode codebook arrangement is more heavily optimized than encode */
  118750. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  118751. int i,j,n=0,tabn;
  118752. int *sortindex;
  118753. memset(c,0,sizeof(*c));
  118754. /* count actually used entries */
  118755. for(i=0;i<s->entries;i++)
  118756. if(s->lengthlist[i]>0)
  118757. n++;
  118758. c->entries=s->entries;
  118759. c->used_entries=n;
  118760. c->dim=s->dim;
  118761. /* two different remappings go on here.
  118762. First, we collapse the likely sparse codebook down only to
  118763. actually represented values/words. This collapsing needs to be
  118764. indexed as map-valueless books are used to encode original entry
  118765. positions as integers.
  118766. Second, we reorder all vectors, including the entry index above,
  118767. by sorted bitreversed codeword to allow treeless decode. */
  118768. {
  118769. /* perform sort */
  118770. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  118771. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  118772. if(codes==NULL)goto err_out;
  118773. for(i=0;i<n;i++){
  118774. codes[i]=ogg_bitreverse(codes[i]);
  118775. codep[i]=codes+i;
  118776. }
  118777. qsort(codep,n,sizeof(*codep),sort32a);
  118778. sortindex=(int*)alloca(n*sizeof(*sortindex));
  118779. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  118780. /* the index is a reverse index */
  118781. for(i=0;i<n;i++){
  118782. int position=codep[i]-codes;
  118783. sortindex[position]=i;
  118784. }
  118785. for(i=0;i<n;i++)
  118786. c->codelist[sortindex[i]]=codes[i];
  118787. _ogg_free(codes);
  118788. }
  118789. c->valuelist=_book_unquantize(s,n,sortindex);
  118790. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  118791. for(n=0,i=0;i<s->entries;i++)
  118792. if(s->lengthlist[i]>0)
  118793. c->dec_index[sortindex[n++]]=i;
  118794. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  118795. for(n=0,i=0;i<s->entries;i++)
  118796. if(s->lengthlist[i]>0)
  118797. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  118798. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  118799. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  118800. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  118801. tabn=1<<c->dec_firsttablen;
  118802. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  118803. c->dec_maxlength=0;
  118804. for(i=0;i<n;i++){
  118805. if(c->dec_maxlength<c->dec_codelengths[i])
  118806. c->dec_maxlength=c->dec_codelengths[i];
  118807. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  118808. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  118809. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  118810. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  118811. }
  118812. }
  118813. /* now fill in 'unused' entries in the firsttable with hi/lo search
  118814. hints for the non-direct-hits */
  118815. {
  118816. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  118817. long lo=0,hi=0;
  118818. for(i=0;i<tabn;i++){
  118819. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  118820. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  118821. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  118822. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  118823. /* we only actually have 15 bits per hint to play with here.
  118824. In order to overflow gracefully (nothing breaks, efficiency
  118825. just drops), encode as the difference from the extremes. */
  118826. {
  118827. unsigned long loval=lo;
  118828. unsigned long hival=n-hi;
  118829. if(loval>0x7fff)loval=0x7fff;
  118830. if(hival>0x7fff)hival=0x7fff;
  118831. c->dec_firsttable[ogg_bitreverse(word)]=
  118832. 0x80000000UL | (loval<<15) | hival;
  118833. }
  118834. }
  118835. }
  118836. }
  118837. return(0);
  118838. err_out:
  118839. vorbis_book_clear(c);
  118840. return(-1);
  118841. }
  118842. static float _dist(int el,float *ref, float *b,int step){
  118843. int i;
  118844. float acc=0.f;
  118845. for(i=0;i<el;i++){
  118846. float val=(ref[i]-b[i*step]);
  118847. acc+=val*val;
  118848. }
  118849. return(acc);
  118850. }
  118851. int _best(codebook *book, float *a, int step){
  118852. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118853. #if 0
  118854. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  118855. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  118856. #endif
  118857. int dim=book->dim;
  118858. int k,o;
  118859. /*int savebest=-1;
  118860. float saverr;*/
  118861. /* do we have a threshhold encode hint? */
  118862. if(tt){
  118863. int index=0,i;
  118864. /* find the quant val of each scalar */
  118865. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118866. i=tt->threshvals>>1;
  118867. if(a[o]<tt->quantthresh[i]){
  118868. for(;i>0;i--)
  118869. if(a[o]>=tt->quantthresh[i-1])
  118870. break;
  118871. }else{
  118872. for(i++;i<tt->threshvals-1;i++)
  118873. if(a[o]<tt->quantthresh[i])break;
  118874. }
  118875. index=(index*tt->quantvals)+tt->quantmap[i];
  118876. }
  118877. /* regular lattices are easy :-) */
  118878. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  118879. use a decision tree after all
  118880. and fall through*/
  118881. return(index);
  118882. }
  118883. #if 0
  118884. /* do we have a pigeonhole encode hint? */
  118885. if(pt){
  118886. const static_codebook *c=book->c;
  118887. int i,besti=-1;
  118888. float best=0.f;
  118889. int entry=0;
  118890. /* dealing with sequentialness is a pain in the ass */
  118891. if(c->q_sequencep){
  118892. int pv;
  118893. long mul=1;
  118894. float qlast=0;
  118895. for(k=0,o=0;k<dim;k++,o+=step){
  118896. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  118897. if(pv<0 || pv>=pt->mapentries)break;
  118898. entry+=pt->pigeonmap[pv]*mul;
  118899. mul*=pt->quantvals;
  118900. qlast+=pv*pt->del+pt->min;
  118901. }
  118902. }else{
  118903. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  118904. int pv=(int)((a[o]-pt->min)/pt->del);
  118905. if(pv<0 || pv>=pt->mapentries)break;
  118906. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  118907. }
  118908. }
  118909. /* must be within the pigeonholable range; if we quant outside (or
  118910. in an entry that we define no list for), brute force it */
  118911. if(k==dim && pt->fitlength[entry]){
  118912. /* search the abbreviated list */
  118913. long *list=pt->fitlist+pt->fitmap[entry];
  118914. for(i=0;i<pt->fitlength[entry];i++){
  118915. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  118916. if(besti==-1 || this<best){
  118917. best=this;
  118918. besti=list[i];
  118919. }
  118920. }
  118921. return(besti);
  118922. }
  118923. }
  118924. if(nt){
  118925. /* optimized using the decision tree */
  118926. while(1){
  118927. float c=0.f;
  118928. float *p=book->valuelist+nt->p[ptr];
  118929. float *q=book->valuelist+nt->q[ptr];
  118930. for(k=0,o=0;k<dim;k++,o+=step)
  118931. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  118932. if(c>0.f) /* in A */
  118933. ptr= -nt->ptr0[ptr];
  118934. else /* in B */
  118935. ptr= -nt->ptr1[ptr];
  118936. if(ptr<=0)break;
  118937. }
  118938. return(-ptr);
  118939. }
  118940. #endif
  118941. /* brute force it! */
  118942. {
  118943. const static_codebook *c=book->c;
  118944. int i,besti=-1;
  118945. float best=0.f;
  118946. float *e=book->valuelist;
  118947. for(i=0;i<book->entries;i++){
  118948. if(c->lengthlist[i]>0){
  118949. float thisx=_dist(dim,e,a,step);
  118950. if(besti==-1 || thisx<best){
  118951. best=thisx;
  118952. besti=i;
  118953. }
  118954. }
  118955. e+=dim;
  118956. }
  118957. /*if(savebest!=-1 && savebest!=besti){
  118958. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  118959. "original:");
  118960. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  118961. fprintf(stderr,"\n"
  118962. "pigeonhole (entry %d, err %g):",savebest,saverr);
  118963. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118964. (book->valuelist+savebest*dim)[i]);
  118965. fprintf(stderr,"\n"
  118966. "bruteforce (entry %d, err %g):",besti,best);
  118967. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  118968. (book->valuelist+besti*dim)[i]);
  118969. fprintf(stderr,"\n");
  118970. }*/
  118971. return(besti);
  118972. }
  118973. }
  118974. long vorbis_book_codeword(codebook *book,int entry){
  118975. if(book->c) /* only use with encode; decode optimizations are
  118976. allowed to break this */
  118977. return book->codelist[entry];
  118978. return -1;
  118979. }
  118980. long vorbis_book_codelen(codebook *book,int entry){
  118981. if(book->c) /* only use with encode; decode optimizations are
  118982. allowed to break this */
  118983. return book->c->lengthlist[entry];
  118984. return -1;
  118985. }
  118986. #ifdef _V_SELFTEST
  118987. /* Unit tests of the dequantizer; this stuff will be OK
  118988. cross-platform, I simply want to be sure that special mapping cases
  118989. actually work properly; a bug could go unnoticed for a while */
  118990. #include <stdio.h>
  118991. /* cases:
  118992. no mapping
  118993. full, explicit mapping
  118994. algorithmic mapping
  118995. nonsequential
  118996. sequential
  118997. */
  118998. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  118999. static long partial_quantlist1[]={0,7,2};
  119000. /* no mapping */
  119001. static_codebook test1={
  119002. 4,16,
  119003. NULL,
  119004. 0,
  119005. 0,0,0,0,
  119006. NULL,
  119007. NULL,NULL
  119008. };
  119009. static float *test1_result=NULL;
  119010. /* linear, full mapping, nonsequential */
  119011. static_codebook test2={
  119012. 4,3,
  119013. NULL,
  119014. 2,
  119015. -533200896,1611661312,4,0,
  119016. full_quantlist1,
  119017. NULL,NULL
  119018. };
  119019. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119020. /* linear, full mapping, sequential */
  119021. static_codebook test3={
  119022. 4,3,
  119023. NULL,
  119024. 2,
  119025. -533200896,1611661312,4,1,
  119026. full_quantlist1,
  119027. NULL,NULL
  119028. };
  119029. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119030. /* linear, algorithmic mapping, nonsequential */
  119031. static_codebook test4={
  119032. 3,27,
  119033. NULL,
  119034. 1,
  119035. -533200896,1611661312,4,0,
  119036. partial_quantlist1,
  119037. NULL,NULL
  119038. };
  119039. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119040. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119041. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119042. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119043. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119044. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119045. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119046. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119047. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119048. /* linear, algorithmic mapping, sequential */
  119049. static_codebook test5={
  119050. 3,27,
  119051. NULL,
  119052. 1,
  119053. -533200896,1611661312,4,1,
  119054. partial_quantlist1,
  119055. NULL,NULL
  119056. };
  119057. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119058. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119059. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119060. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119061. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119062. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119063. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119064. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119065. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119066. void run_test(static_codebook *b,float *comp){
  119067. float *out=_book_unquantize(b,b->entries,NULL);
  119068. int i;
  119069. if(comp){
  119070. if(!out){
  119071. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119072. exit(1);
  119073. }
  119074. for(i=0;i<b->entries*b->dim;i++)
  119075. if(fabs(out[i]-comp[i])>.0001){
  119076. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119077. "position %d, %g != %g\n",i,out[i],comp[i]);
  119078. exit(1);
  119079. }
  119080. }else{
  119081. if(out){
  119082. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119083. " correct result should have been NULL\n");
  119084. exit(1);
  119085. }
  119086. }
  119087. }
  119088. int main(){
  119089. /* run the nine dequant tests, and compare to the hand-rolled results */
  119090. fprintf(stderr,"Dequant test 1... ");
  119091. run_test(&test1,test1_result);
  119092. fprintf(stderr,"OK\nDequant test 2... ");
  119093. run_test(&test2,test2_result);
  119094. fprintf(stderr,"OK\nDequant test 3... ");
  119095. run_test(&test3,test3_result);
  119096. fprintf(stderr,"OK\nDequant test 4... ");
  119097. run_test(&test4,test4_result);
  119098. fprintf(stderr,"OK\nDequant test 5... ");
  119099. run_test(&test5,test5_result);
  119100. fprintf(stderr,"OK\n\n");
  119101. return(0);
  119102. }
  119103. #endif
  119104. #endif
  119105. /*** End of inlined file: sharedbook.c ***/
  119106. /*** Start of inlined file: smallft.c ***/
  119107. /* FFT implementation from OggSquish, minus cosine transforms,
  119108. * minus all but radix 2/4 case. In Vorbis we only need this
  119109. * cut-down version.
  119110. *
  119111. * To do more than just power-of-two sized vectors, see the full
  119112. * version I wrote for NetLib.
  119113. *
  119114. * Note that the packing is a little strange; rather than the FFT r/i
  119115. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119116. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119117. * FORTRAN version
  119118. */
  119119. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119120. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119121. // tasks..
  119122. #if JUCE_MSVC
  119123. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119124. #endif
  119125. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119126. #if JUCE_USE_OGGVORBIS
  119127. #include <stdlib.h>
  119128. #include <string.h>
  119129. #include <math.h>
  119130. static void drfti1(int n, float *wa, int *ifac){
  119131. static int ntryh[4] = { 4,2,3,5 };
  119132. static float tpi = 6.28318530717958648f;
  119133. float arg,argh,argld,fi;
  119134. int ntry=0,i,j=-1;
  119135. int k1, l1, l2, ib;
  119136. int ld, ii, ip, is, nq, nr;
  119137. int ido, ipm, nfm1;
  119138. int nl=n;
  119139. int nf=0;
  119140. L101:
  119141. j++;
  119142. if (j < 4)
  119143. ntry=ntryh[j];
  119144. else
  119145. ntry+=2;
  119146. L104:
  119147. nq=nl/ntry;
  119148. nr=nl-ntry*nq;
  119149. if (nr!=0) goto L101;
  119150. nf++;
  119151. ifac[nf+1]=ntry;
  119152. nl=nq;
  119153. if(ntry!=2)goto L107;
  119154. if(nf==1)goto L107;
  119155. for (i=1;i<nf;i++){
  119156. ib=nf-i+1;
  119157. ifac[ib+1]=ifac[ib];
  119158. }
  119159. ifac[2] = 2;
  119160. L107:
  119161. if(nl!=1)goto L104;
  119162. ifac[0]=n;
  119163. ifac[1]=nf;
  119164. argh=tpi/n;
  119165. is=0;
  119166. nfm1=nf-1;
  119167. l1=1;
  119168. if(nfm1==0)return;
  119169. for (k1=0;k1<nfm1;k1++){
  119170. ip=ifac[k1+2];
  119171. ld=0;
  119172. l2=l1*ip;
  119173. ido=n/l2;
  119174. ipm=ip-1;
  119175. for (j=0;j<ipm;j++){
  119176. ld+=l1;
  119177. i=is;
  119178. argld=(float)ld*argh;
  119179. fi=0.f;
  119180. for (ii=2;ii<ido;ii+=2){
  119181. fi+=1.f;
  119182. arg=fi*argld;
  119183. wa[i++]=cos(arg);
  119184. wa[i++]=sin(arg);
  119185. }
  119186. is+=ido;
  119187. }
  119188. l1=l2;
  119189. }
  119190. }
  119191. static void fdrffti(int n, float *wsave, int *ifac){
  119192. if (n == 1) return;
  119193. drfti1(n, wsave+n, ifac);
  119194. }
  119195. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119196. int i,k;
  119197. float ti2,tr2;
  119198. int t0,t1,t2,t3,t4,t5,t6;
  119199. t1=0;
  119200. t0=(t2=l1*ido);
  119201. t3=ido<<1;
  119202. for(k=0;k<l1;k++){
  119203. ch[t1<<1]=cc[t1]+cc[t2];
  119204. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119205. t1+=ido;
  119206. t2+=ido;
  119207. }
  119208. if(ido<2)return;
  119209. if(ido==2)goto L105;
  119210. t1=0;
  119211. t2=t0;
  119212. for(k=0;k<l1;k++){
  119213. t3=t2;
  119214. t4=(t1<<1)+(ido<<1);
  119215. t5=t1;
  119216. t6=t1+t1;
  119217. for(i=2;i<ido;i+=2){
  119218. t3+=2;
  119219. t4-=2;
  119220. t5+=2;
  119221. t6+=2;
  119222. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119223. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119224. ch[t6]=cc[t5]+ti2;
  119225. ch[t4]=ti2-cc[t5];
  119226. ch[t6-1]=cc[t5-1]+tr2;
  119227. ch[t4-1]=cc[t5-1]-tr2;
  119228. }
  119229. t1+=ido;
  119230. t2+=ido;
  119231. }
  119232. if(ido%2==1)return;
  119233. L105:
  119234. t3=(t2=(t1=ido)-1);
  119235. t2+=t0;
  119236. for(k=0;k<l1;k++){
  119237. ch[t1]=-cc[t2];
  119238. ch[t1-1]=cc[t3];
  119239. t1+=ido<<1;
  119240. t2+=ido;
  119241. t3+=ido;
  119242. }
  119243. }
  119244. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119245. float *wa2,float *wa3){
  119246. static float hsqt2 = .70710678118654752f;
  119247. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119248. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119249. t0=l1*ido;
  119250. t1=t0;
  119251. t4=t1<<1;
  119252. t2=t1+(t1<<1);
  119253. t3=0;
  119254. for(k=0;k<l1;k++){
  119255. tr1=cc[t1]+cc[t2];
  119256. tr2=cc[t3]+cc[t4];
  119257. ch[t5=t3<<2]=tr1+tr2;
  119258. ch[(ido<<2)+t5-1]=tr2-tr1;
  119259. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119260. ch[t5]=cc[t2]-cc[t1];
  119261. t1+=ido;
  119262. t2+=ido;
  119263. t3+=ido;
  119264. t4+=ido;
  119265. }
  119266. if(ido<2)return;
  119267. if(ido==2)goto L105;
  119268. t1=0;
  119269. for(k=0;k<l1;k++){
  119270. t2=t1;
  119271. t4=t1<<2;
  119272. t5=(t6=ido<<1)+t4;
  119273. for(i=2;i<ido;i+=2){
  119274. t3=(t2+=2);
  119275. t4+=2;
  119276. t5-=2;
  119277. t3+=t0;
  119278. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119279. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119280. t3+=t0;
  119281. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119282. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119283. t3+=t0;
  119284. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119285. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119286. tr1=cr2+cr4;
  119287. tr4=cr4-cr2;
  119288. ti1=ci2+ci4;
  119289. ti4=ci2-ci4;
  119290. ti2=cc[t2]+ci3;
  119291. ti3=cc[t2]-ci3;
  119292. tr2=cc[t2-1]+cr3;
  119293. tr3=cc[t2-1]-cr3;
  119294. ch[t4-1]=tr1+tr2;
  119295. ch[t4]=ti1+ti2;
  119296. ch[t5-1]=tr3-ti4;
  119297. ch[t5]=tr4-ti3;
  119298. ch[t4+t6-1]=ti4+tr3;
  119299. ch[t4+t6]=tr4+ti3;
  119300. ch[t5+t6-1]=tr2-tr1;
  119301. ch[t5+t6]=ti1-ti2;
  119302. }
  119303. t1+=ido;
  119304. }
  119305. if(ido&1)return;
  119306. L105:
  119307. t2=(t1=t0+ido-1)+(t0<<1);
  119308. t3=ido<<2;
  119309. t4=ido;
  119310. t5=ido<<1;
  119311. t6=ido;
  119312. for(k=0;k<l1;k++){
  119313. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119314. tr1=hsqt2*(cc[t1]-cc[t2]);
  119315. ch[t4-1]=tr1+cc[t6-1];
  119316. ch[t4+t5-1]=cc[t6-1]-tr1;
  119317. ch[t4]=ti1-cc[t1+t0];
  119318. ch[t4+t5]=ti1+cc[t1+t0];
  119319. t1+=ido;
  119320. t2+=ido;
  119321. t4+=t3;
  119322. t6+=ido;
  119323. }
  119324. }
  119325. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119326. float *c2,float *ch,float *ch2,float *wa){
  119327. static float tpi=6.283185307179586f;
  119328. int idij,ipph,i,j,k,l,ic,ik,is;
  119329. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119330. float dc2,ai1,ai2,ar1,ar2,ds2;
  119331. int nbd;
  119332. float dcp,arg,dsp,ar1h,ar2h;
  119333. int idp2,ipp2;
  119334. arg=tpi/(float)ip;
  119335. dcp=cos(arg);
  119336. dsp=sin(arg);
  119337. ipph=(ip+1)>>1;
  119338. ipp2=ip;
  119339. idp2=ido;
  119340. nbd=(ido-1)>>1;
  119341. t0=l1*ido;
  119342. t10=ip*ido;
  119343. if(ido==1)goto L119;
  119344. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119345. t1=0;
  119346. for(j=1;j<ip;j++){
  119347. t1+=t0;
  119348. t2=t1;
  119349. for(k=0;k<l1;k++){
  119350. ch[t2]=c1[t2];
  119351. t2+=ido;
  119352. }
  119353. }
  119354. is=-ido;
  119355. t1=0;
  119356. if(nbd>l1){
  119357. for(j=1;j<ip;j++){
  119358. t1+=t0;
  119359. is+=ido;
  119360. t2= -ido+t1;
  119361. for(k=0;k<l1;k++){
  119362. idij=is-1;
  119363. t2+=ido;
  119364. t3=t2;
  119365. for(i=2;i<ido;i+=2){
  119366. idij+=2;
  119367. t3+=2;
  119368. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119369. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119370. }
  119371. }
  119372. }
  119373. }else{
  119374. for(j=1;j<ip;j++){
  119375. is+=ido;
  119376. idij=is-1;
  119377. t1+=t0;
  119378. t2=t1;
  119379. for(i=2;i<ido;i+=2){
  119380. idij+=2;
  119381. t2+=2;
  119382. t3=t2;
  119383. for(k=0;k<l1;k++){
  119384. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119385. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119386. t3+=ido;
  119387. }
  119388. }
  119389. }
  119390. }
  119391. t1=0;
  119392. t2=ipp2*t0;
  119393. if(nbd<l1){
  119394. for(j=1;j<ipph;j++){
  119395. t1+=t0;
  119396. t2-=t0;
  119397. t3=t1;
  119398. t4=t2;
  119399. for(i=2;i<ido;i+=2){
  119400. t3+=2;
  119401. t4+=2;
  119402. t5=t3-ido;
  119403. t6=t4-ido;
  119404. for(k=0;k<l1;k++){
  119405. t5+=ido;
  119406. t6+=ido;
  119407. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119408. c1[t6-1]=ch[t5]-ch[t6];
  119409. c1[t5]=ch[t5]+ch[t6];
  119410. c1[t6]=ch[t6-1]-ch[t5-1];
  119411. }
  119412. }
  119413. }
  119414. }else{
  119415. for(j=1;j<ipph;j++){
  119416. t1+=t0;
  119417. t2-=t0;
  119418. t3=t1;
  119419. t4=t2;
  119420. for(k=0;k<l1;k++){
  119421. t5=t3;
  119422. t6=t4;
  119423. for(i=2;i<ido;i+=2){
  119424. t5+=2;
  119425. t6+=2;
  119426. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119427. c1[t6-1]=ch[t5]-ch[t6];
  119428. c1[t5]=ch[t5]+ch[t6];
  119429. c1[t6]=ch[t6-1]-ch[t5-1];
  119430. }
  119431. t3+=ido;
  119432. t4+=ido;
  119433. }
  119434. }
  119435. }
  119436. L119:
  119437. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119438. t1=0;
  119439. t2=ipp2*idl1;
  119440. for(j=1;j<ipph;j++){
  119441. t1+=t0;
  119442. t2-=t0;
  119443. t3=t1-ido;
  119444. t4=t2-ido;
  119445. for(k=0;k<l1;k++){
  119446. t3+=ido;
  119447. t4+=ido;
  119448. c1[t3]=ch[t3]+ch[t4];
  119449. c1[t4]=ch[t4]-ch[t3];
  119450. }
  119451. }
  119452. ar1=1.f;
  119453. ai1=0.f;
  119454. t1=0;
  119455. t2=ipp2*idl1;
  119456. t3=(ip-1)*idl1;
  119457. for(l=1;l<ipph;l++){
  119458. t1+=idl1;
  119459. t2-=idl1;
  119460. ar1h=dcp*ar1-dsp*ai1;
  119461. ai1=dcp*ai1+dsp*ar1;
  119462. ar1=ar1h;
  119463. t4=t1;
  119464. t5=t2;
  119465. t6=t3;
  119466. t7=idl1;
  119467. for(ik=0;ik<idl1;ik++){
  119468. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119469. ch2[t5++]=ai1*c2[t6++];
  119470. }
  119471. dc2=ar1;
  119472. ds2=ai1;
  119473. ar2=ar1;
  119474. ai2=ai1;
  119475. t4=idl1;
  119476. t5=(ipp2-1)*idl1;
  119477. for(j=2;j<ipph;j++){
  119478. t4+=idl1;
  119479. t5-=idl1;
  119480. ar2h=dc2*ar2-ds2*ai2;
  119481. ai2=dc2*ai2+ds2*ar2;
  119482. ar2=ar2h;
  119483. t6=t1;
  119484. t7=t2;
  119485. t8=t4;
  119486. t9=t5;
  119487. for(ik=0;ik<idl1;ik++){
  119488. ch2[t6++]+=ar2*c2[t8++];
  119489. ch2[t7++]+=ai2*c2[t9++];
  119490. }
  119491. }
  119492. }
  119493. t1=0;
  119494. for(j=1;j<ipph;j++){
  119495. t1+=idl1;
  119496. t2=t1;
  119497. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119498. }
  119499. if(ido<l1)goto L132;
  119500. t1=0;
  119501. t2=0;
  119502. for(k=0;k<l1;k++){
  119503. t3=t1;
  119504. t4=t2;
  119505. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119506. t1+=ido;
  119507. t2+=t10;
  119508. }
  119509. goto L135;
  119510. L132:
  119511. for(i=0;i<ido;i++){
  119512. t1=i;
  119513. t2=i;
  119514. for(k=0;k<l1;k++){
  119515. cc[t2]=ch[t1];
  119516. t1+=ido;
  119517. t2+=t10;
  119518. }
  119519. }
  119520. L135:
  119521. t1=0;
  119522. t2=ido<<1;
  119523. t3=0;
  119524. t4=ipp2*t0;
  119525. for(j=1;j<ipph;j++){
  119526. t1+=t2;
  119527. t3+=t0;
  119528. t4-=t0;
  119529. t5=t1;
  119530. t6=t3;
  119531. t7=t4;
  119532. for(k=0;k<l1;k++){
  119533. cc[t5-1]=ch[t6];
  119534. cc[t5]=ch[t7];
  119535. t5+=t10;
  119536. t6+=ido;
  119537. t7+=ido;
  119538. }
  119539. }
  119540. if(ido==1)return;
  119541. if(nbd<l1)goto L141;
  119542. t1=-ido;
  119543. t3=0;
  119544. t4=0;
  119545. t5=ipp2*t0;
  119546. for(j=1;j<ipph;j++){
  119547. t1+=t2;
  119548. t3+=t2;
  119549. t4+=t0;
  119550. t5-=t0;
  119551. t6=t1;
  119552. t7=t3;
  119553. t8=t4;
  119554. t9=t5;
  119555. for(k=0;k<l1;k++){
  119556. for(i=2;i<ido;i+=2){
  119557. ic=idp2-i;
  119558. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119559. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119560. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119561. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119562. }
  119563. t6+=t10;
  119564. t7+=t10;
  119565. t8+=ido;
  119566. t9+=ido;
  119567. }
  119568. }
  119569. return;
  119570. L141:
  119571. t1=-ido;
  119572. t3=0;
  119573. t4=0;
  119574. t5=ipp2*t0;
  119575. for(j=1;j<ipph;j++){
  119576. t1+=t2;
  119577. t3+=t2;
  119578. t4+=t0;
  119579. t5-=t0;
  119580. for(i=2;i<ido;i+=2){
  119581. t6=idp2+t1-i;
  119582. t7=i+t3;
  119583. t8=i+t4;
  119584. t9=i+t5;
  119585. for(k=0;k<l1;k++){
  119586. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119587. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119588. cc[t7]=ch[t8]+ch[t9];
  119589. cc[t6]=ch[t9]-ch[t8];
  119590. t6+=t10;
  119591. t7+=t10;
  119592. t8+=ido;
  119593. t9+=ido;
  119594. }
  119595. }
  119596. }
  119597. }
  119598. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119599. int i,k1,l1,l2;
  119600. int na,kh,nf;
  119601. int ip,iw,ido,idl1,ix2,ix3;
  119602. nf=ifac[1];
  119603. na=1;
  119604. l2=n;
  119605. iw=n;
  119606. for(k1=0;k1<nf;k1++){
  119607. kh=nf-k1;
  119608. ip=ifac[kh+1];
  119609. l1=l2/ip;
  119610. ido=n/l2;
  119611. idl1=ido*l1;
  119612. iw-=(ip-1)*ido;
  119613. na=1-na;
  119614. if(ip!=4)goto L102;
  119615. ix2=iw+ido;
  119616. ix3=ix2+ido;
  119617. if(na!=0)
  119618. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119619. else
  119620. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119621. goto L110;
  119622. L102:
  119623. if(ip!=2)goto L104;
  119624. if(na!=0)goto L103;
  119625. dradf2(ido,l1,c,ch,wa+iw-1);
  119626. goto L110;
  119627. L103:
  119628. dradf2(ido,l1,ch,c,wa+iw-1);
  119629. goto L110;
  119630. L104:
  119631. if(ido==1)na=1-na;
  119632. if(na!=0)goto L109;
  119633. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119634. na=1;
  119635. goto L110;
  119636. L109:
  119637. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119638. na=0;
  119639. L110:
  119640. l2=l1;
  119641. }
  119642. if(na==1)return;
  119643. for(i=0;i<n;i++)c[i]=ch[i];
  119644. }
  119645. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119646. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119647. float ti2,tr2;
  119648. t0=l1*ido;
  119649. t1=0;
  119650. t2=0;
  119651. t3=(ido<<1)-1;
  119652. for(k=0;k<l1;k++){
  119653. ch[t1]=cc[t2]+cc[t3+t2];
  119654. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119655. t2=(t1+=ido)<<1;
  119656. }
  119657. if(ido<2)return;
  119658. if(ido==2)goto L105;
  119659. t1=0;
  119660. t2=0;
  119661. for(k=0;k<l1;k++){
  119662. t3=t1;
  119663. t5=(t4=t2)+(ido<<1);
  119664. t6=t0+t1;
  119665. for(i=2;i<ido;i+=2){
  119666. t3+=2;
  119667. t4+=2;
  119668. t5-=2;
  119669. t6+=2;
  119670. ch[t3-1]=cc[t4-1]+cc[t5-1];
  119671. tr2=cc[t4-1]-cc[t5-1];
  119672. ch[t3]=cc[t4]-cc[t5];
  119673. ti2=cc[t4]+cc[t5];
  119674. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  119675. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  119676. }
  119677. t2=(t1+=ido)<<1;
  119678. }
  119679. if(ido%2==1)return;
  119680. L105:
  119681. t1=ido-1;
  119682. t2=ido-1;
  119683. for(k=0;k<l1;k++){
  119684. ch[t1]=cc[t2]+cc[t2];
  119685. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  119686. t1+=ido;
  119687. t2+=ido<<1;
  119688. }
  119689. }
  119690. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  119691. float *wa2){
  119692. static float taur = -.5f;
  119693. static float taui = .8660254037844386f;
  119694. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119695. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  119696. t0=l1*ido;
  119697. t1=0;
  119698. t2=t0<<1;
  119699. t3=ido<<1;
  119700. t4=ido+(ido<<1);
  119701. t5=0;
  119702. for(k=0;k<l1;k++){
  119703. tr2=cc[t3-1]+cc[t3-1];
  119704. cr2=cc[t5]+(taur*tr2);
  119705. ch[t1]=cc[t5]+tr2;
  119706. ci3=taui*(cc[t3]+cc[t3]);
  119707. ch[t1+t0]=cr2-ci3;
  119708. ch[t1+t2]=cr2+ci3;
  119709. t1+=ido;
  119710. t3+=t4;
  119711. t5+=t4;
  119712. }
  119713. if(ido==1)return;
  119714. t1=0;
  119715. t3=ido<<1;
  119716. for(k=0;k<l1;k++){
  119717. t7=t1+(t1<<1);
  119718. t6=(t5=t7+t3);
  119719. t8=t1;
  119720. t10=(t9=t1+t0)+t0;
  119721. for(i=2;i<ido;i+=2){
  119722. t5+=2;
  119723. t6-=2;
  119724. t7+=2;
  119725. t8+=2;
  119726. t9+=2;
  119727. t10+=2;
  119728. tr2=cc[t5-1]+cc[t6-1];
  119729. cr2=cc[t7-1]+(taur*tr2);
  119730. ch[t8-1]=cc[t7-1]+tr2;
  119731. ti2=cc[t5]-cc[t6];
  119732. ci2=cc[t7]+(taur*ti2);
  119733. ch[t8]=cc[t7]+ti2;
  119734. cr3=taui*(cc[t5-1]-cc[t6-1]);
  119735. ci3=taui*(cc[t5]+cc[t6]);
  119736. dr2=cr2-ci3;
  119737. dr3=cr2+ci3;
  119738. di2=ci2+cr3;
  119739. di3=ci2-cr3;
  119740. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  119741. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  119742. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  119743. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  119744. }
  119745. t1+=ido;
  119746. }
  119747. }
  119748. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  119749. float *wa2,float *wa3){
  119750. static float sqrt2=1.414213562373095f;
  119751. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  119752. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119753. t0=l1*ido;
  119754. t1=0;
  119755. t2=ido<<2;
  119756. t3=0;
  119757. t6=ido<<1;
  119758. for(k=0;k<l1;k++){
  119759. t4=t3+t6;
  119760. t5=t1;
  119761. tr3=cc[t4-1]+cc[t4-1];
  119762. tr4=cc[t4]+cc[t4];
  119763. tr1=cc[t3]-cc[(t4+=t6)-1];
  119764. tr2=cc[t3]+cc[t4-1];
  119765. ch[t5]=tr2+tr3;
  119766. ch[t5+=t0]=tr1-tr4;
  119767. ch[t5+=t0]=tr2-tr3;
  119768. ch[t5+=t0]=tr1+tr4;
  119769. t1+=ido;
  119770. t3+=t2;
  119771. }
  119772. if(ido<2)return;
  119773. if(ido==2)goto L105;
  119774. t1=0;
  119775. for(k=0;k<l1;k++){
  119776. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  119777. t7=t1;
  119778. for(i=2;i<ido;i+=2){
  119779. t2+=2;
  119780. t3+=2;
  119781. t4-=2;
  119782. t5-=2;
  119783. t7+=2;
  119784. ti1=cc[t2]+cc[t5];
  119785. ti2=cc[t2]-cc[t5];
  119786. ti3=cc[t3]-cc[t4];
  119787. tr4=cc[t3]+cc[t4];
  119788. tr1=cc[t2-1]-cc[t5-1];
  119789. tr2=cc[t2-1]+cc[t5-1];
  119790. ti4=cc[t3-1]-cc[t4-1];
  119791. tr3=cc[t3-1]+cc[t4-1];
  119792. ch[t7-1]=tr2+tr3;
  119793. cr3=tr2-tr3;
  119794. ch[t7]=ti2+ti3;
  119795. ci3=ti2-ti3;
  119796. cr2=tr1-tr4;
  119797. cr4=tr1+tr4;
  119798. ci2=ti1+ti4;
  119799. ci4=ti1-ti4;
  119800. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  119801. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  119802. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  119803. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  119804. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  119805. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  119806. }
  119807. t1+=ido;
  119808. }
  119809. if(ido%2 == 1)return;
  119810. L105:
  119811. t1=ido;
  119812. t2=ido<<2;
  119813. t3=ido-1;
  119814. t4=ido+(ido<<1);
  119815. for(k=0;k<l1;k++){
  119816. t5=t3;
  119817. ti1=cc[t1]+cc[t4];
  119818. ti2=cc[t4]-cc[t1];
  119819. tr1=cc[t1-1]-cc[t4-1];
  119820. tr2=cc[t1-1]+cc[t4-1];
  119821. ch[t5]=tr2+tr2;
  119822. ch[t5+=t0]=sqrt2*(tr1-ti1);
  119823. ch[t5+=t0]=ti2+ti2;
  119824. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  119825. t3+=ido;
  119826. t1+=t2;
  119827. t4+=t2;
  119828. }
  119829. }
  119830. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119831. float *c2,float *ch,float *ch2,float *wa){
  119832. static float tpi=6.283185307179586f;
  119833. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  119834. t11,t12;
  119835. float dc2,ai1,ai2,ar1,ar2,ds2;
  119836. int nbd;
  119837. float dcp,arg,dsp,ar1h,ar2h;
  119838. int ipp2;
  119839. t10=ip*ido;
  119840. t0=l1*ido;
  119841. arg=tpi/(float)ip;
  119842. dcp=cos(arg);
  119843. dsp=sin(arg);
  119844. nbd=(ido-1)>>1;
  119845. ipp2=ip;
  119846. ipph=(ip+1)>>1;
  119847. if(ido<l1)goto L103;
  119848. t1=0;
  119849. t2=0;
  119850. for(k=0;k<l1;k++){
  119851. t3=t1;
  119852. t4=t2;
  119853. for(i=0;i<ido;i++){
  119854. ch[t3]=cc[t4];
  119855. t3++;
  119856. t4++;
  119857. }
  119858. t1+=ido;
  119859. t2+=t10;
  119860. }
  119861. goto L106;
  119862. L103:
  119863. t1=0;
  119864. for(i=0;i<ido;i++){
  119865. t2=t1;
  119866. t3=t1;
  119867. for(k=0;k<l1;k++){
  119868. ch[t2]=cc[t3];
  119869. t2+=ido;
  119870. t3+=t10;
  119871. }
  119872. t1++;
  119873. }
  119874. L106:
  119875. t1=0;
  119876. t2=ipp2*t0;
  119877. t7=(t5=ido<<1);
  119878. for(j=1;j<ipph;j++){
  119879. t1+=t0;
  119880. t2-=t0;
  119881. t3=t1;
  119882. t4=t2;
  119883. t6=t5;
  119884. for(k=0;k<l1;k++){
  119885. ch[t3]=cc[t6-1]+cc[t6-1];
  119886. ch[t4]=cc[t6]+cc[t6];
  119887. t3+=ido;
  119888. t4+=ido;
  119889. t6+=t10;
  119890. }
  119891. t5+=t7;
  119892. }
  119893. if (ido == 1)goto L116;
  119894. if(nbd<l1)goto L112;
  119895. t1=0;
  119896. t2=ipp2*t0;
  119897. t7=0;
  119898. for(j=1;j<ipph;j++){
  119899. t1+=t0;
  119900. t2-=t0;
  119901. t3=t1;
  119902. t4=t2;
  119903. t7+=(ido<<1);
  119904. t8=t7;
  119905. for(k=0;k<l1;k++){
  119906. t5=t3;
  119907. t6=t4;
  119908. t9=t8;
  119909. t11=t8;
  119910. for(i=2;i<ido;i+=2){
  119911. t5+=2;
  119912. t6+=2;
  119913. t9+=2;
  119914. t11-=2;
  119915. ch[t5-1]=cc[t9-1]+cc[t11-1];
  119916. ch[t6-1]=cc[t9-1]-cc[t11-1];
  119917. ch[t5]=cc[t9]-cc[t11];
  119918. ch[t6]=cc[t9]+cc[t11];
  119919. }
  119920. t3+=ido;
  119921. t4+=ido;
  119922. t8+=t10;
  119923. }
  119924. }
  119925. goto L116;
  119926. L112:
  119927. t1=0;
  119928. t2=ipp2*t0;
  119929. t7=0;
  119930. for(j=1;j<ipph;j++){
  119931. t1+=t0;
  119932. t2-=t0;
  119933. t3=t1;
  119934. t4=t2;
  119935. t7+=(ido<<1);
  119936. t8=t7;
  119937. t9=t7;
  119938. for(i=2;i<ido;i+=2){
  119939. t3+=2;
  119940. t4+=2;
  119941. t8+=2;
  119942. t9-=2;
  119943. t5=t3;
  119944. t6=t4;
  119945. t11=t8;
  119946. t12=t9;
  119947. for(k=0;k<l1;k++){
  119948. ch[t5-1]=cc[t11-1]+cc[t12-1];
  119949. ch[t6-1]=cc[t11-1]-cc[t12-1];
  119950. ch[t5]=cc[t11]-cc[t12];
  119951. ch[t6]=cc[t11]+cc[t12];
  119952. t5+=ido;
  119953. t6+=ido;
  119954. t11+=t10;
  119955. t12+=t10;
  119956. }
  119957. }
  119958. }
  119959. L116:
  119960. ar1=1.f;
  119961. ai1=0.f;
  119962. t1=0;
  119963. t9=(t2=ipp2*idl1);
  119964. t3=(ip-1)*idl1;
  119965. for(l=1;l<ipph;l++){
  119966. t1+=idl1;
  119967. t2-=idl1;
  119968. ar1h=dcp*ar1-dsp*ai1;
  119969. ai1=dcp*ai1+dsp*ar1;
  119970. ar1=ar1h;
  119971. t4=t1;
  119972. t5=t2;
  119973. t6=0;
  119974. t7=idl1;
  119975. t8=t3;
  119976. for(ik=0;ik<idl1;ik++){
  119977. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  119978. c2[t5++]=ai1*ch2[t8++];
  119979. }
  119980. dc2=ar1;
  119981. ds2=ai1;
  119982. ar2=ar1;
  119983. ai2=ai1;
  119984. t6=idl1;
  119985. t7=t9-idl1;
  119986. for(j=2;j<ipph;j++){
  119987. t6+=idl1;
  119988. t7-=idl1;
  119989. ar2h=dc2*ar2-ds2*ai2;
  119990. ai2=dc2*ai2+ds2*ar2;
  119991. ar2=ar2h;
  119992. t4=t1;
  119993. t5=t2;
  119994. t11=t6;
  119995. t12=t7;
  119996. for(ik=0;ik<idl1;ik++){
  119997. c2[t4++]+=ar2*ch2[t11++];
  119998. c2[t5++]+=ai2*ch2[t12++];
  119999. }
  120000. }
  120001. }
  120002. t1=0;
  120003. for(j=1;j<ipph;j++){
  120004. t1+=idl1;
  120005. t2=t1;
  120006. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120007. }
  120008. t1=0;
  120009. t2=ipp2*t0;
  120010. for(j=1;j<ipph;j++){
  120011. t1+=t0;
  120012. t2-=t0;
  120013. t3=t1;
  120014. t4=t2;
  120015. for(k=0;k<l1;k++){
  120016. ch[t3]=c1[t3]-c1[t4];
  120017. ch[t4]=c1[t3]+c1[t4];
  120018. t3+=ido;
  120019. t4+=ido;
  120020. }
  120021. }
  120022. if(ido==1)goto L132;
  120023. if(nbd<l1)goto L128;
  120024. t1=0;
  120025. t2=ipp2*t0;
  120026. for(j=1;j<ipph;j++){
  120027. t1+=t0;
  120028. t2-=t0;
  120029. t3=t1;
  120030. t4=t2;
  120031. for(k=0;k<l1;k++){
  120032. t5=t3;
  120033. t6=t4;
  120034. for(i=2;i<ido;i+=2){
  120035. t5+=2;
  120036. t6+=2;
  120037. ch[t5-1]=c1[t5-1]-c1[t6];
  120038. ch[t6-1]=c1[t5-1]+c1[t6];
  120039. ch[t5]=c1[t5]+c1[t6-1];
  120040. ch[t6]=c1[t5]-c1[t6-1];
  120041. }
  120042. t3+=ido;
  120043. t4+=ido;
  120044. }
  120045. }
  120046. goto L132;
  120047. L128:
  120048. t1=0;
  120049. t2=ipp2*t0;
  120050. for(j=1;j<ipph;j++){
  120051. t1+=t0;
  120052. t2-=t0;
  120053. t3=t1;
  120054. t4=t2;
  120055. for(i=2;i<ido;i+=2){
  120056. t3+=2;
  120057. t4+=2;
  120058. t5=t3;
  120059. t6=t4;
  120060. for(k=0;k<l1;k++){
  120061. ch[t5-1]=c1[t5-1]-c1[t6];
  120062. ch[t6-1]=c1[t5-1]+c1[t6];
  120063. ch[t5]=c1[t5]+c1[t6-1];
  120064. ch[t6]=c1[t5]-c1[t6-1];
  120065. t5+=ido;
  120066. t6+=ido;
  120067. }
  120068. }
  120069. }
  120070. L132:
  120071. if(ido==1)return;
  120072. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120073. t1=0;
  120074. for(j=1;j<ip;j++){
  120075. t2=(t1+=t0);
  120076. for(k=0;k<l1;k++){
  120077. c1[t2]=ch[t2];
  120078. t2+=ido;
  120079. }
  120080. }
  120081. if(nbd>l1)goto L139;
  120082. is= -ido-1;
  120083. t1=0;
  120084. for(j=1;j<ip;j++){
  120085. is+=ido;
  120086. t1+=t0;
  120087. idij=is;
  120088. t2=t1;
  120089. for(i=2;i<ido;i+=2){
  120090. t2+=2;
  120091. idij+=2;
  120092. t3=t2;
  120093. for(k=0;k<l1;k++){
  120094. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120095. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120096. t3+=ido;
  120097. }
  120098. }
  120099. }
  120100. return;
  120101. L139:
  120102. is= -ido-1;
  120103. t1=0;
  120104. for(j=1;j<ip;j++){
  120105. is+=ido;
  120106. t1+=t0;
  120107. t2=t1;
  120108. for(k=0;k<l1;k++){
  120109. idij=is;
  120110. t3=t2;
  120111. for(i=2;i<ido;i+=2){
  120112. idij+=2;
  120113. t3+=2;
  120114. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120115. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120116. }
  120117. t2+=ido;
  120118. }
  120119. }
  120120. }
  120121. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120122. int i,k1,l1,l2;
  120123. int na;
  120124. int nf,ip,iw,ix2,ix3,ido,idl1;
  120125. nf=ifac[1];
  120126. na=0;
  120127. l1=1;
  120128. iw=1;
  120129. for(k1=0;k1<nf;k1++){
  120130. ip=ifac[k1 + 2];
  120131. l2=ip*l1;
  120132. ido=n/l2;
  120133. idl1=ido*l1;
  120134. if(ip!=4)goto L103;
  120135. ix2=iw+ido;
  120136. ix3=ix2+ido;
  120137. if(na!=0)
  120138. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120139. else
  120140. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120141. na=1-na;
  120142. goto L115;
  120143. L103:
  120144. if(ip!=2)goto L106;
  120145. if(na!=0)
  120146. dradb2(ido,l1,ch,c,wa+iw-1);
  120147. else
  120148. dradb2(ido,l1,c,ch,wa+iw-1);
  120149. na=1-na;
  120150. goto L115;
  120151. L106:
  120152. if(ip!=3)goto L109;
  120153. ix2=iw+ido;
  120154. if(na!=0)
  120155. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120156. else
  120157. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120158. na=1-na;
  120159. goto L115;
  120160. L109:
  120161. /* The radix five case can be translated later..... */
  120162. /* if(ip!=5)goto L112;
  120163. ix2=iw+ido;
  120164. ix3=ix2+ido;
  120165. ix4=ix3+ido;
  120166. if(na!=0)
  120167. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120168. else
  120169. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120170. na=1-na;
  120171. goto L115;
  120172. L112:*/
  120173. if(na!=0)
  120174. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120175. else
  120176. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120177. if(ido==1)na=1-na;
  120178. L115:
  120179. l1=l2;
  120180. iw+=(ip-1)*ido;
  120181. }
  120182. if(na==0)return;
  120183. for(i=0;i<n;i++)c[i]=ch[i];
  120184. }
  120185. void drft_forward(drft_lookup *l,float *data){
  120186. if(l->n==1)return;
  120187. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120188. }
  120189. void drft_backward(drft_lookup *l,float *data){
  120190. if (l->n==1)return;
  120191. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120192. }
  120193. void drft_init(drft_lookup *l,int n){
  120194. l->n=n;
  120195. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120196. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120197. fdrffti(n, l->trigcache, l->splitcache);
  120198. }
  120199. void drft_clear(drft_lookup *l){
  120200. if(l){
  120201. if(l->trigcache)_ogg_free(l->trigcache);
  120202. if(l->splitcache)_ogg_free(l->splitcache);
  120203. memset(l,0,sizeof(*l));
  120204. }
  120205. }
  120206. #endif
  120207. /*** End of inlined file: smallft.c ***/
  120208. /*** Start of inlined file: synthesis.c ***/
  120209. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120210. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120211. // tasks..
  120212. #if JUCE_MSVC
  120213. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120214. #endif
  120215. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120216. #if JUCE_USE_OGGVORBIS
  120217. #include <stdio.h>
  120218. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120219. vorbis_dsp_state *vd=vb->vd;
  120220. private_state *b=(private_state*)vd->backend_state;
  120221. vorbis_info *vi=vd->vi;
  120222. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120223. oggpack_buffer *opb=&vb->opb;
  120224. int type,mode,i;
  120225. /* first things first. Make sure decode is ready */
  120226. _vorbis_block_ripcord(vb);
  120227. oggpack_readinit(opb,op->packet,op->bytes);
  120228. /* Check the packet type */
  120229. if(oggpack_read(opb,1)!=0){
  120230. /* Oops. This is not an audio data packet */
  120231. return(OV_ENOTAUDIO);
  120232. }
  120233. /* read our mode and pre/post windowsize */
  120234. mode=oggpack_read(opb,b->modebits);
  120235. if(mode==-1)return(OV_EBADPACKET);
  120236. vb->mode=mode;
  120237. vb->W=ci->mode_param[mode]->blockflag;
  120238. if(vb->W){
  120239. /* this doesn;t get mapped through mode selection as it's used
  120240. only for window selection */
  120241. vb->lW=oggpack_read(opb,1);
  120242. vb->nW=oggpack_read(opb,1);
  120243. if(vb->nW==-1) return(OV_EBADPACKET);
  120244. }else{
  120245. vb->lW=0;
  120246. vb->nW=0;
  120247. }
  120248. /* more setup */
  120249. vb->granulepos=op->granulepos;
  120250. vb->sequence=op->packetno;
  120251. vb->eofflag=op->e_o_s;
  120252. /* alloc pcm passback storage */
  120253. vb->pcmend=ci->blocksizes[vb->W];
  120254. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120255. for(i=0;i<vi->channels;i++)
  120256. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120257. /* unpack_header enforces range checking */
  120258. type=ci->map_type[ci->mode_param[mode]->mapping];
  120259. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120260. mapping]));
  120261. }
  120262. /* used to track pcm position without actually performing decode.
  120263. Useful for sequential 'fast forward' */
  120264. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120265. vorbis_dsp_state *vd=vb->vd;
  120266. private_state *b=(private_state*)vd->backend_state;
  120267. vorbis_info *vi=vd->vi;
  120268. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120269. oggpack_buffer *opb=&vb->opb;
  120270. int mode;
  120271. /* first things first. Make sure decode is ready */
  120272. _vorbis_block_ripcord(vb);
  120273. oggpack_readinit(opb,op->packet,op->bytes);
  120274. /* Check the packet type */
  120275. if(oggpack_read(opb,1)!=0){
  120276. /* Oops. This is not an audio data packet */
  120277. return(OV_ENOTAUDIO);
  120278. }
  120279. /* read our mode and pre/post windowsize */
  120280. mode=oggpack_read(opb,b->modebits);
  120281. if(mode==-1)return(OV_EBADPACKET);
  120282. vb->mode=mode;
  120283. vb->W=ci->mode_param[mode]->blockflag;
  120284. if(vb->W){
  120285. vb->lW=oggpack_read(opb,1);
  120286. vb->nW=oggpack_read(opb,1);
  120287. if(vb->nW==-1) return(OV_EBADPACKET);
  120288. }else{
  120289. vb->lW=0;
  120290. vb->nW=0;
  120291. }
  120292. /* more setup */
  120293. vb->granulepos=op->granulepos;
  120294. vb->sequence=op->packetno;
  120295. vb->eofflag=op->e_o_s;
  120296. /* no pcm */
  120297. vb->pcmend=0;
  120298. vb->pcm=NULL;
  120299. return(0);
  120300. }
  120301. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120302. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120303. oggpack_buffer opb;
  120304. int mode;
  120305. oggpack_readinit(&opb,op->packet,op->bytes);
  120306. /* Check the packet type */
  120307. if(oggpack_read(&opb,1)!=0){
  120308. /* Oops. This is not an audio data packet */
  120309. return(OV_ENOTAUDIO);
  120310. }
  120311. {
  120312. int modebits=0;
  120313. int v=ci->modes;
  120314. while(v>1){
  120315. modebits++;
  120316. v>>=1;
  120317. }
  120318. /* read our mode and pre/post windowsize */
  120319. mode=oggpack_read(&opb,modebits);
  120320. }
  120321. if(mode==-1)return(OV_EBADPACKET);
  120322. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120323. }
  120324. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120325. /* set / clear half-sample-rate mode */
  120326. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120327. /* right now, our MDCT can't handle < 64 sample windows. */
  120328. if(ci->blocksizes[0]<=64 && flag)return -1;
  120329. ci->halfrate_flag=(flag?1:0);
  120330. return 0;
  120331. }
  120332. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120333. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120334. return ci->halfrate_flag;
  120335. }
  120336. #endif
  120337. /*** End of inlined file: synthesis.c ***/
  120338. /*** Start of inlined file: vorbisenc.c ***/
  120339. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120340. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120341. // tasks..
  120342. #if JUCE_MSVC
  120343. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120344. #endif
  120345. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120346. #if JUCE_USE_OGGVORBIS
  120347. #include <stdlib.h>
  120348. #include <string.h>
  120349. #include <math.h>
  120350. /* careful with this; it's using static array sizing to make managing
  120351. all the modes a little less annoying. If we use a residue backend
  120352. with > 12 partition types, or a different division of iteration,
  120353. this needs to be updated. */
  120354. typedef struct {
  120355. static_codebook *books[12][3];
  120356. } static_bookblock;
  120357. typedef struct {
  120358. int res_type;
  120359. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120360. vorbis_info_residue0 *res;
  120361. static_codebook *book_aux;
  120362. static_codebook *book_aux_managed;
  120363. static_bookblock *books_base;
  120364. static_bookblock *books_base_managed;
  120365. } vorbis_residue_template;
  120366. typedef struct {
  120367. vorbis_info_mapping0 *map;
  120368. vorbis_residue_template *res;
  120369. } vorbis_mapping_template;
  120370. typedef struct vp_adjblock{
  120371. int block[P_BANDS];
  120372. } vp_adjblock;
  120373. typedef struct {
  120374. int data[NOISE_COMPAND_LEVELS];
  120375. } compandblock;
  120376. /* high level configuration information for setting things up
  120377. step-by-step with the detailed vorbis_encode_ctl interface.
  120378. There's a fair amount of redundancy such that interactive setup
  120379. does not directly deal with any vorbis_info or codec_setup_info
  120380. initialization; it's all stored (until full init) in this highlevel
  120381. setup, then flushed out to the real codec setup structs later. */
  120382. typedef struct {
  120383. int att[P_NOISECURVES];
  120384. float boost;
  120385. float decay;
  120386. } att3;
  120387. typedef struct { int data[P_NOISECURVES]; } adj3;
  120388. typedef struct {
  120389. int pre[PACKETBLOBS];
  120390. int post[PACKETBLOBS];
  120391. float kHz[PACKETBLOBS];
  120392. float lowpasskHz[PACKETBLOBS];
  120393. } adj_stereo;
  120394. typedef struct {
  120395. int lo;
  120396. int hi;
  120397. int fixed;
  120398. } noiseguard;
  120399. typedef struct {
  120400. int data[P_NOISECURVES][17];
  120401. } noise3;
  120402. typedef struct {
  120403. int mappings;
  120404. double *rate_mapping;
  120405. double *quality_mapping;
  120406. int coupling_restriction;
  120407. long samplerate_min_restriction;
  120408. long samplerate_max_restriction;
  120409. int *blocksize_short;
  120410. int *blocksize_long;
  120411. att3 *psy_tone_masteratt;
  120412. int *psy_tone_0dB;
  120413. int *psy_tone_dBsuppress;
  120414. vp_adjblock *psy_tone_adj_impulse;
  120415. vp_adjblock *psy_tone_adj_long;
  120416. vp_adjblock *psy_tone_adj_other;
  120417. noiseguard *psy_noiseguards;
  120418. noise3 *psy_noise_bias_impulse;
  120419. noise3 *psy_noise_bias_padding;
  120420. noise3 *psy_noise_bias_trans;
  120421. noise3 *psy_noise_bias_long;
  120422. int *psy_noise_dBsuppress;
  120423. compandblock *psy_noise_compand;
  120424. double *psy_noise_compand_short_mapping;
  120425. double *psy_noise_compand_long_mapping;
  120426. int *psy_noise_normal_start[2];
  120427. int *psy_noise_normal_partition[2];
  120428. double *psy_noise_normal_thresh;
  120429. int *psy_ath_float;
  120430. int *psy_ath_abs;
  120431. double *psy_lowpass;
  120432. vorbis_info_psy_global *global_params;
  120433. double *global_mapping;
  120434. adj_stereo *stereo_modes;
  120435. static_codebook ***floor_books;
  120436. vorbis_info_floor1 *floor_params;
  120437. int *floor_short_mapping;
  120438. int *floor_long_mapping;
  120439. vorbis_mapping_template *maps;
  120440. } ve_setup_data_template;
  120441. /* a few static coder conventions */
  120442. static vorbis_info_mode _mode_template[2]={
  120443. {0,0,0,0},
  120444. {1,0,0,1}
  120445. };
  120446. static vorbis_info_mapping0 _map_nominal[2]={
  120447. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120448. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120449. };
  120450. /*** Start of inlined file: setup_44.h ***/
  120451. /*** Start of inlined file: floor_all.h ***/
  120452. /*** Start of inlined file: floor_books.h ***/
  120453. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120454. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120455. };
  120456. static static_codebook _huff_book_line_256x7_0sub1 = {
  120457. 1, 9,
  120458. _huff_lengthlist_line_256x7_0sub1,
  120459. 0, 0, 0, 0, 0,
  120460. NULL,
  120461. NULL,
  120462. NULL,
  120463. NULL,
  120464. 0
  120465. };
  120466. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120468. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120469. };
  120470. static static_codebook _huff_book_line_256x7_0sub2 = {
  120471. 1, 25,
  120472. _huff_lengthlist_line_256x7_0sub2,
  120473. 0, 0, 0, 0, 0,
  120474. NULL,
  120475. NULL,
  120476. NULL,
  120477. NULL,
  120478. 0
  120479. };
  120480. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120483. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120484. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120485. };
  120486. static static_codebook _huff_book_line_256x7_0sub3 = {
  120487. 1, 64,
  120488. _huff_lengthlist_line_256x7_0sub3,
  120489. 0, 0, 0, 0, 0,
  120490. NULL,
  120491. NULL,
  120492. NULL,
  120493. NULL,
  120494. 0
  120495. };
  120496. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120497. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120498. };
  120499. static static_codebook _huff_book_line_256x7_1sub1 = {
  120500. 1, 9,
  120501. _huff_lengthlist_line_256x7_1sub1,
  120502. 0, 0, 0, 0, 0,
  120503. NULL,
  120504. NULL,
  120505. NULL,
  120506. NULL,
  120507. 0
  120508. };
  120509. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120511. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120512. };
  120513. static static_codebook _huff_book_line_256x7_1sub2 = {
  120514. 1, 25,
  120515. _huff_lengthlist_line_256x7_1sub2,
  120516. 0, 0, 0, 0, 0,
  120517. NULL,
  120518. NULL,
  120519. NULL,
  120520. NULL,
  120521. 0
  120522. };
  120523. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120526. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120527. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120528. };
  120529. static static_codebook _huff_book_line_256x7_1sub3 = {
  120530. 1, 64,
  120531. _huff_lengthlist_line_256x7_1sub3,
  120532. 0, 0, 0, 0, 0,
  120533. NULL,
  120534. NULL,
  120535. NULL,
  120536. NULL,
  120537. 0
  120538. };
  120539. static long _huff_lengthlist_line_256x7_class0[] = {
  120540. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120541. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120542. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120543. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120544. };
  120545. static static_codebook _huff_book_line_256x7_class0 = {
  120546. 1, 64,
  120547. _huff_lengthlist_line_256x7_class0,
  120548. 0, 0, 0, 0, 0,
  120549. NULL,
  120550. NULL,
  120551. NULL,
  120552. NULL,
  120553. 0
  120554. };
  120555. static long _huff_lengthlist_line_256x7_class1[] = {
  120556. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120557. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120558. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120559. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120560. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120561. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120562. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120563. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120564. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120565. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120566. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120567. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120568. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120569. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120570. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120571. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120572. };
  120573. static static_codebook _huff_book_line_256x7_class1 = {
  120574. 1, 256,
  120575. _huff_lengthlist_line_256x7_class1,
  120576. 0, 0, 0, 0, 0,
  120577. NULL,
  120578. NULL,
  120579. NULL,
  120580. NULL,
  120581. 0
  120582. };
  120583. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120584. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120585. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120586. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120587. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120588. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120589. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120590. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120591. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120592. };
  120593. static static_codebook _huff_book_line_512x17_0sub0 = {
  120594. 1, 128,
  120595. _huff_lengthlist_line_512x17_0sub0,
  120596. 0, 0, 0, 0, 0,
  120597. NULL,
  120598. NULL,
  120599. NULL,
  120600. NULL,
  120601. 0
  120602. };
  120603. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120604. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120605. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120606. };
  120607. static static_codebook _huff_book_line_512x17_1sub0 = {
  120608. 1, 32,
  120609. _huff_lengthlist_line_512x17_1sub0,
  120610. 0, 0, 0, 0, 0,
  120611. NULL,
  120612. NULL,
  120613. NULL,
  120614. NULL,
  120615. 0
  120616. };
  120617. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120620. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120621. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120622. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120623. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120624. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120625. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120626. };
  120627. static static_codebook _huff_book_line_512x17_1sub1 = {
  120628. 1, 128,
  120629. _huff_lengthlist_line_512x17_1sub1,
  120630. 0, 0, 0, 0, 0,
  120631. NULL,
  120632. NULL,
  120633. NULL,
  120634. NULL,
  120635. 0
  120636. };
  120637. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120638. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120639. 5, 3,
  120640. };
  120641. static static_codebook _huff_book_line_512x17_2sub1 = {
  120642. 1, 18,
  120643. _huff_lengthlist_line_512x17_2sub1,
  120644. 0, 0, 0, 0, 0,
  120645. NULL,
  120646. NULL,
  120647. NULL,
  120648. NULL,
  120649. 0
  120650. };
  120651. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120653. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120654. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120655. 9, 8,
  120656. };
  120657. static static_codebook _huff_book_line_512x17_2sub2 = {
  120658. 1, 50,
  120659. _huff_lengthlist_line_512x17_2sub2,
  120660. 0, 0, 0, 0, 0,
  120661. NULL,
  120662. NULL,
  120663. NULL,
  120664. NULL,
  120665. 0
  120666. };
  120667. static long _huff_lengthlist_line_512x17_2sub3[] = {
  120668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120671. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  120672. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  120673. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  120676. };
  120677. static static_codebook _huff_book_line_512x17_2sub3 = {
  120678. 1, 128,
  120679. _huff_lengthlist_line_512x17_2sub3,
  120680. 0, 0, 0, 0, 0,
  120681. NULL,
  120682. NULL,
  120683. NULL,
  120684. NULL,
  120685. 0
  120686. };
  120687. static long _huff_lengthlist_line_512x17_3sub1[] = {
  120688. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  120689. 5, 5,
  120690. };
  120691. static static_codebook _huff_book_line_512x17_3sub1 = {
  120692. 1, 18,
  120693. _huff_lengthlist_line_512x17_3sub1,
  120694. 0, 0, 0, 0, 0,
  120695. NULL,
  120696. NULL,
  120697. NULL,
  120698. NULL,
  120699. 0
  120700. };
  120701. static long _huff_lengthlist_line_512x17_3sub2[] = {
  120702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120703. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  120704. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  120705. 11,14,
  120706. };
  120707. static static_codebook _huff_book_line_512x17_3sub2 = {
  120708. 1, 50,
  120709. _huff_lengthlist_line_512x17_3sub2,
  120710. 0, 0, 0, 0, 0,
  120711. NULL,
  120712. NULL,
  120713. NULL,
  120714. NULL,
  120715. 0
  120716. };
  120717. static long _huff_lengthlist_line_512x17_3sub3[] = {
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120721. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  120722. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120723. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120724. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120725. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  120726. };
  120727. static static_codebook _huff_book_line_512x17_3sub3 = {
  120728. 1, 128,
  120729. _huff_lengthlist_line_512x17_3sub3,
  120730. 0, 0, 0, 0, 0,
  120731. NULL,
  120732. NULL,
  120733. NULL,
  120734. NULL,
  120735. 0
  120736. };
  120737. static long _huff_lengthlist_line_512x17_class1[] = {
  120738. 1, 2, 3, 6, 5, 4, 7, 7,
  120739. };
  120740. static static_codebook _huff_book_line_512x17_class1 = {
  120741. 1, 8,
  120742. _huff_lengthlist_line_512x17_class1,
  120743. 0, 0, 0, 0, 0,
  120744. NULL,
  120745. NULL,
  120746. NULL,
  120747. NULL,
  120748. 0
  120749. };
  120750. static long _huff_lengthlist_line_512x17_class2[] = {
  120751. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  120752. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  120753. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  120754. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  120755. };
  120756. static static_codebook _huff_book_line_512x17_class2 = {
  120757. 1, 64,
  120758. _huff_lengthlist_line_512x17_class2,
  120759. 0, 0, 0, 0, 0,
  120760. NULL,
  120761. NULL,
  120762. NULL,
  120763. NULL,
  120764. 0
  120765. };
  120766. static long _huff_lengthlist_line_512x17_class3[] = {
  120767. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  120768. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  120769. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  120770. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  120771. };
  120772. static static_codebook _huff_book_line_512x17_class3 = {
  120773. 1, 64,
  120774. _huff_lengthlist_line_512x17_class3,
  120775. 0, 0, 0, 0, 0,
  120776. NULL,
  120777. NULL,
  120778. NULL,
  120779. NULL,
  120780. 0
  120781. };
  120782. static long _huff_lengthlist_line_128x4_class0[] = {
  120783. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  120784. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  120785. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  120786. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  120787. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  120788. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  120789. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  120790. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  120791. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  120792. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  120793. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  120794. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  120795. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  120796. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  120797. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  120798. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  120799. };
  120800. static static_codebook _huff_book_line_128x4_class0 = {
  120801. 1, 256,
  120802. _huff_lengthlist_line_128x4_class0,
  120803. 0, 0, 0, 0, 0,
  120804. NULL,
  120805. NULL,
  120806. NULL,
  120807. NULL,
  120808. 0
  120809. };
  120810. static long _huff_lengthlist_line_128x4_0sub0[] = {
  120811. 2, 2, 2, 2,
  120812. };
  120813. static static_codebook _huff_book_line_128x4_0sub0 = {
  120814. 1, 4,
  120815. _huff_lengthlist_line_128x4_0sub0,
  120816. 0, 0, 0, 0, 0,
  120817. NULL,
  120818. NULL,
  120819. NULL,
  120820. NULL,
  120821. 0
  120822. };
  120823. static long _huff_lengthlist_line_128x4_0sub1[] = {
  120824. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  120825. };
  120826. static static_codebook _huff_book_line_128x4_0sub1 = {
  120827. 1, 10,
  120828. _huff_lengthlist_line_128x4_0sub1,
  120829. 0, 0, 0, 0, 0,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. NULL,
  120834. 0
  120835. };
  120836. static long _huff_lengthlist_line_128x4_0sub2[] = {
  120837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  120838. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  120839. };
  120840. static static_codebook _huff_book_line_128x4_0sub2 = {
  120841. 1, 25,
  120842. _huff_lengthlist_line_128x4_0sub2,
  120843. 0, 0, 0, 0, 0,
  120844. NULL,
  120845. NULL,
  120846. NULL,
  120847. NULL,
  120848. 0
  120849. };
  120850. static long _huff_lengthlist_line_128x4_0sub3[] = {
  120851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120853. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  120854. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  120855. };
  120856. static static_codebook _huff_book_line_128x4_0sub3 = {
  120857. 1, 64,
  120858. _huff_lengthlist_line_128x4_0sub3,
  120859. 0, 0, 0, 0, 0,
  120860. NULL,
  120861. NULL,
  120862. NULL,
  120863. NULL,
  120864. 0
  120865. };
  120866. static long _huff_lengthlist_line_256x4_class0[] = {
  120867. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  120868. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  120869. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  120870. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  120871. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  120872. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  120873. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  120874. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  120875. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  120876. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  120877. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  120878. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  120879. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  120880. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  120881. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  120882. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  120883. };
  120884. static static_codebook _huff_book_line_256x4_class0 = {
  120885. 1, 256,
  120886. _huff_lengthlist_line_256x4_class0,
  120887. 0, 0, 0, 0, 0,
  120888. NULL,
  120889. NULL,
  120890. NULL,
  120891. NULL,
  120892. 0
  120893. };
  120894. static long _huff_lengthlist_line_256x4_0sub0[] = {
  120895. 2, 2, 2, 2,
  120896. };
  120897. static static_codebook _huff_book_line_256x4_0sub0 = {
  120898. 1, 4,
  120899. _huff_lengthlist_line_256x4_0sub0,
  120900. 0, 0, 0, 0, 0,
  120901. NULL,
  120902. NULL,
  120903. NULL,
  120904. NULL,
  120905. 0
  120906. };
  120907. static long _huff_lengthlist_line_256x4_0sub1[] = {
  120908. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  120909. };
  120910. static static_codebook _huff_book_line_256x4_0sub1 = {
  120911. 1, 10,
  120912. _huff_lengthlist_line_256x4_0sub1,
  120913. 0, 0, 0, 0, 0,
  120914. NULL,
  120915. NULL,
  120916. NULL,
  120917. NULL,
  120918. 0
  120919. };
  120920. static long _huff_lengthlist_line_256x4_0sub2[] = {
  120921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  120922. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  120923. };
  120924. static static_codebook _huff_book_line_256x4_0sub2 = {
  120925. 1, 25,
  120926. _huff_lengthlist_line_256x4_0sub2,
  120927. 0, 0, 0, 0, 0,
  120928. NULL,
  120929. NULL,
  120930. NULL,
  120931. NULL,
  120932. 0
  120933. };
  120934. static long _huff_lengthlist_line_256x4_0sub3[] = {
  120935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  120937. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  120938. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  120939. };
  120940. static static_codebook _huff_book_line_256x4_0sub3 = {
  120941. 1, 64,
  120942. _huff_lengthlist_line_256x4_0sub3,
  120943. 0, 0, 0, 0, 0,
  120944. NULL,
  120945. NULL,
  120946. NULL,
  120947. NULL,
  120948. 0
  120949. };
  120950. static long _huff_lengthlist_line_128x7_class0[] = {
  120951. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  120952. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  120953. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  120954. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  120955. };
  120956. static static_codebook _huff_book_line_128x7_class0 = {
  120957. 1, 64,
  120958. _huff_lengthlist_line_128x7_class0,
  120959. 0, 0, 0, 0, 0,
  120960. NULL,
  120961. NULL,
  120962. NULL,
  120963. NULL,
  120964. 0
  120965. };
  120966. static long _huff_lengthlist_line_128x7_class1[] = {
  120967. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  120968. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  120969. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  120970. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  120971. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  120972. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  120973. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  120974. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  120975. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  120976. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  120977. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  120978. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  120979. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  120980. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  120981. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  120982. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  120983. };
  120984. static static_codebook _huff_book_line_128x7_class1 = {
  120985. 1, 256,
  120986. _huff_lengthlist_line_128x7_class1,
  120987. 0, 0, 0, 0, 0,
  120988. NULL,
  120989. NULL,
  120990. NULL,
  120991. NULL,
  120992. 0
  120993. };
  120994. static long _huff_lengthlist_line_128x7_0sub1[] = {
  120995. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  120996. };
  120997. static static_codebook _huff_book_line_128x7_0sub1 = {
  120998. 1, 9,
  120999. _huff_lengthlist_line_128x7_0sub1,
  121000. 0, 0, 0, 0, 0,
  121001. NULL,
  121002. NULL,
  121003. NULL,
  121004. NULL,
  121005. 0
  121006. };
  121007. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121009. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121010. };
  121011. static static_codebook _huff_book_line_128x7_0sub2 = {
  121012. 1, 25,
  121013. _huff_lengthlist_line_128x7_0sub2,
  121014. 0, 0, 0, 0, 0,
  121015. NULL,
  121016. NULL,
  121017. NULL,
  121018. NULL,
  121019. 0
  121020. };
  121021. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121024. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121025. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121026. };
  121027. static static_codebook _huff_book_line_128x7_0sub3 = {
  121028. 1, 64,
  121029. _huff_lengthlist_line_128x7_0sub3,
  121030. 0, 0, 0, 0, 0,
  121031. NULL,
  121032. NULL,
  121033. NULL,
  121034. NULL,
  121035. 0
  121036. };
  121037. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121038. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121039. };
  121040. static static_codebook _huff_book_line_128x7_1sub1 = {
  121041. 1, 9,
  121042. _huff_lengthlist_line_128x7_1sub1,
  121043. 0, 0, 0, 0, 0,
  121044. NULL,
  121045. NULL,
  121046. NULL,
  121047. NULL,
  121048. 0
  121049. };
  121050. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121052. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121053. };
  121054. static static_codebook _huff_book_line_128x7_1sub2 = {
  121055. 1, 25,
  121056. _huff_lengthlist_line_128x7_1sub2,
  121057. 0, 0, 0, 0, 0,
  121058. NULL,
  121059. NULL,
  121060. NULL,
  121061. NULL,
  121062. 0
  121063. };
  121064. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121067. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121068. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121069. };
  121070. static static_codebook _huff_book_line_128x7_1sub3 = {
  121071. 1, 64,
  121072. _huff_lengthlist_line_128x7_1sub3,
  121073. 0, 0, 0, 0, 0,
  121074. NULL,
  121075. NULL,
  121076. NULL,
  121077. NULL,
  121078. 0
  121079. };
  121080. static long _huff_lengthlist_line_128x11_class1[] = {
  121081. 1, 6, 3, 7, 2, 4, 5, 7,
  121082. };
  121083. static static_codebook _huff_book_line_128x11_class1 = {
  121084. 1, 8,
  121085. _huff_lengthlist_line_128x11_class1,
  121086. 0, 0, 0, 0, 0,
  121087. NULL,
  121088. NULL,
  121089. NULL,
  121090. NULL,
  121091. 0
  121092. };
  121093. static long _huff_lengthlist_line_128x11_class2[] = {
  121094. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121095. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121096. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121097. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121098. };
  121099. static static_codebook _huff_book_line_128x11_class2 = {
  121100. 1, 64,
  121101. _huff_lengthlist_line_128x11_class2,
  121102. 0, 0, 0, 0, 0,
  121103. NULL,
  121104. NULL,
  121105. NULL,
  121106. NULL,
  121107. 0
  121108. };
  121109. static long _huff_lengthlist_line_128x11_class3[] = {
  121110. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121111. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121112. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121113. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121114. };
  121115. static static_codebook _huff_book_line_128x11_class3 = {
  121116. 1, 64,
  121117. _huff_lengthlist_line_128x11_class3,
  121118. 0, 0, 0, 0, 0,
  121119. NULL,
  121120. NULL,
  121121. NULL,
  121122. NULL,
  121123. 0
  121124. };
  121125. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121126. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121127. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121128. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121129. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121130. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121131. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121132. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121133. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121134. };
  121135. static static_codebook _huff_book_line_128x11_0sub0 = {
  121136. 1, 128,
  121137. _huff_lengthlist_line_128x11_0sub0,
  121138. 0, 0, 0, 0, 0,
  121139. NULL,
  121140. NULL,
  121141. NULL,
  121142. NULL,
  121143. 0
  121144. };
  121145. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121146. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121147. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121148. };
  121149. static static_codebook _huff_book_line_128x11_1sub0 = {
  121150. 1, 32,
  121151. _huff_lengthlist_line_128x11_1sub0,
  121152. 0, 0, 0, 0, 0,
  121153. NULL,
  121154. NULL,
  121155. NULL,
  121156. NULL,
  121157. 0
  121158. };
  121159. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121162. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121163. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121164. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121165. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121166. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121167. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121168. };
  121169. static static_codebook _huff_book_line_128x11_1sub1 = {
  121170. 1, 128,
  121171. _huff_lengthlist_line_128x11_1sub1,
  121172. 0, 0, 0, 0, 0,
  121173. NULL,
  121174. NULL,
  121175. NULL,
  121176. NULL,
  121177. 0
  121178. };
  121179. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121180. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121181. 5, 5,
  121182. };
  121183. static static_codebook _huff_book_line_128x11_2sub1 = {
  121184. 1, 18,
  121185. _huff_lengthlist_line_128x11_2sub1,
  121186. 0, 0, 0, 0, 0,
  121187. NULL,
  121188. NULL,
  121189. NULL,
  121190. NULL,
  121191. 0
  121192. };
  121193. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121195. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121196. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121197. 8,11,
  121198. };
  121199. static static_codebook _huff_book_line_128x11_2sub2 = {
  121200. 1, 50,
  121201. _huff_lengthlist_line_128x11_2sub2,
  121202. 0, 0, 0, 0, 0,
  121203. NULL,
  121204. NULL,
  121205. NULL,
  121206. NULL,
  121207. 0
  121208. };
  121209. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121213. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121214. 4, 8, 6, 8, 7, 8, 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. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121217. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121218. };
  121219. static static_codebook _huff_book_line_128x11_2sub3 = {
  121220. 1, 128,
  121221. _huff_lengthlist_line_128x11_2sub3,
  121222. 0, 0, 0, 0, 0,
  121223. NULL,
  121224. NULL,
  121225. NULL,
  121226. NULL,
  121227. 0
  121228. };
  121229. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121230. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121231. 5, 4,
  121232. };
  121233. static static_codebook _huff_book_line_128x11_3sub1 = {
  121234. 1, 18,
  121235. _huff_lengthlist_line_128x11_3sub1,
  121236. 0, 0, 0, 0, 0,
  121237. NULL,
  121238. NULL,
  121239. NULL,
  121240. NULL,
  121241. 0
  121242. };
  121243. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121245. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121246. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121247. 12, 6,
  121248. };
  121249. static static_codebook _huff_book_line_128x11_3sub2 = {
  121250. 1, 50,
  121251. _huff_lengthlist_line_128x11_3sub2,
  121252. 0, 0, 0, 0, 0,
  121253. NULL,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. 0
  121258. };
  121259. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121263. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121264. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121265. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121266. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121267. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121268. };
  121269. static static_codebook _huff_book_line_128x11_3sub3 = {
  121270. 1, 128,
  121271. _huff_lengthlist_line_128x11_3sub3,
  121272. 0, 0, 0, 0, 0,
  121273. NULL,
  121274. NULL,
  121275. NULL,
  121276. NULL,
  121277. 0
  121278. };
  121279. static long _huff_lengthlist_line_128x17_class1[] = {
  121280. 1, 3, 4, 7, 2, 5, 6, 7,
  121281. };
  121282. static static_codebook _huff_book_line_128x17_class1 = {
  121283. 1, 8,
  121284. _huff_lengthlist_line_128x17_class1,
  121285. 0, 0, 0, 0, 0,
  121286. NULL,
  121287. NULL,
  121288. NULL,
  121289. NULL,
  121290. 0
  121291. };
  121292. static long _huff_lengthlist_line_128x17_class2[] = {
  121293. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121294. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121295. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121296. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121297. };
  121298. static static_codebook _huff_book_line_128x17_class2 = {
  121299. 1, 64,
  121300. _huff_lengthlist_line_128x17_class2,
  121301. 0, 0, 0, 0, 0,
  121302. NULL,
  121303. NULL,
  121304. NULL,
  121305. NULL,
  121306. 0
  121307. };
  121308. static long _huff_lengthlist_line_128x17_class3[] = {
  121309. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121310. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121311. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121312. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121313. };
  121314. static static_codebook _huff_book_line_128x17_class3 = {
  121315. 1, 64,
  121316. _huff_lengthlist_line_128x17_class3,
  121317. 0, 0, 0, 0, 0,
  121318. NULL,
  121319. NULL,
  121320. NULL,
  121321. NULL,
  121322. 0
  121323. };
  121324. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121325. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121326. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121327. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121328. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121329. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121330. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121331. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121332. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121333. };
  121334. static static_codebook _huff_book_line_128x17_0sub0 = {
  121335. 1, 128,
  121336. _huff_lengthlist_line_128x17_0sub0,
  121337. 0, 0, 0, 0, 0,
  121338. NULL,
  121339. NULL,
  121340. NULL,
  121341. NULL,
  121342. 0
  121343. };
  121344. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121345. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121346. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121347. };
  121348. static static_codebook _huff_book_line_128x17_1sub0 = {
  121349. 1, 32,
  121350. _huff_lengthlist_line_128x17_1sub0,
  121351. 0, 0, 0, 0, 0,
  121352. NULL,
  121353. NULL,
  121354. NULL,
  121355. NULL,
  121356. 0
  121357. };
  121358. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121361. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121362. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121363. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121364. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121365. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121366. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121367. };
  121368. static static_codebook _huff_book_line_128x17_1sub1 = {
  121369. 1, 128,
  121370. _huff_lengthlist_line_128x17_1sub1,
  121371. 0, 0, 0, 0, 0,
  121372. NULL,
  121373. NULL,
  121374. NULL,
  121375. NULL,
  121376. 0
  121377. };
  121378. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121379. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121380. 9, 4,
  121381. };
  121382. static static_codebook _huff_book_line_128x17_2sub1 = {
  121383. 1, 18,
  121384. _huff_lengthlist_line_128x17_2sub1,
  121385. 0, 0, 0, 0, 0,
  121386. NULL,
  121387. NULL,
  121388. NULL,
  121389. NULL,
  121390. 0
  121391. };
  121392. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121394. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121395. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121396. 13,13,
  121397. };
  121398. static static_codebook _huff_book_line_128x17_2sub2 = {
  121399. 1, 50,
  121400. _huff_lengthlist_line_128x17_2sub2,
  121401. 0, 0, 0, 0, 0,
  121402. NULL,
  121403. NULL,
  121404. NULL,
  121405. NULL,
  121406. 0
  121407. };
  121408. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121412. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121413. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121414. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121415. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121416. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121417. };
  121418. static static_codebook _huff_book_line_128x17_2sub3 = {
  121419. 1, 128,
  121420. _huff_lengthlist_line_128x17_2sub3,
  121421. 0, 0, 0, 0, 0,
  121422. NULL,
  121423. NULL,
  121424. NULL,
  121425. NULL,
  121426. 0
  121427. };
  121428. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121429. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121430. 6, 4,
  121431. };
  121432. static static_codebook _huff_book_line_128x17_3sub1 = {
  121433. 1, 18,
  121434. _huff_lengthlist_line_128x17_3sub1,
  121435. 0, 0, 0, 0, 0,
  121436. NULL,
  121437. NULL,
  121438. NULL,
  121439. NULL,
  121440. 0
  121441. };
  121442. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121444. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121445. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121446. 10, 8,
  121447. };
  121448. static static_codebook _huff_book_line_128x17_3sub2 = {
  121449. 1, 50,
  121450. _huff_lengthlist_line_128x17_3sub2,
  121451. 0, 0, 0, 0, 0,
  121452. NULL,
  121453. NULL,
  121454. NULL,
  121455. NULL,
  121456. 0
  121457. };
  121458. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121462. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121463. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121464. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121467. };
  121468. static static_codebook _huff_book_line_128x17_3sub3 = {
  121469. 1, 128,
  121470. _huff_lengthlist_line_128x17_3sub3,
  121471. 0, 0, 0, 0, 0,
  121472. NULL,
  121473. NULL,
  121474. NULL,
  121475. NULL,
  121476. 0
  121477. };
  121478. static long _huff_lengthlist_line_1024x27_class1[] = {
  121479. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121480. };
  121481. static static_codebook _huff_book_line_1024x27_class1 = {
  121482. 1, 16,
  121483. _huff_lengthlist_line_1024x27_class1,
  121484. 0, 0, 0, 0, 0,
  121485. NULL,
  121486. NULL,
  121487. NULL,
  121488. NULL,
  121489. 0
  121490. };
  121491. static long _huff_lengthlist_line_1024x27_class2[] = {
  121492. 1, 4, 2, 6, 3, 7, 5, 7,
  121493. };
  121494. static static_codebook _huff_book_line_1024x27_class2 = {
  121495. 1, 8,
  121496. _huff_lengthlist_line_1024x27_class2,
  121497. 0, 0, 0, 0, 0,
  121498. NULL,
  121499. NULL,
  121500. NULL,
  121501. NULL,
  121502. 0
  121503. };
  121504. static long _huff_lengthlist_line_1024x27_class3[] = {
  121505. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121506. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121507. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121508. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121509. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121510. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121511. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121512. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121513. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121514. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121515. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121516. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121517. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121518. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121519. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121520. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121521. };
  121522. static static_codebook _huff_book_line_1024x27_class3 = {
  121523. 1, 256,
  121524. _huff_lengthlist_line_1024x27_class3,
  121525. 0, 0, 0, 0, 0,
  121526. NULL,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. 0
  121531. };
  121532. static long _huff_lengthlist_line_1024x27_class4[] = {
  121533. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121534. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121535. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121536. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121537. };
  121538. static static_codebook _huff_book_line_1024x27_class4 = {
  121539. 1, 64,
  121540. _huff_lengthlist_line_1024x27_class4,
  121541. 0, 0, 0, 0, 0,
  121542. NULL,
  121543. NULL,
  121544. NULL,
  121545. NULL,
  121546. 0
  121547. };
  121548. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121549. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121550. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121551. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121552. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121553. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121554. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121555. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121556. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121557. };
  121558. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121559. 1, 128,
  121560. _huff_lengthlist_line_1024x27_0sub0,
  121561. 0, 0, 0, 0, 0,
  121562. NULL,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. 0
  121567. };
  121568. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121569. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121570. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121571. };
  121572. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121573. 1, 32,
  121574. _huff_lengthlist_line_1024x27_1sub0,
  121575. 0, 0, 0, 0, 0,
  121576. NULL,
  121577. NULL,
  121578. NULL,
  121579. NULL,
  121580. 0
  121581. };
  121582. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121586. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121587. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121588. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121589. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121590. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121591. };
  121592. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121593. 1, 128,
  121594. _huff_lengthlist_line_1024x27_1sub1,
  121595. 0, 0, 0, 0, 0,
  121596. NULL,
  121597. NULL,
  121598. NULL,
  121599. NULL,
  121600. 0
  121601. };
  121602. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121603. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121604. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121605. };
  121606. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121607. 1, 32,
  121608. _huff_lengthlist_line_1024x27_2sub0,
  121609. 0, 0, 0, 0, 0,
  121610. NULL,
  121611. NULL,
  121612. NULL,
  121613. NULL,
  121614. 0
  121615. };
  121616. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121619. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121620. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121621. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121622. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121623. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121624. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121625. };
  121626. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121627. 1, 128,
  121628. _huff_lengthlist_line_1024x27_2sub1,
  121629. 0, 0, 0, 0, 0,
  121630. NULL,
  121631. NULL,
  121632. NULL,
  121633. NULL,
  121634. 0
  121635. };
  121636. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121637. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121638. 5, 5,
  121639. };
  121640. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121641. 1, 18,
  121642. _huff_lengthlist_line_1024x27_3sub1,
  121643. 0, 0, 0, 0, 0,
  121644. NULL,
  121645. NULL,
  121646. NULL,
  121647. NULL,
  121648. 0
  121649. };
  121650. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121652. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121653. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121654. 9,11,
  121655. };
  121656. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121657. 1, 50,
  121658. _huff_lengthlist_line_1024x27_3sub2,
  121659. 0, 0, 0, 0, 0,
  121660. NULL,
  121661. NULL,
  121662. NULL,
  121663. NULL,
  121664. 0
  121665. };
  121666. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  121671. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  121672. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121673. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121674. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121675. };
  121676. static static_codebook _huff_book_line_1024x27_3sub3 = {
  121677. 1, 128,
  121678. _huff_lengthlist_line_1024x27_3sub3,
  121679. 0, 0, 0, 0, 0,
  121680. NULL,
  121681. NULL,
  121682. NULL,
  121683. NULL,
  121684. 0
  121685. };
  121686. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  121687. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  121688. 5, 4,
  121689. };
  121690. static static_codebook _huff_book_line_1024x27_4sub1 = {
  121691. 1, 18,
  121692. _huff_lengthlist_line_1024x27_4sub1,
  121693. 0, 0, 0, 0, 0,
  121694. NULL,
  121695. NULL,
  121696. NULL,
  121697. NULL,
  121698. 0
  121699. };
  121700. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  121701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121702. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  121703. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  121704. 9,12,
  121705. };
  121706. static static_codebook _huff_book_line_1024x27_4sub2 = {
  121707. 1, 50,
  121708. _huff_lengthlist_line_1024x27_4sub2,
  121709. 0, 0, 0, 0, 0,
  121710. NULL,
  121711. NULL,
  121712. NULL,
  121713. NULL,
  121714. 0
  121715. };
  121716. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  121717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121720. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  121721. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  121722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121724. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  121725. };
  121726. static static_codebook _huff_book_line_1024x27_4sub3 = {
  121727. 1, 128,
  121728. _huff_lengthlist_line_1024x27_4sub3,
  121729. 0, 0, 0, 0, 0,
  121730. NULL,
  121731. NULL,
  121732. NULL,
  121733. NULL,
  121734. 0
  121735. };
  121736. static long _huff_lengthlist_line_2048x27_class1[] = {
  121737. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  121738. };
  121739. static static_codebook _huff_book_line_2048x27_class1 = {
  121740. 1, 16,
  121741. _huff_lengthlist_line_2048x27_class1,
  121742. 0, 0, 0, 0, 0,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. NULL,
  121747. 0
  121748. };
  121749. static long _huff_lengthlist_line_2048x27_class2[] = {
  121750. 1, 2, 3, 6, 4, 7, 5, 7,
  121751. };
  121752. static static_codebook _huff_book_line_2048x27_class2 = {
  121753. 1, 8,
  121754. _huff_lengthlist_line_2048x27_class2,
  121755. 0, 0, 0, 0, 0,
  121756. NULL,
  121757. NULL,
  121758. NULL,
  121759. NULL,
  121760. 0
  121761. };
  121762. static long _huff_lengthlist_line_2048x27_class3[] = {
  121763. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  121764. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  121765. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  121766. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  121767. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  121768. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  121769. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  121770. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  121771. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  121772. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  121773. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  121774. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121775. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  121776. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  121777. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121778. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  121779. };
  121780. static static_codebook _huff_book_line_2048x27_class3 = {
  121781. 1, 256,
  121782. _huff_lengthlist_line_2048x27_class3,
  121783. 0, 0, 0, 0, 0,
  121784. NULL,
  121785. NULL,
  121786. NULL,
  121787. NULL,
  121788. 0
  121789. };
  121790. static long _huff_lengthlist_line_2048x27_class4[] = {
  121791. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  121792. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  121793. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  121794. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  121795. };
  121796. static static_codebook _huff_book_line_2048x27_class4 = {
  121797. 1, 64,
  121798. _huff_lengthlist_line_2048x27_class4,
  121799. 0, 0, 0, 0, 0,
  121800. NULL,
  121801. NULL,
  121802. NULL,
  121803. NULL,
  121804. 0
  121805. };
  121806. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  121807. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121808. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  121809. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  121810. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  121811. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  121812. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  121813. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  121814. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  121815. };
  121816. static static_codebook _huff_book_line_2048x27_0sub0 = {
  121817. 1, 128,
  121818. _huff_lengthlist_line_2048x27_0sub0,
  121819. 0, 0, 0, 0, 0,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. NULL,
  121824. 0
  121825. };
  121826. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  121827. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121828. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  121829. };
  121830. static static_codebook _huff_book_line_2048x27_1sub0 = {
  121831. 1, 32,
  121832. _huff_lengthlist_line_2048x27_1sub0,
  121833. 0, 0, 0, 0, 0,
  121834. NULL,
  121835. NULL,
  121836. NULL,
  121837. NULL,
  121838. 0
  121839. };
  121840. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121843. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  121844. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  121845. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  121846. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  121847. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  121848. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  121849. };
  121850. static static_codebook _huff_book_line_2048x27_1sub1 = {
  121851. 1, 128,
  121852. _huff_lengthlist_line_2048x27_1sub1,
  121853. 0, 0, 0, 0, 0,
  121854. NULL,
  121855. NULL,
  121856. NULL,
  121857. NULL,
  121858. 0
  121859. };
  121860. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  121861. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121862. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  121863. };
  121864. static static_codebook _huff_book_line_2048x27_2sub0 = {
  121865. 1, 32,
  121866. _huff_lengthlist_line_2048x27_2sub0,
  121867. 0, 0, 0, 0, 0,
  121868. NULL,
  121869. NULL,
  121870. NULL,
  121871. NULL,
  121872. 0
  121873. };
  121874. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  121875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121877. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  121878. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  121879. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  121880. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  121881. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  121882. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  121883. };
  121884. static static_codebook _huff_book_line_2048x27_2sub1 = {
  121885. 1, 128,
  121886. _huff_lengthlist_line_2048x27_2sub1,
  121887. 0, 0, 0, 0, 0,
  121888. NULL,
  121889. NULL,
  121890. NULL,
  121891. NULL,
  121892. 0
  121893. };
  121894. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  121895. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  121896. 5, 5,
  121897. };
  121898. static static_codebook _huff_book_line_2048x27_3sub1 = {
  121899. 1, 18,
  121900. _huff_lengthlist_line_2048x27_3sub1,
  121901. 0, 0, 0, 0, 0,
  121902. NULL,
  121903. NULL,
  121904. NULL,
  121905. NULL,
  121906. 0
  121907. };
  121908. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  121909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121910. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  121911. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  121912. 10,12,
  121913. };
  121914. static static_codebook _huff_book_line_2048x27_3sub2 = {
  121915. 1, 50,
  121916. _huff_lengthlist_line_2048x27_3sub2,
  121917. 0, 0, 0, 0, 0,
  121918. NULL,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. 0
  121923. };
  121924. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  121929. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121930. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121931. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121932. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121933. };
  121934. static static_codebook _huff_book_line_2048x27_3sub3 = {
  121935. 1, 128,
  121936. _huff_lengthlist_line_2048x27_3sub3,
  121937. 0, 0, 0, 0, 0,
  121938. NULL,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. 0
  121943. };
  121944. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  121945. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  121946. 4, 5,
  121947. };
  121948. static static_codebook _huff_book_line_2048x27_4sub1 = {
  121949. 1, 18,
  121950. _huff_lengthlist_line_2048x27_4sub1,
  121951. 0, 0, 0, 0, 0,
  121952. NULL,
  121953. NULL,
  121954. NULL,
  121955. NULL,
  121956. 0
  121957. };
  121958. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  121959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121960. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  121961. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  121962. 10,10,
  121963. };
  121964. static static_codebook _huff_book_line_2048x27_4sub2 = {
  121965. 1, 50,
  121966. _huff_lengthlist_line_2048x27_4sub2,
  121967. 0, 0, 0, 0, 0,
  121968. NULL,
  121969. NULL,
  121970. NULL,
  121971. NULL,
  121972. 0
  121973. };
  121974. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  121975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  121979. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  121980. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121981. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121982. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121983. };
  121984. static static_codebook _huff_book_line_2048x27_4sub3 = {
  121985. 1, 128,
  121986. _huff_lengthlist_line_2048x27_4sub3,
  121987. 0, 0, 0, 0, 0,
  121988. NULL,
  121989. NULL,
  121990. NULL,
  121991. NULL,
  121992. 0
  121993. };
  121994. static long _huff_lengthlist_line_256x4low_class0[] = {
  121995. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  121996. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  121997. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  121998. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  121999. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122000. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122001. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122002. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122003. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122004. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122005. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122006. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122007. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122008. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122009. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122010. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122011. };
  122012. static static_codebook _huff_book_line_256x4low_class0 = {
  122013. 1, 256,
  122014. _huff_lengthlist_line_256x4low_class0,
  122015. 0, 0, 0, 0, 0,
  122016. NULL,
  122017. NULL,
  122018. NULL,
  122019. NULL,
  122020. 0
  122021. };
  122022. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122023. 1, 3, 2, 3,
  122024. };
  122025. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122026. 1, 4,
  122027. _huff_lengthlist_line_256x4low_0sub0,
  122028. 0, 0, 0, 0, 0,
  122029. NULL,
  122030. NULL,
  122031. NULL,
  122032. NULL,
  122033. 0
  122034. };
  122035. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122036. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122037. };
  122038. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122039. 1, 10,
  122040. _huff_lengthlist_line_256x4low_0sub1,
  122041. 0, 0, 0, 0, 0,
  122042. NULL,
  122043. NULL,
  122044. NULL,
  122045. NULL,
  122046. 0
  122047. };
  122048. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122050. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122051. };
  122052. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122053. 1, 25,
  122054. _huff_lengthlist_line_256x4low_0sub2,
  122055. 0, 0, 0, 0, 0,
  122056. NULL,
  122057. NULL,
  122058. NULL,
  122059. NULL,
  122060. 0
  122061. };
  122062. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122065. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122066. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122067. };
  122068. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122069. 1, 64,
  122070. _huff_lengthlist_line_256x4low_0sub3,
  122071. 0, 0, 0, 0, 0,
  122072. NULL,
  122073. NULL,
  122074. NULL,
  122075. NULL,
  122076. 0
  122077. };
  122078. /*** End of inlined file: floor_books.h ***/
  122079. static static_codebook *_floor_128x4_books[]={
  122080. &_huff_book_line_128x4_class0,
  122081. &_huff_book_line_128x4_0sub0,
  122082. &_huff_book_line_128x4_0sub1,
  122083. &_huff_book_line_128x4_0sub2,
  122084. &_huff_book_line_128x4_0sub3,
  122085. };
  122086. static static_codebook *_floor_256x4_books[]={
  122087. &_huff_book_line_256x4_class0,
  122088. &_huff_book_line_256x4_0sub0,
  122089. &_huff_book_line_256x4_0sub1,
  122090. &_huff_book_line_256x4_0sub2,
  122091. &_huff_book_line_256x4_0sub3,
  122092. };
  122093. static static_codebook *_floor_128x7_books[]={
  122094. &_huff_book_line_128x7_class0,
  122095. &_huff_book_line_128x7_class1,
  122096. &_huff_book_line_128x7_0sub1,
  122097. &_huff_book_line_128x7_0sub2,
  122098. &_huff_book_line_128x7_0sub3,
  122099. &_huff_book_line_128x7_1sub1,
  122100. &_huff_book_line_128x7_1sub2,
  122101. &_huff_book_line_128x7_1sub3,
  122102. };
  122103. static static_codebook *_floor_256x7_books[]={
  122104. &_huff_book_line_256x7_class0,
  122105. &_huff_book_line_256x7_class1,
  122106. &_huff_book_line_256x7_0sub1,
  122107. &_huff_book_line_256x7_0sub2,
  122108. &_huff_book_line_256x7_0sub3,
  122109. &_huff_book_line_256x7_1sub1,
  122110. &_huff_book_line_256x7_1sub2,
  122111. &_huff_book_line_256x7_1sub3,
  122112. };
  122113. static static_codebook *_floor_128x11_books[]={
  122114. &_huff_book_line_128x11_class1,
  122115. &_huff_book_line_128x11_class2,
  122116. &_huff_book_line_128x11_class3,
  122117. &_huff_book_line_128x11_0sub0,
  122118. &_huff_book_line_128x11_1sub0,
  122119. &_huff_book_line_128x11_1sub1,
  122120. &_huff_book_line_128x11_2sub1,
  122121. &_huff_book_line_128x11_2sub2,
  122122. &_huff_book_line_128x11_2sub3,
  122123. &_huff_book_line_128x11_3sub1,
  122124. &_huff_book_line_128x11_3sub2,
  122125. &_huff_book_line_128x11_3sub3,
  122126. };
  122127. static static_codebook *_floor_128x17_books[]={
  122128. &_huff_book_line_128x17_class1,
  122129. &_huff_book_line_128x17_class2,
  122130. &_huff_book_line_128x17_class3,
  122131. &_huff_book_line_128x17_0sub0,
  122132. &_huff_book_line_128x17_1sub0,
  122133. &_huff_book_line_128x17_1sub1,
  122134. &_huff_book_line_128x17_2sub1,
  122135. &_huff_book_line_128x17_2sub2,
  122136. &_huff_book_line_128x17_2sub3,
  122137. &_huff_book_line_128x17_3sub1,
  122138. &_huff_book_line_128x17_3sub2,
  122139. &_huff_book_line_128x17_3sub3,
  122140. };
  122141. static static_codebook *_floor_256x4low_books[]={
  122142. &_huff_book_line_256x4low_class0,
  122143. &_huff_book_line_256x4low_0sub0,
  122144. &_huff_book_line_256x4low_0sub1,
  122145. &_huff_book_line_256x4low_0sub2,
  122146. &_huff_book_line_256x4low_0sub3,
  122147. };
  122148. static static_codebook *_floor_1024x27_books[]={
  122149. &_huff_book_line_1024x27_class1,
  122150. &_huff_book_line_1024x27_class2,
  122151. &_huff_book_line_1024x27_class3,
  122152. &_huff_book_line_1024x27_class4,
  122153. &_huff_book_line_1024x27_0sub0,
  122154. &_huff_book_line_1024x27_1sub0,
  122155. &_huff_book_line_1024x27_1sub1,
  122156. &_huff_book_line_1024x27_2sub0,
  122157. &_huff_book_line_1024x27_2sub1,
  122158. &_huff_book_line_1024x27_3sub1,
  122159. &_huff_book_line_1024x27_3sub2,
  122160. &_huff_book_line_1024x27_3sub3,
  122161. &_huff_book_line_1024x27_4sub1,
  122162. &_huff_book_line_1024x27_4sub2,
  122163. &_huff_book_line_1024x27_4sub3,
  122164. };
  122165. static static_codebook *_floor_2048x27_books[]={
  122166. &_huff_book_line_2048x27_class1,
  122167. &_huff_book_line_2048x27_class2,
  122168. &_huff_book_line_2048x27_class3,
  122169. &_huff_book_line_2048x27_class4,
  122170. &_huff_book_line_2048x27_0sub0,
  122171. &_huff_book_line_2048x27_1sub0,
  122172. &_huff_book_line_2048x27_1sub1,
  122173. &_huff_book_line_2048x27_2sub0,
  122174. &_huff_book_line_2048x27_2sub1,
  122175. &_huff_book_line_2048x27_3sub1,
  122176. &_huff_book_line_2048x27_3sub2,
  122177. &_huff_book_line_2048x27_3sub3,
  122178. &_huff_book_line_2048x27_4sub1,
  122179. &_huff_book_line_2048x27_4sub2,
  122180. &_huff_book_line_2048x27_4sub3,
  122181. };
  122182. static static_codebook *_floor_512x17_books[]={
  122183. &_huff_book_line_512x17_class1,
  122184. &_huff_book_line_512x17_class2,
  122185. &_huff_book_line_512x17_class3,
  122186. &_huff_book_line_512x17_0sub0,
  122187. &_huff_book_line_512x17_1sub0,
  122188. &_huff_book_line_512x17_1sub1,
  122189. &_huff_book_line_512x17_2sub1,
  122190. &_huff_book_line_512x17_2sub2,
  122191. &_huff_book_line_512x17_2sub3,
  122192. &_huff_book_line_512x17_3sub1,
  122193. &_huff_book_line_512x17_3sub2,
  122194. &_huff_book_line_512x17_3sub3,
  122195. };
  122196. static static_codebook **_floor_books[10]={
  122197. _floor_128x4_books,
  122198. _floor_256x4_books,
  122199. _floor_128x7_books,
  122200. _floor_256x7_books,
  122201. _floor_128x11_books,
  122202. _floor_128x17_books,
  122203. _floor_256x4low_books,
  122204. _floor_1024x27_books,
  122205. _floor_2048x27_books,
  122206. _floor_512x17_books,
  122207. };
  122208. static vorbis_info_floor1 _floor[10]={
  122209. /* 128 x 4 */
  122210. {
  122211. 1,{0},{4},{2},{0},
  122212. {{1,2,3,4}},
  122213. 4,{0,128, 33,8,16,70},
  122214. 60,30,500, 1.,18., -1
  122215. },
  122216. /* 256 x 4 */
  122217. {
  122218. 1,{0},{4},{2},{0},
  122219. {{1,2,3,4}},
  122220. 4,{0,256, 66,16,32,140},
  122221. 60,30,500, 1.,18., -1
  122222. },
  122223. /* 128 x 7 */
  122224. {
  122225. 2,{0,1},{3,4},{2,2},{0,1},
  122226. {{-1,2,3,4},{-1,5,6,7}},
  122227. 4,{0,128, 14,4,58, 2,8,28,90},
  122228. 60,30,500, 1.,18., -1
  122229. },
  122230. /* 256 x 7 */
  122231. {
  122232. 2,{0,1},{3,4},{2,2},{0,1},
  122233. {{-1,2,3,4},{-1,5,6,7}},
  122234. 4,{0,256, 28,8,116, 4,16,56,180},
  122235. 60,30,500, 1.,18., -1
  122236. },
  122237. /* 128 x 11 */
  122238. {
  122239. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122240. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122241. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122242. 60,30,500, 1,18., -1
  122243. },
  122244. /* 128 x 17 */
  122245. {
  122246. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122247. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122248. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122249. 60,30,500, 1,18., -1
  122250. },
  122251. /* 256 x 4 (low bitrate version) */
  122252. {
  122253. 1,{0},{4},{2},{0},
  122254. {{1,2,3,4}},
  122255. 4,{0,256, 66,16,32,140},
  122256. 60,30,500, 1.,18., -1
  122257. },
  122258. /* 1024 x 27 */
  122259. {
  122260. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122261. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122262. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122263. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122264. 60,30,500, 3,18., -1 /* lowpass */
  122265. },
  122266. /* 2048 x 27 */
  122267. {
  122268. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122269. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122270. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122271. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122272. 60,30,500, 3,18., -1 /* lowpass */
  122273. },
  122274. /* 512 x 17 */
  122275. {
  122276. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122277. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122278. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122279. 7,23,39, 55,79,110, 156,232,360},
  122280. 60,30,500, 1,18., -1 /* lowpass! */
  122281. },
  122282. };
  122283. /*** End of inlined file: floor_all.h ***/
  122284. /*** Start of inlined file: residue_44.h ***/
  122285. /*** Start of inlined file: res_books_stereo.h ***/
  122286. static long _vq_quantlist__16c0_s_p1_0[] = {
  122287. 1,
  122288. 0,
  122289. 2,
  122290. };
  122291. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122292. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122293. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122297. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122298. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122302. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122303. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122338. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  122343. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  122348. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122383. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122384. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122388. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122389. 0, 0, 0, 0, 0, 9,10,12, 0, 0, 0, 0, 0, 0, 0, 0,
  122390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122393. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122394. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0,
  122703. };
  122704. static float _vq_quantthresh__16c0_s_p1_0[] = {
  122705. -0.5, 0.5,
  122706. };
  122707. static long _vq_quantmap__16c0_s_p1_0[] = {
  122708. 1, 0, 2,
  122709. };
  122710. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  122711. _vq_quantthresh__16c0_s_p1_0,
  122712. _vq_quantmap__16c0_s_p1_0,
  122713. 3,
  122714. 3
  122715. };
  122716. static static_codebook _16c0_s_p1_0 = {
  122717. 8, 6561,
  122718. _vq_lengthlist__16c0_s_p1_0,
  122719. 1, -535822336, 1611661312, 2, 0,
  122720. _vq_quantlist__16c0_s_p1_0,
  122721. NULL,
  122722. &_vq_auxt__16c0_s_p1_0,
  122723. NULL,
  122724. 0
  122725. };
  122726. static long _vq_quantlist__16c0_s_p2_0[] = {
  122727. 2,
  122728. 1,
  122729. 3,
  122730. 0,
  122731. 4,
  122732. };
  122733. static long _vq_lengthlist__16c0_s_p2_0[] = {
  122734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0,
  122774. };
  122775. static float _vq_quantthresh__16c0_s_p2_0[] = {
  122776. -1.5, -0.5, 0.5, 1.5,
  122777. };
  122778. static long _vq_quantmap__16c0_s_p2_0[] = {
  122779. 3, 1, 0, 2, 4,
  122780. };
  122781. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  122782. _vq_quantthresh__16c0_s_p2_0,
  122783. _vq_quantmap__16c0_s_p2_0,
  122784. 5,
  122785. 5
  122786. };
  122787. static static_codebook _16c0_s_p2_0 = {
  122788. 4, 625,
  122789. _vq_lengthlist__16c0_s_p2_0,
  122790. 1, -533725184, 1611661312, 3, 0,
  122791. _vq_quantlist__16c0_s_p2_0,
  122792. NULL,
  122793. &_vq_auxt__16c0_s_p2_0,
  122794. NULL,
  122795. 0
  122796. };
  122797. static long _vq_quantlist__16c0_s_p3_0[] = {
  122798. 2,
  122799. 1,
  122800. 3,
  122801. 0,
  122802. 4,
  122803. };
  122804. static long _vq_lengthlist__16c0_s_p3_0[] = {
  122805. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0,
  122845. };
  122846. static float _vq_quantthresh__16c0_s_p3_0[] = {
  122847. -1.5, -0.5, 0.5, 1.5,
  122848. };
  122849. static long _vq_quantmap__16c0_s_p3_0[] = {
  122850. 3, 1, 0, 2, 4,
  122851. };
  122852. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  122853. _vq_quantthresh__16c0_s_p3_0,
  122854. _vq_quantmap__16c0_s_p3_0,
  122855. 5,
  122856. 5
  122857. };
  122858. static static_codebook _16c0_s_p3_0 = {
  122859. 4, 625,
  122860. _vq_lengthlist__16c0_s_p3_0,
  122861. 1, -533725184, 1611661312, 3, 0,
  122862. _vq_quantlist__16c0_s_p3_0,
  122863. NULL,
  122864. &_vq_auxt__16c0_s_p3_0,
  122865. NULL,
  122866. 0
  122867. };
  122868. static long _vq_quantlist__16c0_s_p4_0[] = {
  122869. 4,
  122870. 3,
  122871. 5,
  122872. 2,
  122873. 6,
  122874. 1,
  122875. 7,
  122876. 0,
  122877. 8,
  122878. };
  122879. static long _vq_lengthlist__16c0_s_p4_0[] = {
  122880. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122881. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122882. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122883. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  122884. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0,
  122886. };
  122887. static float _vq_quantthresh__16c0_s_p4_0[] = {
  122888. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122889. };
  122890. static long _vq_quantmap__16c0_s_p4_0[] = {
  122891. 7, 5, 3, 1, 0, 2, 4, 6,
  122892. 8,
  122893. };
  122894. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  122895. _vq_quantthresh__16c0_s_p4_0,
  122896. _vq_quantmap__16c0_s_p4_0,
  122897. 9,
  122898. 9
  122899. };
  122900. static static_codebook _16c0_s_p4_0 = {
  122901. 2, 81,
  122902. _vq_lengthlist__16c0_s_p4_0,
  122903. 1, -531628032, 1611661312, 4, 0,
  122904. _vq_quantlist__16c0_s_p4_0,
  122905. NULL,
  122906. &_vq_auxt__16c0_s_p4_0,
  122907. NULL,
  122908. 0
  122909. };
  122910. static long _vq_quantlist__16c0_s_p5_0[] = {
  122911. 4,
  122912. 3,
  122913. 5,
  122914. 2,
  122915. 6,
  122916. 1,
  122917. 7,
  122918. 0,
  122919. 8,
  122920. };
  122921. static long _vq_lengthlist__16c0_s_p5_0[] = {
  122922. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  122923. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  122924. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  122925. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  122926. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122927. 10,
  122928. };
  122929. static float _vq_quantthresh__16c0_s_p5_0[] = {
  122930. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122931. };
  122932. static long _vq_quantmap__16c0_s_p5_0[] = {
  122933. 7, 5, 3, 1, 0, 2, 4, 6,
  122934. 8,
  122935. };
  122936. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  122937. _vq_quantthresh__16c0_s_p5_0,
  122938. _vq_quantmap__16c0_s_p5_0,
  122939. 9,
  122940. 9
  122941. };
  122942. static static_codebook _16c0_s_p5_0 = {
  122943. 2, 81,
  122944. _vq_lengthlist__16c0_s_p5_0,
  122945. 1, -531628032, 1611661312, 4, 0,
  122946. _vq_quantlist__16c0_s_p5_0,
  122947. NULL,
  122948. &_vq_auxt__16c0_s_p5_0,
  122949. NULL,
  122950. 0
  122951. };
  122952. static long _vq_quantlist__16c0_s_p6_0[] = {
  122953. 8,
  122954. 7,
  122955. 9,
  122956. 6,
  122957. 10,
  122958. 5,
  122959. 11,
  122960. 4,
  122961. 12,
  122962. 3,
  122963. 13,
  122964. 2,
  122965. 14,
  122966. 1,
  122967. 15,
  122968. 0,
  122969. 16,
  122970. };
  122971. static long _vq_lengthlist__16c0_s_p6_0[] = {
  122972. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  122973. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  122974. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  122975. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  122976. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  122977. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  122978. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  122979. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  122980. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  122981. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122982. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  122983. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  122984. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  122985. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  122986. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  122987. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  122988. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  122989. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  122990. 14,
  122991. };
  122992. static float _vq_quantthresh__16c0_s_p6_0[] = {
  122993. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122994. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122995. };
  122996. static long _vq_quantmap__16c0_s_p6_0[] = {
  122997. 15, 13, 11, 9, 7, 5, 3, 1,
  122998. 0, 2, 4, 6, 8, 10, 12, 14,
  122999. 16,
  123000. };
  123001. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123002. _vq_quantthresh__16c0_s_p6_0,
  123003. _vq_quantmap__16c0_s_p6_0,
  123004. 17,
  123005. 17
  123006. };
  123007. static static_codebook _16c0_s_p6_0 = {
  123008. 2, 289,
  123009. _vq_lengthlist__16c0_s_p6_0,
  123010. 1, -529530880, 1611661312, 5, 0,
  123011. _vq_quantlist__16c0_s_p6_0,
  123012. NULL,
  123013. &_vq_auxt__16c0_s_p6_0,
  123014. NULL,
  123015. 0
  123016. };
  123017. static long _vq_quantlist__16c0_s_p7_0[] = {
  123018. 1,
  123019. 0,
  123020. 2,
  123021. };
  123022. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123023. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123024. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123025. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123026. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123027. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123028. 13,
  123029. };
  123030. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123031. -5.5, 5.5,
  123032. };
  123033. static long _vq_quantmap__16c0_s_p7_0[] = {
  123034. 1, 0, 2,
  123035. };
  123036. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123037. _vq_quantthresh__16c0_s_p7_0,
  123038. _vq_quantmap__16c0_s_p7_0,
  123039. 3,
  123040. 3
  123041. };
  123042. static static_codebook _16c0_s_p7_0 = {
  123043. 4, 81,
  123044. _vq_lengthlist__16c0_s_p7_0,
  123045. 1, -529137664, 1618345984, 2, 0,
  123046. _vq_quantlist__16c0_s_p7_0,
  123047. NULL,
  123048. &_vq_auxt__16c0_s_p7_0,
  123049. NULL,
  123050. 0
  123051. };
  123052. static long _vq_quantlist__16c0_s_p7_1[] = {
  123053. 5,
  123054. 4,
  123055. 6,
  123056. 3,
  123057. 7,
  123058. 2,
  123059. 8,
  123060. 1,
  123061. 9,
  123062. 0,
  123063. 10,
  123064. };
  123065. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123066. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123067. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123068. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123069. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123070. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123071. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123072. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123073. 11,11,11, 9, 9, 9, 9,10,10,
  123074. };
  123075. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123076. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123077. 3.5, 4.5,
  123078. };
  123079. static long _vq_quantmap__16c0_s_p7_1[] = {
  123080. 9, 7, 5, 3, 1, 0, 2, 4,
  123081. 6, 8, 10,
  123082. };
  123083. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123084. _vq_quantthresh__16c0_s_p7_1,
  123085. _vq_quantmap__16c0_s_p7_1,
  123086. 11,
  123087. 11
  123088. };
  123089. static static_codebook _16c0_s_p7_1 = {
  123090. 2, 121,
  123091. _vq_lengthlist__16c0_s_p7_1,
  123092. 1, -531365888, 1611661312, 4, 0,
  123093. _vq_quantlist__16c0_s_p7_1,
  123094. NULL,
  123095. &_vq_auxt__16c0_s_p7_1,
  123096. NULL,
  123097. 0
  123098. };
  123099. static long _vq_quantlist__16c0_s_p8_0[] = {
  123100. 6,
  123101. 5,
  123102. 7,
  123103. 4,
  123104. 8,
  123105. 3,
  123106. 9,
  123107. 2,
  123108. 10,
  123109. 1,
  123110. 11,
  123111. 0,
  123112. 12,
  123113. };
  123114. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123115. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123116. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123117. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123118. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123119. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123120. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123121. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123122. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123123. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123124. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123125. 0,12,13,13,12,13,14,14,14,
  123126. };
  123127. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123128. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123129. 12.5, 17.5, 22.5, 27.5,
  123130. };
  123131. static long _vq_quantmap__16c0_s_p8_0[] = {
  123132. 11, 9, 7, 5, 3, 1, 0, 2,
  123133. 4, 6, 8, 10, 12,
  123134. };
  123135. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123136. _vq_quantthresh__16c0_s_p8_0,
  123137. _vq_quantmap__16c0_s_p8_0,
  123138. 13,
  123139. 13
  123140. };
  123141. static static_codebook _16c0_s_p8_0 = {
  123142. 2, 169,
  123143. _vq_lengthlist__16c0_s_p8_0,
  123144. 1, -526516224, 1616117760, 4, 0,
  123145. _vq_quantlist__16c0_s_p8_0,
  123146. NULL,
  123147. &_vq_auxt__16c0_s_p8_0,
  123148. NULL,
  123149. 0
  123150. };
  123151. static long _vq_quantlist__16c0_s_p8_1[] = {
  123152. 2,
  123153. 1,
  123154. 3,
  123155. 0,
  123156. 4,
  123157. };
  123158. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123159. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123160. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123161. };
  123162. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123163. -1.5, -0.5, 0.5, 1.5,
  123164. };
  123165. static long _vq_quantmap__16c0_s_p8_1[] = {
  123166. 3, 1, 0, 2, 4,
  123167. };
  123168. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123169. _vq_quantthresh__16c0_s_p8_1,
  123170. _vq_quantmap__16c0_s_p8_1,
  123171. 5,
  123172. 5
  123173. };
  123174. static static_codebook _16c0_s_p8_1 = {
  123175. 2, 25,
  123176. _vq_lengthlist__16c0_s_p8_1,
  123177. 1, -533725184, 1611661312, 3, 0,
  123178. _vq_quantlist__16c0_s_p8_1,
  123179. NULL,
  123180. &_vq_auxt__16c0_s_p8_1,
  123181. NULL,
  123182. 0
  123183. };
  123184. static long _vq_quantlist__16c0_s_p9_0[] = {
  123185. 1,
  123186. 0,
  123187. 2,
  123188. };
  123189. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123190. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123191. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123192. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123193. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123194. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123195. 7,
  123196. };
  123197. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123198. -157.5, 157.5,
  123199. };
  123200. static long _vq_quantmap__16c0_s_p9_0[] = {
  123201. 1, 0, 2,
  123202. };
  123203. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123204. _vq_quantthresh__16c0_s_p9_0,
  123205. _vq_quantmap__16c0_s_p9_0,
  123206. 3,
  123207. 3
  123208. };
  123209. static static_codebook _16c0_s_p9_0 = {
  123210. 4, 81,
  123211. _vq_lengthlist__16c0_s_p9_0,
  123212. 1, -518803456, 1628680192, 2, 0,
  123213. _vq_quantlist__16c0_s_p9_0,
  123214. NULL,
  123215. &_vq_auxt__16c0_s_p9_0,
  123216. NULL,
  123217. 0
  123218. };
  123219. static long _vq_quantlist__16c0_s_p9_1[] = {
  123220. 7,
  123221. 6,
  123222. 8,
  123223. 5,
  123224. 9,
  123225. 4,
  123226. 10,
  123227. 3,
  123228. 11,
  123229. 2,
  123230. 12,
  123231. 1,
  123232. 13,
  123233. 0,
  123234. 14,
  123235. };
  123236. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123237. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123238. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123239. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123240. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123241. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123243. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123244. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123245. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123246. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123249. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123250. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123251. 10,
  123252. };
  123253. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123254. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123255. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123256. };
  123257. static long _vq_quantmap__16c0_s_p9_1[] = {
  123258. 13, 11, 9, 7, 5, 3, 1, 0,
  123259. 2, 4, 6, 8, 10, 12, 14,
  123260. };
  123261. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123262. _vq_quantthresh__16c0_s_p9_1,
  123263. _vq_quantmap__16c0_s_p9_1,
  123264. 15,
  123265. 15
  123266. };
  123267. static static_codebook _16c0_s_p9_1 = {
  123268. 2, 225,
  123269. _vq_lengthlist__16c0_s_p9_1,
  123270. 1, -520986624, 1620377600, 4, 0,
  123271. _vq_quantlist__16c0_s_p9_1,
  123272. NULL,
  123273. &_vq_auxt__16c0_s_p9_1,
  123274. NULL,
  123275. 0
  123276. };
  123277. static long _vq_quantlist__16c0_s_p9_2[] = {
  123278. 10,
  123279. 9,
  123280. 11,
  123281. 8,
  123282. 12,
  123283. 7,
  123284. 13,
  123285. 6,
  123286. 14,
  123287. 5,
  123288. 15,
  123289. 4,
  123290. 16,
  123291. 3,
  123292. 17,
  123293. 2,
  123294. 18,
  123295. 1,
  123296. 19,
  123297. 0,
  123298. 20,
  123299. };
  123300. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123301. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123302. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123303. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123304. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123305. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123306. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123307. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123308. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123309. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123310. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123311. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123312. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123313. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123314. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123315. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123316. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123317. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123318. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123319. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123320. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123321. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123322. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123323. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123324. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123325. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123326. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123327. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123328. 10,11,10,10,11, 9,10,10,10,
  123329. };
  123330. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123331. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123332. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123333. 6.5, 7.5, 8.5, 9.5,
  123334. };
  123335. static long _vq_quantmap__16c0_s_p9_2[] = {
  123336. 19, 17, 15, 13, 11, 9, 7, 5,
  123337. 3, 1, 0, 2, 4, 6, 8, 10,
  123338. 12, 14, 16, 18, 20,
  123339. };
  123340. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123341. _vq_quantthresh__16c0_s_p9_2,
  123342. _vq_quantmap__16c0_s_p9_2,
  123343. 21,
  123344. 21
  123345. };
  123346. static static_codebook _16c0_s_p9_2 = {
  123347. 2, 441,
  123348. _vq_lengthlist__16c0_s_p9_2,
  123349. 1, -529268736, 1611661312, 5, 0,
  123350. _vq_quantlist__16c0_s_p9_2,
  123351. NULL,
  123352. &_vq_auxt__16c0_s_p9_2,
  123353. NULL,
  123354. 0
  123355. };
  123356. static long _huff_lengthlist__16c0_s_single[] = {
  123357. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123358. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123359. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123360. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123361. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123362. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123363. 16,16,18,18,
  123364. };
  123365. static static_codebook _huff_book__16c0_s_single = {
  123366. 2, 100,
  123367. _huff_lengthlist__16c0_s_single,
  123368. 0, 0, 0, 0, 0,
  123369. NULL,
  123370. NULL,
  123371. NULL,
  123372. NULL,
  123373. 0
  123374. };
  123375. static long _huff_lengthlist__16c1_s_long[] = {
  123376. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123377. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123378. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123379. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123380. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123381. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123382. 12,11,11,13,
  123383. };
  123384. static static_codebook _huff_book__16c1_s_long = {
  123385. 2, 100,
  123386. _huff_lengthlist__16c1_s_long,
  123387. 0, 0, 0, 0, 0,
  123388. NULL,
  123389. NULL,
  123390. NULL,
  123391. NULL,
  123392. 0
  123393. };
  123394. static long _vq_quantlist__16c1_s_p1_0[] = {
  123395. 1,
  123396. 0,
  123397. 2,
  123398. };
  123399. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123400. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123401. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123406. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123411. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123446. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123451. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123456. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123491. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123492. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123496. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123497. 0, 0, 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123501. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123502. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0,
  123811. };
  123812. static float _vq_quantthresh__16c1_s_p1_0[] = {
  123813. -0.5, 0.5,
  123814. };
  123815. static long _vq_quantmap__16c1_s_p1_0[] = {
  123816. 1, 0, 2,
  123817. };
  123818. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  123819. _vq_quantthresh__16c1_s_p1_0,
  123820. _vq_quantmap__16c1_s_p1_0,
  123821. 3,
  123822. 3
  123823. };
  123824. static static_codebook _16c1_s_p1_0 = {
  123825. 8, 6561,
  123826. _vq_lengthlist__16c1_s_p1_0,
  123827. 1, -535822336, 1611661312, 2, 0,
  123828. _vq_quantlist__16c1_s_p1_0,
  123829. NULL,
  123830. &_vq_auxt__16c1_s_p1_0,
  123831. NULL,
  123832. 0
  123833. };
  123834. static long _vq_quantlist__16c1_s_p2_0[] = {
  123835. 2,
  123836. 1,
  123837. 3,
  123838. 0,
  123839. 4,
  123840. };
  123841. static long _vq_lengthlist__16c1_s_p2_0[] = {
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0,
  123882. };
  123883. static float _vq_quantthresh__16c1_s_p2_0[] = {
  123884. -1.5, -0.5, 0.5, 1.5,
  123885. };
  123886. static long _vq_quantmap__16c1_s_p2_0[] = {
  123887. 3, 1, 0, 2, 4,
  123888. };
  123889. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  123890. _vq_quantthresh__16c1_s_p2_0,
  123891. _vq_quantmap__16c1_s_p2_0,
  123892. 5,
  123893. 5
  123894. };
  123895. static static_codebook _16c1_s_p2_0 = {
  123896. 4, 625,
  123897. _vq_lengthlist__16c1_s_p2_0,
  123898. 1, -533725184, 1611661312, 3, 0,
  123899. _vq_quantlist__16c1_s_p2_0,
  123900. NULL,
  123901. &_vq_auxt__16c1_s_p2_0,
  123902. NULL,
  123903. 0
  123904. };
  123905. static long _vq_quantlist__16c1_s_p3_0[] = {
  123906. 2,
  123907. 1,
  123908. 3,
  123909. 0,
  123910. 4,
  123911. };
  123912. static long _vq_lengthlist__16c1_s_p3_0[] = {
  123913. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0,
  123953. };
  123954. static float _vq_quantthresh__16c1_s_p3_0[] = {
  123955. -1.5, -0.5, 0.5, 1.5,
  123956. };
  123957. static long _vq_quantmap__16c1_s_p3_0[] = {
  123958. 3, 1, 0, 2, 4,
  123959. };
  123960. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  123961. _vq_quantthresh__16c1_s_p3_0,
  123962. _vq_quantmap__16c1_s_p3_0,
  123963. 5,
  123964. 5
  123965. };
  123966. static static_codebook _16c1_s_p3_0 = {
  123967. 4, 625,
  123968. _vq_lengthlist__16c1_s_p3_0,
  123969. 1, -533725184, 1611661312, 3, 0,
  123970. _vq_quantlist__16c1_s_p3_0,
  123971. NULL,
  123972. &_vq_auxt__16c1_s_p3_0,
  123973. NULL,
  123974. 0
  123975. };
  123976. static long _vq_quantlist__16c1_s_p4_0[] = {
  123977. 4,
  123978. 3,
  123979. 5,
  123980. 2,
  123981. 6,
  123982. 1,
  123983. 7,
  123984. 0,
  123985. 8,
  123986. };
  123987. static long _vq_lengthlist__16c1_s_p4_0[] = {
  123988. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123989. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123990. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123991. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  123992. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0,
  123994. };
  123995. static float _vq_quantthresh__16c1_s_p4_0[] = {
  123996. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123997. };
  123998. static long _vq_quantmap__16c1_s_p4_0[] = {
  123999. 7, 5, 3, 1, 0, 2, 4, 6,
  124000. 8,
  124001. };
  124002. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124003. _vq_quantthresh__16c1_s_p4_0,
  124004. _vq_quantmap__16c1_s_p4_0,
  124005. 9,
  124006. 9
  124007. };
  124008. static static_codebook _16c1_s_p4_0 = {
  124009. 2, 81,
  124010. _vq_lengthlist__16c1_s_p4_0,
  124011. 1, -531628032, 1611661312, 4, 0,
  124012. _vq_quantlist__16c1_s_p4_0,
  124013. NULL,
  124014. &_vq_auxt__16c1_s_p4_0,
  124015. NULL,
  124016. 0
  124017. };
  124018. static long _vq_quantlist__16c1_s_p5_0[] = {
  124019. 4,
  124020. 3,
  124021. 5,
  124022. 2,
  124023. 6,
  124024. 1,
  124025. 7,
  124026. 0,
  124027. 8,
  124028. };
  124029. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124030. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124031. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124032. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124033. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124034. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124035. 10,
  124036. };
  124037. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124038. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124039. };
  124040. static long _vq_quantmap__16c1_s_p5_0[] = {
  124041. 7, 5, 3, 1, 0, 2, 4, 6,
  124042. 8,
  124043. };
  124044. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124045. _vq_quantthresh__16c1_s_p5_0,
  124046. _vq_quantmap__16c1_s_p5_0,
  124047. 9,
  124048. 9
  124049. };
  124050. static static_codebook _16c1_s_p5_0 = {
  124051. 2, 81,
  124052. _vq_lengthlist__16c1_s_p5_0,
  124053. 1, -531628032, 1611661312, 4, 0,
  124054. _vq_quantlist__16c1_s_p5_0,
  124055. NULL,
  124056. &_vq_auxt__16c1_s_p5_0,
  124057. NULL,
  124058. 0
  124059. };
  124060. static long _vq_quantlist__16c1_s_p6_0[] = {
  124061. 8,
  124062. 7,
  124063. 9,
  124064. 6,
  124065. 10,
  124066. 5,
  124067. 11,
  124068. 4,
  124069. 12,
  124070. 3,
  124071. 13,
  124072. 2,
  124073. 14,
  124074. 1,
  124075. 15,
  124076. 0,
  124077. 16,
  124078. };
  124079. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124080. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124081. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124082. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124083. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124084. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124085. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124086. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124087. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124088. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124089. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124090. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124091. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124092. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124093. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124094. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124095. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124096. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124097. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124098. 14,
  124099. };
  124100. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124101. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124102. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124103. };
  124104. static long _vq_quantmap__16c1_s_p6_0[] = {
  124105. 15, 13, 11, 9, 7, 5, 3, 1,
  124106. 0, 2, 4, 6, 8, 10, 12, 14,
  124107. 16,
  124108. };
  124109. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124110. _vq_quantthresh__16c1_s_p6_0,
  124111. _vq_quantmap__16c1_s_p6_0,
  124112. 17,
  124113. 17
  124114. };
  124115. static static_codebook _16c1_s_p6_0 = {
  124116. 2, 289,
  124117. _vq_lengthlist__16c1_s_p6_0,
  124118. 1, -529530880, 1611661312, 5, 0,
  124119. _vq_quantlist__16c1_s_p6_0,
  124120. NULL,
  124121. &_vq_auxt__16c1_s_p6_0,
  124122. NULL,
  124123. 0
  124124. };
  124125. static long _vq_quantlist__16c1_s_p7_0[] = {
  124126. 1,
  124127. 0,
  124128. 2,
  124129. };
  124130. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124131. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124132. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124133. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124134. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124135. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124136. 11,
  124137. };
  124138. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124139. -5.5, 5.5,
  124140. };
  124141. static long _vq_quantmap__16c1_s_p7_0[] = {
  124142. 1, 0, 2,
  124143. };
  124144. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124145. _vq_quantthresh__16c1_s_p7_0,
  124146. _vq_quantmap__16c1_s_p7_0,
  124147. 3,
  124148. 3
  124149. };
  124150. static static_codebook _16c1_s_p7_0 = {
  124151. 4, 81,
  124152. _vq_lengthlist__16c1_s_p7_0,
  124153. 1, -529137664, 1618345984, 2, 0,
  124154. _vq_quantlist__16c1_s_p7_0,
  124155. NULL,
  124156. &_vq_auxt__16c1_s_p7_0,
  124157. NULL,
  124158. 0
  124159. };
  124160. static long _vq_quantlist__16c1_s_p7_1[] = {
  124161. 5,
  124162. 4,
  124163. 6,
  124164. 3,
  124165. 7,
  124166. 2,
  124167. 8,
  124168. 1,
  124169. 9,
  124170. 0,
  124171. 10,
  124172. };
  124173. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124174. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124175. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124176. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124177. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124178. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124179. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124180. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124181. 10,10,10, 8, 8, 8, 8, 9, 9,
  124182. };
  124183. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124184. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124185. 3.5, 4.5,
  124186. };
  124187. static long _vq_quantmap__16c1_s_p7_1[] = {
  124188. 9, 7, 5, 3, 1, 0, 2, 4,
  124189. 6, 8, 10,
  124190. };
  124191. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124192. _vq_quantthresh__16c1_s_p7_1,
  124193. _vq_quantmap__16c1_s_p7_1,
  124194. 11,
  124195. 11
  124196. };
  124197. static static_codebook _16c1_s_p7_1 = {
  124198. 2, 121,
  124199. _vq_lengthlist__16c1_s_p7_1,
  124200. 1, -531365888, 1611661312, 4, 0,
  124201. _vq_quantlist__16c1_s_p7_1,
  124202. NULL,
  124203. &_vq_auxt__16c1_s_p7_1,
  124204. NULL,
  124205. 0
  124206. };
  124207. static long _vq_quantlist__16c1_s_p8_0[] = {
  124208. 6,
  124209. 5,
  124210. 7,
  124211. 4,
  124212. 8,
  124213. 3,
  124214. 9,
  124215. 2,
  124216. 10,
  124217. 1,
  124218. 11,
  124219. 0,
  124220. 12,
  124221. };
  124222. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124223. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124224. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124225. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124226. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124227. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124228. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124229. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124230. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124231. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124232. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124233. 0,12,12,12,12,13,13,14,15,
  124234. };
  124235. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124236. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124237. 12.5, 17.5, 22.5, 27.5,
  124238. };
  124239. static long _vq_quantmap__16c1_s_p8_0[] = {
  124240. 11, 9, 7, 5, 3, 1, 0, 2,
  124241. 4, 6, 8, 10, 12,
  124242. };
  124243. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124244. _vq_quantthresh__16c1_s_p8_0,
  124245. _vq_quantmap__16c1_s_p8_0,
  124246. 13,
  124247. 13
  124248. };
  124249. static static_codebook _16c1_s_p8_0 = {
  124250. 2, 169,
  124251. _vq_lengthlist__16c1_s_p8_0,
  124252. 1, -526516224, 1616117760, 4, 0,
  124253. _vq_quantlist__16c1_s_p8_0,
  124254. NULL,
  124255. &_vq_auxt__16c1_s_p8_0,
  124256. NULL,
  124257. 0
  124258. };
  124259. static long _vq_quantlist__16c1_s_p8_1[] = {
  124260. 2,
  124261. 1,
  124262. 3,
  124263. 0,
  124264. 4,
  124265. };
  124266. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124267. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124268. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124269. };
  124270. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124271. -1.5, -0.5, 0.5, 1.5,
  124272. };
  124273. static long _vq_quantmap__16c1_s_p8_1[] = {
  124274. 3, 1, 0, 2, 4,
  124275. };
  124276. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124277. _vq_quantthresh__16c1_s_p8_1,
  124278. _vq_quantmap__16c1_s_p8_1,
  124279. 5,
  124280. 5
  124281. };
  124282. static static_codebook _16c1_s_p8_1 = {
  124283. 2, 25,
  124284. _vq_lengthlist__16c1_s_p8_1,
  124285. 1, -533725184, 1611661312, 3, 0,
  124286. _vq_quantlist__16c1_s_p8_1,
  124287. NULL,
  124288. &_vq_auxt__16c1_s_p8_1,
  124289. NULL,
  124290. 0
  124291. };
  124292. static long _vq_quantlist__16c1_s_p9_0[] = {
  124293. 6,
  124294. 5,
  124295. 7,
  124296. 4,
  124297. 8,
  124298. 3,
  124299. 9,
  124300. 2,
  124301. 10,
  124302. 1,
  124303. 11,
  124304. 0,
  124305. 12,
  124306. };
  124307. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124308. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124309. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124310. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124312. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124313. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124314. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124315. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124316. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124317. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124318. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124319. };
  124320. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124321. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124322. 787.5, 1102.5, 1417.5, 1732.5,
  124323. };
  124324. static long _vq_quantmap__16c1_s_p9_0[] = {
  124325. 11, 9, 7, 5, 3, 1, 0, 2,
  124326. 4, 6, 8, 10, 12,
  124327. };
  124328. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124329. _vq_quantthresh__16c1_s_p9_0,
  124330. _vq_quantmap__16c1_s_p9_0,
  124331. 13,
  124332. 13
  124333. };
  124334. static static_codebook _16c1_s_p9_0 = {
  124335. 2, 169,
  124336. _vq_lengthlist__16c1_s_p9_0,
  124337. 1, -513964032, 1628680192, 4, 0,
  124338. _vq_quantlist__16c1_s_p9_0,
  124339. NULL,
  124340. &_vq_auxt__16c1_s_p9_0,
  124341. NULL,
  124342. 0
  124343. };
  124344. static long _vq_quantlist__16c1_s_p9_1[] = {
  124345. 7,
  124346. 6,
  124347. 8,
  124348. 5,
  124349. 9,
  124350. 4,
  124351. 10,
  124352. 3,
  124353. 11,
  124354. 2,
  124355. 12,
  124356. 1,
  124357. 13,
  124358. 0,
  124359. 14,
  124360. };
  124361. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124362. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124363. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124364. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124365. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124366. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124367. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124368. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124369. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124370. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124371. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124372. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124373. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124374. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124375. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124376. 13,
  124377. };
  124378. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124379. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124380. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124381. };
  124382. static long _vq_quantmap__16c1_s_p9_1[] = {
  124383. 13, 11, 9, 7, 5, 3, 1, 0,
  124384. 2, 4, 6, 8, 10, 12, 14,
  124385. };
  124386. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124387. _vq_quantthresh__16c1_s_p9_1,
  124388. _vq_quantmap__16c1_s_p9_1,
  124389. 15,
  124390. 15
  124391. };
  124392. static static_codebook _16c1_s_p9_1 = {
  124393. 2, 225,
  124394. _vq_lengthlist__16c1_s_p9_1,
  124395. 1, -520986624, 1620377600, 4, 0,
  124396. _vq_quantlist__16c1_s_p9_1,
  124397. NULL,
  124398. &_vq_auxt__16c1_s_p9_1,
  124399. NULL,
  124400. 0
  124401. };
  124402. static long _vq_quantlist__16c1_s_p9_2[] = {
  124403. 10,
  124404. 9,
  124405. 11,
  124406. 8,
  124407. 12,
  124408. 7,
  124409. 13,
  124410. 6,
  124411. 14,
  124412. 5,
  124413. 15,
  124414. 4,
  124415. 16,
  124416. 3,
  124417. 17,
  124418. 2,
  124419. 18,
  124420. 1,
  124421. 19,
  124422. 0,
  124423. 20,
  124424. };
  124425. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124426. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124427. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124428. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124429. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124430. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124431. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124432. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124433. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124434. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124435. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124436. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124437. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124438. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124439. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124440. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124441. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124442. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124443. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124444. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124445. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124446. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124447. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124448. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124449. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124450. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124451. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124452. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124453. 11,11,11,11,12,11,11,12,11,
  124454. };
  124455. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124456. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124457. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124458. 6.5, 7.5, 8.5, 9.5,
  124459. };
  124460. static long _vq_quantmap__16c1_s_p9_2[] = {
  124461. 19, 17, 15, 13, 11, 9, 7, 5,
  124462. 3, 1, 0, 2, 4, 6, 8, 10,
  124463. 12, 14, 16, 18, 20,
  124464. };
  124465. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124466. _vq_quantthresh__16c1_s_p9_2,
  124467. _vq_quantmap__16c1_s_p9_2,
  124468. 21,
  124469. 21
  124470. };
  124471. static static_codebook _16c1_s_p9_2 = {
  124472. 2, 441,
  124473. _vq_lengthlist__16c1_s_p9_2,
  124474. 1, -529268736, 1611661312, 5, 0,
  124475. _vq_quantlist__16c1_s_p9_2,
  124476. NULL,
  124477. &_vq_auxt__16c1_s_p9_2,
  124478. NULL,
  124479. 0
  124480. };
  124481. static long _huff_lengthlist__16c1_s_short[] = {
  124482. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124483. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124484. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124485. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124486. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124487. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124488. 9, 9,10,13,
  124489. };
  124490. static static_codebook _huff_book__16c1_s_short = {
  124491. 2, 100,
  124492. _huff_lengthlist__16c1_s_short,
  124493. 0, 0, 0, 0, 0,
  124494. NULL,
  124495. NULL,
  124496. NULL,
  124497. NULL,
  124498. 0
  124499. };
  124500. static long _huff_lengthlist__16c2_s_long[] = {
  124501. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124502. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124503. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124504. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124505. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124506. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124507. 14,14,16,18,
  124508. };
  124509. static static_codebook _huff_book__16c2_s_long = {
  124510. 2, 100,
  124511. _huff_lengthlist__16c2_s_long,
  124512. 0, 0, 0, 0, 0,
  124513. NULL,
  124514. NULL,
  124515. NULL,
  124516. NULL,
  124517. 0
  124518. };
  124519. static long _vq_quantlist__16c2_s_p1_0[] = {
  124520. 1,
  124521. 0,
  124522. 2,
  124523. };
  124524. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124525. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124526. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124530. 0,
  124531. };
  124532. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124533. -0.5, 0.5,
  124534. };
  124535. static long _vq_quantmap__16c2_s_p1_0[] = {
  124536. 1, 0, 2,
  124537. };
  124538. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124539. _vq_quantthresh__16c2_s_p1_0,
  124540. _vq_quantmap__16c2_s_p1_0,
  124541. 3,
  124542. 3
  124543. };
  124544. static static_codebook _16c2_s_p1_0 = {
  124545. 4, 81,
  124546. _vq_lengthlist__16c2_s_p1_0,
  124547. 1, -535822336, 1611661312, 2, 0,
  124548. _vq_quantlist__16c2_s_p1_0,
  124549. NULL,
  124550. &_vq_auxt__16c2_s_p1_0,
  124551. NULL,
  124552. 0
  124553. };
  124554. static long _vq_quantlist__16c2_s_p2_0[] = {
  124555. 2,
  124556. 1,
  124557. 3,
  124558. 0,
  124559. 4,
  124560. };
  124561. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124562. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124563. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124564. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124565. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124566. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124567. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124568. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124569. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124574. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124575. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124576. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124577. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124582. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124583. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124584. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124585. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124590. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124591. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124592. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124593. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124598. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124599. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124600. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124601. 13,
  124602. };
  124603. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124604. -1.5, -0.5, 0.5, 1.5,
  124605. };
  124606. static long _vq_quantmap__16c2_s_p2_0[] = {
  124607. 3, 1, 0, 2, 4,
  124608. };
  124609. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124610. _vq_quantthresh__16c2_s_p2_0,
  124611. _vq_quantmap__16c2_s_p2_0,
  124612. 5,
  124613. 5
  124614. };
  124615. static static_codebook _16c2_s_p2_0 = {
  124616. 4, 625,
  124617. _vq_lengthlist__16c2_s_p2_0,
  124618. 1, -533725184, 1611661312, 3, 0,
  124619. _vq_quantlist__16c2_s_p2_0,
  124620. NULL,
  124621. &_vq_auxt__16c2_s_p2_0,
  124622. NULL,
  124623. 0
  124624. };
  124625. static long _vq_quantlist__16c2_s_p3_0[] = {
  124626. 4,
  124627. 3,
  124628. 5,
  124629. 2,
  124630. 6,
  124631. 1,
  124632. 7,
  124633. 0,
  124634. 8,
  124635. };
  124636. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124637. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124638. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124639. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124640. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0,
  124643. };
  124644. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124645. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124646. };
  124647. static long _vq_quantmap__16c2_s_p3_0[] = {
  124648. 7, 5, 3, 1, 0, 2, 4, 6,
  124649. 8,
  124650. };
  124651. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124652. _vq_quantthresh__16c2_s_p3_0,
  124653. _vq_quantmap__16c2_s_p3_0,
  124654. 9,
  124655. 9
  124656. };
  124657. static static_codebook _16c2_s_p3_0 = {
  124658. 2, 81,
  124659. _vq_lengthlist__16c2_s_p3_0,
  124660. 1, -531628032, 1611661312, 4, 0,
  124661. _vq_quantlist__16c2_s_p3_0,
  124662. NULL,
  124663. &_vq_auxt__16c2_s_p3_0,
  124664. NULL,
  124665. 0
  124666. };
  124667. static long _vq_quantlist__16c2_s_p4_0[] = {
  124668. 8,
  124669. 7,
  124670. 9,
  124671. 6,
  124672. 10,
  124673. 5,
  124674. 11,
  124675. 4,
  124676. 12,
  124677. 3,
  124678. 13,
  124679. 2,
  124680. 14,
  124681. 1,
  124682. 15,
  124683. 0,
  124684. 16,
  124685. };
  124686. static long _vq_lengthlist__16c2_s_p4_0[] = {
  124687. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  124688. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  124689. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  124690. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  124691. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  124692. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  124693. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  124694. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  124695. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  124696. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0,
  124706. };
  124707. static float _vq_quantthresh__16c2_s_p4_0[] = {
  124708. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124709. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124710. };
  124711. static long _vq_quantmap__16c2_s_p4_0[] = {
  124712. 15, 13, 11, 9, 7, 5, 3, 1,
  124713. 0, 2, 4, 6, 8, 10, 12, 14,
  124714. 16,
  124715. };
  124716. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  124717. _vq_quantthresh__16c2_s_p4_0,
  124718. _vq_quantmap__16c2_s_p4_0,
  124719. 17,
  124720. 17
  124721. };
  124722. static static_codebook _16c2_s_p4_0 = {
  124723. 2, 289,
  124724. _vq_lengthlist__16c2_s_p4_0,
  124725. 1, -529530880, 1611661312, 5, 0,
  124726. _vq_quantlist__16c2_s_p4_0,
  124727. NULL,
  124728. &_vq_auxt__16c2_s_p4_0,
  124729. NULL,
  124730. 0
  124731. };
  124732. static long _vq_quantlist__16c2_s_p5_0[] = {
  124733. 1,
  124734. 0,
  124735. 2,
  124736. };
  124737. static long _vq_lengthlist__16c2_s_p5_0[] = {
  124738. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  124739. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  124740. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  124741. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  124742. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  124743. 12,
  124744. };
  124745. static float _vq_quantthresh__16c2_s_p5_0[] = {
  124746. -5.5, 5.5,
  124747. };
  124748. static long _vq_quantmap__16c2_s_p5_0[] = {
  124749. 1, 0, 2,
  124750. };
  124751. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  124752. _vq_quantthresh__16c2_s_p5_0,
  124753. _vq_quantmap__16c2_s_p5_0,
  124754. 3,
  124755. 3
  124756. };
  124757. static static_codebook _16c2_s_p5_0 = {
  124758. 4, 81,
  124759. _vq_lengthlist__16c2_s_p5_0,
  124760. 1, -529137664, 1618345984, 2, 0,
  124761. _vq_quantlist__16c2_s_p5_0,
  124762. NULL,
  124763. &_vq_auxt__16c2_s_p5_0,
  124764. NULL,
  124765. 0
  124766. };
  124767. static long _vq_quantlist__16c2_s_p5_1[] = {
  124768. 5,
  124769. 4,
  124770. 6,
  124771. 3,
  124772. 7,
  124773. 2,
  124774. 8,
  124775. 1,
  124776. 9,
  124777. 0,
  124778. 10,
  124779. };
  124780. static long _vq_lengthlist__16c2_s_p5_1[] = {
  124781. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  124782. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  124783. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  124784. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  124785. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  124786. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  124787. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  124788. 11,11,11, 7, 7, 8, 8, 8, 8,
  124789. };
  124790. static float _vq_quantthresh__16c2_s_p5_1[] = {
  124791. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124792. 3.5, 4.5,
  124793. };
  124794. static long _vq_quantmap__16c2_s_p5_1[] = {
  124795. 9, 7, 5, 3, 1, 0, 2, 4,
  124796. 6, 8, 10,
  124797. };
  124798. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  124799. _vq_quantthresh__16c2_s_p5_1,
  124800. _vq_quantmap__16c2_s_p5_1,
  124801. 11,
  124802. 11
  124803. };
  124804. static static_codebook _16c2_s_p5_1 = {
  124805. 2, 121,
  124806. _vq_lengthlist__16c2_s_p5_1,
  124807. 1, -531365888, 1611661312, 4, 0,
  124808. _vq_quantlist__16c2_s_p5_1,
  124809. NULL,
  124810. &_vq_auxt__16c2_s_p5_1,
  124811. NULL,
  124812. 0
  124813. };
  124814. static long _vq_quantlist__16c2_s_p6_0[] = {
  124815. 6,
  124816. 5,
  124817. 7,
  124818. 4,
  124819. 8,
  124820. 3,
  124821. 9,
  124822. 2,
  124823. 10,
  124824. 1,
  124825. 11,
  124826. 0,
  124827. 12,
  124828. };
  124829. static long _vq_lengthlist__16c2_s_p6_0[] = {
  124830. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124831. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  124832. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  124833. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  124834. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  124835. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124840. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124841. };
  124842. static float _vq_quantthresh__16c2_s_p6_0[] = {
  124843. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124844. 12.5, 17.5, 22.5, 27.5,
  124845. };
  124846. static long _vq_quantmap__16c2_s_p6_0[] = {
  124847. 11, 9, 7, 5, 3, 1, 0, 2,
  124848. 4, 6, 8, 10, 12,
  124849. };
  124850. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  124851. _vq_quantthresh__16c2_s_p6_0,
  124852. _vq_quantmap__16c2_s_p6_0,
  124853. 13,
  124854. 13
  124855. };
  124856. static static_codebook _16c2_s_p6_0 = {
  124857. 2, 169,
  124858. _vq_lengthlist__16c2_s_p6_0,
  124859. 1, -526516224, 1616117760, 4, 0,
  124860. _vq_quantlist__16c2_s_p6_0,
  124861. NULL,
  124862. &_vq_auxt__16c2_s_p6_0,
  124863. NULL,
  124864. 0
  124865. };
  124866. static long _vq_quantlist__16c2_s_p6_1[] = {
  124867. 2,
  124868. 1,
  124869. 3,
  124870. 0,
  124871. 4,
  124872. };
  124873. static long _vq_lengthlist__16c2_s_p6_1[] = {
  124874. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124875. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124876. };
  124877. static float _vq_quantthresh__16c2_s_p6_1[] = {
  124878. -1.5, -0.5, 0.5, 1.5,
  124879. };
  124880. static long _vq_quantmap__16c2_s_p6_1[] = {
  124881. 3, 1, 0, 2, 4,
  124882. };
  124883. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  124884. _vq_quantthresh__16c2_s_p6_1,
  124885. _vq_quantmap__16c2_s_p6_1,
  124886. 5,
  124887. 5
  124888. };
  124889. static static_codebook _16c2_s_p6_1 = {
  124890. 2, 25,
  124891. _vq_lengthlist__16c2_s_p6_1,
  124892. 1, -533725184, 1611661312, 3, 0,
  124893. _vq_quantlist__16c2_s_p6_1,
  124894. NULL,
  124895. &_vq_auxt__16c2_s_p6_1,
  124896. NULL,
  124897. 0
  124898. };
  124899. static long _vq_quantlist__16c2_s_p7_0[] = {
  124900. 6,
  124901. 5,
  124902. 7,
  124903. 4,
  124904. 8,
  124905. 3,
  124906. 9,
  124907. 2,
  124908. 10,
  124909. 1,
  124910. 11,
  124911. 0,
  124912. 12,
  124913. };
  124914. static long _vq_lengthlist__16c2_s_p7_0[] = {
  124915. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  124916. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  124917. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  124918. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  124919. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  124920. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  124921. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  124922. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  124923. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  124924. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  124925. 18,13,14,13,13,14,13,15,14,
  124926. };
  124927. static float _vq_quantthresh__16c2_s_p7_0[] = {
  124928. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  124929. 27.5, 38.5, 49.5, 60.5,
  124930. };
  124931. static long _vq_quantmap__16c2_s_p7_0[] = {
  124932. 11, 9, 7, 5, 3, 1, 0, 2,
  124933. 4, 6, 8, 10, 12,
  124934. };
  124935. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  124936. _vq_quantthresh__16c2_s_p7_0,
  124937. _vq_quantmap__16c2_s_p7_0,
  124938. 13,
  124939. 13
  124940. };
  124941. static static_codebook _16c2_s_p7_0 = {
  124942. 2, 169,
  124943. _vq_lengthlist__16c2_s_p7_0,
  124944. 1, -523206656, 1618345984, 4, 0,
  124945. _vq_quantlist__16c2_s_p7_0,
  124946. NULL,
  124947. &_vq_auxt__16c2_s_p7_0,
  124948. NULL,
  124949. 0
  124950. };
  124951. static long _vq_quantlist__16c2_s_p7_1[] = {
  124952. 5,
  124953. 4,
  124954. 6,
  124955. 3,
  124956. 7,
  124957. 2,
  124958. 8,
  124959. 1,
  124960. 9,
  124961. 0,
  124962. 10,
  124963. };
  124964. static long _vq_lengthlist__16c2_s_p7_1[] = {
  124965. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  124966. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  124967. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  124968. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124969. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  124970. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  124971. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  124972. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  124973. };
  124974. static float _vq_quantthresh__16c2_s_p7_1[] = {
  124975. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124976. 3.5, 4.5,
  124977. };
  124978. static long _vq_quantmap__16c2_s_p7_1[] = {
  124979. 9, 7, 5, 3, 1, 0, 2, 4,
  124980. 6, 8, 10,
  124981. };
  124982. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  124983. _vq_quantthresh__16c2_s_p7_1,
  124984. _vq_quantmap__16c2_s_p7_1,
  124985. 11,
  124986. 11
  124987. };
  124988. static static_codebook _16c2_s_p7_1 = {
  124989. 2, 121,
  124990. _vq_lengthlist__16c2_s_p7_1,
  124991. 1, -531365888, 1611661312, 4, 0,
  124992. _vq_quantlist__16c2_s_p7_1,
  124993. NULL,
  124994. &_vq_auxt__16c2_s_p7_1,
  124995. NULL,
  124996. 0
  124997. };
  124998. static long _vq_quantlist__16c2_s_p8_0[] = {
  124999. 7,
  125000. 6,
  125001. 8,
  125002. 5,
  125003. 9,
  125004. 4,
  125005. 10,
  125006. 3,
  125007. 11,
  125008. 2,
  125009. 12,
  125010. 1,
  125011. 13,
  125012. 0,
  125013. 14,
  125014. };
  125015. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125016. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125017. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125018. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125019. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125020. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125021. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125022. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125023. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125024. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125025. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125026. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125027. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125028. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125029. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125030. 13,
  125031. };
  125032. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125033. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125034. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125035. };
  125036. static long _vq_quantmap__16c2_s_p8_0[] = {
  125037. 13, 11, 9, 7, 5, 3, 1, 0,
  125038. 2, 4, 6, 8, 10, 12, 14,
  125039. };
  125040. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125041. _vq_quantthresh__16c2_s_p8_0,
  125042. _vq_quantmap__16c2_s_p8_0,
  125043. 15,
  125044. 15
  125045. };
  125046. static static_codebook _16c2_s_p8_0 = {
  125047. 2, 225,
  125048. _vq_lengthlist__16c2_s_p8_0,
  125049. 1, -520986624, 1620377600, 4, 0,
  125050. _vq_quantlist__16c2_s_p8_0,
  125051. NULL,
  125052. &_vq_auxt__16c2_s_p8_0,
  125053. NULL,
  125054. 0
  125055. };
  125056. static long _vq_quantlist__16c2_s_p8_1[] = {
  125057. 10,
  125058. 9,
  125059. 11,
  125060. 8,
  125061. 12,
  125062. 7,
  125063. 13,
  125064. 6,
  125065. 14,
  125066. 5,
  125067. 15,
  125068. 4,
  125069. 16,
  125070. 3,
  125071. 17,
  125072. 2,
  125073. 18,
  125074. 1,
  125075. 19,
  125076. 0,
  125077. 20,
  125078. };
  125079. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125080. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125081. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125082. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125083. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125084. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125085. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125086. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125087. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125088. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125089. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125090. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125091. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125092. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125093. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125094. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125095. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125096. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125097. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125098. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125099. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125100. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125101. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125102. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125103. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125104. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125105. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125106. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125107. 10,11,10,10,10,10,10,10,10,
  125108. };
  125109. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125110. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125111. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125112. 6.5, 7.5, 8.5, 9.5,
  125113. };
  125114. static long _vq_quantmap__16c2_s_p8_1[] = {
  125115. 19, 17, 15, 13, 11, 9, 7, 5,
  125116. 3, 1, 0, 2, 4, 6, 8, 10,
  125117. 12, 14, 16, 18, 20,
  125118. };
  125119. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125120. _vq_quantthresh__16c2_s_p8_1,
  125121. _vq_quantmap__16c2_s_p8_1,
  125122. 21,
  125123. 21
  125124. };
  125125. static static_codebook _16c2_s_p8_1 = {
  125126. 2, 441,
  125127. _vq_lengthlist__16c2_s_p8_1,
  125128. 1, -529268736, 1611661312, 5, 0,
  125129. _vq_quantlist__16c2_s_p8_1,
  125130. NULL,
  125131. &_vq_auxt__16c2_s_p8_1,
  125132. NULL,
  125133. 0
  125134. };
  125135. static long _vq_quantlist__16c2_s_p9_0[] = {
  125136. 6,
  125137. 5,
  125138. 7,
  125139. 4,
  125140. 8,
  125141. 3,
  125142. 9,
  125143. 2,
  125144. 10,
  125145. 1,
  125146. 11,
  125147. 0,
  125148. 12,
  125149. };
  125150. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125151. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125153. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125154. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125155. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125156. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125157. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125158. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125159. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125160. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125161. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125162. };
  125163. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125164. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125165. 2327.5, 3258.5, 4189.5, 5120.5,
  125166. };
  125167. static long _vq_quantmap__16c2_s_p9_0[] = {
  125168. 11, 9, 7, 5, 3, 1, 0, 2,
  125169. 4, 6, 8, 10, 12,
  125170. };
  125171. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125172. _vq_quantthresh__16c2_s_p9_0,
  125173. _vq_quantmap__16c2_s_p9_0,
  125174. 13,
  125175. 13
  125176. };
  125177. static static_codebook _16c2_s_p9_0 = {
  125178. 2, 169,
  125179. _vq_lengthlist__16c2_s_p9_0,
  125180. 1, -510275072, 1631393792, 4, 0,
  125181. _vq_quantlist__16c2_s_p9_0,
  125182. NULL,
  125183. &_vq_auxt__16c2_s_p9_0,
  125184. NULL,
  125185. 0
  125186. };
  125187. static long _vq_quantlist__16c2_s_p9_1[] = {
  125188. 8,
  125189. 7,
  125190. 9,
  125191. 6,
  125192. 10,
  125193. 5,
  125194. 11,
  125195. 4,
  125196. 12,
  125197. 3,
  125198. 13,
  125199. 2,
  125200. 14,
  125201. 1,
  125202. 15,
  125203. 0,
  125204. 16,
  125205. };
  125206. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125207. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125208. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125209. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125210. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125211. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125212. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125213. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125214. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125215. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125216. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125217. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125218. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125219. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125220. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125221. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125222. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125223. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125224. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125225. 10,
  125226. };
  125227. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125228. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125229. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125230. };
  125231. static long _vq_quantmap__16c2_s_p9_1[] = {
  125232. 15, 13, 11, 9, 7, 5, 3, 1,
  125233. 0, 2, 4, 6, 8, 10, 12, 14,
  125234. 16,
  125235. };
  125236. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125237. _vq_quantthresh__16c2_s_p9_1,
  125238. _vq_quantmap__16c2_s_p9_1,
  125239. 17,
  125240. 17
  125241. };
  125242. static static_codebook _16c2_s_p9_1 = {
  125243. 2, 289,
  125244. _vq_lengthlist__16c2_s_p9_1,
  125245. 1, -518488064, 1622704128, 5, 0,
  125246. _vq_quantlist__16c2_s_p9_1,
  125247. NULL,
  125248. &_vq_auxt__16c2_s_p9_1,
  125249. NULL,
  125250. 0
  125251. };
  125252. static long _vq_quantlist__16c2_s_p9_2[] = {
  125253. 13,
  125254. 12,
  125255. 14,
  125256. 11,
  125257. 15,
  125258. 10,
  125259. 16,
  125260. 9,
  125261. 17,
  125262. 8,
  125263. 18,
  125264. 7,
  125265. 19,
  125266. 6,
  125267. 20,
  125268. 5,
  125269. 21,
  125270. 4,
  125271. 22,
  125272. 3,
  125273. 23,
  125274. 2,
  125275. 24,
  125276. 1,
  125277. 25,
  125278. 0,
  125279. 26,
  125280. };
  125281. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125282. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125283. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125284. };
  125285. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125286. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125287. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125288. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125289. 11.5, 12.5,
  125290. };
  125291. static long _vq_quantmap__16c2_s_p9_2[] = {
  125292. 25, 23, 21, 19, 17, 15, 13, 11,
  125293. 9, 7, 5, 3, 1, 0, 2, 4,
  125294. 6, 8, 10, 12, 14, 16, 18, 20,
  125295. 22, 24, 26,
  125296. };
  125297. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125298. _vq_quantthresh__16c2_s_p9_2,
  125299. _vq_quantmap__16c2_s_p9_2,
  125300. 27,
  125301. 27
  125302. };
  125303. static static_codebook _16c2_s_p9_2 = {
  125304. 1, 27,
  125305. _vq_lengthlist__16c2_s_p9_2,
  125306. 1, -528875520, 1611661312, 5, 0,
  125307. _vq_quantlist__16c2_s_p9_2,
  125308. NULL,
  125309. &_vq_auxt__16c2_s_p9_2,
  125310. NULL,
  125311. 0
  125312. };
  125313. static long _huff_lengthlist__16c2_s_short[] = {
  125314. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125315. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125316. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125317. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125318. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125319. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125320. 15,12,14,14,
  125321. };
  125322. static static_codebook _huff_book__16c2_s_short = {
  125323. 2, 100,
  125324. _huff_lengthlist__16c2_s_short,
  125325. 0, 0, 0, 0, 0,
  125326. NULL,
  125327. NULL,
  125328. NULL,
  125329. NULL,
  125330. 0
  125331. };
  125332. static long _vq_quantlist__8c0_s_p1_0[] = {
  125333. 1,
  125334. 0,
  125335. 2,
  125336. };
  125337. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125338. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125339. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125343. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125344. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125348. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125349. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125384. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  125389. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  125394. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125429. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125430. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125434. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125435. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  125436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125439. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125440. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125748. 0,
  125749. };
  125750. static float _vq_quantthresh__8c0_s_p1_0[] = {
  125751. -0.5, 0.5,
  125752. };
  125753. static long _vq_quantmap__8c0_s_p1_0[] = {
  125754. 1, 0, 2,
  125755. };
  125756. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  125757. _vq_quantthresh__8c0_s_p1_0,
  125758. _vq_quantmap__8c0_s_p1_0,
  125759. 3,
  125760. 3
  125761. };
  125762. static static_codebook _8c0_s_p1_0 = {
  125763. 8, 6561,
  125764. _vq_lengthlist__8c0_s_p1_0,
  125765. 1, -535822336, 1611661312, 2, 0,
  125766. _vq_quantlist__8c0_s_p1_0,
  125767. NULL,
  125768. &_vq_auxt__8c0_s_p1_0,
  125769. NULL,
  125770. 0
  125771. };
  125772. static long _vq_quantlist__8c0_s_p2_0[] = {
  125773. 2,
  125774. 1,
  125775. 3,
  125776. 0,
  125777. 4,
  125778. };
  125779. static long _vq_lengthlist__8c0_s_p2_0[] = {
  125780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125819. 0,
  125820. };
  125821. static float _vq_quantthresh__8c0_s_p2_0[] = {
  125822. -1.5, -0.5, 0.5, 1.5,
  125823. };
  125824. static long _vq_quantmap__8c0_s_p2_0[] = {
  125825. 3, 1, 0, 2, 4,
  125826. };
  125827. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  125828. _vq_quantthresh__8c0_s_p2_0,
  125829. _vq_quantmap__8c0_s_p2_0,
  125830. 5,
  125831. 5
  125832. };
  125833. static static_codebook _8c0_s_p2_0 = {
  125834. 4, 625,
  125835. _vq_lengthlist__8c0_s_p2_0,
  125836. 1, -533725184, 1611661312, 3, 0,
  125837. _vq_quantlist__8c0_s_p2_0,
  125838. NULL,
  125839. &_vq_auxt__8c0_s_p2_0,
  125840. NULL,
  125841. 0
  125842. };
  125843. static long _vq_quantlist__8c0_s_p3_0[] = {
  125844. 2,
  125845. 1,
  125846. 3,
  125847. 0,
  125848. 4,
  125849. };
  125850. static long _vq_lengthlist__8c0_s_p3_0[] = {
  125851. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  125853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125854. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  125856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125857. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  125858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0,
  125891. };
  125892. static float _vq_quantthresh__8c0_s_p3_0[] = {
  125893. -1.5, -0.5, 0.5, 1.5,
  125894. };
  125895. static long _vq_quantmap__8c0_s_p3_0[] = {
  125896. 3, 1, 0, 2, 4,
  125897. };
  125898. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  125899. _vq_quantthresh__8c0_s_p3_0,
  125900. _vq_quantmap__8c0_s_p3_0,
  125901. 5,
  125902. 5
  125903. };
  125904. static static_codebook _8c0_s_p3_0 = {
  125905. 4, 625,
  125906. _vq_lengthlist__8c0_s_p3_0,
  125907. 1, -533725184, 1611661312, 3, 0,
  125908. _vq_quantlist__8c0_s_p3_0,
  125909. NULL,
  125910. &_vq_auxt__8c0_s_p3_0,
  125911. NULL,
  125912. 0
  125913. };
  125914. static long _vq_quantlist__8c0_s_p4_0[] = {
  125915. 4,
  125916. 3,
  125917. 5,
  125918. 2,
  125919. 6,
  125920. 1,
  125921. 7,
  125922. 0,
  125923. 8,
  125924. };
  125925. static long _vq_lengthlist__8c0_s_p4_0[] = {
  125926. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  125927. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  125928. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  125929. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  125930. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0,
  125932. };
  125933. static float _vq_quantthresh__8c0_s_p4_0[] = {
  125934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125935. };
  125936. static long _vq_quantmap__8c0_s_p4_0[] = {
  125937. 7, 5, 3, 1, 0, 2, 4, 6,
  125938. 8,
  125939. };
  125940. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  125941. _vq_quantthresh__8c0_s_p4_0,
  125942. _vq_quantmap__8c0_s_p4_0,
  125943. 9,
  125944. 9
  125945. };
  125946. static static_codebook _8c0_s_p4_0 = {
  125947. 2, 81,
  125948. _vq_lengthlist__8c0_s_p4_0,
  125949. 1, -531628032, 1611661312, 4, 0,
  125950. _vq_quantlist__8c0_s_p4_0,
  125951. NULL,
  125952. &_vq_auxt__8c0_s_p4_0,
  125953. NULL,
  125954. 0
  125955. };
  125956. static long _vq_quantlist__8c0_s_p5_0[] = {
  125957. 4,
  125958. 3,
  125959. 5,
  125960. 2,
  125961. 6,
  125962. 1,
  125963. 7,
  125964. 0,
  125965. 8,
  125966. };
  125967. static long _vq_lengthlist__8c0_s_p5_0[] = {
  125968. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125969. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  125970. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  125971. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125972. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125973. 10,
  125974. };
  125975. static float _vq_quantthresh__8c0_s_p5_0[] = {
  125976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125977. };
  125978. static long _vq_quantmap__8c0_s_p5_0[] = {
  125979. 7, 5, 3, 1, 0, 2, 4, 6,
  125980. 8,
  125981. };
  125982. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  125983. _vq_quantthresh__8c0_s_p5_0,
  125984. _vq_quantmap__8c0_s_p5_0,
  125985. 9,
  125986. 9
  125987. };
  125988. static static_codebook _8c0_s_p5_0 = {
  125989. 2, 81,
  125990. _vq_lengthlist__8c0_s_p5_0,
  125991. 1, -531628032, 1611661312, 4, 0,
  125992. _vq_quantlist__8c0_s_p5_0,
  125993. NULL,
  125994. &_vq_auxt__8c0_s_p5_0,
  125995. NULL,
  125996. 0
  125997. };
  125998. static long _vq_quantlist__8c0_s_p6_0[] = {
  125999. 8,
  126000. 7,
  126001. 9,
  126002. 6,
  126003. 10,
  126004. 5,
  126005. 11,
  126006. 4,
  126007. 12,
  126008. 3,
  126009. 13,
  126010. 2,
  126011. 14,
  126012. 1,
  126013. 15,
  126014. 0,
  126015. 16,
  126016. };
  126017. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126018. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126019. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126020. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126021. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126022. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126023. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126024. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126025. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126026. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126027. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126028. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126029. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126030. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126031. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126032. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126033. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126034. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126035. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126036. 14,
  126037. };
  126038. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126039. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126040. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126041. };
  126042. static long _vq_quantmap__8c0_s_p6_0[] = {
  126043. 15, 13, 11, 9, 7, 5, 3, 1,
  126044. 0, 2, 4, 6, 8, 10, 12, 14,
  126045. 16,
  126046. };
  126047. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126048. _vq_quantthresh__8c0_s_p6_0,
  126049. _vq_quantmap__8c0_s_p6_0,
  126050. 17,
  126051. 17
  126052. };
  126053. static static_codebook _8c0_s_p6_0 = {
  126054. 2, 289,
  126055. _vq_lengthlist__8c0_s_p6_0,
  126056. 1, -529530880, 1611661312, 5, 0,
  126057. _vq_quantlist__8c0_s_p6_0,
  126058. NULL,
  126059. &_vq_auxt__8c0_s_p6_0,
  126060. NULL,
  126061. 0
  126062. };
  126063. static long _vq_quantlist__8c0_s_p7_0[] = {
  126064. 1,
  126065. 0,
  126066. 2,
  126067. };
  126068. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126069. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126070. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126071. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126072. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126073. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126074. 10,
  126075. };
  126076. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126077. -5.5, 5.5,
  126078. };
  126079. static long _vq_quantmap__8c0_s_p7_0[] = {
  126080. 1, 0, 2,
  126081. };
  126082. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126083. _vq_quantthresh__8c0_s_p7_0,
  126084. _vq_quantmap__8c0_s_p7_0,
  126085. 3,
  126086. 3
  126087. };
  126088. static static_codebook _8c0_s_p7_0 = {
  126089. 4, 81,
  126090. _vq_lengthlist__8c0_s_p7_0,
  126091. 1, -529137664, 1618345984, 2, 0,
  126092. _vq_quantlist__8c0_s_p7_0,
  126093. NULL,
  126094. &_vq_auxt__8c0_s_p7_0,
  126095. NULL,
  126096. 0
  126097. };
  126098. static long _vq_quantlist__8c0_s_p7_1[] = {
  126099. 5,
  126100. 4,
  126101. 6,
  126102. 3,
  126103. 7,
  126104. 2,
  126105. 8,
  126106. 1,
  126107. 9,
  126108. 0,
  126109. 10,
  126110. };
  126111. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126112. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126113. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126114. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126115. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126116. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126117. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126118. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126119. 10,10,10, 9, 9, 9,10,10,10,
  126120. };
  126121. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126123. 3.5, 4.5,
  126124. };
  126125. static long _vq_quantmap__8c0_s_p7_1[] = {
  126126. 9, 7, 5, 3, 1, 0, 2, 4,
  126127. 6, 8, 10,
  126128. };
  126129. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126130. _vq_quantthresh__8c0_s_p7_1,
  126131. _vq_quantmap__8c0_s_p7_1,
  126132. 11,
  126133. 11
  126134. };
  126135. static static_codebook _8c0_s_p7_1 = {
  126136. 2, 121,
  126137. _vq_lengthlist__8c0_s_p7_1,
  126138. 1, -531365888, 1611661312, 4, 0,
  126139. _vq_quantlist__8c0_s_p7_1,
  126140. NULL,
  126141. &_vq_auxt__8c0_s_p7_1,
  126142. NULL,
  126143. 0
  126144. };
  126145. static long _vq_quantlist__8c0_s_p8_0[] = {
  126146. 6,
  126147. 5,
  126148. 7,
  126149. 4,
  126150. 8,
  126151. 3,
  126152. 9,
  126153. 2,
  126154. 10,
  126155. 1,
  126156. 11,
  126157. 0,
  126158. 12,
  126159. };
  126160. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126161. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126162. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126163. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126164. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126165. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126166. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126167. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126168. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126169. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126170. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126171. 0, 0,13,13,11,13,13,11,12,
  126172. };
  126173. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126175. 12.5, 17.5, 22.5, 27.5,
  126176. };
  126177. static long _vq_quantmap__8c0_s_p8_0[] = {
  126178. 11, 9, 7, 5, 3, 1, 0, 2,
  126179. 4, 6, 8, 10, 12,
  126180. };
  126181. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126182. _vq_quantthresh__8c0_s_p8_0,
  126183. _vq_quantmap__8c0_s_p8_0,
  126184. 13,
  126185. 13
  126186. };
  126187. static static_codebook _8c0_s_p8_0 = {
  126188. 2, 169,
  126189. _vq_lengthlist__8c0_s_p8_0,
  126190. 1, -526516224, 1616117760, 4, 0,
  126191. _vq_quantlist__8c0_s_p8_0,
  126192. NULL,
  126193. &_vq_auxt__8c0_s_p8_0,
  126194. NULL,
  126195. 0
  126196. };
  126197. static long _vq_quantlist__8c0_s_p8_1[] = {
  126198. 2,
  126199. 1,
  126200. 3,
  126201. 0,
  126202. 4,
  126203. };
  126204. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126205. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126206. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126207. };
  126208. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126209. -1.5, -0.5, 0.5, 1.5,
  126210. };
  126211. static long _vq_quantmap__8c0_s_p8_1[] = {
  126212. 3, 1, 0, 2, 4,
  126213. };
  126214. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126215. _vq_quantthresh__8c0_s_p8_1,
  126216. _vq_quantmap__8c0_s_p8_1,
  126217. 5,
  126218. 5
  126219. };
  126220. static static_codebook _8c0_s_p8_1 = {
  126221. 2, 25,
  126222. _vq_lengthlist__8c0_s_p8_1,
  126223. 1, -533725184, 1611661312, 3, 0,
  126224. _vq_quantlist__8c0_s_p8_1,
  126225. NULL,
  126226. &_vq_auxt__8c0_s_p8_1,
  126227. NULL,
  126228. 0
  126229. };
  126230. static long _vq_quantlist__8c0_s_p9_0[] = {
  126231. 1,
  126232. 0,
  126233. 2,
  126234. };
  126235. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126236. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126237. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126238. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126239. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126240. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126241. 7,
  126242. };
  126243. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126244. -157.5, 157.5,
  126245. };
  126246. static long _vq_quantmap__8c0_s_p9_0[] = {
  126247. 1, 0, 2,
  126248. };
  126249. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126250. _vq_quantthresh__8c0_s_p9_0,
  126251. _vq_quantmap__8c0_s_p9_0,
  126252. 3,
  126253. 3
  126254. };
  126255. static static_codebook _8c0_s_p9_0 = {
  126256. 4, 81,
  126257. _vq_lengthlist__8c0_s_p9_0,
  126258. 1, -518803456, 1628680192, 2, 0,
  126259. _vq_quantlist__8c0_s_p9_0,
  126260. NULL,
  126261. &_vq_auxt__8c0_s_p9_0,
  126262. NULL,
  126263. 0
  126264. };
  126265. static long _vq_quantlist__8c0_s_p9_1[] = {
  126266. 7,
  126267. 6,
  126268. 8,
  126269. 5,
  126270. 9,
  126271. 4,
  126272. 10,
  126273. 3,
  126274. 11,
  126275. 2,
  126276. 12,
  126277. 1,
  126278. 13,
  126279. 0,
  126280. 14,
  126281. };
  126282. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126283. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126284. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126285. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126286. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126287. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126288. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126291. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126292. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126297. 11,
  126298. };
  126299. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126300. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126301. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126302. };
  126303. static long _vq_quantmap__8c0_s_p9_1[] = {
  126304. 13, 11, 9, 7, 5, 3, 1, 0,
  126305. 2, 4, 6, 8, 10, 12, 14,
  126306. };
  126307. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126308. _vq_quantthresh__8c0_s_p9_1,
  126309. _vq_quantmap__8c0_s_p9_1,
  126310. 15,
  126311. 15
  126312. };
  126313. static static_codebook _8c0_s_p9_1 = {
  126314. 2, 225,
  126315. _vq_lengthlist__8c0_s_p9_1,
  126316. 1, -520986624, 1620377600, 4, 0,
  126317. _vq_quantlist__8c0_s_p9_1,
  126318. NULL,
  126319. &_vq_auxt__8c0_s_p9_1,
  126320. NULL,
  126321. 0
  126322. };
  126323. static long _vq_quantlist__8c0_s_p9_2[] = {
  126324. 10,
  126325. 9,
  126326. 11,
  126327. 8,
  126328. 12,
  126329. 7,
  126330. 13,
  126331. 6,
  126332. 14,
  126333. 5,
  126334. 15,
  126335. 4,
  126336. 16,
  126337. 3,
  126338. 17,
  126339. 2,
  126340. 18,
  126341. 1,
  126342. 19,
  126343. 0,
  126344. 20,
  126345. };
  126346. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126347. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126348. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126349. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126350. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126351. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126352. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126353. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126354. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126355. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126356. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126357. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126358. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126359. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126360. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126361. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126362. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126363. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126364. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126365. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126366. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126367. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126368. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126369. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126370. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126371. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126372. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126373. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126374. 10,11, 9,11,10, 9,10, 9,10,
  126375. };
  126376. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126377. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126378. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126379. 6.5, 7.5, 8.5, 9.5,
  126380. };
  126381. static long _vq_quantmap__8c0_s_p9_2[] = {
  126382. 19, 17, 15, 13, 11, 9, 7, 5,
  126383. 3, 1, 0, 2, 4, 6, 8, 10,
  126384. 12, 14, 16, 18, 20,
  126385. };
  126386. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126387. _vq_quantthresh__8c0_s_p9_2,
  126388. _vq_quantmap__8c0_s_p9_2,
  126389. 21,
  126390. 21
  126391. };
  126392. static static_codebook _8c0_s_p9_2 = {
  126393. 2, 441,
  126394. _vq_lengthlist__8c0_s_p9_2,
  126395. 1, -529268736, 1611661312, 5, 0,
  126396. _vq_quantlist__8c0_s_p9_2,
  126397. NULL,
  126398. &_vq_auxt__8c0_s_p9_2,
  126399. NULL,
  126400. 0
  126401. };
  126402. static long _huff_lengthlist__8c0_s_single[] = {
  126403. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126404. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126405. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126406. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126407. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126408. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126409. 17,16,17,17,
  126410. };
  126411. static static_codebook _huff_book__8c0_s_single = {
  126412. 2, 100,
  126413. _huff_lengthlist__8c0_s_single,
  126414. 0, 0, 0, 0, 0,
  126415. NULL,
  126416. NULL,
  126417. NULL,
  126418. NULL,
  126419. 0
  126420. };
  126421. static long _vq_quantlist__8c1_s_p1_0[] = {
  126422. 1,
  126423. 0,
  126424. 2,
  126425. };
  126426. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126427. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126428. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126433. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126438. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126473. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126478. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126483. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126519. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126523. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126524. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126529. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126837. 0,
  126838. };
  126839. static float _vq_quantthresh__8c1_s_p1_0[] = {
  126840. -0.5, 0.5,
  126841. };
  126842. static long _vq_quantmap__8c1_s_p1_0[] = {
  126843. 1, 0, 2,
  126844. };
  126845. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  126846. _vq_quantthresh__8c1_s_p1_0,
  126847. _vq_quantmap__8c1_s_p1_0,
  126848. 3,
  126849. 3
  126850. };
  126851. static static_codebook _8c1_s_p1_0 = {
  126852. 8, 6561,
  126853. _vq_lengthlist__8c1_s_p1_0,
  126854. 1, -535822336, 1611661312, 2, 0,
  126855. _vq_quantlist__8c1_s_p1_0,
  126856. NULL,
  126857. &_vq_auxt__8c1_s_p1_0,
  126858. NULL,
  126859. 0
  126860. };
  126861. static long _vq_quantlist__8c1_s_p2_0[] = {
  126862. 2,
  126863. 1,
  126864. 3,
  126865. 0,
  126866. 4,
  126867. };
  126868. static long _vq_lengthlist__8c1_s_p2_0[] = {
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126908. 0,
  126909. };
  126910. static float _vq_quantthresh__8c1_s_p2_0[] = {
  126911. -1.5, -0.5, 0.5, 1.5,
  126912. };
  126913. static long _vq_quantmap__8c1_s_p2_0[] = {
  126914. 3, 1, 0, 2, 4,
  126915. };
  126916. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  126917. _vq_quantthresh__8c1_s_p2_0,
  126918. _vq_quantmap__8c1_s_p2_0,
  126919. 5,
  126920. 5
  126921. };
  126922. static static_codebook _8c1_s_p2_0 = {
  126923. 4, 625,
  126924. _vq_lengthlist__8c1_s_p2_0,
  126925. 1, -533725184, 1611661312, 3, 0,
  126926. _vq_quantlist__8c1_s_p2_0,
  126927. NULL,
  126928. &_vq_auxt__8c1_s_p2_0,
  126929. NULL,
  126930. 0
  126931. };
  126932. static long _vq_quantlist__8c1_s_p3_0[] = {
  126933. 2,
  126934. 1,
  126935. 3,
  126936. 0,
  126937. 4,
  126938. };
  126939. static long _vq_lengthlist__8c1_s_p3_0[] = {
  126940. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  126942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126943. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  126945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126946. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126979. 0,
  126980. };
  126981. static float _vq_quantthresh__8c1_s_p3_0[] = {
  126982. -1.5, -0.5, 0.5, 1.5,
  126983. };
  126984. static long _vq_quantmap__8c1_s_p3_0[] = {
  126985. 3, 1, 0, 2, 4,
  126986. };
  126987. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  126988. _vq_quantthresh__8c1_s_p3_0,
  126989. _vq_quantmap__8c1_s_p3_0,
  126990. 5,
  126991. 5
  126992. };
  126993. static static_codebook _8c1_s_p3_0 = {
  126994. 4, 625,
  126995. _vq_lengthlist__8c1_s_p3_0,
  126996. 1, -533725184, 1611661312, 3, 0,
  126997. _vq_quantlist__8c1_s_p3_0,
  126998. NULL,
  126999. &_vq_auxt__8c1_s_p3_0,
  127000. NULL,
  127001. 0
  127002. };
  127003. static long _vq_quantlist__8c1_s_p4_0[] = {
  127004. 4,
  127005. 3,
  127006. 5,
  127007. 2,
  127008. 6,
  127009. 1,
  127010. 7,
  127011. 0,
  127012. 8,
  127013. };
  127014. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127015. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127016. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127017. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127018. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127019. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0,
  127021. };
  127022. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127023. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127024. };
  127025. static long _vq_quantmap__8c1_s_p4_0[] = {
  127026. 7, 5, 3, 1, 0, 2, 4, 6,
  127027. 8,
  127028. };
  127029. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127030. _vq_quantthresh__8c1_s_p4_0,
  127031. _vq_quantmap__8c1_s_p4_0,
  127032. 9,
  127033. 9
  127034. };
  127035. static static_codebook _8c1_s_p4_0 = {
  127036. 2, 81,
  127037. _vq_lengthlist__8c1_s_p4_0,
  127038. 1, -531628032, 1611661312, 4, 0,
  127039. _vq_quantlist__8c1_s_p4_0,
  127040. NULL,
  127041. &_vq_auxt__8c1_s_p4_0,
  127042. NULL,
  127043. 0
  127044. };
  127045. static long _vq_quantlist__8c1_s_p5_0[] = {
  127046. 4,
  127047. 3,
  127048. 5,
  127049. 2,
  127050. 6,
  127051. 1,
  127052. 7,
  127053. 0,
  127054. 8,
  127055. };
  127056. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127057. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127058. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127059. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127060. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127061. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127062. 10,
  127063. };
  127064. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127065. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127066. };
  127067. static long _vq_quantmap__8c1_s_p5_0[] = {
  127068. 7, 5, 3, 1, 0, 2, 4, 6,
  127069. 8,
  127070. };
  127071. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127072. _vq_quantthresh__8c1_s_p5_0,
  127073. _vq_quantmap__8c1_s_p5_0,
  127074. 9,
  127075. 9
  127076. };
  127077. static static_codebook _8c1_s_p5_0 = {
  127078. 2, 81,
  127079. _vq_lengthlist__8c1_s_p5_0,
  127080. 1, -531628032, 1611661312, 4, 0,
  127081. _vq_quantlist__8c1_s_p5_0,
  127082. NULL,
  127083. &_vq_auxt__8c1_s_p5_0,
  127084. NULL,
  127085. 0
  127086. };
  127087. static long _vq_quantlist__8c1_s_p6_0[] = {
  127088. 8,
  127089. 7,
  127090. 9,
  127091. 6,
  127092. 10,
  127093. 5,
  127094. 11,
  127095. 4,
  127096. 12,
  127097. 3,
  127098. 13,
  127099. 2,
  127100. 14,
  127101. 1,
  127102. 15,
  127103. 0,
  127104. 16,
  127105. };
  127106. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127107. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127108. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127109. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127110. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127111. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127112. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127113. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127114. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127115. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127116. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127117. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127118. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127119. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127120. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127121. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127122. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127123. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127124. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127125. 14,
  127126. };
  127127. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127128. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127129. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127130. };
  127131. static long _vq_quantmap__8c1_s_p6_0[] = {
  127132. 15, 13, 11, 9, 7, 5, 3, 1,
  127133. 0, 2, 4, 6, 8, 10, 12, 14,
  127134. 16,
  127135. };
  127136. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127137. _vq_quantthresh__8c1_s_p6_0,
  127138. _vq_quantmap__8c1_s_p6_0,
  127139. 17,
  127140. 17
  127141. };
  127142. static static_codebook _8c1_s_p6_0 = {
  127143. 2, 289,
  127144. _vq_lengthlist__8c1_s_p6_0,
  127145. 1, -529530880, 1611661312, 5, 0,
  127146. _vq_quantlist__8c1_s_p6_0,
  127147. NULL,
  127148. &_vq_auxt__8c1_s_p6_0,
  127149. NULL,
  127150. 0
  127151. };
  127152. static long _vq_quantlist__8c1_s_p7_0[] = {
  127153. 1,
  127154. 0,
  127155. 2,
  127156. };
  127157. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127158. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127159. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127160. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127161. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127162. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127163. 9,
  127164. };
  127165. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127166. -5.5, 5.5,
  127167. };
  127168. static long _vq_quantmap__8c1_s_p7_0[] = {
  127169. 1, 0, 2,
  127170. };
  127171. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127172. _vq_quantthresh__8c1_s_p7_0,
  127173. _vq_quantmap__8c1_s_p7_0,
  127174. 3,
  127175. 3
  127176. };
  127177. static static_codebook _8c1_s_p7_0 = {
  127178. 4, 81,
  127179. _vq_lengthlist__8c1_s_p7_0,
  127180. 1, -529137664, 1618345984, 2, 0,
  127181. _vq_quantlist__8c1_s_p7_0,
  127182. NULL,
  127183. &_vq_auxt__8c1_s_p7_0,
  127184. NULL,
  127185. 0
  127186. };
  127187. static long _vq_quantlist__8c1_s_p7_1[] = {
  127188. 5,
  127189. 4,
  127190. 6,
  127191. 3,
  127192. 7,
  127193. 2,
  127194. 8,
  127195. 1,
  127196. 9,
  127197. 0,
  127198. 10,
  127199. };
  127200. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127201. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127202. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127203. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127204. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127205. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127206. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127207. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127208. 10,10,10, 8, 8, 8, 8, 8, 8,
  127209. };
  127210. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127211. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127212. 3.5, 4.5,
  127213. };
  127214. static long _vq_quantmap__8c1_s_p7_1[] = {
  127215. 9, 7, 5, 3, 1, 0, 2, 4,
  127216. 6, 8, 10,
  127217. };
  127218. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127219. _vq_quantthresh__8c1_s_p7_1,
  127220. _vq_quantmap__8c1_s_p7_1,
  127221. 11,
  127222. 11
  127223. };
  127224. static static_codebook _8c1_s_p7_1 = {
  127225. 2, 121,
  127226. _vq_lengthlist__8c1_s_p7_1,
  127227. 1, -531365888, 1611661312, 4, 0,
  127228. _vq_quantlist__8c1_s_p7_1,
  127229. NULL,
  127230. &_vq_auxt__8c1_s_p7_1,
  127231. NULL,
  127232. 0
  127233. };
  127234. static long _vq_quantlist__8c1_s_p8_0[] = {
  127235. 6,
  127236. 5,
  127237. 7,
  127238. 4,
  127239. 8,
  127240. 3,
  127241. 9,
  127242. 2,
  127243. 10,
  127244. 1,
  127245. 11,
  127246. 0,
  127247. 12,
  127248. };
  127249. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127250. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127251. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127252. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127253. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127254. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127255. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127256. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127257. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127258. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127259. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127260. 0,12,12,11,10,12,11,13,12,
  127261. };
  127262. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127263. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127264. 12.5, 17.5, 22.5, 27.5,
  127265. };
  127266. static long _vq_quantmap__8c1_s_p8_0[] = {
  127267. 11, 9, 7, 5, 3, 1, 0, 2,
  127268. 4, 6, 8, 10, 12,
  127269. };
  127270. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127271. _vq_quantthresh__8c1_s_p8_0,
  127272. _vq_quantmap__8c1_s_p8_0,
  127273. 13,
  127274. 13
  127275. };
  127276. static static_codebook _8c1_s_p8_0 = {
  127277. 2, 169,
  127278. _vq_lengthlist__8c1_s_p8_0,
  127279. 1, -526516224, 1616117760, 4, 0,
  127280. _vq_quantlist__8c1_s_p8_0,
  127281. NULL,
  127282. &_vq_auxt__8c1_s_p8_0,
  127283. NULL,
  127284. 0
  127285. };
  127286. static long _vq_quantlist__8c1_s_p8_1[] = {
  127287. 2,
  127288. 1,
  127289. 3,
  127290. 0,
  127291. 4,
  127292. };
  127293. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127294. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127295. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127296. };
  127297. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127298. -1.5, -0.5, 0.5, 1.5,
  127299. };
  127300. static long _vq_quantmap__8c1_s_p8_1[] = {
  127301. 3, 1, 0, 2, 4,
  127302. };
  127303. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127304. _vq_quantthresh__8c1_s_p8_1,
  127305. _vq_quantmap__8c1_s_p8_1,
  127306. 5,
  127307. 5
  127308. };
  127309. static static_codebook _8c1_s_p8_1 = {
  127310. 2, 25,
  127311. _vq_lengthlist__8c1_s_p8_1,
  127312. 1, -533725184, 1611661312, 3, 0,
  127313. _vq_quantlist__8c1_s_p8_1,
  127314. NULL,
  127315. &_vq_auxt__8c1_s_p8_1,
  127316. NULL,
  127317. 0
  127318. };
  127319. static long _vq_quantlist__8c1_s_p9_0[] = {
  127320. 6,
  127321. 5,
  127322. 7,
  127323. 4,
  127324. 8,
  127325. 3,
  127326. 9,
  127327. 2,
  127328. 10,
  127329. 1,
  127330. 11,
  127331. 0,
  127332. 12,
  127333. };
  127334. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127335. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127336. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127337. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127339. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127340. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127341. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127343. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127344. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127345. 10,10,10,10,10, 9, 9, 9, 9,
  127346. };
  127347. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127348. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127349. 787.5, 1102.5, 1417.5, 1732.5,
  127350. };
  127351. static long _vq_quantmap__8c1_s_p9_0[] = {
  127352. 11, 9, 7, 5, 3, 1, 0, 2,
  127353. 4, 6, 8, 10, 12,
  127354. };
  127355. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127356. _vq_quantthresh__8c1_s_p9_0,
  127357. _vq_quantmap__8c1_s_p9_0,
  127358. 13,
  127359. 13
  127360. };
  127361. static static_codebook _8c1_s_p9_0 = {
  127362. 2, 169,
  127363. _vq_lengthlist__8c1_s_p9_0,
  127364. 1, -513964032, 1628680192, 4, 0,
  127365. _vq_quantlist__8c1_s_p9_0,
  127366. NULL,
  127367. &_vq_auxt__8c1_s_p9_0,
  127368. NULL,
  127369. 0
  127370. };
  127371. static long _vq_quantlist__8c1_s_p9_1[] = {
  127372. 7,
  127373. 6,
  127374. 8,
  127375. 5,
  127376. 9,
  127377. 4,
  127378. 10,
  127379. 3,
  127380. 11,
  127381. 2,
  127382. 12,
  127383. 1,
  127384. 13,
  127385. 0,
  127386. 14,
  127387. };
  127388. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127389. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127390. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127391. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127392. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127393. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127394. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127395. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127396. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127397. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127398. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127399. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127400. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127401. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127402. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127403. 15,
  127404. };
  127405. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127406. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127407. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127408. };
  127409. static long _vq_quantmap__8c1_s_p9_1[] = {
  127410. 13, 11, 9, 7, 5, 3, 1, 0,
  127411. 2, 4, 6, 8, 10, 12, 14,
  127412. };
  127413. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127414. _vq_quantthresh__8c1_s_p9_1,
  127415. _vq_quantmap__8c1_s_p9_1,
  127416. 15,
  127417. 15
  127418. };
  127419. static static_codebook _8c1_s_p9_1 = {
  127420. 2, 225,
  127421. _vq_lengthlist__8c1_s_p9_1,
  127422. 1, -520986624, 1620377600, 4, 0,
  127423. _vq_quantlist__8c1_s_p9_1,
  127424. NULL,
  127425. &_vq_auxt__8c1_s_p9_1,
  127426. NULL,
  127427. 0
  127428. };
  127429. static long _vq_quantlist__8c1_s_p9_2[] = {
  127430. 10,
  127431. 9,
  127432. 11,
  127433. 8,
  127434. 12,
  127435. 7,
  127436. 13,
  127437. 6,
  127438. 14,
  127439. 5,
  127440. 15,
  127441. 4,
  127442. 16,
  127443. 3,
  127444. 17,
  127445. 2,
  127446. 18,
  127447. 1,
  127448. 19,
  127449. 0,
  127450. 20,
  127451. };
  127452. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127453. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127454. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127455. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127456. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127457. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127458. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127459. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127460. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127461. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127462. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127463. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127464. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127465. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127466. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127467. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127468. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127469. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127470. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127471. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127472. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127473. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127474. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127475. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127476. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127477. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127478. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127479. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127480. 10,10,10,10,10,10,10,10,10,
  127481. };
  127482. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127483. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127484. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127485. 6.5, 7.5, 8.5, 9.5,
  127486. };
  127487. static long _vq_quantmap__8c1_s_p9_2[] = {
  127488. 19, 17, 15, 13, 11, 9, 7, 5,
  127489. 3, 1, 0, 2, 4, 6, 8, 10,
  127490. 12, 14, 16, 18, 20,
  127491. };
  127492. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127493. _vq_quantthresh__8c1_s_p9_2,
  127494. _vq_quantmap__8c1_s_p9_2,
  127495. 21,
  127496. 21
  127497. };
  127498. static static_codebook _8c1_s_p9_2 = {
  127499. 2, 441,
  127500. _vq_lengthlist__8c1_s_p9_2,
  127501. 1, -529268736, 1611661312, 5, 0,
  127502. _vq_quantlist__8c1_s_p9_2,
  127503. NULL,
  127504. &_vq_auxt__8c1_s_p9_2,
  127505. NULL,
  127506. 0
  127507. };
  127508. static long _huff_lengthlist__8c1_s_single[] = {
  127509. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127510. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127511. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127512. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127513. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127514. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127515. 9, 7, 7, 8,
  127516. };
  127517. static static_codebook _huff_book__8c1_s_single = {
  127518. 2, 100,
  127519. _huff_lengthlist__8c1_s_single,
  127520. 0, 0, 0, 0, 0,
  127521. NULL,
  127522. NULL,
  127523. NULL,
  127524. NULL,
  127525. 0
  127526. };
  127527. static long _huff_lengthlist__44c2_s_long[] = {
  127528. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127529. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127530. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127531. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127532. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127533. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127534. 10, 8, 8, 9,
  127535. };
  127536. static static_codebook _huff_book__44c2_s_long = {
  127537. 2, 100,
  127538. _huff_lengthlist__44c2_s_long,
  127539. 0, 0, 0, 0, 0,
  127540. NULL,
  127541. NULL,
  127542. NULL,
  127543. NULL,
  127544. 0
  127545. };
  127546. static long _vq_quantlist__44c2_s_p1_0[] = {
  127547. 1,
  127548. 0,
  127549. 2,
  127550. };
  127551. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127552. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127553. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127558. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127563. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127598. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127603. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  127608. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127644. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127649. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127654. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0,
  127963. };
  127964. static float _vq_quantthresh__44c2_s_p1_0[] = {
  127965. -0.5, 0.5,
  127966. };
  127967. static long _vq_quantmap__44c2_s_p1_0[] = {
  127968. 1, 0, 2,
  127969. };
  127970. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  127971. _vq_quantthresh__44c2_s_p1_0,
  127972. _vq_quantmap__44c2_s_p1_0,
  127973. 3,
  127974. 3
  127975. };
  127976. static static_codebook _44c2_s_p1_0 = {
  127977. 8, 6561,
  127978. _vq_lengthlist__44c2_s_p1_0,
  127979. 1, -535822336, 1611661312, 2, 0,
  127980. _vq_quantlist__44c2_s_p1_0,
  127981. NULL,
  127982. &_vq_auxt__44c2_s_p1_0,
  127983. NULL,
  127984. 0
  127985. };
  127986. static long _vq_quantlist__44c2_s_p2_0[] = {
  127987. 2,
  127988. 1,
  127989. 3,
  127990. 0,
  127991. 4,
  127992. };
  127993. static long _vq_lengthlist__44c2_s_p2_0[] = {
  127994. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  127995. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127996. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  127997. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  127998. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128004. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128005. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128006. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128012. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128013. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128019. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128020. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128021. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128033. 0,
  128034. };
  128035. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128036. -1.5, -0.5, 0.5, 1.5,
  128037. };
  128038. static long _vq_quantmap__44c2_s_p2_0[] = {
  128039. 3, 1, 0, 2, 4,
  128040. };
  128041. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128042. _vq_quantthresh__44c2_s_p2_0,
  128043. _vq_quantmap__44c2_s_p2_0,
  128044. 5,
  128045. 5
  128046. };
  128047. static static_codebook _44c2_s_p2_0 = {
  128048. 4, 625,
  128049. _vq_lengthlist__44c2_s_p2_0,
  128050. 1, -533725184, 1611661312, 3, 0,
  128051. _vq_quantlist__44c2_s_p2_0,
  128052. NULL,
  128053. &_vq_auxt__44c2_s_p2_0,
  128054. NULL,
  128055. 0
  128056. };
  128057. static long _vq_quantlist__44c2_s_p3_0[] = {
  128058. 2,
  128059. 1,
  128060. 3,
  128061. 0,
  128062. 4,
  128063. };
  128064. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128065. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128068. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128071. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128104. 0,
  128105. };
  128106. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128107. -1.5, -0.5, 0.5, 1.5,
  128108. };
  128109. static long _vq_quantmap__44c2_s_p3_0[] = {
  128110. 3, 1, 0, 2, 4,
  128111. };
  128112. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128113. _vq_quantthresh__44c2_s_p3_0,
  128114. _vq_quantmap__44c2_s_p3_0,
  128115. 5,
  128116. 5
  128117. };
  128118. static static_codebook _44c2_s_p3_0 = {
  128119. 4, 625,
  128120. _vq_lengthlist__44c2_s_p3_0,
  128121. 1, -533725184, 1611661312, 3, 0,
  128122. _vq_quantlist__44c2_s_p3_0,
  128123. NULL,
  128124. &_vq_auxt__44c2_s_p3_0,
  128125. NULL,
  128126. 0
  128127. };
  128128. static long _vq_quantlist__44c2_s_p4_0[] = {
  128129. 4,
  128130. 3,
  128131. 5,
  128132. 2,
  128133. 6,
  128134. 1,
  128135. 7,
  128136. 0,
  128137. 8,
  128138. };
  128139. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128140. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128141. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128142. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128143. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128144. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0,
  128146. };
  128147. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128148. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128149. };
  128150. static long _vq_quantmap__44c2_s_p4_0[] = {
  128151. 7, 5, 3, 1, 0, 2, 4, 6,
  128152. 8,
  128153. };
  128154. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128155. _vq_quantthresh__44c2_s_p4_0,
  128156. _vq_quantmap__44c2_s_p4_0,
  128157. 9,
  128158. 9
  128159. };
  128160. static static_codebook _44c2_s_p4_0 = {
  128161. 2, 81,
  128162. _vq_lengthlist__44c2_s_p4_0,
  128163. 1, -531628032, 1611661312, 4, 0,
  128164. _vq_quantlist__44c2_s_p4_0,
  128165. NULL,
  128166. &_vq_auxt__44c2_s_p4_0,
  128167. NULL,
  128168. 0
  128169. };
  128170. static long _vq_quantlist__44c2_s_p5_0[] = {
  128171. 4,
  128172. 3,
  128173. 5,
  128174. 2,
  128175. 6,
  128176. 1,
  128177. 7,
  128178. 0,
  128179. 8,
  128180. };
  128181. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128182. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128183. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128184. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128185. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128186. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128187. 11,
  128188. };
  128189. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128190. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128191. };
  128192. static long _vq_quantmap__44c2_s_p5_0[] = {
  128193. 7, 5, 3, 1, 0, 2, 4, 6,
  128194. 8,
  128195. };
  128196. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128197. _vq_quantthresh__44c2_s_p5_0,
  128198. _vq_quantmap__44c2_s_p5_0,
  128199. 9,
  128200. 9
  128201. };
  128202. static static_codebook _44c2_s_p5_0 = {
  128203. 2, 81,
  128204. _vq_lengthlist__44c2_s_p5_0,
  128205. 1, -531628032, 1611661312, 4, 0,
  128206. _vq_quantlist__44c2_s_p5_0,
  128207. NULL,
  128208. &_vq_auxt__44c2_s_p5_0,
  128209. NULL,
  128210. 0
  128211. };
  128212. static long _vq_quantlist__44c2_s_p6_0[] = {
  128213. 8,
  128214. 7,
  128215. 9,
  128216. 6,
  128217. 10,
  128218. 5,
  128219. 11,
  128220. 4,
  128221. 12,
  128222. 3,
  128223. 13,
  128224. 2,
  128225. 14,
  128226. 1,
  128227. 15,
  128228. 0,
  128229. 16,
  128230. };
  128231. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128232. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128233. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128234. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128235. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128236. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128237. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128238. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128239. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128240. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128241. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128242. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128243. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128244. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128245. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128246. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128247. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128248. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128249. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128250. 14,
  128251. };
  128252. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128253. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128254. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128255. };
  128256. static long _vq_quantmap__44c2_s_p6_0[] = {
  128257. 15, 13, 11, 9, 7, 5, 3, 1,
  128258. 0, 2, 4, 6, 8, 10, 12, 14,
  128259. 16,
  128260. };
  128261. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128262. _vq_quantthresh__44c2_s_p6_0,
  128263. _vq_quantmap__44c2_s_p6_0,
  128264. 17,
  128265. 17
  128266. };
  128267. static static_codebook _44c2_s_p6_0 = {
  128268. 2, 289,
  128269. _vq_lengthlist__44c2_s_p6_0,
  128270. 1, -529530880, 1611661312, 5, 0,
  128271. _vq_quantlist__44c2_s_p6_0,
  128272. NULL,
  128273. &_vq_auxt__44c2_s_p6_0,
  128274. NULL,
  128275. 0
  128276. };
  128277. static long _vq_quantlist__44c2_s_p7_0[] = {
  128278. 1,
  128279. 0,
  128280. 2,
  128281. };
  128282. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128283. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128284. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128285. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128286. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128287. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128288. 11,
  128289. };
  128290. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128291. -5.5, 5.5,
  128292. };
  128293. static long _vq_quantmap__44c2_s_p7_0[] = {
  128294. 1, 0, 2,
  128295. };
  128296. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128297. _vq_quantthresh__44c2_s_p7_0,
  128298. _vq_quantmap__44c2_s_p7_0,
  128299. 3,
  128300. 3
  128301. };
  128302. static static_codebook _44c2_s_p7_0 = {
  128303. 4, 81,
  128304. _vq_lengthlist__44c2_s_p7_0,
  128305. 1, -529137664, 1618345984, 2, 0,
  128306. _vq_quantlist__44c2_s_p7_0,
  128307. NULL,
  128308. &_vq_auxt__44c2_s_p7_0,
  128309. NULL,
  128310. 0
  128311. };
  128312. static long _vq_quantlist__44c2_s_p7_1[] = {
  128313. 5,
  128314. 4,
  128315. 6,
  128316. 3,
  128317. 7,
  128318. 2,
  128319. 8,
  128320. 1,
  128321. 9,
  128322. 0,
  128323. 10,
  128324. };
  128325. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128326. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128327. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128328. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128329. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128330. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128331. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128332. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128333. 10,10,10, 8, 8, 8, 8, 8, 8,
  128334. };
  128335. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128336. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128337. 3.5, 4.5,
  128338. };
  128339. static long _vq_quantmap__44c2_s_p7_1[] = {
  128340. 9, 7, 5, 3, 1, 0, 2, 4,
  128341. 6, 8, 10,
  128342. };
  128343. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128344. _vq_quantthresh__44c2_s_p7_1,
  128345. _vq_quantmap__44c2_s_p7_1,
  128346. 11,
  128347. 11
  128348. };
  128349. static static_codebook _44c2_s_p7_1 = {
  128350. 2, 121,
  128351. _vq_lengthlist__44c2_s_p7_1,
  128352. 1, -531365888, 1611661312, 4, 0,
  128353. _vq_quantlist__44c2_s_p7_1,
  128354. NULL,
  128355. &_vq_auxt__44c2_s_p7_1,
  128356. NULL,
  128357. 0
  128358. };
  128359. static long _vq_quantlist__44c2_s_p8_0[] = {
  128360. 6,
  128361. 5,
  128362. 7,
  128363. 4,
  128364. 8,
  128365. 3,
  128366. 9,
  128367. 2,
  128368. 10,
  128369. 1,
  128370. 11,
  128371. 0,
  128372. 12,
  128373. };
  128374. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128375. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128376. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128377. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128378. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128379. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128380. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128381. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128382. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128383. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128384. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128385. 0,12,12,12,12,13,12,14,14,
  128386. };
  128387. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128388. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128389. 12.5, 17.5, 22.5, 27.5,
  128390. };
  128391. static long _vq_quantmap__44c2_s_p8_0[] = {
  128392. 11, 9, 7, 5, 3, 1, 0, 2,
  128393. 4, 6, 8, 10, 12,
  128394. };
  128395. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128396. _vq_quantthresh__44c2_s_p8_0,
  128397. _vq_quantmap__44c2_s_p8_0,
  128398. 13,
  128399. 13
  128400. };
  128401. static static_codebook _44c2_s_p8_0 = {
  128402. 2, 169,
  128403. _vq_lengthlist__44c2_s_p8_0,
  128404. 1, -526516224, 1616117760, 4, 0,
  128405. _vq_quantlist__44c2_s_p8_0,
  128406. NULL,
  128407. &_vq_auxt__44c2_s_p8_0,
  128408. NULL,
  128409. 0
  128410. };
  128411. static long _vq_quantlist__44c2_s_p8_1[] = {
  128412. 2,
  128413. 1,
  128414. 3,
  128415. 0,
  128416. 4,
  128417. };
  128418. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128419. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128420. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128421. };
  128422. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128423. -1.5, -0.5, 0.5, 1.5,
  128424. };
  128425. static long _vq_quantmap__44c2_s_p8_1[] = {
  128426. 3, 1, 0, 2, 4,
  128427. };
  128428. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128429. _vq_quantthresh__44c2_s_p8_1,
  128430. _vq_quantmap__44c2_s_p8_1,
  128431. 5,
  128432. 5
  128433. };
  128434. static static_codebook _44c2_s_p8_1 = {
  128435. 2, 25,
  128436. _vq_lengthlist__44c2_s_p8_1,
  128437. 1, -533725184, 1611661312, 3, 0,
  128438. _vq_quantlist__44c2_s_p8_1,
  128439. NULL,
  128440. &_vq_auxt__44c2_s_p8_1,
  128441. NULL,
  128442. 0
  128443. };
  128444. static long _vq_quantlist__44c2_s_p9_0[] = {
  128445. 6,
  128446. 5,
  128447. 7,
  128448. 4,
  128449. 8,
  128450. 3,
  128451. 9,
  128452. 2,
  128453. 10,
  128454. 1,
  128455. 11,
  128456. 0,
  128457. 12,
  128458. };
  128459. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128460. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128461. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128462. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128463. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128464. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128470. 11,11,11,11,11,11,11,11,11,
  128471. };
  128472. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128473. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128474. 552.5, 773.5, 994.5, 1215.5,
  128475. };
  128476. static long _vq_quantmap__44c2_s_p9_0[] = {
  128477. 11, 9, 7, 5, 3, 1, 0, 2,
  128478. 4, 6, 8, 10, 12,
  128479. };
  128480. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128481. _vq_quantthresh__44c2_s_p9_0,
  128482. _vq_quantmap__44c2_s_p9_0,
  128483. 13,
  128484. 13
  128485. };
  128486. static static_codebook _44c2_s_p9_0 = {
  128487. 2, 169,
  128488. _vq_lengthlist__44c2_s_p9_0,
  128489. 1, -514541568, 1627103232, 4, 0,
  128490. _vq_quantlist__44c2_s_p9_0,
  128491. NULL,
  128492. &_vq_auxt__44c2_s_p9_0,
  128493. NULL,
  128494. 0
  128495. };
  128496. static long _vq_quantlist__44c2_s_p9_1[] = {
  128497. 6,
  128498. 5,
  128499. 7,
  128500. 4,
  128501. 8,
  128502. 3,
  128503. 9,
  128504. 2,
  128505. 10,
  128506. 1,
  128507. 11,
  128508. 0,
  128509. 12,
  128510. };
  128511. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128512. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128513. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128514. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128515. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128516. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128517. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128518. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128519. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128520. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128521. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128522. 17,13,12,12,10,13,11,14,14,
  128523. };
  128524. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128525. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128526. 42.5, 59.5, 76.5, 93.5,
  128527. };
  128528. static long _vq_quantmap__44c2_s_p9_1[] = {
  128529. 11, 9, 7, 5, 3, 1, 0, 2,
  128530. 4, 6, 8, 10, 12,
  128531. };
  128532. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128533. _vq_quantthresh__44c2_s_p9_1,
  128534. _vq_quantmap__44c2_s_p9_1,
  128535. 13,
  128536. 13
  128537. };
  128538. static static_codebook _44c2_s_p9_1 = {
  128539. 2, 169,
  128540. _vq_lengthlist__44c2_s_p9_1,
  128541. 1, -522616832, 1620115456, 4, 0,
  128542. _vq_quantlist__44c2_s_p9_1,
  128543. NULL,
  128544. &_vq_auxt__44c2_s_p9_1,
  128545. NULL,
  128546. 0
  128547. };
  128548. static long _vq_quantlist__44c2_s_p9_2[] = {
  128549. 8,
  128550. 7,
  128551. 9,
  128552. 6,
  128553. 10,
  128554. 5,
  128555. 11,
  128556. 4,
  128557. 12,
  128558. 3,
  128559. 13,
  128560. 2,
  128561. 14,
  128562. 1,
  128563. 15,
  128564. 0,
  128565. 16,
  128566. };
  128567. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128568. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128569. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128570. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128571. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128572. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128573. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128574. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128575. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128576. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128577. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128578. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128579. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128580. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128581. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128582. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128583. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128584. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128585. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128586. 10,
  128587. };
  128588. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128589. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128590. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128591. };
  128592. static long _vq_quantmap__44c2_s_p9_2[] = {
  128593. 15, 13, 11, 9, 7, 5, 3, 1,
  128594. 0, 2, 4, 6, 8, 10, 12, 14,
  128595. 16,
  128596. };
  128597. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128598. _vq_quantthresh__44c2_s_p9_2,
  128599. _vq_quantmap__44c2_s_p9_2,
  128600. 17,
  128601. 17
  128602. };
  128603. static static_codebook _44c2_s_p9_2 = {
  128604. 2, 289,
  128605. _vq_lengthlist__44c2_s_p9_2,
  128606. 1, -529530880, 1611661312, 5, 0,
  128607. _vq_quantlist__44c2_s_p9_2,
  128608. NULL,
  128609. &_vq_auxt__44c2_s_p9_2,
  128610. NULL,
  128611. 0
  128612. };
  128613. static long _huff_lengthlist__44c2_s_short[] = {
  128614. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128615. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128616. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128617. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128618. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128619. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128620. 6, 8, 9,12,
  128621. };
  128622. static static_codebook _huff_book__44c2_s_short = {
  128623. 2, 100,
  128624. _huff_lengthlist__44c2_s_short,
  128625. 0, 0, 0, 0, 0,
  128626. NULL,
  128627. NULL,
  128628. NULL,
  128629. NULL,
  128630. 0
  128631. };
  128632. static long _huff_lengthlist__44c3_s_long[] = {
  128633. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128634. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128635. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128636. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128637. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128638. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128639. 9, 8, 8, 8,
  128640. };
  128641. static static_codebook _huff_book__44c3_s_long = {
  128642. 2, 100,
  128643. _huff_lengthlist__44c3_s_long,
  128644. 0, 0, 0, 0, 0,
  128645. NULL,
  128646. NULL,
  128647. NULL,
  128648. NULL,
  128649. 0
  128650. };
  128651. static long _vq_quantlist__44c3_s_p1_0[] = {
  128652. 1,
  128653. 0,
  128654. 2,
  128655. };
  128656. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128657. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128658. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128663. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128668. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128703. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128708. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128713. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128749. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128754. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128759. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129067. 0,
  129068. };
  129069. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129070. -0.5, 0.5,
  129071. };
  129072. static long _vq_quantmap__44c3_s_p1_0[] = {
  129073. 1, 0, 2,
  129074. };
  129075. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129076. _vq_quantthresh__44c3_s_p1_0,
  129077. _vq_quantmap__44c3_s_p1_0,
  129078. 3,
  129079. 3
  129080. };
  129081. static static_codebook _44c3_s_p1_0 = {
  129082. 8, 6561,
  129083. _vq_lengthlist__44c3_s_p1_0,
  129084. 1, -535822336, 1611661312, 2, 0,
  129085. _vq_quantlist__44c3_s_p1_0,
  129086. NULL,
  129087. &_vq_auxt__44c3_s_p1_0,
  129088. NULL,
  129089. 0
  129090. };
  129091. static long _vq_quantlist__44c3_s_p2_0[] = {
  129092. 2,
  129093. 1,
  129094. 3,
  129095. 0,
  129096. 4,
  129097. };
  129098. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129099. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129100. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129101. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129102. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129103. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129109. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129110. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129111. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129117. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129118. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129124. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129125. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129126. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129138. 0,
  129139. };
  129140. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129141. -1.5, -0.5, 0.5, 1.5,
  129142. };
  129143. static long _vq_quantmap__44c3_s_p2_0[] = {
  129144. 3, 1, 0, 2, 4,
  129145. };
  129146. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129147. _vq_quantthresh__44c3_s_p2_0,
  129148. _vq_quantmap__44c3_s_p2_0,
  129149. 5,
  129150. 5
  129151. };
  129152. static static_codebook _44c3_s_p2_0 = {
  129153. 4, 625,
  129154. _vq_lengthlist__44c3_s_p2_0,
  129155. 1, -533725184, 1611661312, 3, 0,
  129156. _vq_quantlist__44c3_s_p2_0,
  129157. NULL,
  129158. &_vq_auxt__44c3_s_p2_0,
  129159. NULL,
  129160. 0
  129161. };
  129162. static long _vq_quantlist__44c3_s_p3_0[] = {
  129163. 2,
  129164. 1,
  129165. 3,
  129166. 0,
  129167. 4,
  129168. };
  129169. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129170. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129173. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129176. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129209. 0,
  129210. };
  129211. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129212. -1.5, -0.5, 0.5, 1.5,
  129213. };
  129214. static long _vq_quantmap__44c3_s_p3_0[] = {
  129215. 3, 1, 0, 2, 4,
  129216. };
  129217. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129218. _vq_quantthresh__44c3_s_p3_0,
  129219. _vq_quantmap__44c3_s_p3_0,
  129220. 5,
  129221. 5
  129222. };
  129223. static static_codebook _44c3_s_p3_0 = {
  129224. 4, 625,
  129225. _vq_lengthlist__44c3_s_p3_0,
  129226. 1, -533725184, 1611661312, 3, 0,
  129227. _vq_quantlist__44c3_s_p3_0,
  129228. NULL,
  129229. &_vq_auxt__44c3_s_p3_0,
  129230. NULL,
  129231. 0
  129232. };
  129233. static long _vq_quantlist__44c3_s_p4_0[] = {
  129234. 4,
  129235. 3,
  129236. 5,
  129237. 2,
  129238. 6,
  129239. 1,
  129240. 7,
  129241. 0,
  129242. 8,
  129243. };
  129244. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129245. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129246. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129247. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129248. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129249. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0,
  129251. };
  129252. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129253. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129254. };
  129255. static long _vq_quantmap__44c3_s_p4_0[] = {
  129256. 7, 5, 3, 1, 0, 2, 4, 6,
  129257. 8,
  129258. };
  129259. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129260. _vq_quantthresh__44c3_s_p4_0,
  129261. _vq_quantmap__44c3_s_p4_0,
  129262. 9,
  129263. 9
  129264. };
  129265. static static_codebook _44c3_s_p4_0 = {
  129266. 2, 81,
  129267. _vq_lengthlist__44c3_s_p4_0,
  129268. 1, -531628032, 1611661312, 4, 0,
  129269. _vq_quantlist__44c3_s_p4_0,
  129270. NULL,
  129271. &_vq_auxt__44c3_s_p4_0,
  129272. NULL,
  129273. 0
  129274. };
  129275. static long _vq_quantlist__44c3_s_p5_0[] = {
  129276. 4,
  129277. 3,
  129278. 5,
  129279. 2,
  129280. 6,
  129281. 1,
  129282. 7,
  129283. 0,
  129284. 8,
  129285. };
  129286. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129287. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129288. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129289. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129290. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129291. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129292. 11,
  129293. };
  129294. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129295. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129296. };
  129297. static long _vq_quantmap__44c3_s_p5_0[] = {
  129298. 7, 5, 3, 1, 0, 2, 4, 6,
  129299. 8,
  129300. };
  129301. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129302. _vq_quantthresh__44c3_s_p5_0,
  129303. _vq_quantmap__44c3_s_p5_0,
  129304. 9,
  129305. 9
  129306. };
  129307. static static_codebook _44c3_s_p5_0 = {
  129308. 2, 81,
  129309. _vq_lengthlist__44c3_s_p5_0,
  129310. 1, -531628032, 1611661312, 4, 0,
  129311. _vq_quantlist__44c3_s_p5_0,
  129312. NULL,
  129313. &_vq_auxt__44c3_s_p5_0,
  129314. NULL,
  129315. 0
  129316. };
  129317. static long _vq_quantlist__44c3_s_p6_0[] = {
  129318. 8,
  129319. 7,
  129320. 9,
  129321. 6,
  129322. 10,
  129323. 5,
  129324. 11,
  129325. 4,
  129326. 12,
  129327. 3,
  129328. 13,
  129329. 2,
  129330. 14,
  129331. 1,
  129332. 15,
  129333. 0,
  129334. 16,
  129335. };
  129336. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129337. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129338. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129339. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129340. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129341. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129342. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129343. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129344. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129345. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129346. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129347. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129348. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129349. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129350. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129351. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129352. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129353. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129354. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129355. 13,
  129356. };
  129357. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129358. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129359. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129360. };
  129361. static long _vq_quantmap__44c3_s_p6_0[] = {
  129362. 15, 13, 11, 9, 7, 5, 3, 1,
  129363. 0, 2, 4, 6, 8, 10, 12, 14,
  129364. 16,
  129365. };
  129366. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129367. _vq_quantthresh__44c3_s_p6_0,
  129368. _vq_quantmap__44c3_s_p6_0,
  129369. 17,
  129370. 17
  129371. };
  129372. static static_codebook _44c3_s_p6_0 = {
  129373. 2, 289,
  129374. _vq_lengthlist__44c3_s_p6_0,
  129375. 1, -529530880, 1611661312, 5, 0,
  129376. _vq_quantlist__44c3_s_p6_0,
  129377. NULL,
  129378. &_vq_auxt__44c3_s_p6_0,
  129379. NULL,
  129380. 0
  129381. };
  129382. static long _vq_quantlist__44c3_s_p7_0[] = {
  129383. 1,
  129384. 0,
  129385. 2,
  129386. };
  129387. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129388. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129389. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129390. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129391. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129392. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129393. 10,
  129394. };
  129395. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129396. -5.5, 5.5,
  129397. };
  129398. static long _vq_quantmap__44c3_s_p7_0[] = {
  129399. 1, 0, 2,
  129400. };
  129401. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129402. _vq_quantthresh__44c3_s_p7_0,
  129403. _vq_quantmap__44c3_s_p7_0,
  129404. 3,
  129405. 3
  129406. };
  129407. static static_codebook _44c3_s_p7_0 = {
  129408. 4, 81,
  129409. _vq_lengthlist__44c3_s_p7_0,
  129410. 1, -529137664, 1618345984, 2, 0,
  129411. _vq_quantlist__44c3_s_p7_0,
  129412. NULL,
  129413. &_vq_auxt__44c3_s_p7_0,
  129414. NULL,
  129415. 0
  129416. };
  129417. static long _vq_quantlist__44c3_s_p7_1[] = {
  129418. 5,
  129419. 4,
  129420. 6,
  129421. 3,
  129422. 7,
  129423. 2,
  129424. 8,
  129425. 1,
  129426. 9,
  129427. 0,
  129428. 10,
  129429. };
  129430. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129431. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129432. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129433. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129434. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129435. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129436. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129437. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129438. 10,10,10, 8, 8, 8, 8, 8, 8,
  129439. };
  129440. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129441. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129442. 3.5, 4.5,
  129443. };
  129444. static long _vq_quantmap__44c3_s_p7_1[] = {
  129445. 9, 7, 5, 3, 1, 0, 2, 4,
  129446. 6, 8, 10,
  129447. };
  129448. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129449. _vq_quantthresh__44c3_s_p7_1,
  129450. _vq_quantmap__44c3_s_p7_1,
  129451. 11,
  129452. 11
  129453. };
  129454. static static_codebook _44c3_s_p7_1 = {
  129455. 2, 121,
  129456. _vq_lengthlist__44c3_s_p7_1,
  129457. 1, -531365888, 1611661312, 4, 0,
  129458. _vq_quantlist__44c3_s_p7_1,
  129459. NULL,
  129460. &_vq_auxt__44c3_s_p7_1,
  129461. NULL,
  129462. 0
  129463. };
  129464. static long _vq_quantlist__44c3_s_p8_0[] = {
  129465. 6,
  129466. 5,
  129467. 7,
  129468. 4,
  129469. 8,
  129470. 3,
  129471. 9,
  129472. 2,
  129473. 10,
  129474. 1,
  129475. 11,
  129476. 0,
  129477. 12,
  129478. };
  129479. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129480. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129481. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129482. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129483. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129484. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129485. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129486. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129487. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129488. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129489. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129490. 0,13,13,12,12,13,12,14,13,
  129491. };
  129492. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129493. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129494. 12.5, 17.5, 22.5, 27.5,
  129495. };
  129496. static long _vq_quantmap__44c3_s_p8_0[] = {
  129497. 11, 9, 7, 5, 3, 1, 0, 2,
  129498. 4, 6, 8, 10, 12,
  129499. };
  129500. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129501. _vq_quantthresh__44c3_s_p8_0,
  129502. _vq_quantmap__44c3_s_p8_0,
  129503. 13,
  129504. 13
  129505. };
  129506. static static_codebook _44c3_s_p8_0 = {
  129507. 2, 169,
  129508. _vq_lengthlist__44c3_s_p8_0,
  129509. 1, -526516224, 1616117760, 4, 0,
  129510. _vq_quantlist__44c3_s_p8_0,
  129511. NULL,
  129512. &_vq_auxt__44c3_s_p8_0,
  129513. NULL,
  129514. 0
  129515. };
  129516. static long _vq_quantlist__44c3_s_p8_1[] = {
  129517. 2,
  129518. 1,
  129519. 3,
  129520. 0,
  129521. 4,
  129522. };
  129523. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129524. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129525. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129526. };
  129527. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129528. -1.5, -0.5, 0.5, 1.5,
  129529. };
  129530. static long _vq_quantmap__44c3_s_p8_1[] = {
  129531. 3, 1, 0, 2, 4,
  129532. };
  129533. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129534. _vq_quantthresh__44c3_s_p8_1,
  129535. _vq_quantmap__44c3_s_p8_1,
  129536. 5,
  129537. 5
  129538. };
  129539. static static_codebook _44c3_s_p8_1 = {
  129540. 2, 25,
  129541. _vq_lengthlist__44c3_s_p8_1,
  129542. 1, -533725184, 1611661312, 3, 0,
  129543. _vq_quantlist__44c3_s_p8_1,
  129544. NULL,
  129545. &_vq_auxt__44c3_s_p8_1,
  129546. NULL,
  129547. 0
  129548. };
  129549. static long _vq_quantlist__44c3_s_p9_0[] = {
  129550. 6,
  129551. 5,
  129552. 7,
  129553. 4,
  129554. 8,
  129555. 3,
  129556. 9,
  129557. 2,
  129558. 10,
  129559. 1,
  129560. 11,
  129561. 0,
  129562. 12,
  129563. };
  129564. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129565. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129566. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129567. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129568. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129569. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129570. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129571. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129572. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129573. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129574. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129575. 11,11,11,11,11,11,11,11,11,
  129576. };
  129577. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129578. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129579. 637.5, 892.5, 1147.5, 1402.5,
  129580. };
  129581. static long _vq_quantmap__44c3_s_p9_0[] = {
  129582. 11, 9, 7, 5, 3, 1, 0, 2,
  129583. 4, 6, 8, 10, 12,
  129584. };
  129585. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129586. _vq_quantthresh__44c3_s_p9_0,
  129587. _vq_quantmap__44c3_s_p9_0,
  129588. 13,
  129589. 13
  129590. };
  129591. static static_codebook _44c3_s_p9_0 = {
  129592. 2, 169,
  129593. _vq_lengthlist__44c3_s_p9_0,
  129594. 1, -514332672, 1627381760, 4, 0,
  129595. _vq_quantlist__44c3_s_p9_0,
  129596. NULL,
  129597. &_vq_auxt__44c3_s_p9_0,
  129598. NULL,
  129599. 0
  129600. };
  129601. static long _vq_quantlist__44c3_s_p9_1[] = {
  129602. 7,
  129603. 6,
  129604. 8,
  129605. 5,
  129606. 9,
  129607. 4,
  129608. 10,
  129609. 3,
  129610. 11,
  129611. 2,
  129612. 12,
  129613. 1,
  129614. 13,
  129615. 0,
  129616. 14,
  129617. };
  129618. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129619. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129620. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129621. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129622. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129623. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129624. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129625. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129626. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129627. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129628. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129629. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129630. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129631. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129632. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129633. 15,
  129634. };
  129635. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129636. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129637. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129638. };
  129639. static long _vq_quantmap__44c3_s_p9_1[] = {
  129640. 13, 11, 9, 7, 5, 3, 1, 0,
  129641. 2, 4, 6, 8, 10, 12, 14,
  129642. };
  129643. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129644. _vq_quantthresh__44c3_s_p9_1,
  129645. _vq_quantmap__44c3_s_p9_1,
  129646. 15,
  129647. 15
  129648. };
  129649. static static_codebook _44c3_s_p9_1 = {
  129650. 2, 225,
  129651. _vq_lengthlist__44c3_s_p9_1,
  129652. 1, -522338304, 1620115456, 4, 0,
  129653. _vq_quantlist__44c3_s_p9_1,
  129654. NULL,
  129655. &_vq_auxt__44c3_s_p9_1,
  129656. NULL,
  129657. 0
  129658. };
  129659. static long _vq_quantlist__44c3_s_p9_2[] = {
  129660. 8,
  129661. 7,
  129662. 9,
  129663. 6,
  129664. 10,
  129665. 5,
  129666. 11,
  129667. 4,
  129668. 12,
  129669. 3,
  129670. 13,
  129671. 2,
  129672. 14,
  129673. 1,
  129674. 15,
  129675. 0,
  129676. 16,
  129677. };
  129678. static long _vq_lengthlist__44c3_s_p9_2[] = {
  129679. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129680. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  129681. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  129682. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129683. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  129684. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129685. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  129686. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  129687. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  129688. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  129689. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  129690. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  129691. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  129692. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  129693. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  129694. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  129695. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  129696. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  129697. 10,
  129698. };
  129699. static float _vq_quantthresh__44c3_s_p9_2[] = {
  129700. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129701. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129702. };
  129703. static long _vq_quantmap__44c3_s_p9_2[] = {
  129704. 15, 13, 11, 9, 7, 5, 3, 1,
  129705. 0, 2, 4, 6, 8, 10, 12, 14,
  129706. 16,
  129707. };
  129708. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  129709. _vq_quantthresh__44c3_s_p9_2,
  129710. _vq_quantmap__44c3_s_p9_2,
  129711. 17,
  129712. 17
  129713. };
  129714. static static_codebook _44c3_s_p9_2 = {
  129715. 2, 289,
  129716. _vq_lengthlist__44c3_s_p9_2,
  129717. 1, -529530880, 1611661312, 5, 0,
  129718. _vq_quantlist__44c3_s_p9_2,
  129719. NULL,
  129720. &_vq_auxt__44c3_s_p9_2,
  129721. NULL,
  129722. 0
  129723. };
  129724. static long _huff_lengthlist__44c3_s_short[] = {
  129725. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  129726. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  129727. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  129728. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  129729. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  129730. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  129731. 6, 8, 9,11,
  129732. };
  129733. static static_codebook _huff_book__44c3_s_short = {
  129734. 2, 100,
  129735. _huff_lengthlist__44c3_s_short,
  129736. 0, 0, 0, 0, 0,
  129737. NULL,
  129738. NULL,
  129739. NULL,
  129740. NULL,
  129741. 0
  129742. };
  129743. static long _huff_lengthlist__44c4_s_long[] = {
  129744. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  129745. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  129746. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  129747. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  129748. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  129749. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  129750. 9, 8, 7, 7,
  129751. };
  129752. static static_codebook _huff_book__44c4_s_long = {
  129753. 2, 100,
  129754. _huff_lengthlist__44c4_s_long,
  129755. 0, 0, 0, 0, 0,
  129756. NULL,
  129757. NULL,
  129758. NULL,
  129759. NULL,
  129760. 0
  129761. };
  129762. static long _vq_quantlist__44c4_s_p1_0[] = {
  129763. 1,
  129764. 0,
  129765. 2,
  129766. };
  129767. static long _vq_lengthlist__44c4_s_p1_0[] = {
  129768. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129769. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129774. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129779. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129814. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129819. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129824. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129860. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129865. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129870. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0,
  130179. };
  130180. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130181. -0.5, 0.5,
  130182. };
  130183. static long _vq_quantmap__44c4_s_p1_0[] = {
  130184. 1, 0, 2,
  130185. };
  130186. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130187. _vq_quantthresh__44c4_s_p1_0,
  130188. _vq_quantmap__44c4_s_p1_0,
  130189. 3,
  130190. 3
  130191. };
  130192. static static_codebook _44c4_s_p1_0 = {
  130193. 8, 6561,
  130194. _vq_lengthlist__44c4_s_p1_0,
  130195. 1, -535822336, 1611661312, 2, 0,
  130196. _vq_quantlist__44c4_s_p1_0,
  130197. NULL,
  130198. &_vq_auxt__44c4_s_p1_0,
  130199. NULL,
  130200. 0
  130201. };
  130202. static long _vq_quantlist__44c4_s_p2_0[] = {
  130203. 2,
  130204. 1,
  130205. 3,
  130206. 0,
  130207. 4,
  130208. };
  130209. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130210. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130211. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130212. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130213. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130214. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130220. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130221. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130222. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130228. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130229. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130235. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130236. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130237. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130249. 0,
  130250. };
  130251. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130252. -1.5, -0.5, 0.5, 1.5,
  130253. };
  130254. static long _vq_quantmap__44c4_s_p2_0[] = {
  130255. 3, 1, 0, 2, 4,
  130256. };
  130257. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130258. _vq_quantthresh__44c4_s_p2_0,
  130259. _vq_quantmap__44c4_s_p2_0,
  130260. 5,
  130261. 5
  130262. };
  130263. static static_codebook _44c4_s_p2_0 = {
  130264. 4, 625,
  130265. _vq_lengthlist__44c4_s_p2_0,
  130266. 1, -533725184, 1611661312, 3, 0,
  130267. _vq_quantlist__44c4_s_p2_0,
  130268. NULL,
  130269. &_vq_auxt__44c4_s_p2_0,
  130270. NULL,
  130271. 0
  130272. };
  130273. static long _vq_quantlist__44c4_s_p3_0[] = {
  130274. 2,
  130275. 1,
  130276. 3,
  130277. 0,
  130278. 4,
  130279. };
  130280. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130281. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130284. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130287. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130320. 0,
  130321. };
  130322. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130323. -1.5, -0.5, 0.5, 1.5,
  130324. };
  130325. static long _vq_quantmap__44c4_s_p3_0[] = {
  130326. 3, 1, 0, 2, 4,
  130327. };
  130328. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130329. _vq_quantthresh__44c4_s_p3_0,
  130330. _vq_quantmap__44c4_s_p3_0,
  130331. 5,
  130332. 5
  130333. };
  130334. static static_codebook _44c4_s_p3_0 = {
  130335. 4, 625,
  130336. _vq_lengthlist__44c4_s_p3_0,
  130337. 1, -533725184, 1611661312, 3, 0,
  130338. _vq_quantlist__44c4_s_p3_0,
  130339. NULL,
  130340. &_vq_auxt__44c4_s_p3_0,
  130341. NULL,
  130342. 0
  130343. };
  130344. static long _vq_quantlist__44c4_s_p4_0[] = {
  130345. 4,
  130346. 3,
  130347. 5,
  130348. 2,
  130349. 6,
  130350. 1,
  130351. 7,
  130352. 0,
  130353. 8,
  130354. };
  130355. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130356. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130357. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130358. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130359. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130360. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0,
  130362. };
  130363. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130364. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130365. };
  130366. static long _vq_quantmap__44c4_s_p4_0[] = {
  130367. 7, 5, 3, 1, 0, 2, 4, 6,
  130368. 8,
  130369. };
  130370. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130371. _vq_quantthresh__44c4_s_p4_0,
  130372. _vq_quantmap__44c4_s_p4_0,
  130373. 9,
  130374. 9
  130375. };
  130376. static static_codebook _44c4_s_p4_0 = {
  130377. 2, 81,
  130378. _vq_lengthlist__44c4_s_p4_0,
  130379. 1, -531628032, 1611661312, 4, 0,
  130380. _vq_quantlist__44c4_s_p4_0,
  130381. NULL,
  130382. &_vq_auxt__44c4_s_p4_0,
  130383. NULL,
  130384. 0
  130385. };
  130386. static long _vq_quantlist__44c4_s_p5_0[] = {
  130387. 4,
  130388. 3,
  130389. 5,
  130390. 2,
  130391. 6,
  130392. 1,
  130393. 7,
  130394. 0,
  130395. 8,
  130396. };
  130397. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130398. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130399. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130400. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130401. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130402. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130403. 10,
  130404. };
  130405. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130406. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130407. };
  130408. static long _vq_quantmap__44c4_s_p5_0[] = {
  130409. 7, 5, 3, 1, 0, 2, 4, 6,
  130410. 8,
  130411. };
  130412. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130413. _vq_quantthresh__44c4_s_p5_0,
  130414. _vq_quantmap__44c4_s_p5_0,
  130415. 9,
  130416. 9
  130417. };
  130418. static static_codebook _44c4_s_p5_0 = {
  130419. 2, 81,
  130420. _vq_lengthlist__44c4_s_p5_0,
  130421. 1, -531628032, 1611661312, 4, 0,
  130422. _vq_quantlist__44c4_s_p5_0,
  130423. NULL,
  130424. &_vq_auxt__44c4_s_p5_0,
  130425. NULL,
  130426. 0
  130427. };
  130428. static long _vq_quantlist__44c4_s_p6_0[] = {
  130429. 8,
  130430. 7,
  130431. 9,
  130432. 6,
  130433. 10,
  130434. 5,
  130435. 11,
  130436. 4,
  130437. 12,
  130438. 3,
  130439. 13,
  130440. 2,
  130441. 14,
  130442. 1,
  130443. 15,
  130444. 0,
  130445. 16,
  130446. };
  130447. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130448. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130449. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130450. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130451. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130452. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130453. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130454. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130455. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130456. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130457. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130458. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130459. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130460. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130461. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130462. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130463. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130464. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130465. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130466. 13,
  130467. };
  130468. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130469. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130470. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130471. };
  130472. static long _vq_quantmap__44c4_s_p6_0[] = {
  130473. 15, 13, 11, 9, 7, 5, 3, 1,
  130474. 0, 2, 4, 6, 8, 10, 12, 14,
  130475. 16,
  130476. };
  130477. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130478. _vq_quantthresh__44c4_s_p6_0,
  130479. _vq_quantmap__44c4_s_p6_0,
  130480. 17,
  130481. 17
  130482. };
  130483. static static_codebook _44c4_s_p6_0 = {
  130484. 2, 289,
  130485. _vq_lengthlist__44c4_s_p6_0,
  130486. 1, -529530880, 1611661312, 5, 0,
  130487. _vq_quantlist__44c4_s_p6_0,
  130488. NULL,
  130489. &_vq_auxt__44c4_s_p6_0,
  130490. NULL,
  130491. 0
  130492. };
  130493. static long _vq_quantlist__44c4_s_p7_0[] = {
  130494. 1,
  130495. 0,
  130496. 2,
  130497. };
  130498. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130499. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130500. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130501. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130502. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130503. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130504. 10,
  130505. };
  130506. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130507. -5.5, 5.5,
  130508. };
  130509. static long _vq_quantmap__44c4_s_p7_0[] = {
  130510. 1, 0, 2,
  130511. };
  130512. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130513. _vq_quantthresh__44c4_s_p7_0,
  130514. _vq_quantmap__44c4_s_p7_0,
  130515. 3,
  130516. 3
  130517. };
  130518. static static_codebook _44c4_s_p7_0 = {
  130519. 4, 81,
  130520. _vq_lengthlist__44c4_s_p7_0,
  130521. 1, -529137664, 1618345984, 2, 0,
  130522. _vq_quantlist__44c4_s_p7_0,
  130523. NULL,
  130524. &_vq_auxt__44c4_s_p7_0,
  130525. NULL,
  130526. 0
  130527. };
  130528. static long _vq_quantlist__44c4_s_p7_1[] = {
  130529. 5,
  130530. 4,
  130531. 6,
  130532. 3,
  130533. 7,
  130534. 2,
  130535. 8,
  130536. 1,
  130537. 9,
  130538. 0,
  130539. 10,
  130540. };
  130541. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130542. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130543. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130544. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130545. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130546. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130547. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130548. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130549. 10,10,10, 8, 8, 8, 8, 9, 9,
  130550. };
  130551. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130552. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130553. 3.5, 4.5,
  130554. };
  130555. static long _vq_quantmap__44c4_s_p7_1[] = {
  130556. 9, 7, 5, 3, 1, 0, 2, 4,
  130557. 6, 8, 10,
  130558. };
  130559. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130560. _vq_quantthresh__44c4_s_p7_1,
  130561. _vq_quantmap__44c4_s_p7_1,
  130562. 11,
  130563. 11
  130564. };
  130565. static static_codebook _44c4_s_p7_1 = {
  130566. 2, 121,
  130567. _vq_lengthlist__44c4_s_p7_1,
  130568. 1, -531365888, 1611661312, 4, 0,
  130569. _vq_quantlist__44c4_s_p7_1,
  130570. NULL,
  130571. &_vq_auxt__44c4_s_p7_1,
  130572. NULL,
  130573. 0
  130574. };
  130575. static long _vq_quantlist__44c4_s_p8_0[] = {
  130576. 6,
  130577. 5,
  130578. 7,
  130579. 4,
  130580. 8,
  130581. 3,
  130582. 9,
  130583. 2,
  130584. 10,
  130585. 1,
  130586. 11,
  130587. 0,
  130588. 12,
  130589. };
  130590. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130591. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130592. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130593. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130594. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130595. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130596. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130597. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130598. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130599. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130600. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130601. 0,13,12,12,12,12,12,13,13,
  130602. };
  130603. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130604. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130605. 12.5, 17.5, 22.5, 27.5,
  130606. };
  130607. static long _vq_quantmap__44c4_s_p8_0[] = {
  130608. 11, 9, 7, 5, 3, 1, 0, 2,
  130609. 4, 6, 8, 10, 12,
  130610. };
  130611. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130612. _vq_quantthresh__44c4_s_p8_0,
  130613. _vq_quantmap__44c4_s_p8_0,
  130614. 13,
  130615. 13
  130616. };
  130617. static static_codebook _44c4_s_p8_0 = {
  130618. 2, 169,
  130619. _vq_lengthlist__44c4_s_p8_0,
  130620. 1, -526516224, 1616117760, 4, 0,
  130621. _vq_quantlist__44c4_s_p8_0,
  130622. NULL,
  130623. &_vq_auxt__44c4_s_p8_0,
  130624. NULL,
  130625. 0
  130626. };
  130627. static long _vq_quantlist__44c4_s_p8_1[] = {
  130628. 2,
  130629. 1,
  130630. 3,
  130631. 0,
  130632. 4,
  130633. };
  130634. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130635. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130636. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130637. };
  130638. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130639. -1.5, -0.5, 0.5, 1.5,
  130640. };
  130641. static long _vq_quantmap__44c4_s_p8_1[] = {
  130642. 3, 1, 0, 2, 4,
  130643. };
  130644. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130645. _vq_quantthresh__44c4_s_p8_1,
  130646. _vq_quantmap__44c4_s_p8_1,
  130647. 5,
  130648. 5
  130649. };
  130650. static static_codebook _44c4_s_p8_1 = {
  130651. 2, 25,
  130652. _vq_lengthlist__44c4_s_p8_1,
  130653. 1, -533725184, 1611661312, 3, 0,
  130654. _vq_quantlist__44c4_s_p8_1,
  130655. NULL,
  130656. &_vq_auxt__44c4_s_p8_1,
  130657. NULL,
  130658. 0
  130659. };
  130660. static long _vq_quantlist__44c4_s_p9_0[] = {
  130661. 6,
  130662. 5,
  130663. 7,
  130664. 4,
  130665. 8,
  130666. 3,
  130667. 9,
  130668. 2,
  130669. 10,
  130670. 1,
  130671. 11,
  130672. 0,
  130673. 12,
  130674. };
  130675. static long _vq_lengthlist__44c4_s_p9_0[] = {
  130676. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  130677. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  130678. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130679. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130680. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130681. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130682. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130683. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130684. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130685. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130686. 12,12,12,12,12,12,12,12,12,
  130687. };
  130688. static float _vq_quantthresh__44c4_s_p9_0[] = {
  130689. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  130690. 787.5, 1102.5, 1417.5, 1732.5,
  130691. };
  130692. static long _vq_quantmap__44c4_s_p9_0[] = {
  130693. 11, 9, 7, 5, 3, 1, 0, 2,
  130694. 4, 6, 8, 10, 12,
  130695. };
  130696. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  130697. _vq_quantthresh__44c4_s_p9_0,
  130698. _vq_quantmap__44c4_s_p9_0,
  130699. 13,
  130700. 13
  130701. };
  130702. static static_codebook _44c4_s_p9_0 = {
  130703. 2, 169,
  130704. _vq_lengthlist__44c4_s_p9_0,
  130705. 1, -513964032, 1628680192, 4, 0,
  130706. _vq_quantlist__44c4_s_p9_0,
  130707. NULL,
  130708. &_vq_auxt__44c4_s_p9_0,
  130709. NULL,
  130710. 0
  130711. };
  130712. static long _vq_quantlist__44c4_s_p9_1[] = {
  130713. 7,
  130714. 6,
  130715. 8,
  130716. 5,
  130717. 9,
  130718. 4,
  130719. 10,
  130720. 3,
  130721. 11,
  130722. 2,
  130723. 12,
  130724. 1,
  130725. 13,
  130726. 0,
  130727. 14,
  130728. };
  130729. static long _vq_lengthlist__44c4_s_p9_1[] = {
  130730. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  130731. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  130732. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  130733. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  130734. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  130735. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  130736. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  130737. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  130738. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  130739. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  130740. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  130741. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  130742. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  130743. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  130744. 15,
  130745. };
  130746. static float _vq_quantthresh__44c4_s_p9_1[] = {
  130747. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130748. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130749. };
  130750. static long _vq_quantmap__44c4_s_p9_1[] = {
  130751. 13, 11, 9, 7, 5, 3, 1, 0,
  130752. 2, 4, 6, 8, 10, 12, 14,
  130753. };
  130754. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  130755. _vq_quantthresh__44c4_s_p9_1,
  130756. _vq_quantmap__44c4_s_p9_1,
  130757. 15,
  130758. 15
  130759. };
  130760. static static_codebook _44c4_s_p9_1 = {
  130761. 2, 225,
  130762. _vq_lengthlist__44c4_s_p9_1,
  130763. 1, -520986624, 1620377600, 4, 0,
  130764. _vq_quantlist__44c4_s_p9_1,
  130765. NULL,
  130766. &_vq_auxt__44c4_s_p9_1,
  130767. NULL,
  130768. 0
  130769. };
  130770. static long _vq_quantlist__44c4_s_p9_2[] = {
  130771. 10,
  130772. 9,
  130773. 11,
  130774. 8,
  130775. 12,
  130776. 7,
  130777. 13,
  130778. 6,
  130779. 14,
  130780. 5,
  130781. 15,
  130782. 4,
  130783. 16,
  130784. 3,
  130785. 17,
  130786. 2,
  130787. 18,
  130788. 1,
  130789. 19,
  130790. 0,
  130791. 20,
  130792. };
  130793. static long _vq_lengthlist__44c4_s_p9_2[] = {
  130794. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130795. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130796. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  130797. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  130798. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130799. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130800. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  130801. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  130802. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  130803. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  130804. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  130805. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  130806. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  130807. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  130808. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  130809. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  130810. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130811. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  130812. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  130813. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  130814. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130815. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  130816. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  130817. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  130818. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  130819. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  130820. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  130821. 10,10,10,10,10,10,10,10,10,
  130822. };
  130823. static float _vq_quantthresh__44c4_s_p9_2[] = {
  130824. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130825. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130826. 6.5, 7.5, 8.5, 9.5,
  130827. };
  130828. static long _vq_quantmap__44c4_s_p9_2[] = {
  130829. 19, 17, 15, 13, 11, 9, 7, 5,
  130830. 3, 1, 0, 2, 4, 6, 8, 10,
  130831. 12, 14, 16, 18, 20,
  130832. };
  130833. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  130834. _vq_quantthresh__44c4_s_p9_2,
  130835. _vq_quantmap__44c4_s_p9_2,
  130836. 21,
  130837. 21
  130838. };
  130839. static static_codebook _44c4_s_p9_2 = {
  130840. 2, 441,
  130841. _vq_lengthlist__44c4_s_p9_2,
  130842. 1, -529268736, 1611661312, 5, 0,
  130843. _vq_quantlist__44c4_s_p9_2,
  130844. NULL,
  130845. &_vq_auxt__44c4_s_p9_2,
  130846. NULL,
  130847. 0
  130848. };
  130849. static long _huff_lengthlist__44c4_s_short[] = {
  130850. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  130851. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  130852. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  130853. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  130854. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  130855. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  130856. 7, 9,12,17,
  130857. };
  130858. static static_codebook _huff_book__44c4_s_short = {
  130859. 2, 100,
  130860. _huff_lengthlist__44c4_s_short,
  130861. 0, 0, 0, 0, 0,
  130862. NULL,
  130863. NULL,
  130864. NULL,
  130865. NULL,
  130866. 0
  130867. };
  130868. static long _huff_lengthlist__44c5_s_long[] = {
  130869. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  130870. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  130871. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  130872. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  130873. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  130874. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  130875. 9, 8, 7, 7,
  130876. };
  130877. static static_codebook _huff_book__44c5_s_long = {
  130878. 2, 100,
  130879. _huff_lengthlist__44c5_s_long,
  130880. 0, 0, 0, 0, 0,
  130881. NULL,
  130882. NULL,
  130883. NULL,
  130884. NULL,
  130885. 0
  130886. };
  130887. static long _vq_quantlist__44c5_s_p1_0[] = {
  130888. 1,
  130889. 0,
  130890. 2,
  130891. };
  130892. static long _vq_lengthlist__44c5_s_p1_0[] = {
  130893. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130894. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130899. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130904. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  130939. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130944. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130949. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130985. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  130990. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130995. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131303. 0,
  131304. };
  131305. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131306. -0.5, 0.5,
  131307. };
  131308. static long _vq_quantmap__44c5_s_p1_0[] = {
  131309. 1, 0, 2,
  131310. };
  131311. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131312. _vq_quantthresh__44c5_s_p1_0,
  131313. _vq_quantmap__44c5_s_p1_0,
  131314. 3,
  131315. 3
  131316. };
  131317. static static_codebook _44c5_s_p1_0 = {
  131318. 8, 6561,
  131319. _vq_lengthlist__44c5_s_p1_0,
  131320. 1, -535822336, 1611661312, 2, 0,
  131321. _vq_quantlist__44c5_s_p1_0,
  131322. NULL,
  131323. &_vq_auxt__44c5_s_p1_0,
  131324. NULL,
  131325. 0
  131326. };
  131327. static long _vq_quantlist__44c5_s_p2_0[] = {
  131328. 2,
  131329. 1,
  131330. 3,
  131331. 0,
  131332. 4,
  131333. };
  131334. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131335. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131336. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131337. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131338. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131339. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131345. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131346. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131347. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131353. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131354. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131360. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131361. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131362. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131374. 0,
  131375. };
  131376. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131377. -1.5, -0.5, 0.5, 1.5,
  131378. };
  131379. static long _vq_quantmap__44c5_s_p2_0[] = {
  131380. 3, 1, 0, 2, 4,
  131381. };
  131382. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131383. _vq_quantthresh__44c5_s_p2_0,
  131384. _vq_quantmap__44c5_s_p2_0,
  131385. 5,
  131386. 5
  131387. };
  131388. static static_codebook _44c5_s_p2_0 = {
  131389. 4, 625,
  131390. _vq_lengthlist__44c5_s_p2_0,
  131391. 1, -533725184, 1611661312, 3, 0,
  131392. _vq_quantlist__44c5_s_p2_0,
  131393. NULL,
  131394. &_vq_auxt__44c5_s_p2_0,
  131395. NULL,
  131396. 0
  131397. };
  131398. static long _vq_quantlist__44c5_s_p3_0[] = {
  131399. 2,
  131400. 1,
  131401. 3,
  131402. 0,
  131403. 4,
  131404. };
  131405. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131406. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131409. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131412. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131445. 0,
  131446. };
  131447. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131448. -1.5, -0.5, 0.5, 1.5,
  131449. };
  131450. static long _vq_quantmap__44c5_s_p3_0[] = {
  131451. 3, 1, 0, 2, 4,
  131452. };
  131453. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131454. _vq_quantthresh__44c5_s_p3_0,
  131455. _vq_quantmap__44c5_s_p3_0,
  131456. 5,
  131457. 5
  131458. };
  131459. static static_codebook _44c5_s_p3_0 = {
  131460. 4, 625,
  131461. _vq_lengthlist__44c5_s_p3_0,
  131462. 1, -533725184, 1611661312, 3, 0,
  131463. _vq_quantlist__44c5_s_p3_0,
  131464. NULL,
  131465. &_vq_auxt__44c5_s_p3_0,
  131466. NULL,
  131467. 0
  131468. };
  131469. static long _vq_quantlist__44c5_s_p4_0[] = {
  131470. 4,
  131471. 3,
  131472. 5,
  131473. 2,
  131474. 6,
  131475. 1,
  131476. 7,
  131477. 0,
  131478. 8,
  131479. };
  131480. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131481. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131482. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131483. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131484. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131485. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0,
  131487. };
  131488. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131489. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131490. };
  131491. static long _vq_quantmap__44c5_s_p4_0[] = {
  131492. 7, 5, 3, 1, 0, 2, 4, 6,
  131493. 8,
  131494. };
  131495. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131496. _vq_quantthresh__44c5_s_p4_0,
  131497. _vq_quantmap__44c5_s_p4_0,
  131498. 9,
  131499. 9
  131500. };
  131501. static static_codebook _44c5_s_p4_0 = {
  131502. 2, 81,
  131503. _vq_lengthlist__44c5_s_p4_0,
  131504. 1, -531628032, 1611661312, 4, 0,
  131505. _vq_quantlist__44c5_s_p4_0,
  131506. NULL,
  131507. &_vq_auxt__44c5_s_p4_0,
  131508. NULL,
  131509. 0
  131510. };
  131511. static long _vq_quantlist__44c5_s_p5_0[] = {
  131512. 4,
  131513. 3,
  131514. 5,
  131515. 2,
  131516. 6,
  131517. 1,
  131518. 7,
  131519. 0,
  131520. 8,
  131521. };
  131522. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131523. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131524. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131525. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131526. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131527. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131528. 10,
  131529. };
  131530. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131531. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131532. };
  131533. static long _vq_quantmap__44c5_s_p5_0[] = {
  131534. 7, 5, 3, 1, 0, 2, 4, 6,
  131535. 8,
  131536. };
  131537. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131538. _vq_quantthresh__44c5_s_p5_0,
  131539. _vq_quantmap__44c5_s_p5_0,
  131540. 9,
  131541. 9
  131542. };
  131543. static static_codebook _44c5_s_p5_0 = {
  131544. 2, 81,
  131545. _vq_lengthlist__44c5_s_p5_0,
  131546. 1, -531628032, 1611661312, 4, 0,
  131547. _vq_quantlist__44c5_s_p5_0,
  131548. NULL,
  131549. &_vq_auxt__44c5_s_p5_0,
  131550. NULL,
  131551. 0
  131552. };
  131553. static long _vq_quantlist__44c5_s_p6_0[] = {
  131554. 8,
  131555. 7,
  131556. 9,
  131557. 6,
  131558. 10,
  131559. 5,
  131560. 11,
  131561. 4,
  131562. 12,
  131563. 3,
  131564. 13,
  131565. 2,
  131566. 14,
  131567. 1,
  131568. 15,
  131569. 0,
  131570. 16,
  131571. };
  131572. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131573. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131574. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131575. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131576. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131577. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131578. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131579. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131580. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131581. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131582. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131583. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131584. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131585. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131586. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131587. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131588. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131589. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131590. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131591. 13,
  131592. };
  131593. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131594. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131595. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131596. };
  131597. static long _vq_quantmap__44c5_s_p6_0[] = {
  131598. 15, 13, 11, 9, 7, 5, 3, 1,
  131599. 0, 2, 4, 6, 8, 10, 12, 14,
  131600. 16,
  131601. };
  131602. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131603. _vq_quantthresh__44c5_s_p6_0,
  131604. _vq_quantmap__44c5_s_p6_0,
  131605. 17,
  131606. 17
  131607. };
  131608. static static_codebook _44c5_s_p6_0 = {
  131609. 2, 289,
  131610. _vq_lengthlist__44c5_s_p6_0,
  131611. 1, -529530880, 1611661312, 5, 0,
  131612. _vq_quantlist__44c5_s_p6_0,
  131613. NULL,
  131614. &_vq_auxt__44c5_s_p6_0,
  131615. NULL,
  131616. 0
  131617. };
  131618. static long _vq_quantlist__44c5_s_p7_0[] = {
  131619. 1,
  131620. 0,
  131621. 2,
  131622. };
  131623. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131624. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131625. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131626. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131627. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131628. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131629. 10,
  131630. };
  131631. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131632. -5.5, 5.5,
  131633. };
  131634. static long _vq_quantmap__44c5_s_p7_0[] = {
  131635. 1, 0, 2,
  131636. };
  131637. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131638. _vq_quantthresh__44c5_s_p7_0,
  131639. _vq_quantmap__44c5_s_p7_0,
  131640. 3,
  131641. 3
  131642. };
  131643. static static_codebook _44c5_s_p7_0 = {
  131644. 4, 81,
  131645. _vq_lengthlist__44c5_s_p7_0,
  131646. 1, -529137664, 1618345984, 2, 0,
  131647. _vq_quantlist__44c5_s_p7_0,
  131648. NULL,
  131649. &_vq_auxt__44c5_s_p7_0,
  131650. NULL,
  131651. 0
  131652. };
  131653. static long _vq_quantlist__44c5_s_p7_1[] = {
  131654. 5,
  131655. 4,
  131656. 6,
  131657. 3,
  131658. 7,
  131659. 2,
  131660. 8,
  131661. 1,
  131662. 9,
  131663. 0,
  131664. 10,
  131665. };
  131666. static long _vq_lengthlist__44c5_s_p7_1[] = {
  131667. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  131668. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131669. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131670. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131671. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131672. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  131673. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131674. 10,10,10, 8, 8, 8, 8, 8, 8,
  131675. };
  131676. static float _vq_quantthresh__44c5_s_p7_1[] = {
  131677. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131678. 3.5, 4.5,
  131679. };
  131680. static long _vq_quantmap__44c5_s_p7_1[] = {
  131681. 9, 7, 5, 3, 1, 0, 2, 4,
  131682. 6, 8, 10,
  131683. };
  131684. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  131685. _vq_quantthresh__44c5_s_p7_1,
  131686. _vq_quantmap__44c5_s_p7_1,
  131687. 11,
  131688. 11
  131689. };
  131690. static static_codebook _44c5_s_p7_1 = {
  131691. 2, 121,
  131692. _vq_lengthlist__44c5_s_p7_1,
  131693. 1, -531365888, 1611661312, 4, 0,
  131694. _vq_quantlist__44c5_s_p7_1,
  131695. NULL,
  131696. &_vq_auxt__44c5_s_p7_1,
  131697. NULL,
  131698. 0
  131699. };
  131700. static long _vq_quantlist__44c5_s_p8_0[] = {
  131701. 6,
  131702. 5,
  131703. 7,
  131704. 4,
  131705. 8,
  131706. 3,
  131707. 9,
  131708. 2,
  131709. 10,
  131710. 1,
  131711. 11,
  131712. 0,
  131713. 12,
  131714. };
  131715. static long _vq_lengthlist__44c5_s_p8_0[] = {
  131716. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131717. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  131718. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131719. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131720. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  131721. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  131722. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  131723. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131724. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  131725. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131726. 0,12,12,12,12,12,12,13,13,
  131727. };
  131728. static float _vq_quantthresh__44c5_s_p8_0[] = {
  131729. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131730. 12.5, 17.5, 22.5, 27.5,
  131731. };
  131732. static long _vq_quantmap__44c5_s_p8_0[] = {
  131733. 11, 9, 7, 5, 3, 1, 0, 2,
  131734. 4, 6, 8, 10, 12,
  131735. };
  131736. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  131737. _vq_quantthresh__44c5_s_p8_0,
  131738. _vq_quantmap__44c5_s_p8_0,
  131739. 13,
  131740. 13
  131741. };
  131742. static static_codebook _44c5_s_p8_0 = {
  131743. 2, 169,
  131744. _vq_lengthlist__44c5_s_p8_0,
  131745. 1, -526516224, 1616117760, 4, 0,
  131746. _vq_quantlist__44c5_s_p8_0,
  131747. NULL,
  131748. &_vq_auxt__44c5_s_p8_0,
  131749. NULL,
  131750. 0
  131751. };
  131752. static long _vq_quantlist__44c5_s_p8_1[] = {
  131753. 2,
  131754. 1,
  131755. 3,
  131756. 0,
  131757. 4,
  131758. };
  131759. static long _vq_lengthlist__44c5_s_p8_1[] = {
  131760. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  131761. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131762. };
  131763. static float _vq_quantthresh__44c5_s_p8_1[] = {
  131764. -1.5, -0.5, 0.5, 1.5,
  131765. };
  131766. static long _vq_quantmap__44c5_s_p8_1[] = {
  131767. 3, 1, 0, 2, 4,
  131768. };
  131769. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  131770. _vq_quantthresh__44c5_s_p8_1,
  131771. _vq_quantmap__44c5_s_p8_1,
  131772. 5,
  131773. 5
  131774. };
  131775. static static_codebook _44c5_s_p8_1 = {
  131776. 2, 25,
  131777. _vq_lengthlist__44c5_s_p8_1,
  131778. 1, -533725184, 1611661312, 3, 0,
  131779. _vq_quantlist__44c5_s_p8_1,
  131780. NULL,
  131781. &_vq_auxt__44c5_s_p8_1,
  131782. NULL,
  131783. 0
  131784. };
  131785. static long _vq_quantlist__44c5_s_p9_0[] = {
  131786. 7,
  131787. 6,
  131788. 8,
  131789. 5,
  131790. 9,
  131791. 4,
  131792. 10,
  131793. 3,
  131794. 11,
  131795. 2,
  131796. 12,
  131797. 1,
  131798. 13,
  131799. 0,
  131800. 14,
  131801. };
  131802. static long _vq_lengthlist__44c5_s_p9_0[] = {
  131803. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  131804. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  131805. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131806. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131807. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131808. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131809. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131810. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131811. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131812. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131813. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131814. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131815. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  131816. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  131817. 12,
  131818. };
  131819. static float _vq_quantthresh__44c5_s_p9_0[] = {
  131820. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  131821. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  131822. };
  131823. static long _vq_quantmap__44c5_s_p9_0[] = {
  131824. 13, 11, 9, 7, 5, 3, 1, 0,
  131825. 2, 4, 6, 8, 10, 12, 14,
  131826. };
  131827. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  131828. _vq_quantthresh__44c5_s_p9_0,
  131829. _vq_quantmap__44c5_s_p9_0,
  131830. 15,
  131831. 15
  131832. };
  131833. static static_codebook _44c5_s_p9_0 = {
  131834. 2, 225,
  131835. _vq_lengthlist__44c5_s_p9_0,
  131836. 1, -512522752, 1628852224, 4, 0,
  131837. _vq_quantlist__44c5_s_p9_0,
  131838. NULL,
  131839. &_vq_auxt__44c5_s_p9_0,
  131840. NULL,
  131841. 0
  131842. };
  131843. static long _vq_quantlist__44c5_s_p9_1[] = {
  131844. 8,
  131845. 7,
  131846. 9,
  131847. 6,
  131848. 10,
  131849. 5,
  131850. 11,
  131851. 4,
  131852. 12,
  131853. 3,
  131854. 13,
  131855. 2,
  131856. 14,
  131857. 1,
  131858. 15,
  131859. 0,
  131860. 16,
  131861. };
  131862. static long _vq_lengthlist__44c5_s_p9_1[] = {
  131863. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  131864. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  131865. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  131866. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  131867. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  131868. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  131869. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  131870. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  131871. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  131872. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  131873. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  131874. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  131875. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  131876. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  131877. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  131878. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  131879. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  131880. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  131881. 15,
  131882. };
  131883. static float _vq_quantthresh__44c5_s_p9_1[] = {
  131884. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  131885. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  131886. };
  131887. static long _vq_quantmap__44c5_s_p9_1[] = {
  131888. 15, 13, 11, 9, 7, 5, 3, 1,
  131889. 0, 2, 4, 6, 8, 10, 12, 14,
  131890. 16,
  131891. };
  131892. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  131893. _vq_quantthresh__44c5_s_p9_1,
  131894. _vq_quantmap__44c5_s_p9_1,
  131895. 17,
  131896. 17
  131897. };
  131898. static static_codebook _44c5_s_p9_1 = {
  131899. 2, 289,
  131900. _vq_lengthlist__44c5_s_p9_1,
  131901. 1, -520814592, 1620377600, 5, 0,
  131902. _vq_quantlist__44c5_s_p9_1,
  131903. NULL,
  131904. &_vq_auxt__44c5_s_p9_1,
  131905. NULL,
  131906. 0
  131907. };
  131908. static long _vq_quantlist__44c5_s_p9_2[] = {
  131909. 10,
  131910. 9,
  131911. 11,
  131912. 8,
  131913. 12,
  131914. 7,
  131915. 13,
  131916. 6,
  131917. 14,
  131918. 5,
  131919. 15,
  131920. 4,
  131921. 16,
  131922. 3,
  131923. 17,
  131924. 2,
  131925. 18,
  131926. 1,
  131927. 19,
  131928. 0,
  131929. 20,
  131930. };
  131931. static long _vq_lengthlist__44c5_s_p9_2[] = {
  131932. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131933. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  131934. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  131935. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131936. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  131937. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  131938. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  131939. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  131940. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  131941. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131942. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131943. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  131944. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  131945. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  131946. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  131947. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  131948. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131949. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131950. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  131951. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  131952. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131953. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131954. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  131955. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  131956. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  131957. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131958. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  131959. 10,10,10,10,10,10,10,10,10,
  131960. };
  131961. static float _vq_quantthresh__44c5_s_p9_2[] = {
  131962. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131963. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131964. 6.5, 7.5, 8.5, 9.5,
  131965. };
  131966. static long _vq_quantmap__44c5_s_p9_2[] = {
  131967. 19, 17, 15, 13, 11, 9, 7, 5,
  131968. 3, 1, 0, 2, 4, 6, 8, 10,
  131969. 12, 14, 16, 18, 20,
  131970. };
  131971. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  131972. _vq_quantthresh__44c5_s_p9_2,
  131973. _vq_quantmap__44c5_s_p9_2,
  131974. 21,
  131975. 21
  131976. };
  131977. static static_codebook _44c5_s_p9_2 = {
  131978. 2, 441,
  131979. _vq_lengthlist__44c5_s_p9_2,
  131980. 1, -529268736, 1611661312, 5, 0,
  131981. _vq_quantlist__44c5_s_p9_2,
  131982. NULL,
  131983. &_vq_auxt__44c5_s_p9_2,
  131984. NULL,
  131985. 0
  131986. };
  131987. static long _huff_lengthlist__44c5_s_short[] = {
  131988. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  131989. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  131990. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  131991. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  131992. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  131993. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  131994. 6, 8,11,16,
  131995. };
  131996. static static_codebook _huff_book__44c5_s_short = {
  131997. 2, 100,
  131998. _huff_lengthlist__44c5_s_short,
  131999. 0, 0, 0, 0, 0,
  132000. NULL,
  132001. NULL,
  132002. NULL,
  132003. NULL,
  132004. 0
  132005. };
  132006. static long _huff_lengthlist__44c6_s_long[] = {
  132007. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132008. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132009. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132010. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132011. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132012. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132013. 11,10,10,12,
  132014. };
  132015. static static_codebook _huff_book__44c6_s_long = {
  132016. 2, 100,
  132017. _huff_lengthlist__44c6_s_long,
  132018. 0, 0, 0, 0, 0,
  132019. NULL,
  132020. NULL,
  132021. NULL,
  132022. NULL,
  132023. 0
  132024. };
  132025. static long _vq_quantlist__44c6_s_p1_0[] = {
  132026. 1,
  132027. 0,
  132028. 2,
  132029. };
  132030. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132031. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132032. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132033. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132034. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132035. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132036. 8,
  132037. };
  132038. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132039. -0.5, 0.5,
  132040. };
  132041. static long _vq_quantmap__44c6_s_p1_0[] = {
  132042. 1, 0, 2,
  132043. };
  132044. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132045. _vq_quantthresh__44c6_s_p1_0,
  132046. _vq_quantmap__44c6_s_p1_0,
  132047. 3,
  132048. 3
  132049. };
  132050. static static_codebook _44c6_s_p1_0 = {
  132051. 4, 81,
  132052. _vq_lengthlist__44c6_s_p1_0,
  132053. 1, -535822336, 1611661312, 2, 0,
  132054. _vq_quantlist__44c6_s_p1_0,
  132055. NULL,
  132056. &_vq_auxt__44c6_s_p1_0,
  132057. NULL,
  132058. 0
  132059. };
  132060. static long _vq_quantlist__44c6_s_p2_0[] = {
  132061. 2,
  132062. 1,
  132063. 3,
  132064. 0,
  132065. 4,
  132066. };
  132067. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132068. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132069. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132070. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132071. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132072. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132073. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132074. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132075. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132078. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132079. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132080. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132081. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132082. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132083. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132086. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132087. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132088. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132089. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132090. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132091. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132094. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132095. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132096. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132097. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132098. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132099. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132104. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132105. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132106. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132107. 13,
  132108. };
  132109. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132110. -1.5, -0.5, 0.5, 1.5,
  132111. };
  132112. static long _vq_quantmap__44c6_s_p2_0[] = {
  132113. 3, 1, 0, 2, 4,
  132114. };
  132115. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132116. _vq_quantthresh__44c6_s_p2_0,
  132117. _vq_quantmap__44c6_s_p2_0,
  132118. 5,
  132119. 5
  132120. };
  132121. static static_codebook _44c6_s_p2_0 = {
  132122. 4, 625,
  132123. _vq_lengthlist__44c6_s_p2_0,
  132124. 1, -533725184, 1611661312, 3, 0,
  132125. _vq_quantlist__44c6_s_p2_0,
  132126. NULL,
  132127. &_vq_auxt__44c6_s_p2_0,
  132128. NULL,
  132129. 0
  132130. };
  132131. static long _vq_quantlist__44c6_s_p3_0[] = {
  132132. 4,
  132133. 3,
  132134. 5,
  132135. 2,
  132136. 6,
  132137. 1,
  132138. 7,
  132139. 0,
  132140. 8,
  132141. };
  132142. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132143. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132144. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132145. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132146. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0,
  132149. };
  132150. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132151. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132152. };
  132153. static long _vq_quantmap__44c6_s_p3_0[] = {
  132154. 7, 5, 3, 1, 0, 2, 4, 6,
  132155. 8,
  132156. };
  132157. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132158. _vq_quantthresh__44c6_s_p3_0,
  132159. _vq_quantmap__44c6_s_p3_0,
  132160. 9,
  132161. 9
  132162. };
  132163. static static_codebook _44c6_s_p3_0 = {
  132164. 2, 81,
  132165. _vq_lengthlist__44c6_s_p3_0,
  132166. 1, -531628032, 1611661312, 4, 0,
  132167. _vq_quantlist__44c6_s_p3_0,
  132168. NULL,
  132169. &_vq_auxt__44c6_s_p3_0,
  132170. NULL,
  132171. 0
  132172. };
  132173. static long _vq_quantlist__44c6_s_p4_0[] = {
  132174. 8,
  132175. 7,
  132176. 9,
  132177. 6,
  132178. 10,
  132179. 5,
  132180. 11,
  132181. 4,
  132182. 12,
  132183. 3,
  132184. 13,
  132185. 2,
  132186. 14,
  132187. 1,
  132188. 15,
  132189. 0,
  132190. 16,
  132191. };
  132192. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132193. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132194. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132195. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132196. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132197. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132198. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132199. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132200. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132201. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132202. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0,
  132212. };
  132213. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132214. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132215. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132216. };
  132217. static long _vq_quantmap__44c6_s_p4_0[] = {
  132218. 15, 13, 11, 9, 7, 5, 3, 1,
  132219. 0, 2, 4, 6, 8, 10, 12, 14,
  132220. 16,
  132221. };
  132222. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132223. _vq_quantthresh__44c6_s_p4_0,
  132224. _vq_quantmap__44c6_s_p4_0,
  132225. 17,
  132226. 17
  132227. };
  132228. static static_codebook _44c6_s_p4_0 = {
  132229. 2, 289,
  132230. _vq_lengthlist__44c6_s_p4_0,
  132231. 1, -529530880, 1611661312, 5, 0,
  132232. _vq_quantlist__44c6_s_p4_0,
  132233. NULL,
  132234. &_vq_auxt__44c6_s_p4_0,
  132235. NULL,
  132236. 0
  132237. };
  132238. static long _vq_quantlist__44c6_s_p5_0[] = {
  132239. 1,
  132240. 0,
  132241. 2,
  132242. };
  132243. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132244. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132245. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132246. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132247. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132248. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132249. 12,
  132250. };
  132251. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132252. -5.5, 5.5,
  132253. };
  132254. static long _vq_quantmap__44c6_s_p5_0[] = {
  132255. 1, 0, 2,
  132256. };
  132257. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132258. _vq_quantthresh__44c6_s_p5_0,
  132259. _vq_quantmap__44c6_s_p5_0,
  132260. 3,
  132261. 3
  132262. };
  132263. static static_codebook _44c6_s_p5_0 = {
  132264. 4, 81,
  132265. _vq_lengthlist__44c6_s_p5_0,
  132266. 1, -529137664, 1618345984, 2, 0,
  132267. _vq_quantlist__44c6_s_p5_0,
  132268. NULL,
  132269. &_vq_auxt__44c6_s_p5_0,
  132270. NULL,
  132271. 0
  132272. };
  132273. static long _vq_quantlist__44c6_s_p5_1[] = {
  132274. 5,
  132275. 4,
  132276. 6,
  132277. 3,
  132278. 7,
  132279. 2,
  132280. 8,
  132281. 1,
  132282. 9,
  132283. 0,
  132284. 10,
  132285. };
  132286. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132287. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132288. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132289. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132290. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132291. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132292. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132293. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132294. 11,10,10, 7, 7, 8, 8, 8, 8,
  132295. };
  132296. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132297. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132298. 3.5, 4.5,
  132299. };
  132300. static long _vq_quantmap__44c6_s_p5_1[] = {
  132301. 9, 7, 5, 3, 1, 0, 2, 4,
  132302. 6, 8, 10,
  132303. };
  132304. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132305. _vq_quantthresh__44c6_s_p5_1,
  132306. _vq_quantmap__44c6_s_p5_1,
  132307. 11,
  132308. 11
  132309. };
  132310. static static_codebook _44c6_s_p5_1 = {
  132311. 2, 121,
  132312. _vq_lengthlist__44c6_s_p5_1,
  132313. 1, -531365888, 1611661312, 4, 0,
  132314. _vq_quantlist__44c6_s_p5_1,
  132315. NULL,
  132316. &_vq_auxt__44c6_s_p5_1,
  132317. NULL,
  132318. 0
  132319. };
  132320. static long _vq_quantlist__44c6_s_p6_0[] = {
  132321. 6,
  132322. 5,
  132323. 7,
  132324. 4,
  132325. 8,
  132326. 3,
  132327. 9,
  132328. 2,
  132329. 10,
  132330. 1,
  132331. 11,
  132332. 0,
  132333. 12,
  132334. };
  132335. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132336. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132337. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132338. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132339. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132340. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132341. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132346. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132347. };
  132348. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132349. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132350. 12.5, 17.5, 22.5, 27.5,
  132351. };
  132352. static long _vq_quantmap__44c6_s_p6_0[] = {
  132353. 11, 9, 7, 5, 3, 1, 0, 2,
  132354. 4, 6, 8, 10, 12,
  132355. };
  132356. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132357. _vq_quantthresh__44c6_s_p6_0,
  132358. _vq_quantmap__44c6_s_p6_0,
  132359. 13,
  132360. 13
  132361. };
  132362. static static_codebook _44c6_s_p6_0 = {
  132363. 2, 169,
  132364. _vq_lengthlist__44c6_s_p6_0,
  132365. 1, -526516224, 1616117760, 4, 0,
  132366. _vq_quantlist__44c6_s_p6_0,
  132367. NULL,
  132368. &_vq_auxt__44c6_s_p6_0,
  132369. NULL,
  132370. 0
  132371. };
  132372. static long _vq_quantlist__44c6_s_p6_1[] = {
  132373. 2,
  132374. 1,
  132375. 3,
  132376. 0,
  132377. 4,
  132378. };
  132379. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132380. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132381. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132382. };
  132383. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132384. -1.5, -0.5, 0.5, 1.5,
  132385. };
  132386. static long _vq_quantmap__44c6_s_p6_1[] = {
  132387. 3, 1, 0, 2, 4,
  132388. };
  132389. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132390. _vq_quantthresh__44c6_s_p6_1,
  132391. _vq_quantmap__44c6_s_p6_1,
  132392. 5,
  132393. 5
  132394. };
  132395. static static_codebook _44c6_s_p6_1 = {
  132396. 2, 25,
  132397. _vq_lengthlist__44c6_s_p6_1,
  132398. 1, -533725184, 1611661312, 3, 0,
  132399. _vq_quantlist__44c6_s_p6_1,
  132400. NULL,
  132401. &_vq_auxt__44c6_s_p6_1,
  132402. NULL,
  132403. 0
  132404. };
  132405. static long _vq_quantlist__44c6_s_p7_0[] = {
  132406. 6,
  132407. 5,
  132408. 7,
  132409. 4,
  132410. 8,
  132411. 3,
  132412. 9,
  132413. 2,
  132414. 10,
  132415. 1,
  132416. 11,
  132417. 0,
  132418. 12,
  132419. };
  132420. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132421. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132422. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132423. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132424. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132425. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132426. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132427. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132428. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132429. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132430. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132431. 20,13,13,13,13,13,13,14,14,
  132432. };
  132433. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132434. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132435. 27.5, 38.5, 49.5, 60.5,
  132436. };
  132437. static long _vq_quantmap__44c6_s_p7_0[] = {
  132438. 11, 9, 7, 5, 3, 1, 0, 2,
  132439. 4, 6, 8, 10, 12,
  132440. };
  132441. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132442. _vq_quantthresh__44c6_s_p7_0,
  132443. _vq_quantmap__44c6_s_p7_0,
  132444. 13,
  132445. 13
  132446. };
  132447. static static_codebook _44c6_s_p7_0 = {
  132448. 2, 169,
  132449. _vq_lengthlist__44c6_s_p7_0,
  132450. 1, -523206656, 1618345984, 4, 0,
  132451. _vq_quantlist__44c6_s_p7_0,
  132452. NULL,
  132453. &_vq_auxt__44c6_s_p7_0,
  132454. NULL,
  132455. 0
  132456. };
  132457. static long _vq_quantlist__44c6_s_p7_1[] = {
  132458. 5,
  132459. 4,
  132460. 6,
  132461. 3,
  132462. 7,
  132463. 2,
  132464. 8,
  132465. 1,
  132466. 9,
  132467. 0,
  132468. 10,
  132469. };
  132470. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132471. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132472. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132473. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132474. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132475. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132476. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132477. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132478. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132479. };
  132480. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132481. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132482. 3.5, 4.5,
  132483. };
  132484. static long _vq_quantmap__44c6_s_p7_1[] = {
  132485. 9, 7, 5, 3, 1, 0, 2, 4,
  132486. 6, 8, 10,
  132487. };
  132488. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132489. _vq_quantthresh__44c6_s_p7_1,
  132490. _vq_quantmap__44c6_s_p7_1,
  132491. 11,
  132492. 11
  132493. };
  132494. static static_codebook _44c6_s_p7_1 = {
  132495. 2, 121,
  132496. _vq_lengthlist__44c6_s_p7_1,
  132497. 1, -531365888, 1611661312, 4, 0,
  132498. _vq_quantlist__44c6_s_p7_1,
  132499. NULL,
  132500. &_vq_auxt__44c6_s_p7_1,
  132501. NULL,
  132502. 0
  132503. };
  132504. static long _vq_quantlist__44c6_s_p8_0[] = {
  132505. 7,
  132506. 6,
  132507. 8,
  132508. 5,
  132509. 9,
  132510. 4,
  132511. 10,
  132512. 3,
  132513. 11,
  132514. 2,
  132515. 12,
  132516. 1,
  132517. 13,
  132518. 0,
  132519. 14,
  132520. };
  132521. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132522. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132523. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132524. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132525. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132526. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132527. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132528. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132529. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132530. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132531. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132532. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132533. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132534. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132535. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132536. 14,
  132537. };
  132538. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132539. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132540. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132541. };
  132542. static long _vq_quantmap__44c6_s_p8_0[] = {
  132543. 13, 11, 9, 7, 5, 3, 1, 0,
  132544. 2, 4, 6, 8, 10, 12, 14,
  132545. };
  132546. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132547. _vq_quantthresh__44c6_s_p8_0,
  132548. _vq_quantmap__44c6_s_p8_0,
  132549. 15,
  132550. 15
  132551. };
  132552. static static_codebook _44c6_s_p8_0 = {
  132553. 2, 225,
  132554. _vq_lengthlist__44c6_s_p8_0,
  132555. 1, -520986624, 1620377600, 4, 0,
  132556. _vq_quantlist__44c6_s_p8_0,
  132557. NULL,
  132558. &_vq_auxt__44c6_s_p8_0,
  132559. NULL,
  132560. 0
  132561. };
  132562. static long _vq_quantlist__44c6_s_p8_1[] = {
  132563. 10,
  132564. 9,
  132565. 11,
  132566. 8,
  132567. 12,
  132568. 7,
  132569. 13,
  132570. 6,
  132571. 14,
  132572. 5,
  132573. 15,
  132574. 4,
  132575. 16,
  132576. 3,
  132577. 17,
  132578. 2,
  132579. 18,
  132580. 1,
  132581. 19,
  132582. 0,
  132583. 20,
  132584. };
  132585. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132586. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132587. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132588. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132589. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132590. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132591. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132592. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132593. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132594. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132595. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132596. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132598. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132599. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132600. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132601. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132602. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132603. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132604. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132605. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132606. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132607. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132608. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132609. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132610. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132611. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132612. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132613. 10,10,10,10,10,10,10,10,10,
  132614. };
  132615. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132616. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132617. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132618. 6.5, 7.5, 8.5, 9.5,
  132619. };
  132620. static long _vq_quantmap__44c6_s_p8_1[] = {
  132621. 19, 17, 15, 13, 11, 9, 7, 5,
  132622. 3, 1, 0, 2, 4, 6, 8, 10,
  132623. 12, 14, 16, 18, 20,
  132624. };
  132625. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132626. _vq_quantthresh__44c6_s_p8_1,
  132627. _vq_quantmap__44c6_s_p8_1,
  132628. 21,
  132629. 21
  132630. };
  132631. static static_codebook _44c6_s_p8_1 = {
  132632. 2, 441,
  132633. _vq_lengthlist__44c6_s_p8_1,
  132634. 1, -529268736, 1611661312, 5, 0,
  132635. _vq_quantlist__44c6_s_p8_1,
  132636. NULL,
  132637. &_vq_auxt__44c6_s_p8_1,
  132638. NULL,
  132639. 0
  132640. };
  132641. static long _vq_quantlist__44c6_s_p9_0[] = {
  132642. 6,
  132643. 5,
  132644. 7,
  132645. 4,
  132646. 8,
  132647. 3,
  132648. 9,
  132649. 2,
  132650. 10,
  132651. 1,
  132652. 11,
  132653. 0,
  132654. 12,
  132655. };
  132656. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132657. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132658. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132659. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132660. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  132661. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132662. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132663. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132667. 10,10,10,10,10,10,10,10,10,
  132668. };
  132669. static float _vq_quantthresh__44c6_s_p9_0[] = {
  132670. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  132671. 1592.5, 2229.5, 2866.5, 3503.5,
  132672. };
  132673. static long _vq_quantmap__44c6_s_p9_0[] = {
  132674. 11, 9, 7, 5, 3, 1, 0, 2,
  132675. 4, 6, 8, 10, 12,
  132676. };
  132677. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  132678. _vq_quantthresh__44c6_s_p9_0,
  132679. _vq_quantmap__44c6_s_p9_0,
  132680. 13,
  132681. 13
  132682. };
  132683. static static_codebook _44c6_s_p9_0 = {
  132684. 2, 169,
  132685. _vq_lengthlist__44c6_s_p9_0,
  132686. 1, -511845376, 1630791680, 4, 0,
  132687. _vq_quantlist__44c6_s_p9_0,
  132688. NULL,
  132689. &_vq_auxt__44c6_s_p9_0,
  132690. NULL,
  132691. 0
  132692. };
  132693. static long _vq_quantlist__44c6_s_p9_1[] = {
  132694. 6,
  132695. 5,
  132696. 7,
  132697. 4,
  132698. 8,
  132699. 3,
  132700. 9,
  132701. 2,
  132702. 10,
  132703. 1,
  132704. 11,
  132705. 0,
  132706. 12,
  132707. };
  132708. static long _vq_lengthlist__44c6_s_p9_1[] = {
  132709. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  132710. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  132711. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  132712. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  132713. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  132714. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  132715. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  132716. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  132717. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  132718. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  132719. 15,12,10,11,11,13,11,12,13,
  132720. };
  132721. static float _vq_quantthresh__44c6_s_p9_1[] = {
  132722. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  132723. 122.5, 171.5, 220.5, 269.5,
  132724. };
  132725. static long _vq_quantmap__44c6_s_p9_1[] = {
  132726. 11, 9, 7, 5, 3, 1, 0, 2,
  132727. 4, 6, 8, 10, 12,
  132728. };
  132729. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  132730. _vq_quantthresh__44c6_s_p9_1,
  132731. _vq_quantmap__44c6_s_p9_1,
  132732. 13,
  132733. 13
  132734. };
  132735. static static_codebook _44c6_s_p9_1 = {
  132736. 2, 169,
  132737. _vq_lengthlist__44c6_s_p9_1,
  132738. 1, -518889472, 1622704128, 4, 0,
  132739. _vq_quantlist__44c6_s_p9_1,
  132740. NULL,
  132741. &_vq_auxt__44c6_s_p9_1,
  132742. NULL,
  132743. 0
  132744. };
  132745. static long _vq_quantlist__44c6_s_p9_2[] = {
  132746. 24,
  132747. 23,
  132748. 25,
  132749. 22,
  132750. 26,
  132751. 21,
  132752. 27,
  132753. 20,
  132754. 28,
  132755. 19,
  132756. 29,
  132757. 18,
  132758. 30,
  132759. 17,
  132760. 31,
  132761. 16,
  132762. 32,
  132763. 15,
  132764. 33,
  132765. 14,
  132766. 34,
  132767. 13,
  132768. 35,
  132769. 12,
  132770. 36,
  132771. 11,
  132772. 37,
  132773. 10,
  132774. 38,
  132775. 9,
  132776. 39,
  132777. 8,
  132778. 40,
  132779. 7,
  132780. 41,
  132781. 6,
  132782. 42,
  132783. 5,
  132784. 43,
  132785. 4,
  132786. 44,
  132787. 3,
  132788. 45,
  132789. 2,
  132790. 46,
  132791. 1,
  132792. 47,
  132793. 0,
  132794. 48,
  132795. };
  132796. static long _vq_lengthlist__44c6_s_p9_2[] = {
  132797. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  132798. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132799. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  132800. 7,
  132801. };
  132802. static float _vq_quantthresh__44c6_s_p9_2[] = {
  132803. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  132804. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  132805. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132806. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132807. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  132808. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  132809. };
  132810. static long _vq_quantmap__44c6_s_p9_2[] = {
  132811. 47, 45, 43, 41, 39, 37, 35, 33,
  132812. 31, 29, 27, 25, 23, 21, 19, 17,
  132813. 15, 13, 11, 9, 7, 5, 3, 1,
  132814. 0, 2, 4, 6, 8, 10, 12, 14,
  132815. 16, 18, 20, 22, 24, 26, 28, 30,
  132816. 32, 34, 36, 38, 40, 42, 44, 46,
  132817. 48,
  132818. };
  132819. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  132820. _vq_quantthresh__44c6_s_p9_2,
  132821. _vq_quantmap__44c6_s_p9_2,
  132822. 49,
  132823. 49
  132824. };
  132825. static static_codebook _44c6_s_p9_2 = {
  132826. 1, 49,
  132827. _vq_lengthlist__44c6_s_p9_2,
  132828. 1, -526909440, 1611661312, 6, 0,
  132829. _vq_quantlist__44c6_s_p9_2,
  132830. NULL,
  132831. &_vq_auxt__44c6_s_p9_2,
  132832. NULL,
  132833. 0
  132834. };
  132835. static long _huff_lengthlist__44c6_s_short[] = {
  132836. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  132837. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  132838. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  132839. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  132840. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  132841. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  132842. 9,10,17,18,
  132843. };
  132844. static static_codebook _huff_book__44c6_s_short = {
  132845. 2, 100,
  132846. _huff_lengthlist__44c6_s_short,
  132847. 0, 0, 0, 0, 0,
  132848. NULL,
  132849. NULL,
  132850. NULL,
  132851. NULL,
  132852. 0
  132853. };
  132854. static long _huff_lengthlist__44c7_s_long[] = {
  132855. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  132856. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  132857. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  132858. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  132859. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  132860. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  132861. 11,10,10,12,
  132862. };
  132863. static static_codebook _huff_book__44c7_s_long = {
  132864. 2, 100,
  132865. _huff_lengthlist__44c7_s_long,
  132866. 0, 0, 0, 0, 0,
  132867. NULL,
  132868. NULL,
  132869. NULL,
  132870. NULL,
  132871. 0
  132872. };
  132873. static long _vq_quantlist__44c7_s_p1_0[] = {
  132874. 1,
  132875. 0,
  132876. 2,
  132877. };
  132878. static long _vq_lengthlist__44c7_s_p1_0[] = {
  132879. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132880. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132881. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132882. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132883. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  132884. 8,
  132885. };
  132886. static float _vq_quantthresh__44c7_s_p1_0[] = {
  132887. -0.5, 0.5,
  132888. };
  132889. static long _vq_quantmap__44c7_s_p1_0[] = {
  132890. 1, 0, 2,
  132891. };
  132892. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  132893. _vq_quantthresh__44c7_s_p1_0,
  132894. _vq_quantmap__44c7_s_p1_0,
  132895. 3,
  132896. 3
  132897. };
  132898. static static_codebook _44c7_s_p1_0 = {
  132899. 4, 81,
  132900. _vq_lengthlist__44c7_s_p1_0,
  132901. 1, -535822336, 1611661312, 2, 0,
  132902. _vq_quantlist__44c7_s_p1_0,
  132903. NULL,
  132904. &_vq_auxt__44c7_s_p1_0,
  132905. NULL,
  132906. 0
  132907. };
  132908. static long _vq_quantlist__44c7_s_p2_0[] = {
  132909. 2,
  132910. 1,
  132911. 3,
  132912. 0,
  132913. 4,
  132914. };
  132915. static long _vq_lengthlist__44c7_s_p2_0[] = {
  132916. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132917. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132918. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132919. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132920. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  132921. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132922. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  132923. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132925. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132926. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132927. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132928. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132929. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132930. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  132931. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132933. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132934. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  132935. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  132936. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  132937. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  132938. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132939. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132941. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  132942. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132943. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132944. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  132945. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132946. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  132947. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132952. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  132953. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  132954. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132955. 13,
  132956. };
  132957. static float _vq_quantthresh__44c7_s_p2_0[] = {
  132958. -1.5, -0.5, 0.5, 1.5,
  132959. };
  132960. static long _vq_quantmap__44c7_s_p2_0[] = {
  132961. 3, 1, 0, 2, 4,
  132962. };
  132963. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  132964. _vq_quantthresh__44c7_s_p2_0,
  132965. _vq_quantmap__44c7_s_p2_0,
  132966. 5,
  132967. 5
  132968. };
  132969. static static_codebook _44c7_s_p2_0 = {
  132970. 4, 625,
  132971. _vq_lengthlist__44c7_s_p2_0,
  132972. 1, -533725184, 1611661312, 3, 0,
  132973. _vq_quantlist__44c7_s_p2_0,
  132974. NULL,
  132975. &_vq_auxt__44c7_s_p2_0,
  132976. NULL,
  132977. 0
  132978. };
  132979. static long _vq_quantlist__44c7_s_p3_0[] = {
  132980. 4,
  132981. 3,
  132982. 5,
  132983. 2,
  132984. 6,
  132985. 1,
  132986. 7,
  132987. 0,
  132988. 8,
  132989. };
  132990. static long _vq_lengthlist__44c7_s_p3_0[] = {
  132991. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132992. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  132993. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  132994. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  132995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132996. 0,
  132997. };
  132998. static float _vq_quantthresh__44c7_s_p3_0[] = {
  132999. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133000. };
  133001. static long _vq_quantmap__44c7_s_p3_0[] = {
  133002. 7, 5, 3, 1, 0, 2, 4, 6,
  133003. 8,
  133004. };
  133005. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133006. _vq_quantthresh__44c7_s_p3_0,
  133007. _vq_quantmap__44c7_s_p3_0,
  133008. 9,
  133009. 9
  133010. };
  133011. static static_codebook _44c7_s_p3_0 = {
  133012. 2, 81,
  133013. _vq_lengthlist__44c7_s_p3_0,
  133014. 1, -531628032, 1611661312, 4, 0,
  133015. _vq_quantlist__44c7_s_p3_0,
  133016. NULL,
  133017. &_vq_auxt__44c7_s_p3_0,
  133018. NULL,
  133019. 0
  133020. };
  133021. static long _vq_quantlist__44c7_s_p4_0[] = {
  133022. 8,
  133023. 7,
  133024. 9,
  133025. 6,
  133026. 10,
  133027. 5,
  133028. 11,
  133029. 4,
  133030. 12,
  133031. 3,
  133032. 13,
  133033. 2,
  133034. 14,
  133035. 1,
  133036. 15,
  133037. 0,
  133038. 16,
  133039. };
  133040. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133041. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133042. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133043. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133044. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133045. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133046. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133047. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133048. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133049. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133050. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133059. 0,
  133060. };
  133061. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133062. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133063. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133064. };
  133065. static long _vq_quantmap__44c7_s_p4_0[] = {
  133066. 15, 13, 11, 9, 7, 5, 3, 1,
  133067. 0, 2, 4, 6, 8, 10, 12, 14,
  133068. 16,
  133069. };
  133070. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133071. _vq_quantthresh__44c7_s_p4_0,
  133072. _vq_quantmap__44c7_s_p4_0,
  133073. 17,
  133074. 17
  133075. };
  133076. static static_codebook _44c7_s_p4_0 = {
  133077. 2, 289,
  133078. _vq_lengthlist__44c7_s_p4_0,
  133079. 1, -529530880, 1611661312, 5, 0,
  133080. _vq_quantlist__44c7_s_p4_0,
  133081. NULL,
  133082. &_vq_auxt__44c7_s_p4_0,
  133083. NULL,
  133084. 0
  133085. };
  133086. static long _vq_quantlist__44c7_s_p5_0[] = {
  133087. 1,
  133088. 0,
  133089. 2,
  133090. };
  133091. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133092. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133093. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133094. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133095. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133096. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133097. 12,
  133098. };
  133099. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133100. -5.5, 5.5,
  133101. };
  133102. static long _vq_quantmap__44c7_s_p5_0[] = {
  133103. 1, 0, 2,
  133104. };
  133105. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133106. _vq_quantthresh__44c7_s_p5_0,
  133107. _vq_quantmap__44c7_s_p5_0,
  133108. 3,
  133109. 3
  133110. };
  133111. static static_codebook _44c7_s_p5_0 = {
  133112. 4, 81,
  133113. _vq_lengthlist__44c7_s_p5_0,
  133114. 1, -529137664, 1618345984, 2, 0,
  133115. _vq_quantlist__44c7_s_p5_0,
  133116. NULL,
  133117. &_vq_auxt__44c7_s_p5_0,
  133118. NULL,
  133119. 0
  133120. };
  133121. static long _vq_quantlist__44c7_s_p5_1[] = {
  133122. 5,
  133123. 4,
  133124. 6,
  133125. 3,
  133126. 7,
  133127. 2,
  133128. 8,
  133129. 1,
  133130. 9,
  133131. 0,
  133132. 10,
  133133. };
  133134. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133135. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133136. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133137. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133138. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133139. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133140. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133141. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133142. 11,11,11, 7, 7, 8, 8, 8, 8,
  133143. };
  133144. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133145. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133146. 3.5, 4.5,
  133147. };
  133148. static long _vq_quantmap__44c7_s_p5_1[] = {
  133149. 9, 7, 5, 3, 1, 0, 2, 4,
  133150. 6, 8, 10,
  133151. };
  133152. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133153. _vq_quantthresh__44c7_s_p5_1,
  133154. _vq_quantmap__44c7_s_p5_1,
  133155. 11,
  133156. 11
  133157. };
  133158. static static_codebook _44c7_s_p5_1 = {
  133159. 2, 121,
  133160. _vq_lengthlist__44c7_s_p5_1,
  133161. 1, -531365888, 1611661312, 4, 0,
  133162. _vq_quantlist__44c7_s_p5_1,
  133163. NULL,
  133164. &_vq_auxt__44c7_s_p5_1,
  133165. NULL,
  133166. 0
  133167. };
  133168. static long _vq_quantlist__44c7_s_p6_0[] = {
  133169. 6,
  133170. 5,
  133171. 7,
  133172. 4,
  133173. 8,
  133174. 3,
  133175. 9,
  133176. 2,
  133177. 10,
  133178. 1,
  133179. 11,
  133180. 0,
  133181. 12,
  133182. };
  133183. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133184. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133185. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133186. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133187. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133188. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133189. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133194. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133195. };
  133196. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133197. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133198. 12.5, 17.5, 22.5, 27.5,
  133199. };
  133200. static long _vq_quantmap__44c7_s_p6_0[] = {
  133201. 11, 9, 7, 5, 3, 1, 0, 2,
  133202. 4, 6, 8, 10, 12,
  133203. };
  133204. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133205. _vq_quantthresh__44c7_s_p6_0,
  133206. _vq_quantmap__44c7_s_p6_0,
  133207. 13,
  133208. 13
  133209. };
  133210. static static_codebook _44c7_s_p6_0 = {
  133211. 2, 169,
  133212. _vq_lengthlist__44c7_s_p6_0,
  133213. 1, -526516224, 1616117760, 4, 0,
  133214. _vq_quantlist__44c7_s_p6_0,
  133215. NULL,
  133216. &_vq_auxt__44c7_s_p6_0,
  133217. NULL,
  133218. 0
  133219. };
  133220. static long _vq_quantlist__44c7_s_p6_1[] = {
  133221. 2,
  133222. 1,
  133223. 3,
  133224. 0,
  133225. 4,
  133226. };
  133227. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133228. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133229. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133230. };
  133231. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133232. -1.5, -0.5, 0.5, 1.5,
  133233. };
  133234. static long _vq_quantmap__44c7_s_p6_1[] = {
  133235. 3, 1, 0, 2, 4,
  133236. };
  133237. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133238. _vq_quantthresh__44c7_s_p6_1,
  133239. _vq_quantmap__44c7_s_p6_1,
  133240. 5,
  133241. 5
  133242. };
  133243. static static_codebook _44c7_s_p6_1 = {
  133244. 2, 25,
  133245. _vq_lengthlist__44c7_s_p6_1,
  133246. 1, -533725184, 1611661312, 3, 0,
  133247. _vq_quantlist__44c7_s_p6_1,
  133248. NULL,
  133249. &_vq_auxt__44c7_s_p6_1,
  133250. NULL,
  133251. 0
  133252. };
  133253. static long _vq_quantlist__44c7_s_p7_0[] = {
  133254. 6,
  133255. 5,
  133256. 7,
  133257. 4,
  133258. 8,
  133259. 3,
  133260. 9,
  133261. 2,
  133262. 10,
  133263. 1,
  133264. 11,
  133265. 0,
  133266. 12,
  133267. };
  133268. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133269. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133270. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133271. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133272. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133273. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133274. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133275. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133276. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133277. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133278. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133279. 19,13,13,13,13,14,14,15,15,
  133280. };
  133281. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133282. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133283. 27.5, 38.5, 49.5, 60.5,
  133284. };
  133285. static long _vq_quantmap__44c7_s_p7_0[] = {
  133286. 11, 9, 7, 5, 3, 1, 0, 2,
  133287. 4, 6, 8, 10, 12,
  133288. };
  133289. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133290. _vq_quantthresh__44c7_s_p7_0,
  133291. _vq_quantmap__44c7_s_p7_0,
  133292. 13,
  133293. 13
  133294. };
  133295. static static_codebook _44c7_s_p7_0 = {
  133296. 2, 169,
  133297. _vq_lengthlist__44c7_s_p7_0,
  133298. 1, -523206656, 1618345984, 4, 0,
  133299. _vq_quantlist__44c7_s_p7_0,
  133300. NULL,
  133301. &_vq_auxt__44c7_s_p7_0,
  133302. NULL,
  133303. 0
  133304. };
  133305. static long _vq_quantlist__44c7_s_p7_1[] = {
  133306. 5,
  133307. 4,
  133308. 6,
  133309. 3,
  133310. 7,
  133311. 2,
  133312. 8,
  133313. 1,
  133314. 9,
  133315. 0,
  133316. 10,
  133317. };
  133318. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133319. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133320. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133321. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133322. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133323. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133324. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133325. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133326. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133327. };
  133328. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133329. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133330. 3.5, 4.5,
  133331. };
  133332. static long _vq_quantmap__44c7_s_p7_1[] = {
  133333. 9, 7, 5, 3, 1, 0, 2, 4,
  133334. 6, 8, 10,
  133335. };
  133336. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133337. _vq_quantthresh__44c7_s_p7_1,
  133338. _vq_quantmap__44c7_s_p7_1,
  133339. 11,
  133340. 11
  133341. };
  133342. static static_codebook _44c7_s_p7_1 = {
  133343. 2, 121,
  133344. _vq_lengthlist__44c7_s_p7_1,
  133345. 1, -531365888, 1611661312, 4, 0,
  133346. _vq_quantlist__44c7_s_p7_1,
  133347. NULL,
  133348. &_vq_auxt__44c7_s_p7_1,
  133349. NULL,
  133350. 0
  133351. };
  133352. static long _vq_quantlist__44c7_s_p8_0[] = {
  133353. 7,
  133354. 6,
  133355. 8,
  133356. 5,
  133357. 9,
  133358. 4,
  133359. 10,
  133360. 3,
  133361. 11,
  133362. 2,
  133363. 12,
  133364. 1,
  133365. 13,
  133366. 0,
  133367. 14,
  133368. };
  133369. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133370. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133371. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133372. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133373. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133374. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133375. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133376. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133377. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133378. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133379. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133380. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133381. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133382. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133383. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133384. 14,
  133385. };
  133386. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133387. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133388. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133389. };
  133390. static long _vq_quantmap__44c7_s_p8_0[] = {
  133391. 13, 11, 9, 7, 5, 3, 1, 0,
  133392. 2, 4, 6, 8, 10, 12, 14,
  133393. };
  133394. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133395. _vq_quantthresh__44c7_s_p8_0,
  133396. _vq_quantmap__44c7_s_p8_0,
  133397. 15,
  133398. 15
  133399. };
  133400. static static_codebook _44c7_s_p8_0 = {
  133401. 2, 225,
  133402. _vq_lengthlist__44c7_s_p8_0,
  133403. 1, -520986624, 1620377600, 4, 0,
  133404. _vq_quantlist__44c7_s_p8_0,
  133405. NULL,
  133406. &_vq_auxt__44c7_s_p8_0,
  133407. NULL,
  133408. 0
  133409. };
  133410. static long _vq_quantlist__44c7_s_p8_1[] = {
  133411. 10,
  133412. 9,
  133413. 11,
  133414. 8,
  133415. 12,
  133416. 7,
  133417. 13,
  133418. 6,
  133419. 14,
  133420. 5,
  133421. 15,
  133422. 4,
  133423. 16,
  133424. 3,
  133425. 17,
  133426. 2,
  133427. 18,
  133428. 1,
  133429. 19,
  133430. 0,
  133431. 20,
  133432. };
  133433. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133434. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133435. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133436. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133437. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133438. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133439. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133440. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133441. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133442. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133443. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133444. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133445. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133446. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133447. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133448. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133449. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133450. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133451. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133452. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133453. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133454. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133455. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133456. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133457. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133458. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133459. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133460. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133461. 10,10,10,10,10,10,10,10,10,
  133462. };
  133463. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133464. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133465. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133466. 6.5, 7.5, 8.5, 9.5,
  133467. };
  133468. static long _vq_quantmap__44c7_s_p8_1[] = {
  133469. 19, 17, 15, 13, 11, 9, 7, 5,
  133470. 3, 1, 0, 2, 4, 6, 8, 10,
  133471. 12, 14, 16, 18, 20,
  133472. };
  133473. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133474. _vq_quantthresh__44c7_s_p8_1,
  133475. _vq_quantmap__44c7_s_p8_1,
  133476. 21,
  133477. 21
  133478. };
  133479. static static_codebook _44c7_s_p8_1 = {
  133480. 2, 441,
  133481. _vq_lengthlist__44c7_s_p8_1,
  133482. 1, -529268736, 1611661312, 5, 0,
  133483. _vq_quantlist__44c7_s_p8_1,
  133484. NULL,
  133485. &_vq_auxt__44c7_s_p8_1,
  133486. NULL,
  133487. 0
  133488. };
  133489. static long _vq_quantlist__44c7_s_p9_0[] = {
  133490. 6,
  133491. 5,
  133492. 7,
  133493. 4,
  133494. 8,
  133495. 3,
  133496. 9,
  133497. 2,
  133498. 10,
  133499. 1,
  133500. 11,
  133501. 0,
  133502. 12,
  133503. };
  133504. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133505. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133506. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133507. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133508. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133509. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133510. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133515. 11,11,11,11,11,11,11,11,11,
  133516. };
  133517. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133518. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133519. 1592.5, 2229.5, 2866.5, 3503.5,
  133520. };
  133521. static long _vq_quantmap__44c7_s_p9_0[] = {
  133522. 11, 9, 7, 5, 3, 1, 0, 2,
  133523. 4, 6, 8, 10, 12,
  133524. };
  133525. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133526. _vq_quantthresh__44c7_s_p9_0,
  133527. _vq_quantmap__44c7_s_p9_0,
  133528. 13,
  133529. 13
  133530. };
  133531. static static_codebook _44c7_s_p9_0 = {
  133532. 2, 169,
  133533. _vq_lengthlist__44c7_s_p9_0,
  133534. 1, -511845376, 1630791680, 4, 0,
  133535. _vq_quantlist__44c7_s_p9_0,
  133536. NULL,
  133537. &_vq_auxt__44c7_s_p9_0,
  133538. NULL,
  133539. 0
  133540. };
  133541. static long _vq_quantlist__44c7_s_p9_1[] = {
  133542. 6,
  133543. 5,
  133544. 7,
  133545. 4,
  133546. 8,
  133547. 3,
  133548. 9,
  133549. 2,
  133550. 10,
  133551. 1,
  133552. 11,
  133553. 0,
  133554. 12,
  133555. };
  133556. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133557. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133558. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133559. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133560. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133561. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133562. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133563. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133564. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133565. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133566. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133567. 15,11,11,10,10,12,12,12,12,
  133568. };
  133569. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133570. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133571. 122.5, 171.5, 220.5, 269.5,
  133572. };
  133573. static long _vq_quantmap__44c7_s_p9_1[] = {
  133574. 11, 9, 7, 5, 3, 1, 0, 2,
  133575. 4, 6, 8, 10, 12,
  133576. };
  133577. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133578. _vq_quantthresh__44c7_s_p9_1,
  133579. _vq_quantmap__44c7_s_p9_1,
  133580. 13,
  133581. 13
  133582. };
  133583. static static_codebook _44c7_s_p9_1 = {
  133584. 2, 169,
  133585. _vq_lengthlist__44c7_s_p9_1,
  133586. 1, -518889472, 1622704128, 4, 0,
  133587. _vq_quantlist__44c7_s_p9_1,
  133588. NULL,
  133589. &_vq_auxt__44c7_s_p9_1,
  133590. NULL,
  133591. 0
  133592. };
  133593. static long _vq_quantlist__44c7_s_p9_2[] = {
  133594. 24,
  133595. 23,
  133596. 25,
  133597. 22,
  133598. 26,
  133599. 21,
  133600. 27,
  133601. 20,
  133602. 28,
  133603. 19,
  133604. 29,
  133605. 18,
  133606. 30,
  133607. 17,
  133608. 31,
  133609. 16,
  133610. 32,
  133611. 15,
  133612. 33,
  133613. 14,
  133614. 34,
  133615. 13,
  133616. 35,
  133617. 12,
  133618. 36,
  133619. 11,
  133620. 37,
  133621. 10,
  133622. 38,
  133623. 9,
  133624. 39,
  133625. 8,
  133626. 40,
  133627. 7,
  133628. 41,
  133629. 6,
  133630. 42,
  133631. 5,
  133632. 43,
  133633. 4,
  133634. 44,
  133635. 3,
  133636. 45,
  133637. 2,
  133638. 46,
  133639. 1,
  133640. 47,
  133641. 0,
  133642. 48,
  133643. };
  133644. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133645. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133646. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133647. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133648. 7,
  133649. };
  133650. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133651. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133652. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133653. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133654. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133655. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133656. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133657. };
  133658. static long _vq_quantmap__44c7_s_p9_2[] = {
  133659. 47, 45, 43, 41, 39, 37, 35, 33,
  133660. 31, 29, 27, 25, 23, 21, 19, 17,
  133661. 15, 13, 11, 9, 7, 5, 3, 1,
  133662. 0, 2, 4, 6, 8, 10, 12, 14,
  133663. 16, 18, 20, 22, 24, 26, 28, 30,
  133664. 32, 34, 36, 38, 40, 42, 44, 46,
  133665. 48,
  133666. };
  133667. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  133668. _vq_quantthresh__44c7_s_p9_2,
  133669. _vq_quantmap__44c7_s_p9_2,
  133670. 49,
  133671. 49
  133672. };
  133673. static static_codebook _44c7_s_p9_2 = {
  133674. 1, 49,
  133675. _vq_lengthlist__44c7_s_p9_2,
  133676. 1, -526909440, 1611661312, 6, 0,
  133677. _vq_quantlist__44c7_s_p9_2,
  133678. NULL,
  133679. &_vq_auxt__44c7_s_p9_2,
  133680. NULL,
  133681. 0
  133682. };
  133683. static long _huff_lengthlist__44c7_s_short[] = {
  133684. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  133685. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  133686. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  133687. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  133688. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  133689. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  133690. 10, 9,11,14,
  133691. };
  133692. static static_codebook _huff_book__44c7_s_short = {
  133693. 2, 100,
  133694. _huff_lengthlist__44c7_s_short,
  133695. 0, 0, 0, 0, 0,
  133696. NULL,
  133697. NULL,
  133698. NULL,
  133699. NULL,
  133700. 0
  133701. };
  133702. static long _huff_lengthlist__44c8_s_long[] = {
  133703. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  133704. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  133705. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  133706. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  133707. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  133708. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  133709. 11, 9, 9,10,
  133710. };
  133711. static static_codebook _huff_book__44c8_s_long = {
  133712. 2, 100,
  133713. _huff_lengthlist__44c8_s_long,
  133714. 0, 0, 0, 0, 0,
  133715. NULL,
  133716. NULL,
  133717. NULL,
  133718. NULL,
  133719. 0
  133720. };
  133721. static long _vq_quantlist__44c8_s_p1_0[] = {
  133722. 1,
  133723. 0,
  133724. 2,
  133725. };
  133726. static long _vq_lengthlist__44c8_s_p1_0[] = {
  133727. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  133728. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133729. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133730. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133731. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133732. 8,
  133733. };
  133734. static float _vq_quantthresh__44c8_s_p1_0[] = {
  133735. -0.5, 0.5,
  133736. };
  133737. static long _vq_quantmap__44c8_s_p1_0[] = {
  133738. 1, 0, 2,
  133739. };
  133740. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  133741. _vq_quantthresh__44c8_s_p1_0,
  133742. _vq_quantmap__44c8_s_p1_0,
  133743. 3,
  133744. 3
  133745. };
  133746. static static_codebook _44c8_s_p1_0 = {
  133747. 4, 81,
  133748. _vq_lengthlist__44c8_s_p1_0,
  133749. 1, -535822336, 1611661312, 2, 0,
  133750. _vq_quantlist__44c8_s_p1_0,
  133751. NULL,
  133752. &_vq_auxt__44c8_s_p1_0,
  133753. NULL,
  133754. 0
  133755. };
  133756. static long _vq_quantlist__44c8_s_p2_0[] = {
  133757. 2,
  133758. 1,
  133759. 3,
  133760. 0,
  133761. 4,
  133762. };
  133763. static long _vq_lengthlist__44c8_s_p2_0[] = {
  133764. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133765. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133766. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133767. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  133768. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133769. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  133770. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  133771. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133773. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133774. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  133775. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133776. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  133777. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  133778. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  133779. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  133780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133781. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  133782. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  133783. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  133784. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  133785. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  133786. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  133787. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133789. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133790. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  133791. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133792. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  133793. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  133794. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  133795. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133800. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  133801. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133802. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  133803. 13,
  133804. };
  133805. static float _vq_quantthresh__44c8_s_p2_0[] = {
  133806. -1.5, -0.5, 0.5, 1.5,
  133807. };
  133808. static long _vq_quantmap__44c8_s_p2_0[] = {
  133809. 3, 1, 0, 2, 4,
  133810. };
  133811. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  133812. _vq_quantthresh__44c8_s_p2_0,
  133813. _vq_quantmap__44c8_s_p2_0,
  133814. 5,
  133815. 5
  133816. };
  133817. static static_codebook _44c8_s_p2_0 = {
  133818. 4, 625,
  133819. _vq_lengthlist__44c8_s_p2_0,
  133820. 1, -533725184, 1611661312, 3, 0,
  133821. _vq_quantlist__44c8_s_p2_0,
  133822. NULL,
  133823. &_vq_auxt__44c8_s_p2_0,
  133824. NULL,
  133825. 0
  133826. };
  133827. static long _vq_quantlist__44c8_s_p3_0[] = {
  133828. 4,
  133829. 3,
  133830. 5,
  133831. 2,
  133832. 6,
  133833. 1,
  133834. 7,
  133835. 0,
  133836. 8,
  133837. };
  133838. static long _vq_lengthlist__44c8_s_p3_0[] = {
  133839. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133840. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133841. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133842. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133844. 0,
  133845. };
  133846. static float _vq_quantthresh__44c8_s_p3_0[] = {
  133847. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133848. };
  133849. static long _vq_quantmap__44c8_s_p3_0[] = {
  133850. 7, 5, 3, 1, 0, 2, 4, 6,
  133851. 8,
  133852. };
  133853. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  133854. _vq_quantthresh__44c8_s_p3_0,
  133855. _vq_quantmap__44c8_s_p3_0,
  133856. 9,
  133857. 9
  133858. };
  133859. static static_codebook _44c8_s_p3_0 = {
  133860. 2, 81,
  133861. _vq_lengthlist__44c8_s_p3_0,
  133862. 1, -531628032, 1611661312, 4, 0,
  133863. _vq_quantlist__44c8_s_p3_0,
  133864. NULL,
  133865. &_vq_auxt__44c8_s_p3_0,
  133866. NULL,
  133867. 0
  133868. };
  133869. static long _vq_quantlist__44c8_s_p4_0[] = {
  133870. 8,
  133871. 7,
  133872. 9,
  133873. 6,
  133874. 10,
  133875. 5,
  133876. 11,
  133877. 4,
  133878. 12,
  133879. 3,
  133880. 13,
  133881. 2,
  133882. 14,
  133883. 1,
  133884. 15,
  133885. 0,
  133886. 16,
  133887. };
  133888. static long _vq_lengthlist__44c8_s_p4_0[] = {
  133889. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133890. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  133891. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133892. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  133893. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  133894. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133895. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133896. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133897. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133898. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133907. 0,
  133908. };
  133909. static float _vq_quantthresh__44c8_s_p4_0[] = {
  133910. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133911. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133912. };
  133913. static long _vq_quantmap__44c8_s_p4_0[] = {
  133914. 15, 13, 11, 9, 7, 5, 3, 1,
  133915. 0, 2, 4, 6, 8, 10, 12, 14,
  133916. 16,
  133917. };
  133918. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  133919. _vq_quantthresh__44c8_s_p4_0,
  133920. _vq_quantmap__44c8_s_p4_0,
  133921. 17,
  133922. 17
  133923. };
  133924. static static_codebook _44c8_s_p4_0 = {
  133925. 2, 289,
  133926. _vq_lengthlist__44c8_s_p4_0,
  133927. 1, -529530880, 1611661312, 5, 0,
  133928. _vq_quantlist__44c8_s_p4_0,
  133929. NULL,
  133930. &_vq_auxt__44c8_s_p4_0,
  133931. NULL,
  133932. 0
  133933. };
  133934. static long _vq_quantlist__44c8_s_p5_0[] = {
  133935. 1,
  133936. 0,
  133937. 2,
  133938. };
  133939. static long _vq_lengthlist__44c8_s_p5_0[] = {
  133940. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  133941. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133942. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133943. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  133944. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  133945. 12,
  133946. };
  133947. static float _vq_quantthresh__44c8_s_p5_0[] = {
  133948. -5.5, 5.5,
  133949. };
  133950. static long _vq_quantmap__44c8_s_p5_0[] = {
  133951. 1, 0, 2,
  133952. };
  133953. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  133954. _vq_quantthresh__44c8_s_p5_0,
  133955. _vq_quantmap__44c8_s_p5_0,
  133956. 3,
  133957. 3
  133958. };
  133959. static static_codebook _44c8_s_p5_0 = {
  133960. 4, 81,
  133961. _vq_lengthlist__44c8_s_p5_0,
  133962. 1, -529137664, 1618345984, 2, 0,
  133963. _vq_quantlist__44c8_s_p5_0,
  133964. NULL,
  133965. &_vq_auxt__44c8_s_p5_0,
  133966. NULL,
  133967. 0
  133968. };
  133969. static long _vq_quantlist__44c8_s_p5_1[] = {
  133970. 5,
  133971. 4,
  133972. 6,
  133973. 3,
  133974. 7,
  133975. 2,
  133976. 8,
  133977. 1,
  133978. 9,
  133979. 0,
  133980. 10,
  133981. };
  133982. static long _vq_lengthlist__44c8_s_p5_1[] = {
  133983. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  133984. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133985. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  133986. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  133987. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  133988. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  133989. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  133990. 11,11,11, 7, 7, 7, 7, 8, 8,
  133991. };
  133992. static float _vq_quantthresh__44c8_s_p5_1[] = {
  133993. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133994. 3.5, 4.5,
  133995. };
  133996. static long _vq_quantmap__44c8_s_p5_1[] = {
  133997. 9, 7, 5, 3, 1, 0, 2, 4,
  133998. 6, 8, 10,
  133999. };
  134000. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134001. _vq_quantthresh__44c8_s_p5_1,
  134002. _vq_quantmap__44c8_s_p5_1,
  134003. 11,
  134004. 11
  134005. };
  134006. static static_codebook _44c8_s_p5_1 = {
  134007. 2, 121,
  134008. _vq_lengthlist__44c8_s_p5_1,
  134009. 1, -531365888, 1611661312, 4, 0,
  134010. _vq_quantlist__44c8_s_p5_1,
  134011. NULL,
  134012. &_vq_auxt__44c8_s_p5_1,
  134013. NULL,
  134014. 0
  134015. };
  134016. static long _vq_quantlist__44c8_s_p6_0[] = {
  134017. 6,
  134018. 5,
  134019. 7,
  134020. 4,
  134021. 8,
  134022. 3,
  134023. 9,
  134024. 2,
  134025. 10,
  134026. 1,
  134027. 11,
  134028. 0,
  134029. 12,
  134030. };
  134031. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134032. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134033. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134034. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134035. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134036. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134037. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134042. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134043. };
  134044. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134045. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134046. 12.5, 17.5, 22.5, 27.5,
  134047. };
  134048. static long _vq_quantmap__44c8_s_p6_0[] = {
  134049. 11, 9, 7, 5, 3, 1, 0, 2,
  134050. 4, 6, 8, 10, 12,
  134051. };
  134052. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134053. _vq_quantthresh__44c8_s_p6_0,
  134054. _vq_quantmap__44c8_s_p6_0,
  134055. 13,
  134056. 13
  134057. };
  134058. static static_codebook _44c8_s_p6_0 = {
  134059. 2, 169,
  134060. _vq_lengthlist__44c8_s_p6_0,
  134061. 1, -526516224, 1616117760, 4, 0,
  134062. _vq_quantlist__44c8_s_p6_0,
  134063. NULL,
  134064. &_vq_auxt__44c8_s_p6_0,
  134065. NULL,
  134066. 0
  134067. };
  134068. static long _vq_quantlist__44c8_s_p6_1[] = {
  134069. 2,
  134070. 1,
  134071. 3,
  134072. 0,
  134073. 4,
  134074. };
  134075. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134076. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134077. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134078. };
  134079. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134080. -1.5, -0.5, 0.5, 1.5,
  134081. };
  134082. static long _vq_quantmap__44c8_s_p6_1[] = {
  134083. 3, 1, 0, 2, 4,
  134084. };
  134085. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134086. _vq_quantthresh__44c8_s_p6_1,
  134087. _vq_quantmap__44c8_s_p6_1,
  134088. 5,
  134089. 5
  134090. };
  134091. static static_codebook _44c8_s_p6_1 = {
  134092. 2, 25,
  134093. _vq_lengthlist__44c8_s_p6_1,
  134094. 1, -533725184, 1611661312, 3, 0,
  134095. _vq_quantlist__44c8_s_p6_1,
  134096. NULL,
  134097. &_vq_auxt__44c8_s_p6_1,
  134098. NULL,
  134099. 0
  134100. };
  134101. static long _vq_quantlist__44c8_s_p7_0[] = {
  134102. 6,
  134103. 5,
  134104. 7,
  134105. 4,
  134106. 8,
  134107. 3,
  134108. 9,
  134109. 2,
  134110. 10,
  134111. 1,
  134112. 11,
  134113. 0,
  134114. 12,
  134115. };
  134116. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134117. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134118. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134119. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134120. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134121. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134122. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134123. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134124. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134125. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134126. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134127. 20,13,13,13,13,14,13,15,15,
  134128. };
  134129. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134130. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134131. 27.5, 38.5, 49.5, 60.5,
  134132. };
  134133. static long _vq_quantmap__44c8_s_p7_0[] = {
  134134. 11, 9, 7, 5, 3, 1, 0, 2,
  134135. 4, 6, 8, 10, 12,
  134136. };
  134137. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134138. _vq_quantthresh__44c8_s_p7_0,
  134139. _vq_quantmap__44c8_s_p7_0,
  134140. 13,
  134141. 13
  134142. };
  134143. static static_codebook _44c8_s_p7_0 = {
  134144. 2, 169,
  134145. _vq_lengthlist__44c8_s_p7_0,
  134146. 1, -523206656, 1618345984, 4, 0,
  134147. _vq_quantlist__44c8_s_p7_0,
  134148. NULL,
  134149. &_vq_auxt__44c8_s_p7_0,
  134150. NULL,
  134151. 0
  134152. };
  134153. static long _vq_quantlist__44c8_s_p7_1[] = {
  134154. 5,
  134155. 4,
  134156. 6,
  134157. 3,
  134158. 7,
  134159. 2,
  134160. 8,
  134161. 1,
  134162. 9,
  134163. 0,
  134164. 10,
  134165. };
  134166. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134167. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134168. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134169. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134170. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134171. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134172. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134173. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134174. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134175. };
  134176. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134177. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134178. 3.5, 4.5,
  134179. };
  134180. static long _vq_quantmap__44c8_s_p7_1[] = {
  134181. 9, 7, 5, 3, 1, 0, 2, 4,
  134182. 6, 8, 10,
  134183. };
  134184. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134185. _vq_quantthresh__44c8_s_p7_1,
  134186. _vq_quantmap__44c8_s_p7_1,
  134187. 11,
  134188. 11
  134189. };
  134190. static static_codebook _44c8_s_p7_1 = {
  134191. 2, 121,
  134192. _vq_lengthlist__44c8_s_p7_1,
  134193. 1, -531365888, 1611661312, 4, 0,
  134194. _vq_quantlist__44c8_s_p7_1,
  134195. NULL,
  134196. &_vq_auxt__44c8_s_p7_1,
  134197. NULL,
  134198. 0
  134199. };
  134200. static long _vq_quantlist__44c8_s_p8_0[] = {
  134201. 7,
  134202. 6,
  134203. 8,
  134204. 5,
  134205. 9,
  134206. 4,
  134207. 10,
  134208. 3,
  134209. 11,
  134210. 2,
  134211. 12,
  134212. 1,
  134213. 13,
  134214. 0,
  134215. 14,
  134216. };
  134217. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134218. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134219. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134220. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134221. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134222. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134223. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134224. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134225. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134226. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134227. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134228. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134229. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134230. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134231. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134232. 15,
  134233. };
  134234. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134235. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134236. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134237. };
  134238. static long _vq_quantmap__44c8_s_p8_0[] = {
  134239. 13, 11, 9, 7, 5, 3, 1, 0,
  134240. 2, 4, 6, 8, 10, 12, 14,
  134241. };
  134242. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134243. _vq_quantthresh__44c8_s_p8_0,
  134244. _vq_quantmap__44c8_s_p8_0,
  134245. 15,
  134246. 15
  134247. };
  134248. static static_codebook _44c8_s_p8_0 = {
  134249. 2, 225,
  134250. _vq_lengthlist__44c8_s_p8_0,
  134251. 1, -520986624, 1620377600, 4, 0,
  134252. _vq_quantlist__44c8_s_p8_0,
  134253. NULL,
  134254. &_vq_auxt__44c8_s_p8_0,
  134255. NULL,
  134256. 0
  134257. };
  134258. static long _vq_quantlist__44c8_s_p8_1[] = {
  134259. 10,
  134260. 9,
  134261. 11,
  134262. 8,
  134263. 12,
  134264. 7,
  134265. 13,
  134266. 6,
  134267. 14,
  134268. 5,
  134269. 15,
  134270. 4,
  134271. 16,
  134272. 3,
  134273. 17,
  134274. 2,
  134275. 18,
  134276. 1,
  134277. 19,
  134278. 0,
  134279. 20,
  134280. };
  134281. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134282. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134283. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134284. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134285. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134286. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134287. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134288. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134289. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134290. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134291. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134292. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134293. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134294. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134295. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134296. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134297. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134298. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134299. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134300. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134301. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134302. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134303. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134304. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134305. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134306. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134307. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134308. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134309. 10, 9, 9,10,10, 9,10, 9, 9,
  134310. };
  134311. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134312. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134313. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134314. 6.5, 7.5, 8.5, 9.5,
  134315. };
  134316. static long _vq_quantmap__44c8_s_p8_1[] = {
  134317. 19, 17, 15, 13, 11, 9, 7, 5,
  134318. 3, 1, 0, 2, 4, 6, 8, 10,
  134319. 12, 14, 16, 18, 20,
  134320. };
  134321. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134322. _vq_quantthresh__44c8_s_p8_1,
  134323. _vq_quantmap__44c8_s_p8_1,
  134324. 21,
  134325. 21
  134326. };
  134327. static static_codebook _44c8_s_p8_1 = {
  134328. 2, 441,
  134329. _vq_lengthlist__44c8_s_p8_1,
  134330. 1, -529268736, 1611661312, 5, 0,
  134331. _vq_quantlist__44c8_s_p8_1,
  134332. NULL,
  134333. &_vq_auxt__44c8_s_p8_1,
  134334. NULL,
  134335. 0
  134336. };
  134337. static long _vq_quantlist__44c8_s_p9_0[] = {
  134338. 8,
  134339. 7,
  134340. 9,
  134341. 6,
  134342. 10,
  134343. 5,
  134344. 11,
  134345. 4,
  134346. 12,
  134347. 3,
  134348. 13,
  134349. 2,
  134350. 14,
  134351. 1,
  134352. 15,
  134353. 0,
  134354. 16,
  134355. };
  134356. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134357. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134358. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134359. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134370. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134371. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134373. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134374. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134375. 10,
  134376. };
  134377. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134378. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134379. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134380. };
  134381. static long _vq_quantmap__44c8_s_p9_0[] = {
  134382. 15, 13, 11, 9, 7, 5, 3, 1,
  134383. 0, 2, 4, 6, 8, 10, 12, 14,
  134384. 16,
  134385. };
  134386. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134387. _vq_quantthresh__44c8_s_p9_0,
  134388. _vq_quantmap__44c8_s_p9_0,
  134389. 17,
  134390. 17
  134391. };
  134392. static static_codebook _44c8_s_p9_0 = {
  134393. 2, 289,
  134394. _vq_lengthlist__44c8_s_p9_0,
  134395. 1, -509798400, 1631393792, 5, 0,
  134396. _vq_quantlist__44c8_s_p9_0,
  134397. NULL,
  134398. &_vq_auxt__44c8_s_p9_0,
  134399. NULL,
  134400. 0
  134401. };
  134402. static long _vq_quantlist__44c8_s_p9_1[] = {
  134403. 9,
  134404. 8,
  134405. 10,
  134406. 7,
  134407. 11,
  134408. 6,
  134409. 12,
  134410. 5,
  134411. 13,
  134412. 4,
  134413. 14,
  134414. 3,
  134415. 15,
  134416. 2,
  134417. 16,
  134418. 1,
  134419. 17,
  134420. 0,
  134421. 18,
  134422. };
  134423. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134424. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134425. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134426. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134427. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134428. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134429. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134430. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134431. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134432. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134433. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134434. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134435. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134436. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134437. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134438. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134439. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134440. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134441. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134442. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134443. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134444. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134445. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134446. 14,13,13,14,14,15,14,15,14,
  134447. };
  134448. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134449. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134450. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134451. 367.5, 416.5,
  134452. };
  134453. static long _vq_quantmap__44c8_s_p9_1[] = {
  134454. 17, 15, 13, 11, 9, 7, 5, 3,
  134455. 1, 0, 2, 4, 6, 8, 10, 12,
  134456. 14, 16, 18,
  134457. };
  134458. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134459. _vq_quantthresh__44c8_s_p9_1,
  134460. _vq_quantmap__44c8_s_p9_1,
  134461. 19,
  134462. 19
  134463. };
  134464. static static_codebook _44c8_s_p9_1 = {
  134465. 2, 361,
  134466. _vq_lengthlist__44c8_s_p9_1,
  134467. 1, -518287360, 1622704128, 5, 0,
  134468. _vq_quantlist__44c8_s_p9_1,
  134469. NULL,
  134470. &_vq_auxt__44c8_s_p9_1,
  134471. NULL,
  134472. 0
  134473. };
  134474. static long _vq_quantlist__44c8_s_p9_2[] = {
  134475. 24,
  134476. 23,
  134477. 25,
  134478. 22,
  134479. 26,
  134480. 21,
  134481. 27,
  134482. 20,
  134483. 28,
  134484. 19,
  134485. 29,
  134486. 18,
  134487. 30,
  134488. 17,
  134489. 31,
  134490. 16,
  134491. 32,
  134492. 15,
  134493. 33,
  134494. 14,
  134495. 34,
  134496. 13,
  134497. 35,
  134498. 12,
  134499. 36,
  134500. 11,
  134501. 37,
  134502. 10,
  134503. 38,
  134504. 9,
  134505. 39,
  134506. 8,
  134507. 40,
  134508. 7,
  134509. 41,
  134510. 6,
  134511. 42,
  134512. 5,
  134513. 43,
  134514. 4,
  134515. 44,
  134516. 3,
  134517. 45,
  134518. 2,
  134519. 46,
  134520. 1,
  134521. 47,
  134522. 0,
  134523. 48,
  134524. };
  134525. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134526. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134527. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134528. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134529. 7,
  134530. };
  134531. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134532. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134533. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134534. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134535. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134536. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134537. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134538. };
  134539. static long _vq_quantmap__44c8_s_p9_2[] = {
  134540. 47, 45, 43, 41, 39, 37, 35, 33,
  134541. 31, 29, 27, 25, 23, 21, 19, 17,
  134542. 15, 13, 11, 9, 7, 5, 3, 1,
  134543. 0, 2, 4, 6, 8, 10, 12, 14,
  134544. 16, 18, 20, 22, 24, 26, 28, 30,
  134545. 32, 34, 36, 38, 40, 42, 44, 46,
  134546. 48,
  134547. };
  134548. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134549. _vq_quantthresh__44c8_s_p9_2,
  134550. _vq_quantmap__44c8_s_p9_2,
  134551. 49,
  134552. 49
  134553. };
  134554. static static_codebook _44c8_s_p9_2 = {
  134555. 1, 49,
  134556. _vq_lengthlist__44c8_s_p9_2,
  134557. 1, -526909440, 1611661312, 6, 0,
  134558. _vq_quantlist__44c8_s_p9_2,
  134559. NULL,
  134560. &_vq_auxt__44c8_s_p9_2,
  134561. NULL,
  134562. 0
  134563. };
  134564. static long _huff_lengthlist__44c8_s_short[] = {
  134565. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134566. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134567. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134568. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134569. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134570. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134571. 10, 9,11,14,
  134572. };
  134573. static static_codebook _huff_book__44c8_s_short = {
  134574. 2, 100,
  134575. _huff_lengthlist__44c8_s_short,
  134576. 0, 0, 0, 0, 0,
  134577. NULL,
  134578. NULL,
  134579. NULL,
  134580. NULL,
  134581. 0
  134582. };
  134583. static long _huff_lengthlist__44c9_s_long[] = {
  134584. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134585. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134586. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134587. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134588. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134589. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134590. 10, 9, 8, 9,
  134591. };
  134592. static static_codebook _huff_book__44c9_s_long = {
  134593. 2, 100,
  134594. _huff_lengthlist__44c9_s_long,
  134595. 0, 0, 0, 0, 0,
  134596. NULL,
  134597. NULL,
  134598. NULL,
  134599. NULL,
  134600. 0
  134601. };
  134602. static long _vq_quantlist__44c9_s_p1_0[] = {
  134603. 1,
  134604. 0,
  134605. 2,
  134606. };
  134607. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134608. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134609. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134610. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134611. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134612. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134613. 7,
  134614. };
  134615. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134616. -0.5, 0.5,
  134617. };
  134618. static long _vq_quantmap__44c9_s_p1_0[] = {
  134619. 1, 0, 2,
  134620. };
  134621. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134622. _vq_quantthresh__44c9_s_p1_0,
  134623. _vq_quantmap__44c9_s_p1_0,
  134624. 3,
  134625. 3
  134626. };
  134627. static static_codebook _44c9_s_p1_0 = {
  134628. 4, 81,
  134629. _vq_lengthlist__44c9_s_p1_0,
  134630. 1, -535822336, 1611661312, 2, 0,
  134631. _vq_quantlist__44c9_s_p1_0,
  134632. NULL,
  134633. &_vq_auxt__44c9_s_p1_0,
  134634. NULL,
  134635. 0
  134636. };
  134637. static long _vq_quantlist__44c9_s_p2_0[] = {
  134638. 2,
  134639. 1,
  134640. 3,
  134641. 0,
  134642. 4,
  134643. };
  134644. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134645. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134646. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134647. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134648. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134649. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134650. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134651. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134652. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134654. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134655. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134656. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134657. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134658. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134659. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  134660. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  134661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134662. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  134663. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  134664. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  134665. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  134666. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  134667. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  134668. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134670. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  134671. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  134672. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  134673. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  134674. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  134675. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  134676. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134681. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  134682. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  134683. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  134684. 12,
  134685. };
  134686. static float _vq_quantthresh__44c9_s_p2_0[] = {
  134687. -1.5, -0.5, 0.5, 1.5,
  134688. };
  134689. static long _vq_quantmap__44c9_s_p2_0[] = {
  134690. 3, 1, 0, 2, 4,
  134691. };
  134692. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  134693. _vq_quantthresh__44c9_s_p2_0,
  134694. _vq_quantmap__44c9_s_p2_0,
  134695. 5,
  134696. 5
  134697. };
  134698. static static_codebook _44c9_s_p2_0 = {
  134699. 4, 625,
  134700. _vq_lengthlist__44c9_s_p2_0,
  134701. 1, -533725184, 1611661312, 3, 0,
  134702. _vq_quantlist__44c9_s_p2_0,
  134703. NULL,
  134704. &_vq_auxt__44c9_s_p2_0,
  134705. NULL,
  134706. 0
  134707. };
  134708. static long _vq_quantlist__44c9_s_p3_0[] = {
  134709. 4,
  134710. 3,
  134711. 5,
  134712. 2,
  134713. 6,
  134714. 1,
  134715. 7,
  134716. 0,
  134717. 8,
  134718. };
  134719. static long _vq_lengthlist__44c9_s_p3_0[] = {
  134720. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  134721. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  134722. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  134723. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  134724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134725. 0,
  134726. };
  134727. static float _vq_quantthresh__44c9_s_p3_0[] = {
  134728. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134729. };
  134730. static long _vq_quantmap__44c9_s_p3_0[] = {
  134731. 7, 5, 3, 1, 0, 2, 4, 6,
  134732. 8,
  134733. };
  134734. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  134735. _vq_quantthresh__44c9_s_p3_0,
  134736. _vq_quantmap__44c9_s_p3_0,
  134737. 9,
  134738. 9
  134739. };
  134740. static static_codebook _44c9_s_p3_0 = {
  134741. 2, 81,
  134742. _vq_lengthlist__44c9_s_p3_0,
  134743. 1, -531628032, 1611661312, 4, 0,
  134744. _vq_quantlist__44c9_s_p3_0,
  134745. NULL,
  134746. &_vq_auxt__44c9_s_p3_0,
  134747. NULL,
  134748. 0
  134749. };
  134750. static long _vq_quantlist__44c9_s_p4_0[] = {
  134751. 8,
  134752. 7,
  134753. 9,
  134754. 6,
  134755. 10,
  134756. 5,
  134757. 11,
  134758. 4,
  134759. 12,
  134760. 3,
  134761. 13,
  134762. 2,
  134763. 14,
  134764. 1,
  134765. 15,
  134766. 0,
  134767. 16,
  134768. };
  134769. static long _vq_lengthlist__44c9_s_p4_0[] = {
  134770. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  134771. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  134772. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  134773. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  134774. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  134775. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  134776. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  134777. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134778. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134779. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  134780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134788. 0,
  134789. };
  134790. static float _vq_quantthresh__44c9_s_p4_0[] = {
  134791. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134792. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134793. };
  134794. static long _vq_quantmap__44c9_s_p4_0[] = {
  134795. 15, 13, 11, 9, 7, 5, 3, 1,
  134796. 0, 2, 4, 6, 8, 10, 12, 14,
  134797. 16,
  134798. };
  134799. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  134800. _vq_quantthresh__44c9_s_p4_0,
  134801. _vq_quantmap__44c9_s_p4_0,
  134802. 17,
  134803. 17
  134804. };
  134805. static static_codebook _44c9_s_p4_0 = {
  134806. 2, 289,
  134807. _vq_lengthlist__44c9_s_p4_0,
  134808. 1, -529530880, 1611661312, 5, 0,
  134809. _vq_quantlist__44c9_s_p4_0,
  134810. NULL,
  134811. &_vq_auxt__44c9_s_p4_0,
  134812. NULL,
  134813. 0
  134814. };
  134815. static long _vq_quantlist__44c9_s_p5_0[] = {
  134816. 1,
  134817. 0,
  134818. 2,
  134819. };
  134820. static long _vq_lengthlist__44c9_s_p5_0[] = {
  134821. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  134822. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  134823. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  134824. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  134825. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  134826. 12,
  134827. };
  134828. static float _vq_quantthresh__44c9_s_p5_0[] = {
  134829. -5.5, 5.5,
  134830. };
  134831. static long _vq_quantmap__44c9_s_p5_0[] = {
  134832. 1, 0, 2,
  134833. };
  134834. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  134835. _vq_quantthresh__44c9_s_p5_0,
  134836. _vq_quantmap__44c9_s_p5_0,
  134837. 3,
  134838. 3
  134839. };
  134840. static static_codebook _44c9_s_p5_0 = {
  134841. 4, 81,
  134842. _vq_lengthlist__44c9_s_p5_0,
  134843. 1, -529137664, 1618345984, 2, 0,
  134844. _vq_quantlist__44c9_s_p5_0,
  134845. NULL,
  134846. &_vq_auxt__44c9_s_p5_0,
  134847. NULL,
  134848. 0
  134849. };
  134850. static long _vq_quantlist__44c9_s_p5_1[] = {
  134851. 5,
  134852. 4,
  134853. 6,
  134854. 3,
  134855. 7,
  134856. 2,
  134857. 8,
  134858. 1,
  134859. 9,
  134860. 0,
  134861. 10,
  134862. };
  134863. static long _vq_lengthlist__44c9_s_p5_1[] = {
  134864. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  134865. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  134866. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  134867. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  134868. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  134869. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  134870. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  134871. 11,11,11, 7, 7, 7, 7, 7, 7,
  134872. };
  134873. static float _vq_quantthresh__44c9_s_p5_1[] = {
  134874. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134875. 3.5, 4.5,
  134876. };
  134877. static long _vq_quantmap__44c9_s_p5_1[] = {
  134878. 9, 7, 5, 3, 1, 0, 2, 4,
  134879. 6, 8, 10,
  134880. };
  134881. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  134882. _vq_quantthresh__44c9_s_p5_1,
  134883. _vq_quantmap__44c9_s_p5_1,
  134884. 11,
  134885. 11
  134886. };
  134887. static static_codebook _44c9_s_p5_1 = {
  134888. 2, 121,
  134889. _vq_lengthlist__44c9_s_p5_1,
  134890. 1, -531365888, 1611661312, 4, 0,
  134891. _vq_quantlist__44c9_s_p5_1,
  134892. NULL,
  134893. &_vq_auxt__44c9_s_p5_1,
  134894. NULL,
  134895. 0
  134896. };
  134897. static long _vq_quantlist__44c9_s_p6_0[] = {
  134898. 6,
  134899. 5,
  134900. 7,
  134901. 4,
  134902. 8,
  134903. 3,
  134904. 9,
  134905. 2,
  134906. 10,
  134907. 1,
  134908. 11,
  134909. 0,
  134910. 12,
  134911. };
  134912. static long _vq_lengthlist__44c9_s_p6_0[] = {
  134913. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  134914. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  134915. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  134916. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134917. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  134918. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  134919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. };
  134925. static float _vq_quantthresh__44c9_s_p6_0[] = {
  134926. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134927. 12.5, 17.5, 22.5, 27.5,
  134928. };
  134929. static long _vq_quantmap__44c9_s_p6_0[] = {
  134930. 11, 9, 7, 5, 3, 1, 0, 2,
  134931. 4, 6, 8, 10, 12,
  134932. };
  134933. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  134934. _vq_quantthresh__44c9_s_p6_0,
  134935. _vq_quantmap__44c9_s_p6_0,
  134936. 13,
  134937. 13
  134938. };
  134939. static static_codebook _44c9_s_p6_0 = {
  134940. 2, 169,
  134941. _vq_lengthlist__44c9_s_p6_0,
  134942. 1, -526516224, 1616117760, 4, 0,
  134943. _vq_quantlist__44c9_s_p6_0,
  134944. NULL,
  134945. &_vq_auxt__44c9_s_p6_0,
  134946. NULL,
  134947. 0
  134948. };
  134949. static long _vq_quantlist__44c9_s_p6_1[] = {
  134950. 2,
  134951. 1,
  134952. 3,
  134953. 0,
  134954. 4,
  134955. };
  134956. static long _vq_lengthlist__44c9_s_p6_1[] = {
  134957. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  134958. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  134959. };
  134960. static float _vq_quantthresh__44c9_s_p6_1[] = {
  134961. -1.5, -0.5, 0.5, 1.5,
  134962. };
  134963. static long _vq_quantmap__44c9_s_p6_1[] = {
  134964. 3, 1, 0, 2, 4,
  134965. };
  134966. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  134967. _vq_quantthresh__44c9_s_p6_1,
  134968. _vq_quantmap__44c9_s_p6_1,
  134969. 5,
  134970. 5
  134971. };
  134972. static static_codebook _44c9_s_p6_1 = {
  134973. 2, 25,
  134974. _vq_lengthlist__44c9_s_p6_1,
  134975. 1, -533725184, 1611661312, 3, 0,
  134976. _vq_quantlist__44c9_s_p6_1,
  134977. NULL,
  134978. &_vq_auxt__44c9_s_p6_1,
  134979. NULL,
  134980. 0
  134981. };
  134982. static long _vq_quantlist__44c9_s_p7_0[] = {
  134983. 6,
  134984. 5,
  134985. 7,
  134986. 4,
  134987. 8,
  134988. 3,
  134989. 9,
  134990. 2,
  134991. 10,
  134992. 1,
  134993. 11,
  134994. 0,
  134995. 12,
  134996. };
  134997. static long _vq_lengthlist__44c9_s_p7_0[] = {
  134998. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  134999. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135000. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135001. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135002. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135003. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135004. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135005. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135006. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135007. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135008. 19,12,12,12,12,13,13,14,14,
  135009. };
  135010. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135011. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135012. 27.5, 38.5, 49.5, 60.5,
  135013. };
  135014. static long _vq_quantmap__44c9_s_p7_0[] = {
  135015. 11, 9, 7, 5, 3, 1, 0, 2,
  135016. 4, 6, 8, 10, 12,
  135017. };
  135018. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135019. _vq_quantthresh__44c9_s_p7_0,
  135020. _vq_quantmap__44c9_s_p7_0,
  135021. 13,
  135022. 13
  135023. };
  135024. static static_codebook _44c9_s_p7_0 = {
  135025. 2, 169,
  135026. _vq_lengthlist__44c9_s_p7_0,
  135027. 1, -523206656, 1618345984, 4, 0,
  135028. _vq_quantlist__44c9_s_p7_0,
  135029. NULL,
  135030. &_vq_auxt__44c9_s_p7_0,
  135031. NULL,
  135032. 0
  135033. };
  135034. static long _vq_quantlist__44c9_s_p7_1[] = {
  135035. 5,
  135036. 4,
  135037. 6,
  135038. 3,
  135039. 7,
  135040. 2,
  135041. 8,
  135042. 1,
  135043. 9,
  135044. 0,
  135045. 10,
  135046. };
  135047. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135048. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135049. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135050. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135051. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135052. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135053. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135054. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135055. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135056. };
  135057. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135058. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135059. 3.5, 4.5,
  135060. };
  135061. static long _vq_quantmap__44c9_s_p7_1[] = {
  135062. 9, 7, 5, 3, 1, 0, 2, 4,
  135063. 6, 8, 10,
  135064. };
  135065. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135066. _vq_quantthresh__44c9_s_p7_1,
  135067. _vq_quantmap__44c9_s_p7_1,
  135068. 11,
  135069. 11
  135070. };
  135071. static static_codebook _44c9_s_p7_1 = {
  135072. 2, 121,
  135073. _vq_lengthlist__44c9_s_p7_1,
  135074. 1, -531365888, 1611661312, 4, 0,
  135075. _vq_quantlist__44c9_s_p7_1,
  135076. NULL,
  135077. &_vq_auxt__44c9_s_p7_1,
  135078. NULL,
  135079. 0
  135080. };
  135081. static long _vq_quantlist__44c9_s_p8_0[] = {
  135082. 7,
  135083. 6,
  135084. 8,
  135085. 5,
  135086. 9,
  135087. 4,
  135088. 10,
  135089. 3,
  135090. 11,
  135091. 2,
  135092. 12,
  135093. 1,
  135094. 13,
  135095. 0,
  135096. 14,
  135097. };
  135098. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135099. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135100. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135101. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135102. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135103. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135104. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135105. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135106. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135107. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135108. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135109. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135110. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135111. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135112. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135113. 14,
  135114. };
  135115. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135116. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135117. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135118. };
  135119. static long _vq_quantmap__44c9_s_p8_0[] = {
  135120. 13, 11, 9, 7, 5, 3, 1, 0,
  135121. 2, 4, 6, 8, 10, 12, 14,
  135122. };
  135123. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135124. _vq_quantthresh__44c9_s_p8_0,
  135125. _vq_quantmap__44c9_s_p8_0,
  135126. 15,
  135127. 15
  135128. };
  135129. static static_codebook _44c9_s_p8_0 = {
  135130. 2, 225,
  135131. _vq_lengthlist__44c9_s_p8_0,
  135132. 1, -520986624, 1620377600, 4, 0,
  135133. _vq_quantlist__44c9_s_p8_0,
  135134. NULL,
  135135. &_vq_auxt__44c9_s_p8_0,
  135136. NULL,
  135137. 0
  135138. };
  135139. static long _vq_quantlist__44c9_s_p8_1[] = {
  135140. 10,
  135141. 9,
  135142. 11,
  135143. 8,
  135144. 12,
  135145. 7,
  135146. 13,
  135147. 6,
  135148. 14,
  135149. 5,
  135150. 15,
  135151. 4,
  135152. 16,
  135153. 3,
  135154. 17,
  135155. 2,
  135156. 18,
  135157. 1,
  135158. 19,
  135159. 0,
  135160. 20,
  135161. };
  135162. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135163. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135164. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135165. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135166. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135167. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135168. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135169. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135170. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135171. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135172. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135173. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135174. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135175. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135176. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135177. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135178. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135179. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135180. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135181. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135182. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135183. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135184. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135185. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135186. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135187. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135188. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135189. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135190. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135191. };
  135192. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135193. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135194. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135195. 6.5, 7.5, 8.5, 9.5,
  135196. };
  135197. static long _vq_quantmap__44c9_s_p8_1[] = {
  135198. 19, 17, 15, 13, 11, 9, 7, 5,
  135199. 3, 1, 0, 2, 4, 6, 8, 10,
  135200. 12, 14, 16, 18, 20,
  135201. };
  135202. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135203. _vq_quantthresh__44c9_s_p8_1,
  135204. _vq_quantmap__44c9_s_p8_1,
  135205. 21,
  135206. 21
  135207. };
  135208. static static_codebook _44c9_s_p8_1 = {
  135209. 2, 441,
  135210. _vq_lengthlist__44c9_s_p8_1,
  135211. 1, -529268736, 1611661312, 5, 0,
  135212. _vq_quantlist__44c9_s_p8_1,
  135213. NULL,
  135214. &_vq_auxt__44c9_s_p8_1,
  135215. NULL,
  135216. 0
  135217. };
  135218. static long _vq_quantlist__44c9_s_p9_0[] = {
  135219. 9,
  135220. 8,
  135221. 10,
  135222. 7,
  135223. 11,
  135224. 6,
  135225. 12,
  135226. 5,
  135227. 13,
  135228. 4,
  135229. 14,
  135230. 3,
  135231. 15,
  135232. 2,
  135233. 16,
  135234. 1,
  135235. 17,
  135236. 0,
  135237. 18,
  135238. };
  135239. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135240. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135241. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135242. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135243. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135244. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135245. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135246. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135247. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135249. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135253. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135254. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135255. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135256. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135262. 11,11,11,11,11,11,11,11,11,
  135263. };
  135264. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135265. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135266. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135267. 6982.5, 7913.5,
  135268. };
  135269. static long _vq_quantmap__44c9_s_p9_0[] = {
  135270. 17, 15, 13, 11, 9, 7, 5, 3,
  135271. 1, 0, 2, 4, 6, 8, 10, 12,
  135272. 14, 16, 18,
  135273. };
  135274. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135275. _vq_quantthresh__44c9_s_p9_0,
  135276. _vq_quantmap__44c9_s_p9_0,
  135277. 19,
  135278. 19
  135279. };
  135280. static static_codebook _44c9_s_p9_0 = {
  135281. 2, 361,
  135282. _vq_lengthlist__44c9_s_p9_0,
  135283. 1, -508535424, 1631393792, 5, 0,
  135284. _vq_quantlist__44c9_s_p9_0,
  135285. NULL,
  135286. &_vq_auxt__44c9_s_p9_0,
  135287. NULL,
  135288. 0
  135289. };
  135290. static long _vq_quantlist__44c9_s_p9_1[] = {
  135291. 9,
  135292. 8,
  135293. 10,
  135294. 7,
  135295. 11,
  135296. 6,
  135297. 12,
  135298. 5,
  135299. 13,
  135300. 4,
  135301. 14,
  135302. 3,
  135303. 15,
  135304. 2,
  135305. 16,
  135306. 1,
  135307. 17,
  135308. 0,
  135309. 18,
  135310. };
  135311. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135312. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135313. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135314. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135315. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135316. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135317. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135318. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135319. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135320. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135321. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135322. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135323. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135324. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135325. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135326. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135327. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135328. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135329. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135330. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135331. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135332. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135333. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135334. 13,13,13,14,13,14,15,15,15,
  135335. };
  135336. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135337. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135338. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135339. 367.5, 416.5,
  135340. };
  135341. static long _vq_quantmap__44c9_s_p9_1[] = {
  135342. 17, 15, 13, 11, 9, 7, 5, 3,
  135343. 1, 0, 2, 4, 6, 8, 10, 12,
  135344. 14, 16, 18,
  135345. };
  135346. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135347. _vq_quantthresh__44c9_s_p9_1,
  135348. _vq_quantmap__44c9_s_p9_1,
  135349. 19,
  135350. 19
  135351. };
  135352. static static_codebook _44c9_s_p9_1 = {
  135353. 2, 361,
  135354. _vq_lengthlist__44c9_s_p9_1,
  135355. 1, -518287360, 1622704128, 5, 0,
  135356. _vq_quantlist__44c9_s_p9_1,
  135357. NULL,
  135358. &_vq_auxt__44c9_s_p9_1,
  135359. NULL,
  135360. 0
  135361. };
  135362. static long _vq_quantlist__44c9_s_p9_2[] = {
  135363. 24,
  135364. 23,
  135365. 25,
  135366. 22,
  135367. 26,
  135368. 21,
  135369. 27,
  135370. 20,
  135371. 28,
  135372. 19,
  135373. 29,
  135374. 18,
  135375. 30,
  135376. 17,
  135377. 31,
  135378. 16,
  135379. 32,
  135380. 15,
  135381. 33,
  135382. 14,
  135383. 34,
  135384. 13,
  135385. 35,
  135386. 12,
  135387. 36,
  135388. 11,
  135389. 37,
  135390. 10,
  135391. 38,
  135392. 9,
  135393. 39,
  135394. 8,
  135395. 40,
  135396. 7,
  135397. 41,
  135398. 6,
  135399. 42,
  135400. 5,
  135401. 43,
  135402. 4,
  135403. 44,
  135404. 3,
  135405. 45,
  135406. 2,
  135407. 46,
  135408. 1,
  135409. 47,
  135410. 0,
  135411. 48,
  135412. };
  135413. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135414. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135415. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135416. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135417. 7,
  135418. };
  135419. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135420. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135421. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135422. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135423. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135424. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135425. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135426. };
  135427. static long _vq_quantmap__44c9_s_p9_2[] = {
  135428. 47, 45, 43, 41, 39, 37, 35, 33,
  135429. 31, 29, 27, 25, 23, 21, 19, 17,
  135430. 15, 13, 11, 9, 7, 5, 3, 1,
  135431. 0, 2, 4, 6, 8, 10, 12, 14,
  135432. 16, 18, 20, 22, 24, 26, 28, 30,
  135433. 32, 34, 36, 38, 40, 42, 44, 46,
  135434. 48,
  135435. };
  135436. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135437. _vq_quantthresh__44c9_s_p9_2,
  135438. _vq_quantmap__44c9_s_p9_2,
  135439. 49,
  135440. 49
  135441. };
  135442. static static_codebook _44c9_s_p9_2 = {
  135443. 1, 49,
  135444. _vq_lengthlist__44c9_s_p9_2,
  135445. 1, -526909440, 1611661312, 6, 0,
  135446. _vq_quantlist__44c9_s_p9_2,
  135447. NULL,
  135448. &_vq_auxt__44c9_s_p9_2,
  135449. NULL,
  135450. 0
  135451. };
  135452. static long _huff_lengthlist__44c9_s_short[] = {
  135453. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135454. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135455. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135456. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135457. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135458. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135459. 9, 8,10,13,
  135460. };
  135461. static static_codebook _huff_book__44c9_s_short = {
  135462. 2, 100,
  135463. _huff_lengthlist__44c9_s_short,
  135464. 0, 0, 0, 0, 0,
  135465. NULL,
  135466. NULL,
  135467. NULL,
  135468. NULL,
  135469. 0
  135470. };
  135471. static long _huff_lengthlist__44c0_s_long[] = {
  135472. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135473. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135474. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135475. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135476. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135477. 12,
  135478. };
  135479. static static_codebook _huff_book__44c0_s_long = {
  135480. 2, 81,
  135481. _huff_lengthlist__44c0_s_long,
  135482. 0, 0, 0, 0, 0,
  135483. NULL,
  135484. NULL,
  135485. NULL,
  135486. NULL,
  135487. 0
  135488. };
  135489. static long _vq_quantlist__44c0_s_p1_0[] = {
  135490. 1,
  135491. 0,
  135492. 2,
  135493. };
  135494. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135495. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135496. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135500. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135501. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135505. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135506. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135541. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135546. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135551. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135586. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135587. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135591. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135592. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  135593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135596. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135597. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0,
  135906. };
  135907. static float _vq_quantthresh__44c0_s_p1_0[] = {
  135908. -0.5, 0.5,
  135909. };
  135910. static long _vq_quantmap__44c0_s_p1_0[] = {
  135911. 1, 0, 2,
  135912. };
  135913. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  135914. _vq_quantthresh__44c0_s_p1_0,
  135915. _vq_quantmap__44c0_s_p1_0,
  135916. 3,
  135917. 3
  135918. };
  135919. static static_codebook _44c0_s_p1_0 = {
  135920. 8, 6561,
  135921. _vq_lengthlist__44c0_s_p1_0,
  135922. 1, -535822336, 1611661312, 2, 0,
  135923. _vq_quantlist__44c0_s_p1_0,
  135924. NULL,
  135925. &_vq_auxt__44c0_s_p1_0,
  135926. NULL,
  135927. 0
  135928. };
  135929. static long _vq_quantlist__44c0_s_p2_0[] = {
  135930. 2,
  135931. 1,
  135932. 3,
  135933. 0,
  135934. 4,
  135935. };
  135936. static long _vq_lengthlist__44c0_s_p2_0[] = {
  135937. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0,
  135977. };
  135978. static float _vq_quantthresh__44c0_s_p2_0[] = {
  135979. -1.5, -0.5, 0.5, 1.5,
  135980. };
  135981. static long _vq_quantmap__44c0_s_p2_0[] = {
  135982. 3, 1, 0, 2, 4,
  135983. };
  135984. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  135985. _vq_quantthresh__44c0_s_p2_0,
  135986. _vq_quantmap__44c0_s_p2_0,
  135987. 5,
  135988. 5
  135989. };
  135990. static static_codebook _44c0_s_p2_0 = {
  135991. 4, 625,
  135992. _vq_lengthlist__44c0_s_p2_0,
  135993. 1, -533725184, 1611661312, 3, 0,
  135994. _vq_quantlist__44c0_s_p2_0,
  135995. NULL,
  135996. &_vq_auxt__44c0_s_p2_0,
  135997. NULL,
  135998. 0
  135999. };
  136000. static long _vq_quantlist__44c0_s_p3_0[] = {
  136001. 4,
  136002. 3,
  136003. 5,
  136004. 2,
  136005. 6,
  136006. 1,
  136007. 7,
  136008. 0,
  136009. 8,
  136010. };
  136011. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136012. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136013. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136014. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136015. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136016. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0,
  136018. };
  136019. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136020. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136021. };
  136022. static long _vq_quantmap__44c0_s_p3_0[] = {
  136023. 7, 5, 3, 1, 0, 2, 4, 6,
  136024. 8,
  136025. };
  136026. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136027. _vq_quantthresh__44c0_s_p3_0,
  136028. _vq_quantmap__44c0_s_p3_0,
  136029. 9,
  136030. 9
  136031. };
  136032. static static_codebook _44c0_s_p3_0 = {
  136033. 2, 81,
  136034. _vq_lengthlist__44c0_s_p3_0,
  136035. 1, -531628032, 1611661312, 4, 0,
  136036. _vq_quantlist__44c0_s_p3_0,
  136037. NULL,
  136038. &_vq_auxt__44c0_s_p3_0,
  136039. NULL,
  136040. 0
  136041. };
  136042. static long _vq_quantlist__44c0_s_p4_0[] = {
  136043. 4,
  136044. 3,
  136045. 5,
  136046. 2,
  136047. 6,
  136048. 1,
  136049. 7,
  136050. 0,
  136051. 8,
  136052. };
  136053. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136054. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136055. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136056. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136057. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136058. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136059. 10,
  136060. };
  136061. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136062. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136063. };
  136064. static long _vq_quantmap__44c0_s_p4_0[] = {
  136065. 7, 5, 3, 1, 0, 2, 4, 6,
  136066. 8,
  136067. };
  136068. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136069. _vq_quantthresh__44c0_s_p4_0,
  136070. _vq_quantmap__44c0_s_p4_0,
  136071. 9,
  136072. 9
  136073. };
  136074. static static_codebook _44c0_s_p4_0 = {
  136075. 2, 81,
  136076. _vq_lengthlist__44c0_s_p4_0,
  136077. 1, -531628032, 1611661312, 4, 0,
  136078. _vq_quantlist__44c0_s_p4_0,
  136079. NULL,
  136080. &_vq_auxt__44c0_s_p4_0,
  136081. NULL,
  136082. 0
  136083. };
  136084. static long _vq_quantlist__44c0_s_p5_0[] = {
  136085. 8,
  136086. 7,
  136087. 9,
  136088. 6,
  136089. 10,
  136090. 5,
  136091. 11,
  136092. 4,
  136093. 12,
  136094. 3,
  136095. 13,
  136096. 2,
  136097. 14,
  136098. 1,
  136099. 15,
  136100. 0,
  136101. 16,
  136102. };
  136103. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136104. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136105. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136106. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136107. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136108. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136109. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136110. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136111. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136112. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136113. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136114. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136115. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136116. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136117. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136118. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136119. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136120. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136122. 14,
  136123. };
  136124. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136125. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136126. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136127. };
  136128. static long _vq_quantmap__44c0_s_p5_0[] = {
  136129. 15, 13, 11, 9, 7, 5, 3, 1,
  136130. 0, 2, 4, 6, 8, 10, 12, 14,
  136131. 16,
  136132. };
  136133. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136134. _vq_quantthresh__44c0_s_p5_0,
  136135. _vq_quantmap__44c0_s_p5_0,
  136136. 17,
  136137. 17
  136138. };
  136139. static static_codebook _44c0_s_p5_0 = {
  136140. 2, 289,
  136141. _vq_lengthlist__44c0_s_p5_0,
  136142. 1, -529530880, 1611661312, 5, 0,
  136143. _vq_quantlist__44c0_s_p5_0,
  136144. NULL,
  136145. &_vq_auxt__44c0_s_p5_0,
  136146. NULL,
  136147. 0
  136148. };
  136149. static long _vq_quantlist__44c0_s_p6_0[] = {
  136150. 1,
  136151. 0,
  136152. 2,
  136153. };
  136154. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136155. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136156. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136157. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136158. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136159. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136160. 10,
  136161. };
  136162. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136163. -5.5, 5.5,
  136164. };
  136165. static long _vq_quantmap__44c0_s_p6_0[] = {
  136166. 1, 0, 2,
  136167. };
  136168. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136169. _vq_quantthresh__44c0_s_p6_0,
  136170. _vq_quantmap__44c0_s_p6_0,
  136171. 3,
  136172. 3
  136173. };
  136174. static static_codebook _44c0_s_p6_0 = {
  136175. 4, 81,
  136176. _vq_lengthlist__44c0_s_p6_0,
  136177. 1, -529137664, 1618345984, 2, 0,
  136178. _vq_quantlist__44c0_s_p6_0,
  136179. NULL,
  136180. &_vq_auxt__44c0_s_p6_0,
  136181. NULL,
  136182. 0
  136183. };
  136184. static long _vq_quantlist__44c0_s_p6_1[] = {
  136185. 5,
  136186. 4,
  136187. 6,
  136188. 3,
  136189. 7,
  136190. 2,
  136191. 8,
  136192. 1,
  136193. 9,
  136194. 0,
  136195. 10,
  136196. };
  136197. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136198. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136199. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136200. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136201. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136202. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136203. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136204. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136205. 10,10,10, 8, 8, 8, 8, 8, 8,
  136206. };
  136207. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136208. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136209. 3.5, 4.5,
  136210. };
  136211. static long _vq_quantmap__44c0_s_p6_1[] = {
  136212. 9, 7, 5, 3, 1, 0, 2, 4,
  136213. 6, 8, 10,
  136214. };
  136215. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136216. _vq_quantthresh__44c0_s_p6_1,
  136217. _vq_quantmap__44c0_s_p6_1,
  136218. 11,
  136219. 11
  136220. };
  136221. static static_codebook _44c0_s_p6_1 = {
  136222. 2, 121,
  136223. _vq_lengthlist__44c0_s_p6_1,
  136224. 1, -531365888, 1611661312, 4, 0,
  136225. _vq_quantlist__44c0_s_p6_1,
  136226. NULL,
  136227. &_vq_auxt__44c0_s_p6_1,
  136228. NULL,
  136229. 0
  136230. };
  136231. static long _vq_quantlist__44c0_s_p7_0[] = {
  136232. 6,
  136233. 5,
  136234. 7,
  136235. 4,
  136236. 8,
  136237. 3,
  136238. 9,
  136239. 2,
  136240. 10,
  136241. 1,
  136242. 11,
  136243. 0,
  136244. 12,
  136245. };
  136246. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136247. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136248. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136249. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136250. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136251. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136252. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136253. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136254. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136255. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136256. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136257. 0,12,12,11,11,12,12,13,13,
  136258. };
  136259. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136260. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136261. 12.5, 17.5, 22.5, 27.5,
  136262. };
  136263. static long _vq_quantmap__44c0_s_p7_0[] = {
  136264. 11, 9, 7, 5, 3, 1, 0, 2,
  136265. 4, 6, 8, 10, 12,
  136266. };
  136267. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136268. _vq_quantthresh__44c0_s_p7_0,
  136269. _vq_quantmap__44c0_s_p7_0,
  136270. 13,
  136271. 13
  136272. };
  136273. static static_codebook _44c0_s_p7_0 = {
  136274. 2, 169,
  136275. _vq_lengthlist__44c0_s_p7_0,
  136276. 1, -526516224, 1616117760, 4, 0,
  136277. _vq_quantlist__44c0_s_p7_0,
  136278. NULL,
  136279. &_vq_auxt__44c0_s_p7_0,
  136280. NULL,
  136281. 0
  136282. };
  136283. static long _vq_quantlist__44c0_s_p7_1[] = {
  136284. 2,
  136285. 1,
  136286. 3,
  136287. 0,
  136288. 4,
  136289. };
  136290. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136291. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136292. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136293. };
  136294. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136295. -1.5, -0.5, 0.5, 1.5,
  136296. };
  136297. static long _vq_quantmap__44c0_s_p7_1[] = {
  136298. 3, 1, 0, 2, 4,
  136299. };
  136300. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136301. _vq_quantthresh__44c0_s_p7_1,
  136302. _vq_quantmap__44c0_s_p7_1,
  136303. 5,
  136304. 5
  136305. };
  136306. static static_codebook _44c0_s_p7_1 = {
  136307. 2, 25,
  136308. _vq_lengthlist__44c0_s_p7_1,
  136309. 1, -533725184, 1611661312, 3, 0,
  136310. _vq_quantlist__44c0_s_p7_1,
  136311. NULL,
  136312. &_vq_auxt__44c0_s_p7_1,
  136313. NULL,
  136314. 0
  136315. };
  136316. static long _vq_quantlist__44c0_s_p8_0[] = {
  136317. 2,
  136318. 1,
  136319. 3,
  136320. 0,
  136321. 4,
  136322. };
  136323. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136324. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136325. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136326. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136327. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136328. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136329. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136331. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136333. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136334. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136335. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136336. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136337. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136338. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136339. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136340. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136341. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136353. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136354. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136355. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136358. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136363. 11,
  136364. };
  136365. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136366. -331.5, -110.5, 110.5, 331.5,
  136367. };
  136368. static long _vq_quantmap__44c0_s_p8_0[] = {
  136369. 3, 1, 0, 2, 4,
  136370. };
  136371. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136372. _vq_quantthresh__44c0_s_p8_0,
  136373. _vq_quantmap__44c0_s_p8_0,
  136374. 5,
  136375. 5
  136376. };
  136377. static static_codebook _44c0_s_p8_0 = {
  136378. 4, 625,
  136379. _vq_lengthlist__44c0_s_p8_0,
  136380. 1, -518283264, 1627103232, 3, 0,
  136381. _vq_quantlist__44c0_s_p8_0,
  136382. NULL,
  136383. &_vq_auxt__44c0_s_p8_0,
  136384. NULL,
  136385. 0
  136386. };
  136387. static long _vq_quantlist__44c0_s_p8_1[] = {
  136388. 6,
  136389. 5,
  136390. 7,
  136391. 4,
  136392. 8,
  136393. 3,
  136394. 9,
  136395. 2,
  136396. 10,
  136397. 1,
  136398. 11,
  136399. 0,
  136400. 12,
  136401. };
  136402. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136403. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136404. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136405. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136406. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136407. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136408. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136409. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136410. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136411. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136412. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136413. 16,13,13,12,12,14,14,15,13,
  136414. };
  136415. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136416. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136417. 42.5, 59.5, 76.5, 93.5,
  136418. };
  136419. static long _vq_quantmap__44c0_s_p8_1[] = {
  136420. 11, 9, 7, 5, 3, 1, 0, 2,
  136421. 4, 6, 8, 10, 12,
  136422. };
  136423. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136424. _vq_quantthresh__44c0_s_p8_1,
  136425. _vq_quantmap__44c0_s_p8_1,
  136426. 13,
  136427. 13
  136428. };
  136429. static static_codebook _44c0_s_p8_1 = {
  136430. 2, 169,
  136431. _vq_lengthlist__44c0_s_p8_1,
  136432. 1, -522616832, 1620115456, 4, 0,
  136433. _vq_quantlist__44c0_s_p8_1,
  136434. NULL,
  136435. &_vq_auxt__44c0_s_p8_1,
  136436. NULL,
  136437. 0
  136438. };
  136439. static long _vq_quantlist__44c0_s_p8_2[] = {
  136440. 8,
  136441. 7,
  136442. 9,
  136443. 6,
  136444. 10,
  136445. 5,
  136446. 11,
  136447. 4,
  136448. 12,
  136449. 3,
  136450. 13,
  136451. 2,
  136452. 14,
  136453. 1,
  136454. 15,
  136455. 0,
  136456. 16,
  136457. };
  136458. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136459. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136460. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136461. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136462. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136463. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136464. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136465. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136466. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136467. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136468. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136469. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136470. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136471. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136472. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136473. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136474. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136475. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136476. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136477. 10,
  136478. };
  136479. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136480. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136481. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136482. };
  136483. static long _vq_quantmap__44c0_s_p8_2[] = {
  136484. 15, 13, 11, 9, 7, 5, 3, 1,
  136485. 0, 2, 4, 6, 8, 10, 12, 14,
  136486. 16,
  136487. };
  136488. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136489. _vq_quantthresh__44c0_s_p8_2,
  136490. _vq_quantmap__44c0_s_p8_2,
  136491. 17,
  136492. 17
  136493. };
  136494. static static_codebook _44c0_s_p8_2 = {
  136495. 2, 289,
  136496. _vq_lengthlist__44c0_s_p8_2,
  136497. 1, -529530880, 1611661312, 5, 0,
  136498. _vq_quantlist__44c0_s_p8_2,
  136499. NULL,
  136500. &_vq_auxt__44c0_s_p8_2,
  136501. NULL,
  136502. 0
  136503. };
  136504. static long _huff_lengthlist__44c0_s_short[] = {
  136505. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136506. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136507. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136508. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136509. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136510. 12,
  136511. };
  136512. static static_codebook _huff_book__44c0_s_short = {
  136513. 2, 81,
  136514. _huff_lengthlist__44c0_s_short,
  136515. 0, 0, 0, 0, 0,
  136516. NULL,
  136517. NULL,
  136518. NULL,
  136519. NULL,
  136520. 0
  136521. };
  136522. static long _huff_lengthlist__44c0_sm_long[] = {
  136523. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136524. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136525. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136526. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136527. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136528. 13,
  136529. };
  136530. static static_codebook _huff_book__44c0_sm_long = {
  136531. 2, 81,
  136532. _huff_lengthlist__44c0_sm_long,
  136533. 0, 0, 0, 0, 0,
  136534. NULL,
  136535. NULL,
  136536. NULL,
  136537. NULL,
  136538. 0
  136539. };
  136540. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136541. 1,
  136542. 0,
  136543. 2,
  136544. };
  136545. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136546. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136547. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136551. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136552. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136556. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136557. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136592. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136597. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136602. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136638. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136643. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136648. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0,
  136957. };
  136958. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  136959. -0.5, 0.5,
  136960. };
  136961. static long _vq_quantmap__44c0_sm_p1_0[] = {
  136962. 1, 0, 2,
  136963. };
  136964. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  136965. _vq_quantthresh__44c0_sm_p1_0,
  136966. _vq_quantmap__44c0_sm_p1_0,
  136967. 3,
  136968. 3
  136969. };
  136970. static static_codebook _44c0_sm_p1_0 = {
  136971. 8, 6561,
  136972. _vq_lengthlist__44c0_sm_p1_0,
  136973. 1, -535822336, 1611661312, 2, 0,
  136974. _vq_quantlist__44c0_sm_p1_0,
  136975. NULL,
  136976. &_vq_auxt__44c0_sm_p1_0,
  136977. NULL,
  136978. 0
  136979. };
  136980. static long _vq_quantlist__44c0_sm_p2_0[] = {
  136981. 2,
  136982. 1,
  136983. 3,
  136984. 0,
  136985. 4,
  136986. };
  136987. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  136988. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0,
  137028. };
  137029. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137030. -1.5, -0.5, 0.5, 1.5,
  137031. };
  137032. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137033. 3, 1, 0, 2, 4,
  137034. };
  137035. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137036. _vq_quantthresh__44c0_sm_p2_0,
  137037. _vq_quantmap__44c0_sm_p2_0,
  137038. 5,
  137039. 5
  137040. };
  137041. static static_codebook _44c0_sm_p2_0 = {
  137042. 4, 625,
  137043. _vq_lengthlist__44c0_sm_p2_0,
  137044. 1, -533725184, 1611661312, 3, 0,
  137045. _vq_quantlist__44c0_sm_p2_0,
  137046. NULL,
  137047. &_vq_auxt__44c0_sm_p2_0,
  137048. NULL,
  137049. 0
  137050. };
  137051. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137052. 4,
  137053. 3,
  137054. 5,
  137055. 2,
  137056. 6,
  137057. 1,
  137058. 7,
  137059. 0,
  137060. 8,
  137061. };
  137062. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137063. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137064. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137065. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137066. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137067. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0,
  137069. };
  137070. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137071. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137072. };
  137073. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137074. 7, 5, 3, 1, 0, 2, 4, 6,
  137075. 8,
  137076. };
  137077. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137078. _vq_quantthresh__44c0_sm_p3_0,
  137079. _vq_quantmap__44c0_sm_p3_0,
  137080. 9,
  137081. 9
  137082. };
  137083. static static_codebook _44c0_sm_p3_0 = {
  137084. 2, 81,
  137085. _vq_lengthlist__44c0_sm_p3_0,
  137086. 1, -531628032, 1611661312, 4, 0,
  137087. _vq_quantlist__44c0_sm_p3_0,
  137088. NULL,
  137089. &_vq_auxt__44c0_sm_p3_0,
  137090. NULL,
  137091. 0
  137092. };
  137093. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137094. 4,
  137095. 3,
  137096. 5,
  137097. 2,
  137098. 6,
  137099. 1,
  137100. 7,
  137101. 0,
  137102. 8,
  137103. };
  137104. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137105. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137106. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137107. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137108. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137109. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137110. 11,
  137111. };
  137112. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137113. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137114. };
  137115. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137116. 7, 5, 3, 1, 0, 2, 4, 6,
  137117. 8,
  137118. };
  137119. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137120. _vq_quantthresh__44c0_sm_p4_0,
  137121. _vq_quantmap__44c0_sm_p4_0,
  137122. 9,
  137123. 9
  137124. };
  137125. static static_codebook _44c0_sm_p4_0 = {
  137126. 2, 81,
  137127. _vq_lengthlist__44c0_sm_p4_0,
  137128. 1, -531628032, 1611661312, 4, 0,
  137129. _vq_quantlist__44c0_sm_p4_0,
  137130. NULL,
  137131. &_vq_auxt__44c0_sm_p4_0,
  137132. NULL,
  137133. 0
  137134. };
  137135. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137136. 8,
  137137. 7,
  137138. 9,
  137139. 6,
  137140. 10,
  137141. 5,
  137142. 11,
  137143. 4,
  137144. 12,
  137145. 3,
  137146. 13,
  137147. 2,
  137148. 14,
  137149. 1,
  137150. 15,
  137151. 0,
  137152. 16,
  137153. };
  137154. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137155. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137156. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137157. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137158. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137159. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137160. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137161. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137162. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137163. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137164. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137165. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137166. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137167. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137168. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137169. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137170. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137171. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137173. 14,
  137174. };
  137175. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137176. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137177. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137178. };
  137179. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137180. 15, 13, 11, 9, 7, 5, 3, 1,
  137181. 0, 2, 4, 6, 8, 10, 12, 14,
  137182. 16,
  137183. };
  137184. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137185. _vq_quantthresh__44c0_sm_p5_0,
  137186. _vq_quantmap__44c0_sm_p5_0,
  137187. 17,
  137188. 17
  137189. };
  137190. static static_codebook _44c0_sm_p5_0 = {
  137191. 2, 289,
  137192. _vq_lengthlist__44c0_sm_p5_0,
  137193. 1, -529530880, 1611661312, 5, 0,
  137194. _vq_quantlist__44c0_sm_p5_0,
  137195. NULL,
  137196. &_vq_auxt__44c0_sm_p5_0,
  137197. NULL,
  137198. 0
  137199. };
  137200. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137201. 1,
  137202. 0,
  137203. 2,
  137204. };
  137205. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137206. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137207. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137208. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137209. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137210. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137211. 11,
  137212. };
  137213. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137214. -5.5, 5.5,
  137215. };
  137216. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137217. 1, 0, 2,
  137218. };
  137219. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137220. _vq_quantthresh__44c0_sm_p6_0,
  137221. _vq_quantmap__44c0_sm_p6_0,
  137222. 3,
  137223. 3
  137224. };
  137225. static static_codebook _44c0_sm_p6_0 = {
  137226. 4, 81,
  137227. _vq_lengthlist__44c0_sm_p6_0,
  137228. 1, -529137664, 1618345984, 2, 0,
  137229. _vq_quantlist__44c0_sm_p6_0,
  137230. NULL,
  137231. &_vq_auxt__44c0_sm_p6_0,
  137232. NULL,
  137233. 0
  137234. };
  137235. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137236. 5,
  137237. 4,
  137238. 6,
  137239. 3,
  137240. 7,
  137241. 2,
  137242. 8,
  137243. 1,
  137244. 9,
  137245. 0,
  137246. 10,
  137247. };
  137248. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137249. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137250. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137251. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137252. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137253. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137254. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137255. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137256. 10,10,10, 8, 8, 8, 8, 8, 8,
  137257. };
  137258. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137259. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137260. 3.5, 4.5,
  137261. };
  137262. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137263. 9, 7, 5, 3, 1, 0, 2, 4,
  137264. 6, 8, 10,
  137265. };
  137266. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137267. _vq_quantthresh__44c0_sm_p6_1,
  137268. _vq_quantmap__44c0_sm_p6_1,
  137269. 11,
  137270. 11
  137271. };
  137272. static static_codebook _44c0_sm_p6_1 = {
  137273. 2, 121,
  137274. _vq_lengthlist__44c0_sm_p6_1,
  137275. 1, -531365888, 1611661312, 4, 0,
  137276. _vq_quantlist__44c0_sm_p6_1,
  137277. NULL,
  137278. &_vq_auxt__44c0_sm_p6_1,
  137279. NULL,
  137280. 0
  137281. };
  137282. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137283. 6,
  137284. 5,
  137285. 7,
  137286. 4,
  137287. 8,
  137288. 3,
  137289. 9,
  137290. 2,
  137291. 10,
  137292. 1,
  137293. 11,
  137294. 0,
  137295. 12,
  137296. };
  137297. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137298. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137299. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137300. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137301. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137302. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137303. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137304. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137305. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137306. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137307. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137308. 0,12,12,11,11,13,12,14,14,
  137309. };
  137310. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137311. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137312. 12.5, 17.5, 22.5, 27.5,
  137313. };
  137314. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137315. 11, 9, 7, 5, 3, 1, 0, 2,
  137316. 4, 6, 8, 10, 12,
  137317. };
  137318. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137319. _vq_quantthresh__44c0_sm_p7_0,
  137320. _vq_quantmap__44c0_sm_p7_0,
  137321. 13,
  137322. 13
  137323. };
  137324. static static_codebook _44c0_sm_p7_0 = {
  137325. 2, 169,
  137326. _vq_lengthlist__44c0_sm_p7_0,
  137327. 1, -526516224, 1616117760, 4, 0,
  137328. _vq_quantlist__44c0_sm_p7_0,
  137329. NULL,
  137330. &_vq_auxt__44c0_sm_p7_0,
  137331. NULL,
  137332. 0
  137333. };
  137334. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137335. 2,
  137336. 1,
  137337. 3,
  137338. 0,
  137339. 4,
  137340. };
  137341. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137342. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137343. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137344. };
  137345. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137346. -1.5, -0.5, 0.5, 1.5,
  137347. };
  137348. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137349. 3, 1, 0, 2, 4,
  137350. };
  137351. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137352. _vq_quantthresh__44c0_sm_p7_1,
  137353. _vq_quantmap__44c0_sm_p7_1,
  137354. 5,
  137355. 5
  137356. };
  137357. static static_codebook _44c0_sm_p7_1 = {
  137358. 2, 25,
  137359. _vq_lengthlist__44c0_sm_p7_1,
  137360. 1, -533725184, 1611661312, 3, 0,
  137361. _vq_quantlist__44c0_sm_p7_1,
  137362. NULL,
  137363. &_vq_auxt__44c0_sm_p7_1,
  137364. NULL,
  137365. 0
  137366. };
  137367. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137368. 4,
  137369. 3,
  137370. 5,
  137371. 2,
  137372. 6,
  137373. 1,
  137374. 7,
  137375. 0,
  137376. 8,
  137377. };
  137378. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137379. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137380. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137381. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137382. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137383. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137384. 12,
  137385. };
  137386. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137387. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137388. };
  137389. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137390. 7, 5, 3, 1, 0, 2, 4, 6,
  137391. 8,
  137392. };
  137393. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137394. _vq_quantthresh__44c0_sm_p8_0,
  137395. _vq_quantmap__44c0_sm_p8_0,
  137396. 9,
  137397. 9
  137398. };
  137399. static static_codebook _44c0_sm_p8_0 = {
  137400. 2, 81,
  137401. _vq_lengthlist__44c0_sm_p8_0,
  137402. 1, -516186112, 1627103232, 4, 0,
  137403. _vq_quantlist__44c0_sm_p8_0,
  137404. NULL,
  137405. &_vq_auxt__44c0_sm_p8_0,
  137406. NULL,
  137407. 0
  137408. };
  137409. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137410. 6,
  137411. 5,
  137412. 7,
  137413. 4,
  137414. 8,
  137415. 3,
  137416. 9,
  137417. 2,
  137418. 10,
  137419. 1,
  137420. 11,
  137421. 0,
  137422. 12,
  137423. };
  137424. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137425. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137426. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137427. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137428. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137429. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137430. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137431. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137432. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137433. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137434. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137435. 20,13,13,12,12,16,13,15,13,
  137436. };
  137437. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137438. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137439. 42.5, 59.5, 76.5, 93.5,
  137440. };
  137441. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137442. 11, 9, 7, 5, 3, 1, 0, 2,
  137443. 4, 6, 8, 10, 12,
  137444. };
  137445. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137446. _vq_quantthresh__44c0_sm_p8_1,
  137447. _vq_quantmap__44c0_sm_p8_1,
  137448. 13,
  137449. 13
  137450. };
  137451. static static_codebook _44c0_sm_p8_1 = {
  137452. 2, 169,
  137453. _vq_lengthlist__44c0_sm_p8_1,
  137454. 1, -522616832, 1620115456, 4, 0,
  137455. _vq_quantlist__44c0_sm_p8_1,
  137456. NULL,
  137457. &_vq_auxt__44c0_sm_p8_1,
  137458. NULL,
  137459. 0
  137460. };
  137461. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137462. 8,
  137463. 7,
  137464. 9,
  137465. 6,
  137466. 10,
  137467. 5,
  137468. 11,
  137469. 4,
  137470. 12,
  137471. 3,
  137472. 13,
  137473. 2,
  137474. 14,
  137475. 1,
  137476. 15,
  137477. 0,
  137478. 16,
  137479. };
  137480. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137481. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137482. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137483. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137484. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137485. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137486. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137487. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137488. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137489. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137490. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137491. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137492. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137493. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137494. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137495. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137496. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137497. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137498. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137499. 9,
  137500. };
  137501. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137502. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137503. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137504. };
  137505. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137506. 15, 13, 11, 9, 7, 5, 3, 1,
  137507. 0, 2, 4, 6, 8, 10, 12, 14,
  137508. 16,
  137509. };
  137510. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137511. _vq_quantthresh__44c0_sm_p8_2,
  137512. _vq_quantmap__44c0_sm_p8_2,
  137513. 17,
  137514. 17
  137515. };
  137516. static static_codebook _44c0_sm_p8_2 = {
  137517. 2, 289,
  137518. _vq_lengthlist__44c0_sm_p8_2,
  137519. 1, -529530880, 1611661312, 5, 0,
  137520. _vq_quantlist__44c0_sm_p8_2,
  137521. NULL,
  137522. &_vq_auxt__44c0_sm_p8_2,
  137523. NULL,
  137524. 0
  137525. };
  137526. static long _huff_lengthlist__44c0_sm_short[] = {
  137527. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137528. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137529. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137530. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137531. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137532. 12,
  137533. };
  137534. static static_codebook _huff_book__44c0_sm_short = {
  137535. 2, 81,
  137536. _huff_lengthlist__44c0_sm_short,
  137537. 0, 0, 0, 0, 0,
  137538. NULL,
  137539. NULL,
  137540. NULL,
  137541. NULL,
  137542. 0
  137543. };
  137544. static long _huff_lengthlist__44c1_s_long[] = {
  137545. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137546. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137547. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137548. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137549. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137550. 11,
  137551. };
  137552. static static_codebook _huff_book__44c1_s_long = {
  137553. 2, 81,
  137554. _huff_lengthlist__44c1_s_long,
  137555. 0, 0, 0, 0, 0,
  137556. NULL,
  137557. NULL,
  137558. NULL,
  137559. NULL,
  137560. 0
  137561. };
  137562. static long _vq_quantlist__44c1_s_p1_0[] = {
  137563. 1,
  137564. 0,
  137565. 2,
  137566. };
  137567. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137568. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137569. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137574. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137579. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  137614. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137619. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  137624. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137660. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  137665. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  137670. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137978. 0,
  137979. };
  137980. static float _vq_quantthresh__44c1_s_p1_0[] = {
  137981. -0.5, 0.5,
  137982. };
  137983. static long _vq_quantmap__44c1_s_p1_0[] = {
  137984. 1, 0, 2,
  137985. };
  137986. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  137987. _vq_quantthresh__44c1_s_p1_0,
  137988. _vq_quantmap__44c1_s_p1_0,
  137989. 3,
  137990. 3
  137991. };
  137992. static static_codebook _44c1_s_p1_0 = {
  137993. 8, 6561,
  137994. _vq_lengthlist__44c1_s_p1_0,
  137995. 1, -535822336, 1611661312, 2, 0,
  137996. _vq_quantlist__44c1_s_p1_0,
  137997. NULL,
  137998. &_vq_auxt__44c1_s_p1_0,
  137999. NULL,
  138000. 0
  138001. };
  138002. static long _vq_quantlist__44c1_s_p2_0[] = {
  138003. 2,
  138004. 1,
  138005. 3,
  138006. 0,
  138007. 4,
  138008. };
  138009. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138010. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138049. 0,
  138050. };
  138051. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138052. -1.5, -0.5, 0.5, 1.5,
  138053. };
  138054. static long _vq_quantmap__44c1_s_p2_0[] = {
  138055. 3, 1, 0, 2, 4,
  138056. };
  138057. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138058. _vq_quantthresh__44c1_s_p2_0,
  138059. _vq_quantmap__44c1_s_p2_0,
  138060. 5,
  138061. 5
  138062. };
  138063. static static_codebook _44c1_s_p2_0 = {
  138064. 4, 625,
  138065. _vq_lengthlist__44c1_s_p2_0,
  138066. 1, -533725184, 1611661312, 3, 0,
  138067. _vq_quantlist__44c1_s_p2_0,
  138068. NULL,
  138069. &_vq_auxt__44c1_s_p2_0,
  138070. NULL,
  138071. 0
  138072. };
  138073. static long _vq_quantlist__44c1_s_p3_0[] = {
  138074. 4,
  138075. 3,
  138076. 5,
  138077. 2,
  138078. 6,
  138079. 1,
  138080. 7,
  138081. 0,
  138082. 8,
  138083. };
  138084. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138085. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138086. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138087. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138088. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138089. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138090. 0,
  138091. };
  138092. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138093. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138094. };
  138095. static long _vq_quantmap__44c1_s_p3_0[] = {
  138096. 7, 5, 3, 1, 0, 2, 4, 6,
  138097. 8,
  138098. };
  138099. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138100. _vq_quantthresh__44c1_s_p3_0,
  138101. _vq_quantmap__44c1_s_p3_0,
  138102. 9,
  138103. 9
  138104. };
  138105. static static_codebook _44c1_s_p3_0 = {
  138106. 2, 81,
  138107. _vq_lengthlist__44c1_s_p3_0,
  138108. 1, -531628032, 1611661312, 4, 0,
  138109. _vq_quantlist__44c1_s_p3_0,
  138110. NULL,
  138111. &_vq_auxt__44c1_s_p3_0,
  138112. NULL,
  138113. 0
  138114. };
  138115. static long _vq_quantlist__44c1_s_p4_0[] = {
  138116. 4,
  138117. 3,
  138118. 5,
  138119. 2,
  138120. 6,
  138121. 1,
  138122. 7,
  138123. 0,
  138124. 8,
  138125. };
  138126. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138127. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138128. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138129. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138130. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138131. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138132. 11,
  138133. };
  138134. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138135. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138136. };
  138137. static long _vq_quantmap__44c1_s_p4_0[] = {
  138138. 7, 5, 3, 1, 0, 2, 4, 6,
  138139. 8,
  138140. };
  138141. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138142. _vq_quantthresh__44c1_s_p4_0,
  138143. _vq_quantmap__44c1_s_p4_0,
  138144. 9,
  138145. 9
  138146. };
  138147. static static_codebook _44c1_s_p4_0 = {
  138148. 2, 81,
  138149. _vq_lengthlist__44c1_s_p4_0,
  138150. 1, -531628032, 1611661312, 4, 0,
  138151. _vq_quantlist__44c1_s_p4_0,
  138152. NULL,
  138153. &_vq_auxt__44c1_s_p4_0,
  138154. NULL,
  138155. 0
  138156. };
  138157. static long _vq_quantlist__44c1_s_p5_0[] = {
  138158. 8,
  138159. 7,
  138160. 9,
  138161. 6,
  138162. 10,
  138163. 5,
  138164. 11,
  138165. 4,
  138166. 12,
  138167. 3,
  138168. 13,
  138169. 2,
  138170. 14,
  138171. 1,
  138172. 15,
  138173. 0,
  138174. 16,
  138175. };
  138176. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138177. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138178. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138179. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138180. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138181. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138182. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138183. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138184. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138185. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138186. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138187. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138188. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138189. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138190. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138191. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138192. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138193. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138195. 14,
  138196. };
  138197. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138198. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138199. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138200. };
  138201. static long _vq_quantmap__44c1_s_p5_0[] = {
  138202. 15, 13, 11, 9, 7, 5, 3, 1,
  138203. 0, 2, 4, 6, 8, 10, 12, 14,
  138204. 16,
  138205. };
  138206. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138207. _vq_quantthresh__44c1_s_p5_0,
  138208. _vq_quantmap__44c1_s_p5_0,
  138209. 17,
  138210. 17
  138211. };
  138212. static static_codebook _44c1_s_p5_0 = {
  138213. 2, 289,
  138214. _vq_lengthlist__44c1_s_p5_0,
  138215. 1, -529530880, 1611661312, 5, 0,
  138216. _vq_quantlist__44c1_s_p5_0,
  138217. NULL,
  138218. &_vq_auxt__44c1_s_p5_0,
  138219. NULL,
  138220. 0
  138221. };
  138222. static long _vq_quantlist__44c1_s_p6_0[] = {
  138223. 1,
  138224. 0,
  138225. 2,
  138226. };
  138227. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138228. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138229. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138230. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138231. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138232. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138233. 11,
  138234. };
  138235. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138236. -5.5, 5.5,
  138237. };
  138238. static long _vq_quantmap__44c1_s_p6_0[] = {
  138239. 1, 0, 2,
  138240. };
  138241. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138242. _vq_quantthresh__44c1_s_p6_0,
  138243. _vq_quantmap__44c1_s_p6_0,
  138244. 3,
  138245. 3
  138246. };
  138247. static static_codebook _44c1_s_p6_0 = {
  138248. 4, 81,
  138249. _vq_lengthlist__44c1_s_p6_0,
  138250. 1, -529137664, 1618345984, 2, 0,
  138251. _vq_quantlist__44c1_s_p6_0,
  138252. NULL,
  138253. &_vq_auxt__44c1_s_p6_0,
  138254. NULL,
  138255. 0
  138256. };
  138257. static long _vq_quantlist__44c1_s_p6_1[] = {
  138258. 5,
  138259. 4,
  138260. 6,
  138261. 3,
  138262. 7,
  138263. 2,
  138264. 8,
  138265. 1,
  138266. 9,
  138267. 0,
  138268. 10,
  138269. };
  138270. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138271. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138272. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138273. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138274. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138275. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138276. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138277. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138278. 10,10,10, 8, 8, 8, 8, 8, 8,
  138279. };
  138280. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138282. 3.5, 4.5,
  138283. };
  138284. static long _vq_quantmap__44c1_s_p6_1[] = {
  138285. 9, 7, 5, 3, 1, 0, 2, 4,
  138286. 6, 8, 10,
  138287. };
  138288. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138289. _vq_quantthresh__44c1_s_p6_1,
  138290. _vq_quantmap__44c1_s_p6_1,
  138291. 11,
  138292. 11
  138293. };
  138294. static static_codebook _44c1_s_p6_1 = {
  138295. 2, 121,
  138296. _vq_lengthlist__44c1_s_p6_1,
  138297. 1, -531365888, 1611661312, 4, 0,
  138298. _vq_quantlist__44c1_s_p6_1,
  138299. NULL,
  138300. &_vq_auxt__44c1_s_p6_1,
  138301. NULL,
  138302. 0
  138303. };
  138304. static long _vq_quantlist__44c1_s_p7_0[] = {
  138305. 6,
  138306. 5,
  138307. 7,
  138308. 4,
  138309. 8,
  138310. 3,
  138311. 9,
  138312. 2,
  138313. 10,
  138314. 1,
  138315. 11,
  138316. 0,
  138317. 12,
  138318. };
  138319. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138320. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138321. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138322. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138323. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138324. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138325. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138326. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138327. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138328. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138329. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138330. 0,12,11,11,11,13,10,14,13,
  138331. };
  138332. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138333. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138334. 12.5, 17.5, 22.5, 27.5,
  138335. };
  138336. static long _vq_quantmap__44c1_s_p7_0[] = {
  138337. 11, 9, 7, 5, 3, 1, 0, 2,
  138338. 4, 6, 8, 10, 12,
  138339. };
  138340. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138341. _vq_quantthresh__44c1_s_p7_0,
  138342. _vq_quantmap__44c1_s_p7_0,
  138343. 13,
  138344. 13
  138345. };
  138346. static static_codebook _44c1_s_p7_0 = {
  138347. 2, 169,
  138348. _vq_lengthlist__44c1_s_p7_0,
  138349. 1, -526516224, 1616117760, 4, 0,
  138350. _vq_quantlist__44c1_s_p7_0,
  138351. NULL,
  138352. &_vq_auxt__44c1_s_p7_0,
  138353. NULL,
  138354. 0
  138355. };
  138356. static long _vq_quantlist__44c1_s_p7_1[] = {
  138357. 2,
  138358. 1,
  138359. 3,
  138360. 0,
  138361. 4,
  138362. };
  138363. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138364. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138365. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138366. };
  138367. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138368. -1.5, -0.5, 0.5, 1.5,
  138369. };
  138370. static long _vq_quantmap__44c1_s_p7_1[] = {
  138371. 3, 1, 0, 2, 4,
  138372. };
  138373. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138374. _vq_quantthresh__44c1_s_p7_1,
  138375. _vq_quantmap__44c1_s_p7_1,
  138376. 5,
  138377. 5
  138378. };
  138379. static static_codebook _44c1_s_p7_1 = {
  138380. 2, 25,
  138381. _vq_lengthlist__44c1_s_p7_1,
  138382. 1, -533725184, 1611661312, 3, 0,
  138383. _vq_quantlist__44c1_s_p7_1,
  138384. NULL,
  138385. &_vq_auxt__44c1_s_p7_1,
  138386. NULL,
  138387. 0
  138388. };
  138389. static long _vq_quantlist__44c1_s_p8_0[] = {
  138390. 6,
  138391. 5,
  138392. 7,
  138393. 4,
  138394. 8,
  138395. 3,
  138396. 9,
  138397. 2,
  138398. 10,
  138399. 1,
  138400. 11,
  138401. 0,
  138402. 12,
  138403. };
  138404. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138405. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138406. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138407. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138408. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138409. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138410. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138412. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138413. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138415. 10,10,10,10,10,10,10,10,10,
  138416. };
  138417. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138418. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138419. 552.5, 773.5, 994.5, 1215.5,
  138420. };
  138421. static long _vq_quantmap__44c1_s_p8_0[] = {
  138422. 11, 9, 7, 5, 3, 1, 0, 2,
  138423. 4, 6, 8, 10, 12,
  138424. };
  138425. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138426. _vq_quantthresh__44c1_s_p8_0,
  138427. _vq_quantmap__44c1_s_p8_0,
  138428. 13,
  138429. 13
  138430. };
  138431. static static_codebook _44c1_s_p8_0 = {
  138432. 2, 169,
  138433. _vq_lengthlist__44c1_s_p8_0,
  138434. 1, -514541568, 1627103232, 4, 0,
  138435. _vq_quantlist__44c1_s_p8_0,
  138436. NULL,
  138437. &_vq_auxt__44c1_s_p8_0,
  138438. NULL,
  138439. 0
  138440. };
  138441. static long _vq_quantlist__44c1_s_p8_1[] = {
  138442. 6,
  138443. 5,
  138444. 7,
  138445. 4,
  138446. 8,
  138447. 3,
  138448. 9,
  138449. 2,
  138450. 10,
  138451. 1,
  138452. 11,
  138453. 0,
  138454. 12,
  138455. };
  138456. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138457. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138458. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138459. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138460. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138461. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138462. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138463. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138464. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138465. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138466. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138467. 16,13,12,12,11,14,12,15,13,
  138468. };
  138469. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138470. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138471. 42.5, 59.5, 76.5, 93.5,
  138472. };
  138473. static long _vq_quantmap__44c1_s_p8_1[] = {
  138474. 11, 9, 7, 5, 3, 1, 0, 2,
  138475. 4, 6, 8, 10, 12,
  138476. };
  138477. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138478. _vq_quantthresh__44c1_s_p8_1,
  138479. _vq_quantmap__44c1_s_p8_1,
  138480. 13,
  138481. 13
  138482. };
  138483. static static_codebook _44c1_s_p8_1 = {
  138484. 2, 169,
  138485. _vq_lengthlist__44c1_s_p8_1,
  138486. 1, -522616832, 1620115456, 4, 0,
  138487. _vq_quantlist__44c1_s_p8_1,
  138488. NULL,
  138489. &_vq_auxt__44c1_s_p8_1,
  138490. NULL,
  138491. 0
  138492. };
  138493. static long _vq_quantlist__44c1_s_p8_2[] = {
  138494. 8,
  138495. 7,
  138496. 9,
  138497. 6,
  138498. 10,
  138499. 5,
  138500. 11,
  138501. 4,
  138502. 12,
  138503. 3,
  138504. 13,
  138505. 2,
  138506. 14,
  138507. 1,
  138508. 15,
  138509. 0,
  138510. 16,
  138511. };
  138512. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138513. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138514. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138515. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138516. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138517. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138518. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138519. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138520. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138521. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138522. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138523. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138524. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138525. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138526. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138527. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138528. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138529. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138530. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138531. 9,
  138532. };
  138533. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138534. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138535. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138536. };
  138537. static long _vq_quantmap__44c1_s_p8_2[] = {
  138538. 15, 13, 11, 9, 7, 5, 3, 1,
  138539. 0, 2, 4, 6, 8, 10, 12, 14,
  138540. 16,
  138541. };
  138542. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138543. _vq_quantthresh__44c1_s_p8_2,
  138544. _vq_quantmap__44c1_s_p8_2,
  138545. 17,
  138546. 17
  138547. };
  138548. static static_codebook _44c1_s_p8_2 = {
  138549. 2, 289,
  138550. _vq_lengthlist__44c1_s_p8_2,
  138551. 1, -529530880, 1611661312, 5, 0,
  138552. _vq_quantlist__44c1_s_p8_2,
  138553. NULL,
  138554. &_vq_auxt__44c1_s_p8_2,
  138555. NULL,
  138556. 0
  138557. };
  138558. static long _huff_lengthlist__44c1_s_short[] = {
  138559. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138560. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138561. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138562. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138563. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138564. 11,
  138565. };
  138566. static static_codebook _huff_book__44c1_s_short = {
  138567. 2, 81,
  138568. _huff_lengthlist__44c1_s_short,
  138569. 0, 0, 0, 0, 0,
  138570. NULL,
  138571. NULL,
  138572. NULL,
  138573. NULL,
  138574. 0
  138575. };
  138576. static long _huff_lengthlist__44c1_sm_long[] = {
  138577. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138578. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138579. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138580. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138581. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138582. 11,
  138583. };
  138584. static static_codebook _huff_book__44c1_sm_long = {
  138585. 2, 81,
  138586. _huff_lengthlist__44c1_sm_long,
  138587. 0, 0, 0, 0, 0,
  138588. NULL,
  138589. NULL,
  138590. NULL,
  138591. NULL,
  138592. 0
  138593. };
  138594. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138595. 1,
  138596. 0,
  138597. 2,
  138598. };
  138599. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138600. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138601. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138606. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138611. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  138646. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138651. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  138656. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  138692. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  138697. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  138702. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139010. 0,
  139011. };
  139012. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139013. -0.5, 0.5,
  139014. };
  139015. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139016. 1, 0, 2,
  139017. };
  139018. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139019. _vq_quantthresh__44c1_sm_p1_0,
  139020. _vq_quantmap__44c1_sm_p1_0,
  139021. 3,
  139022. 3
  139023. };
  139024. static static_codebook _44c1_sm_p1_0 = {
  139025. 8, 6561,
  139026. _vq_lengthlist__44c1_sm_p1_0,
  139027. 1, -535822336, 1611661312, 2, 0,
  139028. _vq_quantlist__44c1_sm_p1_0,
  139029. NULL,
  139030. &_vq_auxt__44c1_sm_p1_0,
  139031. NULL,
  139032. 0
  139033. };
  139034. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139035. 2,
  139036. 1,
  139037. 3,
  139038. 0,
  139039. 4,
  139040. };
  139041. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139042. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139081. 0,
  139082. };
  139083. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139084. -1.5, -0.5, 0.5, 1.5,
  139085. };
  139086. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139087. 3, 1, 0, 2, 4,
  139088. };
  139089. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139090. _vq_quantthresh__44c1_sm_p2_0,
  139091. _vq_quantmap__44c1_sm_p2_0,
  139092. 5,
  139093. 5
  139094. };
  139095. static static_codebook _44c1_sm_p2_0 = {
  139096. 4, 625,
  139097. _vq_lengthlist__44c1_sm_p2_0,
  139098. 1, -533725184, 1611661312, 3, 0,
  139099. _vq_quantlist__44c1_sm_p2_0,
  139100. NULL,
  139101. &_vq_auxt__44c1_sm_p2_0,
  139102. NULL,
  139103. 0
  139104. };
  139105. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139106. 4,
  139107. 3,
  139108. 5,
  139109. 2,
  139110. 6,
  139111. 1,
  139112. 7,
  139113. 0,
  139114. 8,
  139115. };
  139116. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139117. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139118. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139119. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139120. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139121. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139122. 0,
  139123. };
  139124. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139125. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139126. };
  139127. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139128. 7, 5, 3, 1, 0, 2, 4, 6,
  139129. 8,
  139130. };
  139131. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139132. _vq_quantthresh__44c1_sm_p3_0,
  139133. _vq_quantmap__44c1_sm_p3_0,
  139134. 9,
  139135. 9
  139136. };
  139137. static static_codebook _44c1_sm_p3_0 = {
  139138. 2, 81,
  139139. _vq_lengthlist__44c1_sm_p3_0,
  139140. 1, -531628032, 1611661312, 4, 0,
  139141. _vq_quantlist__44c1_sm_p3_0,
  139142. NULL,
  139143. &_vq_auxt__44c1_sm_p3_0,
  139144. NULL,
  139145. 0
  139146. };
  139147. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139148. 4,
  139149. 3,
  139150. 5,
  139151. 2,
  139152. 6,
  139153. 1,
  139154. 7,
  139155. 0,
  139156. 8,
  139157. };
  139158. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139159. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139160. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139161. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139162. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139163. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139164. 11,
  139165. };
  139166. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139167. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139168. };
  139169. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139170. 7, 5, 3, 1, 0, 2, 4, 6,
  139171. 8,
  139172. };
  139173. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139174. _vq_quantthresh__44c1_sm_p4_0,
  139175. _vq_quantmap__44c1_sm_p4_0,
  139176. 9,
  139177. 9
  139178. };
  139179. static static_codebook _44c1_sm_p4_0 = {
  139180. 2, 81,
  139181. _vq_lengthlist__44c1_sm_p4_0,
  139182. 1, -531628032, 1611661312, 4, 0,
  139183. _vq_quantlist__44c1_sm_p4_0,
  139184. NULL,
  139185. &_vq_auxt__44c1_sm_p4_0,
  139186. NULL,
  139187. 0
  139188. };
  139189. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139190. 8,
  139191. 7,
  139192. 9,
  139193. 6,
  139194. 10,
  139195. 5,
  139196. 11,
  139197. 4,
  139198. 12,
  139199. 3,
  139200. 13,
  139201. 2,
  139202. 14,
  139203. 1,
  139204. 15,
  139205. 0,
  139206. 16,
  139207. };
  139208. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139209. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139210. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139211. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139212. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139213. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139214. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139215. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139216. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139217. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139218. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139219. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139220. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139221. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139222. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139223. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139224. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139225. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139227. 14,
  139228. };
  139229. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139230. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139231. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139232. };
  139233. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139234. 15, 13, 11, 9, 7, 5, 3, 1,
  139235. 0, 2, 4, 6, 8, 10, 12, 14,
  139236. 16,
  139237. };
  139238. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139239. _vq_quantthresh__44c1_sm_p5_0,
  139240. _vq_quantmap__44c1_sm_p5_0,
  139241. 17,
  139242. 17
  139243. };
  139244. static static_codebook _44c1_sm_p5_0 = {
  139245. 2, 289,
  139246. _vq_lengthlist__44c1_sm_p5_0,
  139247. 1, -529530880, 1611661312, 5, 0,
  139248. _vq_quantlist__44c1_sm_p5_0,
  139249. NULL,
  139250. &_vq_auxt__44c1_sm_p5_0,
  139251. NULL,
  139252. 0
  139253. };
  139254. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139255. 1,
  139256. 0,
  139257. 2,
  139258. };
  139259. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139260. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139261. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139262. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139263. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139264. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139265. 11,
  139266. };
  139267. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139268. -5.5, 5.5,
  139269. };
  139270. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139271. 1, 0, 2,
  139272. };
  139273. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139274. _vq_quantthresh__44c1_sm_p6_0,
  139275. _vq_quantmap__44c1_sm_p6_0,
  139276. 3,
  139277. 3
  139278. };
  139279. static static_codebook _44c1_sm_p6_0 = {
  139280. 4, 81,
  139281. _vq_lengthlist__44c1_sm_p6_0,
  139282. 1, -529137664, 1618345984, 2, 0,
  139283. _vq_quantlist__44c1_sm_p6_0,
  139284. NULL,
  139285. &_vq_auxt__44c1_sm_p6_0,
  139286. NULL,
  139287. 0
  139288. };
  139289. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139290. 5,
  139291. 4,
  139292. 6,
  139293. 3,
  139294. 7,
  139295. 2,
  139296. 8,
  139297. 1,
  139298. 9,
  139299. 0,
  139300. 10,
  139301. };
  139302. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139303. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139304. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139305. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139306. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139307. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139308. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139309. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139310. 10,10,10, 8, 8, 8, 8, 8, 8,
  139311. };
  139312. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139313. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139314. 3.5, 4.5,
  139315. };
  139316. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139317. 9, 7, 5, 3, 1, 0, 2, 4,
  139318. 6, 8, 10,
  139319. };
  139320. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139321. _vq_quantthresh__44c1_sm_p6_1,
  139322. _vq_quantmap__44c1_sm_p6_1,
  139323. 11,
  139324. 11
  139325. };
  139326. static static_codebook _44c1_sm_p6_1 = {
  139327. 2, 121,
  139328. _vq_lengthlist__44c1_sm_p6_1,
  139329. 1, -531365888, 1611661312, 4, 0,
  139330. _vq_quantlist__44c1_sm_p6_1,
  139331. NULL,
  139332. &_vq_auxt__44c1_sm_p6_1,
  139333. NULL,
  139334. 0
  139335. };
  139336. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139337. 6,
  139338. 5,
  139339. 7,
  139340. 4,
  139341. 8,
  139342. 3,
  139343. 9,
  139344. 2,
  139345. 10,
  139346. 1,
  139347. 11,
  139348. 0,
  139349. 12,
  139350. };
  139351. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139352. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139353. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139354. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139355. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139356. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139357. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139358. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139359. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139360. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139361. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139362. 0,12,12,11,11,13,12,14,13,
  139363. };
  139364. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139365. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139366. 12.5, 17.5, 22.5, 27.5,
  139367. };
  139368. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139369. 11, 9, 7, 5, 3, 1, 0, 2,
  139370. 4, 6, 8, 10, 12,
  139371. };
  139372. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139373. _vq_quantthresh__44c1_sm_p7_0,
  139374. _vq_quantmap__44c1_sm_p7_0,
  139375. 13,
  139376. 13
  139377. };
  139378. static static_codebook _44c1_sm_p7_0 = {
  139379. 2, 169,
  139380. _vq_lengthlist__44c1_sm_p7_0,
  139381. 1, -526516224, 1616117760, 4, 0,
  139382. _vq_quantlist__44c1_sm_p7_0,
  139383. NULL,
  139384. &_vq_auxt__44c1_sm_p7_0,
  139385. NULL,
  139386. 0
  139387. };
  139388. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139389. 2,
  139390. 1,
  139391. 3,
  139392. 0,
  139393. 4,
  139394. };
  139395. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139396. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139397. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139398. };
  139399. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139400. -1.5, -0.5, 0.5, 1.5,
  139401. };
  139402. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139403. 3, 1, 0, 2, 4,
  139404. };
  139405. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139406. _vq_quantthresh__44c1_sm_p7_1,
  139407. _vq_quantmap__44c1_sm_p7_1,
  139408. 5,
  139409. 5
  139410. };
  139411. static static_codebook _44c1_sm_p7_1 = {
  139412. 2, 25,
  139413. _vq_lengthlist__44c1_sm_p7_1,
  139414. 1, -533725184, 1611661312, 3, 0,
  139415. _vq_quantlist__44c1_sm_p7_1,
  139416. NULL,
  139417. &_vq_auxt__44c1_sm_p7_1,
  139418. NULL,
  139419. 0
  139420. };
  139421. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139422. 6,
  139423. 5,
  139424. 7,
  139425. 4,
  139426. 8,
  139427. 3,
  139428. 9,
  139429. 2,
  139430. 10,
  139431. 1,
  139432. 11,
  139433. 0,
  139434. 12,
  139435. };
  139436. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139437. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139438. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139439. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139440. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139441. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139442. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139443. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139444. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139445. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139446. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139447. 13,13,13,13,13,13,13,13,13,
  139448. };
  139449. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139450. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139451. 552.5, 773.5, 994.5, 1215.5,
  139452. };
  139453. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139454. 11, 9, 7, 5, 3, 1, 0, 2,
  139455. 4, 6, 8, 10, 12,
  139456. };
  139457. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139458. _vq_quantthresh__44c1_sm_p8_0,
  139459. _vq_quantmap__44c1_sm_p8_0,
  139460. 13,
  139461. 13
  139462. };
  139463. static static_codebook _44c1_sm_p8_0 = {
  139464. 2, 169,
  139465. _vq_lengthlist__44c1_sm_p8_0,
  139466. 1, -514541568, 1627103232, 4, 0,
  139467. _vq_quantlist__44c1_sm_p8_0,
  139468. NULL,
  139469. &_vq_auxt__44c1_sm_p8_0,
  139470. NULL,
  139471. 0
  139472. };
  139473. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139474. 6,
  139475. 5,
  139476. 7,
  139477. 4,
  139478. 8,
  139479. 3,
  139480. 9,
  139481. 2,
  139482. 10,
  139483. 1,
  139484. 11,
  139485. 0,
  139486. 12,
  139487. };
  139488. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139489. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139490. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139491. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139492. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139493. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139494. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139495. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139496. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139497. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139498. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139499. 20,13,12,12,12,14,12,14,13,
  139500. };
  139501. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139502. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139503. 42.5, 59.5, 76.5, 93.5,
  139504. };
  139505. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139506. 11, 9, 7, 5, 3, 1, 0, 2,
  139507. 4, 6, 8, 10, 12,
  139508. };
  139509. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139510. _vq_quantthresh__44c1_sm_p8_1,
  139511. _vq_quantmap__44c1_sm_p8_1,
  139512. 13,
  139513. 13
  139514. };
  139515. static static_codebook _44c1_sm_p8_1 = {
  139516. 2, 169,
  139517. _vq_lengthlist__44c1_sm_p8_1,
  139518. 1, -522616832, 1620115456, 4, 0,
  139519. _vq_quantlist__44c1_sm_p8_1,
  139520. NULL,
  139521. &_vq_auxt__44c1_sm_p8_1,
  139522. NULL,
  139523. 0
  139524. };
  139525. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139526. 8,
  139527. 7,
  139528. 9,
  139529. 6,
  139530. 10,
  139531. 5,
  139532. 11,
  139533. 4,
  139534. 12,
  139535. 3,
  139536. 13,
  139537. 2,
  139538. 14,
  139539. 1,
  139540. 15,
  139541. 0,
  139542. 16,
  139543. };
  139544. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139545. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139546. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139547. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139548. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139549. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139550. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139551. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139552. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139553. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139554. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139555. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139556. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139557. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139558. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139559. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139560. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139561. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139562. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139563. 9,
  139564. };
  139565. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139566. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139567. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139568. };
  139569. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139570. 15, 13, 11, 9, 7, 5, 3, 1,
  139571. 0, 2, 4, 6, 8, 10, 12, 14,
  139572. 16,
  139573. };
  139574. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139575. _vq_quantthresh__44c1_sm_p8_2,
  139576. _vq_quantmap__44c1_sm_p8_2,
  139577. 17,
  139578. 17
  139579. };
  139580. static static_codebook _44c1_sm_p8_2 = {
  139581. 2, 289,
  139582. _vq_lengthlist__44c1_sm_p8_2,
  139583. 1, -529530880, 1611661312, 5, 0,
  139584. _vq_quantlist__44c1_sm_p8_2,
  139585. NULL,
  139586. &_vq_auxt__44c1_sm_p8_2,
  139587. NULL,
  139588. 0
  139589. };
  139590. static long _huff_lengthlist__44c1_sm_short[] = {
  139591. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139592. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139593. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139594. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139595. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139596. 11,
  139597. };
  139598. static static_codebook _huff_book__44c1_sm_short = {
  139599. 2, 81,
  139600. _huff_lengthlist__44c1_sm_short,
  139601. 0, 0, 0, 0, 0,
  139602. NULL,
  139603. NULL,
  139604. NULL,
  139605. NULL,
  139606. 0
  139607. };
  139608. static long _huff_lengthlist__44cn1_s_long[] = {
  139609. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139610. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139611. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139612. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139613. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139614. 20,
  139615. };
  139616. static static_codebook _huff_book__44cn1_s_long = {
  139617. 2, 81,
  139618. _huff_lengthlist__44cn1_s_long,
  139619. 0, 0, 0, 0, 0,
  139620. NULL,
  139621. NULL,
  139622. NULL,
  139623. NULL,
  139624. 0
  139625. };
  139626. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139627. 1,
  139628. 0,
  139629. 2,
  139630. };
  139631. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139632. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139633. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139638. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139643. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  139678. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  139683. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  139688. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  139724. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  139729. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  139734. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140042. 0,
  140043. };
  140044. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140045. -0.5, 0.5,
  140046. };
  140047. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140048. 1, 0, 2,
  140049. };
  140050. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140051. _vq_quantthresh__44cn1_s_p1_0,
  140052. _vq_quantmap__44cn1_s_p1_0,
  140053. 3,
  140054. 3
  140055. };
  140056. static static_codebook _44cn1_s_p1_0 = {
  140057. 8, 6561,
  140058. _vq_lengthlist__44cn1_s_p1_0,
  140059. 1, -535822336, 1611661312, 2, 0,
  140060. _vq_quantlist__44cn1_s_p1_0,
  140061. NULL,
  140062. &_vq_auxt__44cn1_s_p1_0,
  140063. NULL,
  140064. 0
  140065. };
  140066. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140067. 2,
  140068. 1,
  140069. 3,
  140070. 0,
  140071. 4,
  140072. };
  140073. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140074. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140113. 0,
  140114. };
  140115. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140116. -1.5, -0.5, 0.5, 1.5,
  140117. };
  140118. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140119. 3, 1, 0, 2, 4,
  140120. };
  140121. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140122. _vq_quantthresh__44cn1_s_p2_0,
  140123. _vq_quantmap__44cn1_s_p2_0,
  140124. 5,
  140125. 5
  140126. };
  140127. static static_codebook _44cn1_s_p2_0 = {
  140128. 4, 625,
  140129. _vq_lengthlist__44cn1_s_p2_0,
  140130. 1, -533725184, 1611661312, 3, 0,
  140131. _vq_quantlist__44cn1_s_p2_0,
  140132. NULL,
  140133. &_vq_auxt__44cn1_s_p2_0,
  140134. NULL,
  140135. 0
  140136. };
  140137. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140138. 4,
  140139. 3,
  140140. 5,
  140141. 2,
  140142. 6,
  140143. 1,
  140144. 7,
  140145. 0,
  140146. 8,
  140147. };
  140148. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140149. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140150. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140151. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140152. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140153. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140154. 0,
  140155. };
  140156. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140157. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140158. };
  140159. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140160. 7, 5, 3, 1, 0, 2, 4, 6,
  140161. 8,
  140162. };
  140163. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140164. _vq_quantthresh__44cn1_s_p3_0,
  140165. _vq_quantmap__44cn1_s_p3_0,
  140166. 9,
  140167. 9
  140168. };
  140169. static static_codebook _44cn1_s_p3_0 = {
  140170. 2, 81,
  140171. _vq_lengthlist__44cn1_s_p3_0,
  140172. 1, -531628032, 1611661312, 4, 0,
  140173. _vq_quantlist__44cn1_s_p3_0,
  140174. NULL,
  140175. &_vq_auxt__44cn1_s_p3_0,
  140176. NULL,
  140177. 0
  140178. };
  140179. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140180. 4,
  140181. 3,
  140182. 5,
  140183. 2,
  140184. 6,
  140185. 1,
  140186. 7,
  140187. 0,
  140188. 8,
  140189. };
  140190. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140191. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140192. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140193. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140194. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140195. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140196. 11,
  140197. };
  140198. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140199. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140200. };
  140201. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140202. 7, 5, 3, 1, 0, 2, 4, 6,
  140203. 8,
  140204. };
  140205. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140206. _vq_quantthresh__44cn1_s_p4_0,
  140207. _vq_quantmap__44cn1_s_p4_0,
  140208. 9,
  140209. 9
  140210. };
  140211. static static_codebook _44cn1_s_p4_0 = {
  140212. 2, 81,
  140213. _vq_lengthlist__44cn1_s_p4_0,
  140214. 1, -531628032, 1611661312, 4, 0,
  140215. _vq_quantlist__44cn1_s_p4_0,
  140216. NULL,
  140217. &_vq_auxt__44cn1_s_p4_0,
  140218. NULL,
  140219. 0
  140220. };
  140221. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140222. 8,
  140223. 7,
  140224. 9,
  140225. 6,
  140226. 10,
  140227. 5,
  140228. 11,
  140229. 4,
  140230. 12,
  140231. 3,
  140232. 13,
  140233. 2,
  140234. 14,
  140235. 1,
  140236. 15,
  140237. 0,
  140238. 16,
  140239. };
  140240. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140241. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140242. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140243. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140244. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140245. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140246. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140247. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140248. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140249. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140250. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140251. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140252. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140253. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140254. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140255. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140256. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140257. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140259. 14,
  140260. };
  140261. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140262. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140263. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140264. };
  140265. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140266. 15, 13, 11, 9, 7, 5, 3, 1,
  140267. 0, 2, 4, 6, 8, 10, 12, 14,
  140268. 16,
  140269. };
  140270. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140271. _vq_quantthresh__44cn1_s_p5_0,
  140272. _vq_quantmap__44cn1_s_p5_0,
  140273. 17,
  140274. 17
  140275. };
  140276. static static_codebook _44cn1_s_p5_0 = {
  140277. 2, 289,
  140278. _vq_lengthlist__44cn1_s_p5_0,
  140279. 1, -529530880, 1611661312, 5, 0,
  140280. _vq_quantlist__44cn1_s_p5_0,
  140281. NULL,
  140282. &_vq_auxt__44cn1_s_p5_0,
  140283. NULL,
  140284. 0
  140285. };
  140286. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140287. 1,
  140288. 0,
  140289. 2,
  140290. };
  140291. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140292. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140293. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140294. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140295. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140296. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140297. 10,
  140298. };
  140299. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140300. -5.5, 5.5,
  140301. };
  140302. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140303. 1, 0, 2,
  140304. };
  140305. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140306. _vq_quantthresh__44cn1_s_p6_0,
  140307. _vq_quantmap__44cn1_s_p6_0,
  140308. 3,
  140309. 3
  140310. };
  140311. static static_codebook _44cn1_s_p6_0 = {
  140312. 4, 81,
  140313. _vq_lengthlist__44cn1_s_p6_0,
  140314. 1, -529137664, 1618345984, 2, 0,
  140315. _vq_quantlist__44cn1_s_p6_0,
  140316. NULL,
  140317. &_vq_auxt__44cn1_s_p6_0,
  140318. NULL,
  140319. 0
  140320. };
  140321. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140322. 5,
  140323. 4,
  140324. 6,
  140325. 3,
  140326. 7,
  140327. 2,
  140328. 8,
  140329. 1,
  140330. 9,
  140331. 0,
  140332. 10,
  140333. };
  140334. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140335. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140336. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140337. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140338. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140339. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140340. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140341. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140342. 10,10,10, 9, 9, 9, 9, 9, 9,
  140343. };
  140344. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140345. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140346. 3.5, 4.5,
  140347. };
  140348. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140349. 9, 7, 5, 3, 1, 0, 2, 4,
  140350. 6, 8, 10,
  140351. };
  140352. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140353. _vq_quantthresh__44cn1_s_p6_1,
  140354. _vq_quantmap__44cn1_s_p6_1,
  140355. 11,
  140356. 11
  140357. };
  140358. static static_codebook _44cn1_s_p6_1 = {
  140359. 2, 121,
  140360. _vq_lengthlist__44cn1_s_p6_1,
  140361. 1, -531365888, 1611661312, 4, 0,
  140362. _vq_quantlist__44cn1_s_p6_1,
  140363. NULL,
  140364. &_vq_auxt__44cn1_s_p6_1,
  140365. NULL,
  140366. 0
  140367. };
  140368. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140369. 6,
  140370. 5,
  140371. 7,
  140372. 4,
  140373. 8,
  140374. 3,
  140375. 9,
  140376. 2,
  140377. 10,
  140378. 1,
  140379. 11,
  140380. 0,
  140381. 12,
  140382. };
  140383. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140384. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140385. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140386. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140387. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140388. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140389. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140390. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140391. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140392. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140393. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140394. 0,13,13,12,12,13,13,13,14,
  140395. };
  140396. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140397. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140398. 12.5, 17.5, 22.5, 27.5,
  140399. };
  140400. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140401. 11, 9, 7, 5, 3, 1, 0, 2,
  140402. 4, 6, 8, 10, 12,
  140403. };
  140404. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140405. _vq_quantthresh__44cn1_s_p7_0,
  140406. _vq_quantmap__44cn1_s_p7_0,
  140407. 13,
  140408. 13
  140409. };
  140410. static static_codebook _44cn1_s_p7_0 = {
  140411. 2, 169,
  140412. _vq_lengthlist__44cn1_s_p7_0,
  140413. 1, -526516224, 1616117760, 4, 0,
  140414. _vq_quantlist__44cn1_s_p7_0,
  140415. NULL,
  140416. &_vq_auxt__44cn1_s_p7_0,
  140417. NULL,
  140418. 0
  140419. };
  140420. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140421. 2,
  140422. 1,
  140423. 3,
  140424. 0,
  140425. 4,
  140426. };
  140427. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140428. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140429. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140430. };
  140431. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140432. -1.5, -0.5, 0.5, 1.5,
  140433. };
  140434. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140435. 3, 1, 0, 2, 4,
  140436. };
  140437. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140438. _vq_quantthresh__44cn1_s_p7_1,
  140439. _vq_quantmap__44cn1_s_p7_1,
  140440. 5,
  140441. 5
  140442. };
  140443. static static_codebook _44cn1_s_p7_1 = {
  140444. 2, 25,
  140445. _vq_lengthlist__44cn1_s_p7_1,
  140446. 1, -533725184, 1611661312, 3, 0,
  140447. _vq_quantlist__44cn1_s_p7_1,
  140448. NULL,
  140449. &_vq_auxt__44cn1_s_p7_1,
  140450. NULL,
  140451. 0
  140452. };
  140453. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140454. 2,
  140455. 1,
  140456. 3,
  140457. 0,
  140458. 4,
  140459. };
  140460. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140461. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140462. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140463. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140464. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140465. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140468. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140470. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140474. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140476. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140480. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140494. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  140495. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140496. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140497. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140498. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140499. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140500. 12,
  140501. };
  140502. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140503. -331.5, -110.5, 110.5, 331.5,
  140504. };
  140505. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140506. 3, 1, 0, 2, 4,
  140507. };
  140508. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140509. _vq_quantthresh__44cn1_s_p8_0,
  140510. _vq_quantmap__44cn1_s_p8_0,
  140511. 5,
  140512. 5
  140513. };
  140514. static static_codebook _44cn1_s_p8_0 = {
  140515. 4, 625,
  140516. _vq_lengthlist__44cn1_s_p8_0,
  140517. 1, -518283264, 1627103232, 3, 0,
  140518. _vq_quantlist__44cn1_s_p8_0,
  140519. NULL,
  140520. &_vq_auxt__44cn1_s_p8_0,
  140521. NULL,
  140522. 0
  140523. };
  140524. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140525. 6,
  140526. 5,
  140527. 7,
  140528. 4,
  140529. 8,
  140530. 3,
  140531. 9,
  140532. 2,
  140533. 10,
  140534. 1,
  140535. 11,
  140536. 0,
  140537. 12,
  140538. };
  140539. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140540. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140541. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140542. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140543. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140544. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140545. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140546. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140547. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140548. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140549. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140550. 15,12,12,11,11,14,12,13,14,
  140551. };
  140552. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140553. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140554. 42.5, 59.5, 76.5, 93.5,
  140555. };
  140556. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140557. 11, 9, 7, 5, 3, 1, 0, 2,
  140558. 4, 6, 8, 10, 12,
  140559. };
  140560. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140561. _vq_quantthresh__44cn1_s_p8_1,
  140562. _vq_quantmap__44cn1_s_p8_1,
  140563. 13,
  140564. 13
  140565. };
  140566. static static_codebook _44cn1_s_p8_1 = {
  140567. 2, 169,
  140568. _vq_lengthlist__44cn1_s_p8_1,
  140569. 1, -522616832, 1620115456, 4, 0,
  140570. _vq_quantlist__44cn1_s_p8_1,
  140571. NULL,
  140572. &_vq_auxt__44cn1_s_p8_1,
  140573. NULL,
  140574. 0
  140575. };
  140576. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140577. 8,
  140578. 7,
  140579. 9,
  140580. 6,
  140581. 10,
  140582. 5,
  140583. 11,
  140584. 4,
  140585. 12,
  140586. 3,
  140587. 13,
  140588. 2,
  140589. 14,
  140590. 1,
  140591. 15,
  140592. 0,
  140593. 16,
  140594. };
  140595. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140596. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140597. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140598. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140599. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140600. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140601. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140602. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140603. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140604. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140605. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140606. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140607. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140608. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140609. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140610. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140611. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140612. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140613. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140614. 9,
  140615. };
  140616. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140617. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140618. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140619. };
  140620. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140621. 15, 13, 11, 9, 7, 5, 3, 1,
  140622. 0, 2, 4, 6, 8, 10, 12, 14,
  140623. 16,
  140624. };
  140625. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140626. _vq_quantthresh__44cn1_s_p8_2,
  140627. _vq_quantmap__44cn1_s_p8_2,
  140628. 17,
  140629. 17
  140630. };
  140631. static static_codebook _44cn1_s_p8_2 = {
  140632. 2, 289,
  140633. _vq_lengthlist__44cn1_s_p8_2,
  140634. 1, -529530880, 1611661312, 5, 0,
  140635. _vq_quantlist__44cn1_s_p8_2,
  140636. NULL,
  140637. &_vq_auxt__44cn1_s_p8_2,
  140638. NULL,
  140639. 0
  140640. };
  140641. static long _huff_lengthlist__44cn1_s_short[] = {
  140642. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140643. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140644. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140645. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140646. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140647. 10,
  140648. };
  140649. static static_codebook _huff_book__44cn1_s_short = {
  140650. 2, 81,
  140651. _huff_lengthlist__44cn1_s_short,
  140652. 0, 0, 0, 0, 0,
  140653. NULL,
  140654. NULL,
  140655. NULL,
  140656. NULL,
  140657. 0
  140658. };
  140659. static long _huff_lengthlist__44cn1_sm_long[] = {
  140660. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  140661. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  140662. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  140663. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  140664. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  140665. 17,
  140666. };
  140667. static static_codebook _huff_book__44cn1_sm_long = {
  140668. 2, 81,
  140669. _huff_lengthlist__44cn1_sm_long,
  140670. 0, 0, 0, 0, 0,
  140671. NULL,
  140672. NULL,
  140673. NULL,
  140674. NULL,
  140675. 0
  140676. };
  140677. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  140678. 1,
  140679. 0,
  140680. 2,
  140681. };
  140682. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  140683. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140684. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140688. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140689. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140693. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  140694. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140729. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  140734. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  140739. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  140775. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  140780. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  140785. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0,
  141094. };
  141095. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141096. -0.5, 0.5,
  141097. };
  141098. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141099. 1, 0, 2,
  141100. };
  141101. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141102. _vq_quantthresh__44cn1_sm_p1_0,
  141103. _vq_quantmap__44cn1_sm_p1_0,
  141104. 3,
  141105. 3
  141106. };
  141107. static static_codebook _44cn1_sm_p1_0 = {
  141108. 8, 6561,
  141109. _vq_lengthlist__44cn1_sm_p1_0,
  141110. 1, -535822336, 1611661312, 2, 0,
  141111. _vq_quantlist__44cn1_sm_p1_0,
  141112. NULL,
  141113. &_vq_auxt__44cn1_sm_p1_0,
  141114. NULL,
  141115. 0
  141116. };
  141117. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141118. 2,
  141119. 1,
  141120. 3,
  141121. 0,
  141122. 4,
  141123. };
  141124. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141125. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141164. 0,
  141165. };
  141166. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141167. -1.5, -0.5, 0.5, 1.5,
  141168. };
  141169. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141170. 3, 1, 0, 2, 4,
  141171. };
  141172. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141173. _vq_quantthresh__44cn1_sm_p2_0,
  141174. _vq_quantmap__44cn1_sm_p2_0,
  141175. 5,
  141176. 5
  141177. };
  141178. static static_codebook _44cn1_sm_p2_0 = {
  141179. 4, 625,
  141180. _vq_lengthlist__44cn1_sm_p2_0,
  141181. 1, -533725184, 1611661312, 3, 0,
  141182. _vq_quantlist__44cn1_sm_p2_0,
  141183. NULL,
  141184. &_vq_auxt__44cn1_sm_p2_0,
  141185. NULL,
  141186. 0
  141187. };
  141188. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141189. 4,
  141190. 3,
  141191. 5,
  141192. 2,
  141193. 6,
  141194. 1,
  141195. 7,
  141196. 0,
  141197. 8,
  141198. };
  141199. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141200. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141201. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141202. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141203. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141204. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141205. 0,
  141206. };
  141207. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141208. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141209. };
  141210. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141211. 7, 5, 3, 1, 0, 2, 4, 6,
  141212. 8,
  141213. };
  141214. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141215. _vq_quantthresh__44cn1_sm_p3_0,
  141216. _vq_quantmap__44cn1_sm_p3_0,
  141217. 9,
  141218. 9
  141219. };
  141220. static static_codebook _44cn1_sm_p3_0 = {
  141221. 2, 81,
  141222. _vq_lengthlist__44cn1_sm_p3_0,
  141223. 1, -531628032, 1611661312, 4, 0,
  141224. _vq_quantlist__44cn1_sm_p3_0,
  141225. NULL,
  141226. &_vq_auxt__44cn1_sm_p3_0,
  141227. NULL,
  141228. 0
  141229. };
  141230. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141231. 4,
  141232. 3,
  141233. 5,
  141234. 2,
  141235. 6,
  141236. 1,
  141237. 7,
  141238. 0,
  141239. 8,
  141240. };
  141241. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141242. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141243. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141244. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141245. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141246. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141247. 11,
  141248. };
  141249. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141250. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141251. };
  141252. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141253. 7, 5, 3, 1, 0, 2, 4, 6,
  141254. 8,
  141255. };
  141256. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141257. _vq_quantthresh__44cn1_sm_p4_0,
  141258. _vq_quantmap__44cn1_sm_p4_0,
  141259. 9,
  141260. 9
  141261. };
  141262. static static_codebook _44cn1_sm_p4_0 = {
  141263. 2, 81,
  141264. _vq_lengthlist__44cn1_sm_p4_0,
  141265. 1, -531628032, 1611661312, 4, 0,
  141266. _vq_quantlist__44cn1_sm_p4_0,
  141267. NULL,
  141268. &_vq_auxt__44cn1_sm_p4_0,
  141269. NULL,
  141270. 0
  141271. };
  141272. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141273. 8,
  141274. 7,
  141275. 9,
  141276. 6,
  141277. 10,
  141278. 5,
  141279. 11,
  141280. 4,
  141281. 12,
  141282. 3,
  141283. 13,
  141284. 2,
  141285. 14,
  141286. 1,
  141287. 15,
  141288. 0,
  141289. 16,
  141290. };
  141291. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141292. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141293. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141294. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141295. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141296. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141297. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141298. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141299. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141300. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141301. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141302. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141303. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141304. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141305. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141306. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141307. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141308. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141310. 14,
  141311. };
  141312. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141313. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141314. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141315. };
  141316. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141317. 15, 13, 11, 9, 7, 5, 3, 1,
  141318. 0, 2, 4, 6, 8, 10, 12, 14,
  141319. 16,
  141320. };
  141321. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141322. _vq_quantthresh__44cn1_sm_p5_0,
  141323. _vq_quantmap__44cn1_sm_p5_0,
  141324. 17,
  141325. 17
  141326. };
  141327. static static_codebook _44cn1_sm_p5_0 = {
  141328. 2, 289,
  141329. _vq_lengthlist__44cn1_sm_p5_0,
  141330. 1, -529530880, 1611661312, 5, 0,
  141331. _vq_quantlist__44cn1_sm_p5_0,
  141332. NULL,
  141333. &_vq_auxt__44cn1_sm_p5_0,
  141334. NULL,
  141335. 0
  141336. };
  141337. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141338. 1,
  141339. 0,
  141340. 2,
  141341. };
  141342. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141343. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141344. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141345. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141346. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141347. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141348. 10,
  141349. };
  141350. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141351. -5.5, 5.5,
  141352. };
  141353. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141354. 1, 0, 2,
  141355. };
  141356. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141357. _vq_quantthresh__44cn1_sm_p6_0,
  141358. _vq_quantmap__44cn1_sm_p6_0,
  141359. 3,
  141360. 3
  141361. };
  141362. static static_codebook _44cn1_sm_p6_0 = {
  141363. 4, 81,
  141364. _vq_lengthlist__44cn1_sm_p6_0,
  141365. 1, -529137664, 1618345984, 2, 0,
  141366. _vq_quantlist__44cn1_sm_p6_0,
  141367. NULL,
  141368. &_vq_auxt__44cn1_sm_p6_0,
  141369. NULL,
  141370. 0
  141371. };
  141372. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141373. 5,
  141374. 4,
  141375. 6,
  141376. 3,
  141377. 7,
  141378. 2,
  141379. 8,
  141380. 1,
  141381. 9,
  141382. 0,
  141383. 10,
  141384. };
  141385. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141386. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141387. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141388. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141389. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141390. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141391. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141392. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141393. 10,10,10, 8, 9, 8, 8, 9, 8,
  141394. };
  141395. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141396. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141397. 3.5, 4.5,
  141398. };
  141399. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141400. 9, 7, 5, 3, 1, 0, 2, 4,
  141401. 6, 8, 10,
  141402. };
  141403. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141404. _vq_quantthresh__44cn1_sm_p6_1,
  141405. _vq_quantmap__44cn1_sm_p6_1,
  141406. 11,
  141407. 11
  141408. };
  141409. static static_codebook _44cn1_sm_p6_1 = {
  141410. 2, 121,
  141411. _vq_lengthlist__44cn1_sm_p6_1,
  141412. 1, -531365888, 1611661312, 4, 0,
  141413. _vq_quantlist__44cn1_sm_p6_1,
  141414. NULL,
  141415. &_vq_auxt__44cn1_sm_p6_1,
  141416. NULL,
  141417. 0
  141418. };
  141419. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141420. 6,
  141421. 5,
  141422. 7,
  141423. 4,
  141424. 8,
  141425. 3,
  141426. 9,
  141427. 2,
  141428. 10,
  141429. 1,
  141430. 11,
  141431. 0,
  141432. 12,
  141433. };
  141434. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141435. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141436. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141437. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141438. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141439. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141440. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141441. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141442. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141443. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141444. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141445. 0,13,12,12,12,13,13,13,14,
  141446. };
  141447. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141448. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141449. 12.5, 17.5, 22.5, 27.5,
  141450. };
  141451. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141452. 11, 9, 7, 5, 3, 1, 0, 2,
  141453. 4, 6, 8, 10, 12,
  141454. };
  141455. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141456. _vq_quantthresh__44cn1_sm_p7_0,
  141457. _vq_quantmap__44cn1_sm_p7_0,
  141458. 13,
  141459. 13
  141460. };
  141461. static static_codebook _44cn1_sm_p7_0 = {
  141462. 2, 169,
  141463. _vq_lengthlist__44cn1_sm_p7_0,
  141464. 1, -526516224, 1616117760, 4, 0,
  141465. _vq_quantlist__44cn1_sm_p7_0,
  141466. NULL,
  141467. &_vq_auxt__44cn1_sm_p7_0,
  141468. NULL,
  141469. 0
  141470. };
  141471. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141472. 2,
  141473. 1,
  141474. 3,
  141475. 0,
  141476. 4,
  141477. };
  141478. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141479. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141480. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141481. };
  141482. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141483. -1.5, -0.5, 0.5, 1.5,
  141484. };
  141485. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141486. 3, 1, 0, 2, 4,
  141487. };
  141488. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141489. _vq_quantthresh__44cn1_sm_p7_1,
  141490. _vq_quantmap__44cn1_sm_p7_1,
  141491. 5,
  141492. 5
  141493. };
  141494. static static_codebook _44cn1_sm_p7_1 = {
  141495. 2, 25,
  141496. _vq_lengthlist__44cn1_sm_p7_1,
  141497. 1, -533725184, 1611661312, 3, 0,
  141498. _vq_quantlist__44cn1_sm_p7_1,
  141499. NULL,
  141500. &_vq_auxt__44cn1_sm_p7_1,
  141501. NULL,
  141502. 0
  141503. };
  141504. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141505. 4,
  141506. 3,
  141507. 5,
  141508. 2,
  141509. 6,
  141510. 1,
  141511. 7,
  141512. 0,
  141513. 8,
  141514. };
  141515. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141516. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141517. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141518. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141519. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141520. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141521. 14,
  141522. };
  141523. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141524. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141525. };
  141526. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141527. 7, 5, 3, 1, 0, 2, 4, 6,
  141528. 8,
  141529. };
  141530. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141531. _vq_quantthresh__44cn1_sm_p8_0,
  141532. _vq_quantmap__44cn1_sm_p8_0,
  141533. 9,
  141534. 9
  141535. };
  141536. static static_codebook _44cn1_sm_p8_0 = {
  141537. 2, 81,
  141538. _vq_lengthlist__44cn1_sm_p8_0,
  141539. 1, -516186112, 1627103232, 4, 0,
  141540. _vq_quantlist__44cn1_sm_p8_0,
  141541. NULL,
  141542. &_vq_auxt__44cn1_sm_p8_0,
  141543. NULL,
  141544. 0
  141545. };
  141546. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141547. 6,
  141548. 5,
  141549. 7,
  141550. 4,
  141551. 8,
  141552. 3,
  141553. 9,
  141554. 2,
  141555. 10,
  141556. 1,
  141557. 11,
  141558. 0,
  141559. 12,
  141560. };
  141561. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141562. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141563. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141564. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141565. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141566. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141567. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141568. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141569. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141570. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141571. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141572. 17,12,12,11,10,13,11,13,13,
  141573. };
  141574. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141575. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141576. 42.5, 59.5, 76.5, 93.5,
  141577. };
  141578. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141579. 11, 9, 7, 5, 3, 1, 0, 2,
  141580. 4, 6, 8, 10, 12,
  141581. };
  141582. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141583. _vq_quantthresh__44cn1_sm_p8_1,
  141584. _vq_quantmap__44cn1_sm_p8_1,
  141585. 13,
  141586. 13
  141587. };
  141588. static static_codebook _44cn1_sm_p8_1 = {
  141589. 2, 169,
  141590. _vq_lengthlist__44cn1_sm_p8_1,
  141591. 1, -522616832, 1620115456, 4, 0,
  141592. _vq_quantlist__44cn1_sm_p8_1,
  141593. NULL,
  141594. &_vq_auxt__44cn1_sm_p8_1,
  141595. NULL,
  141596. 0
  141597. };
  141598. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141599. 8,
  141600. 7,
  141601. 9,
  141602. 6,
  141603. 10,
  141604. 5,
  141605. 11,
  141606. 4,
  141607. 12,
  141608. 3,
  141609. 13,
  141610. 2,
  141611. 14,
  141612. 1,
  141613. 15,
  141614. 0,
  141615. 16,
  141616. };
  141617. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141618. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141619. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141620. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141621. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141622. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141623. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141624. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141625. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141626. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141627. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141628. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141629. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141630. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141631. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141632. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141633. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141634. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141635. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141636. 9,
  141637. };
  141638. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141639. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141640. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141641. };
  141642. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141643. 15, 13, 11, 9, 7, 5, 3, 1,
  141644. 0, 2, 4, 6, 8, 10, 12, 14,
  141645. 16,
  141646. };
  141647. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141648. _vq_quantthresh__44cn1_sm_p8_2,
  141649. _vq_quantmap__44cn1_sm_p8_2,
  141650. 17,
  141651. 17
  141652. };
  141653. static static_codebook _44cn1_sm_p8_2 = {
  141654. 2, 289,
  141655. _vq_lengthlist__44cn1_sm_p8_2,
  141656. 1, -529530880, 1611661312, 5, 0,
  141657. _vq_quantlist__44cn1_sm_p8_2,
  141658. NULL,
  141659. &_vq_auxt__44cn1_sm_p8_2,
  141660. NULL,
  141661. 0
  141662. };
  141663. static long _huff_lengthlist__44cn1_sm_short[] = {
  141664. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  141665. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  141666. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  141667. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  141668. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  141669. 9,
  141670. };
  141671. static static_codebook _huff_book__44cn1_sm_short = {
  141672. 2, 81,
  141673. _huff_lengthlist__44cn1_sm_short,
  141674. 0, 0, 0, 0, 0,
  141675. NULL,
  141676. NULL,
  141677. NULL,
  141678. NULL,
  141679. 0
  141680. };
  141681. /*** End of inlined file: res_books_stereo.h ***/
  141682. /***** residue backends *********************************************/
  141683. static vorbis_info_residue0 _residue_44_low={
  141684. 0,-1, -1, 9,-1,
  141685. /* 0 1 2 3 4 5 6 7 */
  141686. {0},
  141687. {-1},
  141688. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141689. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  141690. };
  141691. static vorbis_info_residue0 _residue_44_mid={
  141692. 0,-1, -1, 10,-1,
  141693. /* 0 1 2 3 4 5 6 7 8 */
  141694. {0},
  141695. {-1},
  141696. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  141697. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  141698. };
  141699. static vorbis_info_residue0 _residue_44_high={
  141700. 0,-1, -1, 10,-1,
  141701. /* 0 1 2 3 4 5 6 7 8 */
  141702. {0},
  141703. {-1},
  141704. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  141705. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  141706. };
  141707. static static_bookblock _resbook_44s_n1={
  141708. {
  141709. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  141710. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  141711. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  141712. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  141713. }
  141714. };
  141715. static static_bookblock _resbook_44sm_n1={
  141716. {
  141717. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  141718. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  141719. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  141720. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  141721. }
  141722. };
  141723. static static_bookblock _resbook_44s_0={
  141724. {
  141725. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  141726. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  141727. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  141728. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  141729. }
  141730. };
  141731. static static_bookblock _resbook_44sm_0={
  141732. {
  141733. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  141734. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  141735. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  141736. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  141737. }
  141738. };
  141739. static static_bookblock _resbook_44s_1={
  141740. {
  141741. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  141742. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  141743. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  141744. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  141745. }
  141746. };
  141747. static static_bookblock _resbook_44sm_1={
  141748. {
  141749. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  141750. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  141751. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  141752. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  141753. }
  141754. };
  141755. static static_bookblock _resbook_44s_2={
  141756. {
  141757. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  141758. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  141759. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  141760. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  141761. }
  141762. };
  141763. static static_bookblock _resbook_44s_3={
  141764. {
  141765. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  141766. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  141767. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  141768. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  141769. }
  141770. };
  141771. static static_bookblock _resbook_44s_4={
  141772. {
  141773. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  141774. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  141775. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  141776. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  141777. }
  141778. };
  141779. static static_bookblock _resbook_44s_5={
  141780. {
  141781. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  141782. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  141783. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  141784. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  141785. }
  141786. };
  141787. static static_bookblock _resbook_44s_6={
  141788. {
  141789. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  141790. {0,0,&_44c6_s_p4_0},
  141791. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  141792. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  141793. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  141794. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  141795. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  141796. }
  141797. };
  141798. static static_bookblock _resbook_44s_7={
  141799. {
  141800. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  141801. {0,0,&_44c7_s_p4_0},
  141802. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  141803. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  141804. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  141805. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  141806. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  141807. }
  141808. };
  141809. static static_bookblock _resbook_44s_8={
  141810. {
  141811. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  141812. {0,0,&_44c8_s_p4_0},
  141813. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  141814. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  141815. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  141816. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  141817. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  141818. }
  141819. };
  141820. static static_bookblock _resbook_44s_9={
  141821. {
  141822. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  141823. {0,0,&_44c9_s_p4_0},
  141824. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  141825. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  141826. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  141827. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  141828. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  141829. }
  141830. };
  141831. static vorbis_residue_template _res_44s_n1[]={
  141832. {2,0, &_residue_44_low,
  141833. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  141834. &_resbook_44s_n1,&_resbook_44sm_n1},
  141835. {2,0, &_residue_44_low,
  141836. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  141837. &_resbook_44s_n1,&_resbook_44sm_n1}
  141838. };
  141839. static vorbis_residue_template _res_44s_0[]={
  141840. {2,0, &_residue_44_low,
  141841. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  141842. &_resbook_44s_0,&_resbook_44sm_0},
  141843. {2,0, &_residue_44_low,
  141844. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  141845. &_resbook_44s_0,&_resbook_44sm_0}
  141846. };
  141847. static vorbis_residue_template _res_44s_1[]={
  141848. {2,0, &_residue_44_low,
  141849. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  141850. &_resbook_44s_1,&_resbook_44sm_1},
  141851. {2,0, &_residue_44_low,
  141852. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  141853. &_resbook_44s_1,&_resbook_44sm_1}
  141854. };
  141855. static vorbis_residue_template _res_44s_2[]={
  141856. {2,0, &_residue_44_mid,
  141857. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  141858. &_resbook_44s_2,&_resbook_44s_2},
  141859. {2,0, &_residue_44_mid,
  141860. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  141861. &_resbook_44s_2,&_resbook_44s_2}
  141862. };
  141863. static vorbis_residue_template _res_44s_3[]={
  141864. {2,0, &_residue_44_mid,
  141865. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  141866. &_resbook_44s_3,&_resbook_44s_3},
  141867. {2,0, &_residue_44_mid,
  141868. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  141869. &_resbook_44s_3,&_resbook_44s_3}
  141870. };
  141871. static vorbis_residue_template _res_44s_4[]={
  141872. {2,0, &_residue_44_mid,
  141873. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  141874. &_resbook_44s_4,&_resbook_44s_4},
  141875. {2,0, &_residue_44_mid,
  141876. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  141877. &_resbook_44s_4,&_resbook_44s_4}
  141878. };
  141879. static vorbis_residue_template _res_44s_5[]={
  141880. {2,0, &_residue_44_mid,
  141881. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  141882. &_resbook_44s_5,&_resbook_44s_5},
  141883. {2,0, &_residue_44_mid,
  141884. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  141885. &_resbook_44s_5,&_resbook_44s_5}
  141886. };
  141887. static vorbis_residue_template _res_44s_6[]={
  141888. {2,0, &_residue_44_high,
  141889. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  141890. &_resbook_44s_6,&_resbook_44s_6},
  141891. {2,0, &_residue_44_high,
  141892. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  141893. &_resbook_44s_6,&_resbook_44s_6}
  141894. };
  141895. static vorbis_residue_template _res_44s_7[]={
  141896. {2,0, &_residue_44_high,
  141897. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  141898. &_resbook_44s_7,&_resbook_44s_7},
  141899. {2,0, &_residue_44_high,
  141900. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  141901. &_resbook_44s_7,&_resbook_44s_7}
  141902. };
  141903. static vorbis_residue_template _res_44s_8[]={
  141904. {2,0, &_residue_44_high,
  141905. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  141906. &_resbook_44s_8,&_resbook_44s_8},
  141907. {2,0, &_residue_44_high,
  141908. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  141909. &_resbook_44s_8,&_resbook_44s_8}
  141910. };
  141911. static vorbis_residue_template _res_44s_9[]={
  141912. {2,0, &_residue_44_high,
  141913. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  141914. &_resbook_44s_9,&_resbook_44s_9},
  141915. {2,0, &_residue_44_high,
  141916. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  141917. &_resbook_44s_9,&_resbook_44s_9}
  141918. };
  141919. static vorbis_mapping_template _mapres_template_44_stereo[]={
  141920. { _map_nominal, _res_44s_n1 }, /* -1 */
  141921. { _map_nominal, _res_44s_0 }, /* 0 */
  141922. { _map_nominal, _res_44s_1 }, /* 1 */
  141923. { _map_nominal, _res_44s_2 }, /* 2 */
  141924. { _map_nominal, _res_44s_3 }, /* 3 */
  141925. { _map_nominal, _res_44s_4 }, /* 4 */
  141926. { _map_nominal, _res_44s_5 }, /* 5 */
  141927. { _map_nominal, _res_44s_6 }, /* 6 */
  141928. { _map_nominal, _res_44s_7 }, /* 7 */
  141929. { _map_nominal, _res_44s_8 }, /* 8 */
  141930. { _map_nominal, _res_44s_9 }, /* 9 */
  141931. };
  141932. /*** End of inlined file: residue_44.h ***/
  141933. /*** Start of inlined file: psych_44.h ***/
  141934. /* preecho trigger settings *****************************************/
  141935. static vorbis_info_psy_global _psy_global_44[5]={
  141936. {8, /* lines per eighth octave */
  141937. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  141938. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  141939. -6.f,
  141940. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141941. },
  141942. {8, /* lines per eighth octave */
  141943. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141944. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  141945. -6.f,
  141946. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141947. },
  141948. {8, /* lines per eighth octave */
  141949. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  141950. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  141951. -6.f,
  141952. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141953. },
  141954. {8, /* lines per eighth octave */
  141955. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  141956. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  141957. -6.f,
  141958. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141959. },
  141960. {8, /* lines per eighth octave */
  141961. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  141962. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  141963. -6.f,
  141964. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  141965. },
  141966. };
  141967. /* noise compander lookups * low, mid, high quality ****************/
  141968. static compandblock _psy_compand_44[6]={
  141969. /* sub-mode Z short */
  141970. {{
  141971. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141972. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141973. 16,17,18,19,20,21,22, 23, /* 23dB */
  141974. 24,25,26,27,28,29,30, 31, /* 31dB */
  141975. 32,33,34,35,36,37,38, 39, /* 39dB */
  141976. }},
  141977. /* mode_Z nominal short */
  141978. {{
  141979. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  141980. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  141981. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  141982. 15,16,17,17,17,18,18, 19, /* 31dB */
  141983. 19,19,20,21,22,23,24, 25, /* 39dB */
  141984. }},
  141985. /* mode A short */
  141986. {{
  141987. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  141988. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  141989. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  141990. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  141991. 11,12,13,14,15,16,17, 18, /* 39dB */
  141992. }},
  141993. /* sub-mode Z long */
  141994. {{
  141995. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  141996. 8, 9,10,11,12,13,14, 15, /* 15dB */
  141997. 16,17,18,19,20,21,22, 23, /* 23dB */
  141998. 24,25,26,27,28,29,30, 31, /* 31dB */
  141999. 32,33,34,35,36,37,38, 39, /* 39dB */
  142000. }},
  142001. /* mode_Z nominal long */
  142002. {{
  142003. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142004. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142005. 13,14,14,14,15,15,15, 15, /* 23dB */
  142006. 16,16,17,17,17,18,18, 19, /* 31dB */
  142007. 19,19,20,21,22,23,24, 25, /* 39dB */
  142008. }},
  142009. /* mode A long */
  142010. {{
  142011. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142012. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142013. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142014. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142015. 11,12,13,14,15,16,17, 18, /* 39dB */
  142016. }}
  142017. };
  142018. /* tonal masking curve level adjustments *************************/
  142019. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142020. /* 63 125 250 500 1 2 4 8 16 */
  142021. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142022. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142023. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142024. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142025. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142026. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142027. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142028. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142029. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142030. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142031. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142032. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142033. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142034. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142035. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142036. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142037. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142038. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142039. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142040. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142041. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142042. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142043. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142044. };
  142045. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142046. /* 63 125 250 500 1 2 4 8 16 */
  142047. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142048. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142049. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142050. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142051. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142052. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142053. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142054. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142055. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142056. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142057. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142058. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142059. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142060. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142061. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142062. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142063. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142064. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142065. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142066. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142067. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142068. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142069. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142070. };
  142071. /* noise bias (transition block) */
  142072. static noise3 _psy_noisebias_trans[12]={
  142073. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142074. /* -1 */
  142075. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142076. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142077. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142078. /* 0
  142079. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142080. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142081. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142082. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142083. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142084. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142085. /* 1
  142086. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142087. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142088. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142089. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142090. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142091. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142092. /* 2
  142093. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142094. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142095. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142096. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142097. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142098. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142099. /* 3
  142100. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142101. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142102. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142103. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142104. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142105. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142106. /* 4
  142107. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142108. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142109. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142110. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142111. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142112. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142113. /* 5
  142114. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142115. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142116. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142117. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142118. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142119. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142120. /* 6
  142121. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142122. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142123. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142124. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142125. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142126. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142127. /* 7
  142128. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142129. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142130. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142131. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142132. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142133. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142134. /* 8
  142135. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142136. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142137. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142138. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142139. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142140. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142141. /* 9
  142142. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142143. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142144. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142145. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142146. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142147. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142148. /* 10 */
  142149. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142150. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142151. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142152. };
  142153. /* noise bias (long block) */
  142154. static noise3 _psy_noisebias_long[12]={
  142155. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142156. /* -1 */
  142157. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142158. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142159. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142160. /* 0 */
  142161. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142162. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142163. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142164. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142165. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142166. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142167. /* 1 */
  142168. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142169. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142170. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142171. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142172. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142173. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142174. /* 2 */
  142175. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142176. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142177. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142178. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142179. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142180. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142181. /* 3 */
  142182. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142183. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142184. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142185. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142186. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142187. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142188. /* 4 */
  142189. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142190. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142191. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142192. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142193. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142194. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142195. /* 5 */
  142196. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142197. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142198. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142199. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142200. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142201. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142202. /* 6 */
  142203. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142204. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142205. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142206. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142207. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142208. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142209. /* 7 */
  142210. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142211. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142212. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142213. /* 8 */
  142214. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142215. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142216. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142217. /* 9 */
  142218. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142219. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142220. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142221. /* 10 */
  142222. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142223. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142224. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142225. };
  142226. /* noise bias (impulse block) */
  142227. static noise3 _psy_noisebias_impulse[12]={
  142228. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142229. /* -1 */
  142230. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142231. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142232. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142233. /* 0 */
  142234. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142235. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142236. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142237. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142238. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142239. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142240. /* 1 */
  142241. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142242. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142243. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142244. /* 2 */
  142245. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142246. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142247. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142248. /* 3 */
  142249. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142250. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142251. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142252. /* 4 */
  142253. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142254. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142255. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142256. /* 5 */
  142257. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142258. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142259. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142260. /* 6
  142261. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142262. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142263. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142264. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142265. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142266. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142267. /* 7 */
  142268. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142269. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142270. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142271. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142272. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142273. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142274. /* 8 */
  142275. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142276. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142277. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142278. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142279. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142280. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142281. /* 9 */
  142282. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142283. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142284. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142285. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142286. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142287. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142288. /* 10 */
  142289. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142290. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142291. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142292. };
  142293. /* noise bias (padding block) */
  142294. static noise3 _psy_noisebias_padding[12]={
  142295. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142296. /* -1 */
  142297. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142298. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142299. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142300. /* 0 */
  142301. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142302. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142303. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142304. /* 1 */
  142305. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142306. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142307. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142308. /* 2 */
  142309. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142310. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142311. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142312. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142313. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142314. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142315. /* 3 */
  142316. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142317. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142318. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142319. /* 4 */
  142320. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142321. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142322. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142323. /* 5 */
  142324. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142325. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142326. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142327. /* 6 */
  142328. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142329. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142330. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142331. /* 7 */
  142332. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142333. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142334. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142335. /* 8 */
  142336. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142337. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142338. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142339. /* 9 */
  142340. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142341. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142342. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142343. /* 10 */
  142344. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142345. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142346. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142347. };
  142348. static noiseguard _psy_noiseguards_44[4]={
  142349. {3,3,15},
  142350. {3,3,15},
  142351. {10,10,100},
  142352. {10,10,100},
  142353. };
  142354. static int _psy_tone_suppress[12]={
  142355. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142356. };
  142357. static int _psy_tone_0dB[12]={
  142358. 90,90,95,95,95,95,105,105,105,105,105,105,
  142359. };
  142360. static int _psy_noise_suppress[12]={
  142361. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142362. };
  142363. static vorbis_info_psy _psy_info_template={
  142364. /* blockflag */
  142365. -1,
  142366. /* ath_adjatt, ath_maxatt */
  142367. -140.,-140.,
  142368. /* tonemask att boost/decay,suppr,curves */
  142369. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142370. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142371. 1, -0.f, .5f, .5f, 0,0,0,
  142372. /* noiseoffset*3, noisecompand, max_curve_dB */
  142373. {{-1},{-1},{-1}},{-1},105.f,
  142374. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142375. 0,0,-1,-1,0.,
  142376. };
  142377. /* ath ****************/
  142378. static int _psy_ath_floater[12]={
  142379. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142380. };
  142381. static int _psy_ath_abs[12]={
  142382. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142383. };
  142384. /* stereo setup. These don't map directly to quality level, there's
  142385. an additional indirection as several of the below may be used in a
  142386. single bitmanaged stream
  142387. ****************/
  142388. /* various stereo possibilities */
  142389. /* stereo mode by base quality level */
  142390. static adj_stereo _psy_stereo_modes_44[12]={
  142391. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142392. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142393. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142394. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142395. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142396. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142397. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142398. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142399. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142400. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142401. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142402. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142403. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142404. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142405. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142406. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142407. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142408. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142409. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142410. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142411. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142412. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142413. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142414. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142415. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142416. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142417. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142418. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142419. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142420. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142421. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142422. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142423. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142424. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142425. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142426. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142427. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142428. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142429. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142430. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142431. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142432. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142433. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142434. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142435. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142436. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142437. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142438. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142439. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142440. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142441. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142442. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142443. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142444. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142445. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142446. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142447. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142448. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142449. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142450. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142451. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142452. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142453. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142454. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142455. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142456. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142457. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142458. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142459. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142460. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142461. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142462. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142463. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142464. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142465. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142466. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142467. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142468. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142469. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142470. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142471. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142472. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142473. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142474. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142475. };
  142476. /* tone master attenuation by base quality mode and bitrate tweak */
  142477. static att3 _psy_tone_masteratt_44[12]={
  142478. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142479. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142480. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142481. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142482. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142483. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142484. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142485. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142486. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142487. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142488. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142489. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142490. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142491. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142492. };
  142493. /* lowpass by mode **************/
  142494. static double _psy_lowpass_44[12]={
  142495. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142496. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142497. };
  142498. /* noise normalization **********/
  142499. static int _noise_start_short_44[11]={
  142500. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142501. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142502. };
  142503. static int _noise_start_long_44[11]={
  142504. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142505. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142506. };
  142507. static int _noise_part_short_44[11]={
  142508. 8,8,8,8,8,8,8,8,8,8,8
  142509. };
  142510. static int _noise_part_long_44[11]={
  142511. 32,32,32,32,32,32,32,32,32,32,32
  142512. };
  142513. static double _noise_thresh_44[11]={
  142514. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142515. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142516. };
  142517. static double _noise_thresh_5only[2]={
  142518. .5,.5,
  142519. };
  142520. /*** End of inlined file: psych_44.h ***/
  142521. static double rate_mapping_44_stereo[12]={
  142522. 22500.,32000.,40000.,48000.,56000.,64000.,
  142523. 80000.,96000.,112000.,128000.,160000.,250001.
  142524. };
  142525. static double quality_mapping_44[12]={
  142526. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142527. };
  142528. static int blocksize_short_44[11]={
  142529. 512,256,256,256,256,256,256,256,256,256,256
  142530. };
  142531. static int blocksize_long_44[11]={
  142532. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142533. };
  142534. static double _psy_compand_short_mapping[12]={
  142535. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142536. };
  142537. static double _psy_compand_long_mapping[12]={
  142538. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142539. };
  142540. static double _global_mapping_44[12]={
  142541. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142542. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142543. };
  142544. static int _floor_short_mapping_44[11]={
  142545. 1,0,0,2,2,4,5,5,5,5,5
  142546. };
  142547. static int _floor_long_mapping_44[11]={
  142548. 8,7,7,7,7,7,7,7,7,7,7
  142549. };
  142550. ve_setup_data_template ve_setup_44_stereo={
  142551. 11,
  142552. rate_mapping_44_stereo,
  142553. quality_mapping_44,
  142554. 2,
  142555. 40000,
  142556. 50000,
  142557. blocksize_short_44,
  142558. blocksize_long_44,
  142559. _psy_tone_masteratt_44,
  142560. _psy_tone_0dB,
  142561. _psy_tone_suppress,
  142562. _vp_tonemask_adj_otherblock,
  142563. _vp_tonemask_adj_longblock,
  142564. _vp_tonemask_adj_otherblock,
  142565. _psy_noiseguards_44,
  142566. _psy_noisebias_impulse,
  142567. _psy_noisebias_padding,
  142568. _psy_noisebias_trans,
  142569. _psy_noisebias_long,
  142570. _psy_noise_suppress,
  142571. _psy_compand_44,
  142572. _psy_compand_short_mapping,
  142573. _psy_compand_long_mapping,
  142574. {_noise_start_short_44,_noise_start_long_44},
  142575. {_noise_part_short_44,_noise_part_long_44},
  142576. _noise_thresh_44,
  142577. _psy_ath_floater,
  142578. _psy_ath_abs,
  142579. _psy_lowpass_44,
  142580. _psy_global_44,
  142581. _global_mapping_44,
  142582. _psy_stereo_modes_44,
  142583. _floor_books,
  142584. _floor,
  142585. _floor_short_mapping_44,
  142586. _floor_long_mapping_44,
  142587. _mapres_template_44_stereo
  142588. };
  142589. /*** End of inlined file: setup_44.h ***/
  142590. /*** Start of inlined file: setup_44u.h ***/
  142591. /*** Start of inlined file: residue_44u.h ***/
  142592. /*** Start of inlined file: res_books_uncoupled.h ***/
  142593. static long _vq_quantlist__16u0__p1_0[] = {
  142594. 1,
  142595. 0,
  142596. 2,
  142597. };
  142598. static long _vq_lengthlist__16u0__p1_0[] = {
  142599. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142600. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142601. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142602. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142603. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142604. 12,
  142605. };
  142606. static float _vq_quantthresh__16u0__p1_0[] = {
  142607. -0.5, 0.5,
  142608. };
  142609. static long _vq_quantmap__16u0__p1_0[] = {
  142610. 1, 0, 2,
  142611. };
  142612. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142613. _vq_quantthresh__16u0__p1_0,
  142614. _vq_quantmap__16u0__p1_0,
  142615. 3,
  142616. 3
  142617. };
  142618. static static_codebook _16u0__p1_0 = {
  142619. 4, 81,
  142620. _vq_lengthlist__16u0__p1_0,
  142621. 1, -535822336, 1611661312, 2, 0,
  142622. _vq_quantlist__16u0__p1_0,
  142623. NULL,
  142624. &_vq_auxt__16u0__p1_0,
  142625. NULL,
  142626. 0
  142627. };
  142628. static long _vq_quantlist__16u0__p2_0[] = {
  142629. 1,
  142630. 0,
  142631. 2,
  142632. };
  142633. static long _vq_lengthlist__16u0__p2_0[] = {
  142634. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142635. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142636. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142637. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142638. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142639. 8,
  142640. };
  142641. static float _vq_quantthresh__16u0__p2_0[] = {
  142642. -0.5, 0.5,
  142643. };
  142644. static long _vq_quantmap__16u0__p2_0[] = {
  142645. 1, 0, 2,
  142646. };
  142647. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142648. _vq_quantthresh__16u0__p2_0,
  142649. _vq_quantmap__16u0__p2_0,
  142650. 3,
  142651. 3
  142652. };
  142653. static static_codebook _16u0__p2_0 = {
  142654. 4, 81,
  142655. _vq_lengthlist__16u0__p2_0,
  142656. 1, -535822336, 1611661312, 2, 0,
  142657. _vq_quantlist__16u0__p2_0,
  142658. NULL,
  142659. &_vq_auxt__16u0__p2_0,
  142660. NULL,
  142661. 0
  142662. };
  142663. static long _vq_quantlist__16u0__p3_0[] = {
  142664. 2,
  142665. 1,
  142666. 3,
  142667. 0,
  142668. 4,
  142669. };
  142670. static long _vq_lengthlist__16u0__p3_0[] = {
  142671. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  142672. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  142673. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  142674. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  142675. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  142676. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  142677. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  142678. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  142679. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  142680. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  142681. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  142682. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  142683. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  142684. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  142685. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  142686. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  142687. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  142688. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  142689. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  142690. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  142691. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  142692. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  142693. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  142694. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  142695. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  142696. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  142697. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  142698. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  142699. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  142700. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  142701. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  142702. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  142703. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  142704. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  142705. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  142706. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  142707. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  142708. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  142709. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  142710. 18,
  142711. };
  142712. static float _vq_quantthresh__16u0__p3_0[] = {
  142713. -1.5, -0.5, 0.5, 1.5,
  142714. };
  142715. static long _vq_quantmap__16u0__p3_0[] = {
  142716. 3, 1, 0, 2, 4,
  142717. };
  142718. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  142719. _vq_quantthresh__16u0__p3_0,
  142720. _vq_quantmap__16u0__p3_0,
  142721. 5,
  142722. 5
  142723. };
  142724. static static_codebook _16u0__p3_0 = {
  142725. 4, 625,
  142726. _vq_lengthlist__16u0__p3_0,
  142727. 1, -533725184, 1611661312, 3, 0,
  142728. _vq_quantlist__16u0__p3_0,
  142729. NULL,
  142730. &_vq_auxt__16u0__p3_0,
  142731. NULL,
  142732. 0
  142733. };
  142734. static long _vq_quantlist__16u0__p4_0[] = {
  142735. 2,
  142736. 1,
  142737. 3,
  142738. 0,
  142739. 4,
  142740. };
  142741. static long _vq_lengthlist__16u0__p4_0[] = {
  142742. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  142743. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  142744. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142745. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  142746. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  142747. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  142748. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  142749. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  142750. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  142751. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  142752. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  142753. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  142754. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  142755. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  142756. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  142757. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  142758. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  142759. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142760. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  142761. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  142762. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  142763. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  142764. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  142765. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  142766. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  142767. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  142768. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  142769. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  142770. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  142771. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  142772. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  142773. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  142774. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  142775. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  142776. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  142777. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  142778. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  142779. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  142780. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  142781. 11,
  142782. };
  142783. static float _vq_quantthresh__16u0__p4_0[] = {
  142784. -1.5, -0.5, 0.5, 1.5,
  142785. };
  142786. static long _vq_quantmap__16u0__p4_0[] = {
  142787. 3, 1, 0, 2, 4,
  142788. };
  142789. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  142790. _vq_quantthresh__16u0__p4_0,
  142791. _vq_quantmap__16u0__p4_0,
  142792. 5,
  142793. 5
  142794. };
  142795. static static_codebook _16u0__p4_0 = {
  142796. 4, 625,
  142797. _vq_lengthlist__16u0__p4_0,
  142798. 1, -533725184, 1611661312, 3, 0,
  142799. _vq_quantlist__16u0__p4_0,
  142800. NULL,
  142801. &_vq_auxt__16u0__p4_0,
  142802. NULL,
  142803. 0
  142804. };
  142805. static long _vq_quantlist__16u0__p5_0[] = {
  142806. 4,
  142807. 3,
  142808. 5,
  142809. 2,
  142810. 6,
  142811. 1,
  142812. 7,
  142813. 0,
  142814. 8,
  142815. };
  142816. static long _vq_lengthlist__16u0__p5_0[] = {
  142817. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142818. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142819. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  142820. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142821. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  142822. 12,
  142823. };
  142824. static float _vq_quantthresh__16u0__p5_0[] = {
  142825. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142826. };
  142827. static long _vq_quantmap__16u0__p5_0[] = {
  142828. 7, 5, 3, 1, 0, 2, 4, 6,
  142829. 8,
  142830. };
  142831. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  142832. _vq_quantthresh__16u0__p5_0,
  142833. _vq_quantmap__16u0__p5_0,
  142834. 9,
  142835. 9
  142836. };
  142837. static static_codebook _16u0__p5_0 = {
  142838. 2, 81,
  142839. _vq_lengthlist__16u0__p5_0,
  142840. 1, -531628032, 1611661312, 4, 0,
  142841. _vq_quantlist__16u0__p5_0,
  142842. NULL,
  142843. &_vq_auxt__16u0__p5_0,
  142844. NULL,
  142845. 0
  142846. };
  142847. static long _vq_quantlist__16u0__p6_0[] = {
  142848. 6,
  142849. 5,
  142850. 7,
  142851. 4,
  142852. 8,
  142853. 3,
  142854. 9,
  142855. 2,
  142856. 10,
  142857. 1,
  142858. 11,
  142859. 0,
  142860. 12,
  142861. };
  142862. static long _vq_lengthlist__16u0__p6_0[] = {
  142863. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  142864. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  142865. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  142866. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  142867. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  142868. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  142869. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  142870. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  142871. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  142872. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  142873. 18, 0,19, 0, 0, 0, 0, 0, 0,
  142874. };
  142875. static float _vq_quantthresh__16u0__p6_0[] = {
  142876. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142877. 12.5, 17.5, 22.5, 27.5,
  142878. };
  142879. static long _vq_quantmap__16u0__p6_0[] = {
  142880. 11, 9, 7, 5, 3, 1, 0, 2,
  142881. 4, 6, 8, 10, 12,
  142882. };
  142883. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  142884. _vq_quantthresh__16u0__p6_0,
  142885. _vq_quantmap__16u0__p6_0,
  142886. 13,
  142887. 13
  142888. };
  142889. static static_codebook _16u0__p6_0 = {
  142890. 2, 169,
  142891. _vq_lengthlist__16u0__p6_0,
  142892. 1, -526516224, 1616117760, 4, 0,
  142893. _vq_quantlist__16u0__p6_0,
  142894. NULL,
  142895. &_vq_auxt__16u0__p6_0,
  142896. NULL,
  142897. 0
  142898. };
  142899. static long _vq_quantlist__16u0__p6_1[] = {
  142900. 2,
  142901. 1,
  142902. 3,
  142903. 0,
  142904. 4,
  142905. };
  142906. static long _vq_lengthlist__16u0__p6_1[] = {
  142907. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  142908. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  142909. };
  142910. static float _vq_quantthresh__16u0__p6_1[] = {
  142911. -1.5, -0.5, 0.5, 1.5,
  142912. };
  142913. static long _vq_quantmap__16u0__p6_1[] = {
  142914. 3, 1, 0, 2, 4,
  142915. };
  142916. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  142917. _vq_quantthresh__16u0__p6_1,
  142918. _vq_quantmap__16u0__p6_1,
  142919. 5,
  142920. 5
  142921. };
  142922. static static_codebook _16u0__p6_1 = {
  142923. 2, 25,
  142924. _vq_lengthlist__16u0__p6_1,
  142925. 1, -533725184, 1611661312, 3, 0,
  142926. _vq_quantlist__16u0__p6_1,
  142927. NULL,
  142928. &_vq_auxt__16u0__p6_1,
  142929. NULL,
  142930. 0
  142931. };
  142932. static long _vq_quantlist__16u0__p7_0[] = {
  142933. 1,
  142934. 0,
  142935. 2,
  142936. };
  142937. static long _vq_lengthlist__16u0__p7_0[] = {
  142938. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142939. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142940. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142941. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142942. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  142943. 7,
  142944. };
  142945. static float _vq_quantthresh__16u0__p7_0[] = {
  142946. -157.5, 157.5,
  142947. };
  142948. static long _vq_quantmap__16u0__p7_0[] = {
  142949. 1, 0, 2,
  142950. };
  142951. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  142952. _vq_quantthresh__16u0__p7_0,
  142953. _vq_quantmap__16u0__p7_0,
  142954. 3,
  142955. 3
  142956. };
  142957. static static_codebook _16u0__p7_0 = {
  142958. 4, 81,
  142959. _vq_lengthlist__16u0__p7_0,
  142960. 1, -518803456, 1628680192, 2, 0,
  142961. _vq_quantlist__16u0__p7_0,
  142962. NULL,
  142963. &_vq_auxt__16u0__p7_0,
  142964. NULL,
  142965. 0
  142966. };
  142967. static long _vq_quantlist__16u0__p7_1[] = {
  142968. 7,
  142969. 6,
  142970. 8,
  142971. 5,
  142972. 9,
  142973. 4,
  142974. 10,
  142975. 3,
  142976. 11,
  142977. 2,
  142978. 12,
  142979. 1,
  142980. 13,
  142981. 0,
  142982. 14,
  142983. };
  142984. static long _vq_lengthlist__16u0__p7_1[] = {
  142985. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  142986. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  142987. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  142988. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  142989. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  142990. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  142991. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142992. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142993. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142994. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142995. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142996. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142998. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142999. 10,
  143000. };
  143001. static float _vq_quantthresh__16u0__p7_1[] = {
  143002. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143003. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143004. };
  143005. static long _vq_quantmap__16u0__p7_1[] = {
  143006. 13, 11, 9, 7, 5, 3, 1, 0,
  143007. 2, 4, 6, 8, 10, 12, 14,
  143008. };
  143009. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143010. _vq_quantthresh__16u0__p7_1,
  143011. _vq_quantmap__16u0__p7_1,
  143012. 15,
  143013. 15
  143014. };
  143015. static static_codebook _16u0__p7_1 = {
  143016. 2, 225,
  143017. _vq_lengthlist__16u0__p7_1,
  143018. 1, -520986624, 1620377600, 4, 0,
  143019. _vq_quantlist__16u0__p7_1,
  143020. NULL,
  143021. &_vq_auxt__16u0__p7_1,
  143022. NULL,
  143023. 0
  143024. };
  143025. static long _vq_quantlist__16u0__p7_2[] = {
  143026. 10,
  143027. 9,
  143028. 11,
  143029. 8,
  143030. 12,
  143031. 7,
  143032. 13,
  143033. 6,
  143034. 14,
  143035. 5,
  143036. 15,
  143037. 4,
  143038. 16,
  143039. 3,
  143040. 17,
  143041. 2,
  143042. 18,
  143043. 1,
  143044. 19,
  143045. 0,
  143046. 20,
  143047. };
  143048. static long _vq_lengthlist__16u0__p7_2[] = {
  143049. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143050. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143051. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143052. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143053. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143054. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143055. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143056. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143057. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143058. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143059. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143060. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143061. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143062. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143063. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143064. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143065. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143066. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143067. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143068. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143069. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143070. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143071. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143072. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143073. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143074. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143075. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143076. 10,10,12,11,10,11,11,11,10,
  143077. };
  143078. static float _vq_quantthresh__16u0__p7_2[] = {
  143079. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143080. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143081. 6.5, 7.5, 8.5, 9.5,
  143082. };
  143083. static long _vq_quantmap__16u0__p7_2[] = {
  143084. 19, 17, 15, 13, 11, 9, 7, 5,
  143085. 3, 1, 0, 2, 4, 6, 8, 10,
  143086. 12, 14, 16, 18, 20,
  143087. };
  143088. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143089. _vq_quantthresh__16u0__p7_2,
  143090. _vq_quantmap__16u0__p7_2,
  143091. 21,
  143092. 21
  143093. };
  143094. static static_codebook _16u0__p7_2 = {
  143095. 2, 441,
  143096. _vq_lengthlist__16u0__p7_2,
  143097. 1, -529268736, 1611661312, 5, 0,
  143098. _vq_quantlist__16u0__p7_2,
  143099. NULL,
  143100. &_vq_auxt__16u0__p7_2,
  143101. NULL,
  143102. 0
  143103. };
  143104. static long _huff_lengthlist__16u0__single[] = {
  143105. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143106. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143107. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143108. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143109. };
  143110. static static_codebook _huff_book__16u0__single = {
  143111. 2, 64,
  143112. _huff_lengthlist__16u0__single,
  143113. 0, 0, 0, 0, 0,
  143114. NULL,
  143115. NULL,
  143116. NULL,
  143117. NULL,
  143118. 0
  143119. };
  143120. static long _huff_lengthlist__16u1__long[] = {
  143121. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143122. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143123. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143124. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143125. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143126. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143127. 16,13,16,18,
  143128. };
  143129. static static_codebook _huff_book__16u1__long = {
  143130. 2, 100,
  143131. _huff_lengthlist__16u1__long,
  143132. 0, 0, 0, 0, 0,
  143133. NULL,
  143134. NULL,
  143135. NULL,
  143136. NULL,
  143137. 0
  143138. };
  143139. static long _vq_quantlist__16u1__p1_0[] = {
  143140. 1,
  143141. 0,
  143142. 2,
  143143. };
  143144. static long _vq_lengthlist__16u1__p1_0[] = {
  143145. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143146. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143147. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143148. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143149. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143150. 11,
  143151. };
  143152. static float _vq_quantthresh__16u1__p1_0[] = {
  143153. -0.5, 0.5,
  143154. };
  143155. static long _vq_quantmap__16u1__p1_0[] = {
  143156. 1, 0, 2,
  143157. };
  143158. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143159. _vq_quantthresh__16u1__p1_0,
  143160. _vq_quantmap__16u1__p1_0,
  143161. 3,
  143162. 3
  143163. };
  143164. static static_codebook _16u1__p1_0 = {
  143165. 4, 81,
  143166. _vq_lengthlist__16u1__p1_0,
  143167. 1, -535822336, 1611661312, 2, 0,
  143168. _vq_quantlist__16u1__p1_0,
  143169. NULL,
  143170. &_vq_auxt__16u1__p1_0,
  143171. NULL,
  143172. 0
  143173. };
  143174. static long _vq_quantlist__16u1__p2_0[] = {
  143175. 1,
  143176. 0,
  143177. 2,
  143178. };
  143179. static long _vq_lengthlist__16u1__p2_0[] = {
  143180. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143181. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143182. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143183. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143184. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143185. 8,
  143186. };
  143187. static float _vq_quantthresh__16u1__p2_0[] = {
  143188. -0.5, 0.5,
  143189. };
  143190. static long _vq_quantmap__16u1__p2_0[] = {
  143191. 1, 0, 2,
  143192. };
  143193. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143194. _vq_quantthresh__16u1__p2_0,
  143195. _vq_quantmap__16u1__p2_0,
  143196. 3,
  143197. 3
  143198. };
  143199. static static_codebook _16u1__p2_0 = {
  143200. 4, 81,
  143201. _vq_lengthlist__16u1__p2_0,
  143202. 1, -535822336, 1611661312, 2, 0,
  143203. _vq_quantlist__16u1__p2_0,
  143204. NULL,
  143205. &_vq_auxt__16u1__p2_0,
  143206. NULL,
  143207. 0
  143208. };
  143209. static long _vq_quantlist__16u1__p3_0[] = {
  143210. 2,
  143211. 1,
  143212. 3,
  143213. 0,
  143214. 4,
  143215. };
  143216. static long _vq_lengthlist__16u1__p3_0[] = {
  143217. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143218. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143219. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143220. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143221. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143222. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143223. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143224. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143225. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143226. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143227. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143228. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143229. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143230. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143231. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143232. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143233. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143234. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143235. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143236. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143237. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143238. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143239. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143240. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143241. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143242. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143243. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143244. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143245. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143246. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143247. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143248. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143249. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143250. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143251. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143252. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143253. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143254. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143255. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143256. 16,
  143257. };
  143258. static float _vq_quantthresh__16u1__p3_0[] = {
  143259. -1.5, -0.5, 0.5, 1.5,
  143260. };
  143261. static long _vq_quantmap__16u1__p3_0[] = {
  143262. 3, 1, 0, 2, 4,
  143263. };
  143264. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143265. _vq_quantthresh__16u1__p3_0,
  143266. _vq_quantmap__16u1__p3_0,
  143267. 5,
  143268. 5
  143269. };
  143270. static static_codebook _16u1__p3_0 = {
  143271. 4, 625,
  143272. _vq_lengthlist__16u1__p3_0,
  143273. 1, -533725184, 1611661312, 3, 0,
  143274. _vq_quantlist__16u1__p3_0,
  143275. NULL,
  143276. &_vq_auxt__16u1__p3_0,
  143277. NULL,
  143278. 0
  143279. };
  143280. static long _vq_quantlist__16u1__p4_0[] = {
  143281. 2,
  143282. 1,
  143283. 3,
  143284. 0,
  143285. 4,
  143286. };
  143287. static long _vq_lengthlist__16u1__p4_0[] = {
  143288. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143289. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143290. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143291. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143292. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143293. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143294. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143295. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143296. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143297. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143298. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143299. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143300. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143301. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143302. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143303. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143304. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143305. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143306. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143307. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143308. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143309. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143310. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143311. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143312. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143313. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143314. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143315. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143316. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143317. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143318. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143319. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143320. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143321. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143322. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143323. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143324. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143325. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143326. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143327. 11,
  143328. };
  143329. static float _vq_quantthresh__16u1__p4_0[] = {
  143330. -1.5, -0.5, 0.5, 1.5,
  143331. };
  143332. static long _vq_quantmap__16u1__p4_0[] = {
  143333. 3, 1, 0, 2, 4,
  143334. };
  143335. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143336. _vq_quantthresh__16u1__p4_0,
  143337. _vq_quantmap__16u1__p4_0,
  143338. 5,
  143339. 5
  143340. };
  143341. static static_codebook _16u1__p4_0 = {
  143342. 4, 625,
  143343. _vq_lengthlist__16u1__p4_0,
  143344. 1, -533725184, 1611661312, 3, 0,
  143345. _vq_quantlist__16u1__p4_0,
  143346. NULL,
  143347. &_vq_auxt__16u1__p4_0,
  143348. NULL,
  143349. 0
  143350. };
  143351. static long _vq_quantlist__16u1__p5_0[] = {
  143352. 4,
  143353. 3,
  143354. 5,
  143355. 2,
  143356. 6,
  143357. 1,
  143358. 7,
  143359. 0,
  143360. 8,
  143361. };
  143362. static long _vq_lengthlist__16u1__p5_0[] = {
  143363. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143364. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143365. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143366. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143367. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143368. 13,
  143369. };
  143370. static float _vq_quantthresh__16u1__p5_0[] = {
  143371. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143372. };
  143373. static long _vq_quantmap__16u1__p5_0[] = {
  143374. 7, 5, 3, 1, 0, 2, 4, 6,
  143375. 8,
  143376. };
  143377. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143378. _vq_quantthresh__16u1__p5_0,
  143379. _vq_quantmap__16u1__p5_0,
  143380. 9,
  143381. 9
  143382. };
  143383. static static_codebook _16u1__p5_0 = {
  143384. 2, 81,
  143385. _vq_lengthlist__16u1__p5_0,
  143386. 1, -531628032, 1611661312, 4, 0,
  143387. _vq_quantlist__16u1__p5_0,
  143388. NULL,
  143389. &_vq_auxt__16u1__p5_0,
  143390. NULL,
  143391. 0
  143392. };
  143393. static long _vq_quantlist__16u1__p6_0[] = {
  143394. 4,
  143395. 3,
  143396. 5,
  143397. 2,
  143398. 6,
  143399. 1,
  143400. 7,
  143401. 0,
  143402. 8,
  143403. };
  143404. static long _vq_lengthlist__16u1__p6_0[] = {
  143405. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143406. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143407. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143408. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143409. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143410. 11,
  143411. };
  143412. static float _vq_quantthresh__16u1__p6_0[] = {
  143413. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143414. };
  143415. static long _vq_quantmap__16u1__p6_0[] = {
  143416. 7, 5, 3, 1, 0, 2, 4, 6,
  143417. 8,
  143418. };
  143419. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143420. _vq_quantthresh__16u1__p6_0,
  143421. _vq_quantmap__16u1__p6_0,
  143422. 9,
  143423. 9
  143424. };
  143425. static static_codebook _16u1__p6_0 = {
  143426. 2, 81,
  143427. _vq_lengthlist__16u1__p6_0,
  143428. 1, -531628032, 1611661312, 4, 0,
  143429. _vq_quantlist__16u1__p6_0,
  143430. NULL,
  143431. &_vq_auxt__16u1__p6_0,
  143432. NULL,
  143433. 0
  143434. };
  143435. static long _vq_quantlist__16u1__p7_0[] = {
  143436. 1,
  143437. 0,
  143438. 2,
  143439. };
  143440. static long _vq_lengthlist__16u1__p7_0[] = {
  143441. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143442. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143443. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143444. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143445. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143446. 13,
  143447. };
  143448. static float _vq_quantthresh__16u1__p7_0[] = {
  143449. -5.5, 5.5,
  143450. };
  143451. static long _vq_quantmap__16u1__p7_0[] = {
  143452. 1, 0, 2,
  143453. };
  143454. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143455. _vq_quantthresh__16u1__p7_0,
  143456. _vq_quantmap__16u1__p7_0,
  143457. 3,
  143458. 3
  143459. };
  143460. static static_codebook _16u1__p7_0 = {
  143461. 4, 81,
  143462. _vq_lengthlist__16u1__p7_0,
  143463. 1, -529137664, 1618345984, 2, 0,
  143464. _vq_quantlist__16u1__p7_0,
  143465. NULL,
  143466. &_vq_auxt__16u1__p7_0,
  143467. NULL,
  143468. 0
  143469. };
  143470. static long _vq_quantlist__16u1__p7_1[] = {
  143471. 5,
  143472. 4,
  143473. 6,
  143474. 3,
  143475. 7,
  143476. 2,
  143477. 8,
  143478. 1,
  143479. 9,
  143480. 0,
  143481. 10,
  143482. };
  143483. static long _vq_lengthlist__16u1__p7_1[] = {
  143484. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143485. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143486. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143487. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143488. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143489. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143490. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143491. 8, 9, 9,10,10,10,10,10,10,
  143492. };
  143493. static float _vq_quantthresh__16u1__p7_1[] = {
  143494. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143495. 3.5, 4.5,
  143496. };
  143497. static long _vq_quantmap__16u1__p7_1[] = {
  143498. 9, 7, 5, 3, 1, 0, 2, 4,
  143499. 6, 8, 10,
  143500. };
  143501. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143502. _vq_quantthresh__16u1__p7_1,
  143503. _vq_quantmap__16u1__p7_1,
  143504. 11,
  143505. 11
  143506. };
  143507. static static_codebook _16u1__p7_1 = {
  143508. 2, 121,
  143509. _vq_lengthlist__16u1__p7_1,
  143510. 1, -531365888, 1611661312, 4, 0,
  143511. _vq_quantlist__16u1__p7_1,
  143512. NULL,
  143513. &_vq_auxt__16u1__p7_1,
  143514. NULL,
  143515. 0
  143516. };
  143517. static long _vq_quantlist__16u1__p8_0[] = {
  143518. 5,
  143519. 4,
  143520. 6,
  143521. 3,
  143522. 7,
  143523. 2,
  143524. 8,
  143525. 1,
  143526. 9,
  143527. 0,
  143528. 10,
  143529. };
  143530. static long _vq_lengthlist__16u1__p8_0[] = {
  143531. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143532. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143533. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143534. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143535. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143536. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143537. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143538. 13,14,14,15,15,16,16,15,16,
  143539. };
  143540. static float _vq_quantthresh__16u1__p8_0[] = {
  143541. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143542. 38.5, 49.5,
  143543. };
  143544. static long _vq_quantmap__16u1__p8_0[] = {
  143545. 9, 7, 5, 3, 1, 0, 2, 4,
  143546. 6, 8, 10,
  143547. };
  143548. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143549. _vq_quantthresh__16u1__p8_0,
  143550. _vq_quantmap__16u1__p8_0,
  143551. 11,
  143552. 11
  143553. };
  143554. static static_codebook _16u1__p8_0 = {
  143555. 2, 121,
  143556. _vq_lengthlist__16u1__p8_0,
  143557. 1, -524582912, 1618345984, 4, 0,
  143558. _vq_quantlist__16u1__p8_0,
  143559. NULL,
  143560. &_vq_auxt__16u1__p8_0,
  143561. NULL,
  143562. 0
  143563. };
  143564. static long _vq_quantlist__16u1__p8_1[] = {
  143565. 5,
  143566. 4,
  143567. 6,
  143568. 3,
  143569. 7,
  143570. 2,
  143571. 8,
  143572. 1,
  143573. 9,
  143574. 0,
  143575. 10,
  143576. };
  143577. static long _vq_lengthlist__16u1__p8_1[] = {
  143578. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143579. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143580. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143581. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143582. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143583. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143584. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143585. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143586. };
  143587. static float _vq_quantthresh__16u1__p8_1[] = {
  143588. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143589. 3.5, 4.5,
  143590. };
  143591. static long _vq_quantmap__16u1__p8_1[] = {
  143592. 9, 7, 5, 3, 1, 0, 2, 4,
  143593. 6, 8, 10,
  143594. };
  143595. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143596. _vq_quantthresh__16u1__p8_1,
  143597. _vq_quantmap__16u1__p8_1,
  143598. 11,
  143599. 11
  143600. };
  143601. static static_codebook _16u1__p8_1 = {
  143602. 2, 121,
  143603. _vq_lengthlist__16u1__p8_1,
  143604. 1, -531365888, 1611661312, 4, 0,
  143605. _vq_quantlist__16u1__p8_1,
  143606. NULL,
  143607. &_vq_auxt__16u1__p8_1,
  143608. NULL,
  143609. 0
  143610. };
  143611. static long _vq_quantlist__16u1__p9_0[] = {
  143612. 7,
  143613. 6,
  143614. 8,
  143615. 5,
  143616. 9,
  143617. 4,
  143618. 10,
  143619. 3,
  143620. 11,
  143621. 2,
  143622. 12,
  143623. 1,
  143624. 13,
  143625. 0,
  143626. 14,
  143627. };
  143628. static long _vq_lengthlist__16u1__p9_0[] = {
  143629. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143630. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143631. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143632. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143633. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143634. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143635. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143636. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143637. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143638. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143639. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143640. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143641. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143642. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143643. 8,
  143644. };
  143645. static float _vq_quantthresh__16u1__p9_0[] = {
  143646. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143647. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143648. };
  143649. static long _vq_quantmap__16u1__p9_0[] = {
  143650. 13, 11, 9, 7, 5, 3, 1, 0,
  143651. 2, 4, 6, 8, 10, 12, 14,
  143652. };
  143653. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143654. _vq_quantthresh__16u1__p9_0,
  143655. _vq_quantmap__16u1__p9_0,
  143656. 15,
  143657. 15
  143658. };
  143659. static static_codebook _16u1__p9_0 = {
  143660. 2, 225,
  143661. _vq_lengthlist__16u1__p9_0,
  143662. 1, -514071552, 1627381760, 4, 0,
  143663. _vq_quantlist__16u1__p9_0,
  143664. NULL,
  143665. &_vq_auxt__16u1__p9_0,
  143666. NULL,
  143667. 0
  143668. };
  143669. static long _vq_quantlist__16u1__p9_1[] = {
  143670. 7,
  143671. 6,
  143672. 8,
  143673. 5,
  143674. 9,
  143675. 4,
  143676. 10,
  143677. 3,
  143678. 11,
  143679. 2,
  143680. 12,
  143681. 1,
  143682. 13,
  143683. 0,
  143684. 14,
  143685. };
  143686. static long _vq_lengthlist__16u1__p9_1[] = {
  143687. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  143688. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  143689. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  143690. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  143691. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  143692. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  143693. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  143694. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  143695. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  143696. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143697. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  143698. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143699. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143700. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143701. 9,
  143702. };
  143703. static float _vq_quantthresh__16u1__p9_1[] = {
  143704. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143705. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143706. };
  143707. static long _vq_quantmap__16u1__p9_1[] = {
  143708. 13, 11, 9, 7, 5, 3, 1, 0,
  143709. 2, 4, 6, 8, 10, 12, 14,
  143710. };
  143711. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  143712. _vq_quantthresh__16u1__p9_1,
  143713. _vq_quantmap__16u1__p9_1,
  143714. 15,
  143715. 15
  143716. };
  143717. static static_codebook _16u1__p9_1 = {
  143718. 2, 225,
  143719. _vq_lengthlist__16u1__p9_1,
  143720. 1, -522338304, 1620115456, 4, 0,
  143721. _vq_quantlist__16u1__p9_1,
  143722. NULL,
  143723. &_vq_auxt__16u1__p9_1,
  143724. NULL,
  143725. 0
  143726. };
  143727. static long _vq_quantlist__16u1__p9_2[] = {
  143728. 8,
  143729. 7,
  143730. 9,
  143731. 6,
  143732. 10,
  143733. 5,
  143734. 11,
  143735. 4,
  143736. 12,
  143737. 3,
  143738. 13,
  143739. 2,
  143740. 14,
  143741. 1,
  143742. 15,
  143743. 0,
  143744. 16,
  143745. };
  143746. static long _vq_lengthlist__16u1__p9_2[] = {
  143747. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  143748. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  143749. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  143750. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  143751. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  143752. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  143753. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  143754. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  143755. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  143756. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  143757. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  143758. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  143759. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  143760. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  143761. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  143762. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  143763. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  143764. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  143765. 10,
  143766. };
  143767. static float _vq_quantthresh__16u1__p9_2[] = {
  143768. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143769. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143770. };
  143771. static long _vq_quantmap__16u1__p9_2[] = {
  143772. 15, 13, 11, 9, 7, 5, 3, 1,
  143773. 0, 2, 4, 6, 8, 10, 12, 14,
  143774. 16,
  143775. };
  143776. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  143777. _vq_quantthresh__16u1__p9_2,
  143778. _vq_quantmap__16u1__p9_2,
  143779. 17,
  143780. 17
  143781. };
  143782. static static_codebook _16u1__p9_2 = {
  143783. 2, 289,
  143784. _vq_lengthlist__16u1__p9_2,
  143785. 1, -529530880, 1611661312, 5, 0,
  143786. _vq_quantlist__16u1__p9_2,
  143787. NULL,
  143788. &_vq_auxt__16u1__p9_2,
  143789. NULL,
  143790. 0
  143791. };
  143792. static long _huff_lengthlist__16u1__short[] = {
  143793. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  143794. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  143795. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  143796. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  143797. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  143798. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  143799. 16,16,16,16,
  143800. };
  143801. static static_codebook _huff_book__16u1__short = {
  143802. 2, 100,
  143803. _huff_lengthlist__16u1__short,
  143804. 0, 0, 0, 0, 0,
  143805. NULL,
  143806. NULL,
  143807. NULL,
  143808. NULL,
  143809. 0
  143810. };
  143811. static long _huff_lengthlist__16u2__long[] = {
  143812. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  143813. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  143814. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  143815. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  143816. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  143817. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  143818. 13,14,18,18,
  143819. };
  143820. static static_codebook _huff_book__16u2__long = {
  143821. 2, 100,
  143822. _huff_lengthlist__16u2__long,
  143823. 0, 0, 0, 0, 0,
  143824. NULL,
  143825. NULL,
  143826. NULL,
  143827. NULL,
  143828. 0
  143829. };
  143830. static long _huff_lengthlist__16u2__short[] = {
  143831. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  143832. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  143833. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  143834. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  143835. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  143836. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  143837. 16,16,16,16,
  143838. };
  143839. static static_codebook _huff_book__16u2__short = {
  143840. 2, 100,
  143841. _huff_lengthlist__16u2__short,
  143842. 0, 0, 0, 0, 0,
  143843. NULL,
  143844. NULL,
  143845. NULL,
  143846. NULL,
  143847. 0
  143848. };
  143849. static long _vq_quantlist__16u2_p1_0[] = {
  143850. 1,
  143851. 0,
  143852. 2,
  143853. };
  143854. static long _vq_lengthlist__16u2_p1_0[] = {
  143855. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  143856. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  143857. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  143858. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  143859. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  143860. 10,
  143861. };
  143862. static float _vq_quantthresh__16u2_p1_0[] = {
  143863. -0.5, 0.5,
  143864. };
  143865. static long _vq_quantmap__16u2_p1_0[] = {
  143866. 1, 0, 2,
  143867. };
  143868. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  143869. _vq_quantthresh__16u2_p1_0,
  143870. _vq_quantmap__16u2_p1_0,
  143871. 3,
  143872. 3
  143873. };
  143874. static static_codebook _16u2_p1_0 = {
  143875. 4, 81,
  143876. _vq_lengthlist__16u2_p1_0,
  143877. 1, -535822336, 1611661312, 2, 0,
  143878. _vq_quantlist__16u2_p1_0,
  143879. NULL,
  143880. &_vq_auxt__16u2_p1_0,
  143881. NULL,
  143882. 0
  143883. };
  143884. static long _vq_quantlist__16u2_p2_0[] = {
  143885. 2,
  143886. 1,
  143887. 3,
  143888. 0,
  143889. 4,
  143890. };
  143891. static long _vq_lengthlist__16u2_p2_0[] = {
  143892. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143893. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143894. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  143895. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  143896. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  143897. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  143898. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  143899. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  143900. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143901. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  143902. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  143903. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143904. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  143905. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  143906. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  143907. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143908. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143909. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  143910. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  143911. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  143912. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  143913. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  143914. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143915. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  143916. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  143917. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  143918. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  143919. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  143920. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  143921. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  143922. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  143923. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  143924. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  143925. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  143926. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  143927. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  143928. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  143929. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  143930. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  143931. 13,
  143932. };
  143933. static float _vq_quantthresh__16u2_p2_0[] = {
  143934. -1.5, -0.5, 0.5, 1.5,
  143935. };
  143936. static long _vq_quantmap__16u2_p2_0[] = {
  143937. 3, 1, 0, 2, 4,
  143938. };
  143939. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  143940. _vq_quantthresh__16u2_p2_0,
  143941. _vq_quantmap__16u2_p2_0,
  143942. 5,
  143943. 5
  143944. };
  143945. static static_codebook _16u2_p2_0 = {
  143946. 4, 625,
  143947. _vq_lengthlist__16u2_p2_0,
  143948. 1, -533725184, 1611661312, 3, 0,
  143949. _vq_quantlist__16u2_p2_0,
  143950. NULL,
  143951. &_vq_auxt__16u2_p2_0,
  143952. NULL,
  143953. 0
  143954. };
  143955. static long _vq_quantlist__16u2_p3_0[] = {
  143956. 4,
  143957. 3,
  143958. 5,
  143959. 2,
  143960. 6,
  143961. 1,
  143962. 7,
  143963. 0,
  143964. 8,
  143965. };
  143966. static long _vq_lengthlist__16u2_p3_0[] = {
  143967. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  143968. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  143969. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143970. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143971. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143972. 11,
  143973. };
  143974. static float _vq_quantthresh__16u2_p3_0[] = {
  143975. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143976. };
  143977. static long _vq_quantmap__16u2_p3_0[] = {
  143978. 7, 5, 3, 1, 0, 2, 4, 6,
  143979. 8,
  143980. };
  143981. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  143982. _vq_quantthresh__16u2_p3_0,
  143983. _vq_quantmap__16u2_p3_0,
  143984. 9,
  143985. 9
  143986. };
  143987. static static_codebook _16u2_p3_0 = {
  143988. 2, 81,
  143989. _vq_lengthlist__16u2_p3_0,
  143990. 1, -531628032, 1611661312, 4, 0,
  143991. _vq_quantlist__16u2_p3_0,
  143992. NULL,
  143993. &_vq_auxt__16u2_p3_0,
  143994. NULL,
  143995. 0
  143996. };
  143997. static long _vq_quantlist__16u2_p4_0[] = {
  143998. 8,
  143999. 7,
  144000. 9,
  144001. 6,
  144002. 10,
  144003. 5,
  144004. 11,
  144005. 4,
  144006. 12,
  144007. 3,
  144008. 13,
  144009. 2,
  144010. 14,
  144011. 1,
  144012. 15,
  144013. 0,
  144014. 16,
  144015. };
  144016. static long _vq_lengthlist__16u2_p4_0[] = {
  144017. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144018. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144019. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144020. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144021. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144022. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144023. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144024. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144025. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144026. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144027. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144028. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144029. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144030. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144031. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144032. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144033. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144034. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144035. 14,
  144036. };
  144037. static float _vq_quantthresh__16u2_p4_0[] = {
  144038. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144039. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144040. };
  144041. static long _vq_quantmap__16u2_p4_0[] = {
  144042. 15, 13, 11, 9, 7, 5, 3, 1,
  144043. 0, 2, 4, 6, 8, 10, 12, 14,
  144044. 16,
  144045. };
  144046. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144047. _vq_quantthresh__16u2_p4_0,
  144048. _vq_quantmap__16u2_p4_0,
  144049. 17,
  144050. 17
  144051. };
  144052. static static_codebook _16u2_p4_0 = {
  144053. 2, 289,
  144054. _vq_lengthlist__16u2_p4_0,
  144055. 1, -529530880, 1611661312, 5, 0,
  144056. _vq_quantlist__16u2_p4_0,
  144057. NULL,
  144058. &_vq_auxt__16u2_p4_0,
  144059. NULL,
  144060. 0
  144061. };
  144062. static long _vq_quantlist__16u2_p5_0[] = {
  144063. 1,
  144064. 0,
  144065. 2,
  144066. };
  144067. static long _vq_lengthlist__16u2_p5_0[] = {
  144068. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144069. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144070. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144071. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144072. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144073. 10,
  144074. };
  144075. static float _vq_quantthresh__16u2_p5_0[] = {
  144076. -5.5, 5.5,
  144077. };
  144078. static long _vq_quantmap__16u2_p5_0[] = {
  144079. 1, 0, 2,
  144080. };
  144081. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144082. _vq_quantthresh__16u2_p5_0,
  144083. _vq_quantmap__16u2_p5_0,
  144084. 3,
  144085. 3
  144086. };
  144087. static static_codebook _16u2_p5_0 = {
  144088. 4, 81,
  144089. _vq_lengthlist__16u2_p5_0,
  144090. 1, -529137664, 1618345984, 2, 0,
  144091. _vq_quantlist__16u2_p5_0,
  144092. NULL,
  144093. &_vq_auxt__16u2_p5_0,
  144094. NULL,
  144095. 0
  144096. };
  144097. static long _vq_quantlist__16u2_p5_1[] = {
  144098. 5,
  144099. 4,
  144100. 6,
  144101. 3,
  144102. 7,
  144103. 2,
  144104. 8,
  144105. 1,
  144106. 9,
  144107. 0,
  144108. 10,
  144109. };
  144110. static long _vq_lengthlist__16u2_p5_1[] = {
  144111. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144112. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144113. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144114. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144115. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144116. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144117. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144118. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144119. };
  144120. static float _vq_quantthresh__16u2_p5_1[] = {
  144121. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144122. 3.5, 4.5,
  144123. };
  144124. static long _vq_quantmap__16u2_p5_1[] = {
  144125. 9, 7, 5, 3, 1, 0, 2, 4,
  144126. 6, 8, 10,
  144127. };
  144128. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144129. _vq_quantthresh__16u2_p5_1,
  144130. _vq_quantmap__16u2_p5_1,
  144131. 11,
  144132. 11
  144133. };
  144134. static static_codebook _16u2_p5_1 = {
  144135. 2, 121,
  144136. _vq_lengthlist__16u2_p5_1,
  144137. 1, -531365888, 1611661312, 4, 0,
  144138. _vq_quantlist__16u2_p5_1,
  144139. NULL,
  144140. &_vq_auxt__16u2_p5_1,
  144141. NULL,
  144142. 0
  144143. };
  144144. static long _vq_quantlist__16u2_p6_0[] = {
  144145. 6,
  144146. 5,
  144147. 7,
  144148. 4,
  144149. 8,
  144150. 3,
  144151. 9,
  144152. 2,
  144153. 10,
  144154. 1,
  144155. 11,
  144156. 0,
  144157. 12,
  144158. };
  144159. static long _vq_lengthlist__16u2_p6_0[] = {
  144160. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144161. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144162. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144163. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144164. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144165. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144166. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144167. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144168. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144169. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144170. 12,13,13,14,14,14,14,15,15,
  144171. };
  144172. static float _vq_quantthresh__16u2_p6_0[] = {
  144173. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144174. 12.5, 17.5, 22.5, 27.5,
  144175. };
  144176. static long _vq_quantmap__16u2_p6_0[] = {
  144177. 11, 9, 7, 5, 3, 1, 0, 2,
  144178. 4, 6, 8, 10, 12,
  144179. };
  144180. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144181. _vq_quantthresh__16u2_p6_0,
  144182. _vq_quantmap__16u2_p6_0,
  144183. 13,
  144184. 13
  144185. };
  144186. static static_codebook _16u2_p6_0 = {
  144187. 2, 169,
  144188. _vq_lengthlist__16u2_p6_0,
  144189. 1, -526516224, 1616117760, 4, 0,
  144190. _vq_quantlist__16u2_p6_0,
  144191. NULL,
  144192. &_vq_auxt__16u2_p6_0,
  144193. NULL,
  144194. 0
  144195. };
  144196. static long _vq_quantlist__16u2_p6_1[] = {
  144197. 2,
  144198. 1,
  144199. 3,
  144200. 0,
  144201. 4,
  144202. };
  144203. static long _vq_lengthlist__16u2_p6_1[] = {
  144204. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144205. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144206. };
  144207. static float _vq_quantthresh__16u2_p6_1[] = {
  144208. -1.5, -0.5, 0.5, 1.5,
  144209. };
  144210. static long _vq_quantmap__16u2_p6_1[] = {
  144211. 3, 1, 0, 2, 4,
  144212. };
  144213. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144214. _vq_quantthresh__16u2_p6_1,
  144215. _vq_quantmap__16u2_p6_1,
  144216. 5,
  144217. 5
  144218. };
  144219. static static_codebook _16u2_p6_1 = {
  144220. 2, 25,
  144221. _vq_lengthlist__16u2_p6_1,
  144222. 1, -533725184, 1611661312, 3, 0,
  144223. _vq_quantlist__16u2_p6_1,
  144224. NULL,
  144225. &_vq_auxt__16u2_p6_1,
  144226. NULL,
  144227. 0
  144228. };
  144229. static long _vq_quantlist__16u2_p7_0[] = {
  144230. 6,
  144231. 5,
  144232. 7,
  144233. 4,
  144234. 8,
  144235. 3,
  144236. 9,
  144237. 2,
  144238. 10,
  144239. 1,
  144240. 11,
  144241. 0,
  144242. 12,
  144243. };
  144244. static long _vq_lengthlist__16u2_p7_0[] = {
  144245. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144246. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144247. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144248. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144249. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144250. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144251. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144252. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144253. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144254. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144255. 12,13,13,13,14,14,14,15,14,
  144256. };
  144257. static float _vq_quantthresh__16u2_p7_0[] = {
  144258. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144259. 27.5, 38.5, 49.5, 60.5,
  144260. };
  144261. static long _vq_quantmap__16u2_p7_0[] = {
  144262. 11, 9, 7, 5, 3, 1, 0, 2,
  144263. 4, 6, 8, 10, 12,
  144264. };
  144265. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144266. _vq_quantthresh__16u2_p7_0,
  144267. _vq_quantmap__16u2_p7_0,
  144268. 13,
  144269. 13
  144270. };
  144271. static static_codebook _16u2_p7_0 = {
  144272. 2, 169,
  144273. _vq_lengthlist__16u2_p7_0,
  144274. 1, -523206656, 1618345984, 4, 0,
  144275. _vq_quantlist__16u2_p7_0,
  144276. NULL,
  144277. &_vq_auxt__16u2_p7_0,
  144278. NULL,
  144279. 0
  144280. };
  144281. static long _vq_quantlist__16u2_p7_1[] = {
  144282. 5,
  144283. 4,
  144284. 6,
  144285. 3,
  144286. 7,
  144287. 2,
  144288. 8,
  144289. 1,
  144290. 9,
  144291. 0,
  144292. 10,
  144293. };
  144294. static long _vq_lengthlist__16u2_p7_1[] = {
  144295. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144296. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144297. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144298. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144299. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144300. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144301. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144302. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144303. };
  144304. static float _vq_quantthresh__16u2_p7_1[] = {
  144305. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144306. 3.5, 4.5,
  144307. };
  144308. static long _vq_quantmap__16u2_p7_1[] = {
  144309. 9, 7, 5, 3, 1, 0, 2, 4,
  144310. 6, 8, 10,
  144311. };
  144312. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144313. _vq_quantthresh__16u2_p7_1,
  144314. _vq_quantmap__16u2_p7_1,
  144315. 11,
  144316. 11
  144317. };
  144318. static static_codebook _16u2_p7_1 = {
  144319. 2, 121,
  144320. _vq_lengthlist__16u2_p7_1,
  144321. 1, -531365888, 1611661312, 4, 0,
  144322. _vq_quantlist__16u2_p7_1,
  144323. NULL,
  144324. &_vq_auxt__16u2_p7_1,
  144325. NULL,
  144326. 0
  144327. };
  144328. static long _vq_quantlist__16u2_p8_0[] = {
  144329. 7,
  144330. 6,
  144331. 8,
  144332. 5,
  144333. 9,
  144334. 4,
  144335. 10,
  144336. 3,
  144337. 11,
  144338. 2,
  144339. 12,
  144340. 1,
  144341. 13,
  144342. 0,
  144343. 14,
  144344. };
  144345. static long _vq_lengthlist__16u2_p8_0[] = {
  144346. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144347. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144348. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144349. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144350. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144351. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144352. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144353. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144354. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144355. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144356. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144357. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144358. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144359. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144360. 14,
  144361. };
  144362. static float _vq_quantthresh__16u2_p8_0[] = {
  144363. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144364. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144365. };
  144366. static long _vq_quantmap__16u2_p8_0[] = {
  144367. 13, 11, 9, 7, 5, 3, 1, 0,
  144368. 2, 4, 6, 8, 10, 12, 14,
  144369. };
  144370. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144371. _vq_quantthresh__16u2_p8_0,
  144372. _vq_quantmap__16u2_p8_0,
  144373. 15,
  144374. 15
  144375. };
  144376. static static_codebook _16u2_p8_0 = {
  144377. 2, 225,
  144378. _vq_lengthlist__16u2_p8_0,
  144379. 1, -520986624, 1620377600, 4, 0,
  144380. _vq_quantlist__16u2_p8_0,
  144381. NULL,
  144382. &_vq_auxt__16u2_p8_0,
  144383. NULL,
  144384. 0
  144385. };
  144386. static long _vq_quantlist__16u2_p8_1[] = {
  144387. 10,
  144388. 9,
  144389. 11,
  144390. 8,
  144391. 12,
  144392. 7,
  144393. 13,
  144394. 6,
  144395. 14,
  144396. 5,
  144397. 15,
  144398. 4,
  144399. 16,
  144400. 3,
  144401. 17,
  144402. 2,
  144403. 18,
  144404. 1,
  144405. 19,
  144406. 0,
  144407. 20,
  144408. };
  144409. static long _vq_lengthlist__16u2_p8_1[] = {
  144410. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144411. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144412. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144413. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144414. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144415. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144416. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144417. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144418. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144419. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144420. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144421. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144422. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144423. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144424. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144425. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144426. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144427. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144428. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144429. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144430. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144431. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144432. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144433. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144434. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144435. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144436. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144437. 11,11,10,11,11,11,10,11,11,
  144438. };
  144439. static float _vq_quantthresh__16u2_p8_1[] = {
  144440. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144441. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144442. 6.5, 7.5, 8.5, 9.5,
  144443. };
  144444. static long _vq_quantmap__16u2_p8_1[] = {
  144445. 19, 17, 15, 13, 11, 9, 7, 5,
  144446. 3, 1, 0, 2, 4, 6, 8, 10,
  144447. 12, 14, 16, 18, 20,
  144448. };
  144449. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144450. _vq_quantthresh__16u2_p8_1,
  144451. _vq_quantmap__16u2_p8_1,
  144452. 21,
  144453. 21
  144454. };
  144455. static static_codebook _16u2_p8_1 = {
  144456. 2, 441,
  144457. _vq_lengthlist__16u2_p8_1,
  144458. 1, -529268736, 1611661312, 5, 0,
  144459. _vq_quantlist__16u2_p8_1,
  144460. NULL,
  144461. &_vq_auxt__16u2_p8_1,
  144462. NULL,
  144463. 0
  144464. };
  144465. static long _vq_quantlist__16u2_p9_0[] = {
  144466. 5586,
  144467. 4655,
  144468. 6517,
  144469. 3724,
  144470. 7448,
  144471. 2793,
  144472. 8379,
  144473. 1862,
  144474. 9310,
  144475. 931,
  144476. 10241,
  144477. 0,
  144478. 11172,
  144479. 5521,
  144480. 5651,
  144481. };
  144482. static long _vq_lengthlist__16u2_p9_0[] = {
  144483. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144484. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144485. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144486. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144487. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144488. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144489. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144490. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144491. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144492. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144493. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144494. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144495. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144496. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144497. 5,
  144498. };
  144499. static float _vq_quantthresh__16u2_p9_0[] = {
  144500. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144501. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144502. };
  144503. static long _vq_quantmap__16u2_p9_0[] = {
  144504. 11, 9, 7, 5, 3, 1, 13, 0,
  144505. 14, 2, 4, 6, 8, 10, 12,
  144506. };
  144507. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144508. _vq_quantthresh__16u2_p9_0,
  144509. _vq_quantmap__16u2_p9_0,
  144510. 15,
  144511. 15
  144512. };
  144513. static static_codebook _16u2_p9_0 = {
  144514. 2, 225,
  144515. _vq_lengthlist__16u2_p9_0,
  144516. 1, -510275072, 1611661312, 14, 0,
  144517. _vq_quantlist__16u2_p9_0,
  144518. NULL,
  144519. &_vq_auxt__16u2_p9_0,
  144520. NULL,
  144521. 0
  144522. };
  144523. static long _vq_quantlist__16u2_p9_1[] = {
  144524. 392,
  144525. 343,
  144526. 441,
  144527. 294,
  144528. 490,
  144529. 245,
  144530. 539,
  144531. 196,
  144532. 588,
  144533. 147,
  144534. 637,
  144535. 98,
  144536. 686,
  144537. 49,
  144538. 735,
  144539. 0,
  144540. 784,
  144541. 388,
  144542. 396,
  144543. };
  144544. static long _vq_lengthlist__16u2_p9_1[] = {
  144545. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144546. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144547. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144548. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144549. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144550. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144551. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144552. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144553. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144554. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144555. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144556. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144557. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144558. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144559. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144560. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144561. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144562. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144563. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144565. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144566. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144567. 11,11,11,11,11,11,11, 5, 4,
  144568. };
  144569. static float _vq_quantthresh__16u2_p9_1[] = {
  144570. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144571. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144572. 318.5, 367.5,
  144573. };
  144574. static long _vq_quantmap__16u2_p9_1[] = {
  144575. 15, 13, 11, 9, 7, 5, 3, 1,
  144576. 17, 0, 18, 2, 4, 6, 8, 10,
  144577. 12, 14, 16,
  144578. };
  144579. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144580. _vq_quantthresh__16u2_p9_1,
  144581. _vq_quantmap__16u2_p9_1,
  144582. 19,
  144583. 19
  144584. };
  144585. static static_codebook _16u2_p9_1 = {
  144586. 2, 361,
  144587. _vq_lengthlist__16u2_p9_1,
  144588. 1, -518488064, 1611661312, 10, 0,
  144589. _vq_quantlist__16u2_p9_1,
  144590. NULL,
  144591. &_vq_auxt__16u2_p9_1,
  144592. NULL,
  144593. 0
  144594. };
  144595. static long _vq_quantlist__16u2_p9_2[] = {
  144596. 24,
  144597. 23,
  144598. 25,
  144599. 22,
  144600. 26,
  144601. 21,
  144602. 27,
  144603. 20,
  144604. 28,
  144605. 19,
  144606. 29,
  144607. 18,
  144608. 30,
  144609. 17,
  144610. 31,
  144611. 16,
  144612. 32,
  144613. 15,
  144614. 33,
  144615. 14,
  144616. 34,
  144617. 13,
  144618. 35,
  144619. 12,
  144620. 36,
  144621. 11,
  144622. 37,
  144623. 10,
  144624. 38,
  144625. 9,
  144626. 39,
  144627. 8,
  144628. 40,
  144629. 7,
  144630. 41,
  144631. 6,
  144632. 42,
  144633. 5,
  144634. 43,
  144635. 4,
  144636. 44,
  144637. 3,
  144638. 45,
  144639. 2,
  144640. 46,
  144641. 1,
  144642. 47,
  144643. 0,
  144644. 48,
  144645. };
  144646. static long _vq_lengthlist__16u2_p9_2[] = {
  144647. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144648. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144649. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144650. 11,
  144651. };
  144652. static float _vq_quantthresh__16u2_p9_2[] = {
  144653. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144654. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144655. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144656. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144657. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144658. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144659. };
  144660. static long _vq_quantmap__16u2_p9_2[] = {
  144661. 47, 45, 43, 41, 39, 37, 35, 33,
  144662. 31, 29, 27, 25, 23, 21, 19, 17,
  144663. 15, 13, 11, 9, 7, 5, 3, 1,
  144664. 0, 2, 4, 6, 8, 10, 12, 14,
  144665. 16, 18, 20, 22, 24, 26, 28, 30,
  144666. 32, 34, 36, 38, 40, 42, 44, 46,
  144667. 48,
  144668. };
  144669. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  144670. _vq_quantthresh__16u2_p9_2,
  144671. _vq_quantmap__16u2_p9_2,
  144672. 49,
  144673. 49
  144674. };
  144675. static static_codebook _16u2_p9_2 = {
  144676. 1, 49,
  144677. _vq_lengthlist__16u2_p9_2,
  144678. 1, -526909440, 1611661312, 6, 0,
  144679. _vq_quantlist__16u2_p9_2,
  144680. NULL,
  144681. &_vq_auxt__16u2_p9_2,
  144682. NULL,
  144683. 0
  144684. };
  144685. static long _vq_quantlist__8u0__p1_0[] = {
  144686. 1,
  144687. 0,
  144688. 2,
  144689. };
  144690. static long _vq_lengthlist__8u0__p1_0[] = {
  144691. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144692. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  144693. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  144694. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  144695. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  144696. 11,
  144697. };
  144698. static float _vq_quantthresh__8u0__p1_0[] = {
  144699. -0.5, 0.5,
  144700. };
  144701. static long _vq_quantmap__8u0__p1_0[] = {
  144702. 1, 0, 2,
  144703. };
  144704. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  144705. _vq_quantthresh__8u0__p1_0,
  144706. _vq_quantmap__8u0__p1_0,
  144707. 3,
  144708. 3
  144709. };
  144710. static static_codebook _8u0__p1_0 = {
  144711. 4, 81,
  144712. _vq_lengthlist__8u0__p1_0,
  144713. 1, -535822336, 1611661312, 2, 0,
  144714. _vq_quantlist__8u0__p1_0,
  144715. NULL,
  144716. &_vq_auxt__8u0__p1_0,
  144717. NULL,
  144718. 0
  144719. };
  144720. static long _vq_quantlist__8u0__p2_0[] = {
  144721. 1,
  144722. 0,
  144723. 2,
  144724. };
  144725. static long _vq_lengthlist__8u0__p2_0[] = {
  144726. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  144727. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  144728. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  144729. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  144730. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  144731. 8,
  144732. };
  144733. static float _vq_quantthresh__8u0__p2_0[] = {
  144734. -0.5, 0.5,
  144735. };
  144736. static long _vq_quantmap__8u0__p2_0[] = {
  144737. 1, 0, 2,
  144738. };
  144739. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  144740. _vq_quantthresh__8u0__p2_0,
  144741. _vq_quantmap__8u0__p2_0,
  144742. 3,
  144743. 3
  144744. };
  144745. static static_codebook _8u0__p2_0 = {
  144746. 4, 81,
  144747. _vq_lengthlist__8u0__p2_0,
  144748. 1, -535822336, 1611661312, 2, 0,
  144749. _vq_quantlist__8u0__p2_0,
  144750. NULL,
  144751. &_vq_auxt__8u0__p2_0,
  144752. NULL,
  144753. 0
  144754. };
  144755. static long _vq_quantlist__8u0__p3_0[] = {
  144756. 2,
  144757. 1,
  144758. 3,
  144759. 0,
  144760. 4,
  144761. };
  144762. static long _vq_lengthlist__8u0__p3_0[] = {
  144763. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  144764. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  144765. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  144766. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  144767. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  144768. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  144769. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  144770. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  144771. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  144772. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  144773. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  144774. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  144775. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  144776. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  144777. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  144778. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  144779. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  144780. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  144781. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  144782. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  144783. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  144784. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  144785. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  144786. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  144787. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  144788. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  144789. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  144790. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  144791. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  144792. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  144793. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  144794. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  144795. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  144796. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  144797. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  144798. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  144799. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  144800. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  144801. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  144802. 16,
  144803. };
  144804. static float _vq_quantthresh__8u0__p3_0[] = {
  144805. -1.5, -0.5, 0.5, 1.5,
  144806. };
  144807. static long _vq_quantmap__8u0__p3_0[] = {
  144808. 3, 1, 0, 2, 4,
  144809. };
  144810. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  144811. _vq_quantthresh__8u0__p3_0,
  144812. _vq_quantmap__8u0__p3_0,
  144813. 5,
  144814. 5
  144815. };
  144816. static static_codebook _8u0__p3_0 = {
  144817. 4, 625,
  144818. _vq_lengthlist__8u0__p3_0,
  144819. 1, -533725184, 1611661312, 3, 0,
  144820. _vq_quantlist__8u0__p3_0,
  144821. NULL,
  144822. &_vq_auxt__8u0__p3_0,
  144823. NULL,
  144824. 0
  144825. };
  144826. static long _vq_quantlist__8u0__p4_0[] = {
  144827. 2,
  144828. 1,
  144829. 3,
  144830. 0,
  144831. 4,
  144832. };
  144833. static long _vq_lengthlist__8u0__p4_0[] = {
  144834. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  144835. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  144836. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  144837. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  144838. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  144839. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  144840. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  144841. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  144842. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  144843. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  144844. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  144845. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  144846. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  144847. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  144848. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  144849. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  144850. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  144851. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  144852. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  144853. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  144854. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  144855. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  144856. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  144857. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  144858. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  144859. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  144860. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  144861. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  144862. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  144863. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  144864. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  144865. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  144866. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  144867. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  144868. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  144869. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  144870. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  144871. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  144872. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  144873. 12,
  144874. };
  144875. static float _vq_quantthresh__8u0__p4_0[] = {
  144876. -1.5, -0.5, 0.5, 1.5,
  144877. };
  144878. static long _vq_quantmap__8u0__p4_0[] = {
  144879. 3, 1, 0, 2, 4,
  144880. };
  144881. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  144882. _vq_quantthresh__8u0__p4_0,
  144883. _vq_quantmap__8u0__p4_0,
  144884. 5,
  144885. 5
  144886. };
  144887. static static_codebook _8u0__p4_0 = {
  144888. 4, 625,
  144889. _vq_lengthlist__8u0__p4_0,
  144890. 1, -533725184, 1611661312, 3, 0,
  144891. _vq_quantlist__8u0__p4_0,
  144892. NULL,
  144893. &_vq_auxt__8u0__p4_0,
  144894. NULL,
  144895. 0
  144896. };
  144897. static long _vq_quantlist__8u0__p5_0[] = {
  144898. 4,
  144899. 3,
  144900. 5,
  144901. 2,
  144902. 6,
  144903. 1,
  144904. 7,
  144905. 0,
  144906. 8,
  144907. };
  144908. static long _vq_lengthlist__8u0__p5_0[] = {
  144909. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  144910. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  144911. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144912. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144913. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  144914. 12,
  144915. };
  144916. static float _vq_quantthresh__8u0__p5_0[] = {
  144917. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144918. };
  144919. static long _vq_quantmap__8u0__p5_0[] = {
  144920. 7, 5, 3, 1, 0, 2, 4, 6,
  144921. 8,
  144922. };
  144923. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  144924. _vq_quantthresh__8u0__p5_0,
  144925. _vq_quantmap__8u0__p5_0,
  144926. 9,
  144927. 9
  144928. };
  144929. static static_codebook _8u0__p5_0 = {
  144930. 2, 81,
  144931. _vq_lengthlist__8u0__p5_0,
  144932. 1, -531628032, 1611661312, 4, 0,
  144933. _vq_quantlist__8u0__p5_0,
  144934. NULL,
  144935. &_vq_auxt__8u0__p5_0,
  144936. NULL,
  144937. 0
  144938. };
  144939. static long _vq_quantlist__8u0__p6_0[] = {
  144940. 6,
  144941. 5,
  144942. 7,
  144943. 4,
  144944. 8,
  144945. 3,
  144946. 9,
  144947. 2,
  144948. 10,
  144949. 1,
  144950. 11,
  144951. 0,
  144952. 12,
  144953. };
  144954. static long _vq_lengthlist__8u0__p6_0[] = {
  144955. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  144956. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  144957. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  144958. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  144959. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  144960. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  144961. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  144962. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  144963. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  144964. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  144965. 16, 0,15, 0,17, 0, 0, 0, 0,
  144966. };
  144967. static float _vq_quantthresh__8u0__p6_0[] = {
  144968. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144969. 12.5, 17.5, 22.5, 27.5,
  144970. };
  144971. static long _vq_quantmap__8u0__p6_0[] = {
  144972. 11, 9, 7, 5, 3, 1, 0, 2,
  144973. 4, 6, 8, 10, 12,
  144974. };
  144975. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  144976. _vq_quantthresh__8u0__p6_0,
  144977. _vq_quantmap__8u0__p6_0,
  144978. 13,
  144979. 13
  144980. };
  144981. static static_codebook _8u0__p6_0 = {
  144982. 2, 169,
  144983. _vq_lengthlist__8u0__p6_0,
  144984. 1, -526516224, 1616117760, 4, 0,
  144985. _vq_quantlist__8u0__p6_0,
  144986. NULL,
  144987. &_vq_auxt__8u0__p6_0,
  144988. NULL,
  144989. 0
  144990. };
  144991. static long _vq_quantlist__8u0__p6_1[] = {
  144992. 2,
  144993. 1,
  144994. 3,
  144995. 0,
  144996. 4,
  144997. };
  144998. static long _vq_lengthlist__8u0__p6_1[] = {
  144999. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145000. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145001. };
  145002. static float _vq_quantthresh__8u0__p6_1[] = {
  145003. -1.5, -0.5, 0.5, 1.5,
  145004. };
  145005. static long _vq_quantmap__8u0__p6_1[] = {
  145006. 3, 1, 0, 2, 4,
  145007. };
  145008. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145009. _vq_quantthresh__8u0__p6_1,
  145010. _vq_quantmap__8u0__p6_1,
  145011. 5,
  145012. 5
  145013. };
  145014. static static_codebook _8u0__p6_1 = {
  145015. 2, 25,
  145016. _vq_lengthlist__8u0__p6_1,
  145017. 1, -533725184, 1611661312, 3, 0,
  145018. _vq_quantlist__8u0__p6_1,
  145019. NULL,
  145020. &_vq_auxt__8u0__p6_1,
  145021. NULL,
  145022. 0
  145023. };
  145024. static long _vq_quantlist__8u0__p7_0[] = {
  145025. 1,
  145026. 0,
  145027. 2,
  145028. };
  145029. static long _vq_lengthlist__8u0__p7_0[] = {
  145030. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145031. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145032. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145033. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145034. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145035. 7,
  145036. };
  145037. static float _vq_quantthresh__8u0__p7_0[] = {
  145038. -157.5, 157.5,
  145039. };
  145040. static long _vq_quantmap__8u0__p7_0[] = {
  145041. 1, 0, 2,
  145042. };
  145043. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145044. _vq_quantthresh__8u0__p7_0,
  145045. _vq_quantmap__8u0__p7_0,
  145046. 3,
  145047. 3
  145048. };
  145049. static static_codebook _8u0__p7_0 = {
  145050. 4, 81,
  145051. _vq_lengthlist__8u0__p7_0,
  145052. 1, -518803456, 1628680192, 2, 0,
  145053. _vq_quantlist__8u0__p7_0,
  145054. NULL,
  145055. &_vq_auxt__8u0__p7_0,
  145056. NULL,
  145057. 0
  145058. };
  145059. static long _vq_quantlist__8u0__p7_1[] = {
  145060. 7,
  145061. 6,
  145062. 8,
  145063. 5,
  145064. 9,
  145065. 4,
  145066. 10,
  145067. 3,
  145068. 11,
  145069. 2,
  145070. 12,
  145071. 1,
  145072. 13,
  145073. 0,
  145074. 14,
  145075. };
  145076. static long _vq_lengthlist__8u0__p7_1[] = {
  145077. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145078. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145079. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145080. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145081. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145082. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145083. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145084. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145085. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145086. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145089. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145090. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145091. 10,
  145092. };
  145093. static float _vq_quantthresh__8u0__p7_1[] = {
  145094. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145095. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145096. };
  145097. static long _vq_quantmap__8u0__p7_1[] = {
  145098. 13, 11, 9, 7, 5, 3, 1, 0,
  145099. 2, 4, 6, 8, 10, 12, 14,
  145100. };
  145101. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145102. _vq_quantthresh__8u0__p7_1,
  145103. _vq_quantmap__8u0__p7_1,
  145104. 15,
  145105. 15
  145106. };
  145107. static static_codebook _8u0__p7_1 = {
  145108. 2, 225,
  145109. _vq_lengthlist__8u0__p7_1,
  145110. 1, -520986624, 1620377600, 4, 0,
  145111. _vq_quantlist__8u0__p7_1,
  145112. NULL,
  145113. &_vq_auxt__8u0__p7_1,
  145114. NULL,
  145115. 0
  145116. };
  145117. static long _vq_quantlist__8u0__p7_2[] = {
  145118. 10,
  145119. 9,
  145120. 11,
  145121. 8,
  145122. 12,
  145123. 7,
  145124. 13,
  145125. 6,
  145126. 14,
  145127. 5,
  145128. 15,
  145129. 4,
  145130. 16,
  145131. 3,
  145132. 17,
  145133. 2,
  145134. 18,
  145135. 1,
  145136. 19,
  145137. 0,
  145138. 20,
  145139. };
  145140. static long _vq_lengthlist__8u0__p7_2[] = {
  145141. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145142. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145143. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145144. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145145. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145146. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145147. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145148. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145149. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145150. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145151. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145152. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145153. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145154. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145155. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145156. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145157. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145158. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145159. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145160. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145161. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145162. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145163. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145164. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145165. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145166. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145167. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145168. 11,12,11,11,11,10,10,11,11,
  145169. };
  145170. static float _vq_quantthresh__8u0__p7_2[] = {
  145171. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145172. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145173. 6.5, 7.5, 8.5, 9.5,
  145174. };
  145175. static long _vq_quantmap__8u0__p7_2[] = {
  145176. 19, 17, 15, 13, 11, 9, 7, 5,
  145177. 3, 1, 0, 2, 4, 6, 8, 10,
  145178. 12, 14, 16, 18, 20,
  145179. };
  145180. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145181. _vq_quantthresh__8u0__p7_2,
  145182. _vq_quantmap__8u0__p7_2,
  145183. 21,
  145184. 21
  145185. };
  145186. static static_codebook _8u0__p7_2 = {
  145187. 2, 441,
  145188. _vq_lengthlist__8u0__p7_2,
  145189. 1, -529268736, 1611661312, 5, 0,
  145190. _vq_quantlist__8u0__p7_2,
  145191. NULL,
  145192. &_vq_auxt__8u0__p7_2,
  145193. NULL,
  145194. 0
  145195. };
  145196. static long _huff_lengthlist__8u0__single[] = {
  145197. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145198. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145199. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145200. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145201. };
  145202. static static_codebook _huff_book__8u0__single = {
  145203. 2, 64,
  145204. _huff_lengthlist__8u0__single,
  145205. 0, 0, 0, 0, 0,
  145206. NULL,
  145207. NULL,
  145208. NULL,
  145209. NULL,
  145210. 0
  145211. };
  145212. static long _vq_quantlist__8u1__p1_0[] = {
  145213. 1,
  145214. 0,
  145215. 2,
  145216. };
  145217. static long _vq_lengthlist__8u1__p1_0[] = {
  145218. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145219. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145220. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145221. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145222. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145223. 10,
  145224. };
  145225. static float _vq_quantthresh__8u1__p1_0[] = {
  145226. -0.5, 0.5,
  145227. };
  145228. static long _vq_quantmap__8u1__p1_0[] = {
  145229. 1, 0, 2,
  145230. };
  145231. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145232. _vq_quantthresh__8u1__p1_0,
  145233. _vq_quantmap__8u1__p1_0,
  145234. 3,
  145235. 3
  145236. };
  145237. static static_codebook _8u1__p1_0 = {
  145238. 4, 81,
  145239. _vq_lengthlist__8u1__p1_0,
  145240. 1, -535822336, 1611661312, 2, 0,
  145241. _vq_quantlist__8u1__p1_0,
  145242. NULL,
  145243. &_vq_auxt__8u1__p1_0,
  145244. NULL,
  145245. 0
  145246. };
  145247. static long _vq_quantlist__8u1__p2_0[] = {
  145248. 1,
  145249. 0,
  145250. 2,
  145251. };
  145252. static long _vq_lengthlist__8u1__p2_0[] = {
  145253. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145254. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145255. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145256. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145257. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145258. 7,
  145259. };
  145260. static float _vq_quantthresh__8u1__p2_0[] = {
  145261. -0.5, 0.5,
  145262. };
  145263. static long _vq_quantmap__8u1__p2_0[] = {
  145264. 1, 0, 2,
  145265. };
  145266. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145267. _vq_quantthresh__8u1__p2_0,
  145268. _vq_quantmap__8u1__p2_0,
  145269. 3,
  145270. 3
  145271. };
  145272. static static_codebook _8u1__p2_0 = {
  145273. 4, 81,
  145274. _vq_lengthlist__8u1__p2_0,
  145275. 1, -535822336, 1611661312, 2, 0,
  145276. _vq_quantlist__8u1__p2_0,
  145277. NULL,
  145278. &_vq_auxt__8u1__p2_0,
  145279. NULL,
  145280. 0
  145281. };
  145282. static long _vq_quantlist__8u1__p3_0[] = {
  145283. 2,
  145284. 1,
  145285. 3,
  145286. 0,
  145287. 4,
  145288. };
  145289. static long _vq_lengthlist__8u1__p3_0[] = {
  145290. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145291. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145292. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145293. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145294. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145295. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145296. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145297. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145298. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145299. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145300. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145301. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145302. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145303. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145304. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145305. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145306. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145307. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145308. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145309. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145310. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145311. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145312. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145313. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145314. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145315. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145316. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145317. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145318. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145319. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145320. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145321. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145322. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145323. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145324. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145325. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145326. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145327. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145328. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145329. 16,
  145330. };
  145331. static float _vq_quantthresh__8u1__p3_0[] = {
  145332. -1.5, -0.5, 0.5, 1.5,
  145333. };
  145334. static long _vq_quantmap__8u1__p3_0[] = {
  145335. 3, 1, 0, 2, 4,
  145336. };
  145337. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145338. _vq_quantthresh__8u1__p3_0,
  145339. _vq_quantmap__8u1__p3_0,
  145340. 5,
  145341. 5
  145342. };
  145343. static static_codebook _8u1__p3_0 = {
  145344. 4, 625,
  145345. _vq_lengthlist__8u1__p3_0,
  145346. 1, -533725184, 1611661312, 3, 0,
  145347. _vq_quantlist__8u1__p3_0,
  145348. NULL,
  145349. &_vq_auxt__8u1__p3_0,
  145350. NULL,
  145351. 0
  145352. };
  145353. static long _vq_quantlist__8u1__p4_0[] = {
  145354. 2,
  145355. 1,
  145356. 3,
  145357. 0,
  145358. 4,
  145359. };
  145360. static long _vq_lengthlist__8u1__p4_0[] = {
  145361. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145362. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145363. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145364. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145365. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145366. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145367. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145368. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145369. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145370. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145371. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145372. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145373. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145374. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145375. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145376. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145377. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145378. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145379. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145380. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145381. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145382. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145383. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145384. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145385. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145386. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145387. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145388. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145389. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145390. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145391. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145392. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145393. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145394. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145395. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145396. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145397. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145398. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145399. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145400. 10,
  145401. };
  145402. static float _vq_quantthresh__8u1__p4_0[] = {
  145403. -1.5, -0.5, 0.5, 1.5,
  145404. };
  145405. static long _vq_quantmap__8u1__p4_0[] = {
  145406. 3, 1, 0, 2, 4,
  145407. };
  145408. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145409. _vq_quantthresh__8u1__p4_0,
  145410. _vq_quantmap__8u1__p4_0,
  145411. 5,
  145412. 5
  145413. };
  145414. static static_codebook _8u1__p4_0 = {
  145415. 4, 625,
  145416. _vq_lengthlist__8u1__p4_0,
  145417. 1, -533725184, 1611661312, 3, 0,
  145418. _vq_quantlist__8u1__p4_0,
  145419. NULL,
  145420. &_vq_auxt__8u1__p4_0,
  145421. NULL,
  145422. 0
  145423. };
  145424. static long _vq_quantlist__8u1__p5_0[] = {
  145425. 4,
  145426. 3,
  145427. 5,
  145428. 2,
  145429. 6,
  145430. 1,
  145431. 7,
  145432. 0,
  145433. 8,
  145434. };
  145435. static long _vq_lengthlist__8u1__p5_0[] = {
  145436. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145437. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145438. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145439. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145440. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145441. 13,
  145442. };
  145443. static float _vq_quantthresh__8u1__p5_0[] = {
  145444. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145445. };
  145446. static long _vq_quantmap__8u1__p5_0[] = {
  145447. 7, 5, 3, 1, 0, 2, 4, 6,
  145448. 8,
  145449. };
  145450. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145451. _vq_quantthresh__8u1__p5_0,
  145452. _vq_quantmap__8u1__p5_0,
  145453. 9,
  145454. 9
  145455. };
  145456. static static_codebook _8u1__p5_0 = {
  145457. 2, 81,
  145458. _vq_lengthlist__8u1__p5_0,
  145459. 1, -531628032, 1611661312, 4, 0,
  145460. _vq_quantlist__8u1__p5_0,
  145461. NULL,
  145462. &_vq_auxt__8u1__p5_0,
  145463. NULL,
  145464. 0
  145465. };
  145466. static long _vq_quantlist__8u1__p6_0[] = {
  145467. 4,
  145468. 3,
  145469. 5,
  145470. 2,
  145471. 6,
  145472. 1,
  145473. 7,
  145474. 0,
  145475. 8,
  145476. };
  145477. static long _vq_lengthlist__8u1__p6_0[] = {
  145478. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145479. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145480. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145481. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145482. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145483. 10,
  145484. };
  145485. static float _vq_quantthresh__8u1__p6_0[] = {
  145486. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145487. };
  145488. static long _vq_quantmap__8u1__p6_0[] = {
  145489. 7, 5, 3, 1, 0, 2, 4, 6,
  145490. 8,
  145491. };
  145492. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145493. _vq_quantthresh__8u1__p6_0,
  145494. _vq_quantmap__8u1__p6_0,
  145495. 9,
  145496. 9
  145497. };
  145498. static static_codebook _8u1__p6_0 = {
  145499. 2, 81,
  145500. _vq_lengthlist__8u1__p6_0,
  145501. 1, -531628032, 1611661312, 4, 0,
  145502. _vq_quantlist__8u1__p6_0,
  145503. NULL,
  145504. &_vq_auxt__8u1__p6_0,
  145505. NULL,
  145506. 0
  145507. };
  145508. static long _vq_quantlist__8u1__p7_0[] = {
  145509. 1,
  145510. 0,
  145511. 2,
  145512. };
  145513. static long _vq_lengthlist__8u1__p7_0[] = {
  145514. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145515. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145516. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145517. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145518. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145519. 11,
  145520. };
  145521. static float _vq_quantthresh__8u1__p7_0[] = {
  145522. -5.5, 5.5,
  145523. };
  145524. static long _vq_quantmap__8u1__p7_0[] = {
  145525. 1, 0, 2,
  145526. };
  145527. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145528. _vq_quantthresh__8u1__p7_0,
  145529. _vq_quantmap__8u1__p7_0,
  145530. 3,
  145531. 3
  145532. };
  145533. static static_codebook _8u1__p7_0 = {
  145534. 4, 81,
  145535. _vq_lengthlist__8u1__p7_0,
  145536. 1, -529137664, 1618345984, 2, 0,
  145537. _vq_quantlist__8u1__p7_0,
  145538. NULL,
  145539. &_vq_auxt__8u1__p7_0,
  145540. NULL,
  145541. 0
  145542. };
  145543. static long _vq_quantlist__8u1__p7_1[] = {
  145544. 5,
  145545. 4,
  145546. 6,
  145547. 3,
  145548. 7,
  145549. 2,
  145550. 8,
  145551. 1,
  145552. 9,
  145553. 0,
  145554. 10,
  145555. };
  145556. static long _vq_lengthlist__8u1__p7_1[] = {
  145557. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145558. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145559. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145560. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145561. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145562. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145563. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145564. 9, 9, 9, 9, 9,10,10,10,10,
  145565. };
  145566. static float _vq_quantthresh__8u1__p7_1[] = {
  145567. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145568. 3.5, 4.5,
  145569. };
  145570. static long _vq_quantmap__8u1__p7_1[] = {
  145571. 9, 7, 5, 3, 1, 0, 2, 4,
  145572. 6, 8, 10,
  145573. };
  145574. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145575. _vq_quantthresh__8u1__p7_1,
  145576. _vq_quantmap__8u1__p7_1,
  145577. 11,
  145578. 11
  145579. };
  145580. static static_codebook _8u1__p7_1 = {
  145581. 2, 121,
  145582. _vq_lengthlist__8u1__p7_1,
  145583. 1, -531365888, 1611661312, 4, 0,
  145584. _vq_quantlist__8u1__p7_1,
  145585. NULL,
  145586. &_vq_auxt__8u1__p7_1,
  145587. NULL,
  145588. 0
  145589. };
  145590. static long _vq_quantlist__8u1__p8_0[] = {
  145591. 5,
  145592. 4,
  145593. 6,
  145594. 3,
  145595. 7,
  145596. 2,
  145597. 8,
  145598. 1,
  145599. 9,
  145600. 0,
  145601. 10,
  145602. };
  145603. static long _vq_lengthlist__8u1__p8_0[] = {
  145604. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145605. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145606. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145607. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145608. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145609. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145610. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145611. 12,13,13,14,14,15,15,15,15,
  145612. };
  145613. static float _vq_quantthresh__8u1__p8_0[] = {
  145614. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145615. 38.5, 49.5,
  145616. };
  145617. static long _vq_quantmap__8u1__p8_0[] = {
  145618. 9, 7, 5, 3, 1, 0, 2, 4,
  145619. 6, 8, 10,
  145620. };
  145621. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145622. _vq_quantthresh__8u1__p8_0,
  145623. _vq_quantmap__8u1__p8_0,
  145624. 11,
  145625. 11
  145626. };
  145627. static static_codebook _8u1__p8_0 = {
  145628. 2, 121,
  145629. _vq_lengthlist__8u1__p8_0,
  145630. 1, -524582912, 1618345984, 4, 0,
  145631. _vq_quantlist__8u1__p8_0,
  145632. NULL,
  145633. &_vq_auxt__8u1__p8_0,
  145634. NULL,
  145635. 0
  145636. };
  145637. static long _vq_quantlist__8u1__p8_1[] = {
  145638. 5,
  145639. 4,
  145640. 6,
  145641. 3,
  145642. 7,
  145643. 2,
  145644. 8,
  145645. 1,
  145646. 9,
  145647. 0,
  145648. 10,
  145649. };
  145650. static long _vq_lengthlist__8u1__p8_1[] = {
  145651. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145652. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145653. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145654. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145655. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145656. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145657. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145658. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145659. };
  145660. static float _vq_quantthresh__8u1__p8_1[] = {
  145661. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145662. 3.5, 4.5,
  145663. };
  145664. static long _vq_quantmap__8u1__p8_1[] = {
  145665. 9, 7, 5, 3, 1, 0, 2, 4,
  145666. 6, 8, 10,
  145667. };
  145668. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  145669. _vq_quantthresh__8u1__p8_1,
  145670. _vq_quantmap__8u1__p8_1,
  145671. 11,
  145672. 11
  145673. };
  145674. static static_codebook _8u1__p8_1 = {
  145675. 2, 121,
  145676. _vq_lengthlist__8u1__p8_1,
  145677. 1, -531365888, 1611661312, 4, 0,
  145678. _vq_quantlist__8u1__p8_1,
  145679. NULL,
  145680. &_vq_auxt__8u1__p8_1,
  145681. NULL,
  145682. 0
  145683. };
  145684. static long _vq_quantlist__8u1__p9_0[] = {
  145685. 7,
  145686. 6,
  145687. 8,
  145688. 5,
  145689. 9,
  145690. 4,
  145691. 10,
  145692. 3,
  145693. 11,
  145694. 2,
  145695. 12,
  145696. 1,
  145697. 13,
  145698. 0,
  145699. 14,
  145700. };
  145701. static long _vq_lengthlist__8u1__p9_0[] = {
  145702. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  145703. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  145704. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145714. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  145715. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145716. 10,
  145717. };
  145718. static float _vq_quantthresh__8u1__p9_0[] = {
  145719. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145720. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145721. };
  145722. static long _vq_quantmap__8u1__p9_0[] = {
  145723. 13, 11, 9, 7, 5, 3, 1, 0,
  145724. 2, 4, 6, 8, 10, 12, 14,
  145725. };
  145726. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  145727. _vq_quantthresh__8u1__p9_0,
  145728. _vq_quantmap__8u1__p9_0,
  145729. 15,
  145730. 15
  145731. };
  145732. static static_codebook _8u1__p9_0 = {
  145733. 2, 225,
  145734. _vq_lengthlist__8u1__p9_0,
  145735. 1, -514071552, 1627381760, 4, 0,
  145736. _vq_quantlist__8u1__p9_0,
  145737. NULL,
  145738. &_vq_auxt__8u1__p9_0,
  145739. NULL,
  145740. 0
  145741. };
  145742. static long _vq_quantlist__8u1__p9_1[] = {
  145743. 7,
  145744. 6,
  145745. 8,
  145746. 5,
  145747. 9,
  145748. 4,
  145749. 10,
  145750. 3,
  145751. 11,
  145752. 2,
  145753. 12,
  145754. 1,
  145755. 13,
  145756. 0,
  145757. 14,
  145758. };
  145759. static long _vq_lengthlist__8u1__p9_1[] = {
  145760. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  145761. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  145762. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  145763. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  145764. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  145765. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  145766. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  145767. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  145768. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  145769. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  145770. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  145771. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  145772. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  145773. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  145774. 13,
  145775. };
  145776. static float _vq_quantthresh__8u1__p9_1[] = {
  145777. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145778. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145779. };
  145780. static long _vq_quantmap__8u1__p9_1[] = {
  145781. 13, 11, 9, 7, 5, 3, 1, 0,
  145782. 2, 4, 6, 8, 10, 12, 14,
  145783. };
  145784. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  145785. _vq_quantthresh__8u1__p9_1,
  145786. _vq_quantmap__8u1__p9_1,
  145787. 15,
  145788. 15
  145789. };
  145790. static static_codebook _8u1__p9_1 = {
  145791. 2, 225,
  145792. _vq_lengthlist__8u1__p9_1,
  145793. 1, -522338304, 1620115456, 4, 0,
  145794. _vq_quantlist__8u1__p9_1,
  145795. NULL,
  145796. &_vq_auxt__8u1__p9_1,
  145797. NULL,
  145798. 0
  145799. };
  145800. static long _vq_quantlist__8u1__p9_2[] = {
  145801. 8,
  145802. 7,
  145803. 9,
  145804. 6,
  145805. 10,
  145806. 5,
  145807. 11,
  145808. 4,
  145809. 12,
  145810. 3,
  145811. 13,
  145812. 2,
  145813. 14,
  145814. 1,
  145815. 15,
  145816. 0,
  145817. 16,
  145818. };
  145819. static long _vq_lengthlist__8u1__p9_2[] = {
  145820. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145821. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145822. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145823. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145824. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145825. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  145826. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145827. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  145828. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145829. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  145830. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  145831. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  145832. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145833. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  145835. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145836. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145837. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145838. 10,
  145839. };
  145840. static float _vq_quantthresh__8u1__p9_2[] = {
  145841. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145842. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145843. };
  145844. static long _vq_quantmap__8u1__p9_2[] = {
  145845. 15, 13, 11, 9, 7, 5, 3, 1,
  145846. 0, 2, 4, 6, 8, 10, 12, 14,
  145847. 16,
  145848. };
  145849. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  145850. _vq_quantthresh__8u1__p9_2,
  145851. _vq_quantmap__8u1__p9_2,
  145852. 17,
  145853. 17
  145854. };
  145855. static static_codebook _8u1__p9_2 = {
  145856. 2, 289,
  145857. _vq_lengthlist__8u1__p9_2,
  145858. 1, -529530880, 1611661312, 5, 0,
  145859. _vq_quantlist__8u1__p9_2,
  145860. NULL,
  145861. &_vq_auxt__8u1__p9_2,
  145862. NULL,
  145863. 0
  145864. };
  145865. static long _huff_lengthlist__8u1__single[] = {
  145866. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  145867. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  145868. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  145869. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  145870. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  145871. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  145872. 13, 8, 8,15,
  145873. };
  145874. static static_codebook _huff_book__8u1__single = {
  145875. 2, 100,
  145876. _huff_lengthlist__8u1__single,
  145877. 0, 0, 0, 0, 0,
  145878. NULL,
  145879. NULL,
  145880. NULL,
  145881. NULL,
  145882. 0
  145883. };
  145884. static long _huff_lengthlist__44u0__long[] = {
  145885. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  145886. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  145887. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  145888. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  145889. };
  145890. static static_codebook _huff_book__44u0__long = {
  145891. 2, 64,
  145892. _huff_lengthlist__44u0__long,
  145893. 0, 0, 0, 0, 0,
  145894. NULL,
  145895. NULL,
  145896. NULL,
  145897. NULL,
  145898. 0
  145899. };
  145900. static long _vq_quantlist__44u0__p1_0[] = {
  145901. 1,
  145902. 0,
  145903. 2,
  145904. };
  145905. static long _vq_lengthlist__44u0__p1_0[] = {
  145906. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  145907. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  145908. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  145909. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  145910. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  145911. 13,
  145912. };
  145913. static float _vq_quantthresh__44u0__p1_0[] = {
  145914. -0.5, 0.5,
  145915. };
  145916. static long _vq_quantmap__44u0__p1_0[] = {
  145917. 1, 0, 2,
  145918. };
  145919. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  145920. _vq_quantthresh__44u0__p1_0,
  145921. _vq_quantmap__44u0__p1_0,
  145922. 3,
  145923. 3
  145924. };
  145925. static static_codebook _44u0__p1_0 = {
  145926. 4, 81,
  145927. _vq_lengthlist__44u0__p1_0,
  145928. 1, -535822336, 1611661312, 2, 0,
  145929. _vq_quantlist__44u0__p1_0,
  145930. NULL,
  145931. &_vq_auxt__44u0__p1_0,
  145932. NULL,
  145933. 0
  145934. };
  145935. static long _vq_quantlist__44u0__p2_0[] = {
  145936. 1,
  145937. 0,
  145938. 2,
  145939. };
  145940. static long _vq_lengthlist__44u0__p2_0[] = {
  145941. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  145942. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  145943. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  145944. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  145945. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  145946. 9,
  145947. };
  145948. static float _vq_quantthresh__44u0__p2_0[] = {
  145949. -0.5, 0.5,
  145950. };
  145951. static long _vq_quantmap__44u0__p2_0[] = {
  145952. 1, 0, 2,
  145953. };
  145954. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  145955. _vq_quantthresh__44u0__p2_0,
  145956. _vq_quantmap__44u0__p2_0,
  145957. 3,
  145958. 3
  145959. };
  145960. static static_codebook _44u0__p2_0 = {
  145961. 4, 81,
  145962. _vq_lengthlist__44u0__p2_0,
  145963. 1, -535822336, 1611661312, 2, 0,
  145964. _vq_quantlist__44u0__p2_0,
  145965. NULL,
  145966. &_vq_auxt__44u0__p2_0,
  145967. NULL,
  145968. 0
  145969. };
  145970. static long _vq_quantlist__44u0__p3_0[] = {
  145971. 2,
  145972. 1,
  145973. 3,
  145974. 0,
  145975. 4,
  145976. };
  145977. static long _vq_lengthlist__44u0__p3_0[] = {
  145978. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  145979. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  145980. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  145981. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145982. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  145983. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  145984. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  145985. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  145986. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  145987. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  145988. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  145989. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  145990. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  145991. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  145992. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  145993. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  145994. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  145995. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  145996. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  145997. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  145998. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  145999. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146000. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146001. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146002. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146003. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146004. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146005. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146006. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146007. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146008. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146009. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146010. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146011. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146012. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146013. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146014. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146015. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146016. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146017. 19,
  146018. };
  146019. static float _vq_quantthresh__44u0__p3_0[] = {
  146020. -1.5, -0.5, 0.5, 1.5,
  146021. };
  146022. static long _vq_quantmap__44u0__p3_0[] = {
  146023. 3, 1, 0, 2, 4,
  146024. };
  146025. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146026. _vq_quantthresh__44u0__p3_0,
  146027. _vq_quantmap__44u0__p3_0,
  146028. 5,
  146029. 5
  146030. };
  146031. static static_codebook _44u0__p3_0 = {
  146032. 4, 625,
  146033. _vq_lengthlist__44u0__p3_0,
  146034. 1, -533725184, 1611661312, 3, 0,
  146035. _vq_quantlist__44u0__p3_0,
  146036. NULL,
  146037. &_vq_auxt__44u0__p3_0,
  146038. NULL,
  146039. 0
  146040. };
  146041. static long _vq_quantlist__44u0__p4_0[] = {
  146042. 2,
  146043. 1,
  146044. 3,
  146045. 0,
  146046. 4,
  146047. };
  146048. static long _vq_lengthlist__44u0__p4_0[] = {
  146049. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146050. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146051. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146052. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146053. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146054. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146055. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146056. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146057. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146058. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146059. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146060. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146061. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146062. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146063. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146064. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146065. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146066. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146067. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146068. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146069. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146070. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146071. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146072. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146073. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146074. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146075. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146076. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146077. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146078. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146079. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146080. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146081. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146082. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146083. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146084. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146085. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146086. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146087. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146088. 12,
  146089. };
  146090. static float _vq_quantthresh__44u0__p4_0[] = {
  146091. -1.5, -0.5, 0.5, 1.5,
  146092. };
  146093. static long _vq_quantmap__44u0__p4_0[] = {
  146094. 3, 1, 0, 2, 4,
  146095. };
  146096. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146097. _vq_quantthresh__44u0__p4_0,
  146098. _vq_quantmap__44u0__p4_0,
  146099. 5,
  146100. 5
  146101. };
  146102. static static_codebook _44u0__p4_0 = {
  146103. 4, 625,
  146104. _vq_lengthlist__44u0__p4_0,
  146105. 1, -533725184, 1611661312, 3, 0,
  146106. _vq_quantlist__44u0__p4_0,
  146107. NULL,
  146108. &_vq_auxt__44u0__p4_0,
  146109. NULL,
  146110. 0
  146111. };
  146112. static long _vq_quantlist__44u0__p5_0[] = {
  146113. 4,
  146114. 3,
  146115. 5,
  146116. 2,
  146117. 6,
  146118. 1,
  146119. 7,
  146120. 0,
  146121. 8,
  146122. };
  146123. static long _vq_lengthlist__44u0__p5_0[] = {
  146124. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146125. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146126. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146127. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146128. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146129. 12,
  146130. };
  146131. static float _vq_quantthresh__44u0__p5_0[] = {
  146132. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146133. };
  146134. static long _vq_quantmap__44u0__p5_0[] = {
  146135. 7, 5, 3, 1, 0, 2, 4, 6,
  146136. 8,
  146137. };
  146138. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146139. _vq_quantthresh__44u0__p5_0,
  146140. _vq_quantmap__44u0__p5_0,
  146141. 9,
  146142. 9
  146143. };
  146144. static static_codebook _44u0__p5_0 = {
  146145. 2, 81,
  146146. _vq_lengthlist__44u0__p5_0,
  146147. 1, -531628032, 1611661312, 4, 0,
  146148. _vq_quantlist__44u0__p5_0,
  146149. NULL,
  146150. &_vq_auxt__44u0__p5_0,
  146151. NULL,
  146152. 0
  146153. };
  146154. static long _vq_quantlist__44u0__p6_0[] = {
  146155. 6,
  146156. 5,
  146157. 7,
  146158. 4,
  146159. 8,
  146160. 3,
  146161. 9,
  146162. 2,
  146163. 10,
  146164. 1,
  146165. 11,
  146166. 0,
  146167. 12,
  146168. };
  146169. static long _vq_lengthlist__44u0__p6_0[] = {
  146170. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146171. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146172. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146173. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146174. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146175. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146176. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146177. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146178. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146179. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146180. 15,17,16,17,18,17,17,18, 0,
  146181. };
  146182. static float _vq_quantthresh__44u0__p6_0[] = {
  146183. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146184. 12.5, 17.5, 22.5, 27.5,
  146185. };
  146186. static long _vq_quantmap__44u0__p6_0[] = {
  146187. 11, 9, 7, 5, 3, 1, 0, 2,
  146188. 4, 6, 8, 10, 12,
  146189. };
  146190. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146191. _vq_quantthresh__44u0__p6_0,
  146192. _vq_quantmap__44u0__p6_0,
  146193. 13,
  146194. 13
  146195. };
  146196. static static_codebook _44u0__p6_0 = {
  146197. 2, 169,
  146198. _vq_lengthlist__44u0__p6_0,
  146199. 1, -526516224, 1616117760, 4, 0,
  146200. _vq_quantlist__44u0__p6_0,
  146201. NULL,
  146202. &_vq_auxt__44u0__p6_0,
  146203. NULL,
  146204. 0
  146205. };
  146206. static long _vq_quantlist__44u0__p6_1[] = {
  146207. 2,
  146208. 1,
  146209. 3,
  146210. 0,
  146211. 4,
  146212. };
  146213. static long _vq_lengthlist__44u0__p6_1[] = {
  146214. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146215. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146216. };
  146217. static float _vq_quantthresh__44u0__p6_1[] = {
  146218. -1.5, -0.5, 0.5, 1.5,
  146219. };
  146220. static long _vq_quantmap__44u0__p6_1[] = {
  146221. 3, 1, 0, 2, 4,
  146222. };
  146223. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146224. _vq_quantthresh__44u0__p6_1,
  146225. _vq_quantmap__44u0__p6_1,
  146226. 5,
  146227. 5
  146228. };
  146229. static static_codebook _44u0__p6_1 = {
  146230. 2, 25,
  146231. _vq_lengthlist__44u0__p6_1,
  146232. 1, -533725184, 1611661312, 3, 0,
  146233. _vq_quantlist__44u0__p6_1,
  146234. NULL,
  146235. &_vq_auxt__44u0__p6_1,
  146236. NULL,
  146237. 0
  146238. };
  146239. static long _vq_quantlist__44u0__p7_0[] = {
  146240. 2,
  146241. 1,
  146242. 3,
  146243. 0,
  146244. 4,
  146245. };
  146246. static long _vq_lengthlist__44u0__p7_0[] = {
  146247. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146249. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146250. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146254. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146258. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146277. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146278. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146279. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146280. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146281. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146283. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146286. 10,
  146287. };
  146288. static float _vq_quantthresh__44u0__p7_0[] = {
  146289. -253.5, -84.5, 84.5, 253.5,
  146290. };
  146291. static long _vq_quantmap__44u0__p7_0[] = {
  146292. 3, 1, 0, 2, 4,
  146293. };
  146294. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146295. _vq_quantthresh__44u0__p7_0,
  146296. _vq_quantmap__44u0__p7_0,
  146297. 5,
  146298. 5
  146299. };
  146300. static static_codebook _44u0__p7_0 = {
  146301. 4, 625,
  146302. _vq_lengthlist__44u0__p7_0,
  146303. 1, -518709248, 1626677248, 3, 0,
  146304. _vq_quantlist__44u0__p7_0,
  146305. NULL,
  146306. &_vq_auxt__44u0__p7_0,
  146307. NULL,
  146308. 0
  146309. };
  146310. static long _vq_quantlist__44u0__p7_1[] = {
  146311. 6,
  146312. 5,
  146313. 7,
  146314. 4,
  146315. 8,
  146316. 3,
  146317. 9,
  146318. 2,
  146319. 10,
  146320. 1,
  146321. 11,
  146322. 0,
  146323. 12,
  146324. };
  146325. static long _vq_lengthlist__44u0__p7_1[] = {
  146326. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146327. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146328. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146329. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146330. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146331. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146332. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146333. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146334. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146335. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146336. 15,15,15,15,15,15,15,15,15,
  146337. };
  146338. static float _vq_quantthresh__44u0__p7_1[] = {
  146339. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146340. 32.5, 45.5, 58.5, 71.5,
  146341. };
  146342. static long _vq_quantmap__44u0__p7_1[] = {
  146343. 11, 9, 7, 5, 3, 1, 0, 2,
  146344. 4, 6, 8, 10, 12,
  146345. };
  146346. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146347. _vq_quantthresh__44u0__p7_1,
  146348. _vq_quantmap__44u0__p7_1,
  146349. 13,
  146350. 13
  146351. };
  146352. static static_codebook _44u0__p7_1 = {
  146353. 2, 169,
  146354. _vq_lengthlist__44u0__p7_1,
  146355. 1, -523010048, 1618608128, 4, 0,
  146356. _vq_quantlist__44u0__p7_1,
  146357. NULL,
  146358. &_vq_auxt__44u0__p7_1,
  146359. NULL,
  146360. 0
  146361. };
  146362. static long _vq_quantlist__44u0__p7_2[] = {
  146363. 6,
  146364. 5,
  146365. 7,
  146366. 4,
  146367. 8,
  146368. 3,
  146369. 9,
  146370. 2,
  146371. 10,
  146372. 1,
  146373. 11,
  146374. 0,
  146375. 12,
  146376. };
  146377. static long _vq_lengthlist__44u0__p7_2[] = {
  146378. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146379. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146380. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146381. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146382. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146383. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146384. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146385. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146386. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146387. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146388. 9, 9, 9,10, 9, 9,10,10, 9,
  146389. };
  146390. static float _vq_quantthresh__44u0__p7_2[] = {
  146391. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146392. 2.5, 3.5, 4.5, 5.5,
  146393. };
  146394. static long _vq_quantmap__44u0__p7_2[] = {
  146395. 11, 9, 7, 5, 3, 1, 0, 2,
  146396. 4, 6, 8, 10, 12,
  146397. };
  146398. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146399. _vq_quantthresh__44u0__p7_2,
  146400. _vq_quantmap__44u0__p7_2,
  146401. 13,
  146402. 13
  146403. };
  146404. static static_codebook _44u0__p7_2 = {
  146405. 2, 169,
  146406. _vq_lengthlist__44u0__p7_2,
  146407. 1, -531103744, 1611661312, 4, 0,
  146408. _vq_quantlist__44u0__p7_2,
  146409. NULL,
  146410. &_vq_auxt__44u0__p7_2,
  146411. NULL,
  146412. 0
  146413. };
  146414. static long _huff_lengthlist__44u0__short[] = {
  146415. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146416. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146417. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146418. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146419. };
  146420. static static_codebook _huff_book__44u0__short = {
  146421. 2, 64,
  146422. _huff_lengthlist__44u0__short,
  146423. 0, 0, 0, 0, 0,
  146424. NULL,
  146425. NULL,
  146426. NULL,
  146427. NULL,
  146428. 0
  146429. };
  146430. static long _huff_lengthlist__44u1__long[] = {
  146431. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146432. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146433. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146434. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146435. };
  146436. static static_codebook _huff_book__44u1__long = {
  146437. 2, 64,
  146438. _huff_lengthlist__44u1__long,
  146439. 0, 0, 0, 0, 0,
  146440. NULL,
  146441. NULL,
  146442. NULL,
  146443. NULL,
  146444. 0
  146445. };
  146446. static long _vq_quantlist__44u1__p1_0[] = {
  146447. 1,
  146448. 0,
  146449. 2,
  146450. };
  146451. static long _vq_lengthlist__44u1__p1_0[] = {
  146452. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146453. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146454. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146455. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146456. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146457. 13,
  146458. };
  146459. static float _vq_quantthresh__44u1__p1_0[] = {
  146460. -0.5, 0.5,
  146461. };
  146462. static long _vq_quantmap__44u1__p1_0[] = {
  146463. 1, 0, 2,
  146464. };
  146465. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146466. _vq_quantthresh__44u1__p1_0,
  146467. _vq_quantmap__44u1__p1_0,
  146468. 3,
  146469. 3
  146470. };
  146471. static static_codebook _44u1__p1_0 = {
  146472. 4, 81,
  146473. _vq_lengthlist__44u1__p1_0,
  146474. 1, -535822336, 1611661312, 2, 0,
  146475. _vq_quantlist__44u1__p1_0,
  146476. NULL,
  146477. &_vq_auxt__44u1__p1_0,
  146478. NULL,
  146479. 0
  146480. };
  146481. static long _vq_quantlist__44u1__p2_0[] = {
  146482. 1,
  146483. 0,
  146484. 2,
  146485. };
  146486. static long _vq_lengthlist__44u1__p2_0[] = {
  146487. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146488. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146489. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146490. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146491. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146492. 9,
  146493. };
  146494. static float _vq_quantthresh__44u1__p2_0[] = {
  146495. -0.5, 0.5,
  146496. };
  146497. static long _vq_quantmap__44u1__p2_0[] = {
  146498. 1, 0, 2,
  146499. };
  146500. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146501. _vq_quantthresh__44u1__p2_0,
  146502. _vq_quantmap__44u1__p2_0,
  146503. 3,
  146504. 3
  146505. };
  146506. static static_codebook _44u1__p2_0 = {
  146507. 4, 81,
  146508. _vq_lengthlist__44u1__p2_0,
  146509. 1, -535822336, 1611661312, 2, 0,
  146510. _vq_quantlist__44u1__p2_0,
  146511. NULL,
  146512. &_vq_auxt__44u1__p2_0,
  146513. NULL,
  146514. 0
  146515. };
  146516. static long _vq_quantlist__44u1__p3_0[] = {
  146517. 2,
  146518. 1,
  146519. 3,
  146520. 0,
  146521. 4,
  146522. };
  146523. static long _vq_lengthlist__44u1__p3_0[] = {
  146524. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146525. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146526. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146527. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146528. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146529. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146530. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146531. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146532. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146533. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146534. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146535. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146536. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146537. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146538. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146539. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146540. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146541. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146542. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146543. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146544. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146545. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146546. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146547. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146548. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146549. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146550. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146551. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146552. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146553. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146554. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146555. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146556. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146557. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146558. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146559. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146560. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146561. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146562. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146563. 19,
  146564. };
  146565. static float _vq_quantthresh__44u1__p3_0[] = {
  146566. -1.5, -0.5, 0.5, 1.5,
  146567. };
  146568. static long _vq_quantmap__44u1__p3_0[] = {
  146569. 3, 1, 0, 2, 4,
  146570. };
  146571. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146572. _vq_quantthresh__44u1__p3_0,
  146573. _vq_quantmap__44u1__p3_0,
  146574. 5,
  146575. 5
  146576. };
  146577. static static_codebook _44u1__p3_0 = {
  146578. 4, 625,
  146579. _vq_lengthlist__44u1__p3_0,
  146580. 1, -533725184, 1611661312, 3, 0,
  146581. _vq_quantlist__44u1__p3_0,
  146582. NULL,
  146583. &_vq_auxt__44u1__p3_0,
  146584. NULL,
  146585. 0
  146586. };
  146587. static long _vq_quantlist__44u1__p4_0[] = {
  146588. 2,
  146589. 1,
  146590. 3,
  146591. 0,
  146592. 4,
  146593. };
  146594. static long _vq_lengthlist__44u1__p4_0[] = {
  146595. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146596. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146597. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146598. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146599. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146600. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146601. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146602. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146603. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146604. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146605. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146606. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146607. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146608. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146609. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146610. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146611. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146612. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146613. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146614. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146615. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146616. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146617. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146618. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146619. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146620. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146621. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146622. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146623. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146624. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146625. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146626. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146627. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146628. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146629. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146630. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146631. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146632. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146633. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146634. 12,
  146635. };
  146636. static float _vq_quantthresh__44u1__p4_0[] = {
  146637. -1.5, -0.5, 0.5, 1.5,
  146638. };
  146639. static long _vq_quantmap__44u1__p4_0[] = {
  146640. 3, 1, 0, 2, 4,
  146641. };
  146642. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146643. _vq_quantthresh__44u1__p4_0,
  146644. _vq_quantmap__44u1__p4_0,
  146645. 5,
  146646. 5
  146647. };
  146648. static static_codebook _44u1__p4_0 = {
  146649. 4, 625,
  146650. _vq_lengthlist__44u1__p4_0,
  146651. 1, -533725184, 1611661312, 3, 0,
  146652. _vq_quantlist__44u1__p4_0,
  146653. NULL,
  146654. &_vq_auxt__44u1__p4_0,
  146655. NULL,
  146656. 0
  146657. };
  146658. static long _vq_quantlist__44u1__p5_0[] = {
  146659. 4,
  146660. 3,
  146661. 5,
  146662. 2,
  146663. 6,
  146664. 1,
  146665. 7,
  146666. 0,
  146667. 8,
  146668. };
  146669. static long _vq_lengthlist__44u1__p5_0[] = {
  146670. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146671. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146672. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146673. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146674. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146675. 12,
  146676. };
  146677. static float _vq_quantthresh__44u1__p5_0[] = {
  146678. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146679. };
  146680. static long _vq_quantmap__44u1__p5_0[] = {
  146681. 7, 5, 3, 1, 0, 2, 4, 6,
  146682. 8,
  146683. };
  146684. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  146685. _vq_quantthresh__44u1__p5_0,
  146686. _vq_quantmap__44u1__p5_0,
  146687. 9,
  146688. 9
  146689. };
  146690. static static_codebook _44u1__p5_0 = {
  146691. 2, 81,
  146692. _vq_lengthlist__44u1__p5_0,
  146693. 1, -531628032, 1611661312, 4, 0,
  146694. _vq_quantlist__44u1__p5_0,
  146695. NULL,
  146696. &_vq_auxt__44u1__p5_0,
  146697. NULL,
  146698. 0
  146699. };
  146700. static long _vq_quantlist__44u1__p6_0[] = {
  146701. 6,
  146702. 5,
  146703. 7,
  146704. 4,
  146705. 8,
  146706. 3,
  146707. 9,
  146708. 2,
  146709. 10,
  146710. 1,
  146711. 11,
  146712. 0,
  146713. 12,
  146714. };
  146715. static long _vq_lengthlist__44u1__p6_0[] = {
  146716. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146717. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146718. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146719. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146720. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146721. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146722. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146723. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146724. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146725. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146726. 15,17,16,17,18,17,17,18, 0,
  146727. };
  146728. static float _vq_quantthresh__44u1__p6_0[] = {
  146729. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146730. 12.5, 17.5, 22.5, 27.5,
  146731. };
  146732. static long _vq_quantmap__44u1__p6_0[] = {
  146733. 11, 9, 7, 5, 3, 1, 0, 2,
  146734. 4, 6, 8, 10, 12,
  146735. };
  146736. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  146737. _vq_quantthresh__44u1__p6_0,
  146738. _vq_quantmap__44u1__p6_0,
  146739. 13,
  146740. 13
  146741. };
  146742. static static_codebook _44u1__p6_0 = {
  146743. 2, 169,
  146744. _vq_lengthlist__44u1__p6_0,
  146745. 1, -526516224, 1616117760, 4, 0,
  146746. _vq_quantlist__44u1__p6_0,
  146747. NULL,
  146748. &_vq_auxt__44u1__p6_0,
  146749. NULL,
  146750. 0
  146751. };
  146752. static long _vq_quantlist__44u1__p6_1[] = {
  146753. 2,
  146754. 1,
  146755. 3,
  146756. 0,
  146757. 4,
  146758. };
  146759. static long _vq_lengthlist__44u1__p6_1[] = {
  146760. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146761. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146762. };
  146763. static float _vq_quantthresh__44u1__p6_1[] = {
  146764. -1.5, -0.5, 0.5, 1.5,
  146765. };
  146766. static long _vq_quantmap__44u1__p6_1[] = {
  146767. 3, 1, 0, 2, 4,
  146768. };
  146769. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  146770. _vq_quantthresh__44u1__p6_1,
  146771. _vq_quantmap__44u1__p6_1,
  146772. 5,
  146773. 5
  146774. };
  146775. static static_codebook _44u1__p6_1 = {
  146776. 2, 25,
  146777. _vq_lengthlist__44u1__p6_1,
  146778. 1, -533725184, 1611661312, 3, 0,
  146779. _vq_quantlist__44u1__p6_1,
  146780. NULL,
  146781. &_vq_auxt__44u1__p6_1,
  146782. NULL,
  146783. 0
  146784. };
  146785. static long _vq_quantlist__44u1__p7_0[] = {
  146786. 3,
  146787. 2,
  146788. 4,
  146789. 1,
  146790. 5,
  146791. 0,
  146792. 6,
  146793. };
  146794. static long _vq_lengthlist__44u1__p7_0[] = {
  146795. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146796. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146797. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146798. 8,
  146799. };
  146800. static float _vq_quantthresh__44u1__p7_0[] = {
  146801. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  146802. };
  146803. static long _vq_quantmap__44u1__p7_0[] = {
  146804. 5, 3, 1, 0, 2, 4, 6,
  146805. };
  146806. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  146807. _vq_quantthresh__44u1__p7_0,
  146808. _vq_quantmap__44u1__p7_0,
  146809. 7,
  146810. 7
  146811. };
  146812. static static_codebook _44u1__p7_0 = {
  146813. 2, 49,
  146814. _vq_lengthlist__44u1__p7_0,
  146815. 1, -518017024, 1626677248, 3, 0,
  146816. _vq_quantlist__44u1__p7_0,
  146817. NULL,
  146818. &_vq_auxt__44u1__p7_0,
  146819. NULL,
  146820. 0
  146821. };
  146822. static long _vq_quantlist__44u1__p7_1[] = {
  146823. 6,
  146824. 5,
  146825. 7,
  146826. 4,
  146827. 8,
  146828. 3,
  146829. 9,
  146830. 2,
  146831. 10,
  146832. 1,
  146833. 11,
  146834. 0,
  146835. 12,
  146836. };
  146837. static long _vq_lengthlist__44u1__p7_1[] = {
  146838. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146839. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146840. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146841. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146842. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146843. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146844. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146845. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146846. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146847. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146848. 15,15,15,15,15,15,15,15,15,
  146849. };
  146850. static float _vq_quantthresh__44u1__p7_1[] = {
  146851. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146852. 32.5, 45.5, 58.5, 71.5,
  146853. };
  146854. static long _vq_quantmap__44u1__p7_1[] = {
  146855. 11, 9, 7, 5, 3, 1, 0, 2,
  146856. 4, 6, 8, 10, 12,
  146857. };
  146858. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  146859. _vq_quantthresh__44u1__p7_1,
  146860. _vq_quantmap__44u1__p7_1,
  146861. 13,
  146862. 13
  146863. };
  146864. static static_codebook _44u1__p7_1 = {
  146865. 2, 169,
  146866. _vq_lengthlist__44u1__p7_1,
  146867. 1, -523010048, 1618608128, 4, 0,
  146868. _vq_quantlist__44u1__p7_1,
  146869. NULL,
  146870. &_vq_auxt__44u1__p7_1,
  146871. NULL,
  146872. 0
  146873. };
  146874. static long _vq_quantlist__44u1__p7_2[] = {
  146875. 6,
  146876. 5,
  146877. 7,
  146878. 4,
  146879. 8,
  146880. 3,
  146881. 9,
  146882. 2,
  146883. 10,
  146884. 1,
  146885. 11,
  146886. 0,
  146887. 12,
  146888. };
  146889. static long _vq_lengthlist__44u1__p7_2[] = {
  146890. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146891. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146892. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146893. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146894. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146895. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146896. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146897. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146898. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146899. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146900. 9, 9, 9,10, 9, 9,10,10, 9,
  146901. };
  146902. static float _vq_quantthresh__44u1__p7_2[] = {
  146903. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146904. 2.5, 3.5, 4.5, 5.5,
  146905. };
  146906. static long _vq_quantmap__44u1__p7_2[] = {
  146907. 11, 9, 7, 5, 3, 1, 0, 2,
  146908. 4, 6, 8, 10, 12,
  146909. };
  146910. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  146911. _vq_quantthresh__44u1__p7_2,
  146912. _vq_quantmap__44u1__p7_2,
  146913. 13,
  146914. 13
  146915. };
  146916. static static_codebook _44u1__p7_2 = {
  146917. 2, 169,
  146918. _vq_lengthlist__44u1__p7_2,
  146919. 1, -531103744, 1611661312, 4, 0,
  146920. _vq_quantlist__44u1__p7_2,
  146921. NULL,
  146922. &_vq_auxt__44u1__p7_2,
  146923. NULL,
  146924. 0
  146925. };
  146926. static long _huff_lengthlist__44u1__short[] = {
  146927. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146928. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146929. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146930. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146931. };
  146932. static static_codebook _huff_book__44u1__short = {
  146933. 2, 64,
  146934. _huff_lengthlist__44u1__short,
  146935. 0, 0, 0, 0, 0,
  146936. NULL,
  146937. NULL,
  146938. NULL,
  146939. NULL,
  146940. 0
  146941. };
  146942. static long _huff_lengthlist__44u2__long[] = {
  146943. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  146944. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  146945. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  146946. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  146947. };
  146948. static static_codebook _huff_book__44u2__long = {
  146949. 2, 64,
  146950. _huff_lengthlist__44u2__long,
  146951. 0, 0, 0, 0, 0,
  146952. NULL,
  146953. NULL,
  146954. NULL,
  146955. NULL,
  146956. 0
  146957. };
  146958. static long _vq_quantlist__44u2__p1_0[] = {
  146959. 1,
  146960. 0,
  146961. 2,
  146962. };
  146963. static long _vq_lengthlist__44u2__p1_0[] = {
  146964. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146965. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146966. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  146967. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  146968. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  146969. 13,
  146970. };
  146971. static float _vq_quantthresh__44u2__p1_0[] = {
  146972. -0.5, 0.5,
  146973. };
  146974. static long _vq_quantmap__44u2__p1_0[] = {
  146975. 1, 0, 2,
  146976. };
  146977. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  146978. _vq_quantthresh__44u2__p1_0,
  146979. _vq_quantmap__44u2__p1_0,
  146980. 3,
  146981. 3
  146982. };
  146983. static static_codebook _44u2__p1_0 = {
  146984. 4, 81,
  146985. _vq_lengthlist__44u2__p1_0,
  146986. 1, -535822336, 1611661312, 2, 0,
  146987. _vq_quantlist__44u2__p1_0,
  146988. NULL,
  146989. &_vq_auxt__44u2__p1_0,
  146990. NULL,
  146991. 0
  146992. };
  146993. static long _vq_quantlist__44u2__p2_0[] = {
  146994. 1,
  146995. 0,
  146996. 2,
  146997. };
  146998. static long _vq_lengthlist__44u2__p2_0[] = {
  146999. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147000. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147001. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147002. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147003. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147004. 9,
  147005. };
  147006. static float _vq_quantthresh__44u2__p2_0[] = {
  147007. -0.5, 0.5,
  147008. };
  147009. static long _vq_quantmap__44u2__p2_0[] = {
  147010. 1, 0, 2,
  147011. };
  147012. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147013. _vq_quantthresh__44u2__p2_0,
  147014. _vq_quantmap__44u2__p2_0,
  147015. 3,
  147016. 3
  147017. };
  147018. static static_codebook _44u2__p2_0 = {
  147019. 4, 81,
  147020. _vq_lengthlist__44u2__p2_0,
  147021. 1, -535822336, 1611661312, 2, 0,
  147022. _vq_quantlist__44u2__p2_0,
  147023. NULL,
  147024. &_vq_auxt__44u2__p2_0,
  147025. NULL,
  147026. 0
  147027. };
  147028. static long _vq_quantlist__44u2__p3_0[] = {
  147029. 2,
  147030. 1,
  147031. 3,
  147032. 0,
  147033. 4,
  147034. };
  147035. static long _vq_lengthlist__44u2__p3_0[] = {
  147036. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147037. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147038. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147039. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147040. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147041. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147042. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147043. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147044. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147045. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147046. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147047. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147048. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147049. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147050. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147051. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147052. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147053. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147054. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147055. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147056. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147057. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147058. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147059. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147060. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147061. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147062. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147063. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147064. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147065. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147066. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147067. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147068. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147069. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147070. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147071. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147072. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147073. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147074. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147075. 0,
  147076. };
  147077. static float _vq_quantthresh__44u2__p3_0[] = {
  147078. -1.5, -0.5, 0.5, 1.5,
  147079. };
  147080. static long _vq_quantmap__44u2__p3_0[] = {
  147081. 3, 1, 0, 2, 4,
  147082. };
  147083. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147084. _vq_quantthresh__44u2__p3_0,
  147085. _vq_quantmap__44u2__p3_0,
  147086. 5,
  147087. 5
  147088. };
  147089. static static_codebook _44u2__p3_0 = {
  147090. 4, 625,
  147091. _vq_lengthlist__44u2__p3_0,
  147092. 1, -533725184, 1611661312, 3, 0,
  147093. _vq_quantlist__44u2__p3_0,
  147094. NULL,
  147095. &_vq_auxt__44u2__p3_0,
  147096. NULL,
  147097. 0
  147098. };
  147099. static long _vq_quantlist__44u2__p4_0[] = {
  147100. 2,
  147101. 1,
  147102. 3,
  147103. 0,
  147104. 4,
  147105. };
  147106. static long _vq_lengthlist__44u2__p4_0[] = {
  147107. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147108. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147109. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147110. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147111. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147112. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147113. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147114. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147115. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147116. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147117. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147118. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147119. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147120. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147121. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147122. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147123. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147124. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147125. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147126. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147127. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147128. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147129. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147130. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147131. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147132. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147133. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147134. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147135. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147136. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147137. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147138. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147139. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147140. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147141. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147142. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147143. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147144. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147145. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147146. 13,
  147147. };
  147148. static float _vq_quantthresh__44u2__p4_0[] = {
  147149. -1.5, -0.5, 0.5, 1.5,
  147150. };
  147151. static long _vq_quantmap__44u2__p4_0[] = {
  147152. 3, 1, 0, 2, 4,
  147153. };
  147154. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147155. _vq_quantthresh__44u2__p4_0,
  147156. _vq_quantmap__44u2__p4_0,
  147157. 5,
  147158. 5
  147159. };
  147160. static static_codebook _44u2__p4_0 = {
  147161. 4, 625,
  147162. _vq_lengthlist__44u2__p4_0,
  147163. 1, -533725184, 1611661312, 3, 0,
  147164. _vq_quantlist__44u2__p4_0,
  147165. NULL,
  147166. &_vq_auxt__44u2__p4_0,
  147167. NULL,
  147168. 0
  147169. };
  147170. static long _vq_quantlist__44u2__p5_0[] = {
  147171. 4,
  147172. 3,
  147173. 5,
  147174. 2,
  147175. 6,
  147176. 1,
  147177. 7,
  147178. 0,
  147179. 8,
  147180. };
  147181. static long _vq_lengthlist__44u2__p5_0[] = {
  147182. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147183. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147184. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147185. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147186. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147187. 13,
  147188. };
  147189. static float _vq_quantthresh__44u2__p5_0[] = {
  147190. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147191. };
  147192. static long _vq_quantmap__44u2__p5_0[] = {
  147193. 7, 5, 3, 1, 0, 2, 4, 6,
  147194. 8,
  147195. };
  147196. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147197. _vq_quantthresh__44u2__p5_0,
  147198. _vq_quantmap__44u2__p5_0,
  147199. 9,
  147200. 9
  147201. };
  147202. static static_codebook _44u2__p5_0 = {
  147203. 2, 81,
  147204. _vq_lengthlist__44u2__p5_0,
  147205. 1, -531628032, 1611661312, 4, 0,
  147206. _vq_quantlist__44u2__p5_0,
  147207. NULL,
  147208. &_vq_auxt__44u2__p5_0,
  147209. NULL,
  147210. 0
  147211. };
  147212. static long _vq_quantlist__44u2__p6_0[] = {
  147213. 6,
  147214. 5,
  147215. 7,
  147216. 4,
  147217. 8,
  147218. 3,
  147219. 9,
  147220. 2,
  147221. 10,
  147222. 1,
  147223. 11,
  147224. 0,
  147225. 12,
  147226. };
  147227. static long _vq_lengthlist__44u2__p6_0[] = {
  147228. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147229. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147230. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147231. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147232. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147233. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147234. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147235. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147236. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147237. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147238. 15,17,17,16,18,17,18, 0, 0,
  147239. };
  147240. static float _vq_quantthresh__44u2__p6_0[] = {
  147241. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147242. 12.5, 17.5, 22.5, 27.5,
  147243. };
  147244. static long _vq_quantmap__44u2__p6_0[] = {
  147245. 11, 9, 7, 5, 3, 1, 0, 2,
  147246. 4, 6, 8, 10, 12,
  147247. };
  147248. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147249. _vq_quantthresh__44u2__p6_0,
  147250. _vq_quantmap__44u2__p6_0,
  147251. 13,
  147252. 13
  147253. };
  147254. static static_codebook _44u2__p6_0 = {
  147255. 2, 169,
  147256. _vq_lengthlist__44u2__p6_0,
  147257. 1, -526516224, 1616117760, 4, 0,
  147258. _vq_quantlist__44u2__p6_0,
  147259. NULL,
  147260. &_vq_auxt__44u2__p6_0,
  147261. NULL,
  147262. 0
  147263. };
  147264. static long _vq_quantlist__44u2__p6_1[] = {
  147265. 2,
  147266. 1,
  147267. 3,
  147268. 0,
  147269. 4,
  147270. };
  147271. static long _vq_lengthlist__44u2__p6_1[] = {
  147272. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147273. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147274. };
  147275. static float _vq_quantthresh__44u2__p6_1[] = {
  147276. -1.5, -0.5, 0.5, 1.5,
  147277. };
  147278. static long _vq_quantmap__44u2__p6_1[] = {
  147279. 3, 1, 0, 2, 4,
  147280. };
  147281. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147282. _vq_quantthresh__44u2__p6_1,
  147283. _vq_quantmap__44u2__p6_1,
  147284. 5,
  147285. 5
  147286. };
  147287. static static_codebook _44u2__p6_1 = {
  147288. 2, 25,
  147289. _vq_lengthlist__44u2__p6_1,
  147290. 1, -533725184, 1611661312, 3, 0,
  147291. _vq_quantlist__44u2__p6_1,
  147292. NULL,
  147293. &_vq_auxt__44u2__p6_1,
  147294. NULL,
  147295. 0
  147296. };
  147297. static long _vq_quantlist__44u2__p7_0[] = {
  147298. 4,
  147299. 3,
  147300. 5,
  147301. 2,
  147302. 6,
  147303. 1,
  147304. 7,
  147305. 0,
  147306. 8,
  147307. };
  147308. static long _vq_lengthlist__44u2__p7_0[] = {
  147309. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147310. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147314. 11,
  147315. };
  147316. static float _vq_quantthresh__44u2__p7_0[] = {
  147317. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147318. };
  147319. static long _vq_quantmap__44u2__p7_0[] = {
  147320. 7, 5, 3, 1, 0, 2, 4, 6,
  147321. 8,
  147322. };
  147323. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147324. _vq_quantthresh__44u2__p7_0,
  147325. _vq_quantmap__44u2__p7_0,
  147326. 9,
  147327. 9
  147328. };
  147329. static static_codebook _44u2__p7_0 = {
  147330. 2, 81,
  147331. _vq_lengthlist__44u2__p7_0,
  147332. 1, -516612096, 1626677248, 4, 0,
  147333. _vq_quantlist__44u2__p7_0,
  147334. NULL,
  147335. &_vq_auxt__44u2__p7_0,
  147336. NULL,
  147337. 0
  147338. };
  147339. static long _vq_quantlist__44u2__p7_1[] = {
  147340. 6,
  147341. 5,
  147342. 7,
  147343. 4,
  147344. 8,
  147345. 3,
  147346. 9,
  147347. 2,
  147348. 10,
  147349. 1,
  147350. 11,
  147351. 0,
  147352. 12,
  147353. };
  147354. static long _vq_lengthlist__44u2__p7_1[] = {
  147355. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147356. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147357. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147358. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147359. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147360. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147361. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147362. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147363. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147364. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147365. 14,14,14,17,15,17,17,17,17,
  147366. };
  147367. static float _vq_quantthresh__44u2__p7_1[] = {
  147368. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147369. 32.5, 45.5, 58.5, 71.5,
  147370. };
  147371. static long _vq_quantmap__44u2__p7_1[] = {
  147372. 11, 9, 7, 5, 3, 1, 0, 2,
  147373. 4, 6, 8, 10, 12,
  147374. };
  147375. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147376. _vq_quantthresh__44u2__p7_1,
  147377. _vq_quantmap__44u2__p7_1,
  147378. 13,
  147379. 13
  147380. };
  147381. static static_codebook _44u2__p7_1 = {
  147382. 2, 169,
  147383. _vq_lengthlist__44u2__p7_1,
  147384. 1, -523010048, 1618608128, 4, 0,
  147385. _vq_quantlist__44u2__p7_1,
  147386. NULL,
  147387. &_vq_auxt__44u2__p7_1,
  147388. NULL,
  147389. 0
  147390. };
  147391. static long _vq_quantlist__44u2__p7_2[] = {
  147392. 6,
  147393. 5,
  147394. 7,
  147395. 4,
  147396. 8,
  147397. 3,
  147398. 9,
  147399. 2,
  147400. 10,
  147401. 1,
  147402. 11,
  147403. 0,
  147404. 12,
  147405. };
  147406. static long _vq_lengthlist__44u2__p7_2[] = {
  147407. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147408. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147409. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147410. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147411. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147412. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147413. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147414. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147415. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147416. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147417. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147418. };
  147419. static float _vq_quantthresh__44u2__p7_2[] = {
  147420. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147421. 2.5, 3.5, 4.5, 5.5,
  147422. };
  147423. static long _vq_quantmap__44u2__p7_2[] = {
  147424. 11, 9, 7, 5, 3, 1, 0, 2,
  147425. 4, 6, 8, 10, 12,
  147426. };
  147427. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147428. _vq_quantthresh__44u2__p7_2,
  147429. _vq_quantmap__44u2__p7_2,
  147430. 13,
  147431. 13
  147432. };
  147433. static static_codebook _44u2__p7_2 = {
  147434. 2, 169,
  147435. _vq_lengthlist__44u2__p7_2,
  147436. 1, -531103744, 1611661312, 4, 0,
  147437. _vq_quantlist__44u2__p7_2,
  147438. NULL,
  147439. &_vq_auxt__44u2__p7_2,
  147440. NULL,
  147441. 0
  147442. };
  147443. static long _huff_lengthlist__44u2__short[] = {
  147444. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147445. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147446. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147447. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147448. };
  147449. static static_codebook _huff_book__44u2__short = {
  147450. 2, 64,
  147451. _huff_lengthlist__44u2__short,
  147452. 0, 0, 0, 0, 0,
  147453. NULL,
  147454. NULL,
  147455. NULL,
  147456. NULL,
  147457. 0
  147458. };
  147459. static long _huff_lengthlist__44u3__long[] = {
  147460. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147461. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147462. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147463. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147464. };
  147465. static static_codebook _huff_book__44u3__long = {
  147466. 2, 64,
  147467. _huff_lengthlist__44u3__long,
  147468. 0, 0, 0, 0, 0,
  147469. NULL,
  147470. NULL,
  147471. NULL,
  147472. NULL,
  147473. 0
  147474. };
  147475. static long _vq_quantlist__44u3__p1_0[] = {
  147476. 1,
  147477. 0,
  147478. 2,
  147479. };
  147480. static long _vq_lengthlist__44u3__p1_0[] = {
  147481. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147482. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147483. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147484. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147485. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147486. 13,
  147487. };
  147488. static float _vq_quantthresh__44u3__p1_0[] = {
  147489. -0.5, 0.5,
  147490. };
  147491. static long _vq_quantmap__44u3__p1_0[] = {
  147492. 1, 0, 2,
  147493. };
  147494. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147495. _vq_quantthresh__44u3__p1_0,
  147496. _vq_quantmap__44u3__p1_0,
  147497. 3,
  147498. 3
  147499. };
  147500. static static_codebook _44u3__p1_0 = {
  147501. 4, 81,
  147502. _vq_lengthlist__44u3__p1_0,
  147503. 1, -535822336, 1611661312, 2, 0,
  147504. _vq_quantlist__44u3__p1_0,
  147505. NULL,
  147506. &_vq_auxt__44u3__p1_0,
  147507. NULL,
  147508. 0
  147509. };
  147510. static long _vq_quantlist__44u3__p2_0[] = {
  147511. 1,
  147512. 0,
  147513. 2,
  147514. };
  147515. static long _vq_lengthlist__44u3__p2_0[] = {
  147516. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147517. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147518. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147519. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147520. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147521. 9,
  147522. };
  147523. static float _vq_quantthresh__44u3__p2_0[] = {
  147524. -0.5, 0.5,
  147525. };
  147526. static long _vq_quantmap__44u3__p2_0[] = {
  147527. 1, 0, 2,
  147528. };
  147529. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147530. _vq_quantthresh__44u3__p2_0,
  147531. _vq_quantmap__44u3__p2_0,
  147532. 3,
  147533. 3
  147534. };
  147535. static static_codebook _44u3__p2_0 = {
  147536. 4, 81,
  147537. _vq_lengthlist__44u3__p2_0,
  147538. 1, -535822336, 1611661312, 2, 0,
  147539. _vq_quantlist__44u3__p2_0,
  147540. NULL,
  147541. &_vq_auxt__44u3__p2_0,
  147542. NULL,
  147543. 0
  147544. };
  147545. static long _vq_quantlist__44u3__p3_0[] = {
  147546. 2,
  147547. 1,
  147548. 3,
  147549. 0,
  147550. 4,
  147551. };
  147552. static long _vq_lengthlist__44u3__p3_0[] = {
  147553. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147554. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147555. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147556. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147557. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147558. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147559. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147560. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147561. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147562. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147563. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147564. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147565. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147566. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147567. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147568. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147569. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147570. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147571. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147572. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147573. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147574. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147575. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147576. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147577. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147578. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147579. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147580. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147581. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147582. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147583. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147584. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147585. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147586. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147587. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147588. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147589. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147590. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147591. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147592. 0,
  147593. };
  147594. static float _vq_quantthresh__44u3__p3_0[] = {
  147595. -1.5, -0.5, 0.5, 1.5,
  147596. };
  147597. static long _vq_quantmap__44u3__p3_0[] = {
  147598. 3, 1, 0, 2, 4,
  147599. };
  147600. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147601. _vq_quantthresh__44u3__p3_0,
  147602. _vq_quantmap__44u3__p3_0,
  147603. 5,
  147604. 5
  147605. };
  147606. static static_codebook _44u3__p3_0 = {
  147607. 4, 625,
  147608. _vq_lengthlist__44u3__p3_0,
  147609. 1, -533725184, 1611661312, 3, 0,
  147610. _vq_quantlist__44u3__p3_0,
  147611. NULL,
  147612. &_vq_auxt__44u3__p3_0,
  147613. NULL,
  147614. 0
  147615. };
  147616. static long _vq_quantlist__44u3__p4_0[] = {
  147617. 2,
  147618. 1,
  147619. 3,
  147620. 0,
  147621. 4,
  147622. };
  147623. static long _vq_lengthlist__44u3__p4_0[] = {
  147624. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147625. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147626. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147627. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147628. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147629. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147630. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147631. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147632. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147633. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147634. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147635. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147636. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147637. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147638. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147639. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147640. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147641. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147642. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147643. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147644. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147645. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147646. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147647. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147648. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147649. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147650. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147651. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147652. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147653. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147654. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147655. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147656. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147657. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147658. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147659. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  147660. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  147661. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  147662. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  147663. 13,
  147664. };
  147665. static float _vq_quantthresh__44u3__p4_0[] = {
  147666. -1.5, -0.5, 0.5, 1.5,
  147667. };
  147668. static long _vq_quantmap__44u3__p4_0[] = {
  147669. 3, 1, 0, 2, 4,
  147670. };
  147671. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  147672. _vq_quantthresh__44u3__p4_0,
  147673. _vq_quantmap__44u3__p4_0,
  147674. 5,
  147675. 5
  147676. };
  147677. static static_codebook _44u3__p4_0 = {
  147678. 4, 625,
  147679. _vq_lengthlist__44u3__p4_0,
  147680. 1, -533725184, 1611661312, 3, 0,
  147681. _vq_quantlist__44u3__p4_0,
  147682. NULL,
  147683. &_vq_auxt__44u3__p4_0,
  147684. NULL,
  147685. 0
  147686. };
  147687. static long _vq_quantlist__44u3__p5_0[] = {
  147688. 4,
  147689. 3,
  147690. 5,
  147691. 2,
  147692. 6,
  147693. 1,
  147694. 7,
  147695. 0,
  147696. 8,
  147697. };
  147698. static long _vq_lengthlist__44u3__p5_0[] = {
  147699. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  147700. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  147701. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  147702. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147703. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  147704. 12,
  147705. };
  147706. static float _vq_quantthresh__44u3__p5_0[] = {
  147707. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147708. };
  147709. static long _vq_quantmap__44u3__p5_0[] = {
  147710. 7, 5, 3, 1, 0, 2, 4, 6,
  147711. 8,
  147712. };
  147713. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  147714. _vq_quantthresh__44u3__p5_0,
  147715. _vq_quantmap__44u3__p5_0,
  147716. 9,
  147717. 9
  147718. };
  147719. static static_codebook _44u3__p5_0 = {
  147720. 2, 81,
  147721. _vq_lengthlist__44u3__p5_0,
  147722. 1, -531628032, 1611661312, 4, 0,
  147723. _vq_quantlist__44u3__p5_0,
  147724. NULL,
  147725. &_vq_auxt__44u3__p5_0,
  147726. NULL,
  147727. 0
  147728. };
  147729. static long _vq_quantlist__44u3__p6_0[] = {
  147730. 6,
  147731. 5,
  147732. 7,
  147733. 4,
  147734. 8,
  147735. 3,
  147736. 9,
  147737. 2,
  147738. 10,
  147739. 1,
  147740. 11,
  147741. 0,
  147742. 12,
  147743. };
  147744. static long _vq_lengthlist__44u3__p6_0[] = {
  147745. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  147746. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  147747. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147748. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  147749. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  147750. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  147751. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  147752. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  147753. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  147754. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  147755. 15,16,16,16,17,18,16,20,18,
  147756. };
  147757. static float _vq_quantthresh__44u3__p6_0[] = {
  147758. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147759. 12.5, 17.5, 22.5, 27.5,
  147760. };
  147761. static long _vq_quantmap__44u3__p6_0[] = {
  147762. 11, 9, 7, 5, 3, 1, 0, 2,
  147763. 4, 6, 8, 10, 12,
  147764. };
  147765. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  147766. _vq_quantthresh__44u3__p6_0,
  147767. _vq_quantmap__44u3__p6_0,
  147768. 13,
  147769. 13
  147770. };
  147771. static static_codebook _44u3__p6_0 = {
  147772. 2, 169,
  147773. _vq_lengthlist__44u3__p6_0,
  147774. 1, -526516224, 1616117760, 4, 0,
  147775. _vq_quantlist__44u3__p6_0,
  147776. NULL,
  147777. &_vq_auxt__44u3__p6_0,
  147778. NULL,
  147779. 0
  147780. };
  147781. static long _vq_quantlist__44u3__p6_1[] = {
  147782. 2,
  147783. 1,
  147784. 3,
  147785. 0,
  147786. 4,
  147787. };
  147788. static long _vq_lengthlist__44u3__p6_1[] = {
  147789. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147790. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147791. };
  147792. static float _vq_quantthresh__44u3__p6_1[] = {
  147793. -1.5, -0.5, 0.5, 1.5,
  147794. };
  147795. static long _vq_quantmap__44u3__p6_1[] = {
  147796. 3, 1, 0, 2, 4,
  147797. };
  147798. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  147799. _vq_quantthresh__44u3__p6_1,
  147800. _vq_quantmap__44u3__p6_1,
  147801. 5,
  147802. 5
  147803. };
  147804. static static_codebook _44u3__p6_1 = {
  147805. 2, 25,
  147806. _vq_lengthlist__44u3__p6_1,
  147807. 1, -533725184, 1611661312, 3, 0,
  147808. _vq_quantlist__44u3__p6_1,
  147809. NULL,
  147810. &_vq_auxt__44u3__p6_1,
  147811. NULL,
  147812. 0
  147813. };
  147814. static long _vq_quantlist__44u3__p7_0[] = {
  147815. 4,
  147816. 3,
  147817. 5,
  147818. 2,
  147819. 6,
  147820. 1,
  147821. 7,
  147822. 0,
  147823. 8,
  147824. };
  147825. static long _vq_lengthlist__44u3__p7_0[] = {
  147826. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  147827. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147828. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147829. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147830. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147831. 9,
  147832. };
  147833. static float _vq_quantthresh__44u3__p7_0[] = {
  147834. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  147835. };
  147836. static long _vq_quantmap__44u3__p7_0[] = {
  147837. 7, 5, 3, 1, 0, 2, 4, 6,
  147838. 8,
  147839. };
  147840. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  147841. _vq_quantthresh__44u3__p7_0,
  147842. _vq_quantmap__44u3__p7_0,
  147843. 9,
  147844. 9
  147845. };
  147846. static static_codebook _44u3__p7_0 = {
  147847. 2, 81,
  147848. _vq_lengthlist__44u3__p7_0,
  147849. 1, -515907584, 1627381760, 4, 0,
  147850. _vq_quantlist__44u3__p7_0,
  147851. NULL,
  147852. &_vq_auxt__44u3__p7_0,
  147853. NULL,
  147854. 0
  147855. };
  147856. static long _vq_quantlist__44u3__p7_1[] = {
  147857. 7,
  147858. 6,
  147859. 8,
  147860. 5,
  147861. 9,
  147862. 4,
  147863. 10,
  147864. 3,
  147865. 11,
  147866. 2,
  147867. 12,
  147868. 1,
  147869. 13,
  147870. 0,
  147871. 14,
  147872. };
  147873. static long _vq_lengthlist__44u3__p7_1[] = {
  147874. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  147875. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  147876. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  147877. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  147878. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  147879. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  147880. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  147881. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  147882. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  147883. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  147884. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  147885. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  147886. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  147887. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  147888. 17,
  147889. };
  147890. static float _vq_quantthresh__44u3__p7_1[] = {
  147891. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  147892. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  147893. };
  147894. static long _vq_quantmap__44u3__p7_1[] = {
  147895. 13, 11, 9, 7, 5, 3, 1, 0,
  147896. 2, 4, 6, 8, 10, 12, 14,
  147897. };
  147898. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  147899. _vq_quantthresh__44u3__p7_1,
  147900. _vq_quantmap__44u3__p7_1,
  147901. 15,
  147902. 15
  147903. };
  147904. static static_codebook _44u3__p7_1 = {
  147905. 2, 225,
  147906. _vq_lengthlist__44u3__p7_1,
  147907. 1, -522338304, 1620115456, 4, 0,
  147908. _vq_quantlist__44u3__p7_1,
  147909. NULL,
  147910. &_vq_auxt__44u3__p7_1,
  147911. NULL,
  147912. 0
  147913. };
  147914. static long _vq_quantlist__44u3__p7_2[] = {
  147915. 8,
  147916. 7,
  147917. 9,
  147918. 6,
  147919. 10,
  147920. 5,
  147921. 11,
  147922. 4,
  147923. 12,
  147924. 3,
  147925. 13,
  147926. 2,
  147927. 14,
  147928. 1,
  147929. 15,
  147930. 0,
  147931. 16,
  147932. };
  147933. static long _vq_lengthlist__44u3__p7_2[] = {
  147934. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147935. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147936. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  147937. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147938. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  147939. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147940. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  147941. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  147942. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  147943. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  147944. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147945. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  147946. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  147947. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  147948. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  147949. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  147950. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147951. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  147952. 11,
  147953. };
  147954. static float _vq_quantthresh__44u3__p7_2[] = {
  147955. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147956. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147957. };
  147958. static long _vq_quantmap__44u3__p7_2[] = {
  147959. 15, 13, 11, 9, 7, 5, 3, 1,
  147960. 0, 2, 4, 6, 8, 10, 12, 14,
  147961. 16,
  147962. };
  147963. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  147964. _vq_quantthresh__44u3__p7_2,
  147965. _vq_quantmap__44u3__p7_2,
  147966. 17,
  147967. 17
  147968. };
  147969. static static_codebook _44u3__p7_2 = {
  147970. 2, 289,
  147971. _vq_lengthlist__44u3__p7_2,
  147972. 1, -529530880, 1611661312, 5, 0,
  147973. _vq_quantlist__44u3__p7_2,
  147974. NULL,
  147975. &_vq_auxt__44u3__p7_2,
  147976. NULL,
  147977. 0
  147978. };
  147979. static long _huff_lengthlist__44u3__short[] = {
  147980. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  147981. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  147982. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  147983. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  147984. };
  147985. static static_codebook _huff_book__44u3__short = {
  147986. 2, 64,
  147987. _huff_lengthlist__44u3__short,
  147988. 0, 0, 0, 0, 0,
  147989. NULL,
  147990. NULL,
  147991. NULL,
  147992. NULL,
  147993. 0
  147994. };
  147995. static long _huff_lengthlist__44u4__long[] = {
  147996. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  147997. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  147998. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  147999. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148000. };
  148001. static static_codebook _huff_book__44u4__long = {
  148002. 2, 64,
  148003. _huff_lengthlist__44u4__long,
  148004. 0, 0, 0, 0, 0,
  148005. NULL,
  148006. NULL,
  148007. NULL,
  148008. NULL,
  148009. 0
  148010. };
  148011. static long _vq_quantlist__44u4__p1_0[] = {
  148012. 1,
  148013. 0,
  148014. 2,
  148015. };
  148016. static long _vq_lengthlist__44u4__p1_0[] = {
  148017. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148018. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148019. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148020. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148021. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148022. 13,
  148023. };
  148024. static float _vq_quantthresh__44u4__p1_0[] = {
  148025. -0.5, 0.5,
  148026. };
  148027. static long _vq_quantmap__44u4__p1_0[] = {
  148028. 1, 0, 2,
  148029. };
  148030. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148031. _vq_quantthresh__44u4__p1_0,
  148032. _vq_quantmap__44u4__p1_0,
  148033. 3,
  148034. 3
  148035. };
  148036. static static_codebook _44u4__p1_0 = {
  148037. 4, 81,
  148038. _vq_lengthlist__44u4__p1_0,
  148039. 1, -535822336, 1611661312, 2, 0,
  148040. _vq_quantlist__44u4__p1_0,
  148041. NULL,
  148042. &_vq_auxt__44u4__p1_0,
  148043. NULL,
  148044. 0
  148045. };
  148046. static long _vq_quantlist__44u4__p2_0[] = {
  148047. 1,
  148048. 0,
  148049. 2,
  148050. };
  148051. static long _vq_lengthlist__44u4__p2_0[] = {
  148052. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148053. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148054. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148055. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148056. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148057. 9,
  148058. };
  148059. static float _vq_quantthresh__44u4__p2_0[] = {
  148060. -0.5, 0.5,
  148061. };
  148062. static long _vq_quantmap__44u4__p2_0[] = {
  148063. 1, 0, 2,
  148064. };
  148065. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148066. _vq_quantthresh__44u4__p2_0,
  148067. _vq_quantmap__44u4__p2_0,
  148068. 3,
  148069. 3
  148070. };
  148071. static static_codebook _44u4__p2_0 = {
  148072. 4, 81,
  148073. _vq_lengthlist__44u4__p2_0,
  148074. 1, -535822336, 1611661312, 2, 0,
  148075. _vq_quantlist__44u4__p2_0,
  148076. NULL,
  148077. &_vq_auxt__44u4__p2_0,
  148078. NULL,
  148079. 0
  148080. };
  148081. static long _vq_quantlist__44u4__p3_0[] = {
  148082. 2,
  148083. 1,
  148084. 3,
  148085. 0,
  148086. 4,
  148087. };
  148088. static long _vq_lengthlist__44u4__p3_0[] = {
  148089. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148090. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148091. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148092. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148093. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148094. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148095. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148096. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148097. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148098. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148099. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148100. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148101. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148102. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148103. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148104. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148105. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148106. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148107. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148108. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148109. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148110. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148111. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148112. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148113. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148114. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148115. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148116. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148117. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148118. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148119. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148120. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148121. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148122. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148123. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148124. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148125. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148126. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148127. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148128. 0,
  148129. };
  148130. static float _vq_quantthresh__44u4__p3_0[] = {
  148131. -1.5, -0.5, 0.5, 1.5,
  148132. };
  148133. static long _vq_quantmap__44u4__p3_0[] = {
  148134. 3, 1, 0, 2, 4,
  148135. };
  148136. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148137. _vq_quantthresh__44u4__p3_0,
  148138. _vq_quantmap__44u4__p3_0,
  148139. 5,
  148140. 5
  148141. };
  148142. static static_codebook _44u4__p3_0 = {
  148143. 4, 625,
  148144. _vq_lengthlist__44u4__p3_0,
  148145. 1, -533725184, 1611661312, 3, 0,
  148146. _vq_quantlist__44u4__p3_0,
  148147. NULL,
  148148. &_vq_auxt__44u4__p3_0,
  148149. NULL,
  148150. 0
  148151. };
  148152. static long _vq_quantlist__44u4__p4_0[] = {
  148153. 2,
  148154. 1,
  148155. 3,
  148156. 0,
  148157. 4,
  148158. };
  148159. static long _vq_lengthlist__44u4__p4_0[] = {
  148160. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148161. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148162. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148163. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148164. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148165. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148166. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148167. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148168. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148169. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148170. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148171. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148172. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148173. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148174. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148175. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148176. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148177. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148178. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148179. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148180. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148181. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148182. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148183. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148184. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148185. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148186. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148187. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148188. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148189. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148190. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148191. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148192. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148193. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148194. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148195. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148196. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148197. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148198. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148199. 13,
  148200. };
  148201. static float _vq_quantthresh__44u4__p4_0[] = {
  148202. -1.5, -0.5, 0.5, 1.5,
  148203. };
  148204. static long _vq_quantmap__44u4__p4_0[] = {
  148205. 3, 1, 0, 2, 4,
  148206. };
  148207. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148208. _vq_quantthresh__44u4__p4_0,
  148209. _vq_quantmap__44u4__p4_0,
  148210. 5,
  148211. 5
  148212. };
  148213. static static_codebook _44u4__p4_0 = {
  148214. 4, 625,
  148215. _vq_lengthlist__44u4__p4_0,
  148216. 1, -533725184, 1611661312, 3, 0,
  148217. _vq_quantlist__44u4__p4_0,
  148218. NULL,
  148219. &_vq_auxt__44u4__p4_0,
  148220. NULL,
  148221. 0
  148222. };
  148223. static long _vq_quantlist__44u4__p5_0[] = {
  148224. 4,
  148225. 3,
  148226. 5,
  148227. 2,
  148228. 6,
  148229. 1,
  148230. 7,
  148231. 0,
  148232. 8,
  148233. };
  148234. static long _vq_lengthlist__44u4__p5_0[] = {
  148235. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148236. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148237. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148238. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148239. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148240. 12,
  148241. };
  148242. static float _vq_quantthresh__44u4__p5_0[] = {
  148243. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148244. };
  148245. static long _vq_quantmap__44u4__p5_0[] = {
  148246. 7, 5, 3, 1, 0, 2, 4, 6,
  148247. 8,
  148248. };
  148249. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148250. _vq_quantthresh__44u4__p5_0,
  148251. _vq_quantmap__44u4__p5_0,
  148252. 9,
  148253. 9
  148254. };
  148255. static static_codebook _44u4__p5_0 = {
  148256. 2, 81,
  148257. _vq_lengthlist__44u4__p5_0,
  148258. 1, -531628032, 1611661312, 4, 0,
  148259. _vq_quantlist__44u4__p5_0,
  148260. NULL,
  148261. &_vq_auxt__44u4__p5_0,
  148262. NULL,
  148263. 0
  148264. };
  148265. static long _vq_quantlist__44u4__p6_0[] = {
  148266. 6,
  148267. 5,
  148268. 7,
  148269. 4,
  148270. 8,
  148271. 3,
  148272. 9,
  148273. 2,
  148274. 10,
  148275. 1,
  148276. 11,
  148277. 0,
  148278. 12,
  148279. };
  148280. static long _vq_lengthlist__44u4__p6_0[] = {
  148281. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148282. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148283. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148284. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148285. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148286. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148287. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148288. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148289. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148290. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148291. 16,16,16,17,17,18,17,20,21,
  148292. };
  148293. static float _vq_quantthresh__44u4__p6_0[] = {
  148294. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148295. 12.5, 17.5, 22.5, 27.5,
  148296. };
  148297. static long _vq_quantmap__44u4__p6_0[] = {
  148298. 11, 9, 7, 5, 3, 1, 0, 2,
  148299. 4, 6, 8, 10, 12,
  148300. };
  148301. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148302. _vq_quantthresh__44u4__p6_0,
  148303. _vq_quantmap__44u4__p6_0,
  148304. 13,
  148305. 13
  148306. };
  148307. static static_codebook _44u4__p6_0 = {
  148308. 2, 169,
  148309. _vq_lengthlist__44u4__p6_0,
  148310. 1, -526516224, 1616117760, 4, 0,
  148311. _vq_quantlist__44u4__p6_0,
  148312. NULL,
  148313. &_vq_auxt__44u4__p6_0,
  148314. NULL,
  148315. 0
  148316. };
  148317. static long _vq_quantlist__44u4__p6_1[] = {
  148318. 2,
  148319. 1,
  148320. 3,
  148321. 0,
  148322. 4,
  148323. };
  148324. static long _vq_lengthlist__44u4__p6_1[] = {
  148325. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148326. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148327. };
  148328. static float _vq_quantthresh__44u4__p6_1[] = {
  148329. -1.5, -0.5, 0.5, 1.5,
  148330. };
  148331. static long _vq_quantmap__44u4__p6_1[] = {
  148332. 3, 1, 0, 2, 4,
  148333. };
  148334. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148335. _vq_quantthresh__44u4__p6_1,
  148336. _vq_quantmap__44u4__p6_1,
  148337. 5,
  148338. 5
  148339. };
  148340. static static_codebook _44u4__p6_1 = {
  148341. 2, 25,
  148342. _vq_lengthlist__44u4__p6_1,
  148343. 1, -533725184, 1611661312, 3, 0,
  148344. _vq_quantlist__44u4__p6_1,
  148345. NULL,
  148346. &_vq_auxt__44u4__p6_1,
  148347. NULL,
  148348. 0
  148349. };
  148350. static long _vq_quantlist__44u4__p7_0[] = {
  148351. 6,
  148352. 5,
  148353. 7,
  148354. 4,
  148355. 8,
  148356. 3,
  148357. 9,
  148358. 2,
  148359. 10,
  148360. 1,
  148361. 11,
  148362. 0,
  148363. 12,
  148364. };
  148365. static long _vq_lengthlist__44u4__p7_0[] = {
  148366. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148367. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148368. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148369. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148370. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148371. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148375. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148376. 11,11,11,11,11,11,11,11,11,
  148377. };
  148378. static float _vq_quantthresh__44u4__p7_0[] = {
  148379. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148380. 637.5, 892.5, 1147.5, 1402.5,
  148381. };
  148382. static long _vq_quantmap__44u4__p7_0[] = {
  148383. 11, 9, 7, 5, 3, 1, 0, 2,
  148384. 4, 6, 8, 10, 12,
  148385. };
  148386. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148387. _vq_quantthresh__44u4__p7_0,
  148388. _vq_quantmap__44u4__p7_0,
  148389. 13,
  148390. 13
  148391. };
  148392. static static_codebook _44u4__p7_0 = {
  148393. 2, 169,
  148394. _vq_lengthlist__44u4__p7_0,
  148395. 1, -514332672, 1627381760, 4, 0,
  148396. _vq_quantlist__44u4__p7_0,
  148397. NULL,
  148398. &_vq_auxt__44u4__p7_0,
  148399. NULL,
  148400. 0
  148401. };
  148402. static long _vq_quantlist__44u4__p7_1[] = {
  148403. 7,
  148404. 6,
  148405. 8,
  148406. 5,
  148407. 9,
  148408. 4,
  148409. 10,
  148410. 3,
  148411. 11,
  148412. 2,
  148413. 12,
  148414. 1,
  148415. 13,
  148416. 0,
  148417. 14,
  148418. };
  148419. static long _vq_lengthlist__44u4__p7_1[] = {
  148420. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148421. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148422. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148423. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148424. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148425. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148426. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148427. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148428. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148429. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148430. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148431. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148432. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148433. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148434. 16,
  148435. };
  148436. static float _vq_quantthresh__44u4__p7_1[] = {
  148437. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148438. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148439. };
  148440. static long _vq_quantmap__44u4__p7_1[] = {
  148441. 13, 11, 9, 7, 5, 3, 1, 0,
  148442. 2, 4, 6, 8, 10, 12, 14,
  148443. };
  148444. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148445. _vq_quantthresh__44u4__p7_1,
  148446. _vq_quantmap__44u4__p7_1,
  148447. 15,
  148448. 15
  148449. };
  148450. static static_codebook _44u4__p7_1 = {
  148451. 2, 225,
  148452. _vq_lengthlist__44u4__p7_1,
  148453. 1, -522338304, 1620115456, 4, 0,
  148454. _vq_quantlist__44u4__p7_1,
  148455. NULL,
  148456. &_vq_auxt__44u4__p7_1,
  148457. NULL,
  148458. 0
  148459. };
  148460. static long _vq_quantlist__44u4__p7_2[] = {
  148461. 8,
  148462. 7,
  148463. 9,
  148464. 6,
  148465. 10,
  148466. 5,
  148467. 11,
  148468. 4,
  148469. 12,
  148470. 3,
  148471. 13,
  148472. 2,
  148473. 14,
  148474. 1,
  148475. 15,
  148476. 0,
  148477. 16,
  148478. };
  148479. static long _vq_lengthlist__44u4__p7_2[] = {
  148480. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148481. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148482. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148483. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148484. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148485. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148486. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148487. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148488. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148489. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148490. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148491. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148492. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148493. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148494. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148495. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148496. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148497. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148498. 10,
  148499. };
  148500. static float _vq_quantthresh__44u4__p7_2[] = {
  148501. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148502. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148503. };
  148504. static long _vq_quantmap__44u4__p7_2[] = {
  148505. 15, 13, 11, 9, 7, 5, 3, 1,
  148506. 0, 2, 4, 6, 8, 10, 12, 14,
  148507. 16,
  148508. };
  148509. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148510. _vq_quantthresh__44u4__p7_2,
  148511. _vq_quantmap__44u4__p7_2,
  148512. 17,
  148513. 17
  148514. };
  148515. static static_codebook _44u4__p7_2 = {
  148516. 2, 289,
  148517. _vq_lengthlist__44u4__p7_2,
  148518. 1, -529530880, 1611661312, 5, 0,
  148519. _vq_quantlist__44u4__p7_2,
  148520. NULL,
  148521. &_vq_auxt__44u4__p7_2,
  148522. NULL,
  148523. 0
  148524. };
  148525. static long _huff_lengthlist__44u4__short[] = {
  148526. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148527. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148528. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148529. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148530. };
  148531. static static_codebook _huff_book__44u4__short = {
  148532. 2, 64,
  148533. _huff_lengthlist__44u4__short,
  148534. 0, 0, 0, 0, 0,
  148535. NULL,
  148536. NULL,
  148537. NULL,
  148538. NULL,
  148539. 0
  148540. };
  148541. static long _huff_lengthlist__44u5__long[] = {
  148542. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148543. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148544. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148545. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148546. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148547. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148548. 14, 8, 7, 8,
  148549. };
  148550. static static_codebook _huff_book__44u5__long = {
  148551. 2, 100,
  148552. _huff_lengthlist__44u5__long,
  148553. 0, 0, 0, 0, 0,
  148554. NULL,
  148555. NULL,
  148556. NULL,
  148557. NULL,
  148558. 0
  148559. };
  148560. static long _vq_quantlist__44u5__p1_0[] = {
  148561. 1,
  148562. 0,
  148563. 2,
  148564. };
  148565. static long _vq_lengthlist__44u5__p1_0[] = {
  148566. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148567. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148568. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148569. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148570. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148571. 12,
  148572. };
  148573. static float _vq_quantthresh__44u5__p1_0[] = {
  148574. -0.5, 0.5,
  148575. };
  148576. static long _vq_quantmap__44u5__p1_0[] = {
  148577. 1, 0, 2,
  148578. };
  148579. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148580. _vq_quantthresh__44u5__p1_0,
  148581. _vq_quantmap__44u5__p1_0,
  148582. 3,
  148583. 3
  148584. };
  148585. static static_codebook _44u5__p1_0 = {
  148586. 4, 81,
  148587. _vq_lengthlist__44u5__p1_0,
  148588. 1, -535822336, 1611661312, 2, 0,
  148589. _vq_quantlist__44u5__p1_0,
  148590. NULL,
  148591. &_vq_auxt__44u5__p1_0,
  148592. NULL,
  148593. 0
  148594. };
  148595. static long _vq_quantlist__44u5__p2_0[] = {
  148596. 1,
  148597. 0,
  148598. 2,
  148599. };
  148600. static long _vq_lengthlist__44u5__p2_0[] = {
  148601. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148602. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148603. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148604. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148605. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148606. 9,
  148607. };
  148608. static float _vq_quantthresh__44u5__p2_0[] = {
  148609. -0.5, 0.5,
  148610. };
  148611. static long _vq_quantmap__44u5__p2_0[] = {
  148612. 1, 0, 2,
  148613. };
  148614. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148615. _vq_quantthresh__44u5__p2_0,
  148616. _vq_quantmap__44u5__p2_0,
  148617. 3,
  148618. 3
  148619. };
  148620. static static_codebook _44u5__p2_0 = {
  148621. 4, 81,
  148622. _vq_lengthlist__44u5__p2_0,
  148623. 1, -535822336, 1611661312, 2, 0,
  148624. _vq_quantlist__44u5__p2_0,
  148625. NULL,
  148626. &_vq_auxt__44u5__p2_0,
  148627. NULL,
  148628. 0
  148629. };
  148630. static long _vq_quantlist__44u5__p3_0[] = {
  148631. 2,
  148632. 1,
  148633. 3,
  148634. 0,
  148635. 4,
  148636. };
  148637. static long _vq_lengthlist__44u5__p3_0[] = {
  148638. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148639. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148640. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148641. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148642. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148643. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148644. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148645. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148646. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148647. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148648. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148649. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148650. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148651. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148652. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148653. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148654. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148655. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148656. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148657. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148658. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148659. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  148660. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  148661. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  148662. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  148663. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  148664. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  148665. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  148666. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  148667. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  148668. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  148669. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  148670. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  148671. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  148672. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  148673. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  148674. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  148675. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  148676. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  148677. 0,
  148678. };
  148679. static float _vq_quantthresh__44u5__p3_0[] = {
  148680. -1.5, -0.5, 0.5, 1.5,
  148681. };
  148682. static long _vq_quantmap__44u5__p3_0[] = {
  148683. 3, 1, 0, 2, 4,
  148684. };
  148685. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  148686. _vq_quantthresh__44u5__p3_0,
  148687. _vq_quantmap__44u5__p3_0,
  148688. 5,
  148689. 5
  148690. };
  148691. static static_codebook _44u5__p3_0 = {
  148692. 4, 625,
  148693. _vq_lengthlist__44u5__p3_0,
  148694. 1, -533725184, 1611661312, 3, 0,
  148695. _vq_quantlist__44u5__p3_0,
  148696. NULL,
  148697. &_vq_auxt__44u5__p3_0,
  148698. NULL,
  148699. 0
  148700. };
  148701. static long _vq_quantlist__44u5__p4_0[] = {
  148702. 2,
  148703. 1,
  148704. 3,
  148705. 0,
  148706. 4,
  148707. };
  148708. static long _vq_lengthlist__44u5__p4_0[] = {
  148709. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  148710. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  148711. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  148712. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  148713. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  148714. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  148715. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148716. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  148717. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  148718. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  148719. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  148720. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148721. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  148722. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  148723. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  148724. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  148725. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  148726. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148727. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  148728. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  148729. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  148730. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  148731. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  148732. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  148733. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  148734. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  148735. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  148736. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  148737. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  148738. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  148739. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  148740. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  148741. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  148742. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  148743. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  148744. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  148745. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  148746. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  148747. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  148748. 12,
  148749. };
  148750. static float _vq_quantthresh__44u5__p4_0[] = {
  148751. -1.5, -0.5, 0.5, 1.5,
  148752. };
  148753. static long _vq_quantmap__44u5__p4_0[] = {
  148754. 3, 1, 0, 2, 4,
  148755. };
  148756. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  148757. _vq_quantthresh__44u5__p4_0,
  148758. _vq_quantmap__44u5__p4_0,
  148759. 5,
  148760. 5
  148761. };
  148762. static static_codebook _44u5__p4_0 = {
  148763. 4, 625,
  148764. _vq_lengthlist__44u5__p4_0,
  148765. 1, -533725184, 1611661312, 3, 0,
  148766. _vq_quantlist__44u5__p4_0,
  148767. NULL,
  148768. &_vq_auxt__44u5__p4_0,
  148769. NULL,
  148770. 0
  148771. };
  148772. static long _vq_quantlist__44u5__p5_0[] = {
  148773. 4,
  148774. 3,
  148775. 5,
  148776. 2,
  148777. 6,
  148778. 1,
  148779. 7,
  148780. 0,
  148781. 8,
  148782. };
  148783. static long _vq_lengthlist__44u5__p5_0[] = {
  148784. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  148785. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  148786. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  148787. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  148788. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  148789. 14,
  148790. };
  148791. static float _vq_quantthresh__44u5__p5_0[] = {
  148792. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148793. };
  148794. static long _vq_quantmap__44u5__p5_0[] = {
  148795. 7, 5, 3, 1, 0, 2, 4, 6,
  148796. 8,
  148797. };
  148798. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  148799. _vq_quantthresh__44u5__p5_0,
  148800. _vq_quantmap__44u5__p5_0,
  148801. 9,
  148802. 9
  148803. };
  148804. static static_codebook _44u5__p5_0 = {
  148805. 2, 81,
  148806. _vq_lengthlist__44u5__p5_0,
  148807. 1, -531628032, 1611661312, 4, 0,
  148808. _vq_quantlist__44u5__p5_0,
  148809. NULL,
  148810. &_vq_auxt__44u5__p5_0,
  148811. NULL,
  148812. 0
  148813. };
  148814. static long _vq_quantlist__44u5__p6_0[] = {
  148815. 4,
  148816. 3,
  148817. 5,
  148818. 2,
  148819. 6,
  148820. 1,
  148821. 7,
  148822. 0,
  148823. 8,
  148824. };
  148825. static long _vq_lengthlist__44u5__p6_0[] = {
  148826. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  148827. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  148828. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  148829. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  148830. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  148831. 11,
  148832. };
  148833. static float _vq_quantthresh__44u5__p6_0[] = {
  148834. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148835. };
  148836. static long _vq_quantmap__44u5__p6_0[] = {
  148837. 7, 5, 3, 1, 0, 2, 4, 6,
  148838. 8,
  148839. };
  148840. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  148841. _vq_quantthresh__44u5__p6_0,
  148842. _vq_quantmap__44u5__p6_0,
  148843. 9,
  148844. 9
  148845. };
  148846. static static_codebook _44u5__p6_0 = {
  148847. 2, 81,
  148848. _vq_lengthlist__44u5__p6_0,
  148849. 1, -531628032, 1611661312, 4, 0,
  148850. _vq_quantlist__44u5__p6_0,
  148851. NULL,
  148852. &_vq_auxt__44u5__p6_0,
  148853. NULL,
  148854. 0
  148855. };
  148856. static long _vq_quantlist__44u5__p7_0[] = {
  148857. 1,
  148858. 0,
  148859. 2,
  148860. };
  148861. static long _vq_lengthlist__44u5__p7_0[] = {
  148862. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  148863. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  148864. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  148865. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  148866. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  148867. 12,
  148868. };
  148869. static float _vq_quantthresh__44u5__p7_0[] = {
  148870. -5.5, 5.5,
  148871. };
  148872. static long _vq_quantmap__44u5__p7_0[] = {
  148873. 1, 0, 2,
  148874. };
  148875. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  148876. _vq_quantthresh__44u5__p7_0,
  148877. _vq_quantmap__44u5__p7_0,
  148878. 3,
  148879. 3
  148880. };
  148881. static static_codebook _44u5__p7_0 = {
  148882. 4, 81,
  148883. _vq_lengthlist__44u5__p7_0,
  148884. 1, -529137664, 1618345984, 2, 0,
  148885. _vq_quantlist__44u5__p7_0,
  148886. NULL,
  148887. &_vq_auxt__44u5__p7_0,
  148888. NULL,
  148889. 0
  148890. };
  148891. static long _vq_quantlist__44u5__p7_1[] = {
  148892. 5,
  148893. 4,
  148894. 6,
  148895. 3,
  148896. 7,
  148897. 2,
  148898. 8,
  148899. 1,
  148900. 9,
  148901. 0,
  148902. 10,
  148903. };
  148904. static long _vq_lengthlist__44u5__p7_1[] = {
  148905. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  148906. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  148907. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  148908. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  148909. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  148910. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  148911. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  148912. 9, 9, 9, 9, 9,10,10,10,10,
  148913. };
  148914. static float _vq_quantthresh__44u5__p7_1[] = {
  148915. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  148916. 3.5, 4.5,
  148917. };
  148918. static long _vq_quantmap__44u5__p7_1[] = {
  148919. 9, 7, 5, 3, 1, 0, 2, 4,
  148920. 6, 8, 10,
  148921. };
  148922. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  148923. _vq_quantthresh__44u5__p7_1,
  148924. _vq_quantmap__44u5__p7_1,
  148925. 11,
  148926. 11
  148927. };
  148928. static static_codebook _44u5__p7_1 = {
  148929. 2, 121,
  148930. _vq_lengthlist__44u5__p7_1,
  148931. 1, -531365888, 1611661312, 4, 0,
  148932. _vq_quantlist__44u5__p7_1,
  148933. NULL,
  148934. &_vq_auxt__44u5__p7_1,
  148935. NULL,
  148936. 0
  148937. };
  148938. static long _vq_quantlist__44u5__p8_0[] = {
  148939. 5,
  148940. 4,
  148941. 6,
  148942. 3,
  148943. 7,
  148944. 2,
  148945. 8,
  148946. 1,
  148947. 9,
  148948. 0,
  148949. 10,
  148950. };
  148951. static long _vq_lengthlist__44u5__p8_0[] = {
  148952. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  148953. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  148954. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  148955. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  148956. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  148957. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  148958. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  148959. 12,13,13,14,14,14,14,15,15,
  148960. };
  148961. static float _vq_quantthresh__44u5__p8_0[] = {
  148962. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  148963. 38.5, 49.5,
  148964. };
  148965. static long _vq_quantmap__44u5__p8_0[] = {
  148966. 9, 7, 5, 3, 1, 0, 2, 4,
  148967. 6, 8, 10,
  148968. };
  148969. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  148970. _vq_quantthresh__44u5__p8_0,
  148971. _vq_quantmap__44u5__p8_0,
  148972. 11,
  148973. 11
  148974. };
  148975. static static_codebook _44u5__p8_0 = {
  148976. 2, 121,
  148977. _vq_lengthlist__44u5__p8_0,
  148978. 1, -524582912, 1618345984, 4, 0,
  148979. _vq_quantlist__44u5__p8_0,
  148980. NULL,
  148981. &_vq_auxt__44u5__p8_0,
  148982. NULL,
  148983. 0
  148984. };
  148985. static long _vq_quantlist__44u5__p8_1[] = {
  148986. 5,
  148987. 4,
  148988. 6,
  148989. 3,
  148990. 7,
  148991. 2,
  148992. 8,
  148993. 1,
  148994. 9,
  148995. 0,
  148996. 10,
  148997. };
  148998. static long _vq_lengthlist__44u5__p8_1[] = {
  148999. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149000. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149001. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149002. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149003. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149004. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149005. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149006. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149007. };
  149008. static float _vq_quantthresh__44u5__p8_1[] = {
  149009. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149010. 3.5, 4.5,
  149011. };
  149012. static long _vq_quantmap__44u5__p8_1[] = {
  149013. 9, 7, 5, 3, 1, 0, 2, 4,
  149014. 6, 8, 10,
  149015. };
  149016. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149017. _vq_quantthresh__44u5__p8_1,
  149018. _vq_quantmap__44u5__p8_1,
  149019. 11,
  149020. 11
  149021. };
  149022. static static_codebook _44u5__p8_1 = {
  149023. 2, 121,
  149024. _vq_lengthlist__44u5__p8_1,
  149025. 1, -531365888, 1611661312, 4, 0,
  149026. _vq_quantlist__44u5__p8_1,
  149027. NULL,
  149028. &_vq_auxt__44u5__p8_1,
  149029. NULL,
  149030. 0
  149031. };
  149032. static long _vq_quantlist__44u5__p9_0[] = {
  149033. 6,
  149034. 5,
  149035. 7,
  149036. 4,
  149037. 8,
  149038. 3,
  149039. 9,
  149040. 2,
  149041. 10,
  149042. 1,
  149043. 11,
  149044. 0,
  149045. 12,
  149046. };
  149047. static long _vq_lengthlist__44u5__p9_0[] = {
  149048. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149049. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149050. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149051. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149052. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149053. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149054. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149055. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149056. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149057. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149058. 12,12,12,12,12,12,12,12,12,
  149059. };
  149060. static float _vq_quantthresh__44u5__p9_0[] = {
  149061. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149062. 637.5, 892.5, 1147.5, 1402.5,
  149063. };
  149064. static long _vq_quantmap__44u5__p9_0[] = {
  149065. 11, 9, 7, 5, 3, 1, 0, 2,
  149066. 4, 6, 8, 10, 12,
  149067. };
  149068. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149069. _vq_quantthresh__44u5__p9_0,
  149070. _vq_quantmap__44u5__p9_0,
  149071. 13,
  149072. 13
  149073. };
  149074. static static_codebook _44u5__p9_0 = {
  149075. 2, 169,
  149076. _vq_lengthlist__44u5__p9_0,
  149077. 1, -514332672, 1627381760, 4, 0,
  149078. _vq_quantlist__44u5__p9_0,
  149079. NULL,
  149080. &_vq_auxt__44u5__p9_0,
  149081. NULL,
  149082. 0
  149083. };
  149084. static long _vq_quantlist__44u5__p9_1[] = {
  149085. 7,
  149086. 6,
  149087. 8,
  149088. 5,
  149089. 9,
  149090. 4,
  149091. 10,
  149092. 3,
  149093. 11,
  149094. 2,
  149095. 12,
  149096. 1,
  149097. 13,
  149098. 0,
  149099. 14,
  149100. };
  149101. static long _vq_lengthlist__44u5__p9_1[] = {
  149102. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149103. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149104. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149105. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149106. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149107. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149108. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149109. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149110. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149111. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149112. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149113. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149114. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149115. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149116. 14,
  149117. };
  149118. static float _vq_quantthresh__44u5__p9_1[] = {
  149119. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149120. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149121. };
  149122. static long _vq_quantmap__44u5__p9_1[] = {
  149123. 13, 11, 9, 7, 5, 3, 1, 0,
  149124. 2, 4, 6, 8, 10, 12, 14,
  149125. };
  149126. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149127. _vq_quantthresh__44u5__p9_1,
  149128. _vq_quantmap__44u5__p9_1,
  149129. 15,
  149130. 15
  149131. };
  149132. static static_codebook _44u5__p9_1 = {
  149133. 2, 225,
  149134. _vq_lengthlist__44u5__p9_1,
  149135. 1, -522338304, 1620115456, 4, 0,
  149136. _vq_quantlist__44u5__p9_1,
  149137. NULL,
  149138. &_vq_auxt__44u5__p9_1,
  149139. NULL,
  149140. 0
  149141. };
  149142. static long _vq_quantlist__44u5__p9_2[] = {
  149143. 8,
  149144. 7,
  149145. 9,
  149146. 6,
  149147. 10,
  149148. 5,
  149149. 11,
  149150. 4,
  149151. 12,
  149152. 3,
  149153. 13,
  149154. 2,
  149155. 14,
  149156. 1,
  149157. 15,
  149158. 0,
  149159. 16,
  149160. };
  149161. static long _vq_lengthlist__44u5__p9_2[] = {
  149162. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149163. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149164. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149165. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149166. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149167. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149168. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149169. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149170. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149171. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149172. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149173. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149174. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149175. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149176. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149177. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149178. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149179. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149180. 10,
  149181. };
  149182. static float _vq_quantthresh__44u5__p9_2[] = {
  149183. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149184. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149185. };
  149186. static long _vq_quantmap__44u5__p9_2[] = {
  149187. 15, 13, 11, 9, 7, 5, 3, 1,
  149188. 0, 2, 4, 6, 8, 10, 12, 14,
  149189. 16,
  149190. };
  149191. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149192. _vq_quantthresh__44u5__p9_2,
  149193. _vq_quantmap__44u5__p9_2,
  149194. 17,
  149195. 17
  149196. };
  149197. static static_codebook _44u5__p9_2 = {
  149198. 2, 289,
  149199. _vq_lengthlist__44u5__p9_2,
  149200. 1, -529530880, 1611661312, 5, 0,
  149201. _vq_quantlist__44u5__p9_2,
  149202. NULL,
  149203. &_vq_auxt__44u5__p9_2,
  149204. NULL,
  149205. 0
  149206. };
  149207. static long _huff_lengthlist__44u5__short[] = {
  149208. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149209. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149210. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149211. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149212. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149213. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149214. 6, 8,15,17,
  149215. };
  149216. static static_codebook _huff_book__44u5__short = {
  149217. 2, 100,
  149218. _huff_lengthlist__44u5__short,
  149219. 0, 0, 0, 0, 0,
  149220. NULL,
  149221. NULL,
  149222. NULL,
  149223. NULL,
  149224. 0
  149225. };
  149226. static long _huff_lengthlist__44u6__long[] = {
  149227. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149228. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149229. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149230. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149231. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149232. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149233. 13, 8, 7, 7,
  149234. };
  149235. static static_codebook _huff_book__44u6__long = {
  149236. 2, 100,
  149237. _huff_lengthlist__44u6__long,
  149238. 0, 0, 0, 0, 0,
  149239. NULL,
  149240. NULL,
  149241. NULL,
  149242. NULL,
  149243. 0
  149244. };
  149245. static long _vq_quantlist__44u6__p1_0[] = {
  149246. 1,
  149247. 0,
  149248. 2,
  149249. };
  149250. static long _vq_lengthlist__44u6__p1_0[] = {
  149251. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149252. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149253. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149254. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149255. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149256. 12,
  149257. };
  149258. static float _vq_quantthresh__44u6__p1_0[] = {
  149259. -0.5, 0.5,
  149260. };
  149261. static long _vq_quantmap__44u6__p1_0[] = {
  149262. 1, 0, 2,
  149263. };
  149264. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149265. _vq_quantthresh__44u6__p1_0,
  149266. _vq_quantmap__44u6__p1_0,
  149267. 3,
  149268. 3
  149269. };
  149270. static static_codebook _44u6__p1_0 = {
  149271. 4, 81,
  149272. _vq_lengthlist__44u6__p1_0,
  149273. 1, -535822336, 1611661312, 2, 0,
  149274. _vq_quantlist__44u6__p1_0,
  149275. NULL,
  149276. &_vq_auxt__44u6__p1_0,
  149277. NULL,
  149278. 0
  149279. };
  149280. static long _vq_quantlist__44u6__p2_0[] = {
  149281. 1,
  149282. 0,
  149283. 2,
  149284. };
  149285. static long _vq_lengthlist__44u6__p2_0[] = {
  149286. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149287. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149288. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149289. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149290. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149291. 9,
  149292. };
  149293. static float _vq_quantthresh__44u6__p2_0[] = {
  149294. -0.5, 0.5,
  149295. };
  149296. static long _vq_quantmap__44u6__p2_0[] = {
  149297. 1, 0, 2,
  149298. };
  149299. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149300. _vq_quantthresh__44u6__p2_0,
  149301. _vq_quantmap__44u6__p2_0,
  149302. 3,
  149303. 3
  149304. };
  149305. static static_codebook _44u6__p2_0 = {
  149306. 4, 81,
  149307. _vq_lengthlist__44u6__p2_0,
  149308. 1, -535822336, 1611661312, 2, 0,
  149309. _vq_quantlist__44u6__p2_0,
  149310. NULL,
  149311. &_vq_auxt__44u6__p2_0,
  149312. NULL,
  149313. 0
  149314. };
  149315. static long _vq_quantlist__44u6__p3_0[] = {
  149316. 2,
  149317. 1,
  149318. 3,
  149319. 0,
  149320. 4,
  149321. };
  149322. static long _vq_lengthlist__44u6__p3_0[] = {
  149323. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149324. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149325. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149326. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149327. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149328. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149329. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149330. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149331. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149332. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149333. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149334. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149335. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149336. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149337. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149338. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149339. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149340. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149341. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149342. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149343. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149344. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149345. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149346. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149347. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149348. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149349. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149350. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149351. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149352. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149353. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149354. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149355. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149356. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149357. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149358. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149359. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149360. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149361. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149362. 19,
  149363. };
  149364. static float _vq_quantthresh__44u6__p3_0[] = {
  149365. -1.5, -0.5, 0.5, 1.5,
  149366. };
  149367. static long _vq_quantmap__44u6__p3_0[] = {
  149368. 3, 1, 0, 2, 4,
  149369. };
  149370. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149371. _vq_quantthresh__44u6__p3_0,
  149372. _vq_quantmap__44u6__p3_0,
  149373. 5,
  149374. 5
  149375. };
  149376. static static_codebook _44u6__p3_0 = {
  149377. 4, 625,
  149378. _vq_lengthlist__44u6__p3_0,
  149379. 1, -533725184, 1611661312, 3, 0,
  149380. _vq_quantlist__44u6__p3_0,
  149381. NULL,
  149382. &_vq_auxt__44u6__p3_0,
  149383. NULL,
  149384. 0
  149385. };
  149386. static long _vq_quantlist__44u6__p4_0[] = {
  149387. 2,
  149388. 1,
  149389. 3,
  149390. 0,
  149391. 4,
  149392. };
  149393. static long _vq_lengthlist__44u6__p4_0[] = {
  149394. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149395. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149396. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149397. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149398. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149399. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149400. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149401. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149402. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149403. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149404. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149405. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149406. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149407. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149408. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149409. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149410. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149411. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149412. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149413. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149414. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149415. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149416. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149417. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149418. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149419. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149420. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149421. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149422. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149423. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149424. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149425. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149426. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149427. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149428. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149429. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149430. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149431. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149432. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149433. 13,
  149434. };
  149435. static float _vq_quantthresh__44u6__p4_0[] = {
  149436. -1.5, -0.5, 0.5, 1.5,
  149437. };
  149438. static long _vq_quantmap__44u6__p4_0[] = {
  149439. 3, 1, 0, 2, 4,
  149440. };
  149441. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149442. _vq_quantthresh__44u6__p4_0,
  149443. _vq_quantmap__44u6__p4_0,
  149444. 5,
  149445. 5
  149446. };
  149447. static static_codebook _44u6__p4_0 = {
  149448. 4, 625,
  149449. _vq_lengthlist__44u6__p4_0,
  149450. 1, -533725184, 1611661312, 3, 0,
  149451. _vq_quantlist__44u6__p4_0,
  149452. NULL,
  149453. &_vq_auxt__44u6__p4_0,
  149454. NULL,
  149455. 0
  149456. };
  149457. static long _vq_quantlist__44u6__p5_0[] = {
  149458. 4,
  149459. 3,
  149460. 5,
  149461. 2,
  149462. 6,
  149463. 1,
  149464. 7,
  149465. 0,
  149466. 8,
  149467. };
  149468. static long _vq_lengthlist__44u6__p5_0[] = {
  149469. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149470. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149471. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149472. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149473. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149474. 14,
  149475. };
  149476. static float _vq_quantthresh__44u6__p5_0[] = {
  149477. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149478. };
  149479. static long _vq_quantmap__44u6__p5_0[] = {
  149480. 7, 5, 3, 1, 0, 2, 4, 6,
  149481. 8,
  149482. };
  149483. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149484. _vq_quantthresh__44u6__p5_0,
  149485. _vq_quantmap__44u6__p5_0,
  149486. 9,
  149487. 9
  149488. };
  149489. static static_codebook _44u6__p5_0 = {
  149490. 2, 81,
  149491. _vq_lengthlist__44u6__p5_0,
  149492. 1, -531628032, 1611661312, 4, 0,
  149493. _vq_quantlist__44u6__p5_0,
  149494. NULL,
  149495. &_vq_auxt__44u6__p5_0,
  149496. NULL,
  149497. 0
  149498. };
  149499. static long _vq_quantlist__44u6__p6_0[] = {
  149500. 4,
  149501. 3,
  149502. 5,
  149503. 2,
  149504. 6,
  149505. 1,
  149506. 7,
  149507. 0,
  149508. 8,
  149509. };
  149510. static long _vq_lengthlist__44u6__p6_0[] = {
  149511. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149512. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149513. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149514. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149515. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149516. 12,
  149517. };
  149518. static float _vq_quantthresh__44u6__p6_0[] = {
  149519. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149520. };
  149521. static long _vq_quantmap__44u6__p6_0[] = {
  149522. 7, 5, 3, 1, 0, 2, 4, 6,
  149523. 8,
  149524. };
  149525. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149526. _vq_quantthresh__44u6__p6_0,
  149527. _vq_quantmap__44u6__p6_0,
  149528. 9,
  149529. 9
  149530. };
  149531. static static_codebook _44u6__p6_0 = {
  149532. 2, 81,
  149533. _vq_lengthlist__44u6__p6_0,
  149534. 1, -531628032, 1611661312, 4, 0,
  149535. _vq_quantlist__44u6__p6_0,
  149536. NULL,
  149537. &_vq_auxt__44u6__p6_0,
  149538. NULL,
  149539. 0
  149540. };
  149541. static long _vq_quantlist__44u6__p7_0[] = {
  149542. 1,
  149543. 0,
  149544. 2,
  149545. };
  149546. static long _vq_lengthlist__44u6__p7_0[] = {
  149547. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149548. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149549. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149550. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149551. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149552. 10,
  149553. };
  149554. static float _vq_quantthresh__44u6__p7_0[] = {
  149555. -5.5, 5.5,
  149556. };
  149557. static long _vq_quantmap__44u6__p7_0[] = {
  149558. 1, 0, 2,
  149559. };
  149560. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149561. _vq_quantthresh__44u6__p7_0,
  149562. _vq_quantmap__44u6__p7_0,
  149563. 3,
  149564. 3
  149565. };
  149566. static static_codebook _44u6__p7_0 = {
  149567. 4, 81,
  149568. _vq_lengthlist__44u6__p7_0,
  149569. 1, -529137664, 1618345984, 2, 0,
  149570. _vq_quantlist__44u6__p7_0,
  149571. NULL,
  149572. &_vq_auxt__44u6__p7_0,
  149573. NULL,
  149574. 0
  149575. };
  149576. static long _vq_quantlist__44u6__p7_1[] = {
  149577. 5,
  149578. 4,
  149579. 6,
  149580. 3,
  149581. 7,
  149582. 2,
  149583. 8,
  149584. 1,
  149585. 9,
  149586. 0,
  149587. 10,
  149588. };
  149589. static long _vq_lengthlist__44u6__p7_1[] = {
  149590. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149591. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149592. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149593. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149594. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149595. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149596. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149597. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149598. };
  149599. static float _vq_quantthresh__44u6__p7_1[] = {
  149600. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149601. 3.5, 4.5,
  149602. };
  149603. static long _vq_quantmap__44u6__p7_1[] = {
  149604. 9, 7, 5, 3, 1, 0, 2, 4,
  149605. 6, 8, 10,
  149606. };
  149607. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149608. _vq_quantthresh__44u6__p7_1,
  149609. _vq_quantmap__44u6__p7_1,
  149610. 11,
  149611. 11
  149612. };
  149613. static static_codebook _44u6__p7_1 = {
  149614. 2, 121,
  149615. _vq_lengthlist__44u6__p7_1,
  149616. 1, -531365888, 1611661312, 4, 0,
  149617. _vq_quantlist__44u6__p7_1,
  149618. NULL,
  149619. &_vq_auxt__44u6__p7_1,
  149620. NULL,
  149621. 0
  149622. };
  149623. static long _vq_quantlist__44u6__p8_0[] = {
  149624. 5,
  149625. 4,
  149626. 6,
  149627. 3,
  149628. 7,
  149629. 2,
  149630. 8,
  149631. 1,
  149632. 9,
  149633. 0,
  149634. 10,
  149635. };
  149636. static long _vq_lengthlist__44u6__p8_0[] = {
  149637. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149638. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149639. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149640. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149641. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149642. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149643. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149644. 12,13,13,14,14,14,15,15,15,
  149645. };
  149646. static float _vq_quantthresh__44u6__p8_0[] = {
  149647. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149648. 38.5, 49.5,
  149649. };
  149650. static long _vq_quantmap__44u6__p8_0[] = {
  149651. 9, 7, 5, 3, 1, 0, 2, 4,
  149652. 6, 8, 10,
  149653. };
  149654. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149655. _vq_quantthresh__44u6__p8_0,
  149656. _vq_quantmap__44u6__p8_0,
  149657. 11,
  149658. 11
  149659. };
  149660. static static_codebook _44u6__p8_0 = {
  149661. 2, 121,
  149662. _vq_lengthlist__44u6__p8_0,
  149663. 1, -524582912, 1618345984, 4, 0,
  149664. _vq_quantlist__44u6__p8_0,
  149665. NULL,
  149666. &_vq_auxt__44u6__p8_0,
  149667. NULL,
  149668. 0
  149669. };
  149670. static long _vq_quantlist__44u6__p8_1[] = {
  149671. 5,
  149672. 4,
  149673. 6,
  149674. 3,
  149675. 7,
  149676. 2,
  149677. 8,
  149678. 1,
  149679. 9,
  149680. 0,
  149681. 10,
  149682. };
  149683. static long _vq_lengthlist__44u6__p8_1[] = {
  149684. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  149685. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  149686. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  149687. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149688. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  149689. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149690. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  149691. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149692. };
  149693. static float _vq_quantthresh__44u6__p8_1[] = {
  149694. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149695. 3.5, 4.5,
  149696. };
  149697. static long _vq_quantmap__44u6__p8_1[] = {
  149698. 9, 7, 5, 3, 1, 0, 2, 4,
  149699. 6, 8, 10,
  149700. };
  149701. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  149702. _vq_quantthresh__44u6__p8_1,
  149703. _vq_quantmap__44u6__p8_1,
  149704. 11,
  149705. 11
  149706. };
  149707. static static_codebook _44u6__p8_1 = {
  149708. 2, 121,
  149709. _vq_lengthlist__44u6__p8_1,
  149710. 1, -531365888, 1611661312, 4, 0,
  149711. _vq_quantlist__44u6__p8_1,
  149712. NULL,
  149713. &_vq_auxt__44u6__p8_1,
  149714. NULL,
  149715. 0
  149716. };
  149717. static long _vq_quantlist__44u6__p9_0[] = {
  149718. 7,
  149719. 6,
  149720. 8,
  149721. 5,
  149722. 9,
  149723. 4,
  149724. 10,
  149725. 3,
  149726. 11,
  149727. 2,
  149728. 12,
  149729. 1,
  149730. 13,
  149731. 0,
  149732. 14,
  149733. };
  149734. static long _vq_lengthlist__44u6__p9_0[] = {
  149735. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  149736. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  149737. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  149738. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  149739. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149740. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149741. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149742. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149743. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149744. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149745. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149746. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149747. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149748. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  149749. 14,
  149750. };
  149751. static float _vq_quantthresh__44u6__p9_0[] = {
  149752. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  149753. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  149754. };
  149755. static long _vq_quantmap__44u6__p9_0[] = {
  149756. 13, 11, 9, 7, 5, 3, 1, 0,
  149757. 2, 4, 6, 8, 10, 12, 14,
  149758. };
  149759. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  149760. _vq_quantthresh__44u6__p9_0,
  149761. _vq_quantmap__44u6__p9_0,
  149762. 15,
  149763. 15
  149764. };
  149765. static static_codebook _44u6__p9_0 = {
  149766. 2, 225,
  149767. _vq_lengthlist__44u6__p9_0,
  149768. 1, -514071552, 1627381760, 4, 0,
  149769. _vq_quantlist__44u6__p9_0,
  149770. NULL,
  149771. &_vq_auxt__44u6__p9_0,
  149772. NULL,
  149773. 0
  149774. };
  149775. static long _vq_quantlist__44u6__p9_1[] = {
  149776. 7,
  149777. 6,
  149778. 8,
  149779. 5,
  149780. 9,
  149781. 4,
  149782. 10,
  149783. 3,
  149784. 11,
  149785. 2,
  149786. 12,
  149787. 1,
  149788. 13,
  149789. 0,
  149790. 14,
  149791. };
  149792. static long _vq_lengthlist__44u6__p9_1[] = {
  149793. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  149794. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  149795. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  149796. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  149797. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  149798. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  149799. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  149800. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  149801. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  149802. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  149803. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  149804. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  149805. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  149806. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  149807. 13,
  149808. };
  149809. static float _vq_quantthresh__44u6__p9_1[] = {
  149810. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149811. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149812. };
  149813. static long _vq_quantmap__44u6__p9_1[] = {
  149814. 13, 11, 9, 7, 5, 3, 1, 0,
  149815. 2, 4, 6, 8, 10, 12, 14,
  149816. };
  149817. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  149818. _vq_quantthresh__44u6__p9_1,
  149819. _vq_quantmap__44u6__p9_1,
  149820. 15,
  149821. 15
  149822. };
  149823. static static_codebook _44u6__p9_1 = {
  149824. 2, 225,
  149825. _vq_lengthlist__44u6__p9_1,
  149826. 1, -522338304, 1620115456, 4, 0,
  149827. _vq_quantlist__44u6__p9_1,
  149828. NULL,
  149829. &_vq_auxt__44u6__p9_1,
  149830. NULL,
  149831. 0
  149832. };
  149833. static long _vq_quantlist__44u6__p9_2[] = {
  149834. 8,
  149835. 7,
  149836. 9,
  149837. 6,
  149838. 10,
  149839. 5,
  149840. 11,
  149841. 4,
  149842. 12,
  149843. 3,
  149844. 13,
  149845. 2,
  149846. 14,
  149847. 1,
  149848. 15,
  149849. 0,
  149850. 16,
  149851. };
  149852. static long _vq_lengthlist__44u6__p9_2[] = {
  149853. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  149854. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  149855. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  149856. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149857. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149858. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149859. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149860. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149861. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  149862. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  149863. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  149864. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  149865. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  149866. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  149867. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  149868. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  149869. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  149870. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  149871. 10,
  149872. };
  149873. static float _vq_quantthresh__44u6__p9_2[] = {
  149874. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149875. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149876. };
  149877. static long _vq_quantmap__44u6__p9_2[] = {
  149878. 15, 13, 11, 9, 7, 5, 3, 1,
  149879. 0, 2, 4, 6, 8, 10, 12, 14,
  149880. 16,
  149881. };
  149882. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  149883. _vq_quantthresh__44u6__p9_2,
  149884. _vq_quantmap__44u6__p9_2,
  149885. 17,
  149886. 17
  149887. };
  149888. static static_codebook _44u6__p9_2 = {
  149889. 2, 289,
  149890. _vq_lengthlist__44u6__p9_2,
  149891. 1, -529530880, 1611661312, 5, 0,
  149892. _vq_quantlist__44u6__p9_2,
  149893. NULL,
  149894. &_vq_auxt__44u6__p9_2,
  149895. NULL,
  149896. 0
  149897. };
  149898. static long _huff_lengthlist__44u6__short[] = {
  149899. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  149900. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  149901. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  149902. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  149903. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  149904. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  149905. 7, 6, 9,16,
  149906. };
  149907. static static_codebook _huff_book__44u6__short = {
  149908. 2, 100,
  149909. _huff_lengthlist__44u6__short,
  149910. 0, 0, 0, 0, 0,
  149911. NULL,
  149912. NULL,
  149913. NULL,
  149914. NULL,
  149915. 0
  149916. };
  149917. static long _huff_lengthlist__44u7__long[] = {
  149918. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  149919. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  149920. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  149921. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  149922. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  149923. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  149924. 12, 8, 6, 7,
  149925. };
  149926. static static_codebook _huff_book__44u7__long = {
  149927. 2, 100,
  149928. _huff_lengthlist__44u7__long,
  149929. 0, 0, 0, 0, 0,
  149930. NULL,
  149931. NULL,
  149932. NULL,
  149933. NULL,
  149934. 0
  149935. };
  149936. static long _vq_quantlist__44u7__p1_0[] = {
  149937. 1,
  149938. 0,
  149939. 2,
  149940. };
  149941. static long _vq_lengthlist__44u7__p1_0[] = {
  149942. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149943. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  149944. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149945. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  149946. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  149947. 12,
  149948. };
  149949. static float _vq_quantthresh__44u7__p1_0[] = {
  149950. -0.5, 0.5,
  149951. };
  149952. static long _vq_quantmap__44u7__p1_0[] = {
  149953. 1, 0, 2,
  149954. };
  149955. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  149956. _vq_quantthresh__44u7__p1_0,
  149957. _vq_quantmap__44u7__p1_0,
  149958. 3,
  149959. 3
  149960. };
  149961. static static_codebook _44u7__p1_0 = {
  149962. 4, 81,
  149963. _vq_lengthlist__44u7__p1_0,
  149964. 1, -535822336, 1611661312, 2, 0,
  149965. _vq_quantlist__44u7__p1_0,
  149966. NULL,
  149967. &_vq_auxt__44u7__p1_0,
  149968. NULL,
  149969. 0
  149970. };
  149971. static long _vq_quantlist__44u7__p2_0[] = {
  149972. 1,
  149973. 0,
  149974. 2,
  149975. };
  149976. static long _vq_lengthlist__44u7__p2_0[] = {
  149977. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149978. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149979. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149980. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149981. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149982. 9,
  149983. };
  149984. static float _vq_quantthresh__44u7__p2_0[] = {
  149985. -0.5, 0.5,
  149986. };
  149987. static long _vq_quantmap__44u7__p2_0[] = {
  149988. 1, 0, 2,
  149989. };
  149990. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  149991. _vq_quantthresh__44u7__p2_0,
  149992. _vq_quantmap__44u7__p2_0,
  149993. 3,
  149994. 3
  149995. };
  149996. static static_codebook _44u7__p2_0 = {
  149997. 4, 81,
  149998. _vq_lengthlist__44u7__p2_0,
  149999. 1, -535822336, 1611661312, 2, 0,
  150000. _vq_quantlist__44u7__p2_0,
  150001. NULL,
  150002. &_vq_auxt__44u7__p2_0,
  150003. NULL,
  150004. 0
  150005. };
  150006. static long _vq_quantlist__44u7__p3_0[] = {
  150007. 2,
  150008. 1,
  150009. 3,
  150010. 0,
  150011. 4,
  150012. };
  150013. static long _vq_lengthlist__44u7__p3_0[] = {
  150014. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150015. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150016. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150017. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150018. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150019. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150020. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150021. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150022. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150023. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150024. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150025. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150026. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150027. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150028. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150029. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150030. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150031. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150032. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150033. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150034. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150035. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150036. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150037. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150038. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150039. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150040. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150041. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150042. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150043. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150044. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150045. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150046. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150047. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150048. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150049. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150050. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150051. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150052. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150053. 0,
  150054. };
  150055. static float _vq_quantthresh__44u7__p3_0[] = {
  150056. -1.5, -0.5, 0.5, 1.5,
  150057. };
  150058. static long _vq_quantmap__44u7__p3_0[] = {
  150059. 3, 1, 0, 2, 4,
  150060. };
  150061. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150062. _vq_quantthresh__44u7__p3_0,
  150063. _vq_quantmap__44u7__p3_0,
  150064. 5,
  150065. 5
  150066. };
  150067. static static_codebook _44u7__p3_0 = {
  150068. 4, 625,
  150069. _vq_lengthlist__44u7__p3_0,
  150070. 1, -533725184, 1611661312, 3, 0,
  150071. _vq_quantlist__44u7__p3_0,
  150072. NULL,
  150073. &_vq_auxt__44u7__p3_0,
  150074. NULL,
  150075. 0
  150076. };
  150077. static long _vq_quantlist__44u7__p4_0[] = {
  150078. 2,
  150079. 1,
  150080. 3,
  150081. 0,
  150082. 4,
  150083. };
  150084. static long _vq_lengthlist__44u7__p4_0[] = {
  150085. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150086. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150087. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150088. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150089. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150090. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150091. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150092. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150093. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150094. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150095. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150096. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150097. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150098. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150099. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150100. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150101. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150102. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150103. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150104. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150105. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150106. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150107. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150108. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150109. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150110. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150111. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150112. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150113. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150114. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150115. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150116. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150117. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150118. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150119. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150120. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150121. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150122. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150123. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150124. 14,
  150125. };
  150126. static float _vq_quantthresh__44u7__p4_0[] = {
  150127. -1.5, -0.5, 0.5, 1.5,
  150128. };
  150129. static long _vq_quantmap__44u7__p4_0[] = {
  150130. 3, 1, 0, 2, 4,
  150131. };
  150132. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150133. _vq_quantthresh__44u7__p4_0,
  150134. _vq_quantmap__44u7__p4_0,
  150135. 5,
  150136. 5
  150137. };
  150138. static static_codebook _44u7__p4_0 = {
  150139. 4, 625,
  150140. _vq_lengthlist__44u7__p4_0,
  150141. 1, -533725184, 1611661312, 3, 0,
  150142. _vq_quantlist__44u7__p4_0,
  150143. NULL,
  150144. &_vq_auxt__44u7__p4_0,
  150145. NULL,
  150146. 0
  150147. };
  150148. static long _vq_quantlist__44u7__p5_0[] = {
  150149. 4,
  150150. 3,
  150151. 5,
  150152. 2,
  150153. 6,
  150154. 1,
  150155. 7,
  150156. 0,
  150157. 8,
  150158. };
  150159. static long _vq_lengthlist__44u7__p5_0[] = {
  150160. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150161. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150162. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150163. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150164. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150165. 14,
  150166. };
  150167. static float _vq_quantthresh__44u7__p5_0[] = {
  150168. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150169. };
  150170. static long _vq_quantmap__44u7__p5_0[] = {
  150171. 7, 5, 3, 1, 0, 2, 4, 6,
  150172. 8,
  150173. };
  150174. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150175. _vq_quantthresh__44u7__p5_0,
  150176. _vq_quantmap__44u7__p5_0,
  150177. 9,
  150178. 9
  150179. };
  150180. static static_codebook _44u7__p5_0 = {
  150181. 2, 81,
  150182. _vq_lengthlist__44u7__p5_0,
  150183. 1, -531628032, 1611661312, 4, 0,
  150184. _vq_quantlist__44u7__p5_0,
  150185. NULL,
  150186. &_vq_auxt__44u7__p5_0,
  150187. NULL,
  150188. 0
  150189. };
  150190. static long _vq_quantlist__44u7__p6_0[] = {
  150191. 4,
  150192. 3,
  150193. 5,
  150194. 2,
  150195. 6,
  150196. 1,
  150197. 7,
  150198. 0,
  150199. 8,
  150200. };
  150201. static long _vq_lengthlist__44u7__p6_0[] = {
  150202. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150203. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150204. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150205. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150206. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150207. 12,
  150208. };
  150209. static float _vq_quantthresh__44u7__p6_0[] = {
  150210. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150211. };
  150212. static long _vq_quantmap__44u7__p6_0[] = {
  150213. 7, 5, 3, 1, 0, 2, 4, 6,
  150214. 8,
  150215. };
  150216. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150217. _vq_quantthresh__44u7__p6_0,
  150218. _vq_quantmap__44u7__p6_0,
  150219. 9,
  150220. 9
  150221. };
  150222. static static_codebook _44u7__p6_0 = {
  150223. 2, 81,
  150224. _vq_lengthlist__44u7__p6_0,
  150225. 1, -531628032, 1611661312, 4, 0,
  150226. _vq_quantlist__44u7__p6_0,
  150227. NULL,
  150228. &_vq_auxt__44u7__p6_0,
  150229. NULL,
  150230. 0
  150231. };
  150232. static long _vq_quantlist__44u7__p7_0[] = {
  150233. 1,
  150234. 0,
  150235. 2,
  150236. };
  150237. static long _vq_lengthlist__44u7__p7_0[] = {
  150238. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150239. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150240. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150241. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150242. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150243. 10,
  150244. };
  150245. static float _vq_quantthresh__44u7__p7_0[] = {
  150246. -5.5, 5.5,
  150247. };
  150248. static long _vq_quantmap__44u7__p7_0[] = {
  150249. 1, 0, 2,
  150250. };
  150251. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150252. _vq_quantthresh__44u7__p7_0,
  150253. _vq_quantmap__44u7__p7_0,
  150254. 3,
  150255. 3
  150256. };
  150257. static static_codebook _44u7__p7_0 = {
  150258. 4, 81,
  150259. _vq_lengthlist__44u7__p7_0,
  150260. 1, -529137664, 1618345984, 2, 0,
  150261. _vq_quantlist__44u7__p7_0,
  150262. NULL,
  150263. &_vq_auxt__44u7__p7_0,
  150264. NULL,
  150265. 0
  150266. };
  150267. static long _vq_quantlist__44u7__p7_1[] = {
  150268. 5,
  150269. 4,
  150270. 6,
  150271. 3,
  150272. 7,
  150273. 2,
  150274. 8,
  150275. 1,
  150276. 9,
  150277. 0,
  150278. 10,
  150279. };
  150280. static long _vq_lengthlist__44u7__p7_1[] = {
  150281. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150282. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150283. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150284. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150285. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150286. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150287. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150288. 8, 9, 9, 9, 9, 9,10,10,10,
  150289. };
  150290. static float _vq_quantthresh__44u7__p7_1[] = {
  150291. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150292. 3.5, 4.5,
  150293. };
  150294. static long _vq_quantmap__44u7__p7_1[] = {
  150295. 9, 7, 5, 3, 1, 0, 2, 4,
  150296. 6, 8, 10,
  150297. };
  150298. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150299. _vq_quantthresh__44u7__p7_1,
  150300. _vq_quantmap__44u7__p7_1,
  150301. 11,
  150302. 11
  150303. };
  150304. static static_codebook _44u7__p7_1 = {
  150305. 2, 121,
  150306. _vq_lengthlist__44u7__p7_1,
  150307. 1, -531365888, 1611661312, 4, 0,
  150308. _vq_quantlist__44u7__p7_1,
  150309. NULL,
  150310. &_vq_auxt__44u7__p7_1,
  150311. NULL,
  150312. 0
  150313. };
  150314. static long _vq_quantlist__44u7__p8_0[] = {
  150315. 5,
  150316. 4,
  150317. 6,
  150318. 3,
  150319. 7,
  150320. 2,
  150321. 8,
  150322. 1,
  150323. 9,
  150324. 0,
  150325. 10,
  150326. };
  150327. static long _vq_lengthlist__44u7__p8_0[] = {
  150328. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150329. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150330. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150331. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150332. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150333. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150334. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150335. 12,13,13,14,14,15,15,15,16,
  150336. };
  150337. static float _vq_quantthresh__44u7__p8_0[] = {
  150338. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150339. 38.5, 49.5,
  150340. };
  150341. static long _vq_quantmap__44u7__p8_0[] = {
  150342. 9, 7, 5, 3, 1, 0, 2, 4,
  150343. 6, 8, 10,
  150344. };
  150345. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150346. _vq_quantthresh__44u7__p8_0,
  150347. _vq_quantmap__44u7__p8_0,
  150348. 11,
  150349. 11
  150350. };
  150351. static static_codebook _44u7__p8_0 = {
  150352. 2, 121,
  150353. _vq_lengthlist__44u7__p8_0,
  150354. 1, -524582912, 1618345984, 4, 0,
  150355. _vq_quantlist__44u7__p8_0,
  150356. NULL,
  150357. &_vq_auxt__44u7__p8_0,
  150358. NULL,
  150359. 0
  150360. };
  150361. static long _vq_quantlist__44u7__p8_1[] = {
  150362. 5,
  150363. 4,
  150364. 6,
  150365. 3,
  150366. 7,
  150367. 2,
  150368. 8,
  150369. 1,
  150370. 9,
  150371. 0,
  150372. 10,
  150373. };
  150374. static long _vq_lengthlist__44u7__p8_1[] = {
  150375. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150376. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150377. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150378. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150379. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150380. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150381. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150382. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150383. };
  150384. static float _vq_quantthresh__44u7__p8_1[] = {
  150385. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150386. 3.5, 4.5,
  150387. };
  150388. static long _vq_quantmap__44u7__p8_1[] = {
  150389. 9, 7, 5, 3, 1, 0, 2, 4,
  150390. 6, 8, 10,
  150391. };
  150392. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150393. _vq_quantthresh__44u7__p8_1,
  150394. _vq_quantmap__44u7__p8_1,
  150395. 11,
  150396. 11
  150397. };
  150398. static static_codebook _44u7__p8_1 = {
  150399. 2, 121,
  150400. _vq_lengthlist__44u7__p8_1,
  150401. 1, -531365888, 1611661312, 4, 0,
  150402. _vq_quantlist__44u7__p8_1,
  150403. NULL,
  150404. &_vq_auxt__44u7__p8_1,
  150405. NULL,
  150406. 0
  150407. };
  150408. static long _vq_quantlist__44u7__p9_0[] = {
  150409. 5,
  150410. 4,
  150411. 6,
  150412. 3,
  150413. 7,
  150414. 2,
  150415. 8,
  150416. 1,
  150417. 9,
  150418. 0,
  150419. 10,
  150420. };
  150421. static long _vq_lengthlist__44u7__p9_0[] = {
  150422. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150423. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150424. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150425. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150426. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150427. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150428. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150429. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150430. };
  150431. static float _vq_quantthresh__44u7__p9_0[] = {
  150432. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150433. 2229.5, 2866.5,
  150434. };
  150435. static long _vq_quantmap__44u7__p9_0[] = {
  150436. 9, 7, 5, 3, 1, 0, 2, 4,
  150437. 6, 8, 10,
  150438. };
  150439. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150440. _vq_quantthresh__44u7__p9_0,
  150441. _vq_quantmap__44u7__p9_0,
  150442. 11,
  150443. 11
  150444. };
  150445. static static_codebook _44u7__p9_0 = {
  150446. 2, 121,
  150447. _vq_lengthlist__44u7__p9_0,
  150448. 1, -512171520, 1630791680, 4, 0,
  150449. _vq_quantlist__44u7__p9_0,
  150450. NULL,
  150451. &_vq_auxt__44u7__p9_0,
  150452. NULL,
  150453. 0
  150454. };
  150455. static long _vq_quantlist__44u7__p9_1[] = {
  150456. 6,
  150457. 5,
  150458. 7,
  150459. 4,
  150460. 8,
  150461. 3,
  150462. 9,
  150463. 2,
  150464. 10,
  150465. 1,
  150466. 11,
  150467. 0,
  150468. 12,
  150469. };
  150470. static long _vq_lengthlist__44u7__p9_1[] = {
  150471. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150472. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150473. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150474. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150475. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150476. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150477. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150478. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150479. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150480. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150481. 15,15,15,15,17,17,16,17,16,
  150482. };
  150483. static float _vq_quantthresh__44u7__p9_1[] = {
  150484. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150485. 122.5, 171.5, 220.5, 269.5,
  150486. };
  150487. static long _vq_quantmap__44u7__p9_1[] = {
  150488. 11, 9, 7, 5, 3, 1, 0, 2,
  150489. 4, 6, 8, 10, 12,
  150490. };
  150491. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150492. _vq_quantthresh__44u7__p9_1,
  150493. _vq_quantmap__44u7__p9_1,
  150494. 13,
  150495. 13
  150496. };
  150497. static static_codebook _44u7__p9_1 = {
  150498. 2, 169,
  150499. _vq_lengthlist__44u7__p9_1,
  150500. 1, -518889472, 1622704128, 4, 0,
  150501. _vq_quantlist__44u7__p9_1,
  150502. NULL,
  150503. &_vq_auxt__44u7__p9_1,
  150504. NULL,
  150505. 0
  150506. };
  150507. static long _vq_quantlist__44u7__p9_2[] = {
  150508. 24,
  150509. 23,
  150510. 25,
  150511. 22,
  150512. 26,
  150513. 21,
  150514. 27,
  150515. 20,
  150516. 28,
  150517. 19,
  150518. 29,
  150519. 18,
  150520. 30,
  150521. 17,
  150522. 31,
  150523. 16,
  150524. 32,
  150525. 15,
  150526. 33,
  150527. 14,
  150528. 34,
  150529. 13,
  150530. 35,
  150531. 12,
  150532. 36,
  150533. 11,
  150534. 37,
  150535. 10,
  150536. 38,
  150537. 9,
  150538. 39,
  150539. 8,
  150540. 40,
  150541. 7,
  150542. 41,
  150543. 6,
  150544. 42,
  150545. 5,
  150546. 43,
  150547. 4,
  150548. 44,
  150549. 3,
  150550. 45,
  150551. 2,
  150552. 46,
  150553. 1,
  150554. 47,
  150555. 0,
  150556. 48,
  150557. };
  150558. static long _vq_lengthlist__44u7__p9_2[] = {
  150559. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150560. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150561. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150562. 8,
  150563. };
  150564. static float _vq_quantthresh__44u7__p9_2[] = {
  150565. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150566. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150567. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150568. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150569. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150570. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150571. };
  150572. static long _vq_quantmap__44u7__p9_2[] = {
  150573. 47, 45, 43, 41, 39, 37, 35, 33,
  150574. 31, 29, 27, 25, 23, 21, 19, 17,
  150575. 15, 13, 11, 9, 7, 5, 3, 1,
  150576. 0, 2, 4, 6, 8, 10, 12, 14,
  150577. 16, 18, 20, 22, 24, 26, 28, 30,
  150578. 32, 34, 36, 38, 40, 42, 44, 46,
  150579. 48,
  150580. };
  150581. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150582. _vq_quantthresh__44u7__p9_2,
  150583. _vq_quantmap__44u7__p9_2,
  150584. 49,
  150585. 49
  150586. };
  150587. static static_codebook _44u7__p9_2 = {
  150588. 1, 49,
  150589. _vq_lengthlist__44u7__p9_2,
  150590. 1, -526909440, 1611661312, 6, 0,
  150591. _vq_quantlist__44u7__p9_2,
  150592. NULL,
  150593. &_vq_auxt__44u7__p9_2,
  150594. NULL,
  150595. 0
  150596. };
  150597. static long _huff_lengthlist__44u7__short[] = {
  150598. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150599. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150600. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150601. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150602. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150603. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150604. 6, 8, 5, 9,
  150605. };
  150606. static static_codebook _huff_book__44u7__short = {
  150607. 2, 100,
  150608. _huff_lengthlist__44u7__short,
  150609. 0, 0, 0, 0, 0,
  150610. NULL,
  150611. NULL,
  150612. NULL,
  150613. NULL,
  150614. 0
  150615. };
  150616. static long _huff_lengthlist__44u8__long[] = {
  150617. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150618. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150619. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150620. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150621. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150622. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150623. 10, 8, 8, 9,
  150624. };
  150625. static static_codebook _huff_book__44u8__long = {
  150626. 2, 100,
  150627. _huff_lengthlist__44u8__long,
  150628. 0, 0, 0, 0, 0,
  150629. NULL,
  150630. NULL,
  150631. NULL,
  150632. NULL,
  150633. 0
  150634. };
  150635. static long _huff_lengthlist__44u8__short[] = {
  150636. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150637. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150638. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150639. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150640. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150641. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150642. 10,10,15,17,
  150643. };
  150644. static static_codebook _huff_book__44u8__short = {
  150645. 2, 100,
  150646. _huff_lengthlist__44u8__short,
  150647. 0, 0, 0, 0, 0,
  150648. NULL,
  150649. NULL,
  150650. NULL,
  150651. NULL,
  150652. 0
  150653. };
  150654. static long _vq_quantlist__44u8_p1_0[] = {
  150655. 1,
  150656. 0,
  150657. 2,
  150658. };
  150659. static long _vq_lengthlist__44u8_p1_0[] = {
  150660. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  150661. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  150662. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  150663. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  150664. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  150665. 10,
  150666. };
  150667. static float _vq_quantthresh__44u8_p1_0[] = {
  150668. -0.5, 0.5,
  150669. };
  150670. static long _vq_quantmap__44u8_p1_0[] = {
  150671. 1, 0, 2,
  150672. };
  150673. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  150674. _vq_quantthresh__44u8_p1_0,
  150675. _vq_quantmap__44u8_p1_0,
  150676. 3,
  150677. 3
  150678. };
  150679. static static_codebook _44u8_p1_0 = {
  150680. 4, 81,
  150681. _vq_lengthlist__44u8_p1_0,
  150682. 1, -535822336, 1611661312, 2, 0,
  150683. _vq_quantlist__44u8_p1_0,
  150684. NULL,
  150685. &_vq_auxt__44u8_p1_0,
  150686. NULL,
  150687. 0
  150688. };
  150689. static long _vq_quantlist__44u8_p2_0[] = {
  150690. 2,
  150691. 1,
  150692. 3,
  150693. 0,
  150694. 4,
  150695. };
  150696. static long _vq_lengthlist__44u8_p2_0[] = {
  150697. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150698. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  150699. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  150700. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  150701. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  150702. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  150703. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150704. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  150705. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  150706. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  150707. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  150708. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  150709. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  150710. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  150711. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  150712. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  150713. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  150714. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  150715. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  150716. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  150717. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  150718. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  150719. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  150720. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150721. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  150722. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150723. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  150724. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  150725. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  150726. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  150727. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  150728. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150729. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  150730. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  150731. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150732. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  150733. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  150734. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  150735. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  150736. 14,
  150737. };
  150738. static float _vq_quantthresh__44u8_p2_0[] = {
  150739. -1.5, -0.5, 0.5, 1.5,
  150740. };
  150741. static long _vq_quantmap__44u8_p2_0[] = {
  150742. 3, 1, 0, 2, 4,
  150743. };
  150744. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  150745. _vq_quantthresh__44u8_p2_0,
  150746. _vq_quantmap__44u8_p2_0,
  150747. 5,
  150748. 5
  150749. };
  150750. static static_codebook _44u8_p2_0 = {
  150751. 4, 625,
  150752. _vq_lengthlist__44u8_p2_0,
  150753. 1, -533725184, 1611661312, 3, 0,
  150754. _vq_quantlist__44u8_p2_0,
  150755. NULL,
  150756. &_vq_auxt__44u8_p2_0,
  150757. NULL,
  150758. 0
  150759. };
  150760. static long _vq_quantlist__44u8_p3_0[] = {
  150761. 4,
  150762. 3,
  150763. 5,
  150764. 2,
  150765. 6,
  150766. 1,
  150767. 7,
  150768. 0,
  150769. 8,
  150770. };
  150771. static long _vq_lengthlist__44u8_p3_0[] = {
  150772. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150773. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150774. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  150775. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  150776. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  150777. 12,
  150778. };
  150779. static float _vq_quantthresh__44u8_p3_0[] = {
  150780. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150781. };
  150782. static long _vq_quantmap__44u8_p3_0[] = {
  150783. 7, 5, 3, 1, 0, 2, 4, 6,
  150784. 8,
  150785. };
  150786. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  150787. _vq_quantthresh__44u8_p3_0,
  150788. _vq_quantmap__44u8_p3_0,
  150789. 9,
  150790. 9
  150791. };
  150792. static static_codebook _44u8_p3_0 = {
  150793. 2, 81,
  150794. _vq_lengthlist__44u8_p3_0,
  150795. 1, -531628032, 1611661312, 4, 0,
  150796. _vq_quantlist__44u8_p3_0,
  150797. NULL,
  150798. &_vq_auxt__44u8_p3_0,
  150799. NULL,
  150800. 0
  150801. };
  150802. static long _vq_quantlist__44u8_p4_0[] = {
  150803. 8,
  150804. 7,
  150805. 9,
  150806. 6,
  150807. 10,
  150808. 5,
  150809. 11,
  150810. 4,
  150811. 12,
  150812. 3,
  150813. 13,
  150814. 2,
  150815. 14,
  150816. 1,
  150817. 15,
  150818. 0,
  150819. 16,
  150820. };
  150821. static long _vq_lengthlist__44u8_p4_0[] = {
  150822. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  150823. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  150824. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  150825. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  150826. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  150827. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  150828. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  150829. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  150830. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  150831. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  150832. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  150833. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  150834. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  150835. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  150836. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  150837. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  150838. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  150839. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  150840. 14,
  150841. };
  150842. static float _vq_quantthresh__44u8_p4_0[] = {
  150843. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150844. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150845. };
  150846. static long _vq_quantmap__44u8_p4_0[] = {
  150847. 15, 13, 11, 9, 7, 5, 3, 1,
  150848. 0, 2, 4, 6, 8, 10, 12, 14,
  150849. 16,
  150850. };
  150851. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  150852. _vq_quantthresh__44u8_p4_0,
  150853. _vq_quantmap__44u8_p4_0,
  150854. 17,
  150855. 17
  150856. };
  150857. static static_codebook _44u8_p4_0 = {
  150858. 2, 289,
  150859. _vq_lengthlist__44u8_p4_0,
  150860. 1, -529530880, 1611661312, 5, 0,
  150861. _vq_quantlist__44u8_p4_0,
  150862. NULL,
  150863. &_vq_auxt__44u8_p4_0,
  150864. NULL,
  150865. 0
  150866. };
  150867. static long _vq_quantlist__44u8_p5_0[] = {
  150868. 1,
  150869. 0,
  150870. 2,
  150871. };
  150872. static long _vq_lengthlist__44u8_p5_0[] = {
  150873. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  150874. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  150875. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  150876. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  150877. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  150878. 10,
  150879. };
  150880. static float _vq_quantthresh__44u8_p5_0[] = {
  150881. -5.5, 5.5,
  150882. };
  150883. static long _vq_quantmap__44u8_p5_0[] = {
  150884. 1, 0, 2,
  150885. };
  150886. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  150887. _vq_quantthresh__44u8_p5_0,
  150888. _vq_quantmap__44u8_p5_0,
  150889. 3,
  150890. 3
  150891. };
  150892. static static_codebook _44u8_p5_0 = {
  150893. 4, 81,
  150894. _vq_lengthlist__44u8_p5_0,
  150895. 1, -529137664, 1618345984, 2, 0,
  150896. _vq_quantlist__44u8_p5_0,
  150897. NULL,
  150898. &_vq_auxt__44u8_p5_0,
  150899. NULL,
  150900. 0
  150901. };
  150902. static long _vq_quantlist__44u8_p5_1[] = {
  150903. 5,
  150904. 4,
  150905. 6,
  150906. 3,
  150907. 7,
  150908. 2,
  150909. 8,
  150910. 1,
  150911. 9,
  150912. 0,
  150913. 10,
  150914. };
  150915. static long _vq_lengthlist__44u8_p5_1[] = {
  150916. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  150917. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  150918. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  150919. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  150920. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  150921. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150922. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  150923. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  150924. };
  150925. static float _vq_quantthresh__44u8_p5_1[] = {
  150926. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150927. 3.5, 4.5,
  150928. };
  150929. static long _vq_quantmap__44u8_p5_1[] = {
  150930. 9, 7, 5, 3, 1, 0, 2, 4,
  150931. 6, 8, 10,
  150932. };
  150933. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  150934. _vq_quantthresh__44u8_p5_1,
  150935. _vq_quantmap__44u8_p5_1,
  150936. 11,
  150937. 11
  150938. };
  150939. static static_codebook _44u8_p5_1 = {
  150940. 2, 121,
  150941. _vq_lengthlist__44u8_p5_1,
  150942. 1, -531365888, 1611661312, 4, 0,
  150943. _vq_quantlist__44u8_p5_1,
  150944. NULL,
  150945. &_vq_auxt__44u8_p5_1,
  150946. NULL,
  150947. 0
  150948. };
  150949. static long _vq_quantlist__44u8_p6_0[] = {
  150950. 6,
  150951. 5,
  150952. 7,
  150953. 4,
  150954. 8,
  150955. 3,
  150956. 9,
  150957. 2,
  150958. 10,
  150959. 1,
  150960. 11,
  150961. 0,
  150962. 12,
  150963. };
  150964. static long _vq_lengthlist__44u8_p6_0[] = {
  150965. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  150966. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  150967. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  150968. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  150969. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  150970. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  150971. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  150972. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  150973. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  150974. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  150975. 11,11,11,11,11,12,11,12,12,
  150976. };
  150977. static float _vq_quantthresh__44u8_p6_0[] = {
  150978. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  150979. 12.5, 17.5, 22.5, 27.5,
  150980. };
  150981. static long _vq_quantmap__44u8_p6_0[] = {
  150982. 11, 9, 7, 5, 3, 1, 0, 2,
  150983. 4, 6, 8, 10, 12,
  150984. };
  150985. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  150986. _vq_quantthresh__44u8_p6_0,
  150987. _vq_quantmap__44u8_p6_0,
  150988. 13,
  150989. 13
  150990. };
  150991. static static_codebook _44u8_p6_0 = {
  150992. 2, 169,
  150993. _vq_lengthlist__44u8_p6_0,
  150994. 1, -526516224, 1616117760, 4, 0,
  150995. _vq_quantlist__44u8_p6_0,
  150996. NULL,
  150997. &_vq_auxt__44u8_p6_0,
  150998. NULL,
  150999. 0
  151000. };
  151001. static long _vq_quantlist__44u8_p6_1[] = {
  151002. 2,
  151003. 1,
  151004. 3,
  151005. 0,
  151006. 4,
  151007. };
  151008. static long _vq_lengthlist__44u8_p6_1[] = {
  151009. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151010. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151011. };
  151012. static float _vq_quantthresh__44u8_p6_1[] = {
  151013. -1.5, -0.5, 0.5, 1.5,
  151014. };
  151015. static long _vq_quantmap__44u8_p6_1[] = {
  151016. 3, 1, 0, 2, 4,
  151017. };
  151018. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151019. _vq_quantthresh__44u8_p6_1,
  151020. _vq_quantmap__44u8_p6_1,
  151021. 5,
  151022. 5
  151023. };
  151024. static static_codebook _44u8_p6_1 = {
  151025. 2, 25,
  151026. _vq_lengthlist__44u8_p6_1,
  151027. 1, -533725184, 1611661312, 3, 0,
  151028. _vq_quantlist__44u8_p6_1,
  151029. NULL,
  151030. &_vq_auxt__44u8_p6_1,
  151031. NULL,
  151032. 0
  151033. };
  151034. static long _vq_quantlist__44u8_p7_0[] = {
  151035. 6,
  151036. 5,
  151037. 7,
  151038. 4,
  151039. 8,
  151040. 3,
  151041. 9,
  151042. 2,
  151043. 10,
  151044. 1,
  151045. 11,
  151046. 0,
  151047. 12,
  151048. };
  151049. static long _vq_lengthlist__44u8_p7_0[] = {
  151050. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151051. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151052. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151053. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151054. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151055. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151056. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151057. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151058. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151059. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151060. 13,13,14,14,14,15,15,15,16,
  151061. };
  151062. static float _vq_quantthresh__44u8_p7_0[] = {
  151063. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151064. 27.5, 38.5, 49.5, 60.5,
  151065. };
  151066. static long _vq_quantmap__44u8_p7_0[] = {
  151067. 11, 9, 7, 5, 3, 1, 0, 2,
  151068. 4, 6, 8, 10, 12,
  151069. };
  151070. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151071. _vq_quantthresh__44u8_p7_0,
  151072. _vq_quantmap__44u8_p7_0,
  151073. 13,
  151074. 13
  151075. };
  151076. static static_codebook _44u8_p7_0 = {
  151077. 2, 169,
  151078. _vq_lengthlist__44u8_p7_0,
  151079. 1, -523206656, 1618345984, 4, 0,
  151080. _vq_quantlist__44u8_p7_0,
  151081. NULL,
  151082. &_vq_auxt__44u8_p7_0,
  151083. NULL,
  151084. 0
  151085. };
  151086. static long _vq_quantlist__44u8_p7_1[] = {
  151087. 5,
  151088. 4,
  151089. 6,
  151090. 3,
  151091. 7,
  151092. 2,
  151093. 8,
  151094. 1,
  151095. 9,
  151096. 0,
  151097. 10,
  151098. };
  151099. static long _vq_lengthlist__44u8_p7_1[] = {
  151100. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151101. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151102. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151103. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151104. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151105. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151106. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151107. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151108. };
  151109. static float _vq_quantthresh__44u8_p7_1[] = {
  151110. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151111. 3.5, 4.5,
  151112. };
  151113. static long _vq_quantmap__44u8_p7_1[] = {
  151114. 9, 7, 5, 3, 1, 0, 2, 4,
  151115. 6, 8, 10,
  151116. };
  151117. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151118. _vq_quantthresh__44u8_p7_1,
  151119. _vq_quantmap__44u8_p7_1,
  151120. 11,
  151121. 11
  151122. };
  151123. static static_codebook _44u8_p7_1 = {
  151124. 2, 121,
  151125. _vq_lengthlist__44u8_p7_1,
  151126. 1, -531365888, 1611661312, 4, 0,
  151127. _vq_quantlist__44u8_p7_1,
  151128. NULL,
  151129. &_vq_auxt__44u8_p7_1,
  151130. NULL,
  151131. 0
  151132. };
  151133. static long _vq_quantlist__44u8_p8_0[] = {
  151134. 7,
  151135. 6,
  151136. 8,
  151137. 5,
  151138. 9,
  151139. 4,
  151140. 10,
  151141. 3,
  151142. 11,
  151143. 2,
  151144. 12,
  151145. 1,
  151146. 13,
  151147. 0,
  151148. 14,
  151149. };
  151150. static long _vq_lengthlist__44u8_p8_0[] = {
  151151. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151152. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151153. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151154. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151155. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151156. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151157. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151158. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151159. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151160. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151161. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151162. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151163. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151164. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151165. 17,
  151166. };
  151167. static float _vq_quantthresh__44u8_p8_0[] = {
  151168. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151169. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151170. };
  151171. static long _vq_quantmap__44u8_p8_0[] = {
  151172. 13, 11, 9, 7, 5, 3, 1, 0,
  151173. 2, 4, 6, 8, 10, 12, 14,
  151174. };
  151175. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151176. _vq_quantthresh__44u8_p8_0,
  151177. _vq_quantmap__44u8_p8_0,
  151178. 15,
  151179. 15
  151180. };
  151181. static static_codebook _44u8_p8_0 = {
  151182. 2, 225,
  151183. _vq_lengthlist__44u8_p8_0,
  151184. 1, -520986624, 1620377600, 4, 0,
  151185. _vq_quantlist__44u8_p8_0,
  151186. NULL,
  151187. &_vq_auxt__44u8_p8_0,
  151188. NULL,
  151189. 0
  151190. };
  151191. static long _vq_quantlist__44u8_p8_1[] = {
  151192. 10,
  151193. 9,
  151194. 11,
  151195. 8,
  151196. 12,
  151197. 7,
  151198. 13,
  151199. 6,
  151200. 14,
  151201. 5,
  151202. 15,
  151203. 4,
  151204. 16,
  151205. 3,
  151206. 17,
  151207. 2,
  151208. 18,
  151209. 1,
  151210. 19,
  151211. 0,
  151212. 20,
  151213. };
  151214. static long _vq_lengthlist__44u8_p8_1[] = {
  151215. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151216. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151217. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151218. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151219. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151220. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151221. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151222. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151223. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151224. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151225. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151226. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151227. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151228. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151229. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151230. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151231. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151232. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151233. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151234. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151235. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151236. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151237. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151238. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151239. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151240. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151241. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151242. 10,10,10,10,10,10,10,10,10,
  151243. };
  151244. static float _vq_quantthresh__44u8_p8_1[] = {
  151245. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151246. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151247. 6.5, 7.5, 8.5, 9.5,
  151248. };
  151249. static long _vq_quantmap__44u8_p8_1[] = {
  151250. 19, 17, 15, 13, 11, 9, 7, 5,
  151251. 3, 1, 0, 2, 4, 6, 8, 10,
  151252. 12, 14, 16, 18, 20,
  151253. };
  151254. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151255. _vq_quantthresh__44u8_p8_1,
  151256. _vq_quantmap__44u8_p8_1,
  151257. 21,
  151258. 21
  151259. };
  151260. static static_codebook _44u8_p8_1 = {
  151261. 2, 441,
  151262. _vq_lengthlist__44u8_p8_1,
  151263. 1, -529268736, 1611661312, 5, 0,
  151264. _vq_quantlist__44u8_p8_1,
  151265. NULL,
  151266. &_vq_auxt__44u8_p8_1,
  151267. NULL,
  151268. 0
  151269. };
  151270. static long _vq_quantlist__44u8_p9_0[] = {
  151271. 4,
  151272. 3,
  151273. 5,
  151274. 2,
  151275. 6,
  151276. 1,
  151277. 7,
  151278. 0,
  151279. 8,
  151280. };
  151281. static long _vq_lengthlist__44u8_p9_0[] = {
  151282. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151283. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151284. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151285. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151286. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151287. 8,
  151288. };
  151289. static float _vq_quantthresh__44u8_p9_0[] = {
  151290. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151291. };
  151292. static long _vq_quantmap__44u8_p9_0[] = {
  151293. 7, 5, 3, 1, 0, 2, 4, 6,
  151294. 8,
  151295. };
  151296. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151297. _vq_quantthresh__44u8_p9_0,
  151298. _vq_quantmap__44u8_p9_0,
  151299. 9,
  151300. 9
  151301. };
  151302. static static_codebook _44u8_p9_0 = {
  151303. 2, 81,
  151304. _vq_lengthlist__44u8_p9_0,
  151305. 1, -511895552, 1631393792, 4, 0,
  151306. _vq_quantlist__44u8_p9_0,
  151307. NULL,
  151308. &_vq_auxt__44u8_p9_0,
  151309. NULL,
  151310. 0
  151311. };
  151312. static long _vq_quantlist__44u8_p9_1[] = {
  151313. 9,
  151314. 8,
  151315. 10,
  151316. 7,
  151317. 11,
  151318. 6,
  151319. 12,
  151320. 5,
  151321. 13,
  151322. 4,
  151323. 14,
  151324. 3,
  151325. 15,
  151326. 2,
  151327. 16,
  151328. 1,
  151329. 17,
  151330. 0,
  151331. 18,
  151332. };
  151333. static long _vq_lengthlist__44u8_p9_1[] = {
  151334. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151335. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151336. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151337. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151338. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151339. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151340. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151341. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151342. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151343. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151344. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151345. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151346. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151347. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151348. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151349. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151350. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151351. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151352. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151353. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151354. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151355. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151356. 16,15,16,16,16,16,16,16,16,
  151357. };
  151358. static float _vq_quantthresh__44u8_p9_1[] = {
  151359. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151360. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151361. 367.5, 416.5,
  151362. };
  151363. static long _vq_quantmap__44u8_p9_1[] = {
  151364. 17, 15, 13, 11, 9, 7, 5, 3,
  151365. 1, 0, 2, 4, 6, 8, 10, 12,
  151366. 14, 16, 18,
  151367. };
  151368. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151369. _vq_quantthresh__44u8_p9_1,
  151370. _vq_quantmap__44u8_p9_1,
  151371. 19,
  151372. 19
  151373. };
  151374. static static_codebook _44u8_p9_1 = {
  151375. 2, 361,
  151376. _vq_lengthlist__44u8_p9_1,
  151377. 1, -518287360, 1622704128, 5, 0,
  151378. _vq_quantlist__44u8_p9_1,
  151379. NULL,
  151380. &_vq_auxt__44u8_p9_1,
  151381. NULL,
  151382. 0
  151383. };
  151384. static long _vq_quantlist__44u8_p9_2[] = {
  151385. 24,
  151386. 23,
  151387. 25,
  151388. 22,
  151389. 26,
  151390. 21,
  151391. 27,
  151392. 20,
  151393. 28,
  151394. 19,
  151395. 29,
  151396. 18,
  151397. 30,
  151398. 17,
  151399. 31,
  151400. 16,
  151401. 32,
  151402. 15,
  151403. 33,
  151404. 14,
  151405. 34,
  151406. 13,
  151407. 35,
  151408. 12,
  151409. 36,
  151410. 11,
  151411. 37,
  151412. 10,
  151413. 38,
  151414. 9,
  151415. 39,
  151416. 8,
  151417. 40,
  151418. 7,
  151419. 41,
  151420. 6,
  151421. 42,
  151422. 5,
  151423. 43,
  151424. 4,
  151425. 44,
  151426. 3,
  151427. 45,
  151428. 2,
  151429. 46,
  151430. 1,
  151431. 47,
  151432. 0,
  151433. 48,
  151434. };
  151435. static long _vq_lengthlist__44u8_p9_2[] = {
  151436. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151437. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151438. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151439. 7,
  151440. };
  151441. static float _vq_quantthresh__44u8_p9_2[] = {
  151442. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151443. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151444. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151445. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151446. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151447. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151448. };
  151449. static long _vq_quantmap__44u8_p9_2[] = {
  151450. 47, 45, 43, 41, 39, 37, 35, 33,
  151451. 31, 29, 27, 25, 23, 21, 19, 17,
  151452. 15, 13, 11, 9, 7, 5, 3, 1,
  151453. 0, 2, 4, 6, 8, 10, 12, 14,
  151454. 16, 18, 20, 22, 24, 26, 28, 30,
  151455. 32, 34, 36, 38, 40, 42, 44, 46,
  151456. 48,
  151457. };
  151458. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151459. _vq_quantthresh__44u8_p9_2,
  151460. _vq_quantmap__44u8_p9_2,
  151461. 49,
  151462. 49
  151463. };
  151464. static static_codebook _44u8_p9_2 = {
  151465. 1, 49,
  151466. _vq_lengthlist__44u8_p9_2,
  151467. 1, -526909440, 1611661312, 6, 0,
  151468. _vq_quantlist__44u8_p9_2,
  151469. NULL,
  151470. &_vq_auxt__44u8_p9_2,
  151471. NULL,
  151472. 0
  151473. };
  151474. static long _huff_lengthlist__44u9__long[] = {
  151475. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151476. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151477. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151478. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151479. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151480. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151481. 10, 8, 8, 9,
  151482. };
  151483. static static_codebook _huff_book__44u9__long = {
  151484. 2, 100,
  151485. _huff_lengthlist__44u9__long,
  151486. 0, 0, 0, 0, 0,
  151487. NULL,
  151488. NULL,
  151489. NULL,
  151490. NULL,
  151491. 0
  151492. };
  151493. static long _huff_lengthlist__44u9__short[] = {
  151494. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151495. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151496. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151497. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151498. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151499. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151500. 9, 9,12,15,
  151501. };
  151502. static static_codebook _huff_book__44u9__short = {
  151503. 2, 100,
  151504. _huff_lengthlist__44u9__short,
  151505. 0, 0, 0, 0, 0,
  151506. NULL,
  151507. NULL,
  151508. NULL,
  151509. NULL,
  151510. 0
  151511. };
  151512. static long _vq_quantlist__44u9_p1_0[] = {
  151513. 1,
  151514. 0,
  151515. 2,
  151516. };
  151517. static long _vq_lengthlist__44u9_p1_0[] = {
  151518. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151519. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151520. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151521. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151522. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151523. 10,
  151524. };
  151525. static float _vq_quantthresh__44u9_p1_0[] = {
  151526. -0.5, 0.5,
  151527. };
  151528. static long _vq_quantmap__44u9_p1_0[] = {
  151529. 1, 0, 2,
  151530. };
  151531. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151532. _vq_quantthresh__44u9_p1_0,
  151533. _vq_quantmap__44u9_p1_0,
  151534. 3,
  151535. 3
  151536. };
  151537. static static_codebook _44u9_p1_0 = {
  151538. 4, 81,
  151539. _vq_lengthlist__44u9_p1_0,
  151540. 1, -535822336, 1611661312, 2, 0,
  151541. _vq_quantlist__44u9_p1_0,
  151542. NULL,
  151543. &_vq_auxt__44u9_p1_0,
  151544. NULL,
  151545. 0
  151546. };
  151547. static long _vq_quantlist__44u9_p2_0[] = {
  151548. 2,
  151549. 1,
  151550. 3,
  151551. 0,
  151552. 4,
  151553. };
  151554. static long _vq_lengthlist__44u9_p2_0[] = {
  151555. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151556. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151557. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151558. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151559. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151560. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151561. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151562. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151563. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151564. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151565. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151566. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151567. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151568. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151569. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151570. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151571. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151572. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151573. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151574. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151575. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151576. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151577. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151578. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151579. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151580. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151581. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151582. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151583. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151584. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151585. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151586. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151587. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151588. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151589. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151590. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151591. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151592. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151593. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151594. 14,
  151595. };
  151596. static float _vq_quantthresh__44u9_p2_0[] = {
  151597. -1.5, -0.5, 0.5, 1.5,
  151598. };
  151599. static long _vq_quantmap__44u9_p2_0[] = {
  151600. 3, 1, 0, 2, 4,
  151601. };
  151602. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151603. _vq_quantthresh__44u9_p2_0,
  151604. _vq_quantmap__44u9_p2_0,
  151605. 5,
  151606. 5
  151607. };
  151608. static static_codebook _44u9_p2_0 = {
  151609. 4, 625,
  151610. _vq_lengthlist__44u9_p2_0,
  151611. 1, -533725184, 1611661312, 3, 0,
  151612. _vq_quantlist__44u9_p2_0,
  151613. NULL,
  151614. &_vq_auxt__44u9_p2_0,
  151615. NULL,
  151616. 0
  151617. };
  151618. static long _vq_quantlist__44u9_p3_0[] = {
  151619. 4,
  151620. 3,
  151621. 5,
  151622. 2,
  151623. 6,
  151624. 1,
  151625. 7,
  151626. 0,
  151627. 8,
  151628. };
  151629. static long _vq_lengthlist__44u9_p3_0[] = {
  151630. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151631. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151632. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151633. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151634. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151635. 11,
  151636. };
  151637. static float _vq_quantthresh__44u9_p3_0[] = {
  151638. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151639. };
  151640. static long _vq_quantmap__44u9_p3_0[] = {
  151641. 7, 5, 3, 1, 0, 2, 4, 6,
  151642. 8,
  151643. };
  151644. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151645. _vq_quantthresh__44u9_p3_0,
  151646. _vq_quantmap__44u9_p3_0,
  151647. 9,
  151648. 9
  151649. };
  151650. static static_codebook _44u9_p3_0 = {
  151651. 2, 81,
  151652. _vq_lengthlist__44u9_p3_0,
  151653. 1, -531628032, 1611661312, 4, 0,
  151654. _vq_quantlist__44u9_p3_0,
  151655. NULL,
  151656. &_vq_auxt__44u9_p3_0,
  151657. NULL,
  151658. 0
  151659. };
  151660. static long _vq_quantlist__44u9_p4_0[] = {
  151661. 8,
  151662. 7,
  151663. 9,
  151664. 6,
  151665. 10,
  151666. 5,
  151667. 11,
  151668. 4,
  151669. 12,
  151670. 3,
  151671. 13,
  151672. 2,
  151673. 14,
  151674. 1,
  151675. 15,
  151676. 0,
  151677. 16,
  151678. };
  151679. static long _vq_lengthlist__44u9_p4_0[] = {
  151680. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  151681. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  151682. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  151683. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  151684. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  151685. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  151686. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  151687. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  151688. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  151689. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  151690. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  151691. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  151692. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  151693. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  151694. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  151695. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  151696. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  151697. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  151698. 14,
  151699. };
  151700. static float _vq_quantthresh__44u9_p4_0[] = {
  151701. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151702. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151703. };
  151704. static long _vq_quantmap__44u9_p4_0[] = {
  151705. 15, 13, 11, 9, 7, 5, 3, 1,
  151706. 0, 2, 4, 6, 8, 10, 12, 14,
  151707. 16,
  151708. };
  151709. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  151710. _vq_quantthresh__44u9_p4_0,
  151711. _vq_quantmap__44u9_p4_0,
  151712. 17,
  151713. 17
  151714. };
  151715. static static_codebook _44u9_p4_0 = {
  151716. 2, 289,
  151717. _vq_lengthlist__44u9_p4_0,
  151718. 1, -529530880, 1611661312, 5, 0,
  151719. _vq_quantlist__44u9_p4_0,
  151720. NULL,
  151721. &_vq_auxt__44u9_p4_0,
  151722. NULL,
  151723. 0
  151724. };
  151725. static long _vq_quantlist__44u9_p5_0[] = {
  151726. 1,
  151727. 0,
  151728. 2,
  151729. };
  151730. static long _vq_lengthlist__44u9_p5_0[] = {
  151731. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151732. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151733. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  151734. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151735. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151736. 10,
  151737. };
  151738. static float _vq_quantthresh__44u9_p5_0[] = {
  151739. -5.5, 5.5,
  151740. };
  151741. static long _vq_quantmap__44u9_p5_0[] = {
  151742. 1, 0, 2,
  151743. };
  151744. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  151745. _vq_quantthresh__44u9_p5_0,
  151746. _vq_quantmap__44u9_p5_0,
  151747. 3,
  151748. 3
  151749. };
  151750. static static_codebook _44u9_p5_0 = {
  151751. 4, 81,
  151752. _vq_lengthlist__44u9_p5_0,
  151753. 1, -529137664, 1618345984, 2, 0,
  151754. _vq_quantlist__44u9_p5_0,
  151755. NULL,
  151756. &_vq_auxt__44u9_p5_0,
  151757. NULL,
  151758. 0
  151759. };
  151760. static long _vq_quantlist__44u9_p5_1[] = {
  151761. 5,
  151762. 4,
  151763. 6,
  151764. 3,
  151765. 7,
  151766. 2,
  151767. 8,
  151768. 1,
  151769. 9,
  151770. 0,
  151771. 10,
  151772. };
  151773. static long _vq_lengthlist__44u9_p5_1[] = {
  151774. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  151775. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  151776. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  151777. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151778. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151779. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  151780. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  151781. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151782. };
  151783. static float _vq_quantthresh__44u9_p5_1[] = {
  151784. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151785. 3.5, 4.5,
  151786. };
  151787. static long _vq_quantmap__44u9_p5_1[] = {
  151788. 9, 7, 5, 3, 1, 0, 2, 4,
  151789. 6, 8, 10,
  151790. };
  151791. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  151792. _vq_quantthresh__44u9_p5_1,
  151793. _vq_quantmap__44u9_p5_1,
  151794. 11,
  151795. 11
  151796. };
  151797. static static_codebook _44u9_p5_1 = {
  151798. 2, 121,
  151799. _vq_lengthlist__44u9_p5_1,
  151800. 1, -531365888, 1611661312, 4, 0,
  151801. _vq_quantlist__44u9_p5_1,
  151802. NULL,
  151803. &_vq_auxt__44u9_p5_1,
  151804. NULL,
  151805. 0
  151806. };
  151807. static long _vq_quantlist__44u9_p6_0[] = {
  151808. 6,
  151809. 5,
  151810. 7,
  151811. 4,
  151812. 8,
  151813. 3,
  151814. 9,
  151815. 2,
  151816. 10,
  151817. 1,
  151818. 11,
  151819. 0,
  151820. 12,
  151821. };
  151822. static long _vq_lengthlist__44u9_p6_0[] = {
  151823. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151824. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  151825. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151826. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  151827. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  151828. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151829. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151830. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  151831. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  151832. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151833. 10,11,11,11,11,12,11,12,12,
  151834. };
  151835. static float _vq_quantthresh__44u9_p6_0[] = {
  151836. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151837. 12.5, 17.5, 22.5, 27.5,
  151838. };
  151839. static long _vq_quantmap__44u9_p6_0[] = {
  151840. 11, 9, 7, 5, 3, 1, 0, 2,
  151841. 4, 6, 8, 10, 12,
  151842. };
  151843. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  151844. _vq_quantthresh__44u9_p6_0,
  151845. _vq_quantmap__44u9_p6_0,
  151846. 13,
  151847. 13
  151848. };
  151849. static static_codebook _44u9_p6_0 = {
  151850. 2, 169,
  151851. _vq_lengthlist__44u9_p6_0,
  151852. 1, -526516224, 1616117760, 4, 0,
  151853. _vq_quantlist__44u9_p6_0,
  151854. NULL,
  151855. &_vq_auxt__44u9_p6_0,
  151856. NULL,
  151857. 0
  151858. };
  151859. static long _vq_quantlist__44u9_p6_1[] = {
  151860. 2,
  151861. 1,
  151862. 3,
  151863. 0,
  151864. 4,
  151865. };
  151866. static long _vq_lengthlist__44u9_p6_1[] = {
  151867. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  151868. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151869. };
  151870. static float _vq_quantthresh__44u9_p6_1[] = {
  151871. -1.5, -0.5, 0.5, 1.5,
  151872. };
  151873. static long _vq_quantmap__44u9_p6_1[] = {
  151874. 3, 1, 0, 2, 4,
  151875. };
  151876. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  151877. _vq_quantthresh__44u9_p6_1,
  151878. _vq_quantmap__44u9_p6_1,
  151879. 5,
  151880. 5
  151881. };
  151882. static static_codebook _44u9_p6_1 = {
  151883. 2, 25,
  151884. _vq_lengthlist__44u9_p6_1,
  151885. 1, -533725184, 1611661312, 3, 0,
  151886. _vq_quantlist__44u9_p6_1,
  151887. NULL,
  151888. &_vq_auxt__44u9_p6_1,
  151889. NULL,
  151890. 0
  151891. };
  151892. static long _vq_quantlist__44u9_p7_0[] = {
  151893. 6,
  151894. 5,
  151895. 7,
  151896. 4,
  151897. 8,
  151898. 3,
  151899. 9,
  151900. 2,
  151901. 10,
  151902. 1,
  151903. 11,
  151904. 0,
  151905. 12,
  151906. };
  151907. static long _vq_lengthlist__44u9_p7_0[] = {
  151908. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  151909. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  151910. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  151911. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  151912. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151913. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151914. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  151915. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  151916. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  151917. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  151918. 12,13,13,14,14,14,15,15,15,
  151919. };
  151920. static float _vq_quantthresh__44u9_p7_0[] = {
  151921. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151922. 27.5, 38.5, 49.5, 60.5,
  151923. };
  151924. static long _vq_quantmap__44u9_p7_0[] = {
  151925. 11, 9, 7, 5, 3, 1, 0, 2,
  151926. 4, 6, 8, 10, 12,
  151927. };
  151928. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  151929. _vq_quantthresh__44u9_p7_0,
  151930. _vq_quantmap__44u9_p7_0,
  151931. 13,
  151932. 13
  151933. };
  151934. static static_codebook _44u9_p7_0 = {
  151935. 2, 169,
  151936. _vq_lengthlist__44u9_p7_0,
  151937. 1, -523206656, 1618345984, 4, 0,
  151938. _vq_quantlist__44u9_p7_0,
  151939. NULL,
  151940. &_vq_auxt__44u9_p7_0,
  151941. NULL,
  151942. 0
  151943. };
  151944. static long _vq_quantlist__44u9_p7_1[] = {
  151945. 5,
  151946. 4,
  151947. 6,
  151948. 3,
  151949. 7,
  151950. 2,
  151951. 8,
  151952. 1,
  151953. 9,
  151954. 0,
  151955. 10,
  151956. };
  151957. static long _vq_lengthlist__44u9_p7_1[] = {
  151958. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  151959. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151960. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  151961. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151962. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151963. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151964. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  151965. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151966. };
  151967. static float _vq_quantthresh__44u9_p7_1[] = {
  151968. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151969. 3.5, 4.5,
  151970. };
  151971. static long _vq_quantmap__44u9_p7_1[] = {
  151972. 9, 7, 5, 3, 1, 0, 2, 4,
  151973. 6, 8, 10,
  151974. };
  151975. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  151976. _vq_quantthresh__44u9_p7_1,
  151977. _vq_quantmap__44u9_p7_1,
  151978. 11,
  151979. 11
  151980. };
  151981. static static_codebook _44u9_p7_1 = {
  151982. 2, 121,
  151983. _vq_lengthlist__44u9_p7_1,
  151984. 1, -531365888, 1611661312, 4, 0,
  151985. _vq_quantlist__44u9_p7_1,
  151986. NULL,
  151987. &_vq_auxt__44u9_p7_1,
  151988. NULL,
  151989. 0
  151990. };
  151991. static long _vq_quantlist__44u9_p8_0[] = {
  151992. 7,
  151993. 6,
  151994. 8,
  151995. 5,
  151996. 9,
  151997. 4,
  151998. 10,
  151999. 3,
  152000. 11,
  152001. 2,
  152002. 12,
  152003. 1,
  152004. 13,
  152005. 0,
  152006. 14,
  152007. };
  152008. static long _vq_lengthlist__44u9_p8_0[] = {
  152009. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152010. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152011. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152012. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152013. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152014. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152015. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152016. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152017. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152018. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152019. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152020. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152021. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152022. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152023. 15,
  152024. };
  152025. static float _vq_quantthresh__44u9_p8_0[] = {
  152026. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152027. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152028. };
  152029. static long _vq_quantmap__44u9_p8_0[] = {
  152030. 13, 11, 9, 7, 5, 3, 1, 0,
  152031. 2, 4, 6, 8, 10, 12, 14,
  152032. };
  152033. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152034. _vq_quantthresh__44u9_p8_0,
  152035. _vq_quantmap__44u9_p8_0,
  152036. 15,
  152037. 15
  152038. };
  152039. static static_codebook _44u9_p8_0 = {
  152040. 2, 225,
  152041. _vq_lengthlist__44u9_p8_0,
  152042. 1, -520986624, 1620377600, 4, 0,
  152043. _vq_quantlist__44u9_p8_0,
  152044. NULL,
  152045. &_vq_auxt__44u9_p8_0,
  152046. NULL,
  152047. 0
  152048. };
  152049. static long _vq_quantlist__44u9_p8_1[] = {
  152050. 10,
  152051. 9,
  152052. 11,
  152053. 8,
  152054. 12,
  152055. 7,
  152056. 13,
  152057. 6,
  152058. 14,
  152059. 5,
  152060. 15,
  152061. 4,
  152062. 16,
  152063. 3,
  152064. 17,
  152065. 2,
  152066. 18,
  152067. 1,
  152068. 19,
  152069. 0,
  152070. 20,
  152071. };
  152072. static long _vq_lengthlist__44u9_p8_1[] = {
  152073. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152074. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152075. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152076. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152077. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152078. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152080. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152081. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152082. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152083. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152084. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152085. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152086. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152087. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152088. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152089. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152090. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152091. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152092. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152094. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152095. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152096. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152098. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152099. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152100. 10,10,10,10,10,10,10,10,10,
  152101. };
  152102. static float _vq_quantthresh__44u9_p8_1[] = {
  152103. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152104. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152105. 6.5, 7.5, 8.5, 9.5,
  152106. };
  152107. static long _vq_quantmap__44u9_p8_1[] = {
  152108. 19, 17, 15, 13, 11, 9, 7, 5,
  152109. 3, 1, 0, 2, 4, 6, 8, 10,
  152110. 12, 14, 16, 18, 20,
  152111. };
  152112. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152113. _vq_quantthresh__44u9_p8_1,
  152114. _vq_quantmap__44u9_p8_1,
  152115. 21,
  152116. 21
  152117. };
  152118. static static_codebook _44u9_p8_1 = {
  152119. 2, 441,
  152120. _vq_lengthlist__44u9_p8_1,
  152121. 1, -529268736, 1611661312, 5, 0,
  152122. _vq_quantlist__44u9_p8_1,
  152123. NULL,
  152124. &_vq_auxt__44u9_p8_1,
  152125. NULL,
  152126. 0
  152127. };
  152128. static long _vq_quantlist__44u9_p9_0[] = {
  152129. 7,
  152130. 6,
  152131. 8,
  152132. 5,
  152133. 9,
  152134. 4,
  152135. 10,
  152136. 3,
  152137. 11,
  152138. 2,
  152139. 12,
  152140. 1,
  152141. 13,
  152142. 0,
  152143. 14,
  152144. };
  152145. static long _vq_lengthlist__44u9_p9_0[] = {
  152146. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152147. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152148. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152151. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152152. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152159. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152160. 10,
  152161. };
  152162. static float _vq_quantthresh__44u9_p9_0[] = {
  152163. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152164. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152165. };
  152166. static long _vq_quantmap__44u9_p9_0[] = {
  152167. 13, 11, 9, 7, 5, 3, 1, 0,
  152168. 2, 4, 6, 8, 10, 12, 14,
  152169. };
  152170. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152171. _vq_quantthresh__44u9_p9_0,
  152172. _vq_quantmap__44u9_p9_0,
  152173. 15,
  152174. 15
  152175. };
  152176. static static_codebook _44u9_p9_0 = {
  152177. 2, 225,
  152178. _vq_lengthlist__44u9_p9_0,
  152179. 1, -510036736, 1631393792, 4, 0,
  152180. _vq_quantlist__44u9_p9_0,
  152181. NULL,
  152182. &_vq_auxt__44u9_p9_0,
  152183. NULL,
  152184. 0
  152185. };
  152186. static long _vq_quantlist__44u9_p9_1[] = {
  152187. 9,
  152188. 8,
  152189. 10,
  152190. 7,
  152191. 11,
  152192. 6,
  152193. 12,
  152194. 5,
  152195. 13,
  152196. 4,
  152197. 14,
  152198. 3,
  152199. 15,
  152200. 2,
  152201. 16,
  152202. 1,
  152203. 17,
  152204. 0,
  152205. 18,
  152206. };
  152207. static long _vq_lengthlist__44u9_p9_1[] = {
  152208. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152209. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152210. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152211. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152212. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152213. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152214. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152215. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152216. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152217. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152218. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152219. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152220. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152221. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152222. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152223. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152224. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152225. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152226. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152227. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152228. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152229. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152230. 17,17,15,17,15,17,16,16,17,
  152231. };
  152232. static float _vq_quantthresh__44u9_p9_1[] = {
  152233. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152234. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152235. 367.5, 416.5,
  152236. };
  152237. static long _vq_quantmap__44u9_p9_1[] = {
  152238. 17, 15, 13, 11, 9, 7, 5, 3,
  152239. 1, 0, 2, 4, 6, 8, 10, 12,
  152240. 14, 16, 18,
  152241. };
  152242. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152243. _vq_quantthresh__44u9_p9_1,
  152244. _vq_quantmap__44u9_p9_1,
  152245. 19,
  152246. 19
  152247. };
  152248. static static_codebook _44u9_p9_1 = {
  152249. 2, 361,
  152250. _vq_lengthlist__44u9_p9_1,
  152251. 1, -518287360, 1622704128, 5, 0,
  152252. _vq_quantlist__44u9_p9_1,
  152253. NULL,
  152254. &_vq_auxt__44u9_p9_1,
  152255. NULL,
  152256. 0
  152257. };
  152258. static long _vq_quantlist__44u9_p9_2[] = {
  152259. 24,
  152260. 23,
  152261. 25,
  152262. 22,
  152263. 26,
  152264. 21,
  152265. 27,
  152266. 20,
  152267. 28,
  152268. 19,
  152269. 29,
  152270. 18,
  152271. 30,
  152272. 17,
  152273. 31,
  152274. 16,
  152275. 32,
  152276. 15,
  152277. 33,
  152278. 14,
  152279. 34,
  152280. 13,
  152281. 35,
  152282. 12,
  152283. 36,
  152284. 11,
  152285. 37,
  152286. 10,
  152287. 38,
  152288. 9,
  152289. 39,
  152290. 8,
  152291. 40,
  152292. 7,
  152293. 41,
  152294. 6,
  152295. 42,
  152296. 5,
  152297. 43,
  152298. 4,
  152299. 44,
  152300. 3,
  152301. 45,
  152302. 2,
  152303. 46,
  152304. 1,
  152305. 47,
  152306. 0,
  152307. 48,
  152308. };
  152309. static long _vq_lengthlist__44u9_p9_2[] = {
  152310. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152311. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152312. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152313. 7,
  152314. };
  152315. static float _vq_quantthresh__44u9_p9_2[] = {
  152316. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152317. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152318. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152319. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152320. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152321. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152322. };
  152323. static long _vq_quantmap__44u9_p9_2[] = {
  152324. 47, 45, 43, 41, 39, 37, 35, 33,
  152325. 31, 29, 27, 25, 23, 21, 19, 17,
  152326. 15, 13, 11, 9, 7, 5, 3, 1,
  152327. 0, 2, 4, 6, 8, 10, 12, 14,
  152328. 16, 18, 20, 22, 24, 26, 28, 30,
  152329. 32, 34, 36, 38, 40, 42, 44, 46,
  152330. 48,
  152331. };
  152332. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152333. _vq_quantthresh__44u9_p9_2,
  152334. _vq_quantmap__44u9_p9_2,
  152335. 49,
  152336. 49
  152337. };
  152338. static static_codebook _44u9_p9_2 = {
  152339. 1, 49,
  152340. _vq_lengthlist__44u9_p9_2,
  152341. 1, -526909440, 1611661312, 6, 0,
  152342. _vq_quantlist__44u9_p9_2,
  152343. NULL,
  152344. &_vq_auxt__44u9_p9_2,
  152345. NULL,
  152346. 0
  152347. };
  152348. static long _huff_lengthlist__44un1__long[] = {
  152349. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152350. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152351. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152352. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152353. };
  152354. static static_codebook _huff_book__44un1__long = {
  152355. 2, 64,
  152356. _huff_lengthlist__44un1__long,
  152357. 0, 0, 0, 0, 0,
  152358. NULL,
  152359. NULL,
  152360. NULL,
  152361. NULL,
  152362. 0
  152363. };
  152364. static long _vq_quantlist__44un1__p1_0[] = {
  152365. 1,
  152366. 0,
  152367. 2,
  152368. };
  152369. static long _vq_lengthlist__44un1__p1_0[] = {
  152370. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152371. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152372. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152373. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152374. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152375. 12,
  152376. };
  152377. static float _vq_quantthresh__44un1__p1_0[] = {
  152378. -0.5, 0.5,
  152379. };
  152380. static long _vq_quantmap__44un1__p1_0[] = {
  152381. 1, 0, 2,
  152382. };
  152383. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152384. _vq_quantthresh__44un1__p1_0,
  152385. _vq_quantmap__44un1__p1_0,
  152386. 3,
  152387. 3
  152388. };
  152389. static static_codebook _44un1__p1_0 = {
  152390. 4, 81,
  152391. _vq_lengthlist__44un1__p1_0,
  152392. 1, -535822336, 1611661312, 2, 0,
  152393. _vq_quantlist__44un1__p1_0,
  152394. NULL,
  152395. &_vq_auxt__44un1__p1_0,
  152396. NULL,
  152397. 0
  152398. };
  152399. static long _vq_quantlist__44un1__p2_0[] = {
  152400. 1,
  152401. 0,
  152402. 2,
  152403. };
  152404. static long _vq_lengthlist__44un1__p2_0[] = {
  152405. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152406. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152407. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152408. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152409. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152410. 8,
  152411. };
  152412. static float _vq_quantthresh__44un1__p2_0[] = {
  152413. -0.5, 0.5,
  152414. };
  152415. static long _vq_quantmap__44un1__p2_0[] = {
  152416. 1, 0, 2,
  152417. };
  152418. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152419. _vq_quantthresh__44un1__p2_0,
  152420. _vq_quantmap__44un1__p2_0,
  152421. 3,
  152422. 3
  152423. };
  152424. static static_codebook _44un1__p2_0 = {
  152425. 4, 81,
  152426. _vq_lengthlist__44un1__p2_0,
  152427. 1, -535822336, 1611661312, 2, 0,
  152428. _vq_quantlist__44un1__p2_0,
  152429. NULL,
  152430. &_vq_auxt__44un1__p2_0,
  152431. NULL,
  152432. 0
  152433. };
  152434. static long _vq_quantlist__44un1__p3_0[] = {
  152435. 2,
  152436. 1,
  152437. 3,
  152438. 0,
  152439. 4,
  152440. };
  152441. static long _vq_lengthlist__44un1__p3_0[] = {
  152442. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152443. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152444. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152445. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152446. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152447. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152448. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152449. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152450. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152451. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152452. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152453. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152454. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152455. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152456. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152457. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152458. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152459. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152460. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152461. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152462. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152463. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152464. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152465. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152466. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152467. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152468. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152469. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152470. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152471. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152472. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152473. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152474. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152475. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152476. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152477. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152478. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152479. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152480. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152481. 17,
  152482. };
  152483. static float _vq_quantthresh__44un1__p3_0[] = {
  152484. -1.5, -0.5, 0.5, 1.5,
  152485. };
  152486. static long _vq_quantmap__44un1__p3_0[] = {
  152487. 3, 1, 0, 2, 4,
  152488. };
  152489. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152490. _vq_quantthresh__44un1__p3_0,
  152491. _vq_quantmap__44un1__p3_0,
  152492. 5,
  152493. 5
  152494. };
  152495. static static_codebook _44un1__p3_0 = {
  152496. 4, 625,
  152497. _vq_lengthlist__44un1__p3_0,
  152498. 1, -533725184, 1611661312, 3, 0,
  152499. _vq_quantlist__44un1__p3_0,
  152500. NULL,
  152501. &_vq_auxt__44un1__p3_0,
  152502. NULL,
  152503. 0
  152504. };
  152505. static long _vq_quantlist__44un1__p4_0[] = {
  152506. 2,
  152507. 1,
  152508. 3,
  152509. 0,
  152510. 4,
  152511. };
  152512. static long _vq_lengthlist__44un1__p4_0[] = {
  152513. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152514. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152515. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152516. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152517. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152518. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152519. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152520. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152521. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152522. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152523. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152524. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152525. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152526. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152527. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152528. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152529. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152530. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152531. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152532. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152533. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152534. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152535. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152536. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152537. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152538. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152539. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152540. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152541. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152542. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152543. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152544. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152545. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152546. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152547. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152548. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152549. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152550. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152551. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152552. 12,
  152553. };
  152554. static float _vq_quantthresh__44un1__p4_0[] = {
  152555. -1.5, -0.5, 0.5, 1.5,
  152556. };
  152557. static long _vq_quantmap__44un1__p4_0[] = {
  152558. 3, 1, 0, 2, 4,
  152559. };
  152560. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152561. _vq_quantthresh__44un1__p4_0,
  152562. _vq_quantmap__44un1__p4_0,
  152563. 5,
  152564. 5
  152565. };
  152566. static static_codebook _44un1__p4_0 = {
  152567. 4, 625,
  152568. _vq_lengthlist__44un1__p4_0,
  152569. 1, -533725184, 1611661312, 3, 0,
  152570. _vq_quantlist__44un1__p4_0,
  152571. NULL,
  152572. &_vq_auxt__44un1__p4_0,
  152573. NULL,
  152574. 0
  152575. };
  152576. static long _vq_quantlist__44un1__p5_0[] = {
  152577. 4,
  152578. 3,
  152579. 5,
  152580. 2,
  152581. 6,
  152582. 1,
  152583. 7,
  152584. 0,
  152585. 8,
  152586. };
  152587. static long _vq_lengthlist__44un1__p5_0[] = {
  152588. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152589. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152590. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152591. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152592. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152593. 12,
  152594. };
  152595. static float _vq_quantthresh__44un1__p5_0[] = {
  152596. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152597. };
  152598. static long _vq_quantmap__44un1__p5_0[] = {
  152599. 7, 5, 3, 1, 0, 2, 4, 6,
  152600. 8,
  152601. };
  152602. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152603. _vq_quantthresh__44un1__p5_0,
  152604. _vq_quantmap__44un1__p5_0,
  152605. 9,
  152606. 9
  152607. };
  152608. static static_codebook _44un1__p5_0 = {
  152609. 2, 81,
  152610. _vq_lengthlist__44un1__p5_0,
  152611. 1, -531628032, 1611661312, 4, 0,
  152612. _vq_quantlist__44un1__p5_0,
  152613. NULL,
  152614. &_vq_auxt__44un1__p5_0,
  152615. NULL,
  152616. 0
  152617. };
  152618. static long _vq_quantlist__44un1__p6_0[] = {
  152619. 6,
  152620. 5,
  152621. 7,
  152622. 4,
  152623. 8,
  152624. 3,
  152625. 9,
  152626. 2,
  152627. 10,
  152628. 1,
  152629. 11,
  152630. 0,
  152631. 12,
  152632. };
  152633. static long _vq_lengthlist__44un1__p6_0[] = {
  152634. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152635. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152636. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152637. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152638. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152639. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152640. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152641. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152642. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152643. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152644. 16, 0,15,18,18, 0,16, 0, 0,
  152645. };
  152646. static float _vq_quantthresh__44un1__p6_0[] = {
  152647. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152648. 12.5, 17.5, 22.5, 27.5,
  152649. };
  152650. static long _vq_quantmap__44un1__p6_0[] = {
  152651. 11, 9, 7, 5, 3, 1, 0, 2,
  152652. 4, 6, 8, 10, 12,
  152653. };
  152654. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152655. _vq_quantthresh__44un1__p6_0,
  152656. _vq_quantmap__44un1__p6_0,
  152657. 13,
  152658. 13
  152659. };
  152660. static static_codebook _44un1__p6_0 = {
  152661. 2, 169,
  152662. _vq_lengthlist__44un1__p6_0,
  152663. 1, -526516224, 1616117760, 4, 0,
  152664. _vq_quantlist__44un1__p6_0,
  152665. NULL,
  152666. &_vq_auxt__44un1__p6_0,
  152667. NULL,
  152668. 0
  152669. };
  152670. static long _vq_quantlist__44un1__p6_1[] = {
  152671. 2,
  152672. 1,
  152673. 3,
  152674. 0,
  152675. 4,
  152676. };
  152677. static long _vq_lengthlist__44un1__p6_1[] = {
  152678. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  152679. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  152680. };
  152681. static float _vq_quantthresh__44un1__p6_1[] = {
  152682. -1.5, -0.5, 0.5, 1.5,
  152683. };
  152684. static long _vq_quantmap__44un1__p6_1[] = {
  152685. 3, 1, 0, 2, 4,
  152686. };
  152687. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  152688. _vq_quantthresh__44un1__p6_1,
  152689. _vq_quantmap__44un1__p6_1,
  152690. 5,
  152691. 5
  152692. };
  152693. static static_codebook _44un1__p6_1 = {
  152694. 2, 25,
  152695. _vq_lengthlist__44un1__p6_1,
  152696. 1, -533725184, 1611661312, 3, 0,
  152697. _vq_quantlist__44un1__p6_1,
  152698. NULL,
  152699. &_vq_auxt__44un1__p6_1,
  152700. NULL,
  152701. 0
  152702. };
  152703. static long _vq_quantlist__44un1__p7_0[] = {
  152704. 2,
  152705. 1,
  152706. 3,
  152707. 0,
  152708. 4,
  152709. };
  152710. static long _vq_lengthlist__44un1__p7_0[] = {
  152711. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  152712. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  152713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152714. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152718. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  152719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  152722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152726. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  152727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152728. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  152729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152730. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152732. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152750. 10,
  152751. };
  152752. static float _vq_quantthresh__44un1__p7_0[] = {
  152753. -253.5, -84.5, 84.5, 253.5,
  152754. };
  152755. static long _vq_quantmap__44un1__p7_0[] = {
  152756. 3, 1, 0, 2, 4,
  152757. };
  152758. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  152759. _vq_quantthresh__44un1__p7_0,
  152760. _vq_quantmap__44un1__p7_0,
  152761. 5,
  152762. 5
  152763. };
  152764. static static_codebook _44un1__p7_0 = {
  152765. 4, 625,
  152766. _vq_lengthlist__44un1__p7_0,
  152767. 1, -518709248, 1626677248, 3, 0,
  152768. _vq_quantlist__44un1__p7_0,
  152769. NULL,
  152770. &_vq_auxt__44un1__p7_0,
  152771. NULL,
  152772. 0
  152773. };
  152774. static long _vq_quantlist__44un1__p7_1[] = {
  152775. 6,
  152776. 5,
  152777. 7,
  152778. 4,
  152779. 8,
  152780. 3,
  152781. 9,
  152782. 2,
  152783. 10,
  152784. 1,
  152785. 11,
  152786. 0,
  152787. 12,
  152788. };
  152789. static long _vq_lengthlist__44un1__p7_1[] = {
  152790. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  152791. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  152792. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  152793. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  152794. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  152795. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  152796. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  152797. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  152798. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  152799. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  152800. 12,13,13,12,13,13,14,14,14,
  152801. };
  152802. static float _vq_quantthresh__44un1__p7_1[] = {
  152803. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  152804. 32.5, 45.5, 58.5, 71.5,
  152805. };
  152806. static long _vq_quantmap__44un1__p7_1[] = {
  152807. 11, 9, 7, 5, 3, 1, 0, 2,
  152808. 4, 6, 8, 10, 12,
  152809. };
  152810. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  152811. _vq_quantthresh__44un1__p7_1,
  152812. _vq_quantmap__44un1__p7_1,
  152813. 13,
  152814. 13
  152815. };
  152816. static static_codebook _44un1__p7_1 = {
  152817. 2, 169,
  152818. _vq_lengthlist__44un1__p7_1,
  152819. 1, -523010048, 1618608128, 4, 0,
  152820. _vq_quantlist__44un1__p7_1,
  152821. NULL,
  152822. &_vq_auxt__44un1__p7_1,
  152823. NULL,
  152824. 0
  152825. };
  152826. static long _vq_quantlist__44un1__p7_2[] = {
  152827. 6,
  152828. 5,
  152829. 7,
  152830. 4,
  152831. 8,
  152832. 3,
  152833. 9,
  152834. 2,
  152835. 10,
  152836. 1,
  152837. 11,
  152838. 0,
  152839. 12,
  152840. };
  152841. static long _vq_lengthlist__44un1__p7_2[] = {
  152842. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  152843. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  152844. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  152845. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  152846. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  152847. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  152848. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  152849. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  152850. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  152851. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  152852. 9, 9, 9,10,10,10,10,10,10,
  152853. };
  152854. static float _vq_quantthresh__44un1__p7_2[] = {
  152855. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  152856. 2.5, 3.5, 4.5, 5.5,
  152857. };
  152858. static long _vq_quantmap__44un1__p7_2[] = {
  152859. 11, 9, 7, 5, 3, 1, 0, 2,
  152860. 4, 6, 8, 10, 12,
  152861. };
  152862. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  152863. _vq_quantthresh__44un1__p7_2,
  152864. _vq_quantmap__44un1__p7_2,
  152865. 13,
  152866. 13
  152867. };
  152868. static static_codebook _44un1__p7_2 = {
  152869. 2, 169,
  152870. _vq_lengthlist__44un1__p7_2,
  152871. 1, -531103744, 1611661312, 4, 0,
  152872. _vq_quantlist__44un1__p7_2,
  152873. NULL,
  152874. &_vq_auxt__44un1__p7_2,
  152875. NULL,
  152876. 0
  152877. };
  152878. static long _huff_lengthlist__44un1__short[] = {
  152879. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  152880. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  152881. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  152882. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  152883. };
  152884. static static_codebook _huff_book__44un1__short = {
  152885. 2, 64,
  152886. _huff_lengthlist__44un1__short,
  152887. 0, 0, 0, 0, 0,
  152888. NULL,
  152889. NULL,
  152890. NULL,
  152891. NULL,
  152892. 0
  152893. };
  152894. /*** End of inlined file: res_books_uncoupled.h ***/
  152895. /***** residue backends *********************************************/
  152896. static vorbis_info_residue0 _residue_44_low_un={
  152897. 0,-1, -1, 8,-1,
  152898. {0},
  152899. {-1},
  152900. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  152901. { -1, 25, -1, 45, -1, -1, -1}
  152902. };
  152903. static vorbis_info_residue0 _residue_44_mid_un={
  152904. 0,-1, -1, 10,-1,
  152905. /* 0 1 2 3 4 5 6 7 8 9 */
  152906. {0},
  152907. {-1},
  152908. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  152909. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  152910. };
  152911. static vorbis_info_residue0 _residue_44_hi_un={
  152912. 0,-1, -1, 10,-1,
  152913. /* 0 1 2 3 4 5 6 7 8 9 */
  152914. {0},
  152915. {-1},
  152916. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  152917. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  152918. };
  152919. /* mapping conventions:
  152920. only one submap (this would change for efficient 5.1 support for example)*/
  152921. /* Four psychoacoustic profiles are used, one for each blocktype */
  152922. static vorbis_info_mapping0 _map_nominal_u[2]={
  152923. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  152924. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  152925. };
  152926. static static_bookblock _resbook_44u_n1={
  152927. {
  152928. {0},
  152929. {0,0,&_44un1__p1_0},
  152930. {0,0,&_44un1__p2_0},
  152931. {0,0,&_44un1__p3_0},
  152932. {0,0,&_44un1__p4_0},
  152933. {0,0,&_44un1__p5_0},
  152934. {&_44un1__p6_0,&_44un1__p6_1},
  152935. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  152936. }
  152937. };
  152938. static static_bookblock _resbook_44u_0={
  152939. {
  152940. {0},
  152941. {0,0,&_44u0__p1_0},
  152942. {0,0,&_44u0__p2_0},
  152943. {0,0,&_44u0__p3_0},
  152944. {0,0,&_44u0__p4_0},
  152945. {0,0,&_44u0__p5_0},
  152946. {&_44u0__p6_0,&_44u0__p6_1},
  152947. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  152948. }
  152949. };
  152950. static static_bookblock _resbook_44u_1={
  152951. {
  152952. {0},
  152953. {0,0,&_44u1__p1_0},
  152954. {0,0,&_44u1__p2_0},
  152955. {0,0,&_44u1__p3_0},
  152956. {0,0,&_44u1__p4_0},
  152957. {0,0,&_44u1__p5_0},
  152958. {&_44u1__p6_0,&_44u1__p6_1},
  152959. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  152960. }
  152961. };
  152962. static static_bookblock _resbook_44u_2={
  152963. {
  152964. {0},
  152965. {0,0,&_44u2__p1_0},
  152966. {0,0,&_44u2__p2_0},
  152967. {0,0,&_44u2__p3_0},
  152968. {0,0,&_44u2__p4_0},
  152969. {0,0,&_44u2__p5_0},
  152970. {&_44u2__p6_0,&_44u2__p6_1},
  152971. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  152972. }
  152973. };
  152974. static static_bookblock _resbook_44u_3={
  152975. {
  152976. {0},
  152977. {0,0,&_44u3__p1_0},
  152978. {0,0,&_44u3__p2_0},
  152979. {0,0,&_44u3__p3_0},
  152980. {0,0,&_44u3__p4_0},
  152981. {0,0,&_44u3__p5_0},
  152982. {&_44u3__p6_0,&_44u3__p6_1},
  152983. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  152984. }
  152985. };
  152986. static static_bookblock _resbook_44u_4={
  152987. {
  152988. {0},
  152989. {0,0,&_44u4__p1_0},
  152990. {0,0,&_44u4__p2_0},
  152991. {0,0,&_44u4__p3_0},
  152992. {0,0,&_44u4__p4_0},
  152993. {0,0,&_44u4__p5_0},
  152994. {&_44u4__p6_0,&_44u4__p6_1},
  152995. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  152996. }
  152997. };
  152998. static static_bookblock _resbook_44u_5={
  152999. {
  153000. {0},
  153001. {0,0,&_44u5__p1_0},
  153002. {0,0,&_44u5__p2_0},
  153003. {0,0,&_44u5__p3_0},
  153004. {0,0,&_44u5__p4_0},
  153005. {0,0,&_44u5__p5_0},
  153006. {0,0,&_44u5__p6_0},
  153007. {&_44u5__p7_0,&_44u5__p7_1},
  153008. {&_44u5__p8_0,&_44u5__p8_1},
  153009. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153010. }
  153011. };
  153012. static static_bookblock _resbook_44u_6={
  153013. {
  153014. {0},
  153015. {0,0,&_44u6__p1_0},
  153016. {0,0,&_44u6__p2_0},
  153017. {0,0,&_44u6__p3_0},
  153018. {0,0,&_44u6__p4_0},
  153019. {0,0,&_44u6__p5_0},
  153020. {0,0,&_44u6__p6_0},
  153021. {&_44u6__p7_0,&_44u6__p7_1},
  153022. {&_44u6__p8_0,&_44u6__p8_1},
  153023. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153024. }
  153025. };
  153026. static static_bookblock _resbook_44u_7={
  153027. {
  153028. {0},
  153029. {0,0,&_44u7__p1_0},
  153030. {0,0,&_44u7__p2_0},
  153031. {0,0,&_44u7__p3_0},
  153032. {0,0,&_44u7__p4_0},
  153033. {0,0,&_44u7__p5_0},
  153034. {0,0,&_44u7__p6_0},
  153035. {&_44u7__p7_0,&_44u7__p7_1},
  153036. {&_44u7__p8_0,&_44u7__p8_1},
  153037. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153038. }
  153039. };
  153040. static static_bookblock _resbook_44u_8={
  153041. {
  153042. {0},
  153043. {0,0,&_44u8_p1_0},
  153044. {0,0,&_44u8_p2_0},
  153045. {0,0,&_44u8_p3_0},
  153046. {0,0,&_44u8_p4_0},
  153047. {&_44u8_p5_0,&_44u8_p5_1},
  153048. {&_44u8_p6_0,&_44u8_p6_1},
  153049. {&_44u8_p7_0,&_44u8_p7_1},
  153050. {&_44u8_p8_0,&_44u8_p8_1},
  153051. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153052. }
  153053. };
  153054. static static_bookblock _resbook_44u_9={
  153055. {
  153056. {0},
  153057. {0,0,&_44u9_p1_0},
  153058. {0,0,&_44u9_p2_0},
  153059. {0,0,&_44u9_p3_0},
  153060. {0,0,&_44u9_p4_0},
  153061. {&_44u9_p5_0,&_44u9_p5_1},
  153062. {&_44u9_p6_0,&_44u9_p6_1},
  153063. {&_44u9_p7_0,&_44u9_p7_1},
  153064. {&_44u9_p8_0,&_44u9_p8_1},
  153065. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153066. }
  153067. };
  153068. static vorbis_residue_template _res_44u_n1[]={
  153069. {1,0, &_residue_44_low_un,
  153070. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153071. &_resbook_44u_n1,&_resbook_44u_n1},
  153072. {1,0, &_residue_44_low_un,
  153073. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153074. &_resbook_44u_n1,&_resbook_44u_n1}
  153075. };
  153076. static vorbis_residue_template _res_44u_0[]={
  153077. {1,0, &_residue_44_low_un,
  153078. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153079. &_resbook_44u_0,&_resbook_44u_0},
  153080. {1,0, &_residue_44_low_un,
  153081. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153082. &_resbook_44u_0,&_resbook_44u_0}
  153083. };
  153084. static vorbis_residue_template _res_44u_1[]={
  153085. {1,0, &_residue_44_low_un,
  153086. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153087. &_resbook_44u_1,&_resbook_44u_1},
  153088. {1,0, &_residue_44_low_un,
  153089. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153090. &_resbook_44u_1,&_resbook_44u_1}
  153091. };
  153092. static vorbis_residue_template _res_44u_2[]={
  153093. {1,0, &_residue_44_low_un,
  153094. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153095. &_resbook_44u_2,&_resbook_44u_2},
  153096. {1,0, &_residue_44_low_un,
  153097. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153098. &_resbook_44u_2,&_resbook_44u_2}
  153099. };
  153100. static vorbis_residue_template _res_44u_3[]={
  153101. {1,0, &_residue_44_low_un,
  153102. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153103. &_resbook_44u_3,&_resbook_44u_3},
  153104. {1,0, &_residue_44_low_un,
  153105. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153106. &_resbook_44u_3,&_resbook_44u_3}
  153107. };
  153108. static vorbis_residue_template _res_44u_4[]={
  153109. {1,0, &_residue_44_low_un,
  153110. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153111. &_resbook_44u_4,&_resbook_44u_4},
  153112. {1,0, &_residue_44_low_un,
  153113. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153114. &_resbook_44u_4,&_resbook_44u_4}
  153115. };
  153116. static vorbis_residue_template _res_44u_5[]={
  153117. {1,0, &_residue_44_mid_un,
  153118. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153119. &_resbook_44u_5,&_resbook_44u_5},
  153120. {1,0, &_residue_44_mid_un,
  153121. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153122. &_resbook_44u_5,&_resbook_44u_5}
  153123. };
  153124. static vorbis_residue_template _res_44u_6[]={
  153125. {1,0, &_residue_44_mid_un,
  153126. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153127. &_resbook_44u_6,&_resbook_44u_6},
  153128. {1,0, &_residue_44_mid_un,
  153129. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153130. &_resbook_44u_6,&_resbook_44u_6}
  153131. };
  153132. static vorbis_residue_template _res_44u_7[]={
  153133. {1,0, &_residue_44_mid_un,
  153134. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153135. &_resbook_44u_7,&_resbook_44u_7},
  153136. {1,0, &_residue_44_mid_un,
  153137. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153138. &_resbook_44u_7,&_resbook_44u_7}
  153139. };
  153140. static vorbis_residue_template _res_44u_8[]={
  153141. {1,0, &_residue_44_hi_un,
  153142. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153143. &_resbook_44u_8,&_resbook_44u_8},
  153144. {1,0, &_residue_44_hi_un,
  153145. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153146. &_resbook_44u_8,&_resbook_44u_8}
  153147. };
  153148. static vorbis_residue_template _res_44u_9[]={
  153149. {1,0, &_residue_44_hi_un,
  153150. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153151. &_resbook_44u_9,&_resbook_44u_9},
  153152. {1,0, &_residue_44_hi_un,
  153153. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153154. &_resbook_44u_9,&_resbook_44u_9}
  153155. };
  153156. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153157. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153158. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153159. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153160. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153161. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153162. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153163. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153164. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153165. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153166. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153167. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153168. };
  153169. /*** End of inlined file: residue_44u.h ***/
  153170. static double rate_mapping_44_un[12]={
  153171. 32000.,48000.,60000.,70000.,80000.,86000.,
  153172. 96000.,110000.,120000.,140000.,160000.,240001.
  153173. };
  153174. ve_setup_data_template ve_setup_44_uncoupled={
  153175. 11,
  153176. rate_mapping_44_un,
  153177. quality_mapping_44,
  153178. -1,
  153179. 40000,
  153180. 50000,
  153181. blocksize_short_44,
  153182. blocksize_long_44,
  153183. _psy_tone_masteratt_44,
  153184. _psy_tone_0dB,
  153185. _psy_tone_suppress,
  153186. _vp_tonemask_adj_otherblock,
  153187. _vp_tonemask_adj_longblock,
  153188. _vp_tonemask_adj_otherblock,
  153189. _psy_noiseguards_44,
  153190. _psy_noisebias_impulse,
  153191. _psy_noisebias_padding,
  153192. _psy_noisebias_trans,
  153193. _psy_noisebias_long,
  153194. _psy_noise_suppress,
  153195. _psy_compand_44,
  153196. _psy_compand_short_mapping,
  153197. _psy_compand_long_mapping,
  153198. {_noise_start_short_44,_noise_start_long_44},
  153199. {_noise_part_short_44,_noise_part_long_44},
  153200. _noise_thresh_44,
  153201. _psy_ath_floater,
  153202. _psy_ath_abs,
  153203. _psy_lowpass_44,
  153204. _psy_global_44,
  153205. _global_mapping_44,
  153206. NULL,
  153207. _floor_books,
  153208. _floor,
  153209. _floor_short_mapping_44,
  153210. _floor_long_mapping_44,
  153211. _mapres_template_44_uncoupled
  153212. };
  153213. /*** End of inlined file: setup_44u.h ***/
  153214. /*** Start of inlined file: setup_32.h ***/
  153215. static double rate_mapping_32[12]={
  153216. 18000.,28000.,35000.,45000.,56000.,60000.,
  153217. 75000.,90000.,100000.,115000.,150000.,190000.,
  153218. };
  153219. static double rate_mapping_32_un[12]={
  153220. 30000.,42000.,52000.,64000.,72000.,78000.,
  153221. 86000.,92000.,110000.,120000.,140000.,190000.,
  153222. };
  153223. static double _psy_lowpass_32[12]={
  153224. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153225. };
  153226. ve_setup_data_template ve_setup_32_stereo={
  153227. 11,
  153228. rate_mapping_32,
  153229. quality_mapping_44,
  153230. 2,
  153231. 26000,
  153232. 40000,
  153233. blocksize_short_44,
  153234. blocksize_long_44,
  153235. _psy_tone_masteratt_44,
  153236. _psy_tone_0dB,
  153237. _psy_tone_suppress,
  153238. _vp_tonemask_adj_otherblock,
  153239. _vp_tonemask_adj_longblock,
  153240. _vp_tonemask_adj_otherblock,
  153241. _psy_noiseguards_44,
  153242. _psy_noisebias_impulse,
  153243. _psy_noisebias_padding,
  153244. _psy_noisebias_trans,
  153245. _psy_noisebias_long,
  153246. _psy_noise_suppress,
  153247. _psy_compand_44,
  153248. _psy_compand_short_mapping,
  153249. _psy_compand_long_mapping,
  153250. {_noise_start_short_44,_noise_start_long_44},
  153251. {_noise_part_short_44,_noise_part_long_44},
  153252. _noise_thresh_44,
  153253. _psy_ath_floater,
  153254. _psy_ath_abs,
  153255. _psy_lowpass_32,
  153256. _psy_global_44,
  153257. _global_mapping_44,
  153258. _psy_stereo_modes_44,
  153259. _floor_books,
  153260. _floor,
  153261. _floor_short_mapping_44,
  153262. _floor_long_mapping_44,
  153263. _mapres_template_44_stereo
  153264. };
  153265. ve_setup_data_template ve_setup_32_uncoupled={
  153266. 11,
  153267. rate_mapping_32_un,
  153268. quality_mapping_44,
  153269. -1,
  153270. 26000,
  153271. 40000,
  153272. blocksize_short_44,
  153273. blocksize_long_44,
  153274. _psy_tone_masteratt_44,
  153275. _psy_tone_0dB,
  153276. _psy_tone_suppress,
  153277. _vp_tonemask_adj_otherblock,
  153278. _vp_tonemask_adj_longblock,
  153279. _vp_tonemask_adj_otherblock,
  153280. _psy_noiseguards_44,
  153281. _psy_noisebias_impulse,
  153282. _psy_noisebias_padding,
  153283. _psy_noisebias_trans,
  153284. _psy_noisebias_long,
  153285. _psy_noise_suppress,
  153286. _psy_compand_44,
  153287. _psy_compand_short_mapping,
  153288. _psy_compand_long_mapping,
  153289. {_noise_start_short_44,_noise_start_long_44},
  153290. {_noise_part_short_44,_noise_part_long_44},
  153291. _noise_thresh_44,
  153292. _psy_ath_floater,
  153293. _psy_ath_abs,
  153294. _psy_lowpass_32,
  153295. _psy_global_44,
  153296. _global_mapping_44,
  153297. NULL,
  153298. _floor_books,
  153299. _floor,
  153300. _floor_short_mapping_44,
  153301. _floor_long_mapping_44,
  153302. _mapres_template_44_uncoupled
  153303. };
  153304. /*** End of inlined file: setup_32.h ***/
  153305. /*** Start of inlined file: setup_8.h ***/
  153306. /*** Start of inlined file: psych_8.h ***/
  153307. static att3 _psy_tone_masteratt_8[3]={
  153308. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153309. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153310. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153311. };
  153312. static vp_adjblock _vp_tonemask_adj_8[3]={
  153313. /* adjust for mode zero */
  153314. /* 63 125 250 500 1 2 4 8 16 */
  153315. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153316. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153317. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153318. };
  153319. static noise3 _psy_noisebias_8[3]={
  153320. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153321. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153322. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153323. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153324. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153325. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153326. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153327. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153328. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153329. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153330. };
  153331. /* stereo mode by base quality level */
  153332. static adj_stereo _psy_stereo_modes_8[3]={
  153333. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153334. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153335. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153336. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153337. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153338. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153339. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153340. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153341. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153342. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153343. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153344. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153345. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153346. };
  153347. static noiseguard _psy_noiseguards_8[2]={
  153348. {10,10,-1},
  153349. {10,10,-1},
  153350. };
  153351. static compandblock _psy_compand_8[2]={
  153352. {{
  153353. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153354. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153355. 12,12,13,13,14,14,15, 15, /* 23dB */
  153356. 16,16,17,17,17,18,18, 19, /* 31dB */
  153357. 19,19,20,21,22,23,24, 25, /* 39dB */
  153358. }},
  153359. {{
  153360. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153361. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153362. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153363. 9,10,11,12,13,14,15, 16, /* 31dB */
  153364. 17,18,19,20,21,22,23, 24, /* 39dB */
  153365. }},
  153366. };
  153367. static double _psy_lowpass_8[3]={3.,4.,4.};
  153368. static int _noise_start_8[2]={
  153369. 64,64,
  153370. };
  153371. static int _noise_part_8[2]={
  153372. 8,8,
  153373. };
  153374. static int _psy_ath_floater_8[3]={
  153375. -100,-100,-105,
  153376. };
  153377. static int _psy_ath_abs_8[3]={
  153378. -130,-130,-140,
  153379. };
  153380. /*** End of inlined file: psych_8.h ***/
  153381. /*** Start of inlined file: residue_8.h ***/
  153382. /***** residue backends *********************************************/
  153383. static static_bookblock _resbook_8s_0={
  153384. {
  153385. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153386. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153387. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153388. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153389. }
  153390. };
  153391. static static_bookblock _resbook_8s_1={
  153392. {
  153393. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153394. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153395. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153396. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153397. }
  153398. };
  153399. static vorbis_residue_template _res_8s_0[]={
  153400. {2,0, &_residue_44_mid,
  153401. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153402. &_resbook_8s_0,&_resbook_8s_0},
  153403. };
  153404. static vorbis_residue_template _res_8s_1[]={
  153405. {2,0, &_residue_44_mid,
  153406. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153407. &_resbook_8s_1,&_resbook_8s_1},
  153408. };
  153409. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153410. { _map_nominal, _res_8s_0 }, /* 0 */
  153411. { _map_nominal, _res_8s_1 }, /* 1 */
  153412. };
  153413. static static_bookblock _resbook_8u_0={
  153414. {
  153415. {0},
  153416. {0,0,&_8u0__p1_0},
  153417. {0,0,&_8u0__p2_0},
  153418. {0,0,&_8u0__p3_0},
  153419. {0,0,&_8u0__p4_0},
  153420. {0,0,&_8u0__p5_0},
  153421. {&_8u0__p6_0,&_8u0__p6_1},
  153422. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153423. }
  153424. };
  153425. static static_bookblock _resbook_8u_1={
  153426. {
  153427. {0},
  153428. {0,0,&_8u1__p1_0},
  153429. {0,0,&_8u1__p2_0},
  153430. {0,0,&_8u1__p3_0},
  153431. {0,0,&_8u1__p4_0},
  153432. {0,0,&_8u1__p5_0},
  153433. {0,0,&_8u1__p6_0},
  153434. {&_8u1__p7_0,&_8u1__p7_1},
  153435. {&_8u1__p8_0,&_8u1__p8_1},
  153436. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153437. }
  153438. };
  153439. static vorbis_residue_template _res_8u_0[]={
  153440. {1,0, &_residue_44_low_un,
  153441. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153442. &_resbook_8u_0,&_resbook_8u_0},
  153443. };
  153444. static vorbis_residue_template _res_8u_1[]={
  153445. {1,0, &_residue_44_mid_un,
  153446. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153447. &_resbook_8u_1,&_resbook_8u_1},
  153448. };
  153449. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153450. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153451. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153452. };
  153453. /*** End of inlined file: residue_8.h ***/
  153454. static int blocksize_8[2]={
  153455. 512,512
  153456. };
  153457. static int _floor_mapping_8[2]={
  153458. 6,6,
  153459. };
  153460. static double rate_mapping_8[3]={
  153461. 6000.,9000.,32000.,
  153462. };
  153463. static double rate_mapping_8_uncoupled[3]={
  153464. 8000.,14000.,42000.,
  153465. };
  153466. static double quality_mapping_8[3]={
  153467. -.1,.0,1.
  153468. };
  153469. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153470. static double _global_mapping_8[3]={ 1., 2., 3. };
  153471. ve_setup_data_template ve_setup_8_stereo={
  153472. 2,
  153473. rate_mapping_8,
  153474. quality_mapping_8,
  153475. 2,
  153476. 8000,
  153477. 9000,
  153478. blocksize_8,
  153479. blocksize_8,
  153480. _psy_tone_masteratt_8,
  153481. _psy_tone_0dB,
  153482. _psy_tone_suppress,
  153483. _vp_tonemask_adj_8,
  153484. NULL,
  153485. _vp_tonemask_adj_8,
  153486. _psy_noiseguards_8,
  153487. _psy_noisebias_8,
  153488. _psy_noisebias_8,
  153489. NULL,
  153490. NULL,
  153491. _psy_noise_suppress,
  153492. _psy_compand_8,
  153493. _psy_compand_8_mapping,
  153494. NULL,
  153495. {_noise_start_8,_noise_start_8},
  153496. {_noise_part_8,_noise_part_8},
  153497. _noise_thresh_5only,
  153498. _psy_ath_floater_8,
  153499. _psy_ath_abs_8,
  153500. _psy_lowpass_8,
  153501. _psy_global_44,
  153502. _global_mapping_8,
  153503. _psy_stereo_modes_8,
  153504. _floor_books,
  153505. _floor,
  153506. _floor_mapping_8,
  153507. NULL,
  153508. _mapres_template_8_stereo
  153509. };
  153510. ve_setup_data_template ve_setup_8_uncoupled={
  153511. 2,
  153512. rate_mapping_8_uncoupled,
  153513. quality_mapping_8,
  153514. -1,
  153515. 8000,
  153516. 9000,
  153517. blocksize_8,
  153518. blocksize_8,
  153519. _psy_tone_masteratt_8,
  153520. _psy_tone_0dB,
  153521. _psy_tone_suppress,
  153522. _vp_tonemask_adj_8,
  153523. NULL,
  153524. _vp_tonemask_adj_8,
  153525. _psy_noiseguards_8,
  153526. _psy_noisebias_8,
  153527. _psy_noisebias_8,
  153528. NULL,
  153529. NULL,
  153530. _psy_noise_suppress,
  153531. _psy_compand_8,
  153532. _psy_compand_8_mapping,
  153533. NULL,
  153534. {_noise_start_8,_noise_start_8},
  153535. {_noise_part_8,_noise_part_8},
  153536. _noise_thresh_5only,
  153537. _psy_ath_floater_8,
  153538. _psy_ath_abs_8,
  153539. _psy_lowpass_8,
  153540. _psy_global_44,
  153541. _global_mapping_8,
  153542. _psy_stereo_modes_8,
  153543. _floor_books,
  153544. _floor,
  153545. _floor_mapping_8,
  153546. NULL,
  153547. _mapres_template_8_uncoupled
  153548. };
  153549. /*** End of inlined file: setup_8.h ***/
  153550. /*** Start of inlined file: setup_11.h ***/
  153551. /*** Start of inlined file: psych_11.h ***/
  153552. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153553. static att3 _psy_tone_masteratt_11[3]={
  153554. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153555. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153556. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153557. };
  153558. static vp_adjblock _vp_tonemask_adj_11[3]={
  153559. /* adjust for mode zero */
  153560. /* 63 125 250 500 1 2 4 8 16 */
  153561. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153562. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153563. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153564. };
  153565. static noise3 _psy_noisebias_11[3]={
  153566. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153567. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153568. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153569. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153570. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153571. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153572. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153573. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153574. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153575. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153576. };
  153577. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153578. /*** End of inlined file: psych_11.h ***/
  153579. static int blocksize_11[2]={
  153580. 512,512
  153581. };
  153582. static int _floor_mapping_11[2]={
  153583. 6,6,
  153584. };
  153585. static double rate_mapping_11[3]={
  153586. 8000.,13000.,44000.,
  153587. };
  153588. static double rate_mapping_11_uncoupled[3]={
  153589. 12000.,20000.,50000.,
  153590. };
  153591. static double quality_mapping_11[3]={
  153592. -.1,.0,1.
  153593. };
  153594. ve_setup_data_template ve_setup_11_stereo={
  153595. 2,
  153596. rate_mapping_11,
  153597. quality_mapping_11,
  153598. 2,
  153599. 9000,
  153600. 15000,
  153601. blocksize_11,
  153602. blocksize_11,
  153603. _psy_tone_masteratt_11,
  153604. _psy_tone_0dB,
  153605. _psy_tone_suppress,
  153606. _vp_tonemask_adj_11,
  153607. NULL,
  153608. _vp_tonemask_adj_11,
  153609. _psy_noiseguards_8,
  153610. _psy_noisebias_11,
  153611. _psy_noisebias_11,
  153612. NULL,
  153613. NULL,
  153614. _psy_noise_suppress,
  153615. _psy_compand_8,
  153616. _psy_compand_8_mapping,
  153617. NULL,
  153618. {_noise_start_8,_noise_start_8},
  153619. {_noise_part_8,_noise_part_8},
  153620. _noise_thresh_11,
  153621. _psy_ath_floater_8,
  153622. _psy_ath_abs_8,
  153623. _psy_lowpass_11,
  153624. _psy_global_44,
  153625. _global_mapping_8,
  153626. _psy_stereo_modes_8,
  153627. _floor_books,
  153628. _floor,
  153629. _floor_mapping_11,
  153630. NULL,
  153631. _mapres_template_8_stereo
  153632. };
  153633. ve_setup_data_template ve_setup_11_uncoupled={
  153634. 2,
  153635. rate_mapping_11_uncoupled,
  153636. quality_mapping_11,
  153637. -1,
  153638. 9000,
  153639. 15000,
  153640. blocksize_11,
  153641. blocksize_11,
  153642. _psy_tone_masteratt_11,
  153643. _psy_tone_0dB,
  153644. _psy_tone_suppress,
  153645. _vp_tonemask_adj_11,
  153646. NULL,
  153647. _vp_tonemask_adj_11,
  153648. _psy_noiseguards_8,
  153649. _psy_noisebias_11,
  153650. _psy_noisebias_11,
  153651. NULL,
  153652. NULL,
  153653. _psy_noise_suppress,
  153654. _psy_compand_8,
  153655. _psy_compand_8_mapping,
  153656. NULL,
  153657. {_noise_start_8,_noise_start_8},
  153658. {_noise_part_8,_noise_part_8},
  153659. _noise_thresh_11,
  153660. _psy_ath_floater_8,
  153661. _psy_ath_abs_8,
  153662. _psy_lowpass_11,
  153663. _psy_global_44,
  153664. _global_mapping_8,
  153665. _psy_stereo_modes_8,
  153666. _floor_books,
  153667. _floor,
  153668. _floor_mapping_11,
  153669. NULL,
  153670. _mapres_template_8_uncoupled
  153671. };
  153672. /*** End of inlined file: setup_11.h ***/
  153673. /*** Start of inlined file: setup_16.h ***/
  153674. /*** Start of inlined file: psych_16.h ***/
  153675. /* stereo mode by base quality level */
  153676. static adj_stereo _psy_stereo_modes_16[4]={
  153677. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153678. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153679. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153680. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  153681. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153682. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153683. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153684. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  153685. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153686. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153687. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153688. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153689. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153690. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153691. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  153692. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  153693. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153694. };
  153695. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  153696. static att3 _psy_tone_masteratt_16[4]={
  153697. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153698. {{ 25, 22, 12}, 0, 0}, /* 0 */
  153699. {{ 20, 12, 0}, 0, 0}, /* 0 */
  153700. {{ 15, 0, -14}, 0, 0}, /* 0 */
  153701. };
  153702. static vp_adjblock _vp_tonemask_adj_16[4]={
  153703. /* adjust for mode zero */
  153704. /* 63 125 250 500 1 2 4 8 16 */
  153705. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  153706. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  153707. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153708. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  153709. };
  153710. static noise3 _psy_noisebias_16_short[4]={
  153711. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153712. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153713. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153714. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153715. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153716. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  153717. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153718. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153719. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  153720. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153721. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153722. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153723. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153724. };
  153725. static noise3 _psy_noisebias_16_impulse[4]={
  153726. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153727. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  153728. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  153729. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153730. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  153731. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  153732. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  153733. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  153734. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  153735. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153736. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153737. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  153738. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153739. };
  153740. static noise3 _psy_noisebias_16[4]={
  153741. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153742. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  153743. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153744. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153745. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  153746. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  153747. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  153748. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  153749. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  153750. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153751. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  153752. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  153753. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  153754. };
  153755. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  153756. static int _noise_start_16[3]={ 256,256,9999 };
  153757. static int _noise_part_16[4]={ 8,8,8,8 };
  153758. static int _psy_ath_floater_16[4]={
  153759. -100,-100,-100,-105,
  153760. };
  153761. static int _psy_ath_abs_16[4]={
  153762. -130,-130,-130,-140,
  153763. };
  153764. /*** End of inlined file: psych_16.h ***/
  153765. /*** Start of inlined file: residue_16.h ***/
  153766. /***** residue backends *********************************************/
  153767. static static_bookblock _resbook_16s_0={
  153768. {
  153769. {0},
  153770. {0,0,&_16c0_s_p1_0},
  153771. {0,0,&_16c0_s_p2_0},
  153772. {0,0,&_16c0_s_p3_0},
  153773. {0,0,&_16c0_s_p4_0},
  153774. {0,0,&_16c0_s_p5_0},
  153775. {0,0,&_16c0_s_p6_0},
  153776. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  153777. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  153778. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  153779. }
  153780. };
  153781. static static_bookblock _resbook_16s_1={
  153782. {
  153783. {0},
  153784. {0,0,&_16c1_s_p1_0},
  153785. {0,0,&_16c1_s_p2_0},
  153786. {0,0,&_16c1_s_p3_0},
  153787. {0,0,&_16c1_s_p4_0},
  153788. {0,0,&_16c1_s_p5_0},
  153789. {0,0,&_16c1_s_p6_0},
  153790. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  153791. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  153792. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  153793. }
  153794. };
  153795. static static_bookblock _resbook_16s_2={
  153796. {
  153797. {0},
  153798. {0,0,&_16c2_s_p1_0},
  153799. {0,0,&_16c2_s_p2_0},
  153800. {0,0,&_16c2_s_p3_0},
  153801. {0,0,&_16c2_s_p4_0},
  153802. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  153803. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  153804. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  153805. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  153806. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  153807. }
  153808. };
  153809. static vorbis_residue_template _res_16s_0[]={
  153810. {2,0, &_residue_44_mid,
  153811. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  153812. &_resbook_16s_0,&_resbook_16s_0},
  153813. };
  153814. static vorbis_residue_template _res_16s_1[]={
  153815. {2,0, &_residue_44_mid,
  153816. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  153817. &_resbook_16s_1,&_resbook_16s_1},
  153818. {2,0, &_residue_44_mid,
  153819. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  153820. &_resbook_16s_1,&_resbook_16s_1}
  153821. };
  153822. static vorbis_residue_template _res_16s_2[]={
  153823. {2,0, &_residue_44_high,
  153824. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  153825. &_resbook_16s_2,&_resbook_16s_2},
  153826. {2,0, &_residue_44_high,
  153827. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  153828. &_resbook_16s_2,&_resbook_16s_2}
  153829. };
  153830. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  153831. { _map_nominal, _res_16s_0 }, /* 0 */
  153832. { _map_nominal, _res_16s_1 }, /* 1 */
  153833. { _map_nominal, _res_16s_2 }, /* 2 */
  153834. };
  153835. static static_bookblock _resbook_16u_0={
  153836. {
  153837. {0},
  153838. {0,0,&_16u0__p1_0},
  153839. {0,0,&_16u0__p2_0},
  153840. {0,0,&_16u0__p3_0},
  153841. {0,0,&_16u0__p4_0},
  153842. {0,0,&_16u0__p5_0},
  153843. {&_16u0__p6_0,&_16u0__p6_1},
  153844. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  153845. }
  153846. };
  153847. static static_bookblock _resbook_16u_1={
  153848. {
  153849. {0},
  153850. {0,0,&_16u1__p1_0},
  153851. {0,0,&_16u1__p2_0},
  153852. {0,0,&_16u1__p3_0},
  153853. {0,0,&_16u1__p4_0},
  153854. {0,0,&_16u1__p5_0},
  153855. {0,0,&_16u1__p6_0},
  153856. {&_16u1__p7_0,&_16u1__p7_1},
  153857. {&_16u1__p8_0,&_16u1__p8_1},
  153858. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  153859. }
  153860. };
  153861. static static_bookblock _resbook_16u_2={
  153862. {
  153863. {0},
  153864. {0,0,&_16u2_p1_0},
  153865. {0,0,&_16u2_p2_0},
  153866. {0,0,&_16u2_p3_0},
  153867. {0,0,&_16u2_p4_0},
  153868. {&_16u2_p5_0,&_16u2_p5_1},
  153869. {&_16u2_p6_0,&_16u2_p6_1},
  153870. {&_16u2_p7_0,&_16u2_p7_1},
  153871. {&_16u2_p8_0,&_16u2_p8_1},
  153872. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  153873. }
  153874. };
  153875. static vorbis_residue_template _res_16u_0[]={
  153876. {1,0, &_residue_44_low_un,
  153877. &_huff_book__16u0__single,&_huff_book__16u0__single,
  153878. &_resbook_16u_0,&_resbook_16u_0},
  153879. };
  153880. static vorbis_residue_template _res_16u_1[]={
  153881. {1,0, &_residue_44_mid_un,
  153882. &_huff_book__16u1__short,&_huff_book__16u1__short,
  153883. &_resbook_16u_1,&_resbook_16u_1},
  153884. {1,0, &_residue_44_mid_un,
  153885. &_huff_book__16u1__long,&_huff_book__16u1__long,
  153886. &_resbook_16u_1,&_resbook_16u_1}
  153887. };
  153888. static vorbis_residue_template _res_16u_2[]={
  153889. {1,0, &_residue_44_hi_un,
  153890. &_huff_book__16u2__short,&_huff_book__16u2__short,
  153891. &_resbook_16u_2,&_resbook_16u_2},
  153892. {1,0, &_residue_44_hi_un,
  153893. &_huff_book__16u2__long,&_huff_book__16u2__long,
  153894. &_resbook_16u_2,&_resbook_16u_2}
  153895. };
  153896. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  153897. { _map_nominal_u, _res_16u_0 }, /* 0 */
  153898. { _map_nominal_u, _res_16u_1 }, /* 1 */
  153899. { _map_nominal_u, _res_16u_2 }, /* 2 */
  153900. };
  153901. /*** End of inlined file: residue_16.h ***/
  153902. static int blocksize_16_short[3]={
  153903. 1024,512,512
  153904. };
  153905. static int blocksize_16_long[3]={
  153906. 1024,1024,1024
  153907. };
  153908. static int _floor_mapping_16_short[3]={
  153909. 9,3,3
  153910. };
  153911. static int _floor_mapping_16[3]={
  153912. 9,9,9
  153913. };
  153914. static double rate_mapping_16[4]={
  153915. 12000.,20000.,44000.,86000.
  153916. };
  153917. static double rate_mapping_16_uncoupled[4]={
  153918. 16000.,28000.,64000.,100000.
  153919. };
  153920. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  153921. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  153922. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  153923. ve_setup_data_template ve_setup_16_stereo={
  153924. 3,
  153925. rate_mapping_16,
  153926. quality_mapping_16,
  153927. 2,
  153928. 15000,
  153929. 19000,
  153930. blocksize_16_short,
  153931. blocksize_16_long,
  153932. _psy_tone_masteratt_16,
  153933. _psy_tone_0dB,
  153934. _psy_tone_suppress,
  153935. _vp_tonemask_adj_16,
  153936. _vp_tonemask_adj_16,
  153937. _vp_tonemask_adj_16,
  153938. _psy_noiseguards_8,
  153939. _psy_noisebias_16_impulse,
  153940. _psy_noisebias_16_short,
  153941. _psy_noisebias_16_short,
  153942. _psy_noisebias_16,
  153943. _psy_noise_suppress,
  153944. _psy_compand_8,
  153945. _psy_compand_16_mapping,
  153946. _psy_compand_16_mapping,
  153947. {_noise_start_16,_noise_start_16},
  153948. { _noise_part_16, _noise_part_16},
  153949. _noise_thresh_16,
  153950. _psy_ath_floater_16,
  153951. _psy_ath_abs_16,
  153952. _psy_lowpass_16,
  153953. _psy_global_44,
  153954. _global_mapping_16,
  153955. _psy_stereo_modes_16,
  153956. _floor_books,
  153957. _floor,
  153958. _floor_mapping_16_short,
  153959. _floor_mapping_16,
  153960. _mapres_template_16_stereo
  153961. };
  153962. ve_setup_data_template ve_setup_16_uncoupled={
  153963. 3,
  153964. rate_mapping_16_uncoupled,
  153965. quality_mapping_16,
  153966. -1,
  153967. 15000,
  153968. 19000,
  153969. blocksize_16_short,
  153970. blocksize_16_long,
  153971. _psy_tone_masteratt_16,
  153972. _psy_tone_0dB,
  153973. _psy_tone_suppress,
  153974. _vp_tonemask_adj_16,
  153975. _vp_tonemask_adj_16,
  153976. _vp_tonemask_adj_16,
  153977. _psy_noiseguards_8,
  153978. _psy_noisebias_16_impulse,
  153979. _psy_noisebias_16_short,
  153980. _psy_noisebias_16_short,
  153981. _psy_noisebias_16,
  153982. _psy_noise_suppress,
  153983. _psy_compand_8,
  153984. _psy_compand_16_mapping,
  153985. _psy_compand_16_mapping,
  153986. {_noise_start_16,_noise_start_16},
  153987. { _noise_part_16, _noise_part_16},
  153988. _noise_thresh_16,
  153989. _psy_ath_floater_16,
  153990. _psy_ath_abs_16,
  153991. _psy_lowpass_16,
  153992. _psy_global_44,
  153993. _global_mapping_16,
  153994. _psy_stereo_modes_16,
  153995. _floor_books,
  153996. _floor,
  153997. _floor_mapping_16_short,
  153998. _floor_mapping_16,
  153999. _mapres_template_16_uncoupled
  154000. };
  154001. /*** End of inlined file: setup_16.h ***/
  154002. /*** Start of inlined file: setup_22.h ***/
  154003. static double rate_mapping_22[4]={
  154004. 15000.,20000.,44000.,86000.
  154005. };
  154006. static double rate_mapping_22_uncoupled[4]={
  154007. 16000.,28000.,50000.,90000.
  154008. };
  154009. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154010. ve_setup_data_template ve_setup_22_stereo={
  154011. 3,
  154012. rate_mapping_22,
  154013. quality_mapping_16,
  154014. 2,
  154015. 19000,
  154016. 26000,
  154017. blocksize_16_short,
  154018. blocksize_16_long,
  154019. _psy_tone_masteratt_16,
  154020. _psy_tone_0dB,
  154021. _psy_tone_suppress,
  154022. _vp_tonemask_adj_16,
  154023. _vp_tonemask_adj_16,
  154024. _vp_tonemask_adj_16,
  154025. _psy_noiseguards_8,
  154026. _psy_noisebias_16_impulse,
  154027. _psy_noisebias_16_short,
  154028. _psy_noisebias_16_short,
  154029. _psy_noisebias_16,
  154030. _psy_noise_suppress,
  154031. _psy_compand_8,
  154032. _psy_compand_8_mapping,
  154033. _psy_compand_8_mapping,
  154034. {_noise_start_16,_noise_start_16},
  154035. { _noise_part_16, _noise_part_16},
  154036. _noise_thresh_16,
  154037. _psy_ath_floater_16,
  154038. _psy_ath_abs_16,
  154039. _psy_lowpass_22,
  154040. _psy_global_44,
  154041. _global_mapping_16,
  154042. _psy_stereo_modes_16,
  154043. _floor_books,
  154044. _floor,
  154045. _floor_mapping_16_short,
  154046. _floor_mapping_16,
  154047. _mapres_template_16_stereo
  154048. };
  154049. ve_setup_data_template ve_setup_22_uncoupled={
  154050. 3,
  154051. rate_mapping_22_uncoupled,
  154052. quality_mapping_16,
  154053. -1,
  154054. 19000,
  154055. 26000,
  154056. blocksize_16_short,
  154057. blocksize_16_long,
  154058. _psy_tone_masteratt_16,
  154059. _psy_tone_0dB,
  154060. _psy_tone_suppress,
  154061. _vp_tonemask_adj_16,
  154062. _vp_tonemask_adj_16,
  154063. _vp_tonemask_adj_16,
  154064. _psy_noiseguards_8,
  154065. _psy_noisebias_16_impulse,
  154066. _psy_noisebias_16_short,
  154067. _psy_noisebias_16_short,
  154068. _psy_noisebias_16,
  154069. _psy_noise_suppress,
  154070. _psy_compand_8,
  154071. _psy_compand_8_mapping,
  154072. _psy_compand_8_mapping,
  154073. {_noise_start_16,_noise_start_16},
  154074. { _noise_part_16, _noise_part_16},
  154075. _noise_thresh_16,
  154076. _psy_ath_floater_16,
  154077. _psy_ath_abs_16,
  154078. _psy_lowpass_22,
  154079. _psy_global_44,
  154080. _global_mapping_16,
  154081. _psy_stereo_modes_16,
  154082. _floor_books,
  154083. _floor,
  154084. _floor_mapping_16_short,
  154085. _floor_mapping_16,
  154086. _mapres_template_16_uncoupled
  154087. };
  154088. /*** End of inlined file: setup_22.h ***/
  154089. /*** Start of inlined file: setup_X.h ***/
  154090. static double rate_mapping_X[12]={
  154091. -1.,-1.,-1.,-1.,-1.,-1.,
  154092. -1.,-1.,-1.,-1.,-1.,-1.
  154093. };
  154094. ve_setup_data_template ve_setup_X_stereo={
  154095. 11,
  154096. rate_mapping_X,
  154097. quality_mapping_44,
  154098. 2,
  154099. 50000,
  154100. 200000,
  154101. blocksize_short_44,
  154102. blocksize_long_44,
  154103. _psy_tone_masteratt_44,
  154104. _psy_tone_0dB,
  154105. _psy_tone_suppress,
  154106. _vp_tonemask_adj_otherblock,
  154107. _vp_tonemask_adj_longblock,
  154108. _vp_tonemask_adj_otherblock,
  154109. _psy_noiseguards_44,
  154110. _psy_noisebias_impulse,
  154111. _psy_noisebias_padding,
  154112. _psy_noisebias_trans,
  154113. _psy_noisebias_long,
  154114. _psy_noise_suppress,
  154115. _psy_compand_44,
  154116. _psy_compand_short_mapping,
  154117. _psy_compand_long_mapping,
  154118. {_noise_start_short_44,_noise_start_long_44},
  154119. {_noise_part_short_44,_noise_part_long_44},
  154120. _noise_thresh_44,
  154121. _psy_ath_floater,
  154122. _psy_ath_abs,
  154123. _psy_lowpass_44,
  154124. _psy_global_44,
  154125. _global_mapping_44,
  154126. _psy_stereo_modes_44,
  154127. _floor_books,
  154128. _floor,
  154129. _floor_short_mapping_44,
  154130. _floor_long_mapping_44,
  154131. _mapres_template_44_stereo
  154132. };
  154133. ve_setup_data_template ve_setup_X_uncoupled={
  154134. 11,
  154135. rate_mapping_X,
  154136. quality_mapping_44,
  154137. -1,
  154138. 50000,
  154139. 200000,
  154140. blocksize_short_44,
  154141. blocksize_long_44,
  154142. _psy_tone_masteratt_44,
  154143. _psy_tone_0dB,
  154144. _psy_tone_suppress,
  154145. _vp_tonemask_adj_otherblock,
  154146. _vp_tonemask_adj_longblock,
  154147. _vp_tonemask_adj_otherblock,
  154148. _psy_noiseguards_44,
  154149. _psy_noisebias_impulse,
  154150. _psy_noisebias_padding,
  154151. _psy_noisebias_trans,
  154152. _psy_noisebias_long,
  154153. _psy_noise_suppress,
  154154. _psy_compand_44,
  154155. _psy_compand_short_mapping,
  154156. _psy_compand_long_mapping,
  154157. {_noise_start_short_44,_noise_start_long_44},
  154158. {_noise_part_short_44,_noise_part_long_44},
  154159. _noise_thresh_44,
  154160. _psy_ath_floater,
  154161. _psy_ath_abs,
  154162. _psy_lowpass_44,
  154163. _psy_global_44,
  154164. _global_mapping_44,
  154165. NULL,
  154166. _floor_books,
  154167. _floor,
  154168. _floor_short_mapping_44,
  154169. _floor_long_mapping_44,
  154170. _mapres_template_44_uncoupled
  154171. };
  154172. ve_setup_data_template ve_setup_XX_stereo={
  154173. 2,
  154174. rate_mapping_X,
  154175. quality_mapping_8,
  154176. 2,
  154177. 0,
  154178. 8000,
  154179. blocksize_8,
  154180. blocksize_8,
  154181. _psy_tone_masteratt_8,
  154182. _psy_tone_0dB,
  154183. _psy_tone_suppress,
  154184. _vp_tonemask_adj_8,
  154185. NULL,
  154186. _vp_tonemask_adj_8,
  154187. _psy_noiseguards_8,
  154188. _psy_noisebias_8,
  154189. _psy_noisebias_8,
  154190. NULL,
  154191. NULL,
  154192. _psy_noise_suppress,
  154193. _psy_compand_8,
  154194. _psy_compand_8_mapping,
  154195. NULL,
  154196. {_noise_start_8,_noise_start_8},
  154197. {_noise_part_8,_noise_part_8},
  154198. _noise_thresh_5only,
  154199. _psy_ath_floater_8,
  154200. _psy_ath_abs_8,
  154201. _psy_lowpass_8,
  154202. _psy_global_44,
  154203. _global_mapping_8,
  154204. _psy_stereo_modes_8,
  154205. _floor_books,
  154206. _floor,
  154207. _floor_mapping_8,
  154208. NULL,
  154209. _mapres_template_8_stereo
  154210. };
  154211. ve_setup_data_template ve_setup_XX_uncoupled={
  154212. 2,
  154213. rate_mapping_X,
  154214. quality_mapping_8,
  154215. -1,
  154216. 0,
  154217. 8000,
  154218. blocksize_8,
  154219. blocksize_8,
  154220. _psy_tone_masteratt_8,
  154221. _psy_tone_0dB,
  154222. _psy_tone_suppress,
  154223. _vp_tonemask_adj_8,
  154224. NULL,
  154225. _vp_tonemask_adj_8,
  154226. _psy_noiseguards_8,
  154227. _psy_noisebias_8,
  154228. _psy_noisebias_8,
  154229. NULL,
  154230. NULL,
  154231. _psy_noise_suppress,
  154232. _psy_compand_8,
  154233. _psy_compand_8_mapping,
  154234. NULL,
  154235. {_noise_start_8,_noise_start_8},
  154236. {_noise_part_8,_noise_part_8},
  154237. _noise_thresh_5only,
  154238. _psy_ath_floater_8,
  154239. _psy_ath_abs_8,
  154240. _psy_lowpass_8,
  154241. _psy_global_44,
  154242. _global_mapping_8,
  154243. _psy_stereo_modes_8,
  154244. _floor_books,
  154245. _floor,
  154246. _floor_mapping_8,
  154247. NULL,
  154248. _mapres_template_8_uncoupled
  154249. };
  154250. /*** End of inlined file: setup_X.h ***/
  154251. static ve_setup_data_template *setup_list[]={
  154252. &ve_setup_44_stereo,
  154253. &ve_setup_44_uncoupled,
  154254. &ve_setup_32_stereo,
  154255. &ve_setup_32_uncoupled,
  154256. &ve_setup_22_stereo,
  154257. &ve_setup_22_uncoupled,
  154258. &ve_setup_16_stereo,
  154259. &ve_setup_16_uncoupled,
  154260. &ve_setup_11_stereo,
  154261. &ve_setup_11_uncoupled,
  154262. &ve_setup_8_stereo,
  154263. &ve_setup_8_uncoupled,
  154264. &ve_setup_X_stereo,
  154265. &ve_setup_X_uncoupled,
  154266. &ve_setup_XX_stereo,
  154267. &ve_setup_XX_uncoupled,
  154268. 0
  154269. };
  154270. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154271. if(vi && vi->codec_setup){
  154272. vi->version=0;
  154273. vi->channels=ch;
  154274. vi->rate=rate;
  154275. return(0);
  154276. }
  154277. return(OV_EINVAL);
  154278. }
  154279. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154280. static_codebook ***books,
  154281. vorbis_info_floor1 *in,
  154282. int *x){
  154283. int i,k,is=s;
  154284. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154285. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154286. memcpy(f,in+x[is],sizeof(*f));
  154287. /* fill in the lowpass field, even if it's temporary */
  154288. f->n=ci->blocksizes[block]>>1;
  154289. /* books */
  154290. {
  154291. int partitions=f->partitions;
  154292. int maxclass=-1;
  154293. int maxbook=-1;
  154294. for(i=0;i<partitions;i++)
  154295. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154296. for(i=0;i<=maxclass;i++){
  154297. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154298. f->class_book[i]+=ci->books;
  154299. for(k=0;k<(1<<f->class_subs[i]);k++){
  154300. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154301. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154302. }
  154303. }
  154304. for(i=0;i<=maxbook;i++)
  154305. ci->book_param[ci->books++]=books[x[is]][i];
  154306. }
  154307. /* for now, we're only using floor 1 */
  154308. ci->floor_type[ci->floors]=1;
  154309. ci->floor_param[ci->floors]=f;
  154310. ci->floors++;
  154311. return;
  154312. }
  154313. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154314. vorbis_info_psy_global *in,
  154315. double *x){
  154316. int i,is=s;
  154317. double ds=s-is;
  154318. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154319. vorbis_info_psy_global *g=&ci->psy_g_param;
  154320. memcpy(g,in+(int)x[is],sizeof(*g));
  154321. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154322. is=(int)ds;
  154323. ds-=is;
  154324. if(ds==0 && is>0){
  154325. is--;
  154326. ds=1.;
  154327. }
  154328. /* interpolate the trigger threshholds */
  154329. for(i=0;i<4;i++){
  154330. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154331. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154332. }
  154333. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154334. return;
  154335. }
  154336. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154337. highlevel_encode_setup *hi,
  154338. adj_stereo *p){
  154339. float s=hi->stereo_point_setting;
  154340. int i,is=s;
  154341. double ds=s-is;
  154342. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154343. vorbis_info_psy_global *g=&ci->psy_g_param;
  154344. if(p){
  154345. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154346. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154347. if(hi->managed){
  154348. /* interpolate the kHz threshholds */
  154349. for(i=0;i<PACKETBLOBS;i++){
  154350. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154351. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154352. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154353. g->coupling_pkHz[i]=kHz;
  154354. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154355. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154356. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154357. }
  154358. }else{
  154359. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154360. for(i=0;i<PACKETBLOBS;i++){
  154361. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154362. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154363. g->coupling_pkHz[i]=kHz;
  154364. }
  154365. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154366. for(i=0;i<PACKETBLOBS;i++){
  154367. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154368. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154369. }
  154370. }
  154371. }else{
  154372. for(i=0;i<PACKETBLOBS;i++){
  154373. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154374. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154375. }
  154376. }
  154377. return;
  154378. }
  154379. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154380. int *nn_start,
  154381. int *nn_partition,
  154382. double *nn_thresh,
  154383. int block){
  154384. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154385. vorbis_info_psy *p=ci->psy_param[block];
  154386. highlevel_encode_setup *hi=&ci->hi;
  154387. int is=s;
  154388. if(block>=ci->psys)
  154389. ci->psys=block+1;
  154390. if(!p){
  154391. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154392. ci->psy_param[block]=p;
  154393. }
  154394. memcpy(p,&_psy_info_template,sizeof(*p));
  154395. p->blockflag=block>>1;
  154396. if(hi->noise_normalize_p){
  154397. p->normal_channel_p=1;
  154398. p->normal_point_p=1;
  154399. p->normal_start=nn_start[is];
  154400. p->normal_partition=nn_partition[is];
  154401. p->normal_thresh=nn_thresh[is];
  154402. }
  154403. return;
  154404. }
  154405. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154406. att3 *att,
  154407. int *max,
  154408. vp_adjblock *in){
  154409. int i,is=s;
  154410. double ds=s-is;
  154411. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154412. vorbis_info_psy *p=ci->psy_param[block];
  154413. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154414. filling the values in here */
  154415. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154416. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154417. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154418. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154419. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154420. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154421. for(i=0;i<P_BANDS;i++)
  154422. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154423. return;
  154424. }
  154425. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154426. compandblock *in, double *x){
  154427. int i,is=s;
  154428. double ds=s-is;
  154429. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154430. vorbis_info_psy *p=ci->psy_param[block];
  154431. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154432. is=(int)ds;
  154433. ds-=is;
  154434. if(ds==0 && is>0){
  154435. is--;
  154436. ds=1.;
  154437. }
  154438. /* interpolate the compander settings */
  154439. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154440. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154441. return;
  154442. }
  154443. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154444. int *suppress){
  154445. int is=s;
  154446. double ds=s-is;
  154447. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154448. vorbis_info_psy *p=ci->psy_param[block];
  154449. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154450. return;
  154451. }
  154452. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154453. int *suppress,
  154454. noise3 *in,
  154455. noiseguard *guard,
  154456. double userbias){
  154457. int i,is=s,j;
  154458. double ds=s-is;
  154459. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154460. vorbis_info_psy *p=ci->psy_param[block];
  154461. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154462. p->noisewindowlomin=guard[block].lo;
  154463. p->noisewindowhimin=guard[block].hi;
  154464. p->noisewindowfixed=guard[block].fixed;
  154465. for(j=0;j<P_NOISECURVES;j++)
  154466. for(i=0;i<P_BANDS;i++)
  154467. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154468. /* impulse blocks may take a user specified bias to boost the
  154469. nominal/high noise encoding depth */
  154470. for(j=0;j<P_NOISECURVES;j++){
  154471. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154472. for(i=0;i<P_BANDS;i++){
  154473. p->noiseoff[j][i]+=userbias;
  154474. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154475. }
  154476. }
  154477. return;
  154478. }
  154479. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154480. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154481. vorbis_info_psy *p=ci->psy_param[block];
  154482. p->ath_adjatt=ci->hi.ath_floating_dB;
  154483. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154484. return;
  154485. }
  154486. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154487. int i;
  154488. for(i=0;i<ci->books;i++)
  154489. if(ci->book_param[i]==book)return(i);
  154490. return(ci->books++);
  154491. }
  154492. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154493. int *shortb,int *longb){
  154494. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154495. int is=s;
  154496. int blockshort=shortb[is];
  154497. int blocklong=longb[is];
  154498. ci->blocksizes[0]=blockshort;
  154499. ci->blocksizes[1]=blocklong;
  154500. }
  154501. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154502. int number, int block,
  154503. vorbis_residue_template *res){
  154504. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154505. int i,n;
  154506. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154507. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154508. memcpy(r,res->res,sizeof(*r));
  154509. if(ci->residues<=number)ci->residues=number+1;
  154510. switch(ci->blocksizes[block]){
  154511. case 64:case 128:case 256:
  154512. r->grouping=16;
  154513. break;
  154514. default:
  154515. r->grouping=32;
  154516. break;
  154517. }
  154518. ci->residue_type[number]=res->res_type;
  154519. /* to be adjusted by lowpass/pointlimit later */
  154520. n=r->end=ci->blocksizes[block]>>1;
  154521. if(res->res_type==2)
  154522. n=r->end*=vi->channels;
  154523. /* fill in all the books */
  154524. {
  154525. int booklist=0,k;
  154526. if(ci->hi.managed){
  154527. for(i=0;i<r->partitions;i++)
  154528. for(k=0;k<3;k++)
  154529. if(res->books_base_managed->books[i][k])
  154530. r->secondstages[i]|=(1<<k);
  154531. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154532. ci->book_param[r->groupbook]=res->book_aux_managed;
  154533. for(i=0;i<r->partitions;i++){
  154534. for(k=0;k<3;k++){
  154535. if(res->books_base_managed->books[i][k]){
  154536. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154537. r->booklist[booklist++]=bookid;
  154538. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154539. }
  154540. }
  154541. }
  154542. }else{
  154543. for(i=0;i<r->partitions;i++)
  154544. for(k=0;k<3;k++)
  154545. if(res->books_base->books[i][k])
  154546. r->secondstages[i]|=(1<<k);
  154547. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154548. ci->book_param[r->groupbook]=res->book_aux;
  154549. for(i=0;i<r->partitions;i++){
  154550. for(k=0;k<3;k++){
  154551. if(res->books_base->books[i][k]){
  154552. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154553. r->booklist[booklist++]=bookid;
  154554. ci->book_param[bookid]=res->books_base->books[i][k];
  154555. }
  154556. }
  154557. }
  154558. }
  154559. }
  154560. /* lowpass setup/pointlimit */
  154561. {
  154562. double freq=ci->hi.lowpass_kHz*1000.;
  154563. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154564. double nyq=vi->rate/2.;
  154565. long blocksize=ci->blocksizes[block]>>1;
  154566. /* lowpass needs to be set in the floor and the residue. */
  154567. if(freq>nyq)freq=nyq;
  154568. /* in the floor, the granularity can be very fine; it doesn't alter
  154569. the encoding structure, only the samples used to fit the floor
  154570. approximation */
  154571. f->n=freq/nyq*blocksize;
  154572. /* this res may by limited by the maximum pointlimit of the mode,
  154573. not the lowpass. the floor is always lowpass limited. */
  154574. if(res->limit_type){
  154575. if(ci->hi.managed)
  154576. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154577. else
  154578. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154579. if(freq>nyq)freq=nyq;
  154580. }
  154581. /* in the residue, we're constrained, physically, by partition
  154582. boundaries. We still lowpass 'wherever', but we have to round up
  154583. here to next boundary, or the vorbis spec will round it *down* to
  154584. previous boundary in encode/decode */
  154585. if(ci->residue_type[block]==2)
  154586. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154587. r->grouping;
  154588. else
  154589. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154590. r->grouping;
  154591. }
  154592. }
  154593. /* we assume two maps in this encoder */
  154594. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154595. vorbis_mapping_template *maps){
  154596. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154597. int i,j,is=s,modes=2;
  154598. vorbis_info_mapping0 *map=maps[is].map;
  154599. vorbis_info_mode *mode=_mode_template;
  154600. vorbis_residue_template *res=maps[is].res;
  154601. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154602. for(i=0;i<modes;i++){
  154603. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154604. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154605. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154606. if(i>=ci->modes)ci->modes=i+1;
  154607. ci->map_type[i]=0;
  154608. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154609. if(i>=ci->maps)ci->maps=i+1;
  154610. for(j=0;j<map[i].submaps;j++)
  154611. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154612. ,res+map[i].residuesubmap[j]);
  154613. }
  154614. }
  154615. static double setting_to_approx_bitrate(vorbis_info *vi){
  154616. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154617. highlevel_encode_setup *hi=&ci->hi;
  154618. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154619. int is=hi->base_setting;
  154620. double ds=hi->base_setting-is;
  154621. int ch=vi->channels;
  154622. double *r=setup->rate_mapping;
  154623. if(r==NULL)
  154624. return(-1);
  154625. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154626. }
  154627. static void get_setup_template(vorbis_info *vi,
  154628. long ch,long srate,
  154629. double req,int q_or_bitrate){
  154630. int i=0,j;
  154631. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154632. highlevel_encode_setup *hi=&ci->hi;
  154633. if(q_or_bitrate)req/=ch;
  154634. while(setup_list[i]){
  154635. if(setup_list[i]->coupling_restriction==-1 ||
  154636. setup_list[i]->coupling_restriction==ch){
  154637. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154638. srate<=setup_list[i]->samplerate_max_restriction){
  154639. int mappings=setup_list[i]->mappings;
  154640. double *map=(q_or_bitrate?
  154641. setup_list[i]->rate_mapping:
  154642. setup_list[i]->quality_mapping);
  154643. /* the template matches. Does the requested quality mode
  154644. fall within this template's modes? */
  154645. if(req<map[0]){++i;continue;}
  154646. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154647. for(j=0;j<mappings;j++)
  154648. if(req>=map[j] && req<map[j+1])break;
  154649. /* an all-points match */
  154650. hi->setup=setup_list[i];
  154651. if(j==mappings)
  154652. hi->base_setting=j-.001;
  154653. else{
  154654. float low=map[j];
  154655. float high=map[j+1];
  154656. float del=(req-low)/(high-low);
  154657. hi->base_setting=j+del;
  154658. }
  154659. return;
  154660. }
  154661. }
  154662. i++;
  154663. }
  154664. hi->setup=NULL;
  154665. }
  154666. /* encoders will need to use vorbis_info_init beforehand and call
  154667. vorbis_info clear when all done */
  154668. /* two interfaces; this, more detailed one, and later a convenience
  154669. layer on top */
  154670. /* the final setup call */
  154671. int vorbis_encode_setup_init(vorbis_info *vi){
  154672. int i0=0,singleblock=0;
  154673. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154674. ve_setup_data_template *setup=NULL;
  154675. highlevel_encode_setup *hi=&ci->hi;
  154676. if(ci==NULL)return(OV_EINVAL);
  154677. if(!hi->impulse_block_p)i0=1;
  154678. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  154679. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  154680. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  154681. /* again, bound this to avoid the app shooting itself int he foot
  154682. too badly */
  154683. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  154684. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  154685. /* get the appropriate setup template; matches the fetch in previous
  154686. stages */
  154687. setup=(ve_setup_data_template *)hi->setup;
  154688. if(setup==NULL)return(OV_EINVAL);
  154689. hi->set_in_stone=1;
  154690. /* choose block sizes from configured sizes as well as paying
  154691. attention to long_block_p and short_block_p. If the configured
  154692. short and long blocks are the same length, we set long_block_p
  154693. and unset short_block_p */
  154694. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  154695. setup->blocksize_short,
  154696. setup->blocksize_long);
  154697. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  154698. /* floor setup; choose proper floor params. Allocated on the floor
  154699. stack in order; if we alloc only long floor, it's 0 */
  154700. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  154701. setup->floor_books,
  154702. setup->floor_params,
  154703. setup->floor_short_mapping);
  154704. if(!singleblock)
  154705. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  154706. setup->floor_books,
  154707. setup->floor_params,
  154708. setup->floor_long_mapping);
  154709. /* setup of [mostly] short block detection and stereo*/
  154710. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  154711. setup->global_params,
  154712. setup->global_mapping);
  154713. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  154714. /* basic psych setup and noise normalization */
  154715. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154716. setup->psy_noise_normal_start[0],
  154717. setup->psy_noise_normal_partition[0],
  154718. setup->psy_noise_normal_thresh,
  154719. 0);
  154720. vorbis_encode_psyset_setup(vi,hi->short_setting,
  154721. setup->psy_noise_normal_start[0],
  154722. setup->psy_noise_normal_partition[0],
  154723. setup->psy_noise_normal_thresh,
  154724. 1);
  154725. if(!singleblock){
  154726. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154727. setup->psy_noise_normal_start[1],
  154728. setup->psy_noise_normal_partition[1],
  154729. setup->psy_noise_normal_thresh,
  154730. 2);
  154731. vorbis_encode_psyset_setup(vi,hi->long_setting,
  154732. setup->psy_noise_normal_start[1],
  154733. setup->psy_noise_normal_partition[1],
  154734. setup->psy_noise_normal_thresh,
  154735. 3);
  154736. }
  154737. /* tone masking setup */
  154738. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  154739. setup->psy_tone_masteratt,
  154740. setup->psy_tone_0dB,
  154741. setup->psy_tone_adj_impulse);
  154742. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  154743. setup->psy_tone_masteratt,
  154744. setup->psy_tone_0dB,
  154745. setup->psy_tone_adj_other);
  154746. if(!singleblock){
  154747. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  154748. setup->psy_tone_masteratt,
  154749. setup->psy_tone_0dB,
  154750. setup->psy_tone_adj_other);
  154751. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  154752. setup->psy_tone_masteratt,
  154753. setup->psy_tone_0dB,
  154754. setup->psy_tone_adj_long);
  154755. }
  154756. /* noise companding setup */
  154757. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  154758. setup->psy_noise_compand,
  154759. setup->psy_noise_compand_short_mapping);
  154760. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  154761. setup->psy_noise_compand,
  154762. setup->psy_noise_compand_short_mapping);
  154763. if(!singleblock){
  154764. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  154765. setup->psy_noise_compand,
  154766. setup->psy_noise_compand_long_mapping);
  154767. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  154768. setup->psy_noise_compand,
  154769. setup->psy_noise_compand_long_mapping);
  154770. }
  154771. /* peak guarding setup */
  154772. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  154773. setup->psy_tone_dBsuppress);
  154774. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  154775. setup->psy_tone_dBsuppress);
  154776. if(!singleblock){
  154777. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  154778. setup->psy_tone_dBsuppress);
  154779. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  154780. setup->psy_tone_dBsuppress);
  154781. }
  154782. /* noise bias setup */
  154783. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  154784. setup->psy_noise_dBsuppress,
  154785. setup->psy_noise_bias_impulse,
  154786. setup->psy_noiseguards,
  154787. (i0==0?hi->impulse_noisetune:0.));
  154788. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  154789. setup->psy_noise_dBsuppress,
  154790. setup->psy_noise_bias_padding,
  154791. setup->psy_noiseguards,0.);
  154792. if(!singleblock){
  154793. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  154794. setup->psy_noise_dBsuppress,
  154795. setup->psy_noise_bias_trans,
  154796. setup->psy_noiseguards,0.);
  154797. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  154798. setup->psy_noise_dBsuppress,
  154799. setup->psy_noise_bias_long,
  154800. setup->psy_noiseguards,0.);
  154801. }
  154802. vorbis_encode_ath_setup(vi,0);
  154803. vorbis_encode_ath_setup(vi,1);
  154804. if(!singleblock){
  154805. vorbis_encode_ath_setup(vi,2);
  154806. vorbis_encode_ath_setup(vi,3);
  154807. }
  154808. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  154809. /* set bitrate readonlies and management */
  154810. if(hi->bitrate_av>0)
  154811. vi->bitrate_nominal=hi->bitrate_av;
  154812. else{
  154813. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  154814. }
  154815. vi->bitrate_lower=hi->bitrate_min;
  154816. vi->bitrate_upper=hi->bitrate_max;
  154817. if(hi->bitrate_av)
  154818. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  154819. else
  154820. vi->bitrate_window=0.;
  154821. if(hi->managed){
  154822. ci->bi.avg_rate=hi->bitrate_av;
  154823. ci->bi.min_rate=hi->bitrate_min;
  154824. ci->bi.max_rate=hi->bitrate_max;
  154825. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  154826. ci->bi.reservoir_bias=
  154827. hi->bitrate_reservoir_bias;
  154828. ci->bi.slew_damp=hi->bitrate_av_damp;
  154829. }
  154830. return(0);
  154831. }
  154832. static int vorbis_encode_setup_setting(vorbis_info *vi,
  154833. long channels,
  154834. long rate){
  154835. int ret=0,i,is;
  154836. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154837. highlevel_encode_setup *hi=&ci->hi;
  154838. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  154839. double ds;
  154840. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  154841. if(ret)return(ret);
  154842. is=hi->base_setting;
  154843. ds=hi->base_setting-is;
  154844. hi->short_setting=hi->base_setting;
  154845. hi->long_setting=hi->base_setting;
  154846. hi->managed=0;
  154847. hi->impulse_block_p=1;
  154848. hi->noise_normalize_p=1;
  154849. hi->stereo_point_setting=hi->base_setting;
  154850. hi->lowpass_kHz=
  154851. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  154852. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  154853. setup->psy_ath_float[is+1]*ds;
  154854. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  154855. setup->psy_ath_abs[is+1]*ds;
  154856. hi->amplitude_track_dBpersec=-6.;
  154857. hi->trigger_setting=hi->base_setting;
  154858. for(i=0;i<4;i++){
  154859. hi->block[i].tone_mask_setting=hi->base_setting;
  154860. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  154861. hi->block[i].noise_bias_setting=hi->base_setting;
  154862. hi->block[i].noise_compand_setting=hi->base_setting;
  154863. }
  154864. return(ret);
  154865. }
  154866. int vorbis_encode_setup_vbr(vorbis_info *vi,
  154867. long channels,
  154868. long rate,
  154869. float quality){
  154870. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154871. highlevel_encode_setup *hi=&ci->hi;
  154872. quality+=.0000001;
  154873. if(quality>=1.)quality=.9999;
  154874. get_setup_template(vi,channels,rate,quality,0);
  154875. if(!hi->setup)return OV_EIMPL;
  154876. return vorbis_encode_setup_setting(vi,channels,rate);
  154877. }
  154878. int vorbis_encode_init_vbr(vorbis_info *vi,
  154879. long channels,
  154880. long rate,
  154881. float base_quality /* 0. to 1. */
  154882. ){
  154883. int ret=0;
  154884. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  154885. if(ret){
  154886. vorbis_info_clear(vi);
  154887. return ret;
  154888. }
  154889. ret=vorbis_encode_setup_init(vi);
  154890. if(ret)
  154891. vorbis_info_clear(vi);
  154892. return(ret);
  154893. }
  154894. int vorbis_encode_setup_managed(vorbis_info *vi,
  154895. long channels,
  154896. long rate,
  154897. long max_bitrate,
  154898. long nominal_bitrate,
  154899. long min_bitrate){
  154900. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154901. highlevel_encode_setup *hi=&ci->hi;
  154902. double tnominal=nominal_bitrate;
  154903. int ret=0;
  154904. if(nominal_bitrate<=0.){
  154905. if(max_bitrate>0.){
  154906. if(min_bitrate>0.)
  154907. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  154908. else
  154909. nominal_bitrate=max_bitrate*.875;
  154910. }else{
  154911. if(min_bitrate>0.){
  154912. nominal_bitrate=min_bitrate;
  154913. }else{
  154914. return(OV_EINVAL);
  154915. }
  154916. }
  154917. }
  154918. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  154919. if(!hi->setup)return OV_EIMPL;
  154920. ret=vorbis_encode_setup_setting(vi,channels,rate);
  154921. if(ret){
  154922. vorbis_info_clear(vi);
  154923. return ret;
  154924. }
  154925. /* initialize management with sane defaults */
  154926. hi->managed=1;
  154927. hi->bitrate_min=min_bitrate;
  154928. hi->bitrate_max=max_bitrate;
  154929. hi->bitrate_av=tnominal;
  154930. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  154931. hi->bitrate_reservoir=nominal_bitrate*2;
  154932. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  154933. return(ret);
  154934. }
  154935. int vorbis_encode_init(vorbis_info *vi,
  154936. long channels,
  154937. long rate,
  154938. long max_bitrate,
  154939. long nominal_bitrate,
  154940. long min_bitrate){
  154941. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  154942. max_bitrate,
  154943. nominal_bitrate,
  154944. min_bitrate);
  154945. if(ret){
  154946. vorbis_info_clear(vi);
  154947. return(ret);
  154948. }
  154949. ret=vorbis_encode_setup_init(vi);
  154950. if(ret)
  154951. vorbis_info_clear(vi);
  154952. return(ret);
  154953. }
  154954. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  154955. if(vi){
  154956. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154957. highlevel_encode_setup *hi=&ci->hi;
  154958. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  154959. if(setp && hi->set_in_stone)return(OV_EINVAL);
  154960. switch(number){
  154961. /* now deprecated *****************/
  154962. case OV_ECTL_RATEMANAGE_GET:
  154963. {
  154964. struct ovectl_ratemanage_arg *ai=
  154965. (struct ovectl_ratemanage_arg *)arg;
  154966. ai->management_active=hi->managed;
  154967. ai->bitrate_hard_window=ai->bitrate_av_window=
  154968. (double)hi->bitrate_reservoir/vi->rate;
  154969. ai->bitrate_av_window_center=1.;
  154970. ai->bitrate_hard_min=hi->bitrate_min;
  154971. ai->bitrate_hard_max=hi->bitrate_max;
  154972. ai->bitrate_av_lo=hi->bitrate_av;
  154973. ai->bitrate_av_hi=hi->bitrate_av;
  154974. }
  154975. return(0);
  154976. /* now deprecated *****************/
  154977. case OV_ECTL_RATEMANAGE_SET:
  154978. {
  154979. struct ovectl_ratemanage_arg *ai=
  154980. (struct ovectl_ratemanage_arg *)arg;
  154981. if(ai==NULL){
  154982. hi->managed=0;
  154983. }else{
  154984. hi->managed=ai->management_active;
  154985. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  154986. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  154987. }
  154988. }
  154989. return 0;
  154990. /* now deprecated *****************/
  154991. case OV_ECTL_RATEMANAGE_AVG:
  154992. {
  154993. struct ovectl_ratemanage_arg *ai=
  154994. (struct ovectl_ratemanage_arg *)arg;
  154995. if(ai==NULL){
  154996. hi->bitrate_av=0;
  154997. }else{
  154998. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  154999. }
  155000. }
  155001. return(0);
  155002. /* now deprecated *****************/
  155003. case OV_ECTL_RATEMANAGE_HARD:
  155004. {
  155005. struct ovectl_ratemanage_arg *ai=
  155006. (struct ovectl_ratemanage_arg *)arg;
  155007. if(ai==NULL){
  155008. hi->bitrate_min=0;
  155009. hi->bitrate_max=0;
  155010. }else{
  155011. hi->bitrate_min=ai->bitrate_hard_min;
  155012. hi->bitrate_max=ai->bitrate_hard_max;
  155013. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155014. (hi->bitrate_max+hi->bitrate_min)*.5;
  155015. }
  155016. if(hi->bitrate_reservoir<128.)
  155017. hi->bitrate_reservoir=128.;
  155018. }
  155019. return(0);
  155020. /* replacement ratemanage interface */
  155021. case OV_ECTL_RATEMANAGE2_GET:
  155022. {
  155023. struct ovectl_ratemanage2_arg *ai=
  155024. (struct ovectl_ratemanage2_arg *)arg;
  155025. if(ai==NULL)return OV_EINVAL;
  155026. ai->management_active=hi->managed;
  155027. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155028. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155029. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155030. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155031. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155032. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155033. }
  155034. return (0);
  155035. case OV_ECTL_RATEMANAGE2_SET:
  155036. {
  155037. struct ovectl_ratemanage2_arg *ai=
  155038. (struct ovectl_ratemanage2_arg *)arg;
  155039. if(ai==NULL){
  155040. hi->managed=0;
  155041. }else{
  155042. /* sanity check; only catch invariant violations */
  155043. if(ai->bitrate_limit_min_kbps>0 &&
  155044. ai->bitrate_average_kbps>0 &&
  155045. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155046. return OV_EINVAL;
  155047. if(ai->bitrate_limit_max_kbps>0 &&
  155048. ai->bitrate_average_kbps>0 &&
  155049. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155050. return OV_EINVAL;
  155051. if(ai->bitrate_limit_min_kbps>0 &&
  155052. ai->bitrate_limit_max_kbps>0 &&
  155053. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155054. return OV_EINVAL;
  155055. if(ai->bitrate_average_damping <= 0.)
  155056. return OV_EINVAL;
  155057. if(ai->bitrate_limit_reservoir_bits < 0)
  155058. return OV_EINVAL;
  155059. if(ai->bitrate_limit_reservoir_bias < 0.)
  155060. return OV_EINVAL;
  155061. if(ai->bitrate_limit_reservoir_bias > 1.)
  155062. return OV_EINVAL;
  155063. hi->managed=ai->management_active;
  155064. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155065. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155066. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155067. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155068. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155069. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155070. }
  155071. }
  155072. return 0;
  155073. case OV_ECTL_LOWPASS_GET:
  155074. {
  155075. double *farg=(double *)arg;
  155076. *farg=hi->lowpass_kHz;
  155077. }
  155078. return(0);
  155079. case OV_ECTL_LOWPASS_SET:
  155080. {
  155081. double *farg=(double *)arg;
  155082. hi->lowpass_kHz=*farg;
  155083. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155084. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155085. }
  155086. return(0);
  155087. case OV_ECTL_IBLOCK_GET:
  155088. {
  155089. double *farg=(double *)arg;
  155090. *farg=hi->impulse_noisetune;
  155091. }
  155092. return(0);
  155093. case OV_ECTL_IBLOCK_SET:
  155094. {
  155095. double *farg=(double *)arg;
  155096. hi->impulse_noisetune=*farg;
  155097. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155098. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155099. }
  155100. return(0);
  155101. }
  155102. return(OV_EIMPL);
  155103. }
  155104. return(OV_EINVAL);
  155105. }
  155106. #endif
  155107. /*** End of inlined file: vorbisenc.c ***/
  155108. /*** Start of inlined file: vorbisfile.c ***/
  155109. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155110. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155111. // tasks..
  155112. #if JUCE_MSVC
  155113. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155114. #endif
  155115. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155116. #if JUCE_USE_OGGVORBIS
  155117. #include <stdlib.h>
  155118. #include <stdio.h>
  155119. #include <errno.h>
  155120. #include <string.h>
  155121. #include <math.h>
  155122. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155123. one logical bitstream arranged end to end (the only form of Ogg
  155124. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155125. multiplexing] is not allowed in Vorbis) */
  155126. /* A Vorbis file can be played beginning to end (streamed) without
  155127. worrying ahead of time about chaining (see decoder_example.c). If
  155128. we have the whole file, however, and want random access
  155129. (seeking/scrubbing) or desire to know the total length/time of a
  155130. file, we need to account for the possibility of chaining. */
  155131. /* We can handle things a number of ways; we can determine the entire
  155132. bitstream structure right off the bat, or find pieces on demand.
  155133. This example determines and caches structure for the entire
  155134. bitstream, but builds a virtual decoder on the fly when moving
  155135. between links in the chain. */
  155136. /* There are also different ways to implement seeking. Enough
  155137. information exists in an Ogg bitstream to seek to
  155138. sample-granularity positions in the output. Or, one can seek by
  155139. picking some portion of the stream roughly in the desired area if
  155140. we only want coarse navigation through the stream. */
  155141. /*************************************************************************
  155142. * Many, many internal helpers. The intention is not to be confusing;
  155143. * rampant duplication and monolithic function implementation would be
  155144. * harder to understand anyway. The high level functions are last. Begin
  155145. * grokking near the end of the file */
  155146. /* read a little more data from the file/pipe into the ogg_sync framer
  155147. */
  155148. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155149. over 8k gets what they deserve */
  155150. static long _get_data(OggVorbis_File *vf){
  155151. errno=0;
  155152. if(vf->datasource){
  155153. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155154. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155155. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155156. if(bytes==0 && errno)return(-1);
  155157. return(bytes);
  155158. }else
  155159. return(0);
  155160. }
  155161. /* save a tiny smidge of verbosity to make the code more readable */
  155162. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155163. if(vf->datasource){
  155164. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155165. vf->offset=offset;
  155166. ogg_sync_reset(&vf->oy);
  155167. }else{
  155168. /* shouldn't happen unless someone writes a broken callback */
  155169. return;
  155170. }
  155171. }
  155172. /* The read/seek functions track absolute position within the stream */
  155173. /* from the head of the stream, get the next page. boundary specifies
  155174. if the function is allowed to fetch more data from the stream (and
  155175. how much) or only use internally buffered data.
  155176. boundary: -1) unbounded search
  155177. 0) read no additional data; use cached only
  155178. n) search for a new page beginning for n bytes
  155179. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155180. n) found a page at absolute offset n */
  155181. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155182. ogg_int64_t boundary){
  155183. if(boundary>0)boundary+=vf->offset;
  155184. while(1){
  155185. long more;
  155186. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155187. more=ogg_sync_pageseek(&vf->oy,og);
  155188. if(more<0){
  155189. /* skipped n bytes */
  155190. vf->offset-=more;
  155191. }else{
  155192. if(more==0){
  155193. /* send more paramedics */
  155194. if(!boundary)return(OV_FALSE);
  155195. {
  155196. long ret=_get_data(vf);
  155197. if(ret==0)return(OV_EOF);
  155198. if(ret<0)return(OV_EREAD);
  155199. }
  155200. }else{
  155201. /* got a page. Return the offset at the page beginning,
  155202. advance the internal offset past the page end */
  155203. ogg_int64_t ret=vf->offset;
  155204. vf->offset+=more;
  155205. return(ret);
  155206. }
  155207. }
  155208. }
  155209. }
  155210. /* find the latest page beginning before the current stream cursor
  155211. position. Much dirtier than the above as Ogg doesn't have any
  155212. backward search linkage. no 'readp' as it will certainly have to
  155213. read. */
  155214. /* returns offset or OV_EREAD, OV_FAULT */
  155215. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155216. ogg_int64_t begin=vf->offset;
  155217. ogg_int64_t end=begin;
  155218. ogg_int64_t ret;
  155219. ogg_int64_t offset=-1;
  155220. while(offset==-1){
  155221. begin-=CHUNKSIZE;
  155222. if(begin<0)
  155223. begin=0;
  155224. _seek_helper(vf,begin);
  155225. while(vf->offset<end){
  155226. ret=_get_next_page(vf,og,end-vf->offset);
  155227. if(ret==OV_EREAD)return(OV_EREAD);
  155228. if(ret<0){
  155229. break;
  155230. }else{
  155231. offset=ret;
  155232. }
  155233. }
  155234. }
  155235. /* we have the offset. Actually snork and hold the page now */
  155236. _seek_helper(vf,offset);
  155237. ret=_get_next_page(vf,og,CHUNKSIZE);
  155238. if(ret<0)
  155239. /* this shouldn't be possible */
  155240. return(OV_EFAULT);
  155241. return(offset);
  155242. }
  155243. /* finds each bitstream link one at a time using a bisection search
  155244. (has to begin by knowing the offset of the lb's initial page).
  155245. Recurses for each link so it can alloc the link storage after
  155246. finding them all, then unroll and fill the cache at the same time */
  155247. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155248. ogg_int64_t begin,
  155249. ogg_int64_t searched,
  155250. ogg_int64_t end,
  155251. long currentno,
  155252. long m){
  155253. ogg_int64_t endsearched=end;
  155254. ogg_int64_t next=end;
  155255. ogg_page og;
  155256. ogg_int64_t ret;
  155257. /* the below guards against garbage seperating the last and
  155258. first pages of two links. */
  155259. while(searched<endsearched){
  155260. ogg_int64_t bisect;
  155261. if(endsearched-searched<CHUNKSIZE){
  155262. bisect=searched;
  155263. }else{
  155264. bisect=(searched+endsearched)/2;
  155265. }
  155266. _seek_helper(vf,bisect);
  155267. ret=_get_next_page(vf,&og,-1);
  155268. if(ret==OV_EREAD)return(OV_EREAD);
  155269. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155270. endsearched=bisect;
  155271. if(ret>=0)next=ret;
  155272. }else{
  155273. searched=ret+og.header_len+og.body_len;
  155274. }
  155275. }
  155276. _seek_helper(vf,next);
  155277. ret=_get_next_page(vf,&og,-1);
  155278. if(ret==OV_EREAD)return(OV_EREAD);
  155279. if(searched>=end || ret<0){
  155280. vf->links=m+1;
  155281. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155282. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155283. vf->offsets[m+1]=searched;
  155284. }else{
  155285. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155286. end,ogg_page_serialno(&og),m+1);
  155287. if(ret==OV_EREAD)return(OV_EREAD);
  155288. }
  155289. vf->offsets[m]=begin;
  155290. vf->serialnos[m]=currentno;
  155291. return(0);
  155292. }
  155293. /* uses the local ogg_stream storage in vf; this is important for
  155294. non-streaming input sources */
  155295. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155296. long *serialno,ogg_page *og_ptr){
  155297. ogg_page og;
  155298. ogg_packet op;
  155299. int i,ret;
  155300. if(!og_ptr){
  155301. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155302. if(llret==OV_EREAD)return(OV_EREAD);
  155303. if(llret<0)return OV_ENOTVORBIS;
  155304. og_ptr=&og;
  155305. }
  155306. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155307. if(serialno)*serialno=vf->os.serialno;
  155308. vf->ready_state=STREAMSET;
  155309. /* extract the initial header from the first page and verify that the
  155310. Ogg bitstream is in fact Vorbis data */
  155311. vorbis_info_init(vi);
  155312. vorbis_comment_init(vc);
  155313. i=0;
  155314. while(i<3){
  155315. ogg_stream_pagein(&vf->os,og_ptr);
  155316. while(i<3){
  155317. int result=ogg_stream_packetout(&vf->os,&op);
  155318. if(result==0)break;
  155319. if(result==-1){
  155320. ret=OV_EBADHEADER;
  155321. goto bail_header;
  155322. }
  155323. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155324. goto bail_header;
  155325. }
  155326. i++;
  155327. }
  155328. if(i<3)
  155329. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155330. ret=OV_EBADHEADER;
  155331. goto bail_header;
  155332. }
  155333. }
  155334. return 0;
  155335. bail_header:
  155336. vorbis_info_clear(vi);
  155337. vorbis_comment_clear(vc);
  155338. vf->ready_state=OPENED;
  155339. return ret;
  155340. }
  155341. /* last step of the OggVorbis_File initialization; get all the
  155342. vorbis_info structs and PCM positions. Only called by the seekable
  155343. initialization (local stream storage is hacked slightly; pay
  155344. attention to how that's done) */
  155345. /* this is void and does not propogate errors up because we want to be
  155346. able to open and use damaged bitstreams as well as we can. Just
  155347. watch out for missing information for links in the OggVorbis_File
  155348. struct */
  155349. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155350. ogg_page og;
  155351. int i;
  155352. ogg_int64_t ret;
  155353. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155354. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155355. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155356. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155357. for(i=0;i<vf->links;i++){
  155358. if(i==0){
  155359. /* we already grabbed the initial header earlier. Just set the offset */
  155360. vf->dataoffsets[i]=dataoffset;
  155361. _seek_helper(vf,dataoffset);
  155362. }else{
  155363. /* seek to the location of the initial header */
  155364. _seek_helper(vf,vf->offsets[i]);
  155365. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155366. vf->dataoffsets[i]=-1;
  155367. }else{
  155368. vf->dataoffsets[i]=vf->offset;
  155369. }
  155370. }
  155371. /* fetch beginning PCM offset */
  155372. if(vf->dataoffsets[i]!=-1){
  155373. ogg_int64_t accumulated=0;
  155374. long lastblock=-1;
  155375. int result;
  155376. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155377. while(1){
  155378. ogg_packet op;
  155379. ret=_get_next_page(vf,&og,-1);
  155380. if(ret<0)
  155381. /* this should not be possible unless the file is
  155382. truncated/mangled */
  155383. break;
  155384. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155385. break;
  155386. /* count blocksizes of all frames in the page */
  155387. ogg_stream_pagein(&vf->os,&og);
  155388. while((result=ogg_stream_packetout(&vf->os,&op))){
  155389. if(result>0){ /* ignore holes */
  155390. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155391. if(lastblock!=-1)
  155392. accumulated+=(lastblock+thisblock)>>2;
  155393. lastblock=thisblock;
  155394. }
  155395. }
  155396. if(ogg_page_granulepos(&og)!=-1){
  155397. /* pcm offset of last packet on the first audio page */
  155398. accumulated= ogg_page_granulepos(&og)-accumulated;
  155399. break;
  155400. }
  155401. }
  155402. /* less than zero? This is a stream with samples trimmed off
  155403. the beginning, a normal occurrence; set the offset to zero */
  155404. if(accumulated<0)accumulated=0;
  155405. vf->pcmlengths[i*2]=accumulated;
  155406. }
  155407. /* get the PCM length of this link. To do this,
  155408. get the last page of the stream */
  155409. {
  155410. ogg_int64_t end=vf->offsets[i+1];
  155411. _seek_helper(vf,end);
  155412. while(1){
  155413. ret=_get_prev_page(vf,&og);
  155414. if(ret<0){
  155415. /* this should not be possible */
  155416. vorbis_info_clear(vf->vi+i);
  155417. vorbis_comment_clear(vf->vc+i);
  155418. break;
  155419. }
  155420. if(ogg_page_granulepos(&og)!=-1){
  155421. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155422. break;
  155423. }
  155424. vf->offset=ret;
  155425. }
  155426. }
  155427. }
  155428. }
  155429. static int _make_decode_ready(OggVorbis_File *vf){
  155430. if(vf->ready_state>STREAMSET)return 0;
  155431. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155432. if(vf->seekable){
  155433. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155434. return OV_EBADLINK;
  155435. }else{
  155436. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155437. return OV_EBADLINK;
  155438. }
  155439. vorbis_block_init(&vf->vd,&vf->vb);
  155440. vf->ready_state=INITSET;
  155441. vf->bittrack=0.f;
  155442. vf->samptrack=0.f;
  155443. return 0;
  155444. }
  155445. static int _open_seekable2(OggVorbis_File *vf){
  155446. long serialno=vf->current_serialno;
  155447. ogg_int64_t dataoffset=vf->offset, end;
  155448. ogg_page og;
  155449. /* we're partially open and have a first link header state in
  155450. storage in vf */
  155451. /* we can seek, so set out learning all about this file */
  155452. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155453. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155454. /* We get the offset for the last page of the physical bitstream.
  155455. Most OggVorbis files will contain a single logical bitstream */
  155456. end=_get_prev_page(vf,&og);
  155457. if(end<0)return(end);
  155458. /* more than one logical bitstream? */
  155459. if(ogg_page_serialno(&og)!=serialno){
  155460. /* Chained bitstream. Bisect-search each logical bitstream
  155461. section. Do so based on serial number only */
  155462. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155463. }else{
  155464. /* Only one logical bitstream */
  155465. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155466. }
  155467. /* the initial header memory is referenced by vf after; don't free it */
  155468. _prefetch_all_headers(vf,dataoffset);
  155469. return(ov_raw_seek(vf,0));
  155470. }
  155471. /* clear out the current logical bitstream decoder */
  155472. static void _decode_clear(OggVorbis_File *vf){
  155473. vorbis_dsp_clear(&vf->vd);
  155474. vorbis_block_clear(&vf->vb);
  155475. vf->ready_state=OPENED;
  155476. }
  155477. /* fetch and process a packet. Handles the case where we're at a
  155478. bitstream boundary and dumps the decoding machine. If the decoding
  155479. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155480. date (seek and read both use this. seek uses a special hack with
  155481. readp).
  155482. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155483. 0) need more data (only if readp==0)
  155484. 1) got a packet
  155485. */
  155486. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155487. ogg_packet *op_in,
  155488. int readp,
  155489. int spanp){
  155490. ogg_page og;
  155491. /* handle one packet. Try to fetch it from current stream state */
  155492. /* extract packets from page */
  155493. while(1){
  155494. /* process a packet if we can. If the machine isn't loaded,
  155495. neither is a page */
  155496. if(vf->ready_state==INITSET){
  155497. while(1) {
  155498. ogg_packet op;
  155499. ogg_packet *op_ptr=(op_in?op_in:&op);
  155500. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155501. ogg_int64_t granulepos;
  155502. op_in=NULL;
  155503. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155504. if(result>0){
  155505. /* got a packet. process it */
  155506. granulepos=op_ptr->granulepos;
  155507. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155508. header handling. The
  155509. header packets aren't
  155510. audio, so if/when we
  155511. submit them,
  155512. vorbis_synthesis will
  155513. reject them */
  155514. /* suck in the synthesis data and track bitrate */
  155515. {
  155516. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155517. /* for proper use of libvorbis within libvorbisfile,
  155518. oldsamples will always be zero. */
  155519. if(oldsamples)return(OV_EFAULT);
  155520. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155521. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155522. vf->bittrack+=op_ptr->bytes*8;
  155523. }
  155524. /* update the pcm offset. */
  155525. if(granulepos!=-1 && !op_ptr->e_o_s){
  155526. int link=(vf->seekable?vf->current_link:0);
  155527. int i,samples;
  155528. /* this packet has a pcm_offset on it (the last packet
  155529. completed on a page carries the offset) After processing
  155530. (above), we know the pcm position of the *last* sample
  155531. ready to be returned. Find the offset of the *first*
  155532. As an aside, this trick is inaccurate if we begin
  155533. reading anew right at the last page; the end-of-stream
  155534. granulepos declares the last frame in the stream, and the
  155535. last packet of the last page may be a partial frame.
  155536. So, we need a previous granulepos from an in-sequence page
  155537. to have a reference point. Thus the !op_ptr->e_o_s clause
  155538. above */
  155539. if(vf->seekable && link>0)
  155540. granulepos-=vf->pcmlengths[link*2];
  155541. if(granulepos<0)granulepos=0; /* actually, this
  155542. shouldn't be possible
  155543. here unless the stream
  155544. is very broken */
  155545. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155546. granulepos-=samples;
  155547. for(i=0;i<link;i++)
  155548. granulepos+=vf->pcmlengths[i*2+1];
  155549. vf->pcm_offset=granulepos;
  155550. }
  155551. return(1);
  155552. }
  155553. }
  155554. else
  155555. break;
  155556. }
  155557. }
  155558. if(vf->ready_state>=OPENED){
  155559. ogg_int64_t ret;
  155560. if(!readp)return(0);
  155561. if((ret=_get_next_page(vf,&og,-1))<0){
  155562. return(OV_EOF); /* eof.
  155563. leave unitialized */
  155564. }
  155565. /* bitrate tracking; add the header's bytes here, the body bytes
  155566. are done by packet above */
  155567. vf->bittrack+=og.header_len*8;
  155568. /* has our decoding just traversed a bitstream boundary? */
  155569. if(vf->ready_state==INITSET){
  155570. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155571. if(!spanp)
  155572. return(OV_EOF);
  155573. _decode_clear(vf);
  155574. if(!vf->seekable){
  155575. vorbis_info_clear(vf->vi);
  155576. vorbis_comment_clear(vf->vc);
  155577. }
  155578. }
  155579. }
  155580. }
  155581. /* Do we need to load a new machine before submitting the page? */
  155582. /* This is different in the seekable and non-seekable cases.
  155583. In the seekable case, we already have all the header
  155584. information loaded and cached; we just initialize the machine
  155585. with it and continue on our merry way.
  155586. In the non-seekable (streaming) case, we'll only be at a
  155587. boundary if we just left the previous logical bitstream and
  155588. we're now nominally at the header of the next bitstream
  155589. */
  155590. if(vf->ready_state!=INITSET){
  155591. int link;
  155592. if(vf->ready_state<STREAMSET){
  155593. if(vf->seekable){
  155594. vf->current_serialno=ogg_page_serialno(&og);
  155595. /* match the serialno to bitstream section. We use this rather than
  155596. offset positions to avoid problems near logical bitstream
  155597. boundaries */
  155598. for(link=0;link<vf->links;link++)
  155599. if(vf->serialnos[link]==vf->current_serialno)break;
  155600. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155601. stream. error out,
  155602. leave machine
  155603. uninitialized */
  155604. vf->current_link=link;
  155605. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155606. vf->ready_state=STREAMSET;
  155607. }else{
  155608. /* we're streaming */
  155609. /* fetch the three header packets, build the info struct */
  155610. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155611. if(ret)return(ret);
  155612. vf->current_link++;
  155613. link=0;
  155614. }
  155615. }
  155616. {
  155617. int ret=_make_decode_ready(vf);
  155618. if(ret<0)return ret;
  155619. }
  155620. }
  155621. ogg_stream_pagein(&vf->os,&og);
  155622. }
  155623. }
  155624. /* if, eg, 64 bit stdio is configured by default, this will build with
  155625. fseek64 */
  155626. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155627. if(f==NULL)return(-1);
  155628. return fseek(f,off,whence);
  155629. }
  155630. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155631. long ibytes, ov_callbacks callbacks){
  155632. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155633. int ret;
  155634. memset(vf,0,sizeof(*vf));
  155635. vf->datasource=f;
  155636. vf->callbacks = callbacks;
  155637. /* init the framing state */
  155638. ogg_sync_init(&vf->oy);
  155639. /* perhaps some data was previously read into a buffer for testing
  155640. against other stream types. Allow initialization from this
  155641. previously read data (as we may be reading from a non-seekable
  155642. stream) */
  155643. if(initial){
  155644. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155645. memcpy(buffer,initial,ibytes);
  155646. ogg_sync_wrote(&vf->oy,ibytes);
  155647. }
  155648. /* can we seek? Stevens suggests the seek test was portable */
  155649. if(offsettest!=-1)vf->seekable=1;
  155650. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155651. entry for partial open */
  155652. vf->links=1;
  155653. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155654. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155655. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155656. /* Try to fetch the headers, maintaining all the storage */
  155657. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155658. vf->datasource=NULL;
  155659. ov_clear(vf);
  155660. }else
  155661. vf->ready_state=PARTOPEN;
  155662. return(ret);
  155663. }
  155664. static int _ov_open2(OggVorbis_File *vf){
  155665. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  155666. vf->ready_state=OPENED;
  155667. if(vf->seekable){
  155668. int ret=_open_seekable2(vf);
  155669. if(ret){
  155670. vf->datasource=NULL;
  155671. ov_clear(vf);
  155672. }
  155673. return(ret);
  155674. }else
  155675. vf->ready_state=STREAMSET;
  155676. return 0;
  155677. }
  155678. /* clear out the OggVorbis_File struct */
  155679. int ov_clear(OggVorbis_File *vf){
  155680. if(vf){
  155681. vorbis_block_clear(&vf->vb);
  155682. vorbis_dsp_clear(&vf->vd);
  155683. ogg_stream_clear(&vf->os);
  155684. if(vf->vi && vf->links){
  155685. int i;
  155686. for(i=0;i<vf->links;i++){
  155687. vorbis_info_clear(vf->vi+i);
  155688. vorbis_comment_clear(vf->vc+i);
  155689. }
  155690. _ogg_free(vf->vi);
  155691. _ogg_free(vf->vc);
  155692. }
  155693. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  155694. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  155695. if(vf->serialnos)_ogg_free(vf->serialnos);
  155696. if(vf->offsets)_ogg_free(vf->offsets);
  155697. ogg_sync_clear(&vf->oy);
  155698. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  155699. memset(vf,0,sizeof(*vf));
  155700. }
  155701. #ifdef DEBUG_LEAKS
  155702. _VDBG_dump();
  155703. #endif
  155704. return(0);
  155705. }
  155706. /* inspects the OggVorbis file and finds/documents all the logical
  155707. bitstreams contained in it. Tries to be tolerant of logical
  155708. bitstream sections that are truncated/woogie.
  155709. return: -1) error
  155710. 0) OK
  155711. */
  155712. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155713. ov_callbacks callbacks){
  155714. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  155715. if(ret)return ret;
  155716. return _ov_open2(vf);
  155717. }
  155718. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155719. ov_callbacks callbacks = {
  155720. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155721. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155722. (int (*)(void *)) fclose,
  155723. (long (*)(void *)) ftell
  155724. };
  155725. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155726. }
  155727. /* cheap hack for game usage where downsampling is desirable; there's
  155728. no need for SRC as we can just do it cheaply in libvorbis. */
  155729. int ov_halfrate(OggVorbis_File *vf,int flag){
  155730. int i;
  155731. if(vf->vi==NULL)return OV_EINVAL;
  155732. if(!vf->seekable)return OV_EINVAL;
  155733. if(vf->ready_state>=STREAMSET)
  155734. _decode_clear(vf); /* clear out stream state; later on libvorbis
  155735. will be able to swap this on the fly, but
  155736. for now dumping the decode machine is needed
  155737. to reinit the MDCT lookups. 1.1 libvorbis
  155738. is planned to be able to switch on the fly */
  155739. for(i=0;i<vf->links;i++){
  155740. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  155741. ov_halfrate(vf,0);
  155742. return OV_EINVAL;
  155743. }
  155744. }
  155745. return 0;
  155746. }
  155747. int ov_halfrate_p(OggVorbis_File *vf){
  155748. if(vf->vi==NULL)return OV_EINVAL;
  155749. return vorbis_synthesis_halfrate_p(vf->vi);
  155750. }
  155751. /* Only partially open the vorbis file; test for Vorbisness, and load
  155752. the headers for the first chain. Do not seek (although test for
  155753. seekability). Use ov_test_open to finish opening the file, else
  155754. ov_clear to close/free it. Same return codes as open. */
  155755. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  155756. ov_callbacks callbacks)
  155757. {
  155758. return _ov_open1(f,vf,initial,ibytes,callbacks);
  155759. }
  155760. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  155761. ov_callbacks callbacks = {
  155762. (size_t (*)(void *, size_t, size_t, void *)) fread,
  155763. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  155764. (int (*)(void *)) fclose,
  155765. (long (*)(void *)) ftell
  155766. };
  155767. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  155768. }
  155769. int ov_test_open(OggVorbis_File *vf){
  155770. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  155771. return _ov_open2(vf);
  155772. }
  155773. /* How many logical bitstreams in this physical bitstream? */
  155774. long ov_streams(OggVorbis_File *vf){
  155775. return vf->links;
  155776. }
  155777. /* Is the FILE * associated with vf seekable? */
  155778. long ov_seekable(OggVorbis_File *vf){
  155779. return vf->seekable;
  155780. }
  155781. /* returns the bitrate for a given logical bitstream or the entire
  155782. physical bitstream. If the file is open for random access, it will
  155783. find the *actual* average bitrate. If the file is streaming, it
  155784. returns the nominal bitrate (if set) else the average of the
  155785. upper/lower bounds (if set) else -1 (unset).
  155786. If you want the actual bitrate field settings, get them from the
  155787. vorbis_info structs */
  155788. long ov_bitrate(OggVorbis_File *vf,int i){
  155789. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155790. if(i>=vf->links)return(OV_EINVAL);
  155791. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  155792. if(i<0){
  155793. ogg_int64_t bits=0;
  155794. int i;
  155795. float br;
  155796. for(i=0;i<vf->links;i++)
  155797. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  155798. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  155799. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  155800. * so this is slightly transformed to make it work.
  155801. */
  155802. br = bits/ov_time_total(vf,-1);
  155803. return(rint(br));
  155804. }else{
  155805. if(vf->seekable){
  155806. /* return the actual bitrate */
  155807. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  155808. }else{
  155809. /* return nominal if set */
  155810. if(vf->vi[i].bitrate_nominal>0){
  155811. return vf->vi[i].bitrate_nominal;
  155812. }else{
  155813. if(vf->vi[i].bitrate_upper>0){
  155814. if(vf->vi[i].bitrate_lower>0){
  155815. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  155816. }else{
  155817. return vf->vi[i].bitrate_upper;
  155818. }
  155819. }
  155820. return(OV_FALSE);
  155821. }
  155822. }
  155823. }
  155824. }
  155825. /* returns the actual bitrate since last call. returns -1 if no
  155826. additional data to offer since last call (or at beginning of stream),
  155827. EINVAL if stream is only partially open
  155828. */
  155829. long ov_bitrate_instant(OggVorbis_File *vf){
  155830. int link=(vf->seekable?vf->current_link:0);
  155831. long ret;
  155832. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155833. if(vf->samptrack==0)return(OV_FALSE);
  155834. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  155835. vf->bittrack=0.f;
  155836. vf->samptrack=0.f;
  155837. return(ret);
  155838. }
  155839. /* Guess */
  155840. long ov_serialnumber(OggVorbis_File *vf,int i){
  155841. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  155842. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  155843. if(i<0){
  155844. return(vf->current_serialno);
  155845. }else{
  155846. return(vf->serialnos[i]);
  155847. }
  155848. }
  155849. /* returns: total raw (compressed) length of content if i==-1
  155850. raw (compressed) length of that logical bitstream for i==0 to n
  155851. OV_EINVAL if the stream is not seekable (we can't know the length)
  155852. or if stream is only partially open
  155853. */
  155854. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  155855. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155856. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155857. if(i<0){
  155858. ogg_int64_t acc=0;
  155859. int i;
  155860. for(i=0;i<vf->links;i++)
  155861. acc+=ov_raw_total(vf,i);
  155862. return(acc);
  155863. }else{
  155864. return(vf->offsets[i+1]-vf->offsets[i]);
  155865. }
  155866. }
  155867. /* returns: total PCM length (samples) of content if i==-1 PCM length
  155868. (samples) of that logical bitstream for i==0 to n
  155869. OV_EINVAL if the stream is not seekable (we can't know the
  155870. length) or only partially open
  155871. */
  155872. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  155873. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155874. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155875. if(i<0){
  155876. ogg_int64_t acc=0;
  155877. int i;
  155878. for(i=0;i<vf->links;i++)
  155879. acc+=ov_pcm_total(vf,i);
  155880. return(acc);
  155881. }else{
  155882. return(vf->pcmlengths[i*2+1]);
  155883. }
  155884. }
  155885. /* returns: total seconds of content if i==-1
  155886. seconds in that logical bitstream for i==0 to n
  155887. OV_EINVAL if the stream is not seekable (we can't know the
  155888. length) or only partially open
  155889. */
  155890. double ov_time_total(OggVorbis_File *vf,int i){
  155891. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155892. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  155893. if(i<0){
  155894. double acc=0;
  155895. int i;
  155896. for(i=0;i<vf->links;i++)
  155897. acc+=ov_time_total(vf,i);
  155898. return(acc);
  155899. }else{
  155900. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  155901. }
  155902. }
  155903. /* seek to an offset relative to the *compressed* data. This also
  155904. scans packets to update the PCM cursor. It will cross a logical
  155905. bitstream boundary, but only if it can't get any packets out of the
  155906. tail of the bitstream we seek to (so no surprises).
  155907. returns zero on success, nonzero on failure */
  155908. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  155909. ogg_stream_state work_os;
  155910. if(vf->ready_state<OPENED)return(OV_EINVAL);
  155911. if(!vf->seekable)
  155912. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  155913. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  155914. /* don't yet clear out decoding machine (if it's initialized), in
  155915. the case we're in the same link. Restart the decode lapping, and
  155916. let _fetch_and_process_packet deal with a potential bitstream
  155917. boundary */
  155918. vf->pcm_offset=-1;
  155919. ogg_stream_reset_serialno(&vf->os,
  155920. vf->current_serialno); /* must set serialno */
  155921. vorbis_synthesis_restart(&vf->vd);
  155922. _seek_helper(vf,pos);
  155923. /* we need to make sure the pcm_offset is set, but we don't want to
  155924. advance the raw cursor past good packets just to get to the first
  155925. with a granulepos. That's not equivalent behavior to beginning
  155926. decoding as immediately after the seek position as possible.
  155927. So, a hack. We use two stream states; a local scratch state and
  155928. the shared vf->os stream state. We use the local state to
  155929. scan, and the shared state as a buffer for later decode.
  155930. Unfortuantely, on the last page we still advance to last packet
  155931. because the granulepos on the last page is not necessarily on a
  155932. packet boundary, and we need to make sure the granpos is
  155933. correct.
  155934. */
  155935. {
  155936. ogg_page og;
  155937. ogg_packet op;
  155938. int lastblock=0;
  155939. int accblock=0;
  155940. int thisblock;
  155941. int eosflag;
  155942. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  155943. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  155944. return from not necessarily
  155945. starting from the beginning */
  155946. while(1){
  155947. if(vf->ready_state>=STREAMSET){
  155948. /* snarf/scan a packet if we can */
  155949. int result=ogg_stream_packetout(&work_os,&op);
  155950. if(result>0){
  155951. if(vf->vi[vf->current_link].codec_setup){
  155952. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  155953. if(thisblock<0){
  155954. ogg_stream_packetout(&vf->os,NULL);
  155955. thisblock=0;
  155956. }else{
  155957. if(eosflag)
  155958. ogg_stream_packetout(&vf->os,NULL);
  155959. else
  155960. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  155961. }
  155962. if(op.granulepos!=-1){
  155963. int i,link=vf->current_link;
  155964. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  155965. if(granulepos<0)granulepos=0;
  155966. for(i=0;i<link;i++)
  155967. granulepos+=vf->pcmlengths[i*2+1];
  155968. vf->pcm_offset=granulepos-accblock;
  155969. break;
  155970. }
  155971. lastblock=thisblock;
  155972. continue;
  155973. }else
  155974. ogg_stream_packetout(&vf->os,NULL);
  155975. }
  155976. }
  155977. if(!lastblock){
  155978. if(_get_next_page(vf,&og,-1)<0){
  155979. vf->pcm_offset=ov_pcm_total(vf,-1);
  155980. break;
  155981. }
  155982. }else{
  155983. /* huh? Bogus stream with packets but no granulepos */
  155984. vf->pcm_offset=-1;
  155985. break;
  155986. }
  155987. /* has our decoding just traversed a bitstream boundary? */
  155988. if(vf->ready_state>=STREAMSET)
  155989. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155990. _decode_clear(vf); /* clear out stream state */
  155991. ogg_stream_clear(&work_os);
  155992. }
  155993. if(vf->ready_state<STREAMSET){
  155994. int link;
  155995. vf->current_serialno=ogg_page_serialno(&og);
  155996. for(link=0;link<vf->links;link++)
  155997. if(vf->serialnos[link]==vf->current_serialno)break;
  155998. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  155999. error out, leave
  156000. machine uninitialized */
  156001. vf->current_link=link;
  156002. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156003. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156004. vf->ready_state=STREAMSET;
  156005. }
  156006. ogg_stream_pagein(&vf->os,&og);
  156007. ogg_stream_pagein(&work_os,&og);
  156008. eosflag=ogg_page_eos(&og);
  156009. }
  156010. }
  156011. ogg_stream_clear(&work_os);
  156012. vf->bittrack=0.f;
  156013. vf->samptrack=0.f;
  156014. return(0);
  156015. seek_error:
  156016. /* dump the machine so we're in a known state */
  156017. vf->pcm_offset=-1;
  156018. ogg_stream_clear(&work_os);
  156019. _decode_clear(vf);
  156020. return OV_EBADLINK;
  156021. }
  156022. /* Page granularity seek (faster than sample granularity because we
  156023. don't do the last bit of decode to find a specific sample).
  156024. Seek to the last [granule marked] page preceeding the specified pos
  156025. location, such that decoding past the returned point will quickly
  156026. arrive at the requested position. */
  156027. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156028. int link=-1;
  156029. ogg_int64_t result=0;
  156030. ogg_int64_t total=ov_pcm_total(vf,-1);
  156031. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156032. if(!vf->seekable)return(OV_ENOSEEK);
  156033. if(pos<0 || pos>total)return(OV_EINVAL);
  156034. /* which bitstream section does this pcm offset occur in? */
  156035. for(link=vf->links-1;link>=0;link--){
  156036. total-=vf->pcmlengths[link*2+1];
  156037. if(pos>=total)break;
  156038. }
  156039. /* search within the logical bitstream for the page with the highest
  156040. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156041. missing pages or incorrect frame number information in the
  156042. bitstream could make our task impossible. Account for that (it
  156043. would be an error condition) */
  156044. /* new search algorithm by HB (Nicholas Vinen) */
  156045. {
  156046. ogg_int64_t end=vf->offsets[link+1];
  156047. ogg_int64_t begin=vf->offsets[link];
  156048. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156049. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156050. ogg_int64_t target=pos-total+begintime;
  156051. ogg_int64_t best=begin;
  156052. ogg_page og;
  156053. while(begin<end){
  156054. ogg_int64_t bisect;
  156055. if(end-begin<CHUNKSIZE){
  156056. bisect=begin;
  156057. }else{
  156058. /* take a (pretty decent) guess. */
  156059. bisect=begin +
  156060. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156061. if(bisect<=begin)
  156062. bisect=begin+1;
  156063. }
  156064. _seek_helper(vf,bisect);
  156065. while(begin<end){
  156066. result=_get_next_page(vf,&og,end-vf->offset);
  156067. if(result==OV_EREAD) goto seek_error;
  156068. if(result<0){
  156069. if(bisect<=begin+1)
  156070. end=begin; /* found it */
  156071. else{
  156072. if(bisect==0) goto seek_error;
  156073. bisect-=CHUNKSIZE;
  156074. if(bisect<=begin)bisect=begin+1;
  156075. _seek_helper(vf,bisect);
  156076. }
  156077. }else{
  156078. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156079. if(granulepos==-1)continue;
  156080. if(granulepos<target){
  156081. best=result; /* raw offset of packet with granulepos */
  156082. begin=vf->offset; /* raw offset of next page */
  156083. begintime=granulepos;
  156084. if(target-begintime>44100)break;
  156085. bisect=begin; /* *not* begin + 1 */
  156086. }else{
  156087. if(bisect<=begin+1)
  156088. end=begin; /* found it */
  156089. else{
  156090. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156091. end=result;
  156092. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156093. if(bisect<=begin)bisect=begin+1;
  156094. _seek_helper(vf,bisect);
  156095. }else{
  156096. end=result;
  156097. endtime=granulepos;
  156098. break;
  156099. }
  156100. }
  156101. }
  156102. }
  156103. }
  156104. }
  156105. /* found our page. seek to it, update pcm offset. Easier case than
  156106. raw_seek, don't keep packets preceeding granulepos. */
  156107. {
  156108. ogg_page og;
  156109. ogg_packet op;
  156110. /* seek */
  156111. _seek_helper(vf,best);
  156112. vf->pcm_offset=-1;
  156113. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156114. if(link!=vf->current_link){
  156115. /* Different link; dump entire decode machine */
  156116. _decode_clear(vf);
  156117. vf->current_link=link;
  156118. vf->current_serialno=ogg_page_serialno(&og);
  156119. vf->ready_state=STREAMSET;
  156120. }else{
  156121. vorbis_synthesis_restart(&vf->vd);
  156122. }
  156123. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156124. ogg_stream_pagein(&vf->os,&og);
  156125. /* pull out all but last packet; the one with granulepos */
  156126. while(1){
  156127. result=ogg_stream_packetpeek(&vf->os,&op);
  156128. if(result==0){
  156129. /* !!! the packet finishing this page originated on a
  156130. preceeding page. Keep fetching previous pages until we
  156131. get one with a granulepos or without the 'continued' flag
  156132. set. Then just use raw_seek for simplicity. */
  156133. _seek_helper(vf,best);
  156134. while(1){
  156135. result=_get_prev_page(vf,&og);
  156136. if(result<0) goto seek_error;
  156137. if(ogg_page_granulepos(&og)>-1 ||
  156138. !ogg_page_continued(&og)){
  156139. return ov_raw_seek(vf,result);
  156140. }
  156141. vf->offset=result;
  156142. }
  156143. }
  156144. if(result<0){
  156145. result = OV_EBADPACKET;
  156146. goto seek_error;
  156147. }
  156148. if(op.granulepos!=-1){
  156149. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156150. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156151. vf->pcm_offset+=total;
  156152. break;
  156153. }else
  156154. result=ogg_stream_packetout(&vf->os,NULL);
  156155. }
  156156. }
  156157. }
  156158. /* verify result */
  156159. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156160. result=OV_EFAULT;
  156161. goto seek_error;
  156162. }
  156163. vf->bittrack=0.f;
  156164. vf->samptrack=0.f;
  156165. return(0);
  156166. seek_error:
  156167. /* dump machine so we're in a known state */
  156168. vf->pcm_offset=-1;
  156169. _decode_clear(vf);
  156170. return (int)result;
  156171. }
  156172. /* seek to a sample offset relative to the decompressed pcm stream
  156173. returns zero on success, nonzero on failure */
  156174. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156175. int thisblock,lastblock=0;
  156176. int ret=ov_pcm_seek_page(vf,pos);
  156177. if(ret<0)return(ret);
  156178. if((ret=_make_decode_ready(vf)))return ret;
  156179. /* discard leading packets we don't need for the lapping of the
  156180. position we want; don't decode them */
  156181. while(1){
  156182. ogg_packet op;
  156183. ogg_page og;
  156184. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156185. if(ret>0){
  156186. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156187. if(thisblock<0){
  156188. ogg_stream_packetout(&vf->os,NULL);
  156189. continue; /* non audio packet */
  156190. }
  156191. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156192. if(vf->pcm_offset+((thisblock+
  156193. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156194. /* remove the packet from packet queue and track its granulepos */
  156195. ogg_stream_packetout(&vf->os,NULL);
  156196. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156197. only tracking, no
  156198. pcm_decode */
  156199. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156200. /* end of logical stream case is hard, especially with exact
  156201. length positioning. */
  156202. if(op.granulepos>-1){
  156203. int i;
  156204. /* always believe the stream markers */
  156205. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156206. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156207. for(i=0;i<vf->current_link;i++)
  156208. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156209. }
  156210. lastblock=thisblock;
  156211. }else{
  156212. if(ret<0 && ret!=OV_HOLE)break;
  156213. /* suck in a new page */
  156214. if(_get_next_page(vf,&og,-1)<0)break;
  156215. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156216. if(vf->ready_state<STREAMSET){
  156217. int link;
  156218. vf->current_serialno=ogg_page_serialno(&og);
  156219. for(link=0;link<vf->links;link++)
  156220. if(vf->serialnos[link]==vf->current_serialno)break;
  156221. if(link==vf->links)return(OV_EBADLINK);
  156222. vf->current_link=link;
  156223. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156224. vf->ready_state=STREAMSET;
  156225. ret=_make_decode_ready(vf);
  156226. if(ret)return ret;
  156227. lastblock=0;
  156228. }
  156229. ogg_stream_pagein(&vf->os,&og);
  156230. }
  156231. }
  156232. vf->bittrack=0.f;
  156233. vf->samptrack=0.f;
  156234. /* discard samples until we reach the desired position. Crossing a
  156235. logical bitstream boundary with abandon is OK. */
  156236. while(vf->pcm_offset<pos){
  156237. ogg_int64_t target=pos-vf->pcm_offset;
  156238. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156239. if(samples>target)samples=target;
  156240. vorbis_synthesis_read(&vf->vd,samples);
  156241. vf->pcm_offset+=samples;
  156242. if(samples<target)
  156243. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156244. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156245. }
  156246. return 0;
  156247. }
  156248. /* seek to a playback time relative to the decompressed pcm stream
  156249. returns zero on success, nonzero on failure */
  156250. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156251. /* translate time to PCM position and call ov_pcm_seek */
  156252. int link=-1;
  156253. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156254. double time_total=ov_time_total(vf,-1);
  156255. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156256. if(!vf->seekable)return(OV_ENOSEEK);
  156257. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156258. /* which bitstream section does this time offset occur in? */
  156259. for(link=vf->links-1;link>=0;link--){
  156260. pcm_total-=vf->pcmlengths[link*2+1];
  156261. time_total-=ov_time_total(vf,link);
  156262. if(seconds>=time_total)break;
  156263. }
  156264. /* enough information to convert time offset to pcm offset */
  156265. {
  156266. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156267. return(ov_pcm_seek(vf,target));
  156268. }
  156269. }
  156270. /* page-granularity version of ov_time_seek
  156271. returns zero on success, nonzero on failure */
  156272. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156273. /* translate time to PCM position and call ov_pcm_seek */
  156274. int link=-1;
  156275. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156276. double time_total=ov_time_total(vf,-1);
  156277. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156278. if(!vf->seekable)return(OV_ENOSEEK);
  156279. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156280. /* which bitstream section does this time offset occur in? */
  156281. for(link=vf->links-1;link>=0;link--){
  156282. pcm_total-=vf->pcmlengths[link*2+1];
  156283. time_total-=ov_time_total(vf,link);
  156284. if(seconds>=time_total)break;
  156285. }
  156286. /* enough information to convert time offset to pcm offset */
  156287. {
  156288. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156289. return(ov_pcm_seek_page(vf,target));
  156290. }
  156291. }
  156292. /* tell the current stream offset cursor. Note that seek followed by
  156293. tell will likely not give the set offset due to caching */
  156294. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156295. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156296. return(vf->offset);
  156297. }
  156298. /* return PCM offset (sample) of next PCM sample to be read */
  156299. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156300. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156301. return(vf->pcm_offset);
  156302. }
  156303. /* return time offset (seconds) of next PCM sample to be read */
  156304. double ov_time_tell(OggVorbis_File *vf){
  156305. int link=0;
  156306. ogg_int64_t pcm_total=0;
  156307. double time_total=0.f;
  156308. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156309. if(vf->seekable){
  156310. pcm_total=ov_pcm_total(vf,-1);
  156311. time_total=ov_time_total(vf,-1);
  156312. /* which bitstream section does this time offset occur in? */
  156313. for(link=vf->links-1;link>=0;link--){
  156314. pcm_total-=vf->pcmlengths[link*2+1];
  156315. time_total-=ov_time_total(vf,link);
  156316. if(vf->pcm_offset>=pcm_total)break;
  156317. }
  156318. }
  156319. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156320. }
  156321. /* link: -1) return the vorbis_info struct for the bitstream section
  156322. currently being decoded
  156323. 0-n) to request information for a specific bitstream section
  156324. In the case of a non-seekable bitstream, any call returns the
  156325. current bitstream. NULL in the case that the machine is not
  156326. initialized */
  156327. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156328. if(vf->seekable){
  156329. if(link<0)
  156330. if(vf->ready_state>=STREAMSET)
  156331. return vf->vi+vf->current_link;
  156332. else
  156333. return vf->vi;
  156334. else
  156335. if(link>=vf->links)
  156336. return NULL;
  156337. else
  156338. return vf->vi+link;
  156339. }else{
  156340. return vf->vi;
  156341. }
  156342. }
  156343. /* grr, strong typing, grr, no templates/inheritence, grr */
  156344. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156345. if(vf->seekable){
  156346. if(link<0)
  156347. if(vf->ready_state>=STREAMSET)
  156348. return vf->vc+vf->current_link;
  156349. else
  156350. return vf->vc;
  156351. else
  156352. if(link>=vf->links)
  156353. return NULL;
  156354. else
  156355. return vf->vc+link;
  156356. }else{
  156357. return vf->vc;
  156358. }
  156359. }
  156360. static int host_is_big_endian() {
  156361. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156362. unsigned char *bytewise = (unsigned char *)&pattern;
  156363. if (bytewise[0] == 0xfe) return 1;
  156364. return 0;
  156365. }
  156366. /* up to this point, everything could more or less hide the multiple
  156367. logical bitstream nature of chaining from the toplevel application
  156368. if the toplevel application didn't particularly care. However, at
  156369. the point that we actually read audio back, the multiple-section
  156370. nature must surface: Multiple bitstream sections do not necessarily
  156371. have to have the same number of channels or sampling rate.
  156372. ov_read returns the sequential logical bitstream number currently
  156373. being decoded along with the PCM data in order that the toplevel
  156374. application can take action on channel/sample rate changes. This
  156375. number will be incremented even for streamed (non-seekable) streams
  156376. (for seekable streams, it represents the actual logical bitstream
  156377. index within the physical bitstream. Note that the accessor
  156378. functions above are aware of this dichotomy).
  156379. input values: buffer) a buffer to hold packed PCM data for return
  156380. length) the byte length requested to be placed into buffer
  156381. bigendianp) should the data be packed LSB first (0) or
  156382. MSB first (1)
  156383. word) word size for output. currently 1 (byte) or
  156384. 2 (16 bit short)
  156385. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156386. 0) EOF
  156387. n) number of bytes of PCM actually returned. The
  156388. below works on a packet-by-packet basis, so the
  156389. return length is not related to the 'length' passed
  156390. in, just guaranteed to fit.
  156391. *section) set to the logical bitstream number */
  156392. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156393. int bigendianp,int word,int sgned,int *bitstream){
  156394. int i,j;
  156395. int host_endian = host_is_big_endian();
  156396. float **pcm;
  156397. long samples;
  156398. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156399. while(1){
  156400. if(vf->ready_state==INITSET){
  156401. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156402. if(samples)break;
  156403. }
  156404. /* suck in another packet */
  156405. {
  156406. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156407. if(ret==OV_EOF)
  156408. return(0);
  156409. if(ret<=0)
  156410. return(ret);
  156411. }
  156412. }
  156413. if(samples>0){
  156414. /* yay! proceed to pack data into the byte buffer */
  156415. long channels=ov_info(vf,-1)->channels;
  156416. long bytespersample=word * channels;
  156417. vorbis_fpu_control fpu;
  156418. (void) fpu; // (to avoid a warning about it being unused)
  156419. if(samples>length/bytespersample)samples=length/bytespersample;
  156420. if(samples <= 0)
  156421. return OV_EINVAL;
  156422. /* a tight loop to pack each size */
  156423. {
  156424. int val;
  156425. if(word==1){
  156426. int off=(sgned?0:128);
  156427. vorbis_fpu_setround(&fpu);
  156428. for(j=0;j<samples;j++)
  156429. for(i=0;i<channels;i++){
  156430. val=vorbis_ftoi(pcm[i][j]*128.f);
  156431. if(val>127)val=127;
  156432. else if(val<-128)val=-128;
  156433. *buffer++=val+off;
  156434. }
  156435. vorbis_fpu_restore(fpu);
  156436. }else{
  156437. int off=(sgned?0:32768);
  156438. if(host_endian==bigendianp){
  156439. if(sgned){
  156440. vorbis_fpu_setround(&fpu);
  156441. for(i=0;i<channels;i++) { /* It's faster in this order */
  156442. float *src=pcm[i];
  156443. short *dest=((short *)buffer)+i;
  156444. for(j=0;j<samples;j++) {
  156445. val=vorbis_ftoi(src[j]*32768.f);
  156446. if(val>32767)val=32767;
  156447. else if(val<-32768)val=-32768;
  156448. *dest=val;
  156449. dest+=channels;
  156450. }
  156451. }
  156452. vorbis_fpu_restore(fpu);
  156453. }else{
  156454. vorbis_fpu_setround(&fpu);
  156455. for(i=0;i<channels;i++) {
  156456. float *src=pcm[i];
  156457. short *dest=((short *)buffer)+i;
  156458. for(j=0;j<samples;j++) {
  156459. val=vorbis_ftoi(src[j]*32768.f);
  156460. if(val>32767)val=32767;
  156461. else if(val<-32768)val=-32768;
  156462. *dest=val+off;
  156463. dest+=channels;
  156464. }
  156465. }
  156466. vorbis_fpu_restore(fpu);
  156467. }
  156468. }else if(bigendianp){
  156469. vorbis_fpu_setround(&fpu);
  156470. for(j=0;j<samples;j++)
  156471. for(i=0;i<channels;i++){
  156472. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156473. if(val>32767)val=32767;
  156474. else if(val<-32768)val=-32768;
  156475. val+=off;
  156476. *buffer++=(val>>8);
  156477. *buffer++=(val&0xff);
  156478. }
  156479. vorbis_fpu_restore(fpu);
  156480. }else{
  156481. int val;
  156482. vorbis_fpu_setround(&fpu);
  156483. for(j=0;j<samples;j++)
  156484. for(i=0;i<channels;i++){
  156485. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156486. if(val>32767)val=32767;
  156487. else if(val<-32768)val=-32768;
  156488. val+=off;
  156489. *buffer++=(val&0xff);
  156490. *buffer++=(val>>8);
  156491. }
  156492. vorbis_fpu_restore(fpu);
  156493. }
  156494. }
  156495. }
  156496. vorbis_synthesis_read(&vf->vd,samples);
  156497. vf->pcm_offset+=samples;
  156498. if(bitstream)*bitstream=vf->current_link;
  156499. return(samples*bytespersample);
  156500. }else{
  156501. return(samples);
  156502. }
  156503. }
  156504. /* input values: pcm_channels) a float vector per channel of output
  156505. length) the sample length being read by the app
  156506. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156507. 0) EOF
  156508. n) number of samples of PCM actually returned. The
  156509. below works on a packet-by-packet basis, so the
  156510. return length is not related to the 'length' passed
  156511. in, just guaranteed to fit.
  156512. *section) set to the logical bitstream number */
  156513. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156514. int *bitstream){
  156515. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156516. while(1){
  156517. if(vf->ready_state==INITSET){
  156518. float **pcm;
  156519. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156520. if(samples){
  156521. if(pcm_channels)*pcm_channels=pcm;
  156522. if(samples>length)samples=length;
  156523. vorbis_synthesis_read(&vf->vd,samples);
  156524. vf->pcm_offset+=samples;
  156525. if(bitstream)*bitstream=vf->current_link;
  156526. return samples;
  156527. }
  156528. }
  156529. /* suck in another packet */
  156530. {
  156531. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156532. if(ret==OV_EOF)return(0);
  156533. if(ret<=0)return(ret);
  156534. }
  156535. }
  156536. }
  156537. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156538. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156539. ogg_int64_t off);
  156540. static void _ov_splice(float **pcm,float **lappcm,
  156541. int n1, int n2,
  156542. int ch1, int ch2,
  156543. float *w1, float *w2){
  156544. int i,j;
  156545. float *w=w1;
  156546. int n=n1;
  156547. if(n1>n2){
  156548. n=n2;
  156549. w=w2;
  156550. }
  156551. /* splice */
  156552. for(j=0;j<ch1 && j<ch2;j++){
  156553. float *s=lappcm[j];
  156554. float *d=pcm[j];
  156555. for(i=0;i<n;i++){
  156556. float wd=w[i]*w[i];
  156557. float ws=1.-wd;
  156558. d[i]=d[i]*wd + s[i]*ws;
  156559. }
  156560. }
  156561. /* window from zero */
  156562. for(;j<ch2;j++){
  156563. float *d=pcm[j];
  156564. for(i=0;i<n;i++){
  156565. float wd=w[i]*w[i];
  156566. d[i]=d[i]*wd;
  156567. }
  156568. }
  156569. }
  156570. /* make sure vf is INITSET */
  156571. static int _ov_initset(OggVorbis_File *vf){
  156572. while(1){
  156573. if(vf->ready_state==INITSET)break;
  156574. /* suck in another packet */
  156575. {
  156576. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156577. if(ret<0 && ret!=OV_HOLE)return(ret);
  156578. }
  156579. }
  156580. return 0;
  156581. }
  156582. /* make sure vf is INITSET and that we have a primed buffer; if
  156583. we're crosslapping at a stream section boundary, this also makes
  156584. sure we're sanity checking against the right stream information */
  156585. static int _ov_initprime(OggVorbis_File *vf){
  156586. vorbis_dsp_state *vd=&vf->vd;
  156587. while(1){
  156588. if(vf->ready_state==INITSET)
  156589. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156590. /* suck in another packet */
  156591. {
  156592. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156593. if(ret<0 && ret!=OV_HOLE)return(ret);
  156594. }
  156595. }
  156596. return 0;
  156597. }
  156598. /* grab enough data for lapping from vf; this may be in the form of
  156599. unreturned, already-decoded pcm, remaining PCM we will need to
  156600. decode, or synthetic postextrapolation from last packets. */
  156601. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156602. float **lappcm,int lapsize){
  156603. int lapcount=0,i;
  156604. float **pcm;
  156605. /* try first to decode the lapping data */
  156606. while(lapcount<lapsize){
  156607. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156608. if(samples){
  156609. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156610. for(i=0;i<vi->channels;i++)
  156611. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156612. lapcount+=samples;
  156613. vorbis_synthesis_read(vd,samples);
  156614. }else{
  156615. /* suck in another packet */
  156616. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156617. if(ret==OV_EOF)break;
  156618. }
  156619. }
  156620. if(lapcount<lapsize){
  156621. /* failed to get lapping data from normal decode; pry it from the
  156622. postextrapolation buffering, or the second half of the MDCT
  156623. from the last packet */
  156624. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156625. if(samples==0){
  156626. for(i=0;i<vi->channels;i++)
  156627. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156628. lapcount=lapsize;
  156629. }else{
  156630. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156631. for(i=0;i<vi->channels;i++)
  156632. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156633. lapcount+=samples;
  156634. }
  156635. }
  156636. }
  156637. /* this sets up crosslapping of a sample by using trailing data from
  156638. sample 1 and lapping it into the windowing buffer of sample 2 */
  156639. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156640. vorbis_info *vi1,*vi2;
  156641. float **lappcm;
  156642. float **pcm;
  156643. float *w1,*w2;
  156644. int n1,n2,i,ret,hs1,hs2;
  156645. if(vf1==vf2)return(0); /* degenerate case */
  156646. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156647. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156648. /* the relevant overlap buffers must be pre-checked and pre-primed
  156649. before looking at settings in the event that priming would cross
  156650. a bitstream boundary. So, do it now */
  156651. ret=_ov_initset(vf1);
  156652. if(ret)return(ret);
  156653. ret=_ov_initprime(vf2);
  156654. if(ret)return(ret);
  156655. vi1=ov_info(vf1,-1);
  156656. vi2=ov_info(vf2,-1);
  156657. hs1=ov_halfrate_p(vf1);
  156658. hs2=ov_halfrate_p(vf2);
  156659. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  156660. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  156661. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  156662. w1=vorbis_window(&vf1->vd,0);
  156663. w2=vorbis_window(&vf2->vd,0);
  156664. for(i=0;i<vi1->channels;i++)
  156665. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156666. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  156667. /* have a lapping buffer from vf1; now to splice it into the lapping
  156668. buffer of vf2 */
  156669. /* consolidate and expose the buffer. */
  156670. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  156671. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  156672. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  156673. /* splice */
  156674. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  156675. /* done */
  156676. return(0);
  156677. }
  156678. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  156679. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  156680. vorbis_info *vi;
  156681. float **lappcm;
  156682. float **pcm;
  156683. float *w1,*w2;
  156684. int n1,n2,ch1,ch2,hs;
  156685. int i,ret;
  156686. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156687. ret=_ov_initset(vf);
  156688. if(ret)return(ret);
  156689. vi=ov_info(vf,-1);
  156690. hs=ov_halfrate_p(vf);
  156691. ch1=vi->channels;
  156692. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156693. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156694. persistent; even if the decode state
  156695. from this link gets dumped, this
  156696. window array continues to exist */
  156697. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156698. for(i=0;i<ch1;i++)
  156699. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156700. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156701. /* have lapping data; seek and prime the buffer */
  156702. ret=localseek(vf,pos);
  156703. if(ret)return ret;
  156704. ret=_ov_initprime(vf);
  156705. if(ret)return(ret);
  156706. /* Guard against cross-link changes; they're perfectly legal */
  156707. vi=ov_info(vf,-1);
  156708. ch2=vi->channels;
  156709. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156710. w2=vorbis_window(&vf->vd,0);
  156711. /* consolidate and expose the buffer. */
  156712. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156713. /* splice */
  156714. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156715. /* done */
  156716. return(0);
  156717. }
  156718. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156719. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  156720. }
  156721. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156722. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  156723. }
  156724. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  156725. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  156726. }
  156727. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  156728. int (*localseek)(OggVorbis_File *,double)){
  156729. vorbis_info *vi;
  156730. float **lappcm;
  156731. float **pcm;
  156732. float *w1,*w2;
  156733. int n1,n2,ch1,ch2,hs;
  156734. int i,ret;
  156735. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156736. ret=_ov_initset(vf);
  156737. if(ret)return(ret);
  156738. vi=ov_info(vf,-1);
  156739. hs=ov_halfrate_p(vf);
  156740. ch1=vi->channels;
  156741. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  156742. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  156743. persistent; even if the decode state
  156744. from this link gets dumped, this
  156745. window array continues to exist */
  156746. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  156747. for(i=0;i<ch1;i++)
  156748. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  156749. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  156750. /* have lapping data; seek and prime the buffer */
  156751. ret=localseek(vf,pos);
  156752. if(ret)return ret;
  156753. ret=_ov_initprime(vf);
  156754. if(ret)return(ret);
  156755. /* Guard against cross-link changes; they're perfectly legal */
  156756. vi=ov_info(vf,-1);
  156757. ch2=vi->channels;
  156758. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  156759. w2=vorbis_window(&vf->vd,0);
  156760. /* consolidate and expose the buffer. */
  156761. vorbis_synthesis_lapout(&vf->vd,&pcm);
  156762. /* splice */
  156763. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  156764. /* done */
  156765. return(0);
  156766. }
  156767. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  156768. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  156769. }
  156770. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  156771. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  156772. }
  156773. #endif
  156774. /*** End of inlined file: vorbisfile.c ***/
  156775. /*** Start of inlined file: window.c ***/
  156776. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  156777. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156778. // tasks..
  156779. #if JUCE_MSVC
  156780. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156781. #endif
  156782. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  156783. #if JUCE_USE_OGGVORBIS
  156784. #include <stdlib.h>
  156785. #include <math.h>
  156786. static float vwin64[32] = {
  156787. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  156788. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  156789. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  156790. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  156791. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  156792. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  156793. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  156794. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  156795. };
  156796. static float vwin128[64] = {
  156797. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  156798. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  156799. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  156800. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  156801. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  156802. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  156803. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  156804. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  156805. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  156806. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  156807. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  156808. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  156809. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  156810. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  156811. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  156812. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  156813. };
  156814. static float vwin256[128] = {
  156815. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  156816. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  156817. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  156818. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  156819. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  156820. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  156821. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  156822. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  156823. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  156824. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  156825. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  156826. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  156827. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  156828. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  156829. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  156830. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  156831. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  156832. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  156833. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  156834. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  156835. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  156836. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  156837. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  156838. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  156839. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  156840. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  156841. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  156842. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  156843. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  156844. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  156845. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  156846. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  156847. };
  156848. static float vwin512[256] = {
  156849. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  156850. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  156851. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  156852. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  156853. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  156854. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  156855. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  156856. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  156857. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  156858. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  156859. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  156860. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  156861. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  156862. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  156863. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  156864. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  156865. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  156866. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  156867. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  156868. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  156869. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  156870. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  156871. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  156872. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  156873. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  156874. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  156875. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  156876. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  156877. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  156878. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  156879. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  156880. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  156881. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  156882. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  156883. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  156884. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  156885. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  156886. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  156887. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  156888. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  156889. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  156890. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  156891. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  156892. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  156893. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  156894. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  156895. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  156896. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  156897. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  156898. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  156899. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  156900. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  156901. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  156902. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  156903. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  156904. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  156905. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  156906. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  156907. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  156908. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  156909. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  156910. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  156911. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  156912. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  156913. };
  156914. static float vwin1024[512] = {
  156915. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  156916. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  156917. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  156918. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  156919. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  156920. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  156921. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  156922. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  156923. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  156924. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  156925. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  156926. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  156927. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  156928. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  156929. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  156930. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  156931. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  156932. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  156933. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  156934. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  156935. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  156936. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  156937. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  156938. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  156939. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  156940. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  156941. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  156942. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  156943. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  156944. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  156945. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  156946. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  156947. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  156948. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  156949. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  156950. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  156951. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  156952. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  156953. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  156954. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  156955. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  156956. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  156957. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  156958. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  156959. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  156960. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  156961. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  156962. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  156963. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  156964. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  156965. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  156966. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  156967. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  156968. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  156969. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  156970. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  156971. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  156972. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  156973. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  156974. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  156975. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  156976. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  156977. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  156978. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  156979. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  156980. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  156981. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  156982. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  156983. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  156984. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  156985. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  156986. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  156987. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  156988. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  156989. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  156990. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  156991. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  156992. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  156993. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  156994. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  156995. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  156996. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  156997. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  156998. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  156999. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157000. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157001. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157002. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157003. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157004. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157005. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157006. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157007. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157008. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157009. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157010. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157011. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157012. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157013. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157014. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157015. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157016. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157017. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157018. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157019. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157020. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157021. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157022. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157023. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157024. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157025. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157026. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157027. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157028. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157029. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157030. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157031. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157032. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157033. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157034. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157035. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157036. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157037. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157038. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157039. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157040. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157041. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157042. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157043. };
  157044. static float vwin2048[1024] = {
  157045. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157046. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157047. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157048. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157049. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157050. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157051. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157052. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157053. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157054. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157055. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157056. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157057. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157058. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157059. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157060. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157061. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157062. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157063. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157064. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157065. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157066. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157067. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157068. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157069. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157070. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157071. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157072. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157073. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157074. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157075. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157076. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157077. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157078. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157079. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157080. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157081. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157082. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157083. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157084. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157085. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157086. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157087. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157088. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157089. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157090. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157091. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157092. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157093. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157094. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157095. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157096. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157097. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157098. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157099. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157100. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157101. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157102. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157103. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157104. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157105. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157106. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157107. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157108. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157109. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157110. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157111. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157112. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157113. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157114. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157115. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157116. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157117. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157118. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157119. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157120. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157121. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157122. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157123. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157124. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157125. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157126. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157127. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157128. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157129. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157130. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157131. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157132. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157133. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157134. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157135. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157136. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157137. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157138. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157139. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157140. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157141. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157142. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157143. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157144. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157145. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157146. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157147. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157148. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157149. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157150. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157151. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157152. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157153. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157154. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157155. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157156. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157157. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157158. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157159. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157160. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157161. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157162. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157163. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157164. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157165. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157166. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157167. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157168. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157169. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157170. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157171. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157172. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157173. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157174. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157175. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157176. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157177. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157178. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157179. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157180. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157181. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157182. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157183. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157184. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157185. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157186. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157187. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157188. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157189. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157190. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157191. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157192. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157193. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157194. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157195. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157196. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157197. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157198. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157199. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157200. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157201. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157202. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157203. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157204. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157205. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157206. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157207. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157208. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157209. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157210. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157211. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157212. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157213. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157214. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157215. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157216. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157217. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157218. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157219. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157220. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157221. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157222. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157223. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157224. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157225. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157226. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157227. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157228. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157229. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157230. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157231. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157232. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157233. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157234. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157235. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157236. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157237. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157238. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157239. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157240. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157241. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157242. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157243. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157244. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157245. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157246. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157247. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157248. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157249. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157250. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157251. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157252. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157253. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157254. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157255. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157256. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157257. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157258. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157259. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157260. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157261. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157262. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157263. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157264. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157265. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157266. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157267. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157268. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157269. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157270. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157271. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157272. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157273. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157274. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157275. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157276. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157277. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157278. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157279. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157280. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157281. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157282. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157283. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157284. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157285. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157286. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157287. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157288. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157289. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157290. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157291. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157292. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157293. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157294. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157295. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157296. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157297. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157298. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157299. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157300. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157301. };
  157302. static float vwin4096[2048] = {
  157303. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157304. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157305. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157306. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157307. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157308. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157309. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157310. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157311. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157312. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157313. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157314. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157315. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157316. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157317. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157318. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157319. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157320. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157321. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157322. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157323. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157324. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157325. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157326. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157327. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157328. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157329. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157330. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157331. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157332. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157333. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157334. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157335. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157336. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157337. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157338. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157339. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157340. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157341. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157342. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157343. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157344. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157345. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157346. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157347. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157348. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157349. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157350. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157351. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157352. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157353. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157354. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157355. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157356. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157357. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157358. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157359. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157360. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157361. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157362. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157363. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157364. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157365. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157366. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157367. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157368. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157369. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157370. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157371. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157372. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157373. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157374. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157375. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157376. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157377. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157378. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157379. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157380. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157381. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157382. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157383. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157384. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157385. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157386. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157387. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157388. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157389. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157390. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157391. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157392. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157393. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157394. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157395. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157396. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157397. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157398. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157399. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157400. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157401. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157402. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157403. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157404. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157405. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157406. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157407. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157408. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157409. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157410. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157411. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157412. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157413. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157414. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157415. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157416. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157417. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157418. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157419. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157420. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157421. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157422. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157423. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157424. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157425. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157426. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157427. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157428. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157429. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157430. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157431. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157432. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157433. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157434. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157435. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157436. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157437. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157438. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157439. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157440. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157441. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157442. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157443. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157444. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157445. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157446. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157447. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157448. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157449. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157450. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157451. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157452. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157453. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157454. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157455. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157456. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157457. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157458. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157459. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157460. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157461. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157462. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157463. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157464. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157465. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157466. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157467. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157468. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157469. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157470. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157471. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157472. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157473. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157474. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157475. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157476. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157477. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157478. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157479. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157480. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157481. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157482. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157483. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157484. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157485. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157486. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157487. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157488. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157489. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157490. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157491. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157492. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157493. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157494. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157495. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157496. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157497. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157498. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157499. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157500. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157501. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157502. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157503. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157504. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157505. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157506. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157507. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157508. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157509. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157510. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157511. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157512. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157513. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157514. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157515. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157516. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157517. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157518. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157519. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157520. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157521. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157522. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157523. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157524. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157525. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157526. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157527. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157528. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157529. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157530. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157531. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157532. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157533. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157534. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157535. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157536. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157537. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157538. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157539. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157540. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157541. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157542. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157543. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157544. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157545. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157546. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157547. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157548. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157549. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157550. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157551. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157552. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157553. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157554. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157555. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157556. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157557. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157558. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157559. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157560. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157561. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157562. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157563. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157564. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157565. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157566. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157567. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157568. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157569. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157570. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157571. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157572. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157573. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157574. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157575. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157576. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157577. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157578. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157579. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157580. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157581. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157582. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157583. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157584. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157585. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157586. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157587. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157588. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157589. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157590. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157591. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157592. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157593. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157594. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157595. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157596. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157597. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157598. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157599. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157600. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157601. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157602. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157603. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157604. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157605. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157606. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157607. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157608. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157609. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157610. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157611. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157612. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157613. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157614. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157615. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157616. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157617. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157618. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157619. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157620. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157621. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157622. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157623. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157624. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157625. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157626. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157627. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157628. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157629. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157630. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157631. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157632. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157633. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157634. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157635. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157636. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157637. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157638. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157639. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157640. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157641. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157642. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157643. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157644. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157645. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157646. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157647. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157648. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157649. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157650. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157651. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157652. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157653. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157654. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157655. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157656. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157657. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157658. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157659. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  157660. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  157661. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  157662. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  157663. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  157664. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  157665. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  157666. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  157667. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  157668. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  157669. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  157670. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  157671. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  157672. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  157673. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  157674. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  157675. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  157676. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  157677. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  157678. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  157679. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  157680. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  157681. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  157682. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  157683. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  157684. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  157685. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  157686. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  157687. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  157688. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  157689. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  157690. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  157691. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  157692. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  157693. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  157694. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  157695. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  157696. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  157697. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  157698. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  157699. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  157700. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  157701. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  157702. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  157703. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  157704. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  157705. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  157706. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  157707. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  157708. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  157709. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  157710. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  157711. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  157712. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  157713. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  157714. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  157715. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  157716. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  157717. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  157718. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  157719. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  157720. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  157721. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  157722. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  157723. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  157724. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  157725. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  157726. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  157727. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  157728. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  157729. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  157730. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  157731. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  157732. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  157733. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  157734. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  157735. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  157736. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  157737. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  157738. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  157739. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  157740. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  157741. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  157742. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  157743. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  157744. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  157745. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  157746. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  157747. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  157748. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  157749. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  157750. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  157751. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  157752. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  157753. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  157754. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  157755. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  157756. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  157757. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  157758. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  157759. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  157760. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  157761. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  157762. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  157763. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  157764. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  157765. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  157766. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  157767. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  157768. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  157769. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  157770. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  157771. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  157772. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  157773. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  157774. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  157775. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  157776. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  157777. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  157778. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  157779. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  157780. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  157781. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  157782. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  157783. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  157784. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  157785. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  157786. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  157787. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  157788. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  157789. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  157790. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  157791. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  157792. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  157793. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  157794. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  157795. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  157796. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  157797. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  157798. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  157799. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  157800. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  157801. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  157802. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  157803. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  157804. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  157805. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  157806. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  157807. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  157808. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  157809. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  157810. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  157811. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  157812. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  157813. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  157814. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  157815. };
  157816. static float vwin8192[4096] = {
  157817. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  157818. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  157819. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  157820. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  157821. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  157822. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  157823. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  157824. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  157825. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  157826. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  157827. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  157828. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  157829. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  157830. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  157831. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  157832. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  157833. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  157834. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  157835. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  157836. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  157837. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  157838. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  157839. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  157840. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  157841. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  157842. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  157843. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  157844. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  157845. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  157846. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  157847. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  157848. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  157849. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  157850. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  157851. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  157852. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  157853. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  157854. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  157855. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  157856. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  157857. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  157858. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  157859. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  157860. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  157861. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  157862. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  157863. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  157864. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  157865. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  157866. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  157867. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  157868. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  157869. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  157870. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  157871. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  157872. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  157873. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  157874. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  157875. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  157876. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  157877. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  157878. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  157879. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  157880. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  157881. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  157882. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  157883. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  157884. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  157885. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  157886. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  157887. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  157888. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  157889. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  157890. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  157891. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  157892. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  157893. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  157894. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  157895. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  157896. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  157897. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  157898. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  157899. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  157900. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  157901. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  157902. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  157903. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  157904. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  157905. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  157906. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  157907. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  157908. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  157909. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  157910. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  157911. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  157912. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  157913. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  157914. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  157915. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  157916. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  157917. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  157918. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  157919. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  157920. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  157921. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  157922. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  157923. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  157924. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  157925. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  157926. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  157927. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  157928. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  157929. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  157930. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  157931. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  157932. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  157933. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  157934. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  157935. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  157936. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  157937. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  157938. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  157939. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  157940. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  157941. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  157942. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  157943. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  157944. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  157945. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  157946. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  157947. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  157948. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  157949. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  157950. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  157951. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  157952. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  157953. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  157954. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  157955. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  157956. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  157957. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  157958. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  157959. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  157960. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  157961. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  157962. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  157963. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  157964. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  157965. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  157966. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  157967. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  157968. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  157969. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  157970. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  157971. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  157972. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  157973. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  157974. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  157975. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  157976. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  157977. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  157978. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  157979. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  157980. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  157981. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  157982. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  157983. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  157984. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  157985. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  157986. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  157987. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  157988. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  157989. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  157990. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  157991. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  157992. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  157993. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  157994. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  157995. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  157996. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  157997. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  157998. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  157999. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158000. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158001. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158002. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158003. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158004. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158005. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158006. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158007. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158008. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158009. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158010. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158011. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158012. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158013. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158014. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158015. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158016. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158017. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158018. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158019. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158020. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158021. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158022. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158023. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158024. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158025. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158026. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158027. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158028. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158029. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158030. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158031. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158032. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158033. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158034. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158035. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158036. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158037. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158038. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158039. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158040. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158041. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158042. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158043. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158044. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158045. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158046. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158047. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158048. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158049. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158050. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158051. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158052. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158053. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158054. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158055. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158056. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158057. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158058. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158059. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158060. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158061. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158062. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158063. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158064. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158065. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158066. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158067. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158068. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158069. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158070. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158071. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158072. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158073. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158074. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158075. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158076. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158077. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158078. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158079. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158080. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158081. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158082. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158083. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158084. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158085. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158086. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158087. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158088. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158089. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158090. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158091. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158092. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158093. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158094. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158095. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158096. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158097. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158098. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158099. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158100. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158101. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158102. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158103. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158104. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158105. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158106. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158107. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158108. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158109. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158110. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158111. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158112. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158113. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158114. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158115. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158116. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158117. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158118. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158119. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158120. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158121. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158122. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158123. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158124. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158125. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158126. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158127. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158128. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158129. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158130. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158131. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158132. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158133. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158134. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158135. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158136. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158137. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158138. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158139. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158140. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158141. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158142. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158143. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158144. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158145. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158146. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158147. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158148. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158149. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158150. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158151. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158152. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158153. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158154. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158155. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158156. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158157. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158158. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158159. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158160. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158161. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158162. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158163. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158164. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158165. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158166. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158167. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158168. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158169. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158170. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158171. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158172. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158173. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158174. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158175. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158176. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158177. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158178. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158179. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158180. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158181. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158182. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158183. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158184. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158185. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158186. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158187. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158188. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158189. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158190. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158191. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158192. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158193. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158194. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158195. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158196. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158197. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158198. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158199. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158200. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158201. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158202. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158203. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158204. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158205. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158206. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158207. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158208. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158209. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158210. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158211. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158212. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158213. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158214. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158215. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158216. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158217. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158218. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158219. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158220. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158221. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158222. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158223. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158224. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158225. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158226. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158227. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158228. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158229. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158230. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158231. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158232. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158233. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158234. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158235. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158236. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158237. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158238. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158239. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158240. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158241. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158242. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158243. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158244. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158245. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158246. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158247. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158248. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158249. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158250. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158251. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158252. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158253. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158254. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158255. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158256. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158257. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158258. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158259. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158260. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158261. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158262. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158263. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158264. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158265. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158266. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158267. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158268. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158269. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158270. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158271. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158272. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158273. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158274. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158275. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158276. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158277. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158278. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158279. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158280. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158281. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158282. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158283. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158284. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158285. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158286. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158287. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158288. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158289. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158290. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158291. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158292. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158293. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158294. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158295. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158296. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158297. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158298. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158299. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158300. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158301. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158302. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158303. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158304. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158305. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158306. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158307. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158308. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158309. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158310. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158311. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158312. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158313. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158314. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158315. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158316. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158317. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158318. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158319. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158320. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158321. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158322. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158323. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158324. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158325. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158326. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158327. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158328. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158329. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158330. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158331. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158332. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158333. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158334. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158335. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158336. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158337. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158338. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158339. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158340. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158341. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158342. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158343. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158344. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158345. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158346. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158347. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158348. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158349. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158350. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158351. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158352. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158353. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158354. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158355. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158356. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158357. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158358. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158359. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158360. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158361. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158362. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158363. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158364. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158365. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158366. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158367. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158368. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158369. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158370. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158371. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158372. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158373. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158374. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158375. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158376. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158377. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158378. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158379. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158380. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158381. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158382. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158383. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158384. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158385. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158386. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158387. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158388. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158389. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158390. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158391. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158392. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158393. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158394. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158395. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158396. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158397. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158398. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158399. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158400. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158401. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158402. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158403. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158404. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158405. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158406. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158407. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158408. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158409. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158410. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158411. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158412. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158413. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158414. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158415. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158416. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158417. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158418. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158419. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158420. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158421. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158422. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158423. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158424. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158425. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158426. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158427. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158428. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158429. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158430. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158431. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158432. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158433. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158434. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158435. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158436. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158437. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158438. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158439. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158440. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158441. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158442. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158443. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158444. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158445. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158446. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158447. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158448. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158449. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158450. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158451. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158452. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158453. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158454. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158455. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158456. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158457. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158458. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158459. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158460. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158461. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158462. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158463. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158464. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158465. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158466. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158467. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158468. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158469. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158470. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158471. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158472. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158473. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158474. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158475. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158476. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158477. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158478. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158479. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158480. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158481. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158482. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158483. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158484. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158485. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158486. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158487. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158488. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158489. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158490. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158491. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158492. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158493. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158494. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158495. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158496. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158497. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158498. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158499. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158500. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158501. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158502. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158503. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158504. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158505. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158506. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158507. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158508. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158509. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158510. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158511. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158512. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158513. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158514. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158515. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158516. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158517. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158518. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158519. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158520. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158521. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158522. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158523. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158524. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158525. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158526. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158527. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158528. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158529. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158530. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158531. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158532. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158533. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158534. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158535. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158536. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158537. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158538. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158539. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158540. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158541. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158542. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158543. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158544. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158545. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158546. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158547. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158548. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158549. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158550. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158551. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158552. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158553. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158554. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158555. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158556. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158557. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158558. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158559. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158560. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158561. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158562. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158563. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158564. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158565. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158566. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158567. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158568. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158569. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158570. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158571. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158572. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158573. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158574. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158575. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158576. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158577. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158578. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158579. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158580. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158581. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158582. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158583. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158584. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158585. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158586. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158587. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158588. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158589. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158590. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158591. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158592. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158593. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158594. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158595. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158596. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158597. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158598. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158599. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158600. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158601. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158602. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158603. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158604. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158605. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158606. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158607. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158608. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158609. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158610. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158611. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158612. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158613. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158614. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158615. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158616. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158617. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158618. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158619. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158620. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158621. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158622. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158623. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158624. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158625. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158626. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158627. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158628. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158629. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158630. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158631. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158632. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158633. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158634. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158635. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158636. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158637. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158638. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158639. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158640. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158641. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158642. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158643. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158644. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158645. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158646. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158647. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158648. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158649. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158650. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158651. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158652. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158653. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158654. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158655. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158656. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158657. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158658. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158659. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  158660. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  158661. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  158662. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  158663. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  158664. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  158665. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  158666. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  158667. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  158668. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  158669. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  158670. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  158671. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  158672. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  158673. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  158674. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  158675. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  158676. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  158677. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  158678. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  158679. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  158680. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  158681. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  158682. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  158683. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  158684. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  158685. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  158686. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  158687. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  158688. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  158689. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  158690. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  158691. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  158692. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  158693. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  158694. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  158695. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  158696. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  158697. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  158698. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  158699. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  158700. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  158701. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  158702. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  158703. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  158704. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  158705. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  158706. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  158707. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  158708. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  158709. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  158710. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  158711. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  158712. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  158713. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  158714. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  158715. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  158716. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  158717. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  158718. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  158719. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  158720. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  158721. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  158722. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  158723. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  158724. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  158725. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  158726. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  158727. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  158728. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  158729. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  158730. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  158731. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  158732. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  158733. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  158734. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  158735. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  158736. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  158737. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  158738. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  158739. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  158740. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  158741. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  158742. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  158743. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  158744. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  158745. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  158746. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  158747. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  158748. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  158749. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  158750. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  158751. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  158752. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  158753. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  158754. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  158755. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  158756. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  158757. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  158758. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  158759. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  158760. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  158761. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  158762. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  158763. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  158764. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  158765. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  158766. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  158767. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  158768. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  158769. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  158770. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  158771. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  158772. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  158773. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  158774. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  158775. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  158776. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  158777. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  158778. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  158779. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  158780. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  158781. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  158782. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  158783. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  158784. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  158785. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  158786. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  158787. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  158788. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  158789. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  158790. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  158791. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  158792. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  158793. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  158794. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  158795. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  158796. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  158797. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  158798. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  158799. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  158800. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  158801. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  158802. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  158803. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  158804. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  158805. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  158806. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  158807. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  158808. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  158809. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  158810. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  158811. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  158812. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  158813. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  158814. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  158815. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  158816. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  158817. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  158818. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  158819. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  158820. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  158821. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  158822. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  158823. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  158824. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  158825. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  158826. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  158827. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  158828. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  158829. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  158830. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  158831. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  158832. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  158833. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  158834. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  158835. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  158836. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  158837. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  158838. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  158839. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158840. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158841. };
  158842. static float *vwin[8] = {
  158843. vwin64,
  158844. vwin128,
  158845. vwin256,
  158846. vwin512,
  158847. vwin1024,
  158848. vwin2048,
  158849. vwin4096,
  158850. vwin8192,
  158851. };
  158852. float *_vorbis_window_get(int n){
  158853. return vwin[n];
  158854. }
  158855. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  158856. int lW,int W,int nW){
  158857. lW=(W?lW:0);
  158858. nW=(W?nW:0);
  158859. {
  158860. float *windowLW=vwin[winno[lW]];
  158861. float *windowNW=vwin[winno[nW]];
  158862. long n=blocksizes[W];
  158863. long ln=blocksizes[lW];
  158864. long rn=blocksizes[nW];
  158865. long leftbegin=n/4-ln/4;
  158866. long leftend=leftbegin+ln/2;
  158867. long rightbegin=n/2+n/4-rn/4;
  158868. long rightend=rightbegin+rn/2;
  158869. int i,p;
  158870. for(i=0;i<leftbegin;i++)
  158871. d[i]=0.f;
  158872. for(p=0;i<leftend;i++,p++)
  158873. d[i]*=windowLW[p];
  158874. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  158875. d[i]*=windowNW[p];
  158876. for(;i<n;i++)
  158877. d[i]=0.f;
  158878. }
  158879. }
  158880. #endif
  158881. /*** End of inlined file: window.c ***/
  158882. #else
  158883. #include <vorbis/vorbisenc.h>
  158884. #include <vorbis/codec.h>
  158885. #include <vorbis/vorbisfile.h>
  158886. #endif
  158887. }
  158888. #undef max
  158889. #undef min
  158890. BEGIN_JUCE_NAMESPACE
  158891. static const char* const oggFormatName = "Ogg-Vorbis file";
  158892. static const char* const oggExtensions[] = { ".ogg", 0 };
  158893. class OggReader : public AudioFormatReader
  158894. {
  158895. OggVorbisNamespace::OggVorbis_File ovFile;
  158896. OggVorbisNamespace::ov_callbacks callbacks;
  158897. AudioSampleBuffer reservoir;
  158898. int reservoirStart, samplesInReservoir;
  158899. public:
  158900. OggReader (InputStream* const inp)
  158901. : AudioFormatReader (inp, TRANS (oggFormatName)),
  158902. reservoir (2, 4096),
  158903. reservoirStart (0),
  158904. samplesInReservoir (0)
  158905. {
  158906. using namespace OggVorbisNamespace;
  158907. sampleRate = 0;
  158908. usesFloatingPointData = true;
  158909. callbacks.read_func = &oggReadCallback;
  158910. callbacks.seek_func = &oggSeekCallback;
  158911. callbacks.close_func = &oggCloseCallback;
  158912. callbacks.tell_func = &oggTellCallback;
  158913. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  158914. if (err == 0)
  158915. {
  158916. vorbis_info* info = ov_info (&ovFile, -1);
  158917. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  158918. numChannels = info->channels;
  158919. bitsPerSample = 16;
  158920. sampleRate = info->rate;
  158921. reservoir.setSize (numChannels,
  158922. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  158923. }
  158924. }
  158925. ~OggReader()
  158926. {
  158927. OggVorbisNamespace::ov_clear (&ovFile);
  158928. }
  158929. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  158930. int64 startSampleInFile, int numSamples)
  158931. {
  158932. while (numSamples > 0)
  158933. {
  158934. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  158935. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  158936. {
  158937. // got a few samples overlapping, so use them before seeking..
  158938. const int numToUse = jmin (numSamples, numAvailable);
  158939. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  158940. if (destSamples[i] != 0)
  158941. memcpy (destSamples[i] + startOffsetInDestBuffer,
  158942. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  158943. sizeof (float) * numToUse);
  158944. startSampleInFile += numToUse;
  158945. numSamples -= numToUse;
  158946. startOffsetInDestBuffer += numToUse;
  158947. if (numSamples == 0)
  158948. break;
  158949. }
  158950. if (startSampleInFile < reservoirStart
  158951. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  158952. {
  158953. // buffer miss, so refill the reservoir
  158954. int bitStream = 0;
  158955. reservoirStart = jmax (0, (int) startSampleInFile);
  158956. samplesInReservoir = reservoir.getNumSamples();
  158957. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  158958. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  158959. int offset = 0;
  158960. int numToRead = samplesInReservoir;
  158961. while (numToRead > 0)
  158962. {
  158963. float** dataIn = 0;
  158964. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  158965. if (samps <= 0)
  158966. break;
  158967. jassert (samps <= numToRead);
  158968. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  158969. {
  158970. memcpy (reservoir.getSampleData (i, offset),
  158971. dataIn[i],
  158972. sizeof (float) * samps);
  158973. }
  158974. numToRead -= samps;
  158975. offset += samps;
  158976. }
  158977. if (numToRead > 0)
  158978. reservoir.clear (offset, numToRead);
  158979. }
  158980. }
  158981. if (numSamples > 0)
  158982. {
  158983. for (int i = numDestChannels; --i >= 0;)
  158984. if (destSamples[i] != 0)
  158985. zeromem (destSamples[i] + startOffsetInDestBuffer,
  158986. sizeof (int) * numSamples);
  158987. }
  158988. return true;
  158989. }
  158990. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  158991. {
  158992. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  158993. }
  158994. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  158995. {
  158996. InputStream* const in = static_cast <InputStream*> (datasource);
  158997. if (whence == SEEK_CUR)
  158998. offset += in->getPosition();
  158999. else if (whence == SEEK_END)
  159000. offset += in->getTotalLength();
  159001. in->setPosition (offset);
  159002. return 0;
  159003. }
  159004. static int oggCloseCallback (void*)
  159005. {
  159006. return 0;
  159007. }
  159008. static long oggTellCallback (void* datasource)
  159009. {
  159010. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159011. }
  159012. private:
  159013. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggReader);
  159014. };
  159015. class OggWriter : public AudioFormatWriter
  159016. {
  159017. OggVorbisNamespace::ogg_stream_state os;
  159018. OggVorbisNamespace::ogg_page og;
  159019. OggVorbisNamespace::ogg_packet op;
  159020. OggVorbisNamespace::vorbis_info vi;
  159021. OggVorbisNamespace::vorbis_comment vc;
  159022. OggVorbisNamespace::vorbis_dsp_state vd;
  159023. OggVorbisNamespace::vorbis_block vb;
  159024. public:
  159025. bool ok;
  159026. OggWriter (OutputStream* const out,
  159027. const double sampleRate,
  159028. const int numChannels,
  159029. const int bitsPerSample,
  159030. const int qualityIndex)
  159031. : AudioFormatWriter (out, TRANS (oggFormatName),
  159032. sampleRate,
  159033. numChannels,
  159034. bitsPerSample)
  159035. {
  159036. using namespace OggVorbisNamespace;
  159037. ok = false;
  159038. vorbis_info_init (&vi);
  159039. if (vorbis_encode_init_vbr (&vi,
  159040. numChannels,
  159041. (int) sampleRate,
  159042. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159043. {
  159044. vorbis_comment_init (&vc);
  159045. if (JUCEApplication::getInstance() != 0)
  159046. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8().getAddress()));
  159047. vorbis_analysis_init (&vd, &vi);
  159048. vorbis_block_init (&vd, &vb);
  159049. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159050. ogg_packet header;
  159051. ogg_packet header_comm;
  159052. ogg_packet header_code;
  159053. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159054. ogg_stream_packetin (&os, &header);
  159055. ogg_stream_packetin (&os, &header_comm);
  159056. ogg_stream_packetin (&os, &header_code);
  159057. for (;;)
  159058. {
  159059. if (ogg_stream_flush (&os, &og) == 0)
  159060. break;
  159061. output->write (og.header, og.header_len);
  159062. output->write (og.body, og.body_len);
  159063. }
  159064. ok = true;
  159065. }
  159066. }
  159067. ~OggWriter()
  159068. {
  159069. using namespace OggVorbisNamespace;
  159070. if (ok)
  159071. {
  159072. // write a zero-length packet to show ogg that we're finished..
  159073. write (0, 0);
  159074. ogg_stream_clear (&os);
  159075. vorbis_block_clear (&vb);
  159076. vorbis_dsp_clear (&vd);
  159077. vorbis_comment_clear (&vc);
  159078. vorbis_info_clear (&vi);
  159079. output->flush();
  159080. }
  159081. else
  159082. {
  159083. vorbis_info_clear (&vi);
  159084. output = 0; // to stop the base class deleting this, as it needs to be returned
  159085. // to the caller of createWriter()
  159086. }
  159087. }
  159088. bool write (const int** samplesToWrite, int numSamples)
  159089. {
  159090. using namespace OggVorbisNamespace;
  159091. if (! ok)
  159092. return false;
  159093. if (numSamples > 0)
  159094. {
  159095. const double gain = 1.0 / 0x80000000u;
  159096. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159097. for (int i = numChannels; --i >= 0;)
  159098. {
  159099. float* const dst = vorbisBuffer[i];
  159100. const int* const src = samplesToWrite [i];
  159101. if (src != 0 && dst != 0)
  159102. {
  159103. for (int j = 0; j < numSamples; ++j)
  159104. dst[j] = (float) (src[j] * gain);
  159105. }
  159106. }
  159107. }
  159108. vorbis_analysis_wrote (&vd, numSamples);
  159109. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159110. {
  159111. vorbis_analysis (&vb, 0);
  159112. vorbis_bitrate_addblock (&vb);
  159113. while (vorbis_bitrate_flushpacket (&vd, &op))
  159114. {
  159115. ogg_stream_packetin (&os, &op);
  159116. for (;;)
  159117. {
  159118. if (ogg_stream_pageout (&os, &og) == 0)
  159119. break;
  159120. output->write (og.header, og.header_len);
  159121. output->write (og.body, og.body_len);
  159122. if (ogg_page_eos (&og))
  159123. break;
  159124. }
  159125. }
  159126. }
  159127. return true;
  159128. }
  159129. private:
  159130. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OggWriter);
  159131. };
  159132. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159133. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159134. {
  159135. }
  159136. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159137. {
  159138. }
  159139. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159140. {
  159141. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159142. return Array <int> (rates);
  159143. }
  159144. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159145. {
  159146. const int depths[] = { 32, 0 };
  159147. return Array <int> (depths);
  159148. }
  159149. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159150. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159151. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159152. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159153. const bool deleteStreamIfOpeningFails)
  159154. {
  159155. ScopedPointer <OggReader> r (new OggReader (in));
  159156. if (r->sampleRate != 0)
  159157. return r.release();
  159158. if (! deleteStreamIfOpeningFails)
  159159. r->input = 0;
  159160. return 0;
  159161. }
  159162. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159163. double sampleRate,
  159164. unsigned int numChannels,
  159165. int bitsPerSample,
  159166. const StringPairArray& /*metadataValues*/,
  159167. int qualityOptionIndex)
  159168. {
  159169. ScopedPointer <OggWriter> w (new OggWriter (out,
  159170. sampleRate,
  159171. numChannels,
  159172. bitsPerSample,
  159173. qualityOptionIndex));
  159174. return w->ok ? w.release() : 0;
  159175. }
  159176. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159177. {
  159178. StringArray s;
  159179. s.add ("Low Quality");
  159180. s.add ("Medium Quality");
  159181. s.add ("High Quality");
  159182. return s;
  159183. }
  159184. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159185. {
  159186. FileInputStream* const in = source.createInputStream();
  159187. if (in != 0)
  159188. {
  159189. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159190. if (r != 0)
  159191. {
  159192. const int64 numSamps = r->lengthInSamples;
  159193. r = 0;
  159194. const int64 fileNumSamps = source.getSize() / 4;
  159195. const double ratio = numSamps / (double) fileNumSamps;
  159196. if (ratio > 12.0)
  159197. return 0;
  159198. else if (ratio > 6.0)
  159199. return 1;
  159200. else
  159201. return 2;
  159202. }
  159203. }
  159204. return 1;
  159205. }
  159206. END_JUCE_NAMESPACE
  159207. #endif
  159208. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159209. #endif
  159210. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159211. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159212. #if JUCE_MSVC
  159213. #pragma warning (push)
  159214. #endif
  159215. namespace jpeglibNamespace
  159216. {
  159217. #if JUCE_INCLUDE_JPEGLIB_CODE
  159218. #if JUCE_MINGW
  159219. typedef unsigned char boolean;
  159220. #endif
  159221. #define JPEG_INTERNALS
  159222. #undef FAR
  159223. /*** Start of inlined file: jpeglib.h ***/
  159224. #ifndef JPEGLIB_H
  159225. #define JPEGLIB_H
  159226. /*
  159227. * First we include the configuration files that record how this
  159228. * installation of the JPEG library is set up. jconfig.h can be
  159229. * generated automatically for many systems. jmorecfg.h contains
  159230. * manual configuration options that most people need not worry about.
  159231. */
  159232. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159233. /*** Start of inlined file: jconfig.h ***/
  159234. /* see jconfig.doc for explanations */
  159235. // disable all the warnings under MSVC
  159236. #ifdef _MSC_VER
  159237. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159238. #endif
  159239. #ifdef __BORLANDC__
  159240. #pragma warn -8057
  159241. #pragma warn -8019
  159242. #pragma warn -8004
  159243. #pragma warn -8008
  159244. #endif
  159245. #define HAVE_PROTOTYPES
  159246. #define HAVE_UNSIGNED_CHAR
  159247. #define HAVE_UNSIGNED_SHORT
  159248. /* #define void char */
  159249. /* #define const */
  159250. #undef CHAR_IS_UNSIGNED
  159251. #define HAVE_STDDEF_H
  159252. #define HAVE_STDLIB_H
  159253. #undef NEED_BSD_STRINGS
  159254. #undef NEED_SYS_TYPES_H
  159255. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159256. #undef NEED_SHORT_EXTERNAL_NAMES
  159257. #undef INCOMPLETE_TYPES_BROKEN
  159258. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159259. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159260. typedef unsigned char boolean;
  159261. #endif
  159262. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159263. #ifdef JPEG_INTERNALS
  159264. #undef RIGHT_SHIFT_IS_UNSIGNED
  159265. #endif /* JPEG_INTERNALS */
  159266. #ifdef JPEG_CJPEG_DJPEG
  159267. #define BMP_SUPPORTED /* BMP image file format */
  159268. #define GIF_SUPPORTED /* GIF image file format */
  159269. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159270. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159271. #define TARGA_SUPPORTED /* Targa image file format */
  159272. #define TWO_FILE_COMMANDLINE /* optional */
  159273. #define USE_SETMODE /* Microsoft has setmode() */
  159274. #undef NEED_SIGNAL_CATCHER
  159275. #undef DONT_USE_B_MODE
  159276. #undef PROGRESS_REPORT /* optional */
  159277. #endif /* JPEG_CJPEG_DJPEG */
  159278. /*** End of inlined file: jconfig.h ***/
  159279. /* widely used configuration options */
  159280. #endif
  159281. /*** Start of inlined file: jmorecfg.h ***/
  159282. /*
  159283. * Define BITS_IN_JSAMPLE as either
  159284. * 8 for 8-bit sample values (the usual setting)
  159285. * 12 for 12-bit sample values
  159286. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159287. * JPEG standard, and the IJG code does not support anything else!
  159288. * We do not support run-time selection of data precision, sorry.
  159289. */
  159290. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159291. /*
  159292. * Maximum number of components (color channels) allowed in JPEG image.
  159293. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159294. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159295. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159296. * really short on memory. (Each allowed component costs a hundred or so
  159297. * bytes of storage, whether actually used in an image or not.)
  159298. */
  159299. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159300. /*
  159301. * Basic data types.
  159302. * You may need to change these if you have a machine with unusual data
  159303. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159304. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159305. * but it had better be at least 16.
  159306. */
  159307. /* Representation of a single sample (pixel element value).
  159308. * We frequently allocate large arrays of these, so it's important to keep
  159309. * them small. But if you have memory to burn and access to char or short
  159310. * arrays is very slow on your hardware, you might want to change these.
  159311. */
  159312. #if BITS_IN_JSAMPLE == 8
  159313. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159314. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159315. */
  159316. #ifdef HAVE_UNSIGNED_CHAR
  159317. typedef unsigned char JSAMPLE;
  159318. #define GETJSAMPLE(value) ((int) (value))
  159319. #else /* not HAVE_UNSIGNED_CHAR */
  159320. typedef char JSAMPLE;
  159321. #ifdef CHAR_IS_UNSIGNED
  159322. #define GETJSAMPLE(value) ((int) (value))
  159323. #else
  159324. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159325. #endif /* CHAR_IS_UNSIGNED */
  159326. #endif /* HAVE_UNSIGNED_CHAR */
  159327. #define MAXJSAMPLE 255
  159328. #define CENTERJSAMPLE 128
  159329. #endif /* BITS_IN_JSAMPLE == 8 */
  159330. #if BITS_IN_JSAMPLE == 12
  159331. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159332. * On nearly all machines "short" will do nicely.
  159333. */
  159334. typedef short JSAMPLE;
  159335. #define GETJSAMPLE(value) ((int) (value))
  159336. #define MAXJSAMPLE 4095
  159337. #define CENTERJSAMPLE 2048
  159338. #endif /* BITS_IN_JSAMPLE == 12 */
  159339. /* Representation of a DCT frequency coefficient.
  159340. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159341. * Again, we allocate large arrays of these, but you can change to int
  159342. * if you have memory to burn and "short" is really slow.
  159343. */
  159344. typedef short JCOEF;
  159345. /* Compressed datastreams are represented as arrays of JOCTET.
  159346. * These must be EXACTLY 8 bits wide, at least once they are written to
  159347. * external storage. Note that when using the stdio data source/destination
  159348. * managers, this is also the data type passed to fread/fwrite.
  159349. */
  159350. #ifdef HAVE_UNSIGNED_CHAR
  159351. typedef unsigned char JOCTET;
  159352. #define GETJOCTET(value) (value)
  159353. #else /* not HAVE_UNSIGNED_CHAR */
  159354. typedef char JOCTET;
  159355. #ifdef CHAR_IS_UNSIGNED
  159356. #define GETJOCTET(value) (value)
  159357. #else
  159358. #define GETJOCTET(value) ((value) & 0xFF)
  159359. #endif /* CHAR_IS_UNSIGNED */
  159360. #endif /* HAVE_UNSIGNED_CHAR */
  159361. /* These typedefs are used for various table entries and so forth.
  159362. * They must be at least as wide as specified; but making them too big
  159363. * won't cost a huge amount of memory, so we don't provide special
  159364. * extraction code like we did for JSAMPLE. (In other words, these
  159365. * typedefs live at a different point on the speed/space tradeoff curve.)
  159366. */
  159367. /* UINT8 must hold at least the values 0..255. */
  159368. #ifdef HAVE_UNSIGNED_CHAR
  159369. typedef unsigned char UINT8;
  159370. #else /* not HAVE_UNSIGNED_CHAR */
  159371. #ifdef CHAR_IS_UNSIGNED
  159372. typedef char UINT8;
  159373. #else /* not CHAR_IS_UNSIGNED */
  159374. typedef short UINT8;
  159375. #endif /* CHAR_IS_UNSIGNED */
  159376. #endif /* HAVE_UNSIGNED_CHAR */
  159377. /* UINT16 must hold at least the values 0..65535. */
  159378. #ifdef HAVE_UNSIGNED_SHORT
  159379. typedef unsigned short UINT16;
  159380. #else /* not HAVE_UNSIGNED_SHORT */
  159381. typedef unsigned int UINT16;
  159382. #endif /* HAVE_UNSIGNED_SHORT */
  159383. /* INT16 must hold at least the values -32768..32767. */
  159384. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159385. typedef short INT16;
  159386. #endif
  159387. /* INT32 must hold at least signed 32-bit values. */
  159388. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159389. typedef long INT32;
  159390. #endif
  159391. /* Datatype used for image dimensions. The JPEG standard only supports
  159392. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159393. * "unsigned int" is sufficient on all machines. However, if you need to
  159394. * handle larger images and you don't mind deviating from the spec, you
  159395. * can change this datatype.
  159396. */
  159397. typedef unsigned int JDIMENSION;
  159398. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159399. /* These macros are used in all function definitions and extern declarations.
  159400. * You could modify them if you need to change function linkage conventions;
  159401. * in particular, you'll need to do that to make the library a Windows DLL.
  159402. * Another application is to make all functions global for use with debuggers
  159403. * or code profilers that require it.
  159404. */
  159405. /* a function called through method pointers: */
  159406. #define METHODDEF(type) static type
  159407. /* a function used only in its module: */
  159408. #define LOCAL(type) static type
  159409. /* a function referenced thru EXTERNs: */
  159410. #define GLOBAL(type) type
  159411. /* a reference to a GLOBAL function: */
  159412. #define EXTERN(type) extern type
  159413. /* This macro is used to declare a "method", that is, a function pointer.
  159414. * We want to supply prototype parameters if the compiler can cope.
  159415. * Note that the arglist parameter must be parenthesized!
  159416. * Again, you can customize this if you need special linkage keywords.
  159417. */
  159418. #ifdef HAVE_PROTOTYPES
  159419. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159420. #else
  159421. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159422. #endif
  159423. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159424. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159425. * by just saying "FAR *" where such a pointer is needed. In a few places
  159426. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159427. */
  159428. #ifdef NEED_FAR_POINTERS
  159429. #define FAR far
  159430. #else
  159431. #define FAR
  159432. #endif
  159433. /*
  159434. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159435. * in standard header files. Or you may have conflicts with application-
  159436. * specific header files that you want to include together with these files.
  159437. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159438. */
  159439. #ifndef HAVE_BOOLEAN
  159440. typedef int boolean;
  159441. #endif
  159442. #ifndef FALSE /* in case these macros already exist */
  159443. #define FALSE 0 /* values of boolean */
  159444. #endif
  159445. #ifndef TRUE
  159446. #define TRUE 1
  159447. #endif
  159448. /*
  159449. * The remaining options affect code selection within the JPEG library,
  159450. * but they don't need to be visible to most applications using the library.
  159451. * To minimize application namespace pollution, the symbols won't be
  159452. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159453. */
  159454. #ifdef JPEG_INTERNALS
  159455. #define JPEG_INTERNAL_OPTIONS
  159456. #endif
  159457. #ifdef JPEG_INTERNAL_OPTIONS
  159458. /*
  159459. * These defines indicate whether to include various optional functions.
  159460. * Undefining some of these symbols will produce a smaller but less capable
  159461. * library. Note that you can leave certain source files out of the
  159462. * compilation/linking process if you've #undef'd the corresponding symbols.
  159463. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159464. */
  159465. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159466. /* Capability options common to encoder and decoder: */
  159467. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159468. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159469. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159470. /* Encoder capability options: */
  159471. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159472. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159473. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159474. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159475. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159476. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159477. * precision, so jchuff.c normally uses entropy optimization to compute
  159478. * usable tables for higher precision. If you don't want to do optimization,
  159479. * you'll have to supply different default Huffman tables.
  159480. * The exact same statements apply for progressive JPEG: the default tables
  159481. * don't work for progressive mode. (This may get fixed, however.)
  159482. */
  159483. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159484. /* Decoder capability options: */
  159485. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159486. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159487. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159488. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159489. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159490. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159491. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159492. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159493. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159494. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159495. /* more capability options later, no doubt */
  159496. /*
  159497. * Ordering of RGB data in scanlines passed to or from the application.
  159498. * If your application wants to deal with data in the order B,G,R, just
  159499. * change these macros. You can also deal with formats such as R,G,B,X
  159500. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159501. * the offsets will also change the order in which colormap data is organized.
  159502. * RESTRICTIONS:
  159503. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159504. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159505. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159506. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159507. * is not 3 (they don't understand about dummy color components!). So you
  159508. * can't use color quantization if you change that value.
  159509. */
  159510. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159511. #define RGB_GREEN 1 /* Offset of Green */
  159512. #define RGB_BLUE 2 /* Offset of Blue */
  159513. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159514. /* Definitions for speed-related optimizations. */
  159515. /* If your compiler supports inline functions, define INLINE
  159516. * as the inline keyword; otherwise define it as empty.
  159517. */
  159518. #ifndef INLINE
  159519. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159520. #define INLINE __inline__
  159521. #endif
  159522. #ifndef INLINE
  159523. #define INLINE /* default is to define it as empty */
  159524. #endif
  159525. #endif
  159526. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159527. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159528. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159529. */
  159530. #ifndef MULTIPLIER
  159531. #define MULTIPLIER int /* type for fastest integer multiply */
  159532. #endif
  159533. /* FAST_FLOAT should be either float or double, whichever is done faster
  159534. * by your compiler. (Note that this type is only used in the floating point
  159535. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159536. * Typically, float is faster in ANSI C compilers, while double is faster in
  159537. * pre-ANSI compilers (because they insist on converting to double anyway).
  159538. * The code below therefore chooses float if we have ANSI-style prototypes.
  159539. */
  159540. #ifndef FAST_FLOAT
  159541. #ifdef HAVE_PROTOTYPES
  159542. #define FAST_FLOAT float
  159543. #else
  159544. #define FAST_FLOAT double
  159545. #endif
  159546. #endif
  159547. #endif /* JPEG_INTERNAL_OPTIONS */
  159548. /*** End of inlined file: jmorecfg.h ***/
  159549. /* seldom changed options */
  159550. /* Version ID for the JPEG library.
  159551. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159552. */
  159553. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159554. /* Various constants determining the sizes of things.
  159555. * All of these are specified by the JPEG standard, so don't change them
  159556. * if you want to be compatible.
  159557. */
  159558. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159559. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159560. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159561. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159562. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159563. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159564. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159565. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159566. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159567. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159568. * to handle it. We even let you do this from the jconfig.h file. However,
  159569. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159570. * sometimes emits noncompliant files doesn't mean you should too.
  159571. */
  159572. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159573. #ifndef D_MAX_BLOCKS_IN_MCU
  159574. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159575. #endif
  159576. /* Data structures for images (arrays of samples and of DCT coefficients).
  159577. * On 80x86 machines, the image arrays are too big for near pointers,
  159578. * but the pointer arrays can fit in near memory.
  159579. */
  159580. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159581. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159582. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159583. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159584. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159585. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159586. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159587. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159588. /* Types for JPEG compression parameters and working tables. */
  159589. /* DCT coefficient quantization tables. */
  159590. typedef struct {
  159591. /* This array gives the coefficient quantizers in natural array order
  159592. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159593. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159594. */
  159595. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159596. /* This field is used only during compression. It's initialized FALSE when
  159597. * the table is created, and set TRUE when it's been output to the file.
  159598. * You could suppress output of a table by setting this to TRUE.
  159599. * (See jpeg_suppress_tables for an example.)
  159600. */
  159601. boolean sent_table; /* TRUE when table has been output */
  159602. } JQUANT_TBL;
  159603. /* Huffman coding tables. */
  159604. typedef struct {
  159605. /* These two fields directly represent the contents of a JPEG DHT marker */
  159606. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159607. /* length k bits; bits[0] is unused */
  159608. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159609. /* This field is used only during compression. It's initialized FALSE when
  159610. * the table is created, and set TRUE when it's been output to the file.
  159611. * You could suppress output of a table by setting this to TRUE.
  159612. * (See jpeg_suppress_tables for an example.)
  159613. */
  159614. boolean sent_table; /* TRUE when table has been output */
  159615. } JHUFF_TBL;
  159616. /* Basic info about one component (color channel). */
  159617. typedef struct {
  159618. /* These values are fixed over the whole image. */
  159619. /* For compression, they must be supplied by parameter setup; */
  159620. /* for decompression, they are read from the SOF marker. */
  159621. int component_id; /* identifier for this component (0..255) */
  159622. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159623. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159624. int v_samp_factor; /* vertical sampling factor (1..4) */
  159625. int quant_tbl_no; /* quantization table selector (0..3) */
  159626. /* These values may vary between scans. */
  159627. /* For compression, they must be supplied by parameter setup; */
  159628. /* for decompression, they are read from the SOS marker. */
  159629. /* The decompressor output side may not use these variables. */
  159630. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159631. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159632. /* Remaining fields should be treated as private by applications. */
  159633. /* These values are computed during compression or decompression startup: */
  159634. /* Component's size in DCT blocks.
  159635. * Any dummy blocks added to complete an MCU are not counted; therefore
  159636. * these values do not depend on whether a scan is interleaved or not.
  159637. */
  159638. JDIMENSION width_in_blocks;
  159639. JDIMENSION height_in_blocks;
  159640. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159641. * For decompression this is the size of the output from one DCT block,
  159642. * reflecting any scaling we choose to apply during the IDCT step.
  159643. * Values of 1,2,4,8 are likely to be supported. Note that different
  159644. * components may receive different IDCT scalings.
  159645. */
  159646. int DCT_scaled_size;
  159647. /* The downsampled dimensions are the component's actual, unpadded number
  159648. * of samples at the main buffer (preprocessing/compression interface), thus
  159649. * downsampled_width = ceil(image_width * Hi/Hmax)
  159650. * and similarly for height. For decompression, IDCT scaling is included, so
  159651. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159652. */
  159653. JDIMENSION downsampled_width; /* actual width in samples */
  159654. JDIMENSION downsampled_height; /* actual height in samples */
  159655. /* This flag is used only for decompression. In cases where some of the
  159656. * components will be ignored (eg grayscale output from YCbCr image),
  159657. * we can skip most computations for the unused components.
  159658. */
  159659. boolean component_needed; /* do we need the value of this component? */
  159660. /* These values are computed before starting a scan of the component. */
  159661. /* The decompressor output side may not use these variables. */
  159662. int MCU_width; /* number of blocks per MCU, horizontally */
  159663. int MCU_height; /* number of blocks per MCU, vertically */
  159664. int MCU_blocks; /* MCU_width * MCU_height */
  159665. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  159666. int last_col_width; /* # of non-dummy blocks across in last MCU */
  159667. int last_row_height; /* # of non-dummy blocks down in last MCU */
  159668. /* Saved quantization table for component; NULL if none yet saved.
  159669. * See jdinput.c comments about the need for this information.
  159670. * This field is currently used only for decompression.
  159671. */
  159672. JQUANT_TBL * quant_table;
  159673. /* Private per-component storage for DCT or IDCT subsystem. */
  159674. void * dct_table;
  159675. } jpeg_component_info;
  159676. /* The script for encoding a multiple-scan file is an array of these: */
  159677. typedef struct {
  159678. int comps_in_scan; /* number of components encoded in this scan */
  159679. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  159680. int Ss, Se; /* progressive JPEG spectral selection parms */
  159681. int Ah, Al; /* progressive JPEG successive approx. parms */
  159682. } jpeg_scan_info;
  159683. /* The decompressor can save APPn and COM markers in a list of these: */
  159684. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  159685. struct jpeg_marker_struct {
  159686. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  159687. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  159688. unsigned int original_length; /* # bytes of data in the file */
  159689. unsigned int data_length; /* # bytes of data saved at data[] */
  159690. JOCTET FAR * data; /* the data contained in the marker */
  159691. /* the marker length word is not counted in data_length or original_length */
  159692. };
  159693. /* Known color spaces. */
  159694. typedef enum {
  159695. JCS_UNKNOWN, /* error/unspecified */
  159696. JCS_GRAYSCALE, /* monochrome */
  159697. JCS_RGB, /* red/green/blue */
  159698. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  159699. JCS_CMYK, /* C/M/Y/K */
  159700. JCS_YCCK /* Y/Cb/Cr/K */
  159701. } J_COLOR_SPACE;
  159702. /* DCT/IDCT algorithm options. */
  159703. typedef enum {
  159704. JDCT_ISLOW, /* slow but accurate integer algorithm */
  159705. JDCT_IFAST, /* faster, less accurate integer method */
  159706. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  159707. } J_DCT_METHOD;
  159708. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  159709. #define JDCT_DEFAULT JDCT_ISLOW
  159710. #endif
  159711. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  159712. #define JDCT_FASTEST JDCT_IFAST
  159713. #endif
  159714. /* Dithering options for decompression. */
  159715. typedef enum {
  159716. JDITHER_NONE, /* no dithering */
  159717. JDITHER_ORDERED, /* simple ordered dither */
  159718. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  159719. } J_DITHER_MODE;
  159720. /* Common fields between JPEG compression and decompression master structs. */
  159721. #define jpeg_common_fields \
  159722. struct jpeg_error_mgr * err; /* Error handler module */\
  159723. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  159724. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  159725. void * client_data; /* Available for use by application */\
  159726. boolean is_decompressor; /* So common code can tell which is which */\
  159727. int global_state /* For checking call sequence validity */
  159728. /* Routines that are to be used by both halves of the library are declared
  159729. * to receive a pointer to this structure. There are no actual instances of
  159730. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  159731. */
  159732. struct jpeg_common_struct {
  159733. jpeg_common_fields; /* Fields common to both master struct types */
  159734. /* Additional fields follow in an actual jpeg_compress_struct or
  159735. * jpeg_decompress_struct. All three structs must agree on these
  159736. * initial fields! (This would be a lot cleaner in C++.)
  159737. */
  159738. };
  159739. typedef struct jpeg_common_struct * j_common_ptr;
  159740. typedef struct jpeg_compress_struct * j_compress_ptr;
  159741. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  159742. /* Master record for a compression instance */
  159743. struct jpeg_compress_struct {
  159744. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  159745. /* Destination for compressed data */
  159746. struct jpeg_destination_mgr * dest;
  159747. /* Description of source image --- these fields must be filled in by
  159748. * outer application before starting compression. in_color_space must
  159749. * be correct before you can even call jpeg_set_defaults().
  159750. */
  159751. JDIMENSION image_width; /* input image width */
  159752. JDIMENSION image_height; /* input image height */
  159753. int input_components; /* # of color components in input image */
  159754. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  159755. double input_gamma; /* image gamma of input image */
  159756. /* Compression parameters --- these fields must be set before calling
  159757. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  159758. * initialize everything to reasonable defaults, then changing anything
  159759. * the application specifically wants to change. That way you won't get
  159760. * burnt when new parameters are added. Also note that there are several
  159761. * helper routines to simplify changing parameters.
  159762. */
  159763. int data_precision; /* bits of precision in image data */
  159764. int num_components; /* # of color components in JPEG image */
  159765. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159766. jpeg_component_info * comp_info;
  159767. /* comp_info[i] describes component that appears i'th in SOF */
  159768. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159769. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159770. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159771. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159772. /* ptrs to Huffman coding tables, or NULL if not defined */
  159773. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159774. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159775. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159776. int num_scans; /* # of entries in scan_info array */
  159777. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  159778. /* The default value of scan_info is NULL, which causes a single-scan
  159779. * sequential JPEG file to be emitted. To create a multi-scan file,
  159780. * set num_scans and scan_info to point to an array of scan definitions.
  159781. */
  159782. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  159783. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159784. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  159785. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159786. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  159787. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  159788. /* The restart interval can be specified in absolute MCUs by setting
  159789. * restart_interval, or in MCU rows by setting restart_in_rows
  159790. * (in which case the correct restart_interval will be figured
  159791. * for each scan).
  159792. */
  159793. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  159794. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  159795. /* Parameters controlling emission of special markers. */
  159796. boolean write_JFIF_header; /* should a JFIF marker be written? */
  159797. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  159798. UINT8 JFIF_minor_version;
  159799. /* These three values are not used by the JPEG code, merely copied */
  159800. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  159801. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  159802. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  159803. UINT8 density_unit; /* JFIF code for pixel size units */
  159804. UINT16 X_density; /* Horizontal pixel density */
  159805. UINT16 Y_density; /* Vertical pixel density */
  159806. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  159807. /* State variable: index of next scanline to be written to
  159808. * jpeg_write_scanlines(). Application may use this to control its
  159809. * processing loop, e.g., "while (next_scanline < image_height)".
  159810. */
  159811. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  159812. /* Remaining fields are known throughout compressor, but generally
  159813. * should not be touched by a surrounding application.
  159814. */
  159815. /*
  159816. * These fields are computed during compression startup
  159817. */
  159818. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  159819. int max_h_samp_factor; /* largest h_samp_factor */
  159820. int max_v_samp_factor; /* largest v_samp_factor */
  159821. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  159822. /* The coefficient controller receives data in units of MCU rows as defined
  159823. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  159824. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  159825. * "iMCU" (interleaved MCU) row.
  159826. */
  159827. /*
  159828. * These fields are valid during any one scan.
  159829. * They describe the components and MCUs actually appearing in the scan.
  159830. */
  159831. int comps_in_scan; /* # of JPEG components in this scan */
  159832. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  159833. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  159834. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  159835. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  159836. int blocks_in_MCU; /* # of DCT blocks per MCU */
  159837. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  159838. /* MCU_membership[i] is index in cur_comp_info of component owning */
  159839. /* i'th block in an MCU */
  159840. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  159841. /*
  159842. * Links to compression subobjects (methods and private variables of modules)
  159843. */
  159844. struct jpeg_comp_master * master;
  159845. struct jpeg_c_main_controller * main;
  159846. struct jpeg_c_prep_controller * prep;
  159847. struct jpeg_c_coef_controller * coef;
  159848. struct jpeg_marker_writer * marker;
  159849. struct jpeg_color_converter * cconvert;
  159850. struct jpeg_downsampler * downsample;
  159851. struct jpeg_forward_dct * fdct;
  159852. struct jpeg_entropy_encoder * entropy;
  159853. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  159854. int script_space_size;
  159855. };
  159856. /* Master record for a decompression instance */
  159857. struct jpeg_decompress_struct {
  159858. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  159859. /* Source of compressed data */
  159860. struct jpeg_source_mgr * src;
  159861. /* Basic description of image --- filled in by jpeg_read_header(). */
  159862. /* Application may inspect these values to decide how to process image. */
  159863. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  159864. JDIMENSION image_height; /* nominal image height */
  159865. int num_components; /* # of color components in JPEG image */
  159866. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  159867. /* Decompression processing parameters --- these fields must be set before
  159868. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  159869. * them to default values.
  159870. */
  159871. J_COLOR_SPACE out_color_space; /* colorspace for output */
  159872. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  159873. double output_gamma; /* image gamma wanted in output */
  159874. boolean buffered_image; /* TRUE=multiple output passes */
  159875. boolean raw_data_out; /* TRUE=downsampled data wanted */
  159876. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  159877. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  159878. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  159879. boolean quantize_colors; /* TRUE=colormapped output wanted */
  159880. /* the following are ignored if not quantize_colors: */
  159881. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  159882. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  159883. int desired_number_of_colors; /* max # colors to use in created colormap */
  159884. /* these are significant only in buffered-image mode: */
  159885. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  159886. boolean enable_external_quant;/* enable future use of external colormap */
  159887. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  159888. /* Description of actual output image that will be returned to application.
  159889. * These fields are computed by jpeg_start_decompress().
  159890. * You can also use jpeg_calc_output_dimensions() to determine these values
  159891. * in advance of calling jpeg_start_decompress().
  159892. */
  159893. JDIMENSION output_width; /* scaled image width */
  159894. JDIMENSION output_height; /* scaled image height */
  159895. int out_color_components; /* # of color components in out_color_space */
  159896. int output_components; /* # of color components returned */
  159897. /* output_components is 1 (a colormap index) when quantizing colors;
  159898. * otherwise it equals out_color_components.
  159899. */
  159900. int rec_outbuf_height; /* min recommended height of scanline buffer */
  159901. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  159902. * high, space and time will be wasted due to unnecessary data copying.
  159903. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  159904. */
  159905. /* When quantizing colors, the output colormap is described by these fields.
  159906. * The application can supply a colormap by setting colormap non-NULL before
  159907. * calling jpeg_start_decompress; otherwise a colormap is created during
  159908. * jpeg_start_decompress or jpeg_start_output.
  159909. * The map has out_color_components rows and actual_number_of_colors columns.
  159910. */
  159911. int actual_number_of_colors; /* number of entries in use */
  159912. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  159913. /* State variables: these variables indicate the progress of decompression.
  159914. * The application may examine these but must not modify them.
  159915. */
  159916. /* Row index of next scanline to be read from jpeg_read_scanlines().
  159917. * Application may use this to control its processing loop, e.g.,
  159918. * "while (output_scanline < output_height)".
  159919. */
  159920. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  159921. /* Current input scan number and number of iMCU rows completed in scan.
  159922. * These indicate the progress of the decompressor input side.
  159923. */
  159924. int input_scan_number; /* Number of SOS markers seen so far */
  159925. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  159926. /* The "output scan number" is the notional scan being displayed by the
  159927. * output side. The decompressor will not allow output scan/row number
  159928. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  159929. */
  159930. int output_scan_number; /* Nominal scan number being displayed */
  159931. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  159932. /* Current progression status. coef_bits[c][i] indicates the precision
  159933. * with which component c's DCT coefficient i (in zigzag order) is known.
  159934. * It is -1 when no data has yet been received, otherwise it is the point
  159935. * transform (shift) value for the most recent scan of the coefficient
  159936. * (thus, 0 at completion of the progression).
  159937. * This pointer is NULL when reading a non-progressive file.
  159938. */
  159939. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  159940. /* Internal JPEG parameters --- the application usually need not look at
  159941. * these fields. Note that the decompressor output side may not use
  159942. * any parameters that can change between scans.
  159943. */
  159944. /* Quantization and Huffman tables are carried forward across input
  159945. * datastreams when processing abbreviated JPEG datastreams.
  159946. */
  159947. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  159948. /* ptrs to coefficient quantization tables, or NULL if not defined */
  159949. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159950. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  159951. /* ptrs to Huffman coding tables, or NULL if not defined */
  159952. /* These parameters are never carried across datastreams, since they
  159953. * are given in SOF/SOS markers or defined to be reset by SOI.
  159954. */
  159955. int data_precision; /* bits of precision in image data */
  159956. jpeg_component_info * comp_info;
  159957. /* comp_info[i] describes component that appears i'th in SOF */
  159958. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  159959. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  159960. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  159961. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  159962. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  159963. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  159964. /* These fields record data obtained from optional markers recognized by
  159965. * the JPEG library.
  159966. */
  159967. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  159968. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  159969. UINT8 JFIF_major_version; /* JFIF version number */
  159970. UINT8 JFIF_minor_version;
  159971. UINT8 density_unit; /* JFIF code for pixel size units */
  159972. UINT16 X_density; /* Horizontal pixel density */
  159973. UINT16 Y_density; /* Vertical pixel density */
  159974. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  159975. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  159976. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  159977. /* Aside from the specific data retained from APPn markers known to the
  159978. * library, the uninterpreted contents of any or all APPn and COM markers
  159979. * can be saved in a list for examination by the application.
  159980. */
  159981. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  159982. /* Remaining fields are known throughout decompressor, but generally
  159983. * should not be touched by a surrounding application.
  159984. */
  159985. /*
  159986. * These fields are computed during decompression startup
  159987. */
  159988. int max_h_samp_factor; /* largest h_samp_factor */
  159989. int max_v_samp_factor; /* largest v_samp_factor */
  159990. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  159991. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  159992. /* The coefficient controller's input and output progress is measured in
  159993. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  159994. * in fully interleaved JPEG scans, but are used whether the scan is
  159995. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  159996. * rows of each component. Therefore, the IDCT output contains
  159997. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  159998. */
  159999. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160000. /*
  160001. * These fields are valid during any one scan.
  160002. * They describe the components and MCUs actually appearing in the scan.
  160003. * Note that the decompressor output side must not use these fields.
  160004. */
  160005. int comps_in_scan; /* # of JPEG components in this scan */
  160006. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160007. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160008. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160009. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160010. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160011. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160012. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160013. /* i'th block in an MCU */
  160014. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160015. /* This field is shared between entropy decoder and marker parser.
  160016. * It is either zero or the code of a JPEG marker that has been
  160017. * read from the data source, but has not yet been processed.
  160018. */
  160019. int unread_marker;
  160020. /*
  160021. * Links to decompression subobjects (methods, private variables of modules)
  160022. */
  160023. struct jpeg_decomp_master * master;
  160024. struct jpeg_d_main_controller * main;
  160025. struct jpeg_d_coef_controller * coef;
  160026. struct jpeg_d_post_controller * post;
  160027. struct jpeg_input_controller * inputctl;
  160028. struct jpeg_marker_reader * marker;
  160029. struct jpeg_entropy_decoder * entropy;
  160030. struct jpeg_inverse_dct * idct;
  160031. struct jpeg_upsampler * upsample;
  160032. struct jpeg_color_deconverter * cconvert;
  160033. struct jpeg_color_quantizer * cquantize;
  160034. };
  160035. /* "Object" declarations for JPEG modules that may be supplied or called
  160036. * directly by the surrounding application.
  160037. * As with all objects in the JPEG library, these structs only define the
  160038. * publicly visible methods and state variables of a module. Additional
  160039. * private fields may exist after the public ones.
  160040. */
  160041. /* Error handler object */
  160042. struct jpeg_error_mgr {
  160043. /* Error exit handler: does not return to caller */
  160044. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160045. /* Conditionally emit a trace or warning message */
  160046. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160047. /* Routine that actually outputs a trace or error message */
  160048. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160049. /* Format a message string for the most recent JPEG error or message */
  160050. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160051. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160052. /* Reset error state variables at start of a new image */
  160053. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160054. /* The message ID code and any parameters are saved here.
  160055. * A message can have one string parameter or up to 8 int parameters.
  160056. */
  160057. int msg_code;
  160058. #define JMSG_STR_PARM_MAX 80
  160059. union {
  160060. int i[8];
  160061. char s[JMSG_STR_PARM_MAX];
  160062. } msg_parm;
  160063. /* Standard state variables for error facility */
  160064. int trace_level; /* max msg_level that will be displayed */
  160065. /* For recoverable corrupt-data errors, we emit a warning message,
  160066. * but keep going unless emit_message chooses to abort. emit_message
  160067. * should count warnings in num_warnings. The surrounding application
  160068. * can check for bad data by seeing if num_warnings is nonzero at the
  160069. * end of processing.
  160070. */
  160071. long num_warnings; /* number of corrupt-data warnings */
  160072. /* These fields point to the table(s) of error message strings.
  160073. * An application can change the table pointer to switch to a different
  160074. * message list (typically, to change the language in which errors are
  160075. * reported). Some applications may wish to add additional error codes
  160076. * that will be handled by the JPEG library error mechanism; the second
  160077. * table pointer is used for this purpose.
  160078. *
  160079. * First table includes all errors generated by JPEG library itself.
  160080. * Error code 0 is reserved for a "no such error string" message.
  160081. */
  160082. const char * const * jpeg_message_table; /* Library errors */
  160083. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160084. /* Second table can be added by application (see cjpeg/djpeg for example).
  160085. * It contains strings numbered first_addon_message..last_addon_message.
  160086. */
  160087. const char * const * addon_message_table; /* Non-library errors */
  160088. int first_addon_message; /* code for first string in addon table */
  160089. int last_addon_message; /* code for last string in addon table */
  160090. };
  160091. /* Progress monitor object */
  160092. struct jpeg_progress_mgr {
  160093. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160094. long pass_counter; /* work units completed in this pass */
  160095. long pass_limit; /* total number of work units in this pass */
  160096. int completed_passes; /* passes completed so far */
  160097. int total_passes; /* total number of passes expected */
  160098. };
  160099. /* Data destination object for compression */
  160100. struct jpeg_destination_mgr {
  160101. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160102. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160103. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160104. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160105. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160106. };
  160107. /* Data source object for decompression */
  160108. struct jpeg_source_mgr {
  160109. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160110. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160111. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160112. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160113. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160114. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160115. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160116. };
  160117. /* Memory manager object.
  160118. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160119. * and "really big" objects (virtual arrays with backing store if needed).
  160120. * The memory manager does not allow individual objects to be freed; rather,
  160121. * each created object is assigned to a pool, and whole pools can be freed
  160122. * at once. This is faster and more convenient than remembering exactly what
  160123. * to free, especially where malloc()/free() are not too speedy.
  160124. * NB: alloc routines never return NULL. They exit to error_exit if not
  160125. * successful.
  160126. */
  160127. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160128. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160129. #define JPOOL_NUMPOOLS 2
  160130. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160131. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160132. struct jpeg_memory_mgr {
  160133. /* Method pointers */
  160134. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160135. size_t sizeofobject));
  160136. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160137. size_t sizeofobject));
  160138. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160139. JDIMENSION samplesperrow,
  160140. JDIMENSION numrows));
  160141. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160142. JDIMENSION blocksperrow,
  160143. JDIMENSION numrows));
  160144. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160145. int pool_id,
  160146. boolean pre_zero,
  160147. JDIMENSION samplesperrow,
  160148. JDIMENSION numrows,
  160149. JDIMENSION maxaccess));
  160150. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160151. int pool_id,
  160152. boolean pre_zero,
  160153. JDIMENSION blocksperrow,
  160154. JDIMENSION numrows,
  160155. JDIMENSION maxaccess));
  160156. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160157. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160158. jvirt_sarray_ptr ptr,
  160159. JDIMENSION start_row,
  160160. JDIMENSION num_rows,
  160161. boolean writable));
  160162. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160163. jvirt_barray_ptr ptr,
  160164. JDIMENSION start_row,
  160165. JDIMENSION num_rows,
  160166. boolean writable));
  160167. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160168. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160169. /* Limit on memory allocation for this JPEG object. (Note that this is
  160170. * merely advisory, not a guaranteed maximum; it only affects the space
  160171. * used for virtual-array buffers.) May be changed by outer application
  160172. * after creating the JPEG object.
  160173. */
  160174. long max_memory_to_use;
  160175. /* Maximum allocation request accepted by alloc_large. */
  160176. long max_alloc_chunk;
  160177. };
  160178. /* Routine signature for application-supplied marker processing methods.
  160179. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160180. */
  160181. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160182. /* Declarations for routines called by application.
  160183. * The JPP macro hides prototype parameters from compilers that can't cope.
  160184. * Note JPP requires double parentheses.
  160185. */
  160186. #ifdef HAVE_PROTOTYPES
  160187. #define JPP(arglist) arglist
  160188. #else
  160189. #define JPP(arglist) ()
  160190. #endif
  160191. /* Short forms of external names for systems with brain-damaged linkers.
  160192. * We shorten external names to be unique in the first six letters, which
  160193. * is good enough for all known systems.
  160194. * (If your compiler itself needs names to be unique in less than 15
  160195. * characters, you are out of luck. Get a better compiler.)
  160196. */
  160197. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160198. #define jpeg_std_error jStdError
  160199. #define jpeg_CreateCompress jCreaCompress
  160200. #define jpeg_CreateDecompress jCreaDecompress
  160201. #define jpeg_destroy_compress jDestCompress
  160202. #define jpeg_destroy_decompress jDestDecompress
  160203. #define jpeg_stdio_dest jStdDest
  160204. #define jpeg_stdio_src jStdSrc
  160205. #define jpeg_set_defaults jSetDefaults
  160206. #define jpeg_set_colorspace jSetColorspace
  160207. #define jpeg_default_colorspace jDefColorspace
  160208. #define jpeg_set_quality jSetQuality
  160209. #define jpeg_set_linear_quality jSetLQuality
  160210. #define jpeg_add_quant_table jAddQuantTable
  160211. #define jpeg_quality_scaling jQualityScaling
  160212. #define jpeg_simple_progression jSimProgress
  160213. #define jpeg_suppress_tables jSuppressTables
  160214. #define jpeg_alloc_quant_table jAlcQTable
  160215. #define jpeg_alloc_huff_table jAlcHTable
  160216. #define jpeg_start_compress jStrtCompress
  160217. #define jpeg_write_scanlines jWrtScanlines
  160218. #define jpeg_finish_compress jFinCompress
  160219. #define jpeg_write_raw_data jWrtRawData
  160220. #define jpeg_write_marker jWrtMarker
  160221. #define jpeg_write_m_header jWrtMHeader
  160222. #define jpeg_write_m_byte jWrtMByte
  160223. #define jpeg_write_tables jWrtTables
  160224. #define jpeg_read_header jReadHeader
  160225. #define jpeg_start_decompress jStrtDecompress
  160226. #define jpeg_read_scanlines jReadScanlines
  160227. #define jpeg_finish_decompress jFinDecompress
  160228. #define jpeg_read_raw_data jReadRawData
  160229. #define jpeg_has_multiple_scans jHasMultScn
  160230. #define jpeg_start_output jStrtOutput
  160231. #define jpeg_finish_output jFinOutput
  160232. #define jpeg_input_complete jInComplete
  160233. #define jpeg_new_colormap jNewCMap
  160234. #define jpeg_consume_input jConsumeInput
  160235. #define jpeg_calc_output_dimensions jCalcDimensions
  160236. #define jpeg_save_markers jSaveMarkers
  160237. #define jpeg_set_marker_processor jSetMarker
  160238. #define jpeg_read_coefficients jReadCoefs
  160239. #define jpeg_write_coefficients jWrtCoefs
  160240. #define jpeg_copy_critical_parameters jCopyCrit
  160241. #define jpeg_abort_compress jAbrtCompress
  160242. #define jpeg_abort_decompress jAbrtDecompress
  160243. #define jpeg_abort jAbort
  160244. #define jpeg_destroy jDestroy
  160245. #define jpeg_resync_to_restart jResyncRestart
  160246. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160247. /* Default error-management setup */
  160248. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160249. JPP((struct jpeg_error_mgr * err));
  160250. /* Initialization of JPEG compression objects.
  160251. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160252. * names that applications should call. These expand to calls on
  160253. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160254. * passed for version mismatch checking.
  160255. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160256. */
  160257. #define jpeg_create_compress(cinfo) \
  160258. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160259. (size_t) sizeof(struct jpeg_compress_struct))
  160260. #define jpeg_create_decompress(cinfo) \
  160261. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160262. (size_t) sizeof(struct jpeg_decompress_struct))
  160263. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160264. int version, size_t structsize));
  160265. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160266. int version, size_t structsize));
  160267. /* Destruction of JPEG compression objects */
  160268. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160269. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160270. /* Standard data source and destination managers: stdio streams. */
  160271. /* Caller is responsible for opening the file before and closing after. */
  160272. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160273. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160274. /* Default parameter setup for compression */
  160275. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160276. /* Compression parameter setup aids */
  160277. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160278. J_COLOR_SPACE colorspace));
  160279. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160280. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160281. boolean force_baseline));
  160282. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160283. int scale_factor,
  160284. boolean force_baseline));
  160285. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160286. const unsigned int *basic_table,
  160287. int scale_factor,
  160288. boolean force_baseline));
  160289. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160290. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160291. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160292. boolean suppress));
  160293. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160294. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160295. /* Main entry points for compression */
  160296. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160297. boolean write_all_tables));
  160298. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160299. JSAMPARRAY scanlines,
  160300. JDIMENSION num_lines));
  160301. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160302. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160303. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160304. JSAMPIMAGE data,
  160305. JDIMENSION num_lines));
  160306. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160307. EXTERN(void) jpeg_write_marker
  160308. JPP((j_compress_ptr cinfo, int marker,
  160309. const JOCTET * dataptr, unsigned int datalen));
  160310. /* Same, but piecemeal. */
  160311. EXTERN(void) jpeg_write_m_header
  160312. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160313. EXTERN(void) jpeg_write_m_byte
  160314. JPP((j_compress_ptr cinfo, int val));
  160315. /* Alternate compression function: just write an abbreviated table file */
  160316. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160317. /* Decompression startup: read start of JPEG datastream to see what's there */
  160318. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160319. boolean require_image));
  160320. /* Return value is one of: */
  160321. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160322. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160323. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160324. /* If you pass require_image = TRUE (normal case), you need not check for
  160325. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160326. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160327. * give a suspension return (the stdio source module doesn't).
  160328. */
  160329. /* Main entry points for decompression */
  160330. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160331. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160332. JSAMPARRAY scanlines,
  160333. JDIMENSION max_lines));
  160334. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160335. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160336. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160337. JSAMPIMAGE data,
  160338. JDIMENSION max_lines));
  160339. /* Additional entry points for buffered-image mode. */
  160340. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160341. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160342. int scan_number));
  160343. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160344. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160345. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160346. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160347. /* Return value is one of: */
  160348. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160349. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160350. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160351. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160352. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160353. /* Precalculate output dimensions for current decompression parameters. */
  160354. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160355. /* Control saving of COM and APPn markers into marker_list. */
  160356. EXTERN(void) jpeg_save_markers
  160357. JPP((j_decompress_ptr cinfo, int marker_code,
  160358. unsigned int length_limit));
  160359. /* Install a special processing method for COM or APPn markers. */
  160360. EXTERN(void) jpeg_set_marker_processor
  160361. JPP((j_decompress_ptr cinfo, int marker_code,
  160362. jpeg_marker_parser_method routine));
  160363. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160364. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160365. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160366. jvirt_barray_ptr * coef_arrays));
  160367. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160368. j_compress_ptr dstinfo));
  160369. /* If you choose to abort compression or decompression before completing
  160370. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160371. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160372. * if you're done with the JPEG object, but if you want to clean it up and
  160373. * reuse it, call this:
  160374. */
  160375. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160376. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160377. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160378. * flavor of JPEG object. These may be more convenient in some places.
  160379. */
  160380. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160381. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160382. /* Default restart-marker-resync procedure for use by data source modules */
  160383. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160384. int desired));
  160385. /* These marker codes are exported since applications and data source modules
  160386. * are likely to want to use them.
  160387. */
  160388. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160389. #define JPEG_EOI 0xD9 /* EOI marker code */
  160390. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160391. #define JPEG_COM 0xFE /* COM marker code */
  160392. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160393. * for structure definitions that are never filled in, keep it quiet by
  160394. * supplying dummy definitions for the various substructures.
  160395. */
  160396. #ifdef INCOMPLETE_TYPES_BROKEN
  160397. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160398. struct jvirt_sarray_control { long dummy; };
  160399. struct jvirt_barray_control { long dummy; };
  160400. struct jpeg_comp_master { long dummy; };
  160401. struct jpeg_c_main_controller { long dummy; };
  160402. struct jpeg_c_prep_controller { long dummy; };
  160403. struct jpeg_c_coef_controller { long dummy; };
  160404. struct jpeg_marker_writer { long dummy; };
  160405. struct jpeg_color_converter { long dummy; };
  160406. struct jpeg_downsampler { long dummy; };
  160407. struct jpeg_forward_dct { long dummy; };
  160408. struct jpeg_entropy_encoder { long dummy; };
  160409. struct jpeg_decomp_master { long dummy; };
  160410. struct jpeg_d_main_controller { long dummy; };
  160411. struct jpeg_d_coef_controller { long dummy; };
  160412. struct jpeg_d_post_controller { long dummy; };
  160413. struct jpeg_input_controller { long dummy; };
  160414. struct jpeg_marker_reader { long dummy; };
  160415. struct jpeg_entropy_decoder { long dummy; };
  160416. struct jpeg_inverse_dct { long dummy; };
  160417. struct jpeg_upsampler { long dummy; };
  160418. struct jpeg_color_deconverter { long dummy; };
  160419. struct jpeg_color_quantizer { long dummy; };
  160420. #endif /* JPEG_INTERNALS */
  160421. #endif /* INCOMPLETE_TYPES_BROKEN */
  160422. /*
  160423. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160424. * The internal structure declarations are read only when that is true.
  160425. * Applications using the library should not include jpegint.h, but may wish
  160426. * to include jerror.h.
  160427. */
  160428. #ifdef JPEG_INTERNALS
  160429. /*** Start of inlined file: jpegint.h ***/
  160430. /* Declarations for both compression & decompression */
  160431. typedef enum { /* Operating modes for buffer controllers */
  160432. JBUF_PASS_THRU, /* Plain stripwise operation */
  160433. /* Remaining modes require a full-image buffer to have been created */
  160434. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160435. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160436. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160437. } J_BUF_MODE;
  160438. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160439. #define CSTATE_START 100 /* after create_compress */
  160440. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160441. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160442. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160443. #define DSTATE_START 200 /* after create_decompress */
  160444. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160445. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160446. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160447. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160448. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160449. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160450. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160451. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160452. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160453. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160454. /* Declarations for compression modules */
  160455. /* Master control module */
  160456. struct jpeg_comp_master {
  160457. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160458. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160459. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160460. /* State variables made visible to other modules */
  160461. boolean call_pass_startup; /* True if pass_startup must be called */
  160462. boolean is_last_pass; /* True during last pass */
  160463. };
  160464. /* Main buffer control (downsampled-data buffer) */
  160465. struct jpeg_c_main_controller {
  160466. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160467. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160468. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160469. JDIMENSION in_rows_avail));
  160470. };
  160471. /* Compression preprocessing (downsampling input buffer control) */
  160472. struct jpeg_c_prep_controller {
  160473. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160474. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160475. JSAMPARRAY input_buf,
  160476. JDIMENSION *in_row_ctr,
  160477. JDIMENSION in_rows_avail,
  160478. JSAMPIMAGE output_buf,
  160479. JDIMENSION *out_row_group_ctr,
  160480. JDIMENSION out_row_groups_avail));
  160481. };
  160482. /* Coefficient buffer control */
  160483. struct jpeg_c_coef_controller {
  160484. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160485. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160486. JSAMPIMAGE input_buf));
  160487. };
  160488. /* Colorspace conversion */
  160489. struct jpeg_color_converter {
  160490. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160491. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160492. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160493. JDIMENSION output_row, int num_rows));
  160494. };
  160495. /* Downsampling */
  160496. struct jpeg_downsampler {
  160497. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160498. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160499. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160500. JSAMPIMAGE output_buf,
  160501. JDIMENSION out_row_group_index));
  160502. boolean need_context_rows; /* TRUE if need rows above & below */
  160503. };
  160504. /* Forward DCT (also controls coefficient quantization) */
  160505. struct jpeg_forward_dct {
  160506. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160507. /* perhaps this should be an array??? */
  160508. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160509. jpeg_component_info * compptr,
  160510. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160511. JDIMENSION start_row, JDIMENSION start_col,
  160512. JDIMENSION num_blocks));
  160513. };
  160514. /* Entropy encoding */
  160515. struct jpeg_entropy_encoder {
  160516. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160517. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160518. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160519. };
  160520. /* Marker writing */
  160521. struct jpeg_marker_writer {
  160522. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160523. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160524. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160525. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160526. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160527. /* These routines are exported to allow insertion of extra markers */
  160528. /* Probably only COM and APPn markers should be written this way */
  160529. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160530. unsigned int datalen));
  160531. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160532. };
  160533. /* Declarations for decompression modules */
  160534. /* Master control module */
  160535. struct jpeg_decomp_master {
  160536. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160537. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160538. /* State variables made visible to other modules */
  160539. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160540. };
  160541. /* Input control module */
  160542. struct jpeg_input_controller {
  160543. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160544. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160545. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160546. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160547. /* State variables made visible to other modules */
  160548. boolean has_multiple_scans; /* True if file has multiple scans */
  160549. boolean eoi_reached; /* True when EOI has been consumed */
  160550. };
  160551. /* Main buffer control (downsampled-data buffer) */
  160552. struct jpeg_d_main_controller {
  160553. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160554. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160555. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160556. JDIMENSION out_rows_avail));
  160557. };
  160558. /* Coefficient buffer control */
  160559. struct jpeg_d_coef_controller {
  160560. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160561. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160562. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160563. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160564. JSAMPIMAGE output_buf));
  160565. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160566. jvirt_barray_ptr *coef_arrays;
  160567. };
  160568. /* Decompression postprocessing (color quantization buffer control) */
  160569. struct jpeg_d_post_controller {
  160570. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160571. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160572. JSAMPIMAGE input_buf,
  160573. JDIMENSION *in_row_group_ctr,
  160574. JDIMENSION in_row_groups_avail,
  160575. JSAMPARRAY output_buf,
  160576. JDIMENSION *out_row_ctr,
  160577. JDIMENSION out_rows_avail));
  160578. };
  160579. /* Marker reading & parsing */
  160580. struct jpeg_marker_reader {
  160581. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160582. /* Read markers until SOS or EOI.
  160583. * Returns same codes as are defined for jpeg_consume_input:
  160584. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160585. */
  160586. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160587. /* Read a restart marker --- exported for use by entropy decoder only */
  160588. jpeg_marker_parser_method read_restart_marker;
  160589. /* State of marker reader --- nominally internal, but applications
  160590. * supplying COM or APPn handlers might like to know the state.
  160591. */
  160592. boolean saw_SOI; /* found SOI? */
  160593. boolean saw_SOF; /* found SOF? */
  160594. int next_restart_num; /* next restart number expected (0-7) */
  160595. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160596. };
  160597. /* Entropy decoding */
  160598. struct jpeg_entropy_decoder {
  160599. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160600. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160601. JBLOCKROW *MCU_data));
  160602. /* This is here to share code between baseline and progressive decoders; */
  160603. /* other modules probably should not use it */
  160604. boolean insufficient_data; /* set TRUE after emitting warning */
  160605. };
  160606. /* Inverse DCT (also performs dequantization) */
  160607. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160608. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160609. JCOEFPTR coef_block,
  160610. JSAMPARRAY output_buf, JDIMENSION output_col));
  160611. struct jpeg_inverse_dct {
  160612. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160613. /* It is useful to allow each component to have a separate IDCT method. */
  160614. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160615. };
  160616. /* Upsampling (note that upsampler must also call color converter) */
  160617. struct jpeg_upsampler {
  160618. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160619. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160620. JSAMPIMAGE input_buf,
  160621. JDIMENSION *in_row_group_ctr,
  160622. JDIMENSION in_row_groups_avail,
  160623. JSAMPARRAY output_buf,
  160624. JDIMENSION *out_row_ctr,
  160625. JDIMENSION out_rows_avail));
  160626. boolean need_context_rows; /* TRUE if need rows above & below */
  160627. };
  160628. /* Colorspace conversion */
  160629. struct jpeg_color_deconverter {
  160630. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160631. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160632. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160633. JSAMPARRAY output_buf, int num_rows));
  160634. };
  160635. /* Color quantization or color precision reduction */
  160636. struct jpeg_color_quantizer {
  160637. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160638. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160639. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160640. int num_rows));
  160641. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160642. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160643. };
  160644. /* Miscellaneous useful macros */
  160645. #undef MAX
  160646. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160647. #undef MIN
  160648. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160649. /* We assume that right shift corresponds to signed division by 2 with
  160650. * rounding towards minus infinity. This is correct for typical "arithmetic
  160651. * shift" instructions that shift in copies of the sign bit. But some
  160652. * C compilers implement >> with an unsigned shift. For these machines you
  160653. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160654. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160655. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160656. * included in the variables of any routine using RIGHT_SHIFT.
  160657. */
  160658. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160659. #define SHIFT_TEMPS INT32 shift_temp;
  160660. #define RIGHT_SHIFT(x,shft) \
  160661. ((shift_temp = (x)) < 0 ? \
  160662. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  160663. (shift_temp >> (shft)))
  160664. #else
  160665. #define SHIFT_TEMPS
  160666. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  160667. #endif
  160668. /* Short forms of external names for systems with brain-damaged linkers. */
  160669. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160670. #define jinit_compress_master jICompress
  160671. #define jinit_c_master_control jICMaster
  160672. #define jinit_c_main_controller jICMainC
  160673. #define jinit_c_prep_controller jICPrepC
  160674. #define jinit_c_coef_controller jICCoefC
  160675. #define jinit_color_converter jICColor
  160676. #define jinit_downsampler jIDownsampler
  160677. #define jinit_forward_dct jIFDCT
  160678. #define jinit_huff_encoder jIHEncoder
  160679. #define jinit_phuff_encoder jIPHEncoder
  160680. #define jinit_marker_writer jIMWriter
  160681. #define jinit_master_decompress jIDMaster
  160682. #define jinit_d_main_controller jIDMainC
  160683. #define jinit_d_coef_controller jIDCoefC
  160684. #define jinit_d_post_controller jIDPostC
  160685. #define jinit_input_controller jIInCtlr
  160686. #define jinit_marker_reader jIMReader
  160687. #define jinit_huff_decoder jIHDecoder
  160688. #define jinit_phuff_decoder jIPHDecoder
  160689. #define jinit_inverse_dct jIIDCT
  160690. #define jinit_upsampler jIUpsampler
  160691. #define jinit_color_deconverter jIDColor
  160692. #define jinit_1pass_quantizer jI1Quant
  160693. #define jinit_2pass_quantizer jI2Quant
  160694. #define jinit_merged_upsampler jIMUpsampler
  160695. #define jinit_memory_mgr jIMemMgr
  160696. #define jdiv_round_up jDivRound
  160697. #define jround_up jRound
  160698. #define jcopy_sample_rows jCopySamples
  160699. #define jcopy_block_row jCopyBlocks
  160700. #define jzero_far jZeroFar
  160701. #define jpeg_zigzag_order jZIGTable
  160702. #define jpeg_natural_order jZAGTable
  160703. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160704. /* Compression module initialization routines */
  160705. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  160706. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  160707. boolean transcode_only));
  160708. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  160709. boolean need_full_buffer));
  160710. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  160711. boolean need_full_buffer));
  160712. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  160713. boolean need_full_buffer));
  160714. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  160715. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  160716. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  160717. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  160718. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  160719. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  160720. /* Decompression module initialization routines */
  160721. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  160722. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  160723. boolean need_full_buffer));
  160724. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  160725. boolean need_full_buffer));
  160726. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  160727. boolean need_full_buffer));
  160728. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  160729. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  160730. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  160731. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  160732. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  160733. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  160734. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  160735. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  160736. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  160737. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  160738. /* Memory manager initialization */
  160739. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  160740. /* Utility routines in jutils.c */
  160741. EXTERN(long) jdiv_round_up JPP((long a, long b));
  160742. EXTERN(long) jround_up JPP((long a, long b));
  160743. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  160744. JSAMPARRAY output_array, int dest_row,
  160745. int num_rows, JDIMENSION num_cols));
  160746. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  160747. JDIMENSION num_blocks));
  160748. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  160749. /* Constant tables in jutils.c */
  160750. #if 0 /* This table is not actually needed in v6a */
  160751. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  160752. #endif
  160753. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  160754. /* Suppress undefined-structure complaints if necessary. */
  160755. #ifdef INCOMPLETE_TYPES_BROKEN
  160756. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  160757. struct jvirt_sarray_control { long dummy; };
  160758. struct jvirt_barray_control { long dummy; };
  160759. #endif
  160760. #endif /* INCOMPLETE_TYPES_BROKEN */
  160761. /*** End of inlined file: jpegint.h ***/
  160762. /* fetch private declarations */
  160763. /*** Start of inlined file: jerror.h ***/
  160764. /*
  160765. * To define the enum list of message codes, include this file without
  160766. * defining macro JMESSAGE. To create a message string table, include it
  160767. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  160768. */
  160769. #ifndef JMESSAGE
  160770. #ifndef JERROR_H
  160771. /* First time through, define the enum list */
  160772. #define JMAKE_ENUM_LIST
  160773. #else
  160774. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  160775. #define JMESSAGE(code,string)
  160776. #endif /* JERROR_H */
  160777. #endif /* JMESSAGE */
  160778. #ifdef JMAKE_ENUM_LIST
  160779. typedef enum {
  160780. #define JMESSAGE(code,string) code ,
  160781. #endif /* JMAKE_ENUM_LIST */
  160782. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  160783. /* For maintenance convenience, list is alphabetical by message code name */
  160784. JMESSAGE(JERR_ARITH_NOTIMPL,
  160785. "Sorry, there are legal restrictions on arithmetic coding")
  160786. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  160787. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  160788. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  160789. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  160790. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  160791. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  160792. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  160793. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  160794. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  160795. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  160796. JMESSAGE(JERR_BAD_LIB_VERSION,
  160797. "Wrong JPEG library version: library is %d, caller expects %d")
  160798. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  160799. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  160800. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  160801. JMESSAGE(JERR_BAD_PROGRESSION,
  160802. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  160803. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  160804. "Invalid progressive parameters at scan script entry %d")
  160805. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  160806. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  160807. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  160808. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  160809. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  160810. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  160811. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  160812. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  160813. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  160814. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  160815. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  160816. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  160817. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  160818. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  160819. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  160820. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  160821. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  160822. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  160823. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  160824. JMESSAGE(JERR_FILE_READ, "Input file read error")
  160825. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  160826. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  160827. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  160828. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  160829. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  160830. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  160831. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  160832. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  160833. "Cannot transcode due to multiple use of quantization table %d")
  160834. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  160835. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  160836. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  160837. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  160838. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  160839. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  160840. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  160841. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  160842. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  160843. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  160844. JMESSAGE(JERR_QUANT_COMPONENTS,
  160845. "Cannot quantize more than %d color components")
  160846. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  160847. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  160848. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  160849. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  160850. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  160851. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  160852. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  160853. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  160854. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  160855. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  160856. JMESSAGE(JERR_TFILE_WRITE,
  160857. "Write failed on temporary file --- out of disk space?")
  160858. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  160859. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  160860. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  160861. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  160862. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  160863. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  160864. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  160865. JMESSAGE(JMSG_VERSION, JVERSION)
  160866. JMESSAGE(JTRC_16BIT_TABLES,
  160867. "Caution: quantization tables are too coarse for baseline JPEG")
  160868. JMESSAGE(JTRC_ADOBE,
  160869. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  160870. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  160871. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  160872. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  160873. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  160874. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  160875. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  160876. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  160877. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  160878. JMESSAGE(JTRC_EOI, "End Of Image")
  160879. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  160880. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  160881. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  160882. "Warning: thumbnail image size does not match data length %u")
  160883. JMESSAGE(JTRC_JFIF_EXTENSION,
  160884. "JFIF extension marker: type 0x%02x, length %u")
  160885. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  160886. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  160887. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  160888. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  160889. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  160890. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  160891. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  160892. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  160893. JMESSAGE(JTRC_RST, "RST%d")
  160894. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  160895. "Smoothing not supported with nonstandard sampling ratios")
  160896. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  160897. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  160898. JMESSAGE(JTRC_SOI, "Start of Image")
  160899. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  160900. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  160901. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  160902. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  160903. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  160904. JMESSAGE(JTRC_THUMB_JPEG,
  160905. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  160906. JMESSAGE(JTRC_THUMB_PALETTE,
  160907. "JFIF extension marker: palette thumbnail image, length %u")
  160908. JMESSAGE(JTRC_THUMB_RGB,
  160909. "JFIF extension marker: RGB thumbnail image, length %u")
  160910. JMESSAGE(JTRC_UNKNOWN_IDS,
  160911. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  160912. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  160913. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  160914. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  160915. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  160916. "Inconsistent progression sequence for component %d coefficient %d")
  160917. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  160918. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  160919. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  160920. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  160921. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  160922. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  160923. JMESSAGE(JWRN_MUST_RESYNC,
  160924. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  160925. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  160926. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  160927. #ifdef JMAKE_ENUM_LIST
  160928. JMSG_LASTMSGCODE
  160929. } J_MESSAGE_CODE;
  160930. #undef JMAKE_ENUM_LIST
  160931. #endif /* JMAKE_ENUM_LIST */
  160932. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  160933. #undef JMESSAGE
  160934. #ifndef JERROR_H
  160935. #define JERROR_H
  160936. /* Macros to simplify using the error and trace message stuff */
  160937. /* The first parameter is either type of cinfo pointer */
  160938. /* Fatal errors (print message and exit) */
  160939. #define ERREXIT(cinfo,code) \
  160940. ((cinfo)->err->msg_code = (code), \
  160941. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160942. #define ERREXIT1(cinfo,code,p1) \
  160943. ((cinfo)->err->msg_code = (code), \
  160944. (cinfo)->err->msg_parm.i[0] = (p1), \
  160945. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160946. #define ERREXIT2(cinfo,code,p1,p2) \
  160947. ((cinfo)->err->msg_code = (code), \
  160948. (cinfo)->err->msg_parm.i[0] = (p1), \
  160949. (cinfo)->err->msg_parm.i[1] = (p2), \
  160950. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160951. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  160952. ((cinfo)->err->msg_code = (code), \
  160953. (cinfo)->err->msg_parm.i[0] = (p1), \
  160954. (cinfo)->err->msg_parm.i[1] = (p2), \
  160955. (cinfo)->err->msg_parm.i[2] = (p3), \
  160956. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160957. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  160958. ((cinfo)->err->msg_code = (code), \
  160959. (cinfo)->err->msg_parm.i[0] = (p1), \
  160960. (cinfo)->err->msg_parm.i[1] = (p2), \
  160961. (cinfo)->err->msg_parm.i[2] = (p3), \
  160962. (cinfo)->err->msg_parm.i[3] = (p4), \
  160963. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160964. #define ERREXITS(cinfo,code,str) \
  160965. ((cinfo)->err->msg_code = (code), \
  160966. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  160967. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  160968. #define MAKESTMT(stuff) do { stuff } while (0)
  160969. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  160970. #define WARNMS(cinfo,code) \
  160971. ((cinfo)->err->msg_code = (code), \
  160972. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160973. #define WARNMS1(cinfo,code,p1) \
  160974. ((cinfo)->err->msg_code = (code), \
  160975. (cinfo)->err->msg_parm.i[0] = (p1), \
  160976. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160977. #define WARNMS2(cinfo,code,p1,p2) \
  160978. ((cinfo)->err->msg_code = (code), \
  160979. (cinfo)->err->msg_parm.i[0] = (p1), \
  160980. (cinfo)->err->msg_parm.i[1] = (p2), \
  160981. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  160982. /* Informational/debugging messages */
  160983. #define TRACEMS(cinfo,lvl,code) \
  160984. ((cinfo)->err->msg_code = (code), \
  160985. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160986. #define TRACEMS1(cinfo,lvl,code,p1) \
  160987. ((cinfo)->err->msg_code = (code), \
  160988. (cinfo)->err->msg_parm.i[0] = (p1), \
  160989. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160990. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  160991. ((cinfo)->err->msg_code = (code), \
  160992. (cinfo)->err->msg_parm.i[0] = (p1), \
  160993. (cinfo)->err->msg_parm.i[1] = (p2), \
  160994. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  160995. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  160996. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  160997. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  160998. (cinfo)->err->msg_code = (code); \
  160999. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161000. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161001. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161002. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161003. (cinfo)->err->msg_code = (code); \
  161004. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161005. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161006. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161007. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161008. _mp[4] = (p5); \
  161009. (cinfo)->err->msg_code = (code); \
  161010. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161011. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161012. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161013. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161014. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161015. (cinfo)->err->msg_code = (code); \
  161016. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161017. #define TRACEMSS(cinfo,lvl,code,str) \
  161018. ((cinfo)->err->msg_code = (code), \
  161019. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161020. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161021. #endif /* JERROR_H */
  161022. /*** End of inlined file: jerror.h ***/
  161023. /* fetch error codes too */
  161024. #endif
  161025. #endif /* JPEGLIB_H */
  161026. /*** End of inlined file: jpeglib.h ***/
  161027. /*** Start of inlined file: jcapimin.c ***/
  161028. #define JPEG_INTERNALS
  161029. /*** Start of inlined file: jinclude.h ***/
  161030. /* Include auto-config file to find out which system include files we need. */
  161031. #ifndef __jinclude_h__
  161032. #define __jinclude_h__
  161033. /*** Start of inlined file: jconfig.h ***/
  161034. /* see jconfig.doc for explanations */
  161035. // disable all the warnings under MSVC
  161036. #ifdef _MSC_VER
  161037. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161038. #endif
  161039. #ifdef __BORLANDC__
  161040. #pragma warn -8057
  161041. #pragma warn -8019
  161042. #pragma warn -8004
  161043. #pragma warn -8008
  161044. #endif
  161045. #define HAVE_PROTOTYPES
  161046. #define HAVE_UNSIGNED_CHAR
  161047. #define HAVE_UNSIGNED_SHORT
  161048. /* #define void char */
  161049. /* #define const */
  161050. #undef CHAR_IS_UNSIGNED
  161051. #define HAVE_STDDEF_H
  161052. #define HAVE_STDLIB_H
  161053. #undef NEED_BSD_STRINGS
  161054. #undef NEED_SYS_TYPES_H
  161055. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161056. #undef NEED_SHORT_EXTERNAL_NAMES
  161057. #undef INCOMPLETE_TYPES_BROKEN
  161058. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161059. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161060. typedef unsigned char boolean;
  161061. #endif
  161062. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161063. #ifdef JPEG_INTERNALS
  161064. #undef RIGHT_SHIFT_IS_UNSIGNED
  161065. #endif /* JPEG_INTERNALS */
  161066. #ifdef JPEG_CJPEG_DJPEG
  161067. #define BMP_SUPPORTED /* BMP image file format */
  161068. #define GIF_SUPPORTED /* GIF image file format */
  161069. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161070. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161071. #define TARGA_SUPPORTED /* Targa image file format */
  161072. #define TWO_FILE_COMMANDLINE /* optional */
  161073. #define USE_SETMODE /* Microsoft has setmode() */
  161074. #undef NEED_SIGNAL_CATCHER
  161075. #undef DONT_USE_B_MODE
  161076. #undef PROGRESS_REPORT /* optional */
  161077. #endif /* JPEG_CJPEG_DJPEG */
  161078. /*** End of inlined file: jconfig.h ***/
  161079. /* auto configuration options */
  161080. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161081. /*
  161082. * We need the NULL macro and size_t typedef.
  161083. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161084. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161085. * pull in <sys/types.h> as well.
  161086. * Note that the core JPEG library does not require <stdio.h>;
  161087. * only the default error handler and data source/destination modules do.
  161088. * But we must pull it in because of the references to FILE in jpeglib.h.
  161089. * You can remove those references if you want to compile without <stdio.h>.
  161090. */
  161091. #ifdef HAVE_STDDEF_H
  161092. #include <stddef.h>
  161093. #endif
  161094. #ifdef HAVE_STDLIB_H
  161095. #include <stdlib.h>
  161096. #endif
  161097. #ifdef NEED_SYS_TYPES_H
  161098. #include <sys/types.h>
  161099. #endif
  161100. #include <stdio.h>
  161101. /*
  161102. * We need memory copying and zeroing functions, plus strncpy().
  161103. * ANSI and System V implementations declare these in <string.h>.
  161104. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161105. * Some systems may declare memset and memcpy in <memory.h>.
  161106. *
  161107. * NOTE: we assume the size parameters to these functions are of type size_t.
  161108. * Change the casts in these macros if not!
  161109. */
  161110. #ifdef NEED_BSD_STRINGS
  161111. #include <strings.h>
  161112. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161113. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161114. #else /* not BSD, assume ANSI/SysV string lib */
  161115. #include <string.h>
  161116. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161117. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161118. #endif
  161119. /*
  161120. * In ANSI C, and indeed any rational implementation, size_t is also the
  161121. * type returned by sizeof(). However, it seems there are some irrational
  161122. * implementations out there, in which sizeof() returns an int even though
  161123. * size_t is defined as long or unsigned long. To ensure consistent results
  161124. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161125. */
  161126. #define SIZEOF(object) ((size_t) sizeof(object))
  161127. /*
  161128. * The modules that use fread() and fwrite() always invoke them through
  161129. * these macros. On some systems you may need to twiddle the argument casts.
  161130. * CAUTION: argument order is different from underlying functions!
  161131. */
  161132. #define JFREAD(file,buf,sizeofbuf) \
  161133. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161134. #define JFWRITE(file,buf,sizeofbuf) \
  161135. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161136. typedef enum { /* JPEG marker codes */
  161137. M_SOF0 = 0xc0,
  161138. M_SOF1 = 0xc1,
  161139. M_SOF2 = 0xc2,
  161140. M_SOF3 = 0xc3,
  161141. M_SOF5 = 0xc5,
  161142. M_SOF6 = 0xc6,
  161143. M_SOF7 = 0xc7,
  161144. M_JPG = 0xc8,
  161145. M_SOF9 = 0xc9,
  161146. M_SOF10 = 0xca,
  161147. M_SOF11 = 0xcb,
  161148. M_SOF13 = 0xcd,
  161149. M_SOF14 = 0xce,
  161150. M_SOF15 = 0xcf,
  161151. M_DHT = 0xc4,
  161152. M_DAC = 0xcc,
  161153. M_RST0 = 0xd0,
  161154. M_RST1 = 0xd1,
  161155. M_RST2 = 0xd2,
  161156. M_RST3 = 0xd3,
  161157. M_RST4 = 0xd4,
  161158. M_RST5 = 0xd5,
  161159. M_RST6 = 0xd6,
  161160. M_RST7 = 0xd7,
  161161. M_SOI = 0xd8,
  161162. M_EOI = 0xd9,
  161163. M_SOS = 0xda,
  161164. M_DQT = 0xdb,
  161165. M_DNL = 0xdc,
  161166. M_DRI = 0xdd,
  161167. M_DHP = 0xde,
  161168. M_EXP = 0xdf,
  161169. M_APP0 = 0xe0,
  161170. M_APP1 = 0xe1,
  161171. M_APP2 = 0xe2,
  161172. M_APP3 = 0xe3,
  161173. M_APP4 = 0xe4,
  161174. M_APP5 = 0xe5,
  161175. M_APP6 = 0xe6,
  161176. M_APP7 = 0xe7,
  161177. M_APP8 = 0xe8,
  161178. M_APP9 = 0xe9,
  161179. M_APP10 = 0xea,
  161180. M_APP11 = 0xeb,
  161181. M_APP12 = 0xec,
  161182. M_APP13 = 0xed,
  161183. M_APP14 = 0xee,
  161184. M_APP15 = 0xef,
  161185. M_JPG0 = 0xf0,
  161186. M_JPG13 = 0xfd,
  161187. M_COM = 0xfe,
  161188. M_TEM = 0x01,
  161189. M_ERROR = 0x100
  161190. } JPEG_MARKER;
  161191. /*
  161192. * Figure F.12: extend sign bit.
  161193. * On some machines, a shift and add will be faster than a table lookup.
  161194. */
  161195. #ifdef AVOID_TABLES
  161196. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161197. #else
  161198. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161199. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161200. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161201. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161202. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161203. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161204. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161205. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161206. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161207. #endif /* AVOID_TABLES */
  161208. #endif
  161209. /*** End of inlined file: jinclude.h ***/
  161210. /*
  161211. * Initialization of a JPEG compression object.
  161212. * The error manager must already be set up (in case memory manager fails).
  161213. */
  161214. GLOBAL(void)
  161215. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161216. {
  161217. int i;
  161218. /* Guard against version mismatches between library and caller. */
  161219. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161220. if (version != JPEG_LIB_VERSION)
  161221. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161222. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161223. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161224. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161225. /* For debugging purposes, we zero the whole master structure.
  161226. * But the application has already set the err pointer, and may have set
  161227. * client_data, so we have to save and restore those fields.
  161228. * Note: if application hasn't set client_data, tools like Purify may
  161229. * complain here.
  161230. */
  161231. {
  161232. struct jpeg_error_mgr * err = cinfo->err;
  161233. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161234. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161235. cinfo->err = err;
  161236. cinfo->client_data = client_data;
  161237. }
  161238. cinfo->is_decompressor = FALSE;
  161239. /* Initialize a memory manager instance for this object */
  161240. jinit_memory_mgr((j_common_ptr) cinfo);
  161241. /* Zero out pointers to permanent structures. */
  161242. cinfo->progress = NULL;
  161243. cinfo->dest = NULL;
  161244. cinfo->comp_info = NULL;
  161245. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161246. cinfo->quant_tbl_ptrs[i] = NULL;
  161247. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161248. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161249. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161250. }
  161251. cinfo->script_space = NULL;
  161252. cinfo->input_gamma = 1.0; /* in case application forgets */
  161253. /* OK, I'm ready */
  161254. cinfo->global_state = CSTATE_START;
  161255. }
  161256. /*
  161257. * Destruction of a JPEG compression object
  161258. */
  161259. GLOBAL(void)
  161260. jpeg_destroy_compress (j_compress_ptr cinfo)
  161261. {
  161262. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161263. }
  161264. /*
  161265. * Abort processing of a JPEG compression operation,
  161266. * but don't destroy the object itself.
  161267. */
  161268. GLOBAL(void)
  161269. jpeg_abort_compress (j_compress_ptr cinfo)
  161270. {
  161271. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161272. }
  161273. /*
  161274. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161275. * Marks all currently defined tables as already written (if suppress)
  161276. * or not written (if !suppress). This will control whether they get emitted
  161277. * by a subsequent jpeg_start_compress call.
  161278. *
  161279. * This routine is exported for use by applications that want to produce
  161280. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161281. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161282. * jcparam.o would be linked whether the application used it or not.
  161283. */
  161284. GLOBAL(void)
  161285. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161286. {
  161287. int i;
  161288. JQUANT_TBL * qtbl;
  161289. JHUFF_TBL * htbl;
  161290. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161291. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161292. qtbl->sent_table = suppress;
  161293. }
  161294. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161295. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161296. htbl->sent_table = suppress;
  161297. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161298. htbl->sent_table = suppress;
  161299. }
  161300. }
  161301. /*
  161302. * Finish JPEG compression.
  161303. *
  161304. * If a multipass operating mode was selected, this may do a great deal of
  161305. * work including most of the actual output.
  161306. */
  161307. GLOBAL(void)
  161308. jpeg_finish_compress (j_compress_ptr cinfo)
  161309. {
  161310. JDIMENSION iMCU_row;
  161311. if (cinfo->global_state == CSTATE_SCANNING ||
  161312. cinfo->global_state == CSTATE_RAW_OK) {
  161313. /* Terminate first pass */
  161314. if (cinfo->next_scanline < cinfo->image_height)
  161315. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161316. (*cinfo->master->finish_pass) (cinfo);
  161317. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161318. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161319. /* Perform any remaining passes */
  161320. while (! cinfo->master->is_last_pass) {
  161321. (*cinfo->master->prepare_for_pass) (cinfo);
  161322. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161323. if (cinfo->progress != NULL) {
  161324. cinfo->progress->pass_counter = (long) iMCU_row;
  161325. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161326. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161327. }
  161328. /* We bypass the main controller and invoke coef controller directly;
  161329. * all work is being done from the coefficient buffer.
  161330. */
  161331. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161332. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161333. }
  161334. (*cinfo->master->finish_pass) (cinfo);
  161335. }
  161336. /* Write EOI, do final cleanup */
  161337. (*cinfo->marker->write_file_trailer) (cinfo);
  161338. (*cinfo->dest->term_destination) (cinfo);
  161339. /* We can use jpeg_abort to release memory and reset global_state */
  161340. jpeg_abort((j_common_ptr) cinfo);
  161341. }
  161342. /*
  161343. * Write a special marker.
  161344. * This is only recommended for writing COM or APPn markers.
  161345. * Must be called after jpeg_start_compress() and before
  161346. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161347. */
  161348. GLOBAL(void)
  161349. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161350. const JOCTET *dataptr, unsigned int datalen)
  161351. {
  161352. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161353. if (cinfo->next_scanline != 0 ||
  161354. (cinfo->global_state != CSTATE_SCANNING &&
  161355. cinfo->global_state != CSTATE_RAW_OK &&
  161356. cinfo->global_state != CSTATE_WRCOEFS))
  161357. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161358. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161359. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161360. while (datalen--) {
  161361. (*write_marker_byte) (cinfo, *dataptr);
  161362. dataptr++;
  161363. }
  161364. }
  161365. /* Same, but piecemeal. */
  161366. GLOBAL(void)
  161367. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161368. {
  161369. if (cinfo->next_scanline != 0 ||
  161370. (cinfo->global_state != CSTATE_SCANNING &&
  161371. cinfo->global_state != CSTATE_RAW_OK &&
  161372. cinfo->global_state != CSTATE_WRCOEFS))
  161373. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161374. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161375. }
  161376. GLOBAL(void)
  161377. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161378. {
  161379. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161380. }
  161381. /*
  161382. * Alternate compression function: just write an abbreviated table file.
  161383. * Before calling this, all parameters and a data destination must be set up.
  161384. *
  161385. * To produce a pair of files containing abbreviated tables and abbreviated
  161386. * image data, one would proceed as follows:
  161387. *
  161388. * initialize JPEG object
  161389. * set JPEG parameters
  161390. * set destination to table file
  161391. * jpeg_write_tables(cinfo);
  161392. * set destination to image file
  161393. * jpeg_start_compress(cinfo, FALSE);
  161394. * write data...
  161395. * jpeg_finish_compress(cinfo);
  161396. *
  161397. * jpeg_write_tables has the side effect of marking all tables written
  161398. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161399. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161400. */
  161401. GLOBAL(void)
  161402. jpeg_write_tables (j_compress_ptr cinfo)
  161403. {
  161404. if (cinfo->global_state != CSTATE_START)
  161405. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161406. /* (Re)initialize error mgr and destination modules */
  161407. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161408. (*cinfo->dest->init_destination) (cinfo);
  161409. /* Initialize the marker writer ... bit of a crock to do it here. */
  161410. jinit_marker_writer(cinfo);
  161411. /* Write them tables! */
  161412. (*cinfo->marker->write_tables_only) (cinfo);
  161413. /* And clean up. */
  161414. (*cinfo->dest->term_destination) (cinfo);
  161415. /*
  161416. * In library releases up through v6a, we called jpeg_abort() here to free
  161417. * any working memory allocated by the destination manager and marker
  161418. * writer. Some applications had a problem with that: they allocated space
  161419. * of their own from the library memory manager, and didn't want it to go
  161420. * away during write_tables. So now we do nothing. This will cause a
  161421. * memory leak if an app calls write_tables repeatedly without doing a full
  161422. * compression cycle or otherwise resetting the JPEG object. However, that
  161423. * seems less bad than unexpectedly freeing memory in the normal case.
  161424. * An app that prefers the old behavior can call jpeg_abort for itself after
  161425. * each call to jpeg_write_tables().
  161426. */
  161427. }
  161428. /*** End of inlined file: jcapimin.c ***/
  161429. /*** Start of inlined file: jcapistd.c ***/
  161430. #define JPEG_INTERNALS
  161431. /*
  161432. * Compression initialization.
  161433. * Before calling this, all parameters and a data destination must be set up.
  161434. *
  161435. * We require a write_all_tables parameter as a failsafe check when writing
  161436. * multiple datastreams from the same compression object. Since prior runs
  161437. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161438. * would emit an abbreviated stream (no tables) by default. This may be what
  161439. * is wanted, but for safety's sake it should not be the default behavior:
  161440. * programmers should have to make a deliberate choice to emit abbreviated
  161441. * images. Therefore the documentation and examples should encourage people
  161442. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161443. * wrong thing.
  161444. */
  161445. GLOBAL(void)
  161446. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161447. {
  161448. if (cinfo->global_state != CSTATE_START)
  161449. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161450. if (write_all_tables)
  161451. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161452. /* (Re)initialize error mgr and destination modules */
  161453. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161454. (*cinfo->dest->init_destination) (cinfo);
  161455. /* Perform master selection of active modules */
  161456. jinit_compress_master(cinfo);
  161457. /* Set up for the first pass */
  161458. (*cinfo->master->prepare_for_pass) (cinfo);
  161459. /* Ready for application to drive first pass through jpeg_write_scanlines
  161460. * or jpeg_write_raw_data.
  161461. */
  161462. cinfo->next_scanline = 0;
  161463. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161464. }
  161465. /*
  161466. * Write some scanlines of data to the JPEG compressor.
  161467. *
  161468. * The return value will be the number of lines actually written.
  161469. * This should be less than the supplied num_lines only in case that
  161470. * the data destination module has requested suspension of the compressor,
  161471. * or if more than image_height scanlines are passed in.
  161472. *
  161473. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161474. * this likely signals an application programmer error. However,
  161475. * excess scanlines passed in the last valid call are *silently* ignored,
  161476. * so that the application need not adjust num_lines for end-of-image
  161477. * when using a multiple-scanline buffer.
  161478. */
  161479. GLOBAL(JDIMENSION)
  161480. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161481. JDIMENSION num_lines)
  161482. {
  161483. JDIMENSION row_ctr, rows_left;
  161484. if (cinfo->global_state != CSTATE_SCANNING)
  161485. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161486. if (cinfo->next_scanline >= cinfo->image_height)
  161487. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161488. /* Call progress monitor hook if present */
  161489. if (cinfo->progress != NULL) {
  161490. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161491. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161492. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161493. }
  161494. /* Give master control module another chance if this is first call to
  161495. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161496. * delayed so that application can write COM, etc, markers between
  161497. * jpeg_start_compress and jpeg_write_scanlines.
  161498. */
  161499. if (cinfo->master->call_pass_startup)
  161500. (*cinfo->master->pass_startup) (cinfo);
  161501. /* Ignore any extra scanlines at bottom of image. */
  161502. rows_left = cinfo->image_height - cinfo->next_scanline;
  161503. if (num_lines > rows_left)
  161504. num_lines = rows_left;
  161505. row_ctr = 0;
  161506. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161507. cinfo->next_scanline += row_ctr;
  161508. return row_ctr;
  161509. }
  161510. /*
  161511. * Alternate entry point to write raw data.
  161512. * Processes exactly one iMCU row per call, unless suspended.
  161513. */
  161514. GLOBAL(JDIMENSION)
  161515. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161516. JDIMENSION num_lines)
  161517. {
  161518. JDIMENSION lines_per_iMCU_row;
  161519. if (cinfo->global_state != CSTATE_RAW_OK)
  161520. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161521. if (cinfo->next_scanline >= cinfo->image_height) {
  161522. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161523. return 0;
  161524. }
  161525. /* Call progress monitor hook if present */
  161526. if (cinfo->progress != NULL) {
  161527. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161528. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161529. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161530. }
  161531. /* Give master control module another chance if this is first call to
  161532. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161533. * delayed so that application can write COM, etc, markers between
  161534. * jpeg_start_compress and jpeg_write_raw_data.
  161535. */
  161536. if (cinfo->master->call_pass_startup)
  161537. (*cinfo->master->pass_startup) (cinfo);
  161538. /* Verify that at least one iMCU row has been passed. */
  161539. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161540. if (num_lines < lines_per_iMCU_row)
  161541. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161542. /* Directly compress the row. */
  161543. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161544. /* If compressor did not consume the whole row, suspend processing. */
  161545. return 0;
  161546. }
  161547. /* OK, we processed one iMCU row. */
  161548. cinfo->next_scanline += lines_per_iMCU_row;
  161549. return lines_per_iMCU_row;
  161550. }
  161551. /*** End of inlined file: jcapistd.c ***/
  161552. /*** Start of inlined file: jccoefct.c ***/
  161553. #define JPEG_INTERNALS
  161554. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161555. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161556. * step is run during the first pass, and subsequent passes need only read
  161557. * the buffered coefficients.
  161558. */
  161559. #ifdef ENTROPY_OPT_SUPPORTED
  161560. #define FULL_COEF_BUFFER_SUPPORTED
  161561. #else
  161562. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161563. #define FULL_COEF_BUFFER_SUPPORTED
  161564. #endif
  161565. #endif
  161566. /* Private buffer controller object */
  161567. typedef struct {
  161568. struct jpeg_c_coef_controller pub; /* public fields */
  161569. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161570. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161571. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161572. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161573. /* For single-pass compression, it's sufficient to buffer just one MCU
  161574. * (although this may prove a bit slow in practice). We allocate a
  161575. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161576. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161577. * it's not really very big; this is to keep the module interfaces unchanged
  161578. * when a large coefficient buffer is necessary.)
  161579. * In multi-pass modes, this array points to the current MCU's blocks
  161580. * within the virtual arrays.
  161581. */
  161582. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161583. /* In multi-pass modes, we need a virtual block array for each component. */
  161584. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161585. } my_coef_controller;
  161586. typedef my_coef_controller * my_coef_ptr;
  161587. /* Forward declarations */
  161588. METHODDEF(boolean) compress_data
  161589. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161590. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161591. METHODDEF(boolean) compress_first_pass
  161592. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161593. METHODDEF(boolean) compress_output
  161594. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161595. #endif
  161596. LOCAL(void)
  161597. start_iMCU_row (j_compress_ptr cinfo)
  161598. /* Reset within-iMCU-row counters for a new row */
  161599. {
  161600. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161601. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161602. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161603. * But at the bottom of the image, process only what's left.
  161604. */
  161605. if (cinfo->comps_in_scan > 1) {
  161606. coef->MCU_rows_per_iMCU_row = 1;
  161607. } else {
  161608. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161609. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161610. else
  161611. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161612. }
  161613. coef->mcu_ctr = 0;
  161614. coef->MCU_vert_offset = 0;
  161615. }
  161616. /*
  161617. * Initialize for a processing pass.
  161618. */
  161619. METHODDEF(void)
  161620. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161621. {
  161622. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161623. coef->iMCU_row_num = 0;
  161624. start_iMCU_row(cinfo);
  161625. switch (pass_mode) {
  161626. case JBUF_PASS_THRU:
  161627. if (coef->whole_image[0] != NULL)
  161628. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161629. coef->pub.compress_data = compress_data;
  161630. break;
  161631. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161632. case JBUF_SAVE_AND_PASS:
  161633. if (coef->whole_image[0] == NULL)
  161634. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161635. coef->pub.compress_data = compress_first_pass;
  161636. break;
  161637. case JBUF_CRANK_DEST:
  161638. if (coef->whole_image[0] == NULL)
  161639. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161640. coef->pub.compress_data = compress_output;
  161641. break;
  161642. #endif
  161643. default:
  161644. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161645. break;
  161646. }
  161647. }
  161648. /*
  161649. * Process some data in the single-pass case.
  161650. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161651. * per call, ie, v_samp_factor block rows for each component in the image.
  161652. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161653. *
  161654. * NB: input_buf contains a plane for each component in image,
  161655. * which we index according to the component's SOF position.
  161656. */
  161657. METHODDEF(boolean)
  161658. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161659. {
  161660. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161661. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161662. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161663. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161664. int blkn, bi, ci, yindex, yoffset, blockcnt;
  161665. JDIMENSION ypos, xpos;
  161666. jpeg_component_info *compptr;
  161667. /* Loop to write as much as one whole iMCU row */
  161668. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161669. yoffset++) {
  161670. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  161671. MCU_col_num++) {
  161672. /* Determine where data comes from in input_buf and do the DCT thing.
  161673. * Each call on forward_DCT processes a horizontal row of DCT blocks
  161674. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  161675. * sequentially. Dummy blocks at the right or bottom edge are filled in
  161676. * specially. The data in them does not matter for image reconstruction,
  161677. * so we fill them with values that will encode to the smallest amount of
  161678. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  161679. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  161680. */
  161681. blkn = 0;
  161682. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161683. compptr = cinfo->cur_comp_info[ci];
  161684. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161685. : compptr->last_col_width;
  161686. xpos = MCU_col_num * compptr->MCU_sample_width;
  161687. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  161688. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161689. if (coef->iMCU_row_num < last_iMCU_row ||
  161690. yoffset+yindex < compptr->last_row_height) {
  161691. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161692. input_buf[compptr->component_index],
  161693. coef->MCU_buffer[blkn],
  161694. ypos, xpos, (JDIMENSION) blockcnt);
  161695. if (blockcnt < compptr->MCU_width) {
  161696. /* Create some dummy blocks at the right edge of the image. */
  161697. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  161698. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  161699. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  161700. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  161701. }
  161702. }
  161703. } else {
  161704. /* Create a row of dummy blocks at the bottom of the image. */
  161705. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  161706. compptr->MCU_width * SIZEOF(JBLOCK));
  161707. for (bi = 0; bi < compptr->MCU_width; bi++) {
  161708. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  161709. }
  161710. }
  161711. blkn += compptr->MCU_width;
  161712. ypos += DCTSIZE;
  161713. }
  161714. }
  161715. /* Try to write the MCU. In event of a suspension failure, we will
  161716. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  161717. */
  161718. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161719. /* Suspension forced; update state counters and exit */
  161720. coef->MCU_vert_offset = yoffset;
  161721. coef->mcu_ctr = MCU_col_num;
  161722. return FALSE;
  161723. }
  161724. }
  161725. /* Completed an MCU row, but perhaps not an iMCU row */
  161726. coef->mcu_ctr = 0;
  161727. }
  161728. /* Completed the iMCU row, advance counters for next one */
  161729. coef->iMCU_row_num++;
  161730. start_iMCU_row(cinfo);
  161731. return TRUE;
  161732. }
  161733. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161734. /*
  161735. * Process some data in the first pass of a multi-pass case.
  161736. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161737. * per call, ie, v_samp_factor block rows for each component in the image.
  161738. * This amount of data is read from the source buffer, DCT'd and quantized,
  161739. * and saved into the virtual arrays. We also generate suitable dummy blocks
  161740. * as needed at the right and lower edges. (The dummy blocks are constructed
  161741. * in the virtual arrays, which have been padded appropriately.) This makes
  161742. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  161743. *
  161744. * We must also emit the data to the entropy encoder. This is conveniently
  161745. * done by calling compress_output() after we've loaded the current strip
  161746. * of the virtual arrays.
  161747. *
  161748. * NB: input_buf contains a plane for each component in image. All
  161749. * components are DCT'd and loaded into the virtual arrays in this pass.
  161750. * However, it may be that only a subset of the components are emitted to
  161751. * the entropy encoder during this first pass; be careful about looking
  161752. * at the scan-dependent variables (MCU dimensions, etc).
  161753. */
  161754. METHODDEF(boolean)
  161755. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161756. {
  161757. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161758. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161759. JDIMENSION blocks_across, MCUs_across, MCUindex;
  161760. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  161761. JCOEF lastDC;
  161762. jpeg_component_info *compptr;
  161763. JBLOCKARRAY buffer;
  161764. JBLOCKROW thisblockrow, lastblockrow;
  161765. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161766. ci++, compptr++) {
  161767. /* Align the virtual buffer for this component. */
  161768. buffer = (*cinfo->mem->access_virt_barray)
  161769. ((j_common_ptr) cinfo, coef->whole_image[ci],
  161770. coef->iMCU_row_num * compptr->v_samp_factor,
  161771. (JDIMENSION) compptr->v_samp_factor, TRUE);
  161772. /* Count non-dummy DCT block rows in this iMCU row. */
  161773. if (coef->iMCU_row_num < last_iMCU_row)
  161774. block_rows = compptr->v_samp_factor;
  161775. else {
  161776. /* NB: can't use last_row_height here, since may not be set! */
  161777. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  161778. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  161779. }
  161780. blocks_across = compptr->width_in_blocks;
  161781. h_samp_factor = compptr->h_samp_factor;
  161782. /* Count number of dummy blocks to be added at the right margin. */
  161783. ndummy = (int) (blocks_across % h_samp_factor);
  161784. if (ndummy > 0)
  161785. ndummy = h_samp_factor - ndummy;
  161786. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  161787. * on forward_DCT processes a complete horizontal row of DCT blocks.
  161788. */
  161789. for (block_row = 0; block_row < block_rows; block_row++) {
  161790. thisblockrow = buffer[block_row];
  161791. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  161792. input_buf[ci], thisblockrow,
  161793. (JDIMENSION) (block_row * DCTSIZE),
  161794. (JDIMENSION) 0, blocks_across);
  161795. if (ndummy > 0) {
  161796. /* Create dummy blocks at the right edge of the image. */
  161797. thisblockrow += blocks_across; /* => first dummy block */
  161798. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  161799. lastDC = thisblockrow[-1][0];
  161800. for (bi = 0; bi < ndummy; bi++) {
  161801. thisblockrow[bi][0] = lastDC;
  161802. }
  161803. }
  161804. }
  161805. /* If at end of image, create dummy block rows as needed.
  161806. * The tricky part here is that within each MCU, we want the DC values
  161807. * of the dummy blocks to match the last real block's DC value.
  161808. * This squeezes a few more bytes out of the resulting file...
  161809. */
  161810. if (coef->iMCU_row_num == last_iMCU_row) {
  161811. blocks_across += ndummy; /* include lower right corner */
  161812. MCUs_across = blocks_across / h_samp_factor;
  161813. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  161814. block_row++) {
  161815. thisblockrow = buffer[block_row];
  161816. lastblockrow = buffer[block_row-1];
  161817. jzero_far((void FAR *) thisblockrow,
  161818. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  161819. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  161820. lastDC = lastblockrow[h_samp_factor-1][0];
  161821. for (bi = 0; bi < h_samp_factor; bi++) {
  161822. thisblockrow[bi][0] = lastDC;
  161823. }
  161824. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  161825. lastblockrow += h_samp_factor;
  161826. }
  161827. }
  161828. }
  161829. }
  161830. /* NB: compress_output will increment iMCU_row_num if successful.
  161831. * A suspension return will result in redoing all the work above next time.
  161832. */
  161833. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  161834. return compress_output(cinfo, input_buf);
  161835. }
  161836. /*
  161837. * Process some data in subsequent passes of a multi-pass case.
  161838. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161839. * per call, ie, v_samp_factor block rows for each component in the scan.
  161840. * The data is obtained from the virtual arrays and fed to the entropy coder.
  161841. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161842. *
  161843. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  161844. */
  161845. METHODDEF(boolean)
  161846. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  161847. {
  161848. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161849. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161850. int blkn, ci, xindex, yindex, yoffset;
  161851. JDIMENSION start_col;
  161852. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  161853. JBLOCKROW buffer_ptr;
  161854. jpeg_component_info *compptr;
  161855. /* Align the virtual buffers for the components used in this scan.
  161856. * NB: during first pass, this is safe only because the buffers will
  161857. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  161858. */
  161859. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161860. compptr = cinfo->cur_comp_info[ci];
  161861. buffer[ci] = (*cinfo->mem->access_virt_barray)
  161862. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  161863. coef->iMCU_row_num * compptr->v_samp_factor,
  161864. (JDIMENSION) compptr->v_samp_factor, FALSE);
  161865. }
  161866. /* Loop to process one whole iMCU row */
  161867. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161868. yoffset++) {
  161869. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  161870. MCU_col_num++) {
  161871. /* Construct list of pointers to DCT blocks belonging to this MCU */
  161872. blkn = 0; /* index of current DCT block within MCU */
  161873. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161874. compptr = cinfo->cur_comp_info[ci];
  161875. start_col = MCU_col_num * compptr->MCU_width;
  161876. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161877. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  161878. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  161879. coef->MCU_buffer[blkn++] = buffer_ptr++;
  161880. }
  161881. }
  161882. }
  161883. /* Try to write the MCU. */
  161884. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  161885. /* Suspension forced; update state counters and exit */
  161886. coef->MCU_vert_offset = yoffset;
  161887. coef->mcu_ctr = MCU_col_num;
  161888. return FALSE;
  161889. }
  161890. }
  161891. /* Completed an MCU row, but perhaps not an iMCU row */
  161892. coef->mcu_ctr = 0;
  161893. }
  161894. /* Completed the iMCU row, advance counters for next one */
  161895. coef->iMCU_row_num++;
  161896. start_iMCU_row(cinfo);
  161897. return TRUE;
  161898. }
  161899. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  161900. /*
  161901. * Initialize coefficient buffer controller.
  161902. */
  161903. GLOBAL(void)
  161904. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  161905. {
  161906. my_coef_ptr coef;
  161907. coef = (my_coef_ptr)
  161908. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161909. SIZEOF(my_coef_controller));
  161910. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  161911. coef->pub.start_pass = start_pass_coef;
  161912. /* Create the coefficient buffer. */
  161913. if (need_full_buffer) {
  161914. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161915. /* Allocate a full-image virtual array for each component, */
  161916. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  161917. int ci;
  161918. jpeg_component_info *compptr;
  161919. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  161920. ci++, compptr++) {
  161921. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  161922. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  161923. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  161924. (long) compptr->h_samp_factor),
  161925. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  161926. (long) compptr->v_samp_factor),
  161927. (JDIMENSION) compptr->v_samp_factor);
  161928. }
  161929. #else
  161930. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161931. #endif
  161932. } else {
  161933. /* We only need a single-MCU buffer. */
  161934. JBLOCKROW buffer;
  161935. int i;
  161936. buffer = (JBLOCKROW)
  161937. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161938. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  161939. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  161940. coef->MCU_buffer[i] = buffer + i;
  161941. }
  161942. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  161943. }
  161944. }
  161945. /*** End of inlined file: jccoefct.c ***/
  161946. /*** Start of inlined file: jccolor.c ***/
  161947. #define JPEG_INTERNALS
  161948. /* Private subobject */
  161949. typedef struct {
  161950. struct jpeg_color_converter pub; /* public fields */
  161951. /* Private state for RGB->YCC conversion */
  161952. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  161953. } my_color_converter;
  161954. typedef my_color_converter * my_cconvert_ptr;
  161955. /**************** RGB -> YCbCr conversion: most common case **************/
  161956. /*
  161957. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  161958. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  161959. * The conversion equations to be implemented are therefore
  161960. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  161961. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  161962. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  161963. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  161964. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  161965. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  161966. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  161967. * were not represented exactly. Now we sacrifice exact representation of
  161968. * maximum red and maximum blue in order to get exact grayscales.
  161969. *
  161970. * To avoid floating-point arithmetic, we represent the fractional constants
  161971. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  161972. * the products by 2^16, with appropriate rounding, to get the correct answer.
  161973. *
  161974. * For even more speed, we avoid doing any multiplications in the inner loop
  161975. * by precalculating the constants times R,G,B for all possible values.
  161976. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  161977. * for 12-bit samples it is still acceptable. It's not very reasonable for
  161978. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  161979. * colorspace anyway.
  161980. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  161981. * in the tables to save adding them separately in the inner loop.
  161982. */
  161983. #define SCALEBITS 16 /* speediest right-shift on some machines */
  161984. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  161985. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  161986. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  161987. /* We allocate one big table and divide it up into eight parts, instead of
  161988. * doing eight alloc_small requests. This lets us use a single table base
  161989. * address, which can be held in a register in the inner loops on many
  161990. * machines (more than can hold all eight addresses, anyway).
  161991. */
  161992. #define R_Y_OFF 0 /* offset to R => Y section */
  161993. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  161994. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  161995. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  161996. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  161997. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  161998. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  161999. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162000. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162001. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162002. /*
  162003. * Initialize for RGB->YCC colorspace conversion.
  162004. */
  162005. METHODDEF(void)
  162006. rgb_ycc_start (j_compress_ptr cinfo)
  162007. {
  162008. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162009. INT32 * rgb_ycc_tab;
  162010. INT32 i;
  162011. /* Allocate and fill in the conversion tables. */
  162012. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162013. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162014. (TABLE_SIZE * SIZEOF(INT32)));
  162015. for (i = 0; i <= MAXJSAMPLE; i++) {
  162016. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162017. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162018. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162019. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162020. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162021. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162022. * This ensures that the maximum output will round to MAXJSAMPLE
  162023. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162024. */
  162025. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162026. /* B=>Cb and R=>Cr tables are the same
  162027. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162028. */
  162029. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162030. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162031. }
  162032. }
  162033. /*
  162034. * Convert some rows of samples to the JPEG colorspace.
  162035. *
  162036. * Note that we change from the application's interleaved-pixel format
  162037. * to our internal noninterleaved, one-plane-per-component format.
  162038. * The input buffer is therefore three times as wide as the output buffer.
  162039. *
  162040. * A starting row offset is provided only for the output buffer. The caller
  162041. * can easily adjust the passed input_buf value to accommodate any row
  162042. * offset required on that side.
  162043. */
  162044. METHODDEF(void)
  162045. rgb_ycc_convert (j_compress_ptr cinfo,
  162046. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162047. JDIMENSION output_row, int num_rows)
  162048. {
  162049. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162050. register int r, g, b;
  162051. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162052. register JSAMPROW inptr;
  162053. register JSAMPROW outptr0, outptr1, outptr2;
  162054. register JDIMENSION col;
  162055. JDIMENSION num_cols = cinfo->image_width;
  162056. while (--num_rows >= 0) {
  162057. inptr = *input_buf++;
  162058. outptr0 = output_buf[0][output_row];
  162059. outptr1 = output_buf[1][output_row];
  162060. outptr2 = output_buf[2][output_row];
  162061. output_row++;
  162062. for (col = 0; col < num_cols; col++) {
  162063. r = GETJSAMPLE(inptr[RGB_RED]);
  162064. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162065. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162066. inptr += RGB_PIXELSIZE;
  162067. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162068. * must be too; we do not need an explicit range-limiting operation.
  162069. * Hence the value being shifted is never negative, and we don't
  162070. * need the general RIGHT_SHIFT macro.
  162071. */
  162072. /* Y */
  162073. outptr0[col] = (JSAMPLE)
  162074. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162075. >> SCALEBITS);
  162076. /* Cb */
  162077. outptr1[col] = (JSAMPLE)
  162078. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162079. >> SCALEBITS);
  162080. /* Cr */
  162081. outptr2[col] = (JSAMPLE)
  162082. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162083. >> SCALEBITS);
  162084. }
  162085. }
  162086. }
  162087. /**************** Cases other than RGB -> YCbCr **************/
  162088. /*
  162089. * Convert some rows of samples to the JPEG colorspace.
  162090. * This version handles RGB->grayscale conversion, which is the same
  162091. * as the RGB->Y portion of RGB->YCbCr.
  162092. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162093. */
  162094. METHODDEF(void)
  162095. rgb_gray_convert (j_compress_ptr cinfo,
  162096. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162097. JDIMENSION output_row, int num_rows)
  162098. {
  162099. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162100. register int r, g, b;
  162101. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162102. register JSAMPROW inptr;
  162103. register JSAMPROW outptr;
  162104. register JDIMENSION col;
  162105. JDIMENSION num_cols = cinfo->image_width;
  162106. while (--num_rows >= 0) {
  162107. inptr = *input_buf++;
  162108. outptr = output_buf[0][output_row];
  162109. output_row++;
  162110. for (col = 0; col < num_cols; col++) {
  162111. r = GETJSAMPLE(inptr[RGB_RED]);
  162112. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162113. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162114. inptr += RGB_PIXELSIZE;
  162115. /* Y */
  162116. outptr[col] = (JSAMPLE)
  162117. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162118. >> SCALEBITS);
  162119. }
  162120. }
  162121. }
  162122. /*
  162123. * Convert some rows of samples to the JPEG colorspace.
  162124. * This version handles Adobe-style CMYK->YCCK conversion,
  162125. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162126. * conversion as above, while passing K (black) unchanged.
  162127. * We assume rgb_ycc_start has been called.
  162128. */
  162129. METHODDEF(void)
  162130. cmyk_ycck_convert (j_compress_ptr cinfo,
  162131. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162132. JDIMENSION output_row, int num_rows)
  162133. {
  162134. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162135. register int r, g, b;
  162136. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162137. register JSAMPROW inptr;
  162138. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162139. register JDIMENSION col;
  162140. JDIMENSION num_cols = cinfo->image_width;
  162141. while (--num_rows >= 0) {
  162142. inptr = *input_buf++;
  162143. outptr0 = output_buf[0][output_row];
  162144. outptr1 = output_buf[1][output_row];
  162145. outptr2 = output_buf[2][output_row];
  162146. outptr3 = output_buf[3][output_row];
  162147. output_row++;
  162148. for (col = 0; col < num_cols; col++) {
  162149. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162150. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162151. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162152. /* K passes through as-is */
  162153. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162154. inptr += 4;
  162155. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162156. * must be too; we do not need an explicit range-limiting operation.
  162157. * Hence the value being shifted is never negative, and we don't
  162158. * need the general RIGHT_SHIFT macro.
  162159. */
  162160. /* Y */
  162161. outptr0[col] = (JSAMPLE)
  162162. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162163. >> SCALEBITS);
  162164. /* Cb */
  162165. outptr1[col] = (JSAMPLE)
  162166. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162167. >> SCALEBITS);
  162168. /* Cr */
  162169. outptr2[col] = (JSAMPLE)
  162170. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162171. >> SCALEBITS);
  162172. }
  162173. }
  162174. }
  162175. /*
  162176. * Convert some rows of samples to the JPEG colorspace.
  162177. * This version handles grayscale output with no conversion.
  162178. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162179. */
  162180. METHODDEF(void)
  162181. grayscale_convert (j_compress_ptr cinfo,
  162182. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162183. JDIMENSION output_row, int num_rows)
  162184. {
  162185. register JSAMPROW inptr;
  162186. register JSAMPROW outptr;
  162187. register JDIMENSION col;
  162188. JDIMENSION num_cols = cinfo->image_width;
  162189. int instride = cinfo->input_components;
  162190. while (--num_rows >= 0) {
  162191. inptr = *input_buf++;
  162192. outptr = output_buf[0][output_row];
  162193. output_row++;
  162194. for (col = 0; col < num_cols; col++) {
  162195. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162196. inptr += instride;
  162197. }
  162198. }
  162199. }
  162200. /*
  162201. * Convert some rows of samples to the JPEG colorspace.
  162202. * This version handles multi-component colorspaces without conversion.
  162203. * We assume input_components == num_components.
  162204. */
  162205. METHODDEF(void)
  162206. null_convert (j_compress_ptr cinfo,
  162207. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162208. JDIMENSION output_row, int num_rows)
  162209. {
  162210. register JSAMPROW inptr;
  162211. register JSAMPROW outptr;
  162212. register JDIMENSION col;
  162213. register int ci;
  162214. int nc = cinfo->num_components;
  162215. JDIMENSION num_cols = cinfo->image_width;
  162216. while (--num_rows >= 0) {
  162217. /* It seems fastest to make a separate pass for each component. */
  162218. for (ci = 0; ci < nc; ci++) {
  162219. inptr = *input_buf;
  162220. outptr = output_buf[ci][output_row];
  162221. for (col = 0; col < num_cols; col++) {
  162222. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162223. inptr += nc;
  162224. }
  162225. }
  162226. input_buf++;
  162227. output_row++;
  162228. }
  162229. }
  162230. /*
  162231. * Empty method for start_pass.
  162232. */
  162233. METHODDEF(void)
  162234. null_method (j_compress_ptr)
  162235. {
  162236. /* no work needed */
  162237. }
  162238. /*
  162239. * Module initialization routine for input colorspace conversion.
  162240. */
  162241. GLOBAL(void)
  162242. jinit_color_converter (j_compress_ptr cinfo)
  162243. {
  162244. my_cconvert_ptr cconvert;
  162245. cconvert = (my_cconvert_ptr)
  162246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162247. SIZEOF(my_color_converter));
  162248. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162249. /* set start_pass to null method until we find out differently */
  162250. cconvert->pub.start_pass = null_method;
  162251. /* Make sure input_components agrees with in_color_space */
  162252. switch (cinfo->in_color_space) {
  162253. case JCS_GRAYSCALE:
  162254. if (cinfo->input_components != 1)
  162255. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162256. break;
  162257. case JCS_RGB:
  162258. #if RGB_PIXELSIZE != 3
  162259. if (cinfo->input_components != RGB_PIXELSIZE)
  162260. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162261. break;
  162262. #endif /* else share code with YCbCr */
  162263. case JCS_YCbCr:
  162264. if (cinfo->input_components != 3)
  162265. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162266. break;
  162267. case JCS_CMYK:
  162268. case JCS_YCCK:
  162269. if (cinfo->input_components != 4)
  162270. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162271. break;
  162272. default: /* JCS_UNKNOWN can be anything */
  162273. if (cinfo->input_components < 1)
  162274. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162275. break;
  162276. }
  162277. /* Check num_components, set conversion method based on requested space */
  162278. switch (cinfo->jpeg_color_space) {
  162279. case JCS_GRAYSCALE:
  162280. if (cinfo->num_components != 1)
  162281. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162282. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162283. cconvert->pub.color_convert = grayscale_convert;
  162284. else if (cinfo->in_color_space == JCS_RGB) {
  162285. cconvert->pub.start_pass = rgb_ycc_start;
  162286. cconvert->pub.color_convert = rgb_gray_convert;
  162287. } else if (cinfo->in_color_space == JCS_YCbCr)
  162288. cconvert->pub.color_convert = grayscale_convert;
  162289. else
  162290. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162291. break;
  162292. case JCS_RGB:
  162293. if (cinfo->num_components != 3)
  162294. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162295. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162296. cconvert->pub.color_convert = null_convert;
  162297. else
  162298. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162299. break;
  162300. case JCS_YCbCr:
  162301. if (cinfo->num_components != 3)
  162302. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162303. if (cinfo->in_color_space == JCS_RGB) {
  162304. cconvert->pub.start_pass = rgb_ycc_start;
  162305. cconvert->pub.color_convert = rgb_ycc_convert;
  162306. } else if (cinfo->in_color_space == JCS_YCbCr)
  162307. cconvert->pub.color_convert = null_convert;
  162308. else
  162309. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162310. break;
  162311. case JCS_CMYK:
  162312. if (cinfo->num_components != 4)
  162313. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162314. if (cinfo->in_color_space == JCS_CMYK)
  162315. cconvert->pub.color_convert = null_convert;
  162316. else
  162317. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162318. break;
  162319. case JCS_YCCK:
  162320. if (cinfo->num_components != 4)
  162321. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162322. if (cinfo->in_color_space == JCS_CMYK) {
  162323. cconvert->pub.start_pass = rgb_ycc_start;
  162324. cconvert->pub.color_convert = cmyk_ycck_convert;
  162325. } else if (cinfo->in_color_space == JCS_YCCK)
  162326. cconvert->pub.color_convert = null_convert;
  162327. else
  162328. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162329. break;
  162330. default: /* allow null conversion of JCS_UNKNOWN */
  162331. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162332. cinfo->num_components != cinfo->input_components)
  162333. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162334. cconvert->pub.color_convert = null_convert;
  162335. break;
  162336. }
  162337. }
  162338. /*** End of inlined file: jccolor.c ***/
  162339. #undef FIX
  162340. /*** Start of inlined file: jcdctmgr.c ***/
  162341. #define JPEG_INTERNALS
  162342. /*** Start of inlined file: jdct.h ***/
  162343. /*
  162344. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162345. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162346. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162347. * implementations use an array of type FAST_FLOAT, instead.)
  162348. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162349. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162350. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162351. * convention improves accuracy in integer implementations and saves some
  162352. * work in floating-point ones.
  162353. * Quantization of the output coefficients is done by jcdctmgr.c.
  162354. */
  162355. #ifndef __jdct_h__
  162356. #define __jdct_h__
  162357. #if BITS_IN_JSAMPLE == 8
  162358. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162359. #else
  162360. typedef INT32 DCTELEM; /* must have 32 bits */
  162361. #endif
  162362. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162363. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162364. /*
  162365. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162366. * to an output sample array. The routine must dequantize the input data as
  162367. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162368. * pointed to by compptr->dct_table. The output data is to be placed into the
  162369. * sample array starting at a specified column. (Any row offset needed will
  162370. * be applied to the array pointer before it is passed to the IDCT code.)
  162371. * Note that the number of samples emitted by the IDCT routine is
  162372. * DCT_scaled_size * DCT_scaled_size.
  162373. */
  162374. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162375. /*
  162376. * Each IDCT routine has its own ideas about the best dct_table element type.
  162377. */
  162378. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162379. #if BITS_IN_JSAMPLE == 8
  162380. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162381. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162382. #else
  162383. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162384. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162385. #endif
  162386. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162387. /*
  162388. * Each IDCT routine is responsible for range-limiting its results and
  162389. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162390. * be quite far out of range if the input data is corrupt, so a bulletproof
  162391. * range-limiting step is required. We use a mask-and-table-lookup method
  162392. * to do the combined operations quickly. See the comments with
  162393. * prepare_range_limit_table (in jdmaster.c) for more info.
  162394. */
  162395. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162396. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162397. /* Short forms of external names for systems with brain-damaged linkers. */
  162398. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162399. #define jpeg_fdct_islow jFDislow
  162400. #define jpeg_fdct_ifast jFDifast
  162401. #define jpeg_fdct_float jFDfloat
  162402. #define jpeg_idct_islow jRDislow
  162403. #define jpeg_idct_ifast jRDifast
  162404. #define jpeg_idct_float jRDfloat
  162405. #define jpeg_idct_4x4 jRD4x4
  162406. #define jpeg_idct_2x2 jRD2x2
  162407. #define jpeg_idct_1x1 jRD1x1
  162408. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162409. /* Extern declarations for the forward and inverse DCT routines. */
  162410. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162411. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162412. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162413. EXTERN(void) jpeg_idct_islow
  162414. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162415. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162416. EXTERN(void) jpeg_idct_ifast
  162417. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162418. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162419. EXTERN(void) jpeg_idct_float
  162420. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162421. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162422. EXTERN(void) jpeg_idct_4x4
  162423. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162424. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162425. EXTERN(void) jpeg_idct_2x2
  162426. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162427. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162428. EXTERN(void) jpeg_idct_1x1
  162429. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162430. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162431. /*
  162432. * Macros for handling fixed-point arithmetic; these are used by many
  162433. * but not all of the DCT/IDCT modules.
  162434. *
  162435. * All values are expected to be of type INT32.
  162436. * Fractional constants are scaled left by CONST_BITS bits.
  162437. * CONST_BITS is defined within each module using these macros,
  162438. * and may differ from one module to the next.
  162439. */
  162440. #define ONE ((INT32) 1)
  162441. #define CONST_SCALE (ONE << CONST_BITS)
  162442. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162443. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162444. * thus causing a lot of useless floating-point operations at run time.
  162445. */
  162446. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162447. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162448. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162449. * the fudge factor is correct for either sign of X.
  162450. */
  162451. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162452. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162453. * This macro is used only when the two inputs will actually be no more than
  162454. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162455. * full 32x32 multiply. This provides a useful speedup on many machines.
  162456. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162457. * in C, but some C compilers will do the right thing if you provide the
  162458. * correct combination of casts.
  162459. */
  162460. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162461. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162462. #endif
  162463. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162464. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162465. #endif
  162466. #ifndef MULTIPLY16C16 /* default definition */
  162467. #define MULTIPLY16C16(var,const) ((var) * (const))
  162468. #endif
  162469. /* Same except both inputs are variables. */
  162470. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162471. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162472. #endif
  162473. #ifndef MULTIPLY16V16 /* default definition */
  162474. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162475. #endif
  162476. #endif
  162477. /*** End of inlined file: jdct.h ***/
  162478. /* Private declarations for DCT subsystem */
  162479. /* Private subobject for this module */
  162480. typedef struct {
  162481. struct jpeg_forward_dct pub; /* public fields */
  162482. /* Pointer to the DCT routine actually in use */
  162483. forward_DCT_method_ptr do_dct;
  162484. /* The actual post-DCT divisors --- not identical to the quant table
  162485. * entries, because of scaling (especially for an unnormalized DCT).
  162486. * Each table is given in normal array order.
  162487. */
  162488. DCTELEM * divisors[NUM_QUANT_TBLS];
  162489. #ifdef DCT_FLOAT_SUPPORTED
  162490. /* Same as above for the floating-point case. */
  162491. float_DCT_method_ptr do_float_dct;
  162492. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162493. #endif
  162494. } my_fdct_controller;
  162495. typedef my_fdct_controller * my_fdct_ptr;
  162496. /*
  162497. * Initialize for a processing pass.
  162498. * Verify that all referenced Q-tables are present, and set up
  162499. * the divisor table for each one.
  162500. * In the current implementation, DCT of all components is done during
  162501. * the first pass, even if only some components will be output in the
  162502. * first scan. Hence all components should be examined here.
  162503. */
  162504. METHODDEF(void)
  162505. start_pass_fdctmgr (j_compress_ptr cinfo)
  162506. {
  162507. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162508. int ci, qtblno, i;
  162509. jpeg_component_info *compptr;
  162510. JQUANT_TBL * qtbl;
  162511. DCTELEM * dtbl;
  162512. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162513. ci++, compptr++) {
  162514. qtblno = compptr->quant_tbl_no;
  162515. /* Make sure specified quantization table is present */
  162516. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162517. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162518. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162519. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162520. /* Compute divisors for this quant table */
  162521. /* We may do this more than once for same table, but it's not a big deal */
  162522. switch (cinfo->dct_method) {
  162523. #ifdef DCT_ISLOW_SUPPORTED
  162524. case JDCT_ISLOW:
  162525. /* For LL&M IDCT method, divisors are equal to raw quantization
  162526. * coefficients multiplied by 8 (to counteract scaling).
  162527. */
  162528. if (fdct->divisors[qtblno] == NULL) {
  162529. fdct->divisors[qtblno] = (DCTELEM *)
  162530. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162531. DCTSIZE2 * SIZEOF(DCTELEM));
  162532. }
  162533. dtbl = fdct->divisors[qtblno];
  162534. for (i = 0; i < DCTSIZE2; i++) {
  162535. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162536. }
  162537. break;
  162538. #endif
  162539. #ifdef DCT_IFAST_SUPPORTED
  162540. case JDCT_IFAST:
  162541. {
  162542. /* For AA&N IDCT method, divisors are equal to quantization
  162543. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162544. * scalefactor[0] = 1
  162545. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162546. * We apply a further scale factor of 8.
  162547. */
  162548. #define CONST_BITS 14
  162549. static const INT16 aanscales[DCTSIZE2] = {
  162550. /* precomputed values scaled up by 14 bits */
  162551. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162552. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162553. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162554. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162555. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162556. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162557. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162558. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162559. };
  162560. SHIFT_TEMPS
  162561. if (fdct->divisors[qtblno] == NULL) {
  162562. fdct->divisors[qtblno] = (DCTELEM *)
  162563. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162564. DCTSIZE2 * SIZEOF(DCTELEM));
  162565. }
  162566. dtbl = fdct->divisors[qtblno];
  162567. for (i = 0; i < DCTSIZE2; i++) {
  162568. dtbl[i] = (DCTELEM)
  162569. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162570. (INT32) aanscales[i]),
  162571. CONST_BITS-3);
  162572. }
  162573. }
  162574. break;
  162575. #endif
  162576. #ifdef DCT_FLOAT_SUPPORTED
  162577. case JDCT_FLOAT:
  162578. {
  162579. /* For float AA&N IDCT method, divisors are equal to quantization
  162580. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162581. * scalefactor[0] = 1
  162582. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162583. * We apply a further scale factor of 8.
  162584. * What's actually stored is 1/divisor so that the inner loop can
  162585. * use a multiplication rather than a division.
  162586. */
  162587. FAST_FLOAT * fdtbl;
  162588. int row, col;
  162589. static const double aanscalefactor[DCTSIZE] = {
  162590. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162591. 1.0, 0.785694958, 0.541196100, 0.275899379
  162592. };
  162593. if (fdct->float_divisors[qtblno] == NULL) {
  162594. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162595. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162596. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162597. }
  162598. fdtbl = fdct->float_divisors[qtblno];
  162599. i = 0;
  162600. for (row = 0; row < DCTSIZE; row++) {
  162601. for (col = 0; col < DCTSIZE; col++) {
  162602. fdtbl[i] = (FAST_FLOAT)
  162603. (1.0 / (((double) qtbl->quantval[i] *
  162604. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162605. i++;
  162606. }
  162607. }
  162608. }
  162609. break;
  162610. #endif
  162611. default:
  162612. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162613. break;
  162614. }
  162615. }
  162616. }
  162617. /*
  162618. * Perform forward DCT on one or more blocks of a component.
  162619. *
  162620. * The input samples are taken from the sample_data[] array starting at
  162621. * position start_row/start_col, and moving to the right for any additional
  162622. * blocks. The quantized coefficients are returned in coef_blocks[].
  162623. */
  162624. METHODDEF(void)
  162625. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162626. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162627. JDIMENSION start_row, JDIMENSION start_col,
  162628. JDIMENSION num_blocks)
  162629. /* This version is used for integer DCT implementations. */
  162630. {
  162631. /* This routine is heavily used, so it's worth coding it tightly. */
  162632. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162633. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162634. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162635. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162636. JDIMENSION bi;
  162637. sample_data += start_row; /* fold in the vertical offset once */
  162638. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162639. /* Load data into workspace, applying unsigned->signed conversion */
  162640. { register DCTELEM *workspaceptr;
  162641. register JSAMPROW elemptr;
  162642. register int elemr;
  162643. workspaceptr = workspace;
  162644. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162645. elemptr = sample_data[elemr] + start_col;
  162646. #if DCTSIZE == 8 /* unroll the inner loop */
  162647. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162648. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162649. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162650. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162651. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162652. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162653. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162654. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162655. #else
  162656. { register int elemc;
  162657. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162658. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162659. }
  162660. }
  162661. #endif
  162662. }
  162663. }
  162664. /* Perform the DCT */
  162665. (*do_dct) (workspace);
  162666. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162667. { register DCTELEM temp, qval;
  162668. register int i;
  162669. register JCOEFPTR output_ptr = coef_blocks[bi];
  162670. for (i = 0; i < DCTSIZE2; i++) {
  162671. qval = divisors[i];
  162672. temp = workspace[i];
  162673. /* Divide the coefficient value by qval, ensuring proper rounding.
  162674. * Since C does not specify the direction of rounding for negative
  162675. * quotients, we have to force the dividend positive for portability.
  162676. *
  162677. * In most files, at least half of the output values will be zero
  162678. * (at default quantization settings, more like three-quarters...)
  162679. * so we should ensure that this case is fast. On many machines,
  162680. * a comparison is enough cheaper than a divide to make a special test
  162681. * a win. Since both inputs will be nonnegative, we need only test
  162682. * for a < b to discover whether a/b is 0.
  162683. * If your machine's division is fast enough, define FAST_DIVIDE.
  162684. */
  162685. #ifdef FAST_DIVIDE
  162686. #define DIVIDE_BY(a,b) a /= b
  162687. #else
  162688. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  162689. #endif
  162690. if (temp < 0) {
  162691. temp = -temp;
  162692. temp += qval>>1; /* for rounding */
  162693. DIVIDE_BY(temp, qval);
  162694. temp = -temp;
  162695. } else {
  162696. temp += qval>>1; /* for rounding */
  162697. DIVIDE_BY(temp, qval);
  162698. }
  162699. output_ptr[i] = (JCOEF) temp;
  162700. }
  162701. }
  162702. }
  162703. }
  162704. #ifdef DCT_FLOAT_SUPPORTED
  162705. METHODDEF(void)
  162706. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162707. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162708. JDIMENSION start_row, JDIMENSION start_col,
  162709. JDIMENSION num_blocks)
  162710. /* This version is used for floating-point DCT implementations. */
  162711. {
  162712. /* This routine is heavily used, so it's worth coding it tightly. */
  162713. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162714. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  162715. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  162716. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162717. JDIMENSION bi;
  162718. sample_data += start_row; /* fold in the vertical offset once */
  162719. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162720. /* Load data into workspace, applying unsigned->signed conversion */
  162721. { register FAST_FLOAT *workspaceptr;
  162722. register JSAMPROW elemptr;
  162723. register int elemr;
  162724. workspaceptr = workspace;
  162725. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162726. elemptr = sample_data[elemr] + start_col;
  162727. #if DCTSIZE == 8 /* unroll the inner loop */
  162728. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162729. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162730. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162731. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162732. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162733. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162734. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162735. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162736. #else
  162737. { register int elemc;
  162738. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162739. *workspaceptr++ = (FAST_FLOAT)
  162740. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  162741. }
  162742. }
  162743. #endif
  162744. }
  162745. }
  162746. /* Perform the DCT */
  162747. (*do_dct) (workspace);
  162748. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  162749. { register FAST_FLOAT temp;
  162750. register int i;
  162751. register JCOEFPTR output_ptr = coef_blocks[bi];
  162752. for (i = 0; i < DCTSIZE2; i++) {
  162753. /* Apply the quantization and scaling factor */
  162754. temp = workspace[i] * divisors[i];
  162755. /* Round to nearest integer.
  162756. * Since C does not specify the direction of rounding for negative
  162757. * quotients, we have to force the dividend positive for portability.
  162758. * The maximum coefficient size is +-16K (for 12-bit data), so this
  162759. * code should work for either 16-bit or 32-bit ints.
  162760. */
  162761. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  162762. }
  162763. }
  162764. }
  162765. }
  162766. #endif /* DCT_FLOAT_SUPPORTED */
  162767. /*
  162768. * Initialize FDCT manager.
  162769. */
  162770. GLOBAL(void)
  162771. jinit_forward_dct (j_compress_ptr cinfo)
  162772. {
  162773. my_fdct_ptr fdct;
  162774. int i;
  162775. fdct = (my_fdct_ptr)
  162776. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162777. SIZEOF(my_fdct_controller));
  162778. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  162779. fdct->pub.start_pass = start_pass_fdctmgr;
  162780. switch (cinfo->dct_method) {
  162781. #ifdef DCT_ISLOW_SUPPORTED
  162782. case JDCT_ISLOW:
  162783. fdct->pub.forward_DCT = forward_DCT;
  162784. fdct->do_dct = jpeg_fdct_islow;
  162785. break;
  162786. #endif
  162787. #ifdef DCT_IFAST_SUPPORTED
  162788. case JDCT_IFAST:
  162789. fdct->pub.forward_DCT = forward_DCT;
  162790. fdct->do_dct = jpeg_fdct_ifast;
  162791. break;
  162792. #endif
  162793. #ifdef DCT_FLOAT_SUPPORTED
  162794. case JDCT_FLOAT:
  162795. fdct->pub.forward_DCT = forward_DCT_float;
  162796. fdct->do_float_dct = jpeg_fdct_float;
  162797. break;
  162798. #endif
  162799. default:
  162800. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162801. break;
  162802. }
  162803. /* Mark divisor tables unallocated */
  162804. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162805. fdct->divisors[i] = NULL;
  162806. #ifdef DCT_FLOAT_SUPPORTED
  162807. fdct->float_divisors[i] = NULL;
  162808. #endif
  162809. }
  162810. }
  162811. /*** End of inlined file: jcdctmgr.c ***/
  162812. #undef CONST_BITS
  162813. /*** Start of inlined file: jchuff.c ***/
  162814. #define JPEG_INTERNALS
  162815. /*** Start of inlined file: jchuff.h ***/
  162816. /* The legal range of a DCT coefficient is
  162817. * -1024 .. +1023 for 8-bit data;
  162818. * -16384 .. +16383 for 12-bit data.
  162819. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  162820. */
  162821. #ifndef _jchuff_h_
  162822. #define _jchuff_h_
  162823. #if BITS_IN_JSAMPLE == 8
  162824. #define MAX_COEF_BITS 10
  162825. #else
  162826. #define MAX_COEF_BITS 14
  162827. #endif
  162828. /* Derived data constructed for each Huffman table */
  162829. typedef struct {
  162830. unsigned int ehufco[256]; /* code for each symbol */
  162831. char ehufsi[256]; /* length of code for each symbol */
  162832. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  162833. } c_derived_tbl;
  162834. /* Short forms of external names for systems with brain-damaged linkers. */
  162835. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162836. #define jpeg_make_c_derived_tbl jMkCDerived
  162837. #define jpeg_gen_optimal_table jGenOptTbl
  162838. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162839. /* Expand a Huffman table definition into the derived format */
  162840. EXTERN(void) jpeg_make_c_derived_tbl
  162841. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  162842. c_derived_tbl ** pdtbl));
  162843. /* Generate an optimal table definition given the specified counts */
  162844. EXTERN(void) jpeg_gen_optimal_table
  162845. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  162846. #endif
  162847. /*** End of inlined file: jchuff.h ***/
  162848. /* Declarations shared with jcphuff.c */
  162849. /* Expanded entropy encoder object for Huffman encoding.
  162850. *
  162851. * The savable_state subrecord contains fields that change within an MCU,
  162852. * but must not be updated permanently until we complete the MCU.
  162853. */
  162854. typedef struct {
  162855. INT32 put_buffer; /* current bit-accumulation buffer */
  162856. int put_bits; /* # of bits now in it */
  162857. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  162858. } savable_state;
  162859. /* This macro is to work around compilers with missing or broken
  162860. * structure assignment. You'll need to fix this code if you have
  162861. * such a compiler and you change MAX_COMPS_IN_SCAN.
  162862. */
  162863. #ifndef NO_STRUCT_ASSIGN
  162864. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  162865. #else
  162866. #if MAX_COMPS_IN_SCAN == 4
  162867. #define ASSIGN_STATE(dest,src) \
  162868. ((dest).put_buffer = (src).put_buffer, \
  162869. (dest).put_bits = (src).put_bits, \
  162870. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  162871. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  162872. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  162873. (dest).last_dc_val[3] = (src).last_dc_val[3])
  162874. #endif
  162875. #endif
  162876. typedef struct {
  162877. struct jpeg_entropy_encoder pub; /* public fields */
  162878. savable_state saved; /* Bit buffer & DC state at start of MCU */
  162879. /* These fields are NOT loaded into local working state. */
  162880. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  162881. int next_restart_num; /* next restart number to write (0-7) */
  162882. /* Pointers to derived tables (these workspaces have image lifespan) */
  162883. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  162884. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  162885. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  162886. long * dc_count_ptrs[NUM_HUFF_TBLS];
  162887. long * ac_count_ptrs[NUM_HUFF_TBLS];
  162888. #endif
  162889. } huff_entropy_encoder;
  162890. typedef huff_entropy_encoder * huff_entropy_ptr;
  162891. /* Working state while writing an MCU.
  162892. * This struct contains all the fields that are needed by subroutines.
  162893. */
  162894. typedef struct {
  162895. JOCTET * next_output_byte; /* => next byte to write in buffer */
  162896. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  162897. savable_state cur; /* Current bit buffer & DC state */
  162898. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  162899. } working_state;
  162900. /* Forward declarations */
  162901. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  162902. JBLOCKROW *MCU_data));
  162903. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  162904. #ifdef ENTROPY_OPT_SUPPORTED
  162905. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  162906. JBLOCKROW *MCU_data));
  162907. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  162908. #endif
  162909. /*
  162910. * Initialize for a Huffman-compressed scan.
  162911. * If gather_statistics is TRUE, we do not output anything during the scan,
  162912. * just count the Huffman symbols used and generate Huffman code tables.
  162913. */
  162914. METHODDEF(void)
  162915. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  162916. {
  162917. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  162918. int ci, dctbl, actbl;
  162919. jpeg_component_info * compptr;
  162920. if (gather_statistics) {
  162921. #ifdef ENTROPY_OPT_SUPPORTED
  162922. entropy->pub.encode_mcu = encode_mcu_gather;
  162923. entropy->pub.finish_pass = finish_pass_gather;
  162924. #else
  162925. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162926. #endif
  162927. } else {
  162928. entropy->pub.encode_mcu = encode_mcu_huff;
  162929. entropy->pub.finish_pass = finish_pass_huff;
  162930. }
  162931. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162932. compptr = cinfo->cur_comp_info[ci];
  162933. dctbl = compptr->dc_tbl_no;
  162934. actbl = compptr->ac_tbl_no;
  162935. if (gather_statistics) {
  162936. #ifdef ENTROPY_OPT_SUPPORTED
  162937. /* Check for invalid table indexes */
  162938. /* (make_c_derived_tbl does this in the other path) */
  162939. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  162940. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  162941. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  162942. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  162943. /* Allocate and zero the statistics tables */
  162944. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  162945. if (entropy->dc_count_ptrs[dctbl] == NULL)
  162946. entropy->dc_count_ptrs[dctbl] = (long *)
  162947. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162948. 257 * SIZEOF(long));
  162949. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  162950. if (entropy->ac_count_ptrs[actbl] == NULL)
  162951. entropy->ac_count_ptrs[actbl] = (long *)
  162952. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162953. 257 * SIZEOF(long));
  162954. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  162955. #endif
  162956. } else {
  162957. /* Compute derived values for Huffman tables */
  162958. /* We may do this more than once for a table, but it's not expensive */
  162959. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  162960. & entropy->dc_derived_tbls[dctbl]);
  162961. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  162962. & entropy->ac_derived_tbls[actbl]);
  162963. }
  162964. /* Initialize DC predictions to 0 */
  162965. entropy->saved.last_dc_val[ci] = 0;
  162966. }
  162967. /* Initialize bit buffer to empty */
  162968. entropy->saved.put_buffer = 0;
  162969. entropy->saved.put_bits = 0;
  162970. /* Initialize restart stuff */
  162971. entropy->restarts_to_go = cinfo->restart_interval;
  162972. entropy->next_restart_num = 0;
  162973. }
  162974. /*
  162975. * Compute the derived values for a Huffman table.
  162976. * This routine also performs some validation checks on the table.
  162977. *
  162978. * Note this is also used by jcphuff.c.
  162979. */
  162980. GLOBAL(void)
  162981. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  162982. c_derived_tbl ** pdtbl)
  162983. {
  162984. JHUFF_TBL *htbl;
  162985. c_derived_tbl *dtbl;
  162986. int p, i, l, lastp, si, maxsymbol;
  162987. char huffsize[257];
  162988. unsigned int huffcode[257];
  162989. unsigned int code;
  162990. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  162991. * paralleling the order of the symbols themselves in htbl->huffval[].
  162992. */
  162993. /* Find the input Huffman table */
  162994. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  162995. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  162996. htbl =
  162997. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  162998. if (htbl == NULL)
  162999. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163000. /* Allocate a workspace if we haven't already done so. */
  163001. if (*pdtbl == NULL)
  163002. *pdtbl = (c_derived_tbl *)
  163003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163004. SIZEOF(c_derived_tbl));
  163005. dtbl = *pdtbl;
  163006. /* Figure C.1: make table of Huffman code length for each symbol */
  163007. p = 0;
  163008. for (l = 1; l <= 16; l++) {
  163009. i = (int) htbl->bits[l];
  163010. if (i < 0 || p + i > 256) /* protect against table overrun */
  163011. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163012. while (i--)
  163013. huffsize[p++] = (char) l;
  163014. }
  163015. huffsize[p] = 0;
  163016. lastp = p;
  163017. /* Figure C.2: generate the codes themselves */
  163018. /* We also validate that the counts represent a legal Huffman code tree. */
  163019. code = 0;
  163020. si = huffsize[0];
  163021. p = 0;
  163022. while (huffsize[p]) {
  163023. while (((int) huffsize[p]) == si) {
  163024. huffcode[p++] = code;
  163025. code++;
  163026. }
  163027. /* code is now 1 more than the last code used for codelength si; but
  163028. * it must still fit in si bits, since no code is allowed to be all ones.
  163029. */
  163030. if (((INT32) code) >= (((INT32) 1) << si))
  163031. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163032. code <<= 1;
  163033. si++;
  163034. }
  163035. /* Figure C.3: generate encoding tables */
  163036. /* These are code and size indexed by symbol value */
  163037. /* Set all codeless symbols to have code length 0;
  163038. * this lets us detect duplicate VAL entries here, and later
  163039. * allows emit_bits to detect any attempt to emit such symbols.
  163040. */
  163041. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163042. /* This is also a convenient place to check for out-of-range
  163043. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163044. * but only 0..15 for DC. (We could constrain them further
  163045. * based on data depth and mode, but this seems enough.)
  163046. */
  163047. maxsymbol = isDC ? 15 : 255;
  163048. for (p = 0; p < lastp; p++) {
  163049. i = htbl->huffval[p];
  163050. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163051. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163052. dtbl->ehufco[i] = huffcode[p];
  163053. dtbl->ehufsi[i] = huffsize[p];
  163054. }
  163055. }
  163056. /* Outputting bytes to the file */
  163057. /* Emit a byte, taking 'action' if must suspend. */
  163058. #define emit_byte(state,val,action) \
  163059. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163060. if (--(state)->free_in_buffer == 0) \
  163061. if (! dump_buffer(state)) \
  163062. { action; } }
  163063. LOCAL(boolean)
  163064. dump_buffer (working_state * state)
  163065. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163066. {
  163067. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163068. if (! (*dest->empty_output_buffer) (state->cinfo))
  163069. return FALSE;
  163070. /* After a successful buffer dump, must reset buffer pointers */
  163071. state->next_output_byte = dest->next_output_byte;
  163072. state->free_in_buffer = dest->free_in_buffer;
  163073. return TRUE;
  163074. }
  163075. /* Outputting bits to the file */
  163076. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163077. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163078. * in one call, and we never retain more than 7 bits in put_buffer
  163079. * between calls, so 24 bits are sufficient.
  163080. */
  163081. INLINE
  163082. LOCAL(boolean)
  163083. emit_bits (working_state * state, unsigned int code, int size)
  163084. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163085. {
  163086. /* This routine is heavily used, so it's worth coding tightly. */
  163087. register INT32 put_buffer = (INT32) code;
  163088. register int put_bits = state->cur.put_bits;
  163089. /* if size is 0, caller used an invalid Huffman table entry */
  163090. if (size == 0)
  163091. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163092. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163093. put_bits += size; /* new number of bits in buffer */
  163094. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163095. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163096. while (put_bits >= 8) {
  163097. int c = (int) ((put_buffer >> 16) & 0xFF);
  163098. emit_byte(state, c, return FALSE);
  163099. if (c == 0xFF) { /* need to stuff a zero byte? */
  163100. emit_byte(state, 0, return FALSE);
  163101. }
  163102. put_buffer <<= 8;
  163103. put_bits -= 8;
  163104. }
  163105. state->cur.put_buffer = put_buffer; /* update state variables */
  163106. state->cur.put_bits = put_bits;
  163107. return TRUE;
  163108. }
  163109. LOCAL(boolean)
  163110. flush_bits (working_state * state)
  163111. {
  163112. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163113. return FALSE;
  163114. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163115. state->cur.put_bits = 0;
  163116. return TRUE;
  163117. }
  163118. /* Encode a single block's worth of coefficients */
  163119. LOCAL(boolean)
  163120. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163121. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163122. {
  163123. register int temp, temp2;
  163124. register int nbits;
  163125. register int k, r, i;
  163126. /* Encode the DC coefficient difference per section F.1.2.1 */
  163127. temp = temp2 = block[0] - last_dc_val;
  163128. if (temp < 0) {
  163129. temp = -temp; /* temp is abs value of input */
  163130. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163131. /* This code assumes we are on a two's complement machine */
  163132. temp2--;
  163133. }
  163134. /* Find the number of bits needed for the magnitude of the coefficient */
  163135. nbits = 0;
  163136. while (temp) {
  163137. nbits++;
  163138. temp >>= 1;
  163139. }
  163140. /* Check for out-of-range coefficient values.
  163141. * Since we're encoding a difference, the range limit is twice as much.
  163142. */
  163143. if (nbits > MAX_COEF_BITS+1)
  163144. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163145. /* Emit the Huffman-coded symbol for the number of bits */
  163146. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163147. return FALSE;
  163148. /* Emit that number of bits of the value, if positive, */
  163149. /* or the complement of its magnitude, if negative. */
  163150. if (nbits) /* emit_bits rejects calls with size 0 */
  163151. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163152. return FALSE;
  163153. /* Encode the AC coefficients per section F.1.2.2 */
  163154. r = 0; /* r = run length of zeros */
  163155. for (k = 1; k < DCTSIZE2; k++) {
  163156. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163157. r++;
  163158. } else {
  163159. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163160. while (r > 15) {
  163161. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163162. return FALSE;
  163163. r -= 16;
  163164. }
  163165. temp2 = temp;
  163166. if (temp < 0) {
  163167. temp = -temp; /* temp is abs value of input */
  163168. /* This code assumes we are on a two's complement machine */
  163169. temp2--;
  163170. }
  163171. /* Find the number of bits needed for the magnitude of the coefficient */
  163172. nbits = 1; /* there must be at least one 1 bit */
  163173. while ((temp >>= 1))
  163174. nbits++;
  163175. /* Check for out-of-range coefficient values */
  163176. if (nbits > MAX_COEF_BITS)
  163177. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163178. /* Emit Huffman symbol for run length / number of bits */
  163179. i = (r << 4) + nbits;
  163180. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163181. return FALSE;
  163182. /* Emit that number of bits of the value, if positive, */
  163183. /* or the complement of its magnitude, if negative. */
  163184. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163185. return FALSE;
  163186. r = 0;
  163187. }
  163188. }
  163189. /* If the last coef(s) were zero, emit an end-of-block code */
  163190. if (r > 0)
  163191. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163192. return FALSE;
  163193. return TRUE;
  163194. }
  163195. /*
  163196. * Emit a restart marker & resynchronize predictions.
  163197. */
  163198. LOCAL(boolean)
  163199. emit_restart (working_state * state, int restart_num)
  163200. {
  163201. int ci;
  163202. if (! flush_bits(state))
  163203. return FALSE;
  163204. emit_byte(state, 0xFF, return FALSE);
  163205. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163206. /* Re-initialize DC predictions to 0 */
  163207. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163208. state->cur.last_dc_val[ci] = 0;
  163209. /* The restart counter is not updated until we successfully write the MCU. */
  163210. return TRUE;
  163211. }
  163212. /*
  163213. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163214. */
  163215. METHODDEF(boolean)
  163216. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163217. {
  163218. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163219. working_state state;
  163220. int blkn, ci;
  163221. jpeg_component_info * compptr;
  163222. /* Load up working state */
  163223. state.next_output_byte = cinfo->dest->next_output_byte;
  163224. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163225. ASSIGN_STATE(state.cur, entropy->saved);
  163226. state.cinfo = cinfo;
  163227. /* Emit restart marker if needed */
  163228. if (cinfo->restart_interval) {
  163229. if (entropy->restarts_to_go == 0)
  163230. if (! emit_restart(&state, entropy->next_restart_num))
  163231. return FALSE;
  163232. }
  163233. /* Encode the MCU data blocks */
  163234. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163235. ci = cinfo->MCU_membership[blkn];
  163236. compptr = cinfo->cur_comp_info[ci];
  163237. if (! encode_one_block(&state,
  163238. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163239. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163240. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163241. return FALSE;
  163242. /* Update last_dc_val */
  163243. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163244. }
  163245. /* Completed MCU, so update state */
  163246. cinfo->dest->next_output_byte = state.next_output_byte;
  163247. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163248. ASSIGN_STATE(entropy->saved, state.cur);
  163249. /* Update restart-interval state too */
  163250. if (cinfo->restart_interval) {
  163251. if (entropy->restarts_to_go == 0) {
  163252. entropy->restarts_to_go = cinfo->restart_interval;
  163253. entropy->next_restart_num++;
  163254. entropy->next_restart_num &= 7;
  163255. }
  163256. entropy->restarts_to_go--;
  163257. }
  163258. return TRUE;
  163259. }
  163260. /*
  163261. * Finish up at the end of a Huffman-compressed scan.
  163262. */
  163263. METHODDEF(void)
  163264. finish_pass_huff (j_compress_ptr cinfo)
  163265. {
  163266. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163267. working_state state;
  163268. /* Load up working state ... flush_bits needs it */
  163269. state.next_output_byte = cinfo->dest->next_output_byte;
  163270. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163271. ASSIGN_STATE(state.cur, entropy->saved);
  163272. state.cinfo = cinfo;
  163273. /* Flush out the last data */
  163274. if (! flush_bits(&state))
  163275. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163276. /* Update state */
  163277. cinfo->dest->next_output_byte = state.next_output_byte;
  163278. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163279. ASSIGN_STATE(entropy->saved, state.cur);
  163280. }
  163281. /*
  163282. * Huffman coding optimization.
  163283. *
  163284. * We first scan the supplied data and count the number of uses of each symbol
  163285. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163286. * Then we build a Huffman coding tree for the observed counts.
  163287. * Symbols which are not needed at all for the particular image are not
  163288. * assigned any code, which saves space in the DHT marker as well as in
  163289. * the compressed data.
  163290. */
  163291. #ifdef ENTROPY_OPT_SUPPORTED
  163292. /* Process a single block's worth of coefficients */
  163293. LOCAL(void)
  163294. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163295. long dc_counts[], long ac_counts[])
  163296. {
  163297. register int temp;
  163298. register int nbits;
  163299. register int k, r;
  163300. /* Encode the DC coefficient difference per section F.1.2.1 */
  163301. temp = block[0] - last_dc_val;
  163302. if (temp < 0)
  163303. temp = -temp;
  163304. /* Find the number of bits needed for the magnitude of the coefficient */
  163305. nbits = 0;
  163306. while (temp) {
  163307. nbits++;
  163308. temp >>= 1;
  163309. }
  163310. /* Check for out-of-range coefficient values.
  163311. * Since we're encoding a difference, the range limit is twice as much.
  163312. */
  163313. if (nbits > MAX_COEF_BITS+1)
  163314. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163315. /* Count the Huffman symbol for the number of bits */
  163316. dc_counts[nbits]++;
  163317. /* Encode the AC coefficients per section F.1.2.2 */
  163318. r = 0; /* r = run length of zeros */
  163319. for (k = 1; k < DCTSIZE2; k++) {
  163320. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163321. r++;
  163322. } else {
  163323. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163324. while (r > 15) {
  163325. ac_counts[0xF0]++;
  163326. r -= 16;
  163327. }
  163328. /* Find the number of bits needed for the magnitude of the coefficient */
  163329. if (temp < 0)
  163330. temp = -temp;
  163331. /* Find the number of bits needed for the magnitude of the coefficient */
  163332. nbits = 1; /* there must be at least one 1 bit */
  163333. while ((temp >>= 1))
  163334. nbits++;
  163335. /* Check for out-of-range coefficient values */
  163336. if (nbits > MAX_COEF_BITS)
  163337. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163338. /* Count Huffman symbol for run length / number of bits */
  163339. ac_counts[(r << 4) + nbits]++;
  163340. r = 0;
  163341. }
  163342. }
  163343. /* If the last coef(s) were zero, emit an end-of-block code */
  163344. if (r > 0)
  163345. ac_counts[0]++;
  163346. }
  163347. /*
  163348. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163349. * No data is actually output, so no suspension return is possible.
  163350. */
  163351. METHODDEF(boolean)
  163352. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163353. {
  163354. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163355. int blkn, ci;
  163356. jpeg_component_info * compptr;
  163357. /* Take care of restart intervals if needed */
  163358. if (cinfo->restart_interval) {
  163359. if (entropy->restarts_to_go == 0) {
  163360. /* Re-initialize DC predictions to 0 */
  163361. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163362. entropy->saved.last_dc_val[ci] = 0;
  163363. /* Update restart state */
  163364. entropy->restarts_to_go = cinfo->restart_interval;
  163365. }
  163366. entropy->restarts_to_go--;
  163367. }
  163368. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163369. ci = cinfo->MCU_membership[blkn];
  163370. compptr = cinfo->cur_comp_info[ci];
  163371. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163372. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163373. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163374. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163375. }
  163376. return TRUE;
  163377. }
  163378. /*
  163379. * Generate the best Huffman code table for the given counts, fill htbl.
  163380. * Note this is also used by jcphuff.c.
  163381. *
  163382. * The JPEG standard requires that no symbol be assigned a codeword of all
  163383. * one bits (so that padding bits added at the end of a compressed segment
  163384. * can't look like a valid code). Because of the canonical ordering of
  163385. * codewords, this just means that there must be an unused slot in the
  163386. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163387. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163388. * with count 1. In theory that's not optimal; giving it count zero but
  163389. * including it in the symbol set anyway should give a better Huffman code.
  163390. * But the theoretically better code actually seems to come out worse in
  163391. * practice, because it produces more all-ones bytes (which incur stuffed
  163392. * zero bytes in the final file). In any case the difference is tiny.
  163393. *
  163394. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163395. * If some symbols have a very small but nonzero probability, the Huffman tree
  163396. * must be adjusted to meet the code length restriction. We currently use
  163397. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163398. * optimal; it may not choose the best possible limited-length code. But
  163399. * typically only very-low-frequency symbols will be given less-than-optimal
  163400. * lengths, so the code is almost optimal. Experimental comparisons against
  163401. * an optimal limited-length-code algorithm indicate that the difference is
  163402. * microscopic --- usually less than a hundredth of a percent of total size.
  163403. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163404. */
  163405. GLOBAL(void)
  163406. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163407. {
  163408. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163409. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163410. int codesize[257]; /* codesize[k] = code length of symbol k */
  163411. int others[257]; /* next symbol in current branch of tree */
  163412. int c1, c2;
  163413. int p, i, j;
  163414. long v;
  163415. /* This algorithm is explained in section K.2 of the JPEG standard */
  163416. MEMZERO(bits, SIZEOF(bits));
  163417. MEMZERO(codesize, SIZEOF(codesize));
  163418. for (i = 0; i < 257; i++)
  163419. others[i] = -1; /* init links to empty */
  163420. freq[256] = 1; /* make sure 256 has a nonzero count */
  163421. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163422. * that no real symbol is given code-value of all ones, because 256
  163423. * will be placed last in the largest codeword category.
  163424. */
  163425. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163426. for (;;) {
  163427. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163428. /* In case of ties, take the larger symbol number */
  163429. c1 = -1;
  163430. v = 1000000000L;
  163431. for (i = 0; i <= 256; i++) {
  163432. if (freq[i] && freq[i] <= v) {
  163433. v = freq[i];
  163434. c1 = i;
  163435. }
  163436. }
  163437. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163438. /* In case of ties, take the larger symbol number */
  163439. c2 = -1;
  163440. v = 1000000000L;
  163441. for (i = 0; i <= 256; i++) {
  163442. if (freq[i] && freq[i] <= v && i != c1) {
  163443. v = freq[i];
  163444. c2 = i;
  163445. }
  163446. }
  163447. /* Done if we've merged everything into one frequency */
  163448. if (c2 < 0)
  163449. break;
  163450. /* Else merge the two counts/trees */
  163451. freq[c1] += freq[c2];
  163452. freq[c2] = 0;
  163453. /* Increment the codesize of everything in c1's tree branch */
  163454. codesize[c1]++;
  163455. while (others[c1] >= 0) {
  163456. c1 = others[c1];
  163457. codesize[c1]++;
  163458. }
  163459. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163460. /* Increment the codesize of everything in c2's tree branch */
  163461. codesize[c2]++;
  163462. while (others[c2] >= 0) {
  163463. c2 = others[c2];
  163464. codesize[c2]++;
  163465. }
  163466. }
  163467. /* Now count the number of symbols of each code length */
  163468. for (i = 0; i <= 256; i++) {
  163469. if (codesize[i]) {
  163470. /* The JPEG standard seems to think that this can't happen, */
  163471. /* but I'm paranoid... */
  163472. if (codesize[i] > MAX_CLEN)
  163473. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163474. bits[codesize[i]]++;
  163475. }
  163476. }
  163477. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163478. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163479. * Here is what the JPEG spec says about how this next bit works:
  163480. * Since symbols are paired for the longest Huffman code, the symbols are
  163481. * removed from this length category two at a time. The prefix for the pair
  163482. * (which is one bit shorter) is allocated to one of the pair; then,
  163483. * skipping the BITS entry for that prefix length, a code word from the next
  163484. * shortest nonzero BITS entry is converted into a prefix for two code words
  163485. * one bit longer.
  163486. */
  163487. for (i = MAX_CLEN; i > 16; i--) {
  163488. while (bits[i] > 0) {
  163489. j = i - 2; /* find length of new prefix to be used */
  163490. while (bits[j] == 0)
  163491. j--;
  163492. bits[i] -= 2; /* remove two symbols */
  163493. bits[i-1]++; /* one goes in this length */
  163494. bits[j+1] += 2; /* two new symbols in this length */
  163495. bits[j]--; /* symbol of this length is now a prefix */
  163496. }
  163497. }
  163498. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163499. while (bits[i] == 0) /* find largest codelength still in use */
  163500. i--;
  163501. bits[i]--;
  163502. /* Return final symbol counts (only for lengths 0..16) */
  163503. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163504. /* Return a list of the symbols sorted by code length */
  163505. /* It's not real clear to me why we don't need to consider the codelength
  163506. * changes made above, but the JPEG spec seems to think this works.
  163507. */
  163508. p = 0;
  163509. for (i = 1; i <= MAX_CLEN; i++) {
  163510. for (j = 0; j <= 255; j++) {
  163511. if (codesize[j] == i) {
  163512. htbl->huffval[p] = (UINT8) j;
  163513. p++;
  163514. }
  163515. }
  163516. }
  163517. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163518. htbl->sent_table = FALSE;
  163519. }
  163520. /*
  163521. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163522. */
  163523. METHODDEF(void)
  163524. finish_pass_gather (j_compress_ptr cinfo)
  163525. {
  163526. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163527. int ci, dctbl, actbl;
  163528. jpeg_component_info * compptr;
  163529. JHUFF_TBL **htblptr;
  163530. boolean did_dc[NUM_HUFF_TBLS];
  163531. boolean did_ac[NUM_HUFF_TBLS];
  163532. /* It's important not to apply jpeg_gen_optimal_table more than once
  163533. * per table, because it clobbers the input frequency counts!
  163534. */
  163535. MEMZERO(did_dc, SIZEOF(did_dc));
  163536. MEMZERO(did_ac, SIZEOF(did_ac));
  163537. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163538. compptr = cinfo->cur_comp_info[ci];
  163539. dctbl = compptr->dc_tbl_no;
  163540. actbl = compptr->ac_tbl_no;
  163541. if (! did_dc[dctbl]) {
  163542. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163543. if (*htblptr == NULL)
  163544. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163545. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163546. did_dc[dctbl] = TRUE;
  163547. }
  163548. if (! did_ac[actbl]) {
  163549. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163550. if (*htblptr == NULL)
  163551. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163552. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163553. did_ac[actbl] = TRUE;
  163554. }
  163555. }
  163556. }
  163557. #endif /* ENTROPY_OPT_SUPPORTED */
  163558. /*
  163559. * Module initialization routine for Huffman entropy encoding.
  163560. */
  163561. GLOBAL(void)
  163562. jinit_huff_encoder (j_compress_ptr cinfo)
  163563. {
  163564. huff_entropy_ptr entropy;
  163565. int i;
  163566. entropy = (huff_entropy_ptr)
  163567. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163568. SIZEOF(huff_entropy_encoder));
  163569. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163570. entropy->pub.start_pass = start_pass_huff;
  163571. /* Mark tables unallocated */
  163572. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163573. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163574. #ifdef ENTROPY_OPT_SUPPORTED
  163575. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163576. #endif
  163577. }
  163578. }
  163579. /*** End of inlined file: jchuff.c ***/
  163580. #undef emit_byte
  163581. /*** Start of inlined file: jcinit.c ***/
  163582. #define JPEG_INTERNALS
  163583. /*
  163584. * Master selection of compression modules.
  163585. * This is done once at the start of processing an image. We determine
  163586. * which modules will be used and give them appropriate initialization calls.
  163587. */
  163588. GLOBAL(void)
  163589. jinit_compress_master (j_compress_ptr cinfo)
  163590. {
  163591. /* Initialize master control (includes parameter checking/processing) */
  163592. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163593. /* Preprocessing */
  163594. if (! cinfo->raw_data_in) {
  163595. jinit_color_converter(cinfo);
  163596. jinit_downsampler(cinfo);
  163597. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163598. }
  163599. /* Forward DCT */
  163600. jinit_forward_dct(cinfo);
  163601. /* Entropy encoding: either Huffman or arithmetic coding. */
  163602. if (cinfo->arith_code) {
  163603. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163604. } else {
  163605. if (cinfo->progressive_mode) {
  163606. #ifdef C_PROGRESSIVE_SUPPORTED
  163607. jinit_phuff_encoder(cinfo);
  163608. #else
  163609. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163610. #endif
  163611. } else
  163612. jinit_huff_encoder(cinfo);
  163613. }
  163614. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163615. jinit_c_coef_controller(cinfo,
  163616. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163617. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163618. jinit_marker_writer(cinfo);
  163619. /* We can now tell the memory manager to allocate virtual arrays. */
  163620. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163621. /* Write the datastream header (SOI) immediately.
  163622. * Frame and scan headers are postponed till later.
  163623. * This lets application insert special markers after the SOI.
  163624. */
  163625. (*cinfo->marker->write_file_header) (cinfo);
  163626. }
  163627. /*** End of inlined file: jcinit.c ***/
  163628. /*** Start of inlined file: jcmainct.c ***/
  163629. #define JPEG_INTERNALS
  163630. /* Note: currently, there is no operating mode in which a full-image buffer
  163631. * is needed at this step. If there were, that mode could not be used with
  163632. * "raw data" input, since this module is bypassed in that case. However,
  163633. * we've left the code here for possible use in special applications.
  163634. */
  163635. #undef FULL_MAIN_BUFFER_SUPPORTED
  163636. /* Private buffer controller object */
  163637. typedef struct {
  163638. struct jpeg_c_main_controller pub; /* public fields */
  163639. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163640. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163641. boolean suspended; /* remember if we suspended output */
  163642. J_BUF_MODE pass_mode; /* current operating mode */
  163643. /* If using just a strip buffer, this points to the entire set of buffers
  163644. * (we allocate one for each component). In the full-image case, this
  163645. * points to the currently accessible strips of the virtual arrays.
  163646. */
  163647. JSAMPARRAY buffer[MAX_COMPONENTS];
  163648. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163649. /* If using full-image storage, this array holds pointers to virtual-array
  163650. * control blocks for each component. Unused if not full-image storage.
  163651. */
  163652. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163653. #endif
  163654. } my_main_controller;
  163655. typedef my_main_controller * my_main_ptr;
  163656. /* Forward declarations */
  163657. METHODDEF(void) process_data_simple_main
  163658. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163659. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163660. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163661. METHODDEF(void) process_data_buffer_main
  163662. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163663. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163664. #endif
  163665. /*
  163666. * Initialize for a processing pass.
  163667. */
  163668. METHODDEF(void)
  163669. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  163670. {
  163671. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163672. /* Do nothing in raw-data mode. */
  163673. if (cinfo->raw_data_in)
  163674. return;
  163675. main_->cur_iMCU_row = 0; /* initialize counters */
  163676. main_->rowgroup_ctr = 0;
  163677. main_->suspended = FALSE;
  163678. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  163679. switch (pass_mode) {
  163680. case JBUF_PASS_THRU:
  163681. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163682. if (main_->whole_image[0] != NULL)
  163683. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163684. #endif
  163685. main_->pub.process_data = process_data_simple_main;
  163686. break;
  163687. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163688. case JBUF_SAVE_SOURCE:
  163689. case JBUF_CRANK_DEST:
  163690. case JBUF_SAVE_AND_PASS:
  163691. if (main_->whole_image[0] == NULL)
  163692. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163693. main_->pub.process_data = process_data_buffer_main;
  163694. break;
  163695. #endif
  163696. default:
  163697. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163698. break;
  163699. }
  163700. }
  163701. /*
  163702. * Process some data.
  163703. * This routine handles the simple pass-through mode,
  163704. * where we have only a strip buffer.
  163705. */
  163706. METHODDEF(void)
  163707. process_data_simple_main (j_compress_ptr cinfo,
  163708. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163709. JDIMENSION in_rows_avail)
  163710. {
  163711. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  163712. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163713. /* Read input data if we haven't filled the main buffer yet */
  163714. if (main_->rowgroup_ctr < DCTSIZE)
  163715. (*cinfo->prep->pre_process_data) (cinfo,
  163716. input_buf, in_row_ctr, in_rows_avail,
  163717. main_->buffer, &main_->rowgroup_ctr,
  163718. (JDIMENSION) DCTSIZE);
  163719. /* If we don't have a full iMCU row buffered, return to application for
  163720. * more data. Note that preprocessor will always pad to fill the iMCU row
  163721. * at the bottom of the image.
  163722. */
  163723. if (main_->rowgroup_ctr != DCTSIZE)
  163724. return;
  163725. /* Send the completed row to the compressor */
  163726. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  163727. /* If compressor did not consume the whole row, then we must need to
  163728. * suspend processing and return to the application. In this situation
  163729. * we pretend we didn't yet consume the last input row; otherwise, if
  163730. * it happened to be the last row of the image, the application would
  163731. * think we were done.
  163732. */
  163733. if (! main_->suspended) {
  163734. (*in_row_ctr)--;
  163735. main_->suspended = TRUE;
  163736. }
  163737. return;
  163738. }
  163739. /* We did finish the row. Undo our little suspension hack if a previous
  163740. * call suspended; then mark the main buffer empty.
  163741. */
  163742. if (main_->suspended) {
  163743. (*in_row_ctr)++;
  163744. main_->suspended = FALSE;
  163745. }
  163746. main_->rowgroup_ctr = 0;
  163747. main_->cur_iMCU_row++;
  163748. }
  163749. }
  163750. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163751. /*
  163752. * Process some data.
  163753. * This routine handles all of the modes that use a full-size buffer.
  163754. */
  163755. METHODDEF(void)
  163756. process_data_buffer_main (j_compress_ptr cinfo,
  163757. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  163758. JDIMENSION in_rows_avail)
  163759. {
  163760. my_main_ptr main = (my_main_ptr) cinfo->main;
  163761. int ci;
  163762. jpeg_component_info *compptr;
  163763. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  163764. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  163765. /* Realign the virtual buffers if at the start of an iMCU row. */
  163766. if (main->rowgroup_ctr == 0) {
  163767. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163768. ci++, compptr++) {
  163769. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  163770. ((j_common_ptr) cinfo, main->whole_image[ci],
  163771. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  163772. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  163773. }
  163774. /* In a read pass, pretend we just read some source data. */
  163775. if (! writing) {
  163776. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  163777. main->rowgroup_ctr = DCTSIZE;
  163778. }
  163779. }
  163780. /* If a write pass, read input data until the current iMCU row is full. */
  163781. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  163782. if (writing) {
  163783. (*cinfo->prep->pre_process_data) (cinfo,
  163784. input_buf, in_row_ctr, in_rows_avail,
  163785. main->buffer, &main->rowgroup_ctr,
  163786. (JDIMENSION) DCTSIZE);
  163787. /* Return to application if we need more data to fill the iMCU row. */
  163788. if (main->rowgroup_ctr < DCTSIZE)
  163789. return;
  163790. }
  163791. /* Emit data, unless this is a sink-only pass. */
  163792. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  163793. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  163794. /* If compressor did not consume the whole row, then we must need to
  163795. * suspend processing and return to the application. In this situation
  163796. * we pretend we didn't yet consume the last input row; otherwise, if
  163797. * it happened to be the last row of the image, the application would
  163798. * think we were done.
  163799. */
  163800. if (! main->suspended) {
  163801. (*in_row_ctr)--;
  163802. main->suspended = TRUE;
  163803. }
  163804. return;
  163805. }
  163806. /* We did finish the row. Undo our little suspension hack if a previous
  163807. * call suspended; then mark the main buffer empty.
  163808. */
  163809. if (main->suspended) {
  163810. (*in_row_ctr)++;
  163811. main->suspended = FALSE;
  163812. }
  163813. }
  163814. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  163815. main->rowgroup_ctr = 0;
  163816. main->cur_iMCU_row++;
  163817. }
  163818. }
  163819. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  163820. /*
  163821. * Initialize main buffer controller.
  163822. */
  163823. GLOBAL(void)
  163824. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163825. {
  163826. my_main_ptr main_;
  163827. int ci;
  163828. jpeg_component_info *compptr;
  163829. main_ = (my_main_ptr)
  163830. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163831. SIZEOF(my_main_controller));
  163832. cinfo->main = (struct jpeg_c_main_controller *) main_;
  163833. main_->pub.start_pass = start_pass_main;
  163834. /* We don't need to create a buffer in raw-data mode. */
  163835. if (cinfo->raw_data_in)
  163836. return;
  163837. /* Create the buffer. It holds downsampled data, so each component
  163838. * may be of a different size.
  163839. */
  163840. if (need_full_buffer) {
  163841. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163842. /* Allocate a full-image virtual array for each component */
  163843. /* Note we pad the bottom to a multiple of the iMCU height */
  163844. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163845. ci++, compptr++) {
  163846. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  163847. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163848. compptr->width_in_blocks * DCTSIZE,
  163849. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163850. (long) compptr->v_samp_factor) * DCTSIZE,
  163851. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163852. }
  163853. #else
  163854. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163855. #endif
  163856. } else {
  163857. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163858. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  163859. #endif
  163860. /* Allocate a strip buffer for each component */
  163861. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163862. ci++, compptr++) {
  163863. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  163864. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163865. compptr->width_in_blocks * DCTSIZE,
  163866. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  163867. }
  163868. }
  163869. }
  163870. /*** End of inlined file: jcmainct.c ***/
  163871. /*** Start of inlined file: jcmarker.c ***/
  163872. #define JPEG_INTERNALS
  163873. /* Private state */
  163874. typedef struct {
  163875. struct jpeg_marker_writer pub; /* public fields */
  163876. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  163877. } my_marker_writer;
  163878. typedef my_marker_writer * my_marker_ptr;
  163879. /*
  163880. * Basic output routines.
  163881. *
  163882. * Note that we do not support suspension while writing a marker.
  163883. * Therefore, an application using suspension must ensure that there is
  163884. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  163885. * calling jpeg_start_compress, and enough space to write the trailing EOI
  163886. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  163887. * modes are not supported at all with suspension, so those two are the only
  163888. * points where markers will be written.
  163889. */
  163890. LOCAL(void)
  163891. emit_byte (j_compress_ptr cinfo, int val)
  163892. /* Emit a byte */
  163893. {
  163894. struct jpeg_destination_mgr * dest = cinfo->dest;
  163895. *(dest->next_output_byte)++ = (JOCTET) val;
  163896. if (--dest->free_in_buffer == 0) {
  163897. if (! (*dest->empty_output_buffer) (cinfo))
  163898. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163899. }
  163900. }
  163901. LOCAL(void)
  163902. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  163903. /* Emit a marker code */
  163904. {
  163905. emit_byte(cinfo, 0xFF);
  163906. emit_byte(cinfo, (int) mark);
  163907. }
  163908. LOCAL(void)
  163909. emit_2bytes (j_compress_ptr cinfo, int value)
  163910. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  163911. {
  163912. emit_byte(cinfo, (value >> 8) & 0xFF);
  163913. emit_byte(cinfo, value & 0xFF);
  163914. }
  163915. /*
  163916. * Routines to write specific marker types.
  163917. */
  163918. LOCAL(int)
  163919. emit_dqt (j_compress_ptr cinfo, int index)
  163920. /* Emit a DQT marker */
  163921. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  163922. {
  163923. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  163924. int prec;
  163925. int i;
  163926. if (qtbl == NULL)
  163927. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  163928. prec = 0;
  163929. for (i = 0; i < DCTSIZE2; i++) {
  163930. if (qtbl->quantval[i] > 255)
  163931. prec = 1;
  163932. }
  163933. if (! qtbl->sent_table) {
  163934. emit_marker(cinfo, M_DQT);
  163935. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  163936. emit_byte(cinfo, index + (prec<<4));
  163937. for (i = 0; i < DCTSIZE2; i++) {
  163938. /* The table entries must be emitted in zigzag order. */
  163939. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  163940. if (prec)
  163941. emit_byte(cinfo, (int) (qval >> 8));
  163942. emit_byte(cinfo, (int) (qval & 0xFF));
  163943. }
  163944. qtbl->sent_table = TRUE;
  163945. }
  163946. return prec;
  163947. }
  163948. LOCAL(void)
  163949. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  163950. /* Emit a DHT marker */
  163951. {
  163952. JHUFF_TBL * htbl;
  163953. int length, i;
  163954. if (is_ac) {
  163955. htbl = cinfo->ac_huff_tbl_ptrs[index];
  163956. index += 0x10; /* output index has AC bit set */
  163957. } else {
  163958. htbl = cinfo->dc_huff_tbl_ptrs[index];
  163959. }
  163960. if (htbl == NULL)
  163961. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  163962. if (! htbl->sent_table) {
  163963. emit_marker(cinfo, M_DHT);
  163964. length = 0;
  163965. for (i = 1; i <= 16; i++)
  163966. length += htbl->bits[i];
  163967. emit_2bytes(cinfo, length + 2 + 1 + 16);
  163968. emit_byte(cinfo, index);
  163969. for (i = 1; i <= 16; i++)
  163970. emit_byte(cinfo, htbl->bits[i]);
  163971. for (i = 0; i < length; i++)
  163972. emit_byte(cinfo, htbl->huffval[i]);
  163973. htbl->sent_table = TRUE;
  163974. }
  163975. }
  163976. LOCAL(void)
  163977. emit_dac (j_compress_ptr)
  163978. /* Emit a DAC marker */
  163979. /* Since the useful info is so small, we want to emit all the tables in */
  163980. /* one DAC marker. Therefore this routine does its own scan of the table. */
  163981. {
  163982. #ifdef C_ARITH_CODING_SUPPORTED
  163983. char dc_in_use[NUM_ARITH_TBLS];
  163984. char ac_in_use[NUM_ARITH_TBLS];
  163985. int length, i;
  163986. jpeg_component_info *compptr;
  163987. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163988. dc_in_use[i] = ac_in_use[i] = 0;
  163989. for (i = 0; i < cinfo->comps_in_scan; i++) {
  163990. compptr = cinfo->cur_comp_info[i];
  163991. dc_in_use[compptr->dc_tbl_no] = 1;
  163992. ac_in_use[compptr->ac_tbl_no] = 1;
  163993. }
  163994. length = 0;
  163995. for (i = 0; i < NUM_ARITH_TBLS; i++)
  163996. length += dc_in_use[i] + ac_in_use[i];
  163997. emit_marker(cinfo, M_DAC);
  163998. emit_2bytes(cinfo, length*2 + 2);
  163999. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164000. if (dc_in_use[i]) {
  164001. emit_byte(cinfo, i);
  164002. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164003. }
  164004. if (ac_in_use[i]) {
  164005. emit_byte(cinfo, i + 0x10);
  164006. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164007. }
  164008. }
  164009. #endif /* C_ARITH_CODING_SUPPORTED */
  164010. }
  164011. LOCAL(void)
  164012. emit_dri (j_compress_ptr cinfo)
  164013. /* Emit a DRI marker */
  164014. {
  164015. emit_marker(cinfo, M_DRI);
  164016. emit_2bytes(cinfo, 4); /* fixed length */
  164017. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164018. }
  164019. LOCAL(void)
  164020. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164021. /* Emit a SOF marker */
  164022. {
  164023. int ci;
  164024. jpeg_component_info *compptr;
  164025. emit_marker(cinfo, code);
  164026. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164027. /* Make sure image isn't bigger than SOF field can handle */
  164028. if ((long) cinfo->image_height > 65535L ||
  164029. (long) cinfo->image_width > 65535L)
  164030. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164031. emit_byte(cinfo, cinfo->data_precision);
  164032. emit_2bytes(cinfo, (int) cinfo->image_height);
  164033. emit_2bytes(cinfo, (int) cinfo->image_width);
  164034. emit_byte(cinfo, cinfo->num_components);
  164035. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164036. ci++, compptr++) {
  164037. emit_byte(cinfo, compptr->component_id);
  164038. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164039. emit_byte(cinfo, compptr->quant_tbl_no);
  164040. }
  164041. }
  164042. LOCAL(void)
  164043. emit_sos (j_compress_ptr cinfo)
  164044. /* Emit a SOS marker */
  164045. {
  164046. int i, td, ta;
  164047. jpeg_component_info *compptr;
  164048. emit_marker(cinfo, M_SOS);
  164049. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164050. emit_byte(cinfo, cinfo->comps_in_scan);
  164051. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164052. compptr = cinfo->cur_comp_info[i];
  164053. emit_byte(cinfo, compptr->component_id);
  164054. td = compptr->dc_tbl_no;
  164055. ta = compptr->ac_tbl_no;
  164056. if (cinfo->progressive_mode) {
  164057. /* Progressive mode: only DC or only AC tables are used in one scan;
  164058. * furthermore, Huffman coding of DC refinement uses no table at all.
  164059. * We emit 0 for unused field(s); this is recommended by the P&M text
  164060. * but does not seem to be specified in the standard.
  164061. */
  164062. if (cinfo->Ss == 0) {
  164063. ta = 0; /* DC scan */
  164064. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164065. td = 0; /* no DC table either */
  164066. } else {
  164067. td = 0; /* AC scan */
  164068. }
  164069. }
  164070. emit_byte(cinfo, (td << 4) + ta);
  164071. }
  164072. emit_byte(cinfo, cinfo->Ss);
  164073. emit_byte(cinfo, cinfo->Se);
  164074. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164075. }
  164076. LOCAL(void)
  164077. emit_jfif_app0 (j_compress_ptr cinfo)
  164078. /* Emit a JFIF-compliant APP0 marker */
  164079. {
  164080. /*
  164081. * Length of APP0 block (2 bytes)
  164082. * Block ID (4 bytes - ASCII "JFIF")
  164083. * Zero byte (1 byte to terminate the ID string)
  164084. * Version Major, Minor (2 bytes - major first)
  164085. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164086. * Xdpu (2 bytes - dots per unit horizontal)
  164087. * Ydpu (2 bytes - dots per unit vertical)
  164088. * Thumbnail X size (1 byte)
  164089. * Thumbnail Y size (1 byte)
  164090. */
  164091. emit_marker(cinfo, M_APP0);
  164092. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164093. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164094. emit_byte(cinfo, 0x46);
  164095. emit_byte(cinfo, 0x49);
  164096. emit_byte(cinfo, 0x46);
  164097. emit_byte(cinfo, 0);
  164098. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164099. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164100. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164101. emit_2bytes(cinfo, (int) cinfo->X_density);
  164102. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164103. emit_byte(cinfo, 0); /* No thumbnail image */
  164104. emit_byte(cinfo, 0);
  164105. }
  164106. LOCAL(void)
  164107. emit_adobe_app14 (j_compress_ptr cinfo)
  164108. /* Emit an Adobe APP14 marker */
  164109. {
  164110. /*
  164111. * Length of APP14 block (2 bytes)
  164112. * Block ID (5 bytes - ASCII "Adobe")
  164113. * Version Number (2 bytes - currently 100)
  164114. * Flags0 (2 bytes - currently 0)
  164115. * Flags1 (2 bytes - currently 0)
  164116. * Color transform (1 byte)
  164117. *
  164118. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164119. * now in circulation seem to use Version = 100, so that's what we write.
  164120. *
  164121. * We write the color transform byte as 1 if the JPEG color space is
  164122. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164123. * whether the encoder performed a transformation, which is pretty useless.
  164124. */
  164125. emit_marker(cinfo, M_APP14);
  164126. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164127. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164128. emit_byte(cinfo, 0x64);
  164129. emit_byte(cinfo, 0x6F);
  164130. emit_byte(cinfo, 0x62);
  164131. emit_byte(cinfo, 0x65);
  164132. emit_2bytes(cinfo, 100); /* Version */
  164133. emit_2bytes(cinfo, 0); /* Flags0 */
  164134. emit_2bytes(cinfo, 0); /* Flags1 */
  164135. switch (cinfo->jpeg_color_space) {
  164136. case JCS_YCbCr:
  164137. emit_byte(cinfo, 1); /* Color transform = 1 */
  164138. break;
  164139. case JCS_YCCK:
  164140. emit_byte(cinfo, 2); /* Color transform = 2 */
  164141. break;
  164142. default:
  164143. emit_byte(cinfo, 0); /* Color transform = 0 */
  164144. break;
  164145. }
  164146. }
  164147. /*
  164148. * These routines allow writing an arbitrary marker with parameters.
  164149. * The only intended use is to emit COM or APPn markers after calling
  164150. * write_file_header and before calling write_frame_header.
  164151. * Other uses are not guaranteed to produce desirable results.
  164152. * Counting the parameter bytes properly is the caller's responsibility.
  164153. */
  164154. METHODDEF(void)
  164155. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164156. /* Emit an arbitrary marker header */
  164157. {
  164158. if (datalen > (unsigned int) 65533) /* safety check */
  164159. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164160. emit_marker(cinfo, (JPEG_MARKER) marker);
  164161. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164162. }
  164163. METHODDEF(void)
  164164. write_marker_byte (j_compress_ptr cinfo, int val)
  164165. /* Emit one byte of marker parameters following write_marker_header */
  164166. {
  164167. emit_byte(cinfo, val);
  164168. }
  164169. /*
  164170. * Write datastream header.
  164171. * This consists of an SOI and optional APPn markers.
  164172. * We recommend use of the JFIF marker, but not the Adobe marker,
  164173. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164174. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164175. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164176. * Note that an application can write additional header markers after
  164177. * jpeg_start_compress returns.
  164178. */
  164179. METHODDEF(void)
  164180. write_file_header (j_compress_ptr cinfo)
  164181. {
  164182. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164183. emit_marker(cinfo, M_SOI); /* first the SOI */
  164184. /* SOI is defined to reset restart interval to 0 */
  164185. marker->last_restart_interval = 0;
  164186. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164187. emit_jfif_app0(cinfo);
  164188. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164189. emit_adobe_app14(cinfo);
  164190. }
  164191. /*
  164192. * Write frame header.
  164193. * This consists of DQT and SOFn markers.
  164194. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164195. * This avoids compatibility problems with incorrect implementations that
  164196. * try to error-check the quant table numbers as soon as they see the SOF.
  164197. */
  164198. METHODDEF(void)
  164199. write_frame_header (j_compress_ptr cinfo)
  164200. {
  164201. int ci, prec;
  164202. boolean is_baseline;
  164203. jpeg_component_info *compptr;
  164204. /* Emit DQT for each quantization table.
  164205. * Note that emit_dqt() suppresses any duplicate tables.
  164206. */
  164207. prec = 0;
  164208. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164209. ci++, compptr++) {
  164210. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164211. }
  164212. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164213. /* Check for a non-baseline specification.
  164214. * Note we assume that Huffman table numbers won't be changed later.
  164215. */
  164216. if (cinfo->arith_code || cinfo->progressive_mode ||
  164217. cinfo->data_precision != 8) {
  164218. is_baseline = FALSE;
  164219. } else {
  164220. is_baseline = TRUE;
  164221. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164222. ci++, compptr++) {
  164223. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164224. is_baseline = FALSE;
  164225. }
  164226. if (prec && is_baseline) {
  164227. is_baseline = FALSE;
  164228. /* If it's baseline except for quantizer size, warn the user */
  164229. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164230. }
  164231. }
  164232. /* Emit the proper SOF marker */
  164233. if (cinfo->arith_code) {
  164234. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164235. } else {
  164236. if (cinfo->progressive_mode)
  164237. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164238. else if (is_baseline)
  164239. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164240. else
  164241. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164242. }
  164243. }
  164244. /*
  164245. * Write scan header.
  164246. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164247. * Compressed data will be written following the SOS.
  164248. */
  164249. METHODDEF(void)
  164250. write_scan_header (j_compress_ptr cinfo)
  164251. {
  164252. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164253. int i;
  164254. jpeg_component_info *compptr;
  164255. if (cinfo->arith_code) {
  164256. /* Emit arith conditioning info. We may have some duplication
  164257. * if the file has multiple scans, but it's so small it's hardly
  164258. * worth worrying about.
  164259. */
  164260. emit_dac(cinfo);
  164261. } else {
  164262. /* Emit Huffman tables.
  164263. * Note that emit_dht() suppresses any duplicate tables.
  164264. */
  164265. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164266. compptr = cinfo->cur_comp_info[i];
  164267. if (cinfo->progressive_mode) {
  164268. /* Progressive mode: only DC or only AC tables are used in one scan */
  164269. if (cinfo->Ss == 0) {
  164270. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164271. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164272. } else {
  164273. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164274. }
  164275. } else {
  164276. /* Sequential mode: need both DC and AC tables */
  164277. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164278. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164279. }
  164280. }
  164281. }
  164282. /* Emit DRI if required --- note that DRI value could change for each scan.
  164283. * We avoid wasting space with unnecessary DRIs, however.
  164284. */
  164285. if (cinfo->restart_interval != marker->last_restart_interval) {
  164286. emit_dri(cinfo);
  164287. marker->last_restart_interval = cinfo->restart_interval;
  164288. }
  164289. emit_sos(cinfo);
  164290. }
  164291. /*
  164292. * Write datastream trailer.
  164293. */
  164294. METHODDEF(void)
  164295. write_file_trailer (j_compress_ptr cinfo)
  164296. {
  164297. emit_marker(cinfo, M_EOI);
  164298. }
  164299. /*
  164300. * Write an abbreviated table-specification datastream.
  164301. * This consists of SOI, DQT and DHT tables, and EOI.
  164302. * Any table that is defined and not marked sent_table = TRUE will be
  164303. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164304. */
  164305. METHODDEF(void)
  164306. write_tables_only (j_compress_ptr cinfo)
  164307. {
  164308. int i;
  164309. emit_marker(cinfo, M_SOI);
  164310. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164311. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164312. (void) emit_dqt(cinfo, i);
  164313. }
  164314. if (! cinfo->arith_code) {
  164315. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164316. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164317. emit_dht(cinfo, i, FALSE);
  164318. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164319. emit_dht(cinfo, i, TRUE);
  164320. }
  164321. }
  164322. emit_marker(cinfo, M_EOI);
  164323. }
  164324. /*
  164325. * Initialize the marker writer module.
  164326. */
  164327. GLOBAL(void)
  164328. jinit_marker_writer (j_compress_ptr cinfo)
  164329. {
  164330. my_marker_ptr marker;
  164331. /* Create the subobject */
  164332. marker = (my_marker_ptr)
  164333. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164334. SIZEOF(my_marker_writer));
  164335. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164336. /* Initialize method pointers */
  164337. marker->pub.write_file_header = write_file_header;
  164338. marker->pub.write_frame_header = write_frame_header;
  164339. marker->pub.write_scan_header = write_scan_header;
  164340. marker->pub.write_file_trailer = write_file_trailer;
  164341. marker->pub.write_tables_only = write_tables_only;
  164342. marker->pub.write_marker_header = write_marker_header;
  164343. marker->pub.write_marker_byte = write_marker_byte;
  164344. /* Initialize private state */
  164345. marker->last_restart_interval = 0;
  164346. }
  164347. /*** End of inlined file: jcmarker.c ***/
  164348. /*** Start of inlined file: jcmaster.c ***/
  164349. #define JPEG_INTERNALS
  164350. /* Private state */
  164351. typedef enum {
  164352. main_pass, /* input data, also do first output step */
  164353. huff_opt_pass, /* Huffman code optimization pass */
  164354. output_pass /* data output pass */
  164355. } c_pass_type;
  164356. typedef struct {
  164357. struct jpeg_comp_master pub; /* public fields */
  164358. c_pass_type pass_type; /* the type of the current pass */
  164359. int pass_number; /* # of passes completed */
  164360. int total_passes; /* total # of passes needed */
  164361. int scan_number; /* current index in scan_info[] */
  164362. } my_comp_master;
  164363. typedef my_comp_master * my_master_ptr;
  164364. /*
  164365. * Support routines that do various essential calculations.
  164366. */
  164367. LOCAL(void)
  164368. initial_setup (j_compress_ptr cinfo)
  164369. /* Do computations that are needed before master selection phase */
  164370. {
  164371. int ci;
  164372. jpeg_component_info *compptr;
  164373. long samplesperrow;
  164374. JDIMENSION jd_samplesperrow;
  164375. /* Sanity check on image dimensions */
  164376. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164377. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164378. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164379. /* Make sure image isn't bigger than I can handle */
  164380. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164381. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164382. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164383. /* Width of an input scanline must be representable as JDIMENSION. */
  164384. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164385. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164386. if ((long) jd_samplesperrow != samplesperrow)
  164387. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164388. /* For now, precision must match compiled-in value... */
  164389. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164390. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164391. /* Check that number of components won't exceed internal array sizes */
  164392. if (cinfo->num_components > MAX_COMPONENTS)
  164393. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164394. MAX_COMPONENTS);
  164395. /* Compute maximum sampling factors; check factor validity */
  164396. cinfo->max_h_samp_factor = 1;
  164397. cinfo->max_v_samp_factor = 1;
  164398. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164399. ci++, compptr++) {
  164400. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164401. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164402. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164403. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164404. compptr->h_samp_factor);
  164405. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164406. compptr->v_samp_factor);
  164407. }
  164408. /* Compute dimensions of components */
  164409. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164410. ci++, compptr++) {
  164411. /* Fill in the correct component_index value; don't rely on application */
  164412. compptr->component_index = ci;
  164413. /* For compression, we never do DCT scaling. */
  164414. compptr->DCT_scaled_size = DCTSIZE;
  164415. /* Size in DCT blocks */
  164416. compptr->width_in_blocks = (JDIMENSION)
  164417. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164418. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164419. compptr->height_in_blocks = (JDIMENSION)
  164420. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164421. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164422. /* Size in samples */
  164423. compptr->downsampled_width = (JDIMENSION)
  164424. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164425. (long) cinfo->max_h_samp_factor);
  164426. compptr->downsampled_height = (JDIMENSION)
  164427. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164428. (long) cinfo->max_v_samp_factor);
  164429. /* Mark component needed (this flag isn't actually used for compression) */
  164430. compptr->component_needed = TRUE;
  164431. }
  164432. /* Compute number of fully interleaved MCU rows (number of times that
  164433. * main controller will call coefficient controller).
  164434. */
  164435. cinfo->total_iMCU_rows = (JDIMENSION)
  164436. jdiv_round_up((long) cinfo->image_height,
  164437. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164438. }
  164439. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164440. LOCAL(void)
  164441. validate_script (j_compress_ptr cinfo)
  164442. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164443. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164444. */
  164445. {
  164446. const jpeg_scan_info * scanptr;
  164447. int scanno, ncomps, ci, coefi, thisi;
  164448. int Ss, Se, Ah, Al;
  164449. boolean component_sent[MAX_COMPONENTS];
  164450. #ifdef C_PROGRESSIVE_SUPPORTED
  164451. int * last_bitpos_ptr;
  164452. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164453. /* -1 until that coefficient has been seen; then last Al for it */
  164454. #endif
  164455. if (cinfo->num_scans <= 0)
  164456. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164457. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164458. * for progressive JPEG, no scan can have this.
  164459. */
  164460. scanptr = cinfo->scan_info;
  164461. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164462. #ifdef C_PROGRESSIVE_SUPPORTED
  164463. cinfo->progressive_mode = TRUE;
  164464. last_bitpos_ptr = & last_bitpos[0][0];
  164465. for (ci = 0; ci < cinfo->num_components; ci++)
  164466. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164467. *last_bitpos_ptr++ = -1;
  164468. #else
  164469. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164470. #endif
  164471. } else {
  164472. cinfo->progressive_mode = FALSE;
  164473. for (ci = 0; ci < cinfo->num_components; ci++)
  164474. component_sent[ci] = FALSE;
  164475. }
  164476. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164477. /* Validate component indexes */
  164478. ncomps = scanptr->comps_in_scan;
  164479. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164480. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164481. for (ci = 0; ci < ncomps; ci++) {
  164482. thisi = scanptr->component_index[ci];
  164483. if (thisi < 0 || thisi >= cinfo->num_components)
  164484. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164485. /* Components must appear in SOF order within each scan */
  164486. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164487. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164488. }
  164489. /* Validate progression parameters */
  164490. Ss = scanptr->Ss;
  164491. Se = scanptr->Se;
  164492. Ah = scanptr->Ah;
  164493. Al = scanptr->Al;
  164494. if (cinfo->progressive_mode) {
  164495. #ifdef C_PROGRESSIVE_SUPPORTED
  164496. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164497. * seems wrong: the upper bound ought to depend on data precision.
  164498. * Perhaps they really meant 0..N+1 for N-bit precision.
  164499. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164500. * out-of-range reconstructed DC values during the first DC scan,
  164501. * which might cause problems for some decoders.
  164502. */
  164503. #if BITS_IN_JSAMPLE == 8
  164504. #define MAX_AH_AL 10
  164505. #else
  164506. #define MAX_AH_AL 13
  164507. #endif
  164508. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164509. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164510. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164511. if (Ss == 0) {
  164512. if (Se != 0) /* DC and AC together not OK */
  164513. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164514. } else {
  164515. if (ncomps != 1) /* AC scans must be for only one component */
  164516. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164517. }
  164518. for (ci = 0; ci < ncomps; ci++) {
  164519. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164520. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164521. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164522. for (coefi = Ss; coefi <= Se; coefi++) {
  164523. if (last_bitpos_ptr[coefi] < 0) {
  164524. /* first scan of this coefficient */
  164525. if (Ah != 0)
  164526. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164527. } else {
  164528. /* not first scan */
  164529. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164530. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164531. }
  164532. last_bitpos_ptr[coefi] = Al;
  164533. }
  164534. }
  164535. #endif
  164536. } else {
  164537. /* For sequential JPEG, all progression parameters must be these: */
  164538. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164539. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164540. /* Make sure components are not sent twice */
  164541. for (ci = 0; ci < ncomps; ci++) {
  164542. thisi = scanptr->component_index[ci];
  164543. if (component_sent[thisi])
  164544. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164545. component_sent[thisi] = TRUE;
  164546. }
  164547. }
  164548. }
  164549. /* Now verify that everything got sent. */
  164550. if (cinfo->progressive_mode) {
  164551. #ifdef C_PROGRESSIVE_SUPPORTED
  164552. /* For progressive mode, we only check that at least some DC data
  164553. * got sent for each component; the spec does not require that all bits
  164554. * of all coefficients be transmitted. Would it be wiser to enforce
  164555. * transmission of all coefficient bits??
  164556. */
  164557. for (ci = 0; ci < cinfo->num_components; ci++) {
  164558. if (last_bitpos[ci][0] < 0)
  164559. ERREXIT(cinfo, JERR_MISSING_DATA);
  164560. }
  164561. #endif
  164562. } else {
  164563. for (ci = 0; ci < cinfo->num_components; ci++) {
  164564. if (! component_sent[ci])
  164565. ERREXIT(cinfo, JERR_MISSING_DATA);
  164566. }
  164567. }
  164568. }
  164569. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164570. LOCAL(void)
  164571. select_scan_parameters (j_compress_ptr cinfo)
  164572. /* Set up the scan parameters for the current scan */
  164573. {
  164574. int ci;
  164575. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164576. if (cinfo->scan_info != NULL) {
  164577. /* Prepare for current scan --- the script is already validated */
  164578. my_master_ptr master = (my_master_ptr) cinfo->master;
  164579. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164580. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164581. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164582. cinfo->cur_comp_info[ci] =
  164583. &cinfo->comp_info[scanptr->component_index[ci]];
  164584. }
  164585. cinfo->Ss = scanptr->Ss;
  164586. cinfo->Se = scanptr->Se;
  164587. cinfo->Ah = scanptr->Ah;
  164588. cinfo->Al = scanptr->Al;
  164589. }
  164590. else
  164591. #endif
  164592. {
  164593. /* Prepare for single sequential-JPEG scan containing all components */
  164594. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164595. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164596. MAX_COMPS_IN_SCAN);
  164597. cinfo->comps_in_scan = cinfo->num_components;
  164598. for (ci = 0; ci < cinfo->num_components; ci++) {
  164599. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164600. }
  164601. cinfo->Ss = 0;
  164602. cinfo->Se = DCTSIZE2-1;
  164603. cinfo->Ah = 0;
  164604. cinfo->Al = 0;
  164605. }
  164606. }
  164607. LOCAL(void)
  164608. per_scan_setup (j_compress_ptr cinfo)
  164609. /* Do computations that are needed before processing a JPEG scan */
  164610. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164611. {
  164612. int ci, mcublks, tmp;
  164613. jpeg_component_info *compptr;
  164614. if (cinfo->comps_in_scan == 1) {
  164615. /* Noninterleaved (single-component) scan */
  164616. compptr = cinfo->cur_comp_info[0];
  164617. /* Overall image size in MCUs */
  164618. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164619. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164620. /* For noninterleaved scan, always one block per MCU */
  164621. compptr->MCU_width = 1;
  164622. compptr->MCU_height = 1;
  164623. compptr->MCU_blocks = 1;
  164624. compptr->MCU_sample_width = DCTSIZE;
  164625. compptr->last_col_width = 1;
  164626. /* For noninterleaved scans, it is convenient to define last_row_height
  164627. * as the number of block rows present in the last iMCU row.
  164628. */
  164629. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164630. if (tmp == 0) tmp = compptr->v_samp_factor;
  164631. compptr->last_row_height = tmp;
  164632. /* Prepare array describing MCU composition */
  164633. cinfo->blocks_in_MCU = 1;
  164634. cinfo->MCU_membership[0] = 0;
  164635. } else {
  164636. /* Interleaved (multi-component) scan */
  164637. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164638. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164639. MAX_COMPS_IN_SCAN);
  164640. /* Overall image size in MCUs */
  164641. cinfo->MCUs_per_row = (JDIMENSION)
  164642. jdiv_round_up((long) cinfo->image_width,
  164643. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164644. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164645. jdiv_round_up((long) cinfo->image_height,
  164646. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164647. cinfo->blocks_in_MCU = 0;
  164648. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164649. compptr = cinfo->cur_comp_info[ci];
  164650. /* Sampling factors give # of blocks of component in each MCU */
  164651. compptr->MCU_width = compptr->h_samp_factor;
  164652. compptr->MCU_height = compptr->v_samp_factor;
  164653. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164654. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164655. /* Figure number of non-dummy blocks in last MCU column & row */
  164656. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164657. if (tmp == 0) tmp = compptr->MCU_width;
  164658. compptr->last_col_width = tmp;
  164659. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164660. if (tmp == 0) tmp = compptr->MCU_height;
  164661. compptr->last_row_height = tmp;
  164662. /* Prepare array describing MCU composition */
  164663. mcublks = compptr->MCU_blocks;
  164664. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  164665. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  164666. while (mcublks-- > 0) {
  164667. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  164668. }
  164669. }
  164670. }
  164671. /* Convert restart specified in rows to actual MCU count. */
  164672. /* Note that count must fit in 16 bits, so we provide limiting. */
  164673. if (cinfo->restart_in_rows > 0) {
  164674. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  164675. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  164676. }
  164677. }
  164678. /*
  164679. * Per-pass setup.
  164680. * This is called at the beginning of each pass. We determine which modules
  164681. * will be active during this pass and give them appropriate start_pass calls.
  164682. * We also set is_last_pass to indicate whether any more passes will be
  164683. * required.
  164684. */
  164685. METHODDEF(void)
  164686. prepare_for_pass (j_compress_ptr cinfo)
  164687. {
  164688. my_master_ptr master = (my_master_ptr) cinfo->master;
  164689. switch (master->pass_type) {
  164690. case main_pass:
  164691. /* Initial pass: will collect input data, and do either Huffman
  164692. * optimization or data output for the first scan.
  164693. */
  164694. select_scan_parameters(cinfo);
  164695. per_scan_setup(cinfo);
  164696. if (! cinfo->raw_data_in) {
  164697. (*cinfo->cconvert->start_pass) (cinfo);
  164698. (*cinfo->downsample->start_pass) (cinfo);
  164699. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  164700. }
  164701. (*cinfo->fdct->start_pass) (cinfo);
  164702. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  164703. (*cinfo->coef->start_pass) (cinfo,
  164704. (master->total_passes > 1 ?
  164705. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  164706. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  164707. if (cinfo->optimize_coding) {
  164708. /* No immediate data output; postpone writing frame/scan headers */
  164709. master->pub.call_pass_startup = FALSE;
  164710. } else {
  164711. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  164712. master->pub.call_pass_startup = TRUE;
  164713. }
  164714. break;
  164715. #ifdef ENTROPY_OPT_SUPPORTED
  164716. case huff_opt_pass:
  164717. /* Do Huffman optimization for a scan after the first one. */
  164718. select_scan_parameters(cinfo);
  164719. per_scan_setup(cinfo);
  164720. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  164721. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  164722. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164723. master->pub.call_pass_startup = FALSE;
  164724. break;
  164725. }
  164726. /* Special case: Huffman DC refinement scans need no Huffman table
  164727. * and therefore we can skip the optimization pass for them.
  164728. */
  164729. master->pass_type = output_pass;
  164730. master->pass_number++;
  164731. /*FALLTHROUGH*/
  164732. #endif
  164733. case output_pass:
  164734. /* Do a data-output pass. */
  164735. /* We need not repeat per-scan setup if prior optimization pass did it. */
  164736. if (! cinfo->optimize_coding) {
  164737. select_scan_parameters(cinfo);
  164738. per_scan_setup(cinfo);
  164739. }
  164740. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  164741. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  164742. /* We emit frame/scan headers now */
  164743. if (master->scan_number == 0)
  164744. (*cinfo->marker->write_frame_header) (cinfo);
  164745. (*cinfo->marker->write_scan_header) (cinfo);
  164746. master->pub.call_pass_startup = FALSE;
  164747. break;
  164748. default:
  164749. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164750. }
  164751. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  164752. /* Set up progress monitor's pass info if present */
  164753. if (cinfo->progress != NULL) {
  164754. cinfo->progress->completed_passes = master->pass_number;
  164755. cinfo->progress->total_passes = master->total_passes;
  164756. }
  164757. }
  164758. /*
  164759. * Special start-of-pass hook.
  164760. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  164761. * In single-pass processing, we need this hook because we don't want to
  164762. * write frame/scan headers during jpeg_start_compress; we want to let the
  164763. * application write COM markers etc. between jpeg_start_compress and the
  164764. * jpeg_write_scanlines loop.
  164765. * In multi-pass processing, this routine is not used.
  164766. */
  164767. METHODDEF(void)
  164768. pass_startup (j_compress_ptr cinfo)
  164769. {
  164770. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  164771. (*cinfo->marker->write_frame_header) (cinfo);
  164772. (*cinfo->marker->write_scan_header) (cinfo);
  164773. }
  164774. /*
  164775. * Finish up at end of pass.
  164776. */
  164777. METHODDEF(void)
  164778. finish_pass_master (j_compress_ptr cinfo)
  164779. {
  164780. my_master_ptr master = (my_master_ptr) cinfo->master;
  164781. /* The entropy coder always needs an end-of-pass call,
  164782. * either to analyze statistics or to flush its output buffer.
  164783. */
  164784. (*cinfo->entropy->finish_pass) (cinfo);
  164785. /* Update state for next pass */
  164786. switch (master->pass_type) {
  164787. case main_pass:
  164788. /* next pass is either output of scan 0 (after optimization)
  164789. * or output of scan 1 (if no optimization).
  164790. */
  164791. master->pass_type = output_pass;
  164792. if (! cinfo->optimize_coding)
  164793. master->scan_number++;
  164794. break;
  164795. case huff_opt_pass:
  164796. /* next pass is always output of current scan */
  164797. master->pass_type = output_pass;
  164798. break;
  164799. case output_pass:
  164800. /* next pass is either optimization or output of next scan */
  164801. if (cinfo->optimize_coding)
  164802. master->pass_type = huff_opt_pass;
  164803. master->scan_number++;
  164804. break;
  164805. }
  164806. master->pass_number++;
  164807. }
  164808. /*
  164809. * Initialize master compression control.
  164810. */
  164811. GLOBAL(void)
  164812. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  164813. {
  164814. my_master_ptr master;
  164815. master = (my_master_ptr)
  164816. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164817. SIZEOF(my_comp_master));
  164818. cinfo->master = (struct jpeg_comp_master *) master;
  164819. master->pub.prepare_for_pass = prepare_for_pass;
  164820. master->pub.pass_startup = pass_startup;
  164821. master->pub.finish_pass = finish_pass_master;
  164822. master->pub.is_last_pass = FALSE;
  164823. /* Validate parameters, determine derived values */
  164824. initial_setup(cinfo);
  164825. if (cinfo->scan_info != NULL) {
  164826. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164827. validate_script(cinfo);
  164828. #else
  164829. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164830. #endif
  164831. } else {
  164832. cinfo->progressive_mode = FALSE;
  164833. cinfo->num_scans = 1;
  164834. }
  164835. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  164836. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  164837. /* Initialize my private state */
  164838. if (transcode_only) {
  164839. /* no main pass in transcoding */
  164840. if (cinfo->optimize_coding)
  164841. master->pass_type = huff_opt_pass;
  164842. else
  164843. master->pass_type = output_pass;
  164844. } else {
  164845. /* for normal compression, first pass is always this type: */
  164846. master->pass_type = main_pass;
  164847. }
  164848. master->scan_number = 0;
  164849. master->pass_number = 0;
  164850. if (cinfo->optimize_coding)
  164851. master->total_passes = cinfo->num_scans * 2;
  164852. else
  164853. master->total_passes = cinfo->num_scans;
  164854. }
  164855. /*** End of inlined file: jcmaster.c ***/
  164856. /*** Start of inlined file: jcomapi.c ***/
  164857. #define JPEG_INTERNALS
  164858. /*
  164859. * Abort processing of a JPEG compression or decompression operation,
  164860. * but don't destroy the object itself.
  164861. *
  164862. * For this, we merely clean up all the nonpermanent memory pools.
  164863. * Note that temp files (virtual arrays) are not allowed to belong to
  164864. * the permanent pool, so we will be able to close all temp files here.
  164865. * Closing a data source or destination, if necessary, is the application's
  164866. * responsibility.
  164867. */
  164868. GLOBAL(void)
  164869. jpeg_abort (j_common_ptr cinfo)
  164870. {
  164871. int pool;
  164872. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  164873. if (cinfo->mem == NULL)
  164874. return;
  164875. /* Releasing pools in reverse order might help avoid fragmentation
  164876. * with some (brain-damaged) malloc libraries.
  164877. */
  164878. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  164879. (*cinfo->mem->free_pool) (cinfo, pool);
  164880. }
  164881. /* Reset overall state for possible reuse of object */
  164882. if (cinfo->is_decompressor) {
  164883. cinfo->global_state = DSTATE_START;
  164884. /* Try to keep application from accessing now-deleted marker list.
  164885. * A bit kludgy to do it here, but this is the most central place.
  164886. */
  164887. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  164888. } else {
  164889. cinfo->global_state = CSTATE_START;
  164890. }
  164891. }
  164892. /*
  164893. * Destruction of a JPEG object.
  164894. *
  164895. * Everything gets deallocated except the master jpeg_compress_struct itself
  164896. * and the error manager struct. Both of these are supplied by the application
  164897. * and must be freed, if necessary, by the application. (Often they are on
  164898. * the stack and so don't need to be freed anyway.)
  164899. * Closing a data source or destination, if necessary, is the application's
  164900. * responsibility.
  164901. */
  164902. GLOBAL(void)
  164903. jpeg_destroy (j_common_ptr cinfo)
  164904. {
  164905. /* We need only tell the memory manager to release everything. */
  164906. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  164907. if (cinfo->mem != NULL)
  164908. (*cinfo->mem->self_destruct) (cinfo);
  164909. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  164910. cinfo->global_state = 0; /* mark it destroyed */
  164911. }
  164912. /*
  164913. * Convenience routines for allocating quantization and Huffman tables.
  164914. * (Would jutils.c be a more reasonable place to put these?)
  164915. */
  164916. GLOBAL(JQUANT_TBL *)
  164917. jpeg_alloc_quant_table (j_common_ptr cinfo)
  164918. {
  164919. JQUANT_TBL *tbl;
  164920. tbl = (JQUANT_TBL *)
  164921. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  164922. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164923. return tbl;
  164924. }
  164925. GLOBAL(JHUFF_TBL *)
  164926. jpeg_alloc_huff_table (j_common_ptr cinfo)
  164927. {
  164928. JHUFF_TBL *tbl;
  164929. tbl = (JHUFF_TBL *)
  164930. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  164931. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  164932. return tbl;
  164933. }
  164934. /*** End of inlined file: jcomapi.c ***/
  164935. /*** Start of inlined file: jcparam.c ***/
  164936. #define JPEG_INTERNALS
  164937. /*
  164938. * Quantization table setup routines
  164939. */
  164940. GLOBAL(void)
  164941. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  164942. const unsigned int *basic_table,
  164943. int scale_factor, boolean force_baseline)
  164944. /* Define a quantization table equal to the basic_table times
  164945. * a scale factor (given as a percentage).
  164946. * If force_baseline is TRUE, the computed quantization table entries
  164947. * are limited to 1..255 for JPEG baseline compatibility.
  164948. */
  164949. {
  164950. JQUANT_TBL ** qtblptr;
  164951. int i;
  164952. long temp;
  164953. /* Safety check to ensure start_compress not called yet. */
  164954. if (cinfo->global_state != CSTATE_START)
  164955. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  164956. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  164957. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  164958. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  164959. if (*qtblptr == NULL)
  164960. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164961. for (i = 0; i < DCTSIZE2; i++) {
  164962. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  164963. /* limit the values to the valid range */
  164964. if (temp <= 0L) temp = 1L;
  164965. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  164966. if (force_baseline && temp > 255L)
  164967. temp = 255L; /* limit to baseline range if requested */
  164968. (*qtblptr)->quantval[i] = (UINT16) temp;
  164969. }
  164970. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  164971. (*qtblptr)->sent_table = FALSE;
  164972. }
  164973. GLOBAL(void)
  164974. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  164975. boolean force_baseline)
  164976. /* Set or change the 'quality' (quantization) setting, using default tables
  164977. * and a straight percentage-scaling quality scale. In most cases it's better
  164978. * to use jpeg_set_quality (below); this entry point is provided for
  164979. * applications that insist on a linear percentage scaling.
  164980. */
  164981. {
  164982. /* These are the sample quantization tables given in JPEG spec section K.1.
  164983. * The spec says that the values given produce "good" quality, and
  164984. * when divided by 2, "very good" quality.
  164985. */
  164986. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  164987. 16, 11, 10, 16, 24, 40, 51, 61,
  164988. 12, 12, 14, 19, 26, 58, 60, 55,
  164989. 14, 13, 16, 24, 40, 57, 69, 56,
  164990. 14, 17, 22, 29, 51, 87, 80, 62,
  164991. 18, 22, 37, 56, 68, 109, 103, 77,
  164992. 24, 35, 55, 64, 81, 104, 113, 92,
  164993. 49, 64, 78, 87, 103, 121, 120, 101,
  164994. 72, 92, 95, 98, 112, 100, 103, 99
  164995. };
  164996. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  164997. 17, 18, 24, 47, 99, 99, 99, 99,
  164998. 18, 21, 26, 66, 99, 99, 99, 99,
  164999. 24, 26, 56, 99, 99, 99, 99, 99,
  165000. 47, 66, 99, 99, 99, 99, 99, 99,
  165001. 99, 99, 99, 99, 99, 99, 99, 99,
  165002. 99, 99, 99, 99, 99, 99, 99, 99,
  165003. 99, 99, 99, 99, 99, 99, 99, 99,
  165004. 99, 99, 99, 99, 99, 99, 99, 99
  165005. };
  165006. /* Set up two quantization tables using the specified scaling */
  165007. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165008. scale_factor, force_baseline);
  165009. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165010. scale_factor, force_baseline);
  165011. }
  165012. GLOBAL(int)
  165013. jpeg_quality_scaling (int quality)
  165014. /* Convert a user-specified quality rating to a percentage scaling factor
  165015. * for an underlying quantization table, using our recommended scaling curve.
  165016. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165017. */
  165018. {
  165019. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165020. if (quality <= 0) quality = 1;
  165021. if (quality > 100) quality = 100;
  165022. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165023. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165024. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165025. * to make all the table entries 1 (hence, minimum quantization loss).
  165026. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165027. */
  165028. if (quality < 50)
  165029. quality = 5000 / quality;
  165030. else
  165031. quality = 200 - quality*2;
  165032. return quality;
  165033. }
  165034. GLOBAL(void)
  165035. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165036. /* Set or change the 'quality' (quantization) setting, using default tables.
  165037. * This is the standard quality-adjusting entry point for typical user
  165038. * interfaces; only those who want detailed control over quantization tables
  165039. * would use the preceding three routines directly.
  165040. */
  165041. {
  165042. /* Convert user 0-100 rating to percentage scaling */
  165043. quality = jpeg_quality_scaling(quality);
  165044. /* Set up standard quality tables */
  165045. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165046. }
  165047. /*
  165048. * Huffman table setup routines
  165049. */
  165050. LOCAL(void)
  165051. add_huff_table (j_compress_ptr cinfo,
  165052. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165053. /* Define a Huffman table */
  165054. {
  165055. int nsymbols, len;
  165056. if (*htblptr == NULL)
  165057. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165058. /* Copy the number-of-symbols-of-each-code-length counts */
  165059. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165060. /* Validate the counts. We do this here mainly so we can copy the right
  165061. * number of symbols from the val[] array, without risking marching off
  165062. * the end of memory. jchuff.c will do a more thorough test later.
  165063. */
  165064. nsymbols = 0;
  165065. for (len = 1; len <= 16; len++)
  165066. nsymbols += bits[len];
  165067. if (nsymbols < 1 || nsymbols > 256)
  165068. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165069. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165070. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165071. (*htblptr)->sent_table = FALSE;
  165072. }
  165073. LOCAL(void)
  165074. std_huff_tables (j_compress_ptr cinfo)
  165075. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165076. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165077. {
  165078. static const UINT8 bits_dc_luminance[17] =
  165079. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165080. static const UINT8 val_dc_luminance[] =
  165081. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165082. static const UINT8 bits_dc_chrominance[17] =
  165083. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165084. static const UINT8 val_dc_chrominance[] =
  165085. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165086. static const UINT8 bits_ac_luminance[17] =
  165087. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165088. static const UINT8 val_ac_luminance[] =
  165089. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165090. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165091. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165092. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165093. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165094. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165095. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165096. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165097. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165098. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165099. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165100. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165101. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165102. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165103. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165104. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165105. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165106. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165107. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165108. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165109. 0xf9, 0xfa };
  165110. static const UINT8 bits_ac_chrominance[17] =
  165111. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165112. static const UINT8 val_ac_chrominance[] =
  165113. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165114. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165115. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165116. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165117. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165118. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165119. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165120. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165121. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165122. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165123. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165124. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165125. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165126. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165127. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165128. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165129. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165130. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165131. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165132. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165133. 0xf9, 0xfa };
  165134. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165135. bits_dc_luminance, val_dc_luminance);
  165136. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165137. bits_ac_luminance, val_ac_luminance);
  165138. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165139. bits_dc_chrominance, val_dc_chrominance);
  165140. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165141. bits_ac_chrominance, val_ac_chrominance);
  165142. }
  165143. /*
  165144. * Default parameter setup for compression.
  165145. *
  165146. * Applications that don't choose to use this routine must do their
  165147. * own setup of all these parameters. Alternately, you can call this
  165148. * to establish defaults and then alter parameters selectively. This
  165149. * is the recommended approach since, if we add any new parameters,
  165150. * your code will still work (they'll be set to reasonable defaults).
  165151. */
  165152. GLOBAL(void)
  165153. jpeg_set_defaults (j_compress_ptr cinfo)
  165154. {
  165155. int i;
  165156. /* Safety check to ensure start_compress not called yet. */
  165157. if (cinfo->global_state != CSTATE_START)
  165158. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165159. /* Allocate comp_info array large enough for maximum component count.
  165160. * Array is made permanent in case application wants to compress
  165161. * multiple images at same param settings.
  165162. */
  165163. if (cinfo->comp_info == NULL)
  165164. cinfo->comp_info = (jpeg_component_info *)
  165165. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165166. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165167. /* Initialize everything not dependent on the color space */
  165168. cinfo->data_precision = BITS_IN_JSAMPLE;
  165169. /* Set up two quantization tables using default quality of 75 */
  165170. jpeg_set_quality(cinfo, 75, TRUE);
  165171. /* Set up two Huffman tables */
  165172. std_huff_tables(cinfo);
  165173. /* Initialize default arithmetic coding conditioning */
  165174. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165175. cinfo->arith_dc_L[i] = 0;
  165176. cinfo->arith_dc_U[i] = 1;
  165177. cinfo->arith_ac_K[i] = 5;
  165178. }
  165179. /* Default is no multiple-scan output */
  165180. cinfo->scan_info = NULL;
  165181. cinfo->num_scans = 0;
  165182. /* Expect normal source image, not raw downsampled data */
  165183. cinfo->raw_data_in = FALSE;
  165184. /* Use Huffman coding, not arithmetic coding, by default */
  165185. cinfo->arith_code = FALSE;
  165186. /* By default, don't do extra passes to optimize entropy coding */
  165187. cinfo->optimize_coding = FALSE;
  165188. /* The standard Huffman tables are only valid for 8-bit data precision.
  165189. * If the precision is higher, force optimization on so that usable
  165190. * tables will be computed. This test can be removed if default tables
  165191. * are supplied that are valid for the desired precision.
  165192. */
  165193. if (cinfo->data_precision > 8)
  165194. cinfo->optimize_coding = TRUE;
  165195. /* By default, use the simpler non-cosited sampling alignment */
  165196. cinfo->CCIR601_sampling = FALSE;
  165197. /* No input smoothing */
  165198. cinfo->smoothing_factor = 0;
  165199. /* DCT algorithm preference */
  165200. cinfo->dct_method = JDCT_DEFAULT;
  165201. /* No restart markers */
  165202. cinfo->restart_interval = 0;
  165203. cinfo->restart_in_rows = 0;
  165204. /* Fill in default JFIF marker parameters. Note that whether the marker
  165205. * will actually be written is determined by jpeg_set_colorspace.
  165206. *
  165207. * By default, the library emits JFIF version code 1.01.
  165208. * An application that wants to emit JFIF 1.02 extension markers should set
  165209. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165210. * to 1.02, but there may still be some decoders in use that will complain
  165211. * about that; saying 1.01 should minimize compatibility problems.
  165212. */
  165213. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165214. cinfo->JFIF_minor_version = 1;
  165215. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165216. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165217. cinfo->Y_density = 1;
  165218. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165219. jpeg_default_colorspace(cinfo);
  165220. }
  165221. /*
  165222. * Select an appropriate JPEG colorspace for in_color_space.
  165223. */
  165224. GLOBAL(void)
  165225. jpeg_default_colorspace (j_compress_ptr cinfo)
  165226. {
  165227. switch (cinfo->in_color_space) {
  165228. case JCS_GRAYSCALE:
  165229. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165230. break;
  165231. case JCS_RGB:
  165232. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165233. break;
  165234. case JCS_YCbCr:
  165235. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165236. break;
  165237. case JCS_CMYK:
  165238. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165239. break;
  165240. case JCS_YCCK:
  165241. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165242. break;
  165243. case JCS_UNKNOWN:
  165244. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165245. break;
  165246. default:
  165247. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165248. }
  165249. }
  165250. /*
  165251. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165252. */
  165253. GLOBAL(void)
  165254. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165255. {
  165256. jpeg_component_info * compptr;
  165257. int ci;
  165258. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165259. (compptr = &cinfo->comp_info[index], \
  165260. compptr->component_id = (id), \
  165261. compptr->h_samp_factor = (hsamp), \
  165262. compptr->v_samp_factor = (vsamp), \
  165263. compptr->quant_tbl_no = (quant), \
  165264. compptr->dc_tbl_no = (dctbl), \
  165265. compptr->ac_tbl_no = (actbl) )
  165266. /* Safety check to ensure start_compress not called yet. */
  165267. if (cinfo->global_state != CSTATE_START)
  165268. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165269. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165270. * tables 1 for chrominance components.
  165271. */
  165272. cinfo->jpeg_color_space = colorspace;
  165273. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165274. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165275. switch (colorspace) {
  165276. case JCS_GRAYSCALE:
  165277. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165278. cinfo->num_components = 1;
  165279. /* JFIF specifies component ID 1 */
  165280. SET_COMP(0, 1, 1,1, 0, 0,0);
  165281. break;
  165282. case JCS_RGB:
  165283. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165284. cinfo->num_components = 3;
  165285. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165286. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165287. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165288. break;
  165289. case JCS_YCbCr:
  165290. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165291. cinfo->num_components = 3;
  165292. /* JFIF specifies component IDs 1,2,3 */
  165293. /* We default to 2x2 subsamples of chrominance */
  165294. SET_COMP(0, 1, 2,2, 0, 0,0);
  165295. SET_COMP(1, 2, 1,1, 1, 1,1);
  165296. SET_COMP(2, 3, 1,1, 1, 1,1);
  165297. break;
  165298. case JCS_CMYK:
  165299. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165300. cinfo->num_components = 4;
  165301. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165302. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165303. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165304. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165305. break;
  165306. case JCS_YCCK:
  165307. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165308. cinfo->num_components = 4;
  165309. SET_COMP(0, 1, 2,2, 0, 0,0);
  165310. SET_COMP(1, 2, 1,1, 1, 1,1);
  165311. SET_COMP(2, 3, 1,1, 1, 1,1);
  165312. SET_COMP(3, 4, 2,2, 0, 0,0);
  165313. break;
  165314. case JCS_UNKNOWN:
  165315. cinfo->num_components = cinfo->input_components;
  165316. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165317. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165318. MAX_COMPONENTS);
  165319. for (ci = 0; ci < cinfo->num_components; ci++) {
  165320. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165321. }
  165322. break;
  165323. default:
  165324. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165325. }
  165326. }
  165327. #ifdef C_PROGRESSIVE_SUPPORTED
  165328. LOCAL(jpeg_scan_info *)
  165329. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165330. int Ss, int Se, int Ah, int Al)
  165331. /* Support routine: generate one scan for specified component */
  165332. {
  165333. scanptr->comps_in_scan = 1;
  165334. scanptr->component_index[0] = ci;
  165335. scanptr->Ss = Ss;
  165336. scanptr->Se = Se;
  165337. scanptr->Ah = Ah;
  165338. scanptr->Al = Al;
  165339. scanptr++;
  165340. return scanptr;
  165341. }
  165342. LOCAL(jpeg_scan_info *)
  165343. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165344. int Ss, int Se, int Ah, int Al)
  165345. /* Support routine: generate one scan for each component */
  165346. {
  165347. int ci;
  165348. for (ci = 0; ci < ncomps; ci++) {
  165349. scanptr->comps_in_scan = 1;
  165350. scanptr->component_index[0] = ci;
  165351. scanptr->Ss = Ss;
  165352. scanptr->Se = Se;
  165353. scanptr->Ah = Ah;
  165354. scanptr->Al = Al;
  165355. scanptr++;
  165356. }
  165357. return scanptr;
  165358. }
  165359. LOCAL(jpeg_scan_info *)
  165360. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165361. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165362. {
  165363. int ci;
  165364. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165365. /* Single interleaved DC scan */
  165366. scanptr->comps_in_scan = ncomps;
  165367. for (ci = 0; ci < ncomps; ci++)
  165368. scanptr->component_index[ci] = ci;
  165369. scanptr->Ss = scanptr->Se = 0;
  165370. scanptr->Ah = Ah;
  165371. scanptr->Al = Al;
  165372. scanptr++;
  165373. } else {
  165374. /* Noninterleaved DC scan for each component */
  165375. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165376. }
  165377. return scanptr;
  165378. }
  165379. /*
  165380. * Create a recommended progressive-JPEG script.
  165381. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165382. */
  165383. GLOBAL(void)
  165384. jpeg_simple_progression (j_compress_ptr cinfo)
  165385. {
  165386. int ncomps = cinfo->num_components;
  165387. int nscans;
  165388. jpeg_scan_info * scanptr;
  165389. /* Safety check to ensure start_compress not called yet. */
  165390. if (cinfo->global_state != CSTATE_START)
  165391. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165392. /* Figure space needed for script. Calculation must match code below! */
  165393. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165394. /* Custom script for YCbCr color images. */
  165395. nscans = 10;
  165396. } else {
  165397. /* All-purpose script for other color spaces. */
  165398. if (ncomps > MAX_COMPS_IN_SCAN)
  165399. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165400. else
  165401. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165402. }
  165403. /* Allocate space for script.
  165404. * We need to put it in the permanent pool in case the application performs
  165405. * multiple compressions without changing the settings. To avoid a memory
  165406. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165407. * object, we try to re-use previously allocated space, and we allocate
  165408. * enough space to handle YCbCr even if initially asked for grayscale.
  165409. */
  165410. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165411. cinfo->script_space_size = MAX(nscans, 10);
  165412. cinfo->script_space = (jpeg_scan_info *)
  165413. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165414. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165415. }
  165416. scanptr = cinfo->script_space;
  165417. cinfo->scan_info = scanptr;
  165418. cinfo->num_scans = nscans;
  165419. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165420. /* Custom script for YCbCr color images. */
  165421. /* Initial DC scan */
  165422. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165423. /* Initial AC scan: get some luma data out in a hurry */
  165424. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165425. /* Chroma data is too small to be worth expending many scans on */
  165426. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165427. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165428. /* Complete spectral selection for luma AC */
  165429. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165430. /* Refine next bit of luma AC */
  165431. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165432. /* Finish DC successive approximation */
  165433. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165434. /* Finish AC successive approximation */
  165435. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165436. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165437. /* Luma bottom bit comes last since it's usually largest scan */
  165438. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165439. } else {
  165440. /* All-purpose script for other color spaces. */
  165441. /* Successive approximation first pass */
  165442. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165443. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165444. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165445. /* Successive approximation second pass */
  165446. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165447. /* Successive approximation final pass */
  165448. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165449. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165450. }
  165451. }
  165452. #endif /* C_PROGRESSIVE_SUPPORTED */
  165453. /*** End of inlined file: jcparam.c ***/
  165454. /*** Start of inlined file: jcphuff.c ***/
  165455. #define JPEG_INTERNALS
  165456. #ifdef C_PROGRESSIVE_SUPPORTED
  165457. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165458. typedef struct {
  165459. struct jpeg_entropy_encoder pub; /* public fields */
  165460. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165461. boolean gather_statistics;
  165462. /* Bit-level coding status.
  165463. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165464. */
  165465. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165466. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165467. INT32 put_buffer; /* current bit-accumulation buffer */
  165468. int put_bits; /* # of bits now in it */
  165469. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165470. /* Coding status for DC components */
  165471. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165472. /* Coding status for AC components */
  165473. int ac_tbl_no; /* the table number of the single component */
  165474. unsigned int EOBRUN; /* run length of EOBs */
  165475. unsigned int BE; /* # of buffered correction bits before MCU */
  165476. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165477. /* packing correction bits tightly would save some space but cost time... */
  165478. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165479. int next_restart_num; /* next restart number to write (0-7) */
  165480. /* Pointers to derived tables (these workspaces have image lifespan).
  165481. * Since any one scan codes only DC or only AC, we only need one set
  165482. * of tables, not one for DC and one for AC.
  165483. */
  165484. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165485. /* Statistics tables for optimization; again, one set is enough */
  165486. long * count_ptrs[NUM_HUFF_TBLS];
  165487. } phuff_entropy_encoder;
  165488. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165489. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165490. * buffer can hold. Larger sizes may slightly improve compression, but
  165491. * 1000 is already well into the realm of overkill.
  165492. * The minimum safe size is 64 bits.
  165493. */
  165494. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165495. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165496. * We assume that int right shift is unsigned if INT32 right shift is,
  165497. * which should be safe.
  165498. */
  165499. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165500. #define ISHIFT_TEMPS int ishift_temp;
  165501. #define IRIGHT_SHIFT(x,shft) \
  165502. ((ishift_temp = (x)) < 0 ? \
  165503. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165504. (ishift_temp >> (shft)))
  165505. #else
  165506. #define ISHIFT_TEMPS
  165507. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165508. #endif
  165509. /* Forward declarations */
  165510. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165511. JBLOCKROW *MCU_data));
  165512. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165513. JBLOCKROW *MCU_data));
  165514. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165515. JBLOCKROW *MCU_data));
  165516. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165517. JBLOCKROW *MCU_data));
  165518. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165519. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165520. /*
  165521. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165522. */
  165523. METHODDEF(void)
  165524. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165525. {
  165526. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165527. boolean is_DC_band;
  165528. int ci, tbl;
  165529. jpeg_component_info * compptr;
  165530. entropy->cinfo = cinfo;
  165531. entropy->gather_statistics = gather_statistics;
  165532. is_DC_band = (cinfo->Ss == 0);
  165533. /* We assume jcmaster.c already validated the scan parameters. */
  165534. /* Select execution routines */
  165535. if (cinfo->Ah == 0) {
  165536. if (is_DC_band)
  165537. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165538. else
  165539. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165540. } else {
  165541. if (is_DC_band)
  165542. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165543. else {
  165544. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165545. /* AC refinement needs a correction bit buffer */
  165546. if (entropy->bit_buffer == NULL)
  165547. entropy->bit_buffer = (char *)
  165548. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165549. MAX_CORR_BITS * SIZEOF(char));
  165550. }
  165551. }
  165552. if (gather_statistics)
  165553. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165554. else
  165555. entropy->pub.finish_pass = finish_pass_phuff;
  165556. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165557. * for AC coefficients.
  165558. */
  165559. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165560. compptr = cinfo->cur_comp_info[ci];
  165561. /* Initialize DC predictions to 0 */
  165562. entropy->last_dc_val[ci] = 0;
  165563. /* Get table index */
  165564. if (is_DC_band) {
  165565. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165566. continue;
  165567. tbl = compptr->dc_tbl_no;
  165568. } else {
  165569. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165570. }
  165571. if (gather_statistics) {
  165572. /* Check for invalid table index */
  165573. /* (make_c_derived_tbl does this in the other path) */
  165574. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165575. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165576. /* Allocate and zero the statistics tables */
  165577. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165578. if (entropy->count_ptrs[tbl] == NULL)
  165579. entropy->count_ptrs[tbl] = (long *)
  165580. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165581. 257 * SIZEOF(long));
  165582. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165583. } else {
  165584. /* Compute derived values for Huffman table */
  165585. /* We may do this more than once for a table, but it's not expensive */
  165586. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165587. & entropy->derived_tbls[tbl]);
  165588. }
  165589. }
  165590. /* Initialize AC stuff */
  165591. entropy->EOBRUN = 0;
  165592. entropy->BE = 0;
  165593. /* Initialize bit buffer to empty */
  165594. entropy->put_buffer = 0;
  165595. entropy->put_bits = 0;
  165596. /* Initialize restart stuff */
  165597. entropy->restarts_to_go = cinfo->restart_interval;
  165598. entropy->next_restart_num = 0;
  165599. }
  165600. /* Outputting bytes to the file.
  165601. * NB: these must be called only when actually outputting,
  165602. * that is, entropy->gather_statistics == FALSE.
  165603. */
  165604. /* Emit a byte */
  165605. #define emit_byte(entropy,val) \
  165606. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165607. if (--(entropy)->free_in_buffer == 0) \
  165608. dump_buffer_p(entropy); }
  165609. LOCAL(void)
  165610. dump_buffer_p (phuff_entropy_ptr entropy)
  165611. /* Empty the output buffer; we do not support suspension in this module. */
  165612. {
  165613. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165614. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165615. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165616. /* After a successful buffer dump, must reset buffer pointers */
  165617. entropy->next_output_byte = dest->next_output_byte;
  165618. entropy->free_in_buffer = dest->free_in_buffer;
  165619. }
  165620. /* Outputting bits to the file */
  165621. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165622. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165623. * in one call, and we never retain more than 7 bits in put_buffer
  165624. * between calls, so 24 bits are sufficient.
  165625. */
  165626. INLINE
  165627. LOCAL(void)
  165628. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165629. /* Emit some bits, unless we are in gather mode */
  165630. {
  165631. /* This routine is heavily used, so it's worth coding tightly. */
  165632. register INT32 put_buffer = (INT32) code;
  165633. register int put_bits = entropy->put_bits;
  165634. /* if size is 0, caller used an invalid Huffman table entry */
  165635. if (size == 0)
  165636. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165637. if (entropy->gather_statistics)
  165638. return; /* do nothing if we're only getting stats */
  165639. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165640. put_bits += size; /* new number of bits in buffer */
  165641. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165642. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165643. while (put_bits >= 8) {
  165644. int c = (int) ((put_buffer >> 16) & 0xFF);
  165645. emit_byte(entropy, c);
  165646. if (c == 0xFF) { /* need to stuff a zero byte? */
  165647. emit_byte(entropy, 0);
  165648. }
  165649. put_buffer <<= 8;
  165650. put_bits -= 8;
  165651. }
  165652. entropy->put_buffer = put_buffer; /* update variables */
  165653. entropy->put_bits = put_bits;
  165654. }
  165655. LOCAL(void)
  165656. flush_bits_p (phuff_entropy_ptr entropy)
  165657. {
  165658. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165659. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165660. entropy->put_bits = 0;
  165661. }
  165662. /*
  165663. * Emit (or just count) a Huffman symbol.
  165664. */
  165665. INLINE
  165666. LOCAL(void)
  165667. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  165668. {
  165669. if (entropy->gather_statistics)
  165670. entropy->count_ptrs[tbl_no][symbol]++;
  165671. else {
  165672. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  165673. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  165674. }
  165675. }
  165676. /*
  165677. * Emit bits from a correction bit buffer.
  165678. */
  165679. LOCAL(void)
  165680. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  165681. unsigned int nbits)
  165682. {
  165683. if (entropy->gather_statistics)
  165684. return; /* no real work */
  165685. while (nbits > 0) {
  165686. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  165687. bufstart++;
  165688. nbits--;
  165689. }
  165690. }
  165691. /*
  165692. * Emit any pending EOBRUN symbol.
  165693. */
  165694. LOCAL(void)
  165695. emit_eobrun (phuff_entropy_ptr entropy)
  165696. {
  165697. register int temp, nbits;
  165698. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  165699. temp = entropy->EOBRUN;
  165700. nbits = 0;
  165701. while ((temp >>= 1))
  165702. nbits++;
  165703. /* safety check: shouldn't happen given limited correction-bit buffer */
  165704. if (nbits > 14)
  165705. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165706. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  165707. if (nbits)
  165708. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  165709. entropy->EOBRUN = 0;
  165710. /* Emit any buffered correction bits */
  165711. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  165712. entropy->BE = 0;
  165713. }
  165714. }
  165715. /*
  165716. * Emit a restart marker & resynchronize predictions.
  165717. */
  165718. LOCAL(void)
  165719. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  165720. {
  165721. int ci;
  165722. emit_eobrun(entropy);
  165723. if (! entropy->gather_statistics) {
  165724. flush_bits_p(entropy);
  165725. emit_byte(entropy, 0xFF);
  165726. emit_byte(entropy, JPEG_RST0 + restart_num);
  165727. }
  165728. if (entropy->cinfo->Ss == 0) {
  165729. /* Re-initialize DC predictions to 0 */
  165730. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  165731. entropy->last_dc_val[ci] = 0;
  165732. } else {
  165733. /* Re-initialize all AC-related fields to 0 */
  165734. entropy->EOBRUN = 0;
  165735. entropy->BE = 0;
  165736. }
  165737. }
  165738. /*
  165739. * MCU encoding for DC initial scan (either spectral selection,
  165740. * or first pass of successive approximation).
  165741. */
  165742. METHODDEF(boolean)
  165743. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165744. {
  165745. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165746. register int temp, temp2;
  165747. register int nbits;
  165748. int blkn, ci;
  165749. int Al = cinfo->Al;
  165750. JBLOCKROW block;
  165751. jpeg_component_info * compptr;
  165752. ISHIFT_TEMPS
  165753. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165754. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165755. /* Emit restart marker if needed */
  165756. if (cinfo->restart_interval)
  165757. if (entropy->restarts_to_go == 0)
  165758. emit_restart_p(entropy, entropy->next_restart_num);
  165759. /* Encode the MCU data blocks */
  165760. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165761. block = MCU_data[blkn];
  165762. ci = cinfo->MCU_membership[blkn];
  165763. compptr = cinfo->cur_comp_info[ci];
  165764. /* Compute the DC value after the required point transform by Al.
  165765. * This is simply an arithmetic right shift.
  165766. */
  165767. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  165768. /* DC differences are figured on the point-transformed values. */
  165769. temp = temp2 - entropy->last_dc_val[ci];
  165770. entropy->last_dc_val[ci] = temp2;
  165771. /* Encode the DC coefficient difference per section G.1.2.1 */
  165772. temp2 = temp;
  165773. if (temp < 0) {
  165774. temp = -temp; /* temp is abs value of input */
  165775. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  165776. /* This code assumes we are on a two's complement machine */
  165777. temp2--;
  165778. }
  165779. /* Find the number of bits needed for the magnitude of the coefficient */
  165780. nbits = 0;
  165781. while (temp) {
  165782. nbits++;
  165783. temp >>= 1;
  165784. }
  165785. /* Check for out-of-range coefficient values.
  165786. * Since we're encoding a difference, the range limit is twice as much.
  165787. */
  165788. if (nbits > MAX_COEF_BITS+1)
  165789. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165790. /* Count/emit the Huffman-coded symbol for the number of bits */
  165791. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  165792. /* Emit that number of bits of the value, if positive, */
  165793. /* or the complement of its magnitude, if negative. */
  165794. if (nbits) /* emit_bits rejects calls with size 0 */
  165795. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165796. }
  165797. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165798. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165799. /* Update restart-interval state too */
  165800. if (cinfo->restart_interval) {
  165801. if (entropy->restarts_to_go == 0) {
  165802. entropy->restarts_to_go = cinfo->restart_interval;
  165803. entropy->next_restart_num++;
  165804. entropy->next_restart_num &= 7;
  165805. }
  165806. entropy->restarts_to_go--;
  165807. }
  165808. return TRUE;
  165809. }
  165810. /*
  165811. * MCU encoding for AC initial scan (either spectral selection,
  165812. * or first pass of successive approximation).
  165813. */
  165814. METHODDEF(boolean)
  165815. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165816. {
  165817. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165818. register int temp, temp2;
  165819. register int nbits;
  165820. register int r, k;
  165821. int Se = cinfo->Se;
  165822. int Al = cinfo->Al;
  165823. JBLOCKROW block;
  165824. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165825. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165826. /* Emit restart marker if needed */
  165827. if (cinfo->restart_interval)
  165828. if (entropy->restarts_to_go == 0)
  165829. emit_restart_p(entropy, entropy->next_restart_num);
  165830. /* Encode the MCU data block */
  165831. block = MCU_data[0];
  165832. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  165833. r = 0; /* r = run length of zeros */
  165834. for (k = cinfo->Ss; k <= Se; k++) {
  165835. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  165836. r++;
  165837. continue;
  165838. }
  165839. /* We must apply the point transform by Al. For AC coefficients this
  165840. * is an integer division with rounding towards 0. To do this portably
  165841. * in C, we shift after obtaining the absolute value; so the code is
  165842. * interwoven with finding the abs value (temp) and output bits (temp2).
  165843. */
  165844. if (temp < 0) {
  165845. temp = -temp; /* temp is abs value of input */
  165846. temp >>= Al; /* apply the point transform */
  165847. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  165848. temp2 = ~temp;
  165849. } else {
  165850. temp >>= Al; /* apply the point transform */
  165851. temp2 = temp;
  165852. }
  165853. /* Watch out for case that nonzero coef is zero after point transform */
  165854. if (temp == 0) {
  165855. r++;
  165856. continue;
  165857. }
  165858. /* Emit any pending EOBRUN */
  165859. if (entropy->EOBRUN > 0)
  165860. emit_eobrun(entropy);
  165861. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  165862. while (r > 15) {
  165863. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165864. r -= 16;
  165865. }
  165866. /* Find the number of bits needed for the magnitude of the coefficient */
  165867. nbits = 1; /* there must be at least one 1 bit */
  165868. while ((temp >>= 1))
  165869. nbits++;
  165870. /* Check for out-of-range coefficient values */
  165871. if (nbits > MAX_COEF_BITS)
  165872. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  165873. /* Count/emit Huffman symbol for run length / number of bits */
  165874. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  165875. /* Emit that number of bits of the value, if positive, */
  165876. /* or the complement of its magnitude, if negative. */
  165877. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  165878. r = 0; /* reset zero run length */
  165879. }
  165880. if (r > 0) { /* If there are trailing zeroes, */
  165881. entropy->EOBRUN++; /* count an EOB */
  165882. if (entropy->EOBRUN == 0x7FFF)
  165883. emit_eobrun(entropy); /* force it out to avoid overflow */
  165884. }
  165885. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165886. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165887. /* Update restart-interval state too */
  165888. if (cinfo->restart_interval) {
  165889. if (entropy->restarts_to_go == 0) {
  165890. entropy->restarts_to_go = cinfo->restart_interval;
  165891. entropy->next_restart_num++;
  165892. entropy->next_restart_num &= 7;
  165893. }
  165894. entropy->restarts_to_go--;
  165895. }
  165896. return TRUE;
  165897. }
  165898. /*
  165899. * MCU encoding for DC successive approximation refinement scan.
  165900. * Note: we assume such scans can be multi-component, although the spec
  165901. * is not very clear on the point.
  165902. */
  165903. METHODDEF(boolean)
  165904. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165905. {
  165906. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165907. register int temp;
  165908. int blkn;
  165909. int Al = cinfo->Al;
  165910. JBLOCKROW block;
  165911. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165912. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165913. /* Emit restart marker if needed */
  165914. if (cinfo->restart_interval)
  165915. if (entropy->restarts_to_go == 0)
  165916. emit_restart_p(entropy, entropy->next_restart_num);
  165917. /* Encode the MCU data blocks */
  165918. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165919. block = MCU_data[blkn];
  165920. /* We simply emit the Al'th bit of the DC coefficient value. */
  165921. temp = (*block)[0];
  165922. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  165923. }
  165924. cinfo->dest->next_output_byte = entropy->next_output_byte;
  165925. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  165926. /* Update restart-interval state too */
  165927. if (cinfo->restart_interval) {
  165928. if (entropy->restarts_to_go == 0) {
  165929. entropy->restarts_to_go = cinfo->restart_interval;
  165930. entropy->next_restart_num++;
  165931. entropy->next_restart_num &= 7;
  165932. }
  165933. entropy->restarts_to_go--;
  165934. }
  165935. return TRUE;
  165936. }
  165937. /*
  165938. * MCU encoding for AC successive approximation refinement scan.
  165939. */
  165940. METHODDEF(boolean)
  165941. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  165942. {
  165943. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165944. register int temp;
  165945. register int r, k;
  165946. int EOB;
  165947. char *BR_buffer;
  165948. unsigned int BR;
  165949. int Se = cinfo->Se;
  165950. int Al = cinfo->Al;
  165951. JBLOCKROW block;
  165952. int absvalues[DCTSIZE2];
  165953. entropy->next_output_byte = cinfo->dest->next_output_byte;
  165954. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  165955. /* Emit restart marker if needed */
  165956. if (cinfo->restart_interval)
  165957. if (entropy->restarts_to_go == 0)
  165958. emit_restart_p(entropy, entropy->next_restart_num);
  165959. /* Encode the MCU data block */
  165960. block = MCU_data[0];
  165961. /* It is convenient to make a pre-pass to determine the transformed
  165962. * coefficients' absolute values and the EOB position.
  165963. */
  165964. EOB = 0;
  165965. for (k = cinfo->Ss; k <= Se; k++) {
  165966. temp = (*block)[jpeg_natural_order[k]];
  165967. /* We must apply the point transform by Al. For AC coefficients this
  165968. * is an integer division with rounding towards 0. To do this portably
  165969. * in C, we shift after obtaining the absolute value.
  165970. */
  165971. if (temp < 0)
  165972. temp = -temp; /* temp is abs value of input */
  165973. temp >>= Al; /* apply the point transform */
  165974. absvalues[k] = temp; /* save abs value for main pass */
  165975. if (temp == 1)
  165976. EOB = k; /* EOB = index of last newly-nonzero coef */
  165977. }
  165978. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  165979. r = 0; /* r = run length of zeros */
  165980. BR = 0; /* BR = count of buffered bits added now */
  165981. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  165982. for (k = cinfo->Ss; k <= Se; k++) {
  165983. if ((temp = absvalues[k]) == 0) {
  165984. r++;
  165985. continue;
  165986. }
  165987. /* Emit any required ZRLs, but not if they can be folded into EOB */
  165988. while (r > 15 && k <= EOB) {
  165989. /* emit any pending EOBRUN and the BE correction bits */
  165990. emit_eobrun(entropy);
  165991. /* Emit ZRL */
  165992. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  165993. r -= 16;
  165994. /* Emit buffered correction bits that must be associated with ZRL */
  165995. emit_buffered_bits(entropy, BR_buffer, BR);
  165996. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  165997. BR = 0;
  165998. }
  165999. /* If the coef was previously nonzero, it only needs a correction bit.
  166000. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166001. * that we also need to test r > 15. But if r > 15, we can only get here
  166002. * if k > EOB, which implies that this coefficient is not 1.
  166003. */
  166004. if (temp > 1) {
  166005. /* The correction bit is the next bit of the absolute value. */
  166006. BR_buffer[BR++] = (char) (temp & 1);
  166007. continue;
  166008. }
  166009. /* Emit any pending EOBRUN and the BE correction bits */
  166010. emit_eobrun(entropy);
  166011. /* Count/emit Huffman symbol for run length / number of bits */
  166012. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166013. /* Emit output bit for newly-nonzero coef */
  166014. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166015. emit_bits_p(entropy, (unsigned int) temp, 1);
  166016. /* Emit buffered correction bits that must be associated with this code */
  166017. emit_buffered_bits(entropy, BR_buffer, BR);
  166018. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166019. BR = 0;
  166020. r = 0; /* reset zero run length */
  166021. }
  166022. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166023. entropy->EOBRUN++; /* count an EOB */
  166024. entropy->BE += BR; /* concat my correction bits to older ones */
  166025. /* We force out the EOB if we risk either:
  166026. * 1. overflow of the EOB counter;
  166027. * 2. overflow of the correction bit buffer during the next MCU.
  166028. */
  166029. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166030. emit_eobrun(entropy);
  166031. }
  166032. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166033. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166034. /* Update restart-interval state too */
  166035. if (cinfo->restart_interval) {
  166036. if (entropy->restarts_to_go == 0) {
  166037. entropy->restarts_to_go = cinfo->restart_interval;
  166038. entropy->next_restart_num++;
  166039. entropy->next_restart_num &= 7;
  166040. }
  166041. entropy->restarts_to_go--;
  166042. }
  166043. return TRUE;
  166044. }
  166045. /*
  166046. * Finish up at the end of a Huffman-compressed progressive scan.
  166047. */
  166048. METHODDEF(void)
  166049. finish_pass_phuff (j_compress_ptr cinfo)
  166050. {
  166051. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166052. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166053. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166054. /* Flush out any buffered data */
  166055. emit_eobrun(entropy);
  166056. flush_bits_p(entropy);
  166057. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166058. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166059. }
  166060. /*
  166061. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166062. */
  166063. METHODDEF(void)
  166064. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166065. {
  166066. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166067. boolean is_DC_band;
  166068. int ci, tbl;
  166069. jpeg_component_info * compptr;
  166070. JHUFF_TBL **htblptr;
  166071. boolean did[NUM_HUFF_TBLS];
  166072. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166073. emit_eobrun(entropy);
  166074. is_DC_band = (cinfo->Ss == 0);
  166075. /* It's important not to apply jpeg_gen_optimal_table more than once
  166076. * per table, because it clobbers the input frequency counts!
  166077. */
  166078. MEMZERO(did, SIZEOF(did));
  166079. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166080. compptr = cinfo->cur_comp_info[ci];
  166081. if (is_DC_band) {
  166082. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166083. continue;
  166084. tbl = compptr->dc_tbl_no;
  166085. } else {
  166086. tbl = compptr->ac_tbl_no;
  166087. }
  166088. if (! did[tbl]) {
  166089. if (is_DC_band)
  166090. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166091. else
  166092. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166093. if (*htblptr == NULL)
  166094. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166095. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166096. did[tbl] = TRUE;
  166097. }
  166098. }
  166099. }
  166100. /*
  166101. * Module initialization routine for progressive Huffman entropy encoding.
  166102. */
  166103. GLOBAL(void)
  166104. jinit_phuff_encoder (j_compress_ptr cinfo)
  166105. {
  166106. phuff_entropy_ptr entropy;
  166107. int i;
  166108. entropy = (phuff_entropy_ptr)
  166109. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166110. SIZEOF(phuff_entropy_encoder));
  166111. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166112. entropy->pub.start_pass = start_pass_phuff;
  166113. /* Mark tables unallocated */
  166114. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166115. entropy->derived_tbls[i] = NULL;
  166116. entropy->count_ptrs[i] = NULL;
  166117. }
  166118. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166119. }
  166120. #endif /* C_PROGRESSIVE_SUPPORTED */
  166121. /*** End of inlined file: jcphuff.c ***/
  166122. /*** Start of inlined file: jcprepct.c ***/
  166123. #define JPEG_INTERNALS
  166124. /* At present, jcsample.c can request context rows only for smoothing.
  166125. * In the future, we might also need context rows for CCIR601 sampling
  166126. * or other more-complex downsampling procedures. The code to support
  166127. * context rows should be compiled only if needed.
  166128. */
  166129. #ifdef INPUT_SMOOTHING_SUPPORTED
  166130. #define CONTEXT_ROWS_SUPPORTED
  166131. #endif
  166132. /*
  166133. * For the simple (no-context-row) case, we just need to buffer one
  166134. * row group's worth of pixels for the downsampling step. At the bottom of
  166135. * the image, we pad to a full row group by replicating the last pixel row.
  166136. * The downsampler's last output row is then replicated if needed to pad
  166137. * out to a full iMCU row.
  166138. *
  166139. * When providing context rows, we must buffer three row groups' worth of
  166140. * pixels. Three row groups are physically allocated, but the row pointer
  166141. * arrays are made five row groups high, with the extra pointers above and
  166142. * below "wrapping around" to point to the last and first real row groups.
  166143. * This allows the downsampler to access the proper context rows.
  166144. * At the top and bottom of the image, we create dummy context rows by
  166145. * copying the first or last real pixel row. This copying could be avoided
  166146. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166147. * trouble on the compression side.
  166148. */
  166149. /* Private buffer controller object */
  166150. typedef struct {
  166151. struct jpeg_c_prep_controller pub; /* public fields */
  166152. /* Downsampling input buffer. This buffer holds color-converted data
  166153. * until we have enough to do a downsample step.
  166154. */
  166155. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166156. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166157. int next_buf_row; /* index of next row to store in color_buf */
  166158. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166159. int this_row_group; /* starting row index of group to process */
  166160. int next_buf_stop; /* downsample when we reach this index */
  166161. #endif
  166162. } my_prep_controller;
  166163. typedef my_prep_controller * my_prep_ptr;
  166164. /*
  166165. * Initialize for a processing pass.
  166166. */
  166167. METHODDEF(void)
  166168. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166169. {
  166170. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166171. if (pass_mode != JBUF_PASS_THRU)
  166172. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166173. /* Initialize total-height counter for detecting bottom of image */
  166174. prep->rows_to_go = cinfo->image_height;
  166175. /* Mark the conversion buffer empty */
  166176. prep->next_buf_row = 0;
  166177. #ifdef CONTEXT_ROWS_SUPPORTED
  166178. /* Preset additional state variables for context mode.
  166179. * These aren't used in non-context mode, so we needn't test which mode.
  166180. */
  166181. prep->this_row_group = 0;
  166182. /* Set next_buf_stop to stop after two row groups have been read in. */
  166183. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166184. #endif
  166185. }
  166186. /*
  166187. * Expand an image vertically from height input_rows to height output_rows,
  166188. * by duplicating the bottom row.
  166189. */
  166190. LOCAL(void)
  166191. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166192. int input_rows, int output_rows)
  166193. {
  166194. register int row;
  166195. for (row = input_rows; row < output_rows; row++) {
  166196. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166197. 1, num_cols);
  166198. }
  166199. }
  166200. /*
  166201. * Process some data in the simple no-context case.
  166202. *
  166203. * Preprocessor output data is counted in "row groups". A row group
  166204. * is defined to be v_samp_factor sample rows of each component.
  166205. * Downsampling will produce this much data from each max_v_samp_factor
  166206. * input rows.
  166207. */
  166208. METHODDEF(void)
  166209. pre_process_data (j_compress_ptr cinfo,
  166210. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166211. JDIMENSION in_rows_avail,
  166212. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166213. JDIMENSION out_row_groups_avail)
  166214. {
  166215. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166216. int numrows, ci;
  166217. JDIMENSION inrows;
  166218. jpeg_component_info * compptr;
  166219. while (*in_row_ctr < in_rows_avail &&
  166220. *out_row_group_ctr < out_row_groups_avail) {
  166221. /* Do color conversion to fill the conversion buffer. */
  166222. inrows = in_rows_avail - *in_row_ctr;
  166223. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166224. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166225. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166226. prep->color_buf,
  166227. (JDIMENSION) prep->next_buf_row,
  166228. numrows);
  166229. *in_row_ctr += numrows;
  166230. prep->next_buf_row += numrows;
  166231. prep->rows_to_go -= numrows;
  166232. /* If at bottom of image, pad to fill the conversion buffer. */
  166233. if (prep->rows_to_go == 0 &&
  166234. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166235. for (ci = 0; ci < cinfo->num_components; ci++) {
  166236. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166237. prep->next_buf_row, cinfo->max_v_samp_factor);
  166238. }
  166239. prep->next_buf_row = cinfo->max_v_samp_factor;
  166240. }
  166241. /* If we've filled the conversion buffer, empty it. */
  166242. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166243. (*cinfo->downsample->downsample) (cinfo,
  166244. prep->color_buf, (JDIMENSION) 0,
  166245. output_buf, *out_row_group_ctr);
  166246. prep->next_buf_row = 0;
  166247. (*out_row_group_ctr)++;
  166248. }
  166249. /* If at bottom of image, pad the output to a full iMCU height.
  166250. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166251. */
  166252. if (prep->rows_to_go == 0 &&
  166253. *out_row_group_ctr < out_row_groups_avail) {
  166254. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166255. ci++, compptr++) {
  166256. expand_bottom_edge(output_buf[ci],
  166257. compptr->width_in_blocks * DCTSIZE,
  166258. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166259. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166260. }
  166261. *out_row_group_ctr = out_row_groups_avail;
  166262. break; /* can exit outer loop without test */
  166263. }
  166264. }
  166265. }
  166266. #ifdef CONTEXT_ROWS_SUPPORTED
  166267. /*
  166268. * Process some data in the context case.
  166269. */
  166270. METHODDEF(void)
  166271. pre_process_context (j_compress_ptr cinfo,
  166272. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166273. JDIMENSION in_rows_avail,
  166274. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166275. JDIMENSION out_row_groups_avail)
  166276. {
  166277. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166278. int numrows, ci;
  166279. int buf_height = cinfo->max_v_samp_factor * 3;
  166280. JDIMENSION inrows;
  166281. while (*out_row_group_ctr < out_row_groups_avail) {
  166282. if (*in_row_ctr < in_rows_avail) {
  166283. /* Do color conversion to fill the conversion buffer. */
  166284. inrows = in_rows_avail - *in_row_ctr;
  166285. numrows = prep->next_buf_stop - prep->next_buf_row;
  166286. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166287. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166288. prep->color_buf,
  166289. (JDIMENSION) prep->next_buf_row,
  166290. numrows);
  166291. /* Pad at top of image, if first time through */
  166292. if (prep->rows_to_go == cinfo->image_height) {
  166293. for (ci = 0; ci < cinfo->num_components; ci++) {
  166294. int row;
  166295. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166296. jcopy_sample_rows(prep->color_buf[ci], 0,
  166297. prep->color_buf[ci], -row,
  166298. 1, cinfo->image_width);
  166299. }
  166300. }
  166301. }
  166302. *in_row_ctr += numrows;
  166303. prep->next_buf_row += numrows;
  166304. prep->rows_to_go -= numrows;
  166305. } else {
  166306. /* Return for more data, unless we are at the bottom of the image. */
  166307. if (prep->rows_to_go != 0)
  166308. break;
  166309. /* When at bottom of image, pad to fill the conversion buffer. */
  166310. if (prep->next_buf_row < prep->next_buf_stop) {
  166311. for (ci = 0; ci < cinfo->num_components; ci++) {
  166312. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166313. prep->next_buf_row, prep->next_buf_stop);
  166314. }
  166315. prep->next_buf_row = prep->next_buf_stop;
  166316. }
  166317. }
  166318. /* If we've gotten enough data, downsample a row group. */
  166319. if (prep->next_buf_row == prep->next_buf_stop) {
  166320. (*cinfo->downsample->downsample) (cinfo,
  166321. prep->color_buf,
  166322. (JDIMENSION) prep->this_row_group,
  166323. output_buf, *out_row_group_ctr);
  166324. (*out_row_group_ctr)++;
  166325. /* Advance pointers with wraparound as necessary. */
  166326. prep->this_row_group += cinfo->max_v_samp_factor;
  166327. if (prep->this_row_group >= buf_height)
  166328. prep->this_row_group = 0;
  166329. if (prep->next_buf_row >= buf_height)
  166330. prep->next_buf_row = 0;
  166331. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166332. }
  166333. }
  166334. }
  166335. /*
  166336. * Create the wrapped-around downsampling input buffer needed for context mode.
  166337. */
  166338. LOCAL(void)
  166339. create_context_buffer (j_compress_ptr cinfo)
  166340. {
  166341. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166342. int rgroup_height = cinfo->max_v_samp_factor;
  166343. int ci, i;
  166344. jpeg_component_info * compptr;
  166345. JSAMPARRAY true_buffer, fake_buffer;
  166346. /* Grab enough space for fake row pointers for all the components;
  166347. * we need five row groups' worth of pointers for each component.
  166348. */
  166349. fake_buffer = (JSAMPARRAY)
  166350. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166351. (cinfo->num_components * 5 * rgroup_height) *
  166352. SIZEOF(JSAMPROW));
  166353. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166354. ci++, compptr++) {
  166355. /* Allocate the actual buffer space (3 row groups) for this component.
  166356. * We make the buffer wide enough to allow the downsampler to edge-expand
  166357. * horizontally within the buffer, if it so chooses.
  166358. */
  166359. true_buffer = (*cinfo->mem->alloc_sarray)
  166360. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166361. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166362. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166363. (JDIMENSION) (3 * rgroup_height));
  166364. /* Copy true buffer row pointers into the middle of the fake row array */
  166365. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166366. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166367. /* Fill in the above and below wraparound pointers */
  166368. for (i = 0; i < rgroup_height; i++) {
  166369. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166370. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166371. }
  166372. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166373. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166374. }
  166375. }
  166376. #endif /* CONTEXT_ROWS_SUPPORTED */
  166377. /*
  166378. * Initialize preprocessing controller.
  166379. */
  166380. GLOBAL(void)
  166381. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166382. {
  166383. my_prep_ptr prep;
  166384. int ci;
  166385. jpeg_component_info * compptr;
  166386. if (need_full_buffer) /* safety check */
  166387. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166388. prep = (my_prep_ptr)
  166389. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166390. SIZEOF(my_prep_controller));
  166391. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166392. prep->pub.start_pass = start_pass_prep;
  166393. /* Allocate the color conversion buffer.
  166394. * We make the buffer wide enough to allow the downsampler to edge-expand
  166395. * horizontally within the buffer, if it so chooses.
  166396. */
  166397. if (cinfo->downsample->need_context_rows) {
  166398. /* Set up to provide context rows */
  166399. #ifdef CONTEXT_ROWS_SUPPORTED
  166400. prep->pub.pre_process_data = pre_process_context;
  166401. create_context_buffer(cinfo);
  166402. #else
  166403. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166404. #endif
  166405. } else {
  166406. /* No context, just make it tall enough for one row group */
  166407. prep->pub.pre_process_data = pre_process_data;
  166408. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166409. ci++, compptr++) {
  166410. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166411. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166412. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166413. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166414. (JDIMENSION) cinfo->max_v_samp_factor);
  166415. }
  166416. }
  166417. }
  166418. /*** End of inlined file: jcprepct.c ***/
  166419. /*** Start of inlined file: jcsample.c ***/
  166420. #define JPEG_INTERNALS
  166421. /* Pointer to routine to downsample a single component */
  166422. typedef JMETHOD(void, downsample1_ptr,
  166423. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166424. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166425. /* Private subobject */
  166426. typedef struct {
  166427. struct jpeg_downsampler pub; /* public fields */
  166428. /* Downsampling method pointers, one per component */
  166429. downsample1_ptr methods[MAX_COMPONENTS];
  166430. } my_downsampler;
  166431. typedef my_downsampler * my_downsample_ptr;
  166432. /*
  166433. * Initialize for a downsampling pass.
  166434. */
  166435. METHODDEF(void)
  166436. start_pass_downsample (j_compress_ptr)
  166437. {
  166438. /* no work for now */
  166439. }
  166440. /*
  166441. * Expand a component horizontally from width input_cols to width output_cols,
  166442. * by duplicating the rightmost samples.
  166443. */
  166444. LOCAL(void)
  166445. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166446. JDIMENSION input_cols, JDIMENSION output_cols)
  166447. {
  166448. register JSAMPROW ptr;
  166449. register JSAMPLE pixval;
  166450. register int count;
  166451. int row;
  166452. int numcols = (int) (output_cols - input_cols);
  166453. if (numcols > 0) {
  166454. for (row = 0; row < num_rows; row++) {
  166455. ptr = image_data[row] + input_cols;
  166456. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166457. for (count = numcols; count > 0; count--)
  166458. *ptr++ = pixval;
  166459. }
  166460. }
  166461. }
  166462. /*
  166463. * Do downsampling for a whole row group (all components).
  166464. *
  166465. * In this version we simply downsample each component independently.
  166466. */
  166467. METHODDEF(void)
  166468. sep_downsample (j_compress_ptr cinfo,
  166469. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166470. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166471. {
  166472. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166473. int ci;
  166474. jpeg_component_info * compptr;
  166475. JSAMPARRAY in_ptr, out_ptr;
  166476. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166477. ci++, compptr++) {
  166478. in_ptr = input_buf[ci] + in_row_index;
  166479. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166480. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166481. }
  166482. }
  166483. /*
  166484. * Downsample pixel values of a single component.
  166485. * One row group is processed per call.
  166486. * This version handles arbitrary integral sampling ratios, without smoothing.
  166487. * Note that this version is not actually used for customary sampling ratios.
  166488. */
  166489. METHODDEF(void)
  166490. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166491. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166492. {
  166493. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166494. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166495. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166496. JSAMPROW inptr, outptr;
  166497. INT32 outvalue;
  166498. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166499. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166500. numpix = h_expand * v_expand;
  166501. numpix2 = numpix/2;
  166502. /* Expand input data enough to let all the output samples be generated
  166503. * by the standard loop. Special-casing padded output would be more
  166504. * efficient.
  166505. */
  166506. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166507. cinfo->image_width, output_cols * h_expand);
  166508. inrow = 0;
  166509. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166510. outptr = output_data[outrow];
  166511. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166512. outcol++, outcol_h += h_expand) {
  166513. outvalue = 0;
  166514. for (v = 0; v < v_expand; v++) {
  166515. inptr = input_data[inrow+v] + outcol_h;
  166516. for (h = 0; h < h_expand; h++) {
  166517. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166518. }
  166519. }
  166520. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166521. }
  166522. inrow += v_expand;
  166523. }
  166524. }
  166525. /*
  166526. * Downsample pixel values of a single component.
  166527. * This version handles the special case of a full-size component,
  166528. * without smoothing.
  166529. */
  166530. METHODDEF(void)
  166531. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166532. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166533. {
  166534. /* Copy the data */
  166535. jcopy_sample_rows(input_data, 0, output_data, 0,
  166536. cinfo->max_v_samp_factor, cinfo->image_width);
  166537. /* Edge-expand */
  166538. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166539. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166540. }
  166541. /*
  166542. * Downsample pixel values of a single component.
  166543. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166544. * without smoothing.
  166545. *
  166546. * A note about the "bias" calculations: when rounding fractional values to
  166547. * integer, we do not want to always round 0.5 up to the next integer.
  166548. * If we did that, we'd introduce a noticeable bias towards larger values.
  166549. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166550. * alternate pixel locations (a simple ordered dither pattern).
  166551. */
  166552. METHODDEF(void)
  166553. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166554. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166555. {
  166556. int outrow;
  166557. JDIMENSION outcol;
  166558. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166559. register JSAMPROW inptr, outptr;
  166560. register int bias;
  166561. /* Expand input data enough to let all the output samples be generated
  166562. * by the standard loop. Special-casing padded output would be more
  166563. * efficient.
  166564. */
  166565. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166566. cinfo->image_width, output_cols * 2);
  166567. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166568. outptr = output_data[outrow];
  166569. inptr = input_data[outrow];
  166570. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166571. for (outcol = 0; outcol < output_cols; outcol++) {
  166572. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166573. + bias) >> 1);
  166574. bias ^= 1; /* 0=>1, 1=>0 */
  166575. inptr += 2;
  166576. }
  166577. }
  166578. }
  166579. /*
  166580. * Downsample pixel values of a single component.
  166581. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166582. * without smoothing.
  166583. */
  166584. METHODDEF(void)
  166585. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166586. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166587. {
  166588. int inrow, outrow;
  166589. JDIMENSION outcol;
  166590. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166591. register JSAMPROW inptr0, inptr1, outptr;
  166592. register int bias;
  166593. /* Expand input data enough to let all the output samples be generated
  166594. * by the standard loop. Special-casing padded output would be more
  166595. * efficient.
  166596. */
  166597. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166598. cinfo->image_width, output_cols * 2);
  166599. inrow = 0;
  166600. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166601. outptr = output_data[outrow];
  166602. inptr0 = input_data[inrow];
  166603. inptr1 = input_data[inrow+1];
  166604. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166605. for (outcol = 0; outcol < output_cols; outcol++) {
  166606. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166607. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166608. + bias) >> 2);
  166609. bias ^= 3; /* 1=>2, 2=>1 */
  166610. inptr0 += 2; inptr1 += 2;
  166611. }
  166612. inrow += 2;
  166613. }
  166614. }
  166615. #ifdef INPUT_SMOOTHING_SUPPORTED
  166616. /*
  166617. * Downsample pixel values of a single component.
  166618. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166619. * with smoothing. One row of context is required.
  166620. */
  166621. METHODDEF(void)
  166622. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166623. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166624. {
  166625. int inrow, outrow;
  166626. JDIMENSION colctr;
  166627. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166628. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166629. INT32 membersum, neighsum, memberscale, neighscale;
  166630. /* Expand input data enough to let all the output samples be generated
  166631. * by the standard loop. Special-casing padded output would be more
  166632. * efficient.
  166633. */
  166634. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166635. cinfo->image_width, output_cols * 2);
  166636. /* We don't bother to form the individual "smoothed" input pixel values;
  166637. * we can directly compute the output which is the average of the four
  166638. * smoothed values. Each of the four member pixels contributes a fraction
  166639. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166640. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166641. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166642. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166643. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166644. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166645. * factors are scaled by 2^16 = 65536.
  166646. * Also recall that SF = smoothing_factor / 1024.
  166647. */
  166648. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166649. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166650. inrow = 0;
  166651. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166652. outptr = output_data[outrow];
  166653. inptr0 = input_data[inrow];
  166654. inptr1 = input_data[inrow+1];
  166655. above_ptr = input_data[inrow-1];
  166656. below_ptr = input_data[inrow+2];
  166657. /* Special case for first column: pretend column -1 is same as column 0 */
  166658. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166659. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166660. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166661. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166662. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  166663. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  166664. neighsum += neighsum;
  166665. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  166666. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  166667. membersum = membersum * memberscale + neighsum * neighscale;
  166668. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166669. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166670. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166671. /* sum of pixels directly mapped to this output element */
  166672. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166673. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166674. /* sum of edge-neighbor pixels */
  166675. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166676. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166677. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  166678. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  166679. /* The edge-neighbors count twice as much as corner-neighbors */
  166680. neighsum += neighsum;
  166681. /* Add in the corner-neighbors */
  166682. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  166683. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  166684. /* form final output scaled up by 2^16 */
  166685. membersum = membersum * memberscale + neighsum * neighscale;
  166686. /* round, descale and output it */
  166687. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166688. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  166689. }
  166690. /* Special case for last column */
  166691. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166692. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166693. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166694. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  166695. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  166696. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  166697. neighsum += neighsum;
  166698. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  166699. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  166700. membersum = membersum * memberscale + neighsum * neighscale;
  166701. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166702. inrow += 2;
  166703. }
  166704. }
  166705. /*
  166706. * Downsample pixel values of a single component.
  166707. * This version handles the special case of a full-size component,
  166708. * with smoothing. One row of context is required.
  166709. */
  166710. METHODDEF(void)
  166711. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  166712. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166713. {
  166714. int outrow;
  166715. JDIMENSION colctr;
  166716. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166717. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  166718. INT32 membersum, neighsum, memberscale, neighscale;
  166719. int colsum, lastcolsum, nextcolsum;
  166720. /* Expand input data enough to let all the output samples be generated
  166721. * by the standard loop. Special-casing padded output would be more
  166722. * efficient.
  166723. */
  166724. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166725. cinfo->image_width, output_cols);
  166726. /* Each of the eight neighbor pixels contributes a fraction SF to the
  166727. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  166728. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  166729. * Also recall that SF = smoothing_factor / 1024.
  166730. */
  166731. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  166732. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  166733. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166734. outptr = output_data[outrow];
  166735. inptr = input_data[outrow];
  166736. above_ptr = input_data[outrow-1];
  166737. below_ptr = input_data[outrow+1];
  166738. /* Special case for first column */
  166739. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  166740. GETJSAMPLE(*inptr);
  166741. membersum = GETJSAMPLE(*inptr++);
  166742. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166743. GETJSAMPLE(*inptr);
  166744. neighsum = colsum + (colsum - membersum) + nextcolsum;
  166745. membersum = membersum * memberscale + neighsum * neighscale;
  166746. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166747. lastcolsum = colsum; colsum = nextcolsum;
  166748. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  166749. membersum = GETJSAMPLE(*inptr++);
  166750. above_ptr++; below_ptr++;
  166751. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  166752. GETJSAMPLE(*inptr);
  166753. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  166754. membersum = membersum * memberscale + neighsum * neighscale;
  166755. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  166756. lastcolsum = colsum; colsum = nextcolsum;
  166757. }
  166758. /* Special case for last column */
  166759. membersum = GETJSAMPLE(*inptr);
  166760. neighsum = lastcolsum + (colsum - membersum) + colsum;
  166761. membersum = membersum * memberscale + neighsum * neighscale;
  166762. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  166763. }
  166764. }
  166765. #endif /* INPUT_SMOOTHING_SUPPORTED */
  166766. /*
  166767. * Module initialization routine for downsampling.
  166768. * Note that we must select a routine for each component.
  166769. */
  166770. GLOBAL(void)
  166771. jinit_downsampler (j_compress_ptr cinfo)
  166772. {
  166773. my_downsample_ptr downsample;
  166774. int ci;
  166775. jpeg_component_info * compptr;
  166776. boolean smoothok = TRUE;
  166777. downsample = (my_downsample_ptr)
  166778. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166779. SIZEOF(my_downsampler));
  166780. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  166781. downsample->pub.start_pass = start_pass_downsample;
  166782. downsample->pub.downsample = sep_downsample;
  166783. downsample->pub.need_context_rows = FALSE;
  166784. if (cinfo->CCIR601_sampling)
  166785. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  166786. /* Verify we can handle the sampling factors, and set up method pointers */
  166787. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166788. ci++, compptr++) {
  166789. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  166790. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166791. #ifdef INPUT_SMOOTHING_SUPPORTED
  166792. if (cinfo->smoothing_factor) {
  166793. downsample->methods[ci] = fullsize_smooth_downsample;
  166794. downsample->pub.need_context_rows = TRUE;
  166795. } else
  166796. #endif
  166797. downsample->methods[ci] = fullsize_downsample;
  166798. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166799. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  166800. smoothok = FALSE;
  166801. downsample->methods[ci] = h2v1_downsample;
  166802. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  166803. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  166804. #ifdef INPUT_SMOOTHING_SUPPORTED
  166805. if (cinfo->smoothing_factor) {
  166806. downsample->methods[ci] = h2v2_smooth_downsample;
  166807. downsample->pub.need_context_rows = TRUE;
  166808. } else
  166809. #endif
  166810. downsample->methods[ci] = h2v2_downsample;
  166811. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  166812. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  166813. smoothok = FALSE;
  166814. downsample->methods[ci] = int_downsample;
  166815. } else
  166816. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  166817. }
  166818. #ifdef INPUT_SMOOTHING_SUPPORTED
  166819. if (cinfo->smoothing_factor && !smoothok)
  166820. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  166821. #endif
  166822. }
  166823. /*** End of inlined file: jcsample.c ***/
  166824. /*** Start of inlined file: jctrans.c ***/
  166825. #define JPEG_INTERNALS
  166826. /* Forward declarations */
  166827. LOCAL(void) transencode_master_selection
  166828. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166829. LOCAL(void) transencode_coef_controller
  166830. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  166831. /*
  166832. * Compression initialization for writing raw-coefficient data.
  166833. * Before calling this, all parameters and a data destination must be set up.
  166834. * Call jpeg_finish_compress() to actually write the data.
  166835. *
  166836. * The number of passed virtual arrays must match cinfo->num_components.
  166837. * Note that the virtual arrays need not be filled or even realized at
  166838. * the time write_coefficients is called; indeed, if the virtual arrays
  166839. * were requested from this compression object's memory manager, they
  166840. * typically will be realized during this routine and filled afterwards.
  166841. */
  166842. GLOBAL(void)
  166843. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  166844. {
  166845. if (cinfo->global_state != CSTATE_START)
  166846. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166847. /* Mark all tables to be written */
  166848. jpeg_suppress_tables(cinfo, FALSE);
  166849. /* (Re)initialize error mgr and destination modules */
  166850. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166851. (*cinfo->dest->init_destination) (cinfo);
  166852. /* Perform master selection of active modules */
  166853. transencode_master_selection(cinfo, coef_arrays);
  166854. /* Wait for jpeg_finish_compress() call */
  166855. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  166856. cinfo->global_state = CSTATE_WRCOEFS;
  166857. }
  166858. /*
  166859. * Initialize the compression object with default parameters,
  166860. * then copy from the source object all parameters needed for lossless
  166861. * transcoding. Parameters that can be varied without loss (such as
  166862. * scan script and Huffman optimization) are left in their default states.
  166863. */
  166864. GLOBAL(void)
  166865. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  166866. j_compress_ptr dstinfo)
  166867. {
  166868. JQUANT_TBL ** qtblptr;
  166869. jpeg_component_info *incomp, *outcomp;
  166870. JQUANT_TBL *c_quant, *slot_quant;
  166871. int tblno, ci, coefi;
  166872. /* Safety check to ensure start_compress not called yet. */
  166873. if (dstinfo->global_state != CSTATE_START)
  166874. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  166875. /* Copy fundamental image dimensions */
  166876. dstinfo->image_width = srcinfo->image_width;
  166877. dstinfo->image_height = srcinfo->image_height;
  166878. dstinfo->input_components = srcinfo->num_components;
  166879. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  166880. /* Initialize all parameters to default values */
  166881. jpeg_set_defaults(dstinfo);
  166882. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  166883. * Fix it to get the right header markers for the image colorspace.
  166884. */
  166885. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  166886. dstinfo->data_precision = srcinfo->data_precision;
  166887. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  166888. /* Copy the source's quantization tables. */
  166889. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  166890. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  166891. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  166892. if (*qtblptr == NULL)
  166893. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  166894. MEMCOPY((*qtblptr)->quantval,
  166895. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  166896. SIZEOF((*qtblptr)->quantval));
  166897. (*qtblptr)->sent_table = FALSE;
  166898. }
  166899. }
  166900. /* Copy the source's per-component info.
  166901. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  166902. */
  166903. dstinfo->num_components = srcinfo->num_components;
  166904. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  166905. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  166906. MAX_COMPONENTS);
  166907. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  166908. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  166909. outcomp->component_id = incomp->component_id;
  166910. outcomp->h_samp_factor = incomp->h_samp_factor;
  166911. outcomp->v_samp_factor = incomp->v_samp_factor;
  166912. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  166913. /* Make sure saved quantization table for component matches the qtable
  166914. * slot. If not, the input file re-used this qtable slot.
  166915. * IJG encoder currently cannot duplicate this.
  166916. */
  166917. tblno = outcomp->quant_tbl_no;
  166918. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  166919. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  166920. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  166921. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  166922. c_quant = incomp->quant_table;
  166923. if (c_quant != NULL) {
  166924. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  166925. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  166926. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  166927. }
  166928. }
  166929. /* Note: we do not copy the source's Huffman table assignments;
  166930. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  166931. */
  166932. }
  166933. /* Also copy JFIF version and resolution information, if available.
  166934. * Strictly speaking this isn't "critical" info, but it's nearly
  166935. * always appropriate to copy it if available. In particular,
  166936. * if the application chooses to copy JFIF 1.02 extension markers from
  166937. * the source file, we need to copy the version to make sure we don't
  166938. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  166939. * We will *not*, however, copy version info from mislabeled "2.01" files.
  166940. */
  166941. if (srcinfo->saw_JFIF_marker) {
  166942. if (srcinfo->JFIF_major_version == 1) {
  166943. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  166944. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  166945. }
  166946. dstinfo->density_unit = srcinfo->density_unit;
  166947. dstinfo->X_density = srcinfo->X_density;
  166948. dstinfo->Y_density = srcinfo->Y_density;
  166949. }
  166950. }
  166951. /*
  166952. * Master selection of compression modules for transcoding.
  166953. * This substitutes for jcinit.c's initialization of the full compressor.
  166954. */
  166955. LOCAL(void)
  166956. transencode_master_selection (j_compress_ptr cinfo,
  166957. jvirt_barray_ptr * coef_arrays)
  166958. {
  166959. /* Although we don't actually use input_components for transcoding,
  166960. * jcmaster.c's initial_setup will complain if input_components is 0.
  166961. */
  166962. cinfo->input_components = 1;
  166963. /* Initialize master control (includes parameter checking/processing) */
  166964. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  166965. /* Entropy encoding: either Huffman or arithmetic coding. */
  166966. if (cinfo->arith_code) {
  166967. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  166968. } else {
  166969. if (cinfo->progressive_mode) {
  166970. #ifdef C_PROGRESSIVE_SUPPORTED
  166971. jinit_phuff_encoder(cinfo);
  166972. #else
  166973. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166974. #endif
  166975. } else
  166976. jinit_huff_encoder(cinfo);
  166977. }
  166978. /* We need a special coefficient buffer controller. */
  166979. transencode_coef_controller(cinfo, coef_arrays);
  166980. jinit_marker_writer(cinfo);
  166981. /* We can now tell the memory manager to allocate virtual arrays. */
  166982. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  166983. /* Write the datastream header (SOI, JFIF) immediately.
  166984. * Frame and scan headers are postponed till later.
  166985. * This lets application insert special markers after the SOI.
  166986. */
  166987. (*cinfo->marker->write_file_header) (cinfo);
  166988. }
  166989. /*
  166990. * The rest of this file is a special implementation of the coefficient
  166991. * buffer controller. This is similar to jccoefct.c, but it handles only
  166992. * output from presupplied virtual arrays. Furthermore, we generate any
  166993. * dummy padding blocks on-the-fly rather than expecting them to be present
  166994. * in the arrays.
  166995. */
  166996. /* Private buffer controller object */
  166997. typedef struct {
  166998. struct jpeg_c_coef_controller pub; /* public fields */
  166999. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167000. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167001. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167002. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167003. /* Virtual block array for each component. */
  167004. jvirt_barray_ptr * whole_image;
  167005. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167006. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167007. } my_coef_controller2;
  167008. typedef my_coef_controller2 * my_coef_ptr2;
  167009. LOCAL(void)
  167010. start_iMCU_row2 (j_compress_ptr cinfo)
  167011. /* Reset within-iMCU-row counters for a new row */
  167012. {
  167013. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167014. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167015. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167016. * But at the bottom of the image, process only what's left.
  167017. */
  167018. if (cinfo->comps_in_scan > 1) {
  167019. coef->MCU_rows_per_iMCU_row = 1;
  167020. } else {
  167021. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167022. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167023. else
  167024. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167025. }
  167026. coef->mcu_ctr = 0;
  167027. coef->MCU_vert_offset = 0;
  167028. }
  167029. /*
  167030. * Initialize for a processing pass.
  167031. */
  167032. METHODDEF(void)
  167033. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167034. {
  167035. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167036. if (pass_mode != JBUF_CRANK_DEST)
  167037. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167038. coef->iMCU_row_num = 0;
  167039. start_iMCU_row2(cinfo);
  167040. }
  167041. /*
  167042. * Process some data.
  167043. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167044. * per call, ie, v_samp_factor block rows for each component in the scan.
  167045. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167046. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167047. *
  167048. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167049. */
  167050. METHODDEF(boolean)
  167051. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167052. {
  167053. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167054. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167055. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167056. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167057. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167058. JDIMENSION start_col;
  167059. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167060. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167061. JBLOCKROW buffer_ptr;
  167062. jpeg_component_info *compptr;
  167063. /* Align the virtual buffers for the components used in this scan. */
  167064. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167065. compptr = cinfo->cur_comp_info[ci];
  167066. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167067. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167068. coef->iMCU_row_num * compptr->v_samp_factor,
  167069. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167070. }
  167071. /* Loop to process one whole iMCU row */
  167072. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167073. yoffset++) {
  167074. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167075. MCU_col_num++) {
  167076. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167077. blkn = 0; /* index of current DCT block within MCU */
  167078. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167079. compptr = cinfo->cur_comp_info[ci];
  167080. start_col = MCU_col_num * compptr->MCU_width;
  167081. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167082. : compptr->last_col_width;
  167083. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167084. if (coef->iMCU_row_num < last_iMCU_row ||
  167085. yindex+yoffset < compptr->last_row_height) {
  167086. /* Fill in pointers to real blocks in this row */
  167087. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167088. for (xindex = 0; xindex < blockcnt; xindex++)
  167089. MCU_buffer[blkn++] = buffer_ptr++;
  167090. } else {
  167091. /* At bottom of image, need a whole row of dummy blocks */
  167092. xindex = 0;
  167093. }
  167094. /* Fill in any dummy blocks needed in this row.
  167095. * Dummy blocks are filled in the same way as in jccoefct.c:
  167096. * all zeroes in the AC entries, DC entries equal to previous
  167097. * block's DC value. The init routine has already zeroed the
  167098. * AC entries, so we need only set the DC entries correctly.
  167099. */
  167100. for (; xindex < compptr->MCU_width; xindex++) {
  167101. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167102. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167103. blkn++;
  167104. }
  167105. }
  167106. }
  167107. /* Try to write the MCU. */
  167108. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167109. /* Suspension forced; update state counters and exit */
  167110. coef->MCU_vert_offset = yoffset;
  167111. coef->mcu_ctr = MCU_col_num;
  167112. return FALSE;
  167113. }
  167114. }
  167115. /* Completed an MCU row, but perhaps not an iMCU row */
  167116. coef->mcu_ctr = 0;
  167117. }
  167118. /* Completed the iMCU row, advance counters for next one */
  167119. coef->iMCU_row_num++;
  167120. start_iMCU_row2(cinfo);
  167121. return TRUE;
  167122. }
  167123. /*
  167124. * Initialize coefficient buffer controller.
  167125. *
  167126. * Each passed coefficient array must be the right size for that
  167127. * coefficient: width_in_blocks wide and height_in_blocks high,
  167128. * with unitheight at least v_samp_factor.
  167129. */
  167130. LOCAL(void)
  167131. transencode_coef_controller (j_compress_ptr cinfo,
  167132. jvirt_barray_ptr * coef_arrays)
  167133. {
  167134. my_coef_ptr2 coef;
  167135. JBLOCKROW buffer;
  167136. int i;
  167137. coef = (my_coef_ptr2)
  167138. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167139. SIZEOF(my_coef_controller2));
  167140. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167141. coef->pub.start_pass = start_pass_coef2;
  167142. coef->pub.compress_data = compress_output2;
  167143. /* Save pointer to virtual arrays */
  167144. coef->whole_image = coef_arrays;
  167145. /* Allocate and pre-zero space for dummy DCT blocks. */
  167146. buffer = (JBLOCKROW)
  167147. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167148. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167149. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167150. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167151. coef->dummy_buffer[i] = buffer + i;
  167152. }
  167153. }
  167154. /*** End of inlined file: jctrans.c ***/
  167155. /*** Start of inlined file: jdapistd.c ***/
  167156. #define JPEG_INTERNALS
  167157. /* Forward declarations */
  167158. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167159. /*
  167160. * Decompression initialization.
  167161. * jpeg_read_header must be completed before calling this.
  167162. *
  167163. * If a multipass operating mode was selected, this will do all but the
  167164. * last pass, and thus may take a great deal of time.
  167165. *
  167166. * Returns FALSE if suspended. The return value need be inspected only if
  167167. * a suspending data source is used.
  167168. */
  167169. GLOBAL(boolean)
  167170. jpeg_start_decompress (j_decompress_ptr cinfo)
  167171. {
  167172. if (cinfo->global_state == DSTATE_READY) {
  167173. /* First call: initialize master control, select active modules */
  167174. jinit_master_decompress(cinfo);
  167175. if (cinfo->buffered_image) {
  167176. /* No more work here; expecting jpeg_start_output next */
  167177. cinfo->global_state = DSTATE_BUFIMAGE;
  167178. return TRUE;
  167179. }
  167180. cinfo->global_state = DSTATE_PRELOAD;
  167181. }
  167182. if (cinfo->global_state == DSTATE_PRELOAD) {
  167183. /* If file has multiple scans, absorb them all into the coef buffer */
  167184. if (cinfo->inputctl->has_multiple_scans) {
  167185. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167186. for (;;) {
  167187. int retcode;
  167188. /* Call progress monitor hook if present */
  167189. if (cinfo->progress != NULL)
  167190. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167191. /* Absorb some more input */
  167192. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167193. if (retcode == JPEG_SUSPENDED)
  167194. return FALSE;
  167195. if (retcode == JPEG_REACHED_EOI)
  167196. break;
  167197. /* Advance progress counter if appropriate */
  167198. if (cinfo->progress != NULL &&
  167199. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167200. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167201. /* jdmaster underestimated number of scans; ratchet up one scan */
  167202. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167203. }
  167204. }
  167205. }
  167206. #else
  167207. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167208. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167209. }
  167210. cinfo->output_scan_number = cinfo->input_scan_number;
  167211. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167212. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167213. /* Perform any dummy output passes, and set up for the final pass */
  167214. return output_pass_setup(cinfo);
  167215. }
  167216. /*
  167217. * Set up for an output pass, and perform any dummy pass(es) needed.
  167218. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167219. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167220. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167221. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167222. */
  167223. LOCAL(boolean)
  167224. output_pass_setup (j_decompress_ptr cinfo)
  167225. {
  167226. if (cinfo->global_state != DSTATE_PRESCAN) {
  167227. /* First call: do pass setup */
  167228. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167229. cinfo->output_scanline = 0;
  167230. cinfo->global_state = DSTATE_PRESCAN;
  167231. }
  167232. /* Loop over any required dummy passes */
  167233. while (cinfo->master->is_dummy_pass) {
  167234. #ifdef QUANT_2PASS_SUPPORTED
  167235. /* Crank through the dummy pass */
  167236. while (cinfo->output_scanline < cinfo->output_height) {
  167237. JDIMENSION last_scanline;
  167238. /* Call progress monitor hook if present */
  167239. if (cinfo->progress != NULL) {
  167240. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167241. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167242. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167243. }
  167244. /* Process some data */
  167245. last_scanline = cinfo->output_scanline;
  167246. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167247. &cinfo->output_scanline, (JDIMENSION) 0);
  167248. if (cinfo->output_scanline == last_scanline)
  167249. return FALSE; /* No progress made, must suspend */
  167250. }
  167251. /* Finish up dummy pass, and set up for another one */
  167252. (*cinfo->master->finish_output_pass) (cinfo);
  167253. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167254. cinfo->output_scanline = 0;
  167255. #else
  167256. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167257. #endif /* QUANT_2PASS_SUPPORTED */
  167258. }
  167259. /* Ready for application to drive output pass through
  167260. * jpeg_read_scanlines or jpeg_read_raw_data.
  167261. */
  167262. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167263. return TRUE;
  167264. }
  167265. /*
  167266. * Read some scanlines of data from the JPEG decompressor.
  167267. *
  167268. * The return value will be the number of lines actually read.
  167269. * This may be less than the number requested in several cases,
  167270. * including bottom of image, data source suspension, and operating
  167271. * modes that emit multiple scanlines at a time.
  167272. *
  167273. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167274. * this likely signals an application programmer error. However,
  167275. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167276. */
  167277. GLOBAL(JDIMENSION)
  167278. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167279. JDIMENSION max_lines)
  167280. {
  167281. JDIMENSION row_ctr;
  167282. if (cinfo->global_state != DSTATE_SCANNING)
  167283. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167284. if (cinfo->output_scanline >= cinfo->output_height) {
  167285. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167286. return 0;
  167287. }
  167288. /* Call progress monitor hook if present */
  167289. if (cinfo->progress != NULL) {
  167290. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167291. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167292. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167293. }
  167294. /* Process some data */
  167295. row_ctr = 0;
  167296. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167297. cinfo->output_scanline += row_ctr;
  167298. return row_ctr;
  167299. }
  167300. /*
  167301. * Alternate entry point to read raw data.
  167302. * Processes exactly one iMCU row per call, unless suspended.
  167303. */
  167304. GLOBAL(JDIMENSION)
  167305. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167306. JDIMENSION max_lines)
  167307. {
  167308. JDIMENSION lines_per_iMCU_row;
  167309. if (cinfo->global_state != DSTATE_RAW_OK)
  167310. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167311. if (cinfo->output_scanline >= cinfo->output_height) {
  167312. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167313. return 0;
  167314. }
  167315. /* Call progress monitor hook if present */
  167316. if (cinfo->progress != NULL) {
  167317. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167318. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167319. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167320. }
  167321. /* Verify that at least one iMCU row can be returned. */
  167322. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167323. if (max_lines < lines_per_iMCU_row)
  167324. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167325. /* Decompress directly into user's buffer. */
  167326. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167327. return 0; /* suspension forced, can do nothing more */
  167328. /* OK, we processed one iMCU row. */
  167329. cinfo->output_scanline += lines_per_iMCU_row;
  167330. return lines_per_iMCU_row;
  167331. }
  167332. /* Additional entry points for buffered-image mode. */
  167333. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167334. /*
  167335. * Initialize for an output pass in buffered-image mode.
  167336. */
  167337. GLOBAL(boolean)
  167338. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167339. {
  167340. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167341. cinfo->global_state != DSTATE_PRESCAN)
  167342. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167343. /* Limit scan number to valid range */
  167344. if (scan_number <= 0)
  167345. scan_number = 1;
  167346. if (cinfo->inputctl->eoi_reached &&
  167347. scan_number > cinfo->input_scan_number)
  167348. scan_number = cinfo->input_scan_number;
  167349. cinfo->output_scan_number = scan_number;
  167350. /* Perform any dummy output passes, and set up for the real pass */
  167351. return output_pass_setup(cinfo);
  167352. }
  167353. /*
  167354. * Finish up after an output pass in buffered-image mode.
  167355. *
  167356. * Returns FALSE if suspended. The return value need be inspected only if
  167357. * a suspending data source is used.
  167358. */
  167359. GLOBAL(boolean)
  167360. jpeg_finish_output (j_decompress_ptr cinfo)
  167361. {
  167362. if ((cinfo->global_state == DSTATE_SCANNING ||
  167363. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167364. /* Terminate this pass. */
  167365. /* We do not require the whole pass to have been completed. */
  167366. (*cinfo->master->finish_output_pass) (cinfo);
  167367. cinfo->global_state = DSTATE_BUFPOST;
  167368. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167369. /* BUFPOST = repeat call after a suspension, anything else is error */
  167370. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167371. }
  167372. /* Read markers looking for SOS or EOI */
  167373. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167374. ! cinfo->inputctl->eoi_reached) {
  167375. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167376. return FALSE; /* Suspend, come back later */
  167377. }
  167378. cinfo->global_state = DSTATE_BUFIMAGE;
  167379. return TRUE;
  167380. }
  167381. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167382. /*** End of inlined file: jdapistd.c ***/
  167383. /*** Start of inlined file: jdapimin.c ***/
  167384. #define JPEG_INTERNALS
  167385. /*
  167386. * Initialization of a JPEG decompression object.
  167387. * The error manager must already be set up (in case memory manager fails).
  167388. */
  167389. GLOBAL(void)
  167390. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167391. {
  167392. int i;
  167393. /* Guard against version mismatches between library and caller. */
  167394. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167395. if (version != JPEG_LIB_VERSION)
  167396. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167397. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167398. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167399. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167400. /* For debugging purposes, we zero the whole master structure.
  167401. * But the application has already set the err pointer, and may have set
  167402. * client_data, so we have to save and restore those fields.
  167403. * Note: if application hasn't set client_data, tools like Purify may
  167404. * complain here.
  167405. */
  167406. {
  167407. struct jpeg_error_mgr * err = cinfo->err;
  167408. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167409. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167410. cinfo->err = err;
  167411. cinfo->client_data = client_data;
  167412. }
  167413. cinfo->is_decompressor = TRUE;
  167414. /* Initialize a memory manager instance for this object */
  167415. jinit_memory_mgr((j_common_ptr) cinfo);
  167416. /* Zero out pointers to permanent structures. */
  167417. cinfo->progress = NULL;
  167418. cinfo->src = NULL;
  167419. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167420. cinfo->quant_tbl_ptrs[i] = NULL;
  167421. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167422. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167423. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167424. }
  167425. /* Initialize marker processor so application can override methods
  167426. * for COM, APPn markers before calling jpeg_read_header.
  167427. */
  167428. cinfo->marker_list = NULL;
  167429. jinit_marker_reader(cinfo);
  167430. /* And initialize the overall input controller. */
  167431. jinit_input_controller(cinfo);
  167432. /* OK, I'm ready */
  167433. cinfo->global_state = DSTATE_START;
  167434. }
  167435. /*
  167436. * Destruction of a JPEG decompression object
  167437. */
  167438. GLOBAL(void)
  167439. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167440. {
  167441. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167442. }
  167443. /*
  167444. * Abort processing of a JPEG decompression operation,
  167445. * but don't destroy the object itself.
  167446. */
  167447. GLOBAL(void)
  167448. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167449. {
  167450. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167451. }
  167452. /*
  167453. * Set default decompression parameters.
  167454. */
  167455. LOCAL(void)
  167456. default_decompress_parms (j_decompress_ptr cinfo)
  167457. {
  167458. /* Guess the input colorspace, and set output colorspace accordingly. */
  167459. /* (Wish JPEG committee had provided a real way to specify this...) */
  167460. /* Note application may override our guesses. */
  167461. switch (cinfo->num_components) {
  167462. case 1:
  167463. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167464. cinfo->out_color_space = JCS_GRAYSCALE;
  167465. break;
  167466. case 3:
  167467. if (cinfo->saw_JFIF_marker) {
  167468. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167469. } else if (cinfo->saw_Adobe_marker) {
  167470. switch (cinfo->Adobe_transform) {
  167471. case 0:
  167472. cinfo->jpeg_color_space = JCS_RGB;
  167473. break;
  167474. case 1:
  167475. cinfo->jpeg_color_space = JCS_YCbCr;
  167476. break;
  167477. default:
  167478. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167479. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167480. break;
  167481. }
  167482. } else {
  167483. /* Saw no special markers, try to guess from the component IDs */
  167484. int cid0 = cinfo->comp_info[0].component_id;
  167485. int cid1 = cinfo->comp_info[1].component_id;
  167486. int cid2 = cinfo->comp_info[2].component_id;
  167487. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167488. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167489. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167490. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167491. else {
  167492. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167493. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167494. }
  167495. }
  167496. /* Always guess RGB is proper output colorspace. */
  167497. cinfo->out_color_space = JCS_RGB;
  167498. break;
  167499. case 4:
  167500. if (cinfo->saw_Adobe_marker) {
  167501. switch (cinfo->Adobe_transform) {
  167502. case 0:
  167503. cinfo->jpeg_color_space = JCS_CMYK;
  167504. break;
  167505. case 2:
  167506. cinfo->jpeg_color_space = JCS_YCCK;
  167507. break;
  167508. default:
  167509. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167510. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167511. break;
  167512. }
  167513. } else {
  167514. /* No special markers, assume straight CMYK. */
  167515. cinfo->jpeg_color_space = JCS_CMYK;
  167516. }
  167517. cinfo->out_color_space = JCS_CMYK;
  167518. break;
  167519. default:
  167520. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167521. cinfo->out_color_space = JCS_UNKNOWN;
  167522. break;
  167523. }
  167524. /* Set defaults for other decompression parameters. */
  167525. cinfo->scale_num = 1; /* 1:1 scaling */
  167526. cinfo->scale_denom = 1;
  167527. cinfo->output_gamma = 1.0;
  167528. cinfo->buffered_image = FALSE;
  167529. cinfo->raw_data_out = FALSE;
  167530. cinfo->dct_method = JDCT_DEFAULT;
  167531. cinfo->do_fancy_upsampling = TRUE;
  167532. cinfo->do_block_smoothing = TRUE;
  167533. cinfo->quantize_colors = FALSE;
  167534. /* We set these in case application only sets quantize_colors. */
  167535. cinfo->dither_mode = JDITHER_FS;
  167536. #ifdef QUANT_2PASS_SUPPORTED
  167537. cinfo->two_pass_quantize = TRUE;
  167538. #else
  167539. cinfo->two_pass_quantize = FALSE;
  167540. #endif
  167541. cinfo->desired_number_of_colors = 256;
  167542. cinfo->colormap = NULL;
  167543. /* Initialize for no mode change in buffered-image mode. */
  167544. cinfo->enable_1pass_quant = FALSE;
  167545. cinfo->enable_external_quant = FALSE;
  167546. cinfo->enable_2pass_quant = FALSE;
  167547. }
  167548. /*
  167549. * Decompression startup: read start of JPEG datastream to see what's there.
  167550. * Need only initialize JPEG object and supply a data source before calling.
  167551. *
  167552. * This routine will read as far as the first SOS marker (ie, actual start of
  167553. * compressed data), and will save all tables and parameters in the JPEG
  167554. * object. It will also initialize the decompression parameters to default
  167555. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167556. * adjust the decompression parameters and then call jpeg_start_decompress.
  167557. * (Or, if the application only wanted to determine the image parameters,
  167558. * the data need not be decompressed. In that case, call jpeg_abort or
  167559. * jpeg_destroy to release any temporary space.)
  167560. * If an abbreviated (tables only) datastream is presented, the routine will
  167561. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167562. * re-use the JPEG object to read the abbreviated image datastream(s).
  167563. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167564. * The JPEG_SUSPENDED return code only occurs if the data source module
  167565. * requests suspension of the decompressor. In this case the application
  167566. * should load more source data and then re-call jpeg_read_header to resume
  167567. * processing.
  167568. * If a non-suspending data source is used and require_image is TRUE, then the
  167569. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167570. *
  167571. * This routine is now just a front end to jpeg_consume_input, with some
  167572. * extra error checking.
  167573. */
  167574. GLOBAL(int)
  167575. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167576. {
  167577. int retcode;
  167578. if (cinfo->global_state != DSTATE_START &&
  167579. cinfo->global_state != DSTATE_INHEADER)
  167580. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167581. retcode = jpeg_consume_input(cinfo);
  167582. switch (retcode) {
  167583. case JPEG_REACHED_SOS:
  167584. retcode = JPEG_HEADER_OK;
  167585. break;
  167586. case JPEG_REACHED_EOI:
  167587. if (require_image) /* Complain if application wanted an image */
  167588. ERREXIT(cinfo, JERR_NO_IMAGE);
  167589. /* Reset to start state; it would be safer to require the application to
  167590. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167591. * A side effect is to free any temporary memory (there shouldn't be any).
  167592. */
  167593. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167594. retcode = JPEG_HEADER_TABLES_ONLY;
  167595. break;
  167596. case JPEG_SUSPENDED:
  167597. /* no work */
  167598. break;
  167599. }
  167600. return retcode;
  167601. }
  167602. /*
  167603. * Consume data in advance of what the decompressor requires.
  167604. * This can be called at any time once the decompressor object has
  167605. * been created and a data source has been set up.
  167606. *
  167607. * This routine is essentially a state machine that handles a couple
  167608. * of critical state-transition actions, namely initial setup and
  167609. * transition from header scanning to ready-for-start_decompress.
  167610. * All the actual input is done via the input controller's consume_input
  167611. * method.
  167612. */
  167613. GLOBAL(int)
  167614. jpeg_consume_input (j_decompress_ptr cinfo)
  167615. {
  167616. int retcode = JPEG_SUSPENDED;
  167617. /* NB: every possible DSTATE value should be listed in this switch */
  167618. switch (cinfo->global_state) {
  167619. case DSTATE_START:
  167620. /* Start-of-datastream actions: reset appropriate modules */
  167621. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167622. /* Initialize application's data source module */
  167623. (*cinfo->src->init_source) (cinfo);
  167624. cinfo->global_state = DSTATE_INHEADER;
  167625. /*FALLTHROUGH*/
  167626. case DSTATE_INHEADER:
  167627. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167628. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167629. /* Set up default parameters based on header data */
  167630. default_decompress_parms(cinfo);
  167631. /* Set global state: ready for start_decompress */
  167632. cinfo->global_state = DSTATE_READY;
  167633. }
  167634. break;
  167635. case DSTATE_READY:
  167636. /* Can't advance past first SOS until start_decompress is called */
  167637. retcode = JPEG_REACHED_SOS;
  167638. break;
  167639. case DSTATE_PRELOAD:
  167640. case DSTATE_PRESCAN:
  167641. case DSTATE_SCANNING:
  167642. case DSTATE_RAW_OK:
  167643. case DSTATE_BUFIMAGE:
  167644. case DSTATE_BUFPOST:
  167645. case DSTATE_STOPPING:
  167646. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167647. break;
  167648. default:
  167649. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167650. }
  167651. return retcode;
  167652. }
  167653. /*
  167654. * Have we finished reading the input file?
  167655. */
  167656. GLOBAL(boolean)
  167657. jpeg_input_complete (j_decompress_ptr cinfo)
  167658. {
  167659. /* Check for valid jpeg object */
  167660. if (cinfo->global_state < DSTATE_START ||
  167661. cinfo->global_state > DSTATE_STOPPING)
  167662. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167663. return cinfo->inputctl->eoi_reached;
  167664. }
  167665. /*
  167666. * Is there more than one scan?
  167667. */
  167668. GLOBAL(boolean)
  167669. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  167670. {
  167671. /* Only valid after jpeg_read_header completes */
  167672. if (cinfo->global_state < DSTATE_READY ||
  167673. cinfo->global_state > DSTATE_STOPPING)
  167674. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167675. return cinfo->inputctl->has_multiple_scans;
  167676. }
  167677. /*
  167678. * Finish JPEG decompression.
  167679. *
  167680. * This will normally just verify the file trailer and release temp storage.
  167681. *
  167682. * Returns FALSE if suspended. The return value need be inspected only if
  167683. * a suspending data source is used.
  167684. */
  167685. GLOBAL(boolean)
  167686. jpeg_finish_decompress (j_decompress_ptr cinfo)
  167687. {
  167688. if ((cinfo->global_state == DSTATE_SCANNING ||
  167689. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  167690. /* Terminate final pass of non-buffered mode */
  167691. if (cinfo->output_scanline < cinfo->output_height)
  167692. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  167693. (*cinfo->master->finish_output_pass) (cinfo);
  167694. cinfo->global_state = DSTATE_STOPPING;
  167695. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  167696. /* Finishing after a buffered-image operation */
  167697. cinfo->global_state = DSTATE_STOPPING;
  167698. } else if (cinfo->global_state != DSTATE_STOPPING) {
  167699. /* STOPPING = repeat call after a suspension, anything else is error */
  167700. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167701. }
  167702. /* Read until EOI */
  167703. while (! cinfo->inputctl->eoi_reached) {
  167704. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167705. return FALSE; /* Suspend, come back later */
  167706. }
  167707. /* Do final cleanup */
  167708. (*cinfo->src->term_source) (cinfo);
  167709. /* We can use jpeg_abort to release memory and reset global_state */
  167710. jpeg_abort((j_common_ptr) cinfo);
  167711. return TRUE;
  167712. }
  167713. /*** End of inlined file: jdapimin.c ***/
  167714. /*** Start of inlined file: jdatasrc.c ***/
  167715. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  167716. /*** Start of inlined file: jerror.h ***/
  167717. /*
  167718. * To define the enum list of message codes, include this file without
  167719. * defining macro JMESSAGE. To create a message string table, include it
  167720. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  167721. */
  167722. #ifndef JMESSAGE
  167723. #ifndef JERROR_H
  167724. /* First time through, define the enum list */
  167725. #define JMAKE_ENUM_LIST
  167726. #else
  167727. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  167728. #define JMESSAGE(code,string)
  167729. #endif /* JERROR_H */
  167730. #endif /* JMESSAGE */
  167731. #ifdef JMAKE_ENUM_LIST
  167732. typedef enum {
  167733. #define JMESSAGE(code,string) code ,
  167734. #endif /* JMAKE_ENUM_LIST */
  167735. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  167736. /* For maintenance convenience, list is alphabetical by message code name */
  167737. JMESSAGE(JERR_ARITH_NOTIMPL,
  167738. "Sorry, there are legal restrictions on arithmetic coding")
  167739. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  167740. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  167741. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  167742. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  167743. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  167744. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  167745. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  167746. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  167747. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  167748. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  167749. JMESSAGE(JERR_BAD_LIB_VERSION,
  167750. "Wrong JPEG library version: library is %d, caller expects %d")
  167751. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  167752. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  167753. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  167754. JMESSAGE(JERR_BAD_PROGRESSION,
  167755. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  167756. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  167757. "Invalid progressive parameters at scan script entry %d")
  167758. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  167759. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  167760. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  167761. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  167762. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  167763. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  167764. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  167765. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  167766. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  167767. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  167768. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  167769. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  167770. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  167771. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  167772. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  167773. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  167774. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  167775. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  167776. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  167777. JMESSAGE(JERR_FILE_READ, "Input file read error")
  167778. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  167779. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  167780. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  167781. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  167782. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  167783. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  167784. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  167785. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  167786. "Cannot transcode due to multiple use of quantization table %d")
  167787. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  167788. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  167789. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  167790. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  167791. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  167792. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  167793. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  167794. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  167795. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  167796. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  167797. JMESSAGE(JERR_QUANT_COMPONENTS,
  167798. "Cannot quantize more than %d color components")
  167799. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  167800. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  167801. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  167802. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  167803. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  167804. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  167805. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  167806. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  167807. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  167808. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  167809. JMESSAGE(JERR_TFILE_WRITE,
  167810. "Write failed on temporary file --- out of disk space?")
  167811. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  167812. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  167813. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  167814. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  167815. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  167816. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  167817. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  167818. JMESSAGE(JMSG_VERSION, JVERSION)
  167819. JMESSAGE(JTRC_16BIT_TABLES,
  167820. "Caution: quantization tables are too coarse for baseline JPEG")
  167821. JMESSAGE(JTRC_ADOBE,
  167822. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  167823. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  167824. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  167825. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  167826. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  167827. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  167828. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  167829. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  167830. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  167831. JMESSAGE(JTRC_EOI, "End Of Image")
  167832. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  167833. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  167834. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  167835. "Warning: thumbnail image size does not match data length %u")
  167836. JMESSAGE(JTRC_JFIF_EXTENSION,
  167837. "JFIF extension marker: type 0x%02x, length %u")
  167838. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  167839. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  167840. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  167841. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  167842. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  167843. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  167844. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  167845. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  167846. JMESSAGE(JTRC_RST, "RST%d")
  167847. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  167848. "Smoothing not supported with nonstandard sampling ratios")
  167849. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  167850. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  167851. JMESSAGE(JTRC_SOI, "Start of Image")
  167852. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  167853. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  167854. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  167855. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  167856. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  167857. JMESSAGE(JTRC_THUMB_JPEG,
  167858. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  167859. JMESSAGE(JTRC_THUMB_PALETTE,
  167860. "JFIF extension marker: palette thumbnail image, length %u")
  167861. JMESSAGE(JTRC_THUMB_RGB,
  167862. "JFIF extension marker: RGB thumbnail image, length %u")
  167863. JMESSAGE(JTRC_UNKNOWN_IDS,
  167864. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  167865. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  167866. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  167867. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  167868. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  167869. "Inconsistent progression sequence for component %d coefficient %d")
  167870. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  167871. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  167872. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  167873. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  167874. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  167875. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  167876. JMESSAGE(JWRN_MUST_RESYNC,
  167877. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  167878. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  167879. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  167880. #ifdef JMAKE_ENUM_LIST
  167881. JMSG_LASTMSGCODE
  167882. } J_MESSAGE_CODE;
  167883. #undef JMAKE_ENUM_LIST
  167884. #endif /* JMAKE_ENUM_LIST */
  167885. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  167886. #undef JMESSAGE
  167887. #ifndef JERROR_H
  167888. #define JERROR_H
  167889. /* Macros to simplify using the error and trace message stuff */
  167890. /* The first parameter is either type of cinfo pointer */
  167891. /* Fatal errors (print message and exit) */
  167892. #define ERREXIT(cinfo,code) \
  167893. ((cinfo)->err->msg_code = (code), \
  167894. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167895. #define ERREXIT1(cinfo,code,p1) \
  167896. ((cinfo)->err->msg_code = (code), \
  167897. (cinfo)->err->msg_parm.i[0] = (p1), \
  167898. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167899. #define ERREXIT2(cinfo,code,p1,p2) \
  167900. ((cinfo)->err->msg_code = (code), \
  167901. (cinfo)->err->msg_parm.i[0] = (p1), \
  167902. (cinfo)->err->msg_parm.i[1] = (p2), \
  167903. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167904. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  167905. ((cinfo)->err->msg_code = (code), \
  167906. (cinfo)->err->msg_parm.i[0] = (p1), \
  167907. (cinfo)->err->msg_parm.i[1] = (p2), \
  167908. (cinfo)->err->msg_parm.i[2] = (p3), \
  167909. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167910. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  167911. ((cinfo)->err->msg_code = (code), \
  167912. (cinfo)->err->msg_parm.i[0] = (p1), \
  167913. (cinfo)->err->msg_parm.i[1] = (p2), \
  167914. (cinfo)->err->msg_parm.i[2] = (p3), \
  167915. (cinfo)->err->msg_parm.i[3] = (p4), \
  167916. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167917. #define ERREXITS(cinfo,code,str) \
  167918. ((cinfo)->err->msg_code = (code), \
  167919. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167920. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  167921. #define MAKESTMT(stuff) do { stuff } while (0)
  167922. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  167923. #define WARNMS(cinfo,code) \
  167924. ((cinfo)->err->msg_code = (code), \
  167925. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167926. #define WARNMS1(cinfo,code,p1) \
  167927. ((cinfo)->err->msg_code = (code), \
  167928. (cinfo)->err->msg_parm.i[0] = (p1), \
  167929. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167930. #define WARNMS2(cinfo,code,p1,p2) \
  167931. ((cinfo)->err->msg_code = (code), \
  167932. (cinfo)->err->msg_parm.i[0] = (p1), \
  167933. (cinfo)->err->msg_parm.i[1] = (p2), \
  167934. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  167935. /* Informational/debugging messages */
  167936. #define TRACEMS(cinfo,lvl,code) \
  167937. ((cinfo)->err->msg_code = (code), \
  167938. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167939. #define TRACEMS1(cinfo,lvl,code,p1) \
  167940. ((cinfo)->err->msg_code = (code), \
  167941. (cinfo)->err->msg_parm.i[0] = (p1), \
  167942. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167943. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  167944. ((cinfo)->err->msg_code = (code), \
  167945. (cinfo)->err->msg_parm.i[0] = (p1), \
  167946. (cinfo)->err->msg_parm.i[1] = (p2), \
  167947. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167948. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  167949. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167950. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  167951. (cinfo)->err->msg_code = (code); \
  167952. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167953. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  167954. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167955. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167956. (cinfo)->err->msg_code = (code); \
  167957. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167958. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  167959. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167960. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167961. _mp[4] = (p5); \
  167962. (cinfo)->err->msg_code = (code); \
  167963. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167964. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  167965. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  167966. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  167967. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  167968. (cinfo)->err->msg_code = (code); \
  167969. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  167970. #define TRACEMSS(cinfo,lvl,code,str) \
  167971. ((cinfo)->err->msg_code = (code), \
  167972. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  167973. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  167974. #endif /* JERROR_H */
  167975. /*** End of inlined file: jerror.h ***/
  167976. /* Expanded data source object for stdio input */
  167977. typedef struct {
  167978. struct jpeg_source_mgr pub; /* public fields */
  167979. FILE * infile; /* source stream */
  167980. JOCTET * buffer; /* start of buffer */
  167981. boolean start_of_file; /* have we gotten any data yet? */
  167982. } my_source_mgr;
  167983. typedef my_source_mgr * my_src_ptr;
  167984. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  167985. /*
  167986. * Initialize source --- called by jpeg_read_header
  167987. * before any data is actually read.
  167988. */
  167989. METHODDEF(void)
  167990. init_source (j_decompress_ptr cinfo)
  167991. {
  167992. my_src_ptr src = (my_src_ptr) cinfo->src;
  167993. /* We reset the empty-input-file flag for each image,
  167994. * but we don't clear the input buffer.
  167995. * This is correct behavior for reading a series of images from one source.
  167996. */
  167997. src->start_of_file = TRUE;
  167998. }
  167999. /*
  168000. * Fill the input buffer --- called whenever buffer is emptied.
  168001. *
  168002. * In typical applications, this should read fresh data into the buffer
  168003. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168004. * reset the pointer & count to the start of the buffer, and return TRUE
  168005. * indicating that the buffer has been reloaded. It is not necessary to
  168006. * fill the buffer entirely, only to obtain at least one more byte.
  168007. *
  168008. * There is no such thing as an EOF return. If the end of the file has been
  168009. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168010. * the buffer. In most cases, generating a warning message and inserting a
  168011. * fake EOI marker is the best course of action --- this will allow the
  168012. * decompressor to output however much of the image is there. However,
  168013. * the resulting error message is misleading if the real problem is an empty
  168014. * input file, so we handle that case specially.
  168015. *
  168016. * In applications that need to be able to suspend compression due to input
  168017. * not being available yet, a FALSE return indicates that no more data can be
  168018. * obtained right now, but more may be forthcoming later. In this situation,
  168019. * the decompressor will return to its caller (with an indication of the
  168020. * number of scanlines it has read, if any). The application should resume
  168021. * decompression after it has loaded more data into the input buffer. Note
  168022. * that there are substantial restrictions on the use of suspension --- see
  168023. * the documentation.
  168024. *
  168025. * When suspending, the decompressor will back up to a convenient restart point
  168026. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168027. * indicate where the restart point will be if the current call returns FALSE.
  168028. * Data beyond this point must be rescanned after resumption, so move it to
  168029. * the front of the buffer rather than discarding it.
  168030. */
  168031. METHODDEF(boolean)
  168032. fill_input_buffer (j_decompress_ptr cinfo)
  168033. {
  168034. my_src_ptr src = (my_src_ptr) cinfo->src;
  168035. size_t nbytes;
  168036. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168037. if (nbytes <= 0) {
  168038. if (src->start_of_file) /* Treat empty input file as fatal error */
  168039. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168040. WARNMS(cinfo, JWRN_JPEG_EOF);
  168041. /* Insert a fake EOI marker */
  168042. src->buffer[0] = (JOCTET) 0xFF;
  168043. src->buffer[1] = (JOCTET) JPEG_EOI;
  168044. nbytes = 2;
  168045. }
  168046. src->pub.next_input_byte = src->buffer;
  168047. src->pub.bytes_in_buffer = nbytes;
  168048. src->start_of_file = FALSE;
  168049. return TRUE;
  168050. }
  168051. /*
  168052. * Skip data --- used to skip over a potentially large amount of
  168053. * uninteresting data (such as an APPn marker).
  168054. *
  168055. * Writers of suspendable-input applications must note that skip_input_data
  168056. * is not granted the right to give a suspension return. If the skip extends
  168057. * beyond the data currently in the buffer, the buffer can be marked empty so
  168058. * that the next read will cause a fill_input_buffer call that can suspend.
  168059. * Arranging for additional bytes to be discarded before reloading the input
  168060. * buffer is the application writer's problem.
  168061. */
  168062. METHODDEF(void)
  168063. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168064. {
  168065. my_src_ptr src = (my_src_ptr) cinfo->src;
  168066. /* Just a dumb implementation for now. Could use fseek() except
  168067. * it doesn't work on pipes. Not clear that being smart is worth
  168068. * any trouble anyway --- large skips are infrequent.
  168069. */
  168070. if (num_bytes > 0) {
  168071. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168072. num_bytes -= (long) src->pub.bytes_in_buffer;
  168073. (void) fill_input_buffer(cinfo);
  168074. /* note we assume that fill_input_buffer will never return FALSE,
  168075. * so suspension need not be handled.
  168076. */
  168077. }
  168078. src->pub.next_input_byte += (size_t) num_bytes;
  168079. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168080. }
  168081. }
  168082. /*
  168083. * An additional method that can be provided by data source modules is the
  168084. * resync_to_restart method for error recovery in the presence of RST markers.
  168085. * For the moment, this source module just uses the default resync method
  168086. * provided by the JPEG library. That method assumes that no backtracking
  168087. * is possible.
  168088. */
  168089. /*
  168090. * Terminate source --- called by jpeg_finish_decompress
  168091. * after all data has been read. Often a no-op.
  168092. *
  168093. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168094. * application must deal with any cleanup that should happen even
  168095. * for error exit.
  168096. */
  168097. METHODDEF(void)
  168098. term_source (j_decompress_ptr)
  168099. {
  168100. /* no work necessary here */
  168101. }
  168102. /*
  168103. * Prepare for input from a stdio stream.
  168104. * The caller must have already opened the stream, and is responsible
  168105. * for closing it after finishing decompression.
  168106. */
  168107. GLOBAL(void)
  168108. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168109. {
  168110. my_src_ptr src;
  168111. /* The source object and input buffer are made permanent so that a series
  168112. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168113. * only before the first one. (If we discarded the buffer at the end of
  168114. * one image, we'd likely lose the start of the next one.)
  168115. * This makes it unsafe to use this manager and a different source
  168116. * manager serially with the same JPEG object. Caveat programmer.
  168117. */
  168118. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168119. cinfo->src = (struct jpeg_source_mgr *)
  168120. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168121. SIZEOF(my_source_mgr));
  168122. src = (my_src_ptr) cinfo->src;
  168123. src->buffer = (JOCTET *)
  168124. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168125. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168126. }
  168127. src = (my_src_ptr) cinfo->src;
  168128. src->pub.init_source = init_source;
  168129. src->pub.fill_input_buffer = fill_input_buffer;
  168130. src->pub.skip_input_data = skip_input_data;
  168131. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168132. src->pub.term_source = term_source;
  168133. src->infile = infile;
  168134. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168135. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168136. }
  168137. /*** End of inlined file: jdatasrc.c ***/
  168138. /*** Start of inlined file: jdcoefct.c ***/
  168139. #define JPEG_INTERNALS
  168140. /* Block smoothing is only applicable for progressive JPEG, so: */
  168141. #ifndef D_PROGRESSIVE_SUPPORTED
  168142. #undef BLOCK_SMOOTHING_SUPPORTED
  168143. #endif
  168144. /* Private buffer controller object */
  168145. typedef struct {
  168146. struct jpeg_d_coef_controller pub; /* public fields */
  168147. /* These variables keep track of the current location of the input side. */
  168148. /* cinfo->input_iMCU_row is also used for this. */
  168149. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168150. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168151. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168152. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168153. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168154. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168155. * and let the entropy decoder write into that workspace each time.
  168156. * (On 80x86, the workspace is FAR even though it's not really very big;
  168157. * this is to keep the module interfaces unchanged when a large coefficient
  168158. * buffer is necessary.)
  168159. * In multi-pass modes, this array points to the current MCU's blocks
  168160. * within the virtual arrays; it is used only by the input side.
  168161. */
  168162. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168163. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168164. /* In multi-pass modes, we need a virtual block array for each component. */
  168165. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168166. #endif
  168167. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168168. /* When doing block smoothing, we latch coefficient Al values here */
  168169. int * coef_bits_latch;
  168170. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168171. #endif
  168172. } my_coef_controller3;
  168173. typedef my_coef_controller3 * my_coef_ptr3;
  168174. /* Forward declarations */
  168175. METHODDEF(int) decompress_onepass
  168176. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168177. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168178. METHODDEF(int) decompress_data
  168179. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168180. #endif
  168181. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168182. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168183. METHODDEF(int) decompress_smooth_data
  168184. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168185. #endif
  168186. LOCAL(void)
  168187. start_iMCU_row3 (j_decompress_ptr cinfo)
  168188. /* Reset within-iMCU-row counters for a new row (input side) */
  168189. {
  168190. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168191. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168192. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168193. * But at the bottom of the image, process only what's left.
  168194. */
  168195. if (cinfo->comps_in_scan > 1) {
  168196. coef->MCU_rows_per_iMCU_row = 1;
  168197. } else {
  168198. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168199. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168200. else
  168201. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168202. }
  168203. coef->MCU_ctr = 0;
  168204. coef->MCU_vert_offset = 0;
  168205. }
  168206. /*
  168207. * Initialize for an input processing pass.
  168208. */
  168209. METHODDEF(void)
  168210. start_input_pass (j_decompress_ptr cinfo)
  168211. {
  168212. cinfo->input_iMCU_row = 0;
  168213. start_iMCU_row3(cinfo);
  168214. }
  168215. /*
  168216. * Initialize for an output processing pass.
  168217. */
  168218. METHODDEF(void)
  168219. start_output_pass (j_decompress_ptr cinfo)
  168220. {
  168221. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168222. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168223. /* If multipass, check to see whether to use block smoothing on this pass */
  168224. if (coef->pub.coef_arrays != NULL) {
  168225. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168226. coef->pub.decompress_data = decompress_smooth_data;
  168227. else
  168228. coef->pub.decompress_data = decompress_data;
  168229. }
  168230. #endif
  168231. cinfo->output_iMCU_row = 0;
  168232. }
  168233. /*
  168234. * Decompress and return some data in the single-pass case.
  168235. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168236. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168237. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168238. *
  168239. * NB: output_buf contains a plane for each component in image,
  168240. * which we index according to the component's SOF position.
  168241. */
  168242. METHODDEF(int)
  168243. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168244. {
  168245. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168246. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168247. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168248. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168249. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168250. JSAMPARRAY output_ptr;
  168251. JDIMENSION start_col, output_col;
  168252. jpeg_component_info *compptr;
  168253. inverse_DCT_method_ptr inverse_DCT;
  168254. /* Loop to process as much as one whole iMCU row */
  168255. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168256. yoffset++) {
  168257. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168258. MCU_col_num++) {
  168259. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168260. jzero_far((void FAR *) coef->MCU_buffer[0],
  168261. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168262. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168263. /* Suspension forced; update state counters and exit */
  168264. coef->MCU_vert_offset = yoffset;
  168265. coef->MCU_ctr = MCU_col_num;
  168266. return JPEG_SUSPENDED;
  168267. }
  168268. /* Determine where data should go in output_buf and do the IDCT thing.
  168269. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168270. * incremented past them!). Note the inner loop relies on having
  168271. * allocated the MCU_buffer[] blocks sequentially.
  168272. */
  168273. blkn = 0; /* index of current DCT block within MCU */
  168274. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168275. compptr = cinfo->cur_comp_info[ci];
  168276. /* Don't bother to IDCT an uninteresting component. */
  168277. if (! compptr->component_needed) {
  168278. blkn += compptr->MCU_blocks;
  168279. continue;
  168280. }
  168281. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168282. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168283. : compptr->last_col_width;
  168284. output_ptr = output_buf[compptr->component_index] +
  168285. yoffset * compptr->DCT_scaled_size;
  168286. start_col = MCU_col_num * compptr->MCU_sample_width;
  168287. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168288. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168289. yoffset+yindex < compptr->last_row_height) {
  168290. output_col = start_col;
  168291. for (xindex = 0; xindex < useful_width; xindex++) {
  168292. (*inverse_DCT) (cinfo, compptr,
  168293. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168294. output_ptr, output_col);
  168295. output_col += compptr->DCT_scaled_size;
  168296. }
  168297. }
  168298. blkn += compptr->MCU_width;
  168299. output_ptr += compptr->DCT_scaled_size;
  168300. }
  168301. }
  168302. }
  168303. /* Completed an MCU row, but perhaps not an iMCU row */
  168304. coef->MCU_ctr = 0;
  168305. }
  168306. /* Completed the iMCU row, advance counters for next one */
  168307. cinfo->output_iMCU_row++;
  168308. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168309. start_iMCU_row3(cinfo);
  168310. return JPEG_ROW_COMPLETED;
  168311. }
  168312. /* Completed the scan */
  168313. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168314. return JPEG_SCAN_COMPLETED;
  168315. }
  168316. /*
  168317. * Dummy consume-input routine for single-pass operation.
  168318. */
  168319. METHODDEF(int)
  168320. dummy_consume_data (j_decompress_ptr)
  168321. {
  168322. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168323. }
  168324. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168325. /*
  168326. * Consume input data and store it in the full-image coefficient buffer.
  168327. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168328. * ie, v_samp_factor block rows for each component in the scan.
  168329. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168330. */
  168331. METHODDEF(int)
  168332. consume_data (j_decompress_ptr cinfo)
  168333. {
  168334. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168335. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168336. int blkn, ci, xindex, yindex, yoffset;
  168337. JDIMENSION start_col;
  168338. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168339. JBLOCKROW buffer_ptr;
  168340. jpeg_component_info *compptr;
  168341. /* Align the virtual buffers for the components used in this scan. */
  168342. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168343. compptr = cinfo->cur_comp_info[ci];
  168344. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168345. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168346. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168347. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168348. /* Note: entropy decoder expects buffer to be zeroed,
  168349. * but this is handled automatically by the memory manager
  168350. * because we requested a pre-zeroed array.
  168351. */
  168352. }
  168353. /* Loop to process one whole iMCU row */
  168354. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168355. yoffset++) {
  168356. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168357. MCU_col_num++) {
  168358. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168359. blkn = 0; /* index of current DCT block within MCU */
  168360. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168361. compptr = cinfo->cur_comp_info[ci];
  168362. start_col = MCU_col_num * compptr->MCU_width;
  168363. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168364. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168365. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168366. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168367. }
  168368. }
  168369. }
  168370. /* Try to fetch the MCU. */
  168371. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168372. /* Suspension forced; update state counters and exit */
  168373. coef->MCU_vert_offset = yoffset;
  168374. coef->MCU_ctr = MCU_col_num;
  168375. return JPEG_SUSPENDED;
  168376. }
  168377. }
  168378. /* Completed an MCU row, but perhaps not an iMCU row */
  168379. coef->MCU_ctr = 0;
  168380. }
  168381. /* Completed the iMCU row, advance counters for next one */
  168382. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168383. start_iMCU_row3(cinfo);
  168384. return JPEG_ROW_COMPLETED;
  168385. }
  168386. /* Completed the scan */
  168387. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168388. return JPEG_SCAN_COMPLETED;
  168389. }
  168390. /*
  168391. * Decompress and return some data in the multi-pass case.
  168392. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168393. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168394. *
  168395. * NB: output_buf contains a plane for each component in image.
  168396. */
  168397. METHODDEF(int)
  168398. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168399. {
  168400. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168401. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168402. JDIMENSION block_num;
  168403. int ci, block_row, block_rows;
  168404. JBLOCKARRAY buffer;
  168405. JBLOCKROW buffer_ptr;
  168406. JSAMPARRAY output_ptr;
  168407. JDIMENSION output_col;
  168408. jpeg_component_info *compptr;
  168409. inverse_DCT_method_ptr inverse_DCT;
  168410. /* Force some input to be done if we are getting ahead of the input. */
  168411. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168412. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168413. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168414. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168415. return JPEG_SUSPENDED;
  168416. }
  168417. /* OK, output from the virtual arrays. */
  168418. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168419. ci++, compptr++) {
  168420. /* Don't bother to IDCT an uninteresting component. */
  168421. if (! compptr->component_needed)
  168422. continue;
  168423. /* Align the virtual buffer for this component. */
  168424. buffer = (*cinfo->mem->access_virt_barray)
  168425. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168426. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168427. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168428. /* Count non-dummy DCT block rows in this iMCU row. */
  168429. if (cinfo->output_iMCU_row < last_iMCU_row)
  168430. block_rows = compptr->v_samp_factor;
  168431. else {
  168432. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168433. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168434. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168435. }
  168436. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168437. output_ptr = output_buf[ci];
  168438. /* Loop over all DCT blocks to be processed. */
  168439. for (block_row = 0; block_row < block_rows; block_row++) {
  168440. buffer_ptr = buffer[block_row];
  168441. output_col = 0;
  168442. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168443. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168444. output_ptr, output_col);
  168445. buffer_ptr++;
  168446. output_col += compptr->DCT_scaled_size;
  168447. }
  168448. output_ptr += compptr->DCT_scaled_size;
  168449. }
  168450. }
  168451. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168452. return JPEG_ROW_COMPLETED;
  168453. return JPEG_SCAN_COMPLETED;
  168454. }
  168455. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168456. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168457. /*
  168458. * This code applies interblock smoothing as described by section K.8
  168459. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168460. * the DC values of a DCT block and its 8 neighboring blocks.
  168461. * We apply smoothing only for progressive JPEG decoding, and only if
  168462. * the coefficients it can estimate are not yet known to full precision.
  168463. */
  168464. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168465. #define Q01_POS 1
  168466. #define Q10_POS 8
  168467. #define Q20_POS 16
  168468. #define Q11_POS 9
  168469. #define Q02_POS 2
  168470. /*
  168471. * Determine whether block smoothing is applicable and safe.
  168472. * We also latch the current states of the coef_bits[] entries for the
  168473. * AC coefficients; otherwise, if the input side of the decompressor
  168474. * advances into a new scan, we might think the coefficients are known
  168475. * more accurately than they really are.
  168476. */
  168477. LOCAL(boolean)
  168478. smoothing_ok (j_decompress_ptr cinfo)
  168479. {
  168480. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168481. boolean smoothing_useful = FALSE;
  168482. int ci, coefi;
  168483. jpeg_component_info *compptr;
  168484. JQUANT_TBL * qtable;
  168485. int * coef_bits;
  168486. int * coef_bits_latch;
  168487. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168488. return FALSE;
  168489. /* Allocate latch area if not already done */
  168490. if (coef->coef_bits_latch == NULL)
  168491. coef->coef_bits_latch = (int *)
  168492. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168493. cinfo->num_components *
  168494. (SAVED_COEFS * SIZEOF(int)));
  168495. coef_bits_latch = coef->coef_bits_latch;
  168496. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168497. ci++, compptr++) {
  168498. /* All components' quantization values must already be latched. */
  168499. if ((qtable = compptr->quant_table) == NULL)
  168500. return FALSE;
  168501. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168502. if (qtable->quantval[0] == 0 ||
  168503. qtable->quantval[Q01_POS] == 0 ||
  168504. qtable->quantval[Q10_POS] == 0 ||
  168505. qtable->quantval[Q20_POS] == 0 ||
  168506. qtable->quantval[Q11_POS] == 0 ||
  168507. qtable->quantval[Q02_POS] == 0)
  168508. return FALSE;
  168509. /* DC values must be at least partly known for all components. */
  168510. coef_bits = cinfo->coef_bits[ci];
  168511. if (coef_bits[0] < 0)
  168512. return FALSE;
  168513. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168514. for (coefi = 1; coefi <= 5; coefi++) {
  168515. coef_bits_latch[coefi] = coef_bits[coefi];
  168516. if (coef_bits[coefi] != 0)
  168517. smoothing_useful = TRUE;
  168518. }
  168519. coef_bits_latch += SAVED_COEFS;
  168520. }
  168521. return smoothing_useful;
  168522. }
  168523. /*
  168524. * Variant of decompress_data for use when doing block smoothing.
  168525. */
  168526. METHODDEF(int)
  168527. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168528. {
  168529. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168530. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168531. JDIMENSION block_num, last_block_column;
  168532. int ci, block_row, block_rows, access_rows;
  168533. JBLOCKARRAY buffer;
  168534. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168535. JSAMPARRAY output_ptr;
  168536. JDIMENSION output_col;
  168537. jpeg_component_info *compptr;
  168538. inverse_DCT_method_ptr inverse_DCT;
  168539. boolean first_row, last_row;
  168540. JBLOCK workspace;
  168541. int *coef_bits;
  168542. JQUANT_TBL *quanttbl;
  168543. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168544. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168545. int Al, pred;
  168546. /* Force some input to be done if we are getting ahead of the input. */
  168547. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168548. ! cinfo->inputctl->eoi_reached) {
  168549. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168550. /* If input is working on current scan, we ordinarily want it to
  168551. * have completed the current row. But if input scan is DC,
  168552. * we want it to keep one row ahead so that next block row's DC
  168553. * values are up to date.
  168554. */
  168555. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168556. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168557. break;
  168558. }
  168559. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168560. return JPEG_SUSPENDED;
  168561. }
  168562. /* OK, output from the virtual arrays. */
  168563. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168564. ci++, compptr++) {
  168565. /* Don't bother to IDCT an uninteresting component. */
  168566. if (! compptr->component_needed)
  168567. continue;
  168568. /* Count non-dummy DCT block rows in this iMCU row. */
  168569. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168570. block_rows = compptr->v_samp_factor;
  168571. access_rows = block_rows * 2; /* this and next iMCU row */
  168572. last_row = FALSE;
  168573. } else {
  168574. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168575. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168576. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168577. access_rows = block_rows; /* this iMCU row only */
  168578. last_row = TRUE;
  168579. }
  168580. /* Align the virtual buffer for this component. */
  168581. if (cinfo->output_iMCU_row > 0) {
  168582. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168583. buffer = (*cinfo->mem->access_virt_barray)
  168584. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168585. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168586. (JDIMENSION) access_rows, FALSE);
  168587. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168588. first_row = FALSE;
  168589. } else {
  168590. buffer = (*cinfo->mem->access_virt_barray)
  168591. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168592. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168593. first_row = TRUE;
  168594. }
  168595. /* Fetch component-dependent info */
  168596. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168597. quanttbl = compptr->quant_table;
  168598. Q00 = quanttbl->quantval[0];
  168599. Q01 = quanttbl->quantval[Q01_POS];
  168600. Q10 = quanttbl->quantval[Q10_POS];
  168601. Q20 = quanttbl->quantval[Q20_POS];
  168602. Q11 = quanttbl->quantval[Q11_POS];
  168603. Q02 = quanttbl->quantval[Q02_POS];
  168604. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168605. output_ptr = output_buf[ci];
  168606. /* Loop over all DCT blocks to be processed. */
  168607. for (block_row = 0; block_row < block_rows; block_row++) {
  168608. buffer_ptr = buffer[block_row];
  168609. if (first_row && block_row == 0)
  168610. prev_block_row = buffer_ptr;
  168611. else
  168612. prev_block_row = buffer[block_row-1];
  168613. if (last_row && block_row == block_rows-1)
  168614. next_block_row = buffer_ptr;
  168615. else
  168616. next_block_row = buffer[block_row+1];
  168617. /* We fetch the surrounding DC values using a sliding-register approach.
  168618. * Initialize all nine here so as to do the right thing on narrow pics.
  168619. */
  168620. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168621. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168622. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168623. output_col = 0;
  168624. last_block_column = compptr->width_in_blocks - 1;
  168625. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168626. /* Fetch current DCT block into workspace so we can modify it. */
  168627. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168628. /* Update DC values */
  168629. if (block_num < last_block_column) {
  168630. DC3 = (int) prev_block_row[1][0];
  168631. DC6 = (int) buffer_ptr[1][0];
  168632. DC9 = (int) next_block_row[1][0];
  168633. }
  168634. /* Compute coefficient estimates per K.8.
  168635. * An estimate is applied only if coefficient is still zero,
  168636. * and is not known to be fully accurate.
  168637. */
  168638. /* AC01 */
  168639. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168640. num = 36 * Q00 * (DC4 - DC6);
  168641. if (num >= 0) {
  168642. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168643. if (Al > 0 && pred >= (1<<Al))
  168644. pred = (1<<Al)-1;
  168645. } else {
  168646. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168647. if (Al > 0 && pred >= (1<<Al))
  168648. pred = (1<<Al)-1;
  168649. pred = -pred;
  168650. }
  168651. workspace[1] = (JCOEF) pred;
  168652. }
  168653. /* AC10 */
  168654. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168655. num = 36 * Q00 * (DC2 - DC8);
  168656. if (num >= 0) {
  168657. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168658. if (Al > 0 && pred >= (1<<Al))
  168659. pred = (1<<Al)-1;
  168660. } else {
  168661. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  168662. if (Al > 0 && pred >= (1<<Al))
  168663. pred = (1<<Al)-1;
  168664. pred = -pred;
  168665. }
  168666. workspace[8] = (JCOEF) pred;
  168667. }
  168668. /* AC20 */
  168669. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  168670. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  168671. if (num >= 0) {
  168672. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  168673. if (Al > 0 && pred >= (1<<Al))
  168674. pred = (1<<Al)-1;
  168675. } else {
  168676. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  168677. if (Al > 0 && pred >= (1<<Al))
  168678. pred = (1<<Al)-1;
  168679. pred = -pred;
  168680. }
  168681. workspace[16] = (JCOEF) pred;
  168682. }
  168683. /* AC11 */
  168684. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  168685. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  168686. if (num >= 0) {
  168687. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  168688. if (Al > 0 && pred >= (1<<Al))
  168689. pred = (1<<Al)-1;
  168690. } else {
  168691. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  168692. if (Al > 0 && pred >= (1<<Al))
  168693. pred = (1<<Al)-1;
  168694. pred = -pred;
  168695. }
  168696. workspace[9] = (JCOEF) pred;
  168697. }
  168698. /* AC02 */
  168699. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  168700. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  168701. if (num >= 0) {
  168702. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  168703. if (Al > 0 && pred >= (1<<Al))
  168704. pred = (1<<Al)-1;
  168705. } else {
  168706. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  168707. if (Al > 0 && pred >= (1<<Al))
  168708. pred = (1<<Al)-1;
  168709. pred = -pred;
  168710. }
  168711. workspace[2] = (JCOEF) pred;
  168712. }
  168713. /* OK, do the IDCT */
  168714. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  168715. output_ptr, output_col);
  168716. /* Advance for next column */
  168717. DC1 = DC2; DC2 = DC3;
  168718. DC4 = DC5; DC5 = DC6;
  168719. DC7 = DC8; DC8 = DC9;
  168720. buffer_ptr++, prev_block_row++, next_block_row++;
  168721. output_col += compptr->DCT_scaled_size;
  168722. }
  168723. output_ptr += compptr->DCT_scaled_size;
  168724. }
  168725. }
  168726. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168727. return JPEG_ROW_COMPLETED;
  168728. return JPEG_SCAN_COMPLETED;
  168729. }
  168730. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  168731. /*
  168732. * Initialize coefficient buffer controller.
  168733. */
  168734. GLOBAL(void)
  168735. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  168736. {
  168737. my_coef_ptr3 coef;
  168738. coef = (my_coef_ptr3)
  168739. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168740. SIZEOF(my_coef_controller3));
  168741. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  168742. coef->pub.start_input_pass = start_input_pass;
  168743. coef->pub.start_output_pass = start_output_pass;
  168744. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168745. coef->coef_bits_latch = NULL;
  168746. #endif
  168747. /* Create the coefficient buffer. */
  168748. if (need_full_buffer) {
  168749. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168750. /* Allocate a full-image virtual array for each component, */
  168751. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  168752. /* Note we ask for a pre-zeroed array. */
  168753. int ci, access_rows;
  168754. jpeg_component_info *compptr;
  168755. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168756. ci++, compptr++) {
  168757. access_rows = compptr->v_samp_factor;
  168758. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168759. /* If block smoothing could be used, need a bigger window */
  168760. if (cinfo->progressive_mode)
  168761. access_rows *= 3;
  168762. #endif
  168763. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  168764. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  168765. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  168766. (long) compptr->h_samp_factor),
  168767. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  168768. (long) compptr->v_samp_factor),
  168769. (JDIMENSION) access_rows);
  168770. }
  168771. coef->pub.consume_data = consume_data;
  168772. coef->pub.decompress_data = decompress_data;
  168773. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  168774. #else
  168775. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168776. #endif
  168777. } else {
  168778. /* We only need a single-MCU buffer. */
  168779. JBLOCKROW buffer;
  168780. int i;
  168781. buffer = (JBLOCKROW)
  168782. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168783. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168784. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  168785. coef->MCU_buffer[i] = buffer + i;
  168786. }
  168787. coef->pub.consume_data = dummy_consume_data;
  168788. coef->pub.decompress_data = decompress_onepass;
  168789. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  168790. }
  168791. }
  168792. /*** End of inlined file: jdcoefct.c ***/
  168793. #undef FIX
  168794. /*** Start of inlined file: jdcolor.c ***/
  168795. #define JPEG_INTERNALS
  168796. /* Private subobject */
  168797. typedef struct {
  168798. struct jpeg_color_deconverter pub; /* public fields */
  168799. /* Private state for YCC->RGB conversion */
  168800. int * Cr_r_tab; /* => table for Cr to R conversion */
  168801. int * Cb_b_tab; /* => table for Cb to B conversion */
  168802. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168803. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168804. } my_color_deconverter2;
  168805. typedef my_color_deconverter2 * my_cconvert_ptr2;
  168806. /**************** YCbCr -> RGB conversion: most common case **************/
  168807. /*
  168808. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  168809. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  168810. * The conversion equations to be implemented are therefore
  168811. * R = Y + 1.40200 * Cr
  168812. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  168813. * B = Y + 1.77200 * Cb
  168814. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  168815. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  168816. *
  168817. * To avoid floating-point arithmetic, we represent the fractional constants
  168818. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  168819. * the products by 2^16, with appropriate rounding, to get the correct answer.
  168820. * Notice that Y, being an integral input, does not contribute any fraction
  168821. * so it need not participate in the rounding.
  168822. *
  168823. * For even more speed, we avoid doing any multiplications in the inner loop
  168824. * by precalculating the constants times Cb and Cr for all possible values.
  168825. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  168826. * for 12-bit samples it is still acceptable. It's not very reasonable for
  168827. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  168828. * colorspace anyway.
  168829. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  168830. * values for the G calculation are left scaled up, since we must add them
  168831. * together before rounding.
  168832. */
  168833. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168834. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168835. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168836. /*
  168837. * Initialize tables for YCC->RGB colorspace conversion.
  168838. */
  168839. LOCAL(void)
  168840. build_ycc_rgb_table (j_decompress_ptr cinfo)
  168841. {
  168842. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168843. int i;
  168844. INT32 x;
  168845. SHIFT_TEMPS
  168846. cconvert->Cr_r_tab = (int *)
  168847. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168848. (MAXJSAMPLE+1) * SIZEOF(int));
  168849. cconvert->Cb_b_tab = (int *)
  168850. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168851. (MAXJSAMPLE+1) * SIZEOF(int));
  168852. cconvert->Cr_g_tab = (INT32 *)
  168853. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168854. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168855. cconvert->Cb_g_tab = (INT32 *)
  168856. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168857. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168858. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168859. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168860. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168861. /* Cr=>R value is nearest int to 1.40200 * x */
  168862. cconvert->Cr_r_tab[i] = (int)
  168863. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168864. /* Cb=>B value is nearest int to 1.77200 * x */
  168865. cconvert->Cb_b_tab[i] = (int)
  168866. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168867. /* Cr=>G value is scaled-up -0.71414 * x */
  168868. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168869. /* Cb=>G value is scaled-up -0.34414 * x */
  168870. /* We also add in ONE_HALF so that need not do it in inner loop */
  168871. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168872. }
  168873. }
  168874. /*
  168875. * Convert some rows of samples to the output colorspace.
  168876. *
  168877. * Note that we change from noninterleaved, one-plane-per-component format
  168878. * to interleaved-pixel format. The output buffer is therefore three times
  168879. * as wide as the input buffer.
  168880. * A starting row offset is provided only for the input buffer. The caller
  168881. * can easily adjust the passed output_buf value to accommodate any row
  168882. * offset required on that side.
  168883. */
  168884. METHODDEF(void)
  168885. ycc_rgb_convert (j_decompress_ptr cinfo,
  168886. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168887. JSAMPARRAY output_buf, int num_rows)
  168888. {
  168889. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168890. register int y, cb, cr;
  168891. register JSAMPROW outptr;
  168892. register JSAMPROW inptr0, inptr1, inptr2;
  168893. register JDIMENSION col;
  168894. JDIMENSION num_cols = cinfo->output_width;
  168895. /* copy these pointers into registers if possible */
  168896. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168897. register int * Crrtab = cconvert->Cr_r_tab;
  168898. register int * Cbbtab = cconvert->Cb_b_tab;
  168899. register INT32 * Crgtab = cconvert->Cr_g_tab;
  168900. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  168901. SHIFT_TEMPS
  168902. while (--num_rows >= 0) {
  168903. inptr0 = input_buf[0][input_row];
  168904. inptr1 = input_buf[1][input_row];
  168905. inptr2 = input_buf[2][input_row];
  168906. input_row++;
  168907. outptr = *output_buf++;
  168908. for (col = 0; col < num_cols; col++) {
  168909. y = GETJSAMPLE(inptr0[col]);
  168910. cb = GETJSAMPLE(inptr1[col]);
  168911. cr = GETJSAMPLE(inptr2[col]);
  168912. /* Range-limiting is essential due to noise introduced by DCT losses. */
  168913. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  168914. outptr[RGB_GREEN] = range_limit[y +
  168915. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  168916. SCALEBITS))];
  168917. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  168918. outptr += RGB_PIXELSIZE;
  168919. }
  168920. }
  168921. }
  168922. /**************** Cases other than YCbCr -> RGB **************/
  168923. /*
  168924. * Color conversion for no colorspace change: just copy the data,
  168925. * converting from separate-planes to interleaved representation.
  168926. */
  168927. METHODDEF(void)
  168928. null_convert2 (j_decompress_ptr cinfo,
  168929. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168930. JSAMPARRAY output_buf, int num_rows)
  168931. {
  168932. register JSAMPROW inptr, outptr;
  168933. register JDIMENSION count;
  168934. register int num_components = cinfo->num_components;
  168935. JDIMENSION num_cols = cinfo->output_width;
  168936. int ci;
  168937. while (--num_rows >= 0) {
  168938. for (ci = 0; ci < num_components; ci++) {
  168939. inptr = input_buf[ci][input_row];
  168940. outptr = output_buf[0] + ci;
  168941. for (count = num_cols; count > 0; count--) {
  168942. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  168943. outptr += num_components;
  168944. }
  168945. }
  168946. input_row++;
  168947. output_buf++;
  168948. }
  168949. }
  168950. /*
  168951. * Color conversion for grayscale: just copy the data.
  168952. * This also works for YCbCr -> grayscale conversion, in which
  168953. * we just copy the Y (luminance) component and ignore chrominance.
  168954. */
  168955. METHODDEF(void)
  168956. grayscale_convert2 (j_decompress_ptr cinfo,
  168957. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168958. JSAMPARRAY output_buf, int num_rows)
  168959. {
  168960. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  168961. num_rows, cinfo->output_width);
  168962. }
  168963. /*
  168964. * Convert grayscale to RGB: just duplicate the graylevel three times.
  168965. * This is provided to support applications that don't want to cope
  168966. * with grayscale as a separate case.
  168967. */
  168968. METHODDEF(void)
  168969. gray_rgb_convert (j_decompress_ptr cinfo,
  168970. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168971. JSAMPARRAY output_buf, int num_rows)
  168972. {
  168973. register JSAMPROW inptr, outptr;
  168974. register JDIMENSION col;
  168975. JDIMENSION num_cols = cinfo->output_width;
  168976. while (--num_rows >= 0) {
  168977. inptr = input_buf[0][input_row++];
  168978. outptr = *output_buf++;
  168979. for (col = 0; col < num_cols; col++) {
  168980. /* We can dispense with GETJSAMPLE() here */
  168981. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  168982. outptr += RGB_PIXELSIZE;
  168983. }
  168984. }
  168985. }
  168986. /*
  168987. * Adobe-style YCCK->CMYK conversion.
  168988. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  168989. * conversion as above, while passing K (black) unchanged.
  168990. * We assume build_ycc_rgb_table has been called.
  168991. */
  168992. METHODDEF(void)
  168993. ycck_cmyk_convert (j_decompress_ptr cinfo,
  168994. JSAMPIMAGE input_buf, JDIMENSION input_row,
  168995. JSAMPARRAY output_buf, int num_rows)
  168996. {
  168997. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  168998. register int y, cb, cr;
  168999. register JSAMPROW outptr;
  169000. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169001. register JDIMENSION col;
  169002. JDIMENSION num_cols = cinfo->output_width;
  169003. /* copy these pointers into registers if possible */
  169004. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169005. register int * Crrtab = cconvert->Cr_r_tab;
  169006. register int * Cbbtab = cconvert->Cb_b_tab;
  169007. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169008. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169009. SHIFT_TEMPS
  169010. while (--num_rows >= 0) {
  169011. inptr0 = input_buf[0][input_row];
  169012. inptr1 = input_buf[1][input_row];
  169013. inptr2 = input_buf[2][input_row];
  169014. inptr3 = input_buf[3][input_row];
  169015. input_row++;
  169016. outptr = *output_buf++;
  169017. for (col = 0; col < num_cols; col++) {
  169018. y = GETJSAMPLE(inptr0[col]);
  169019. cb = GETJSAMPLE(inptr1[col]);
  169020. cr = GETJSAMPLE(inptr2[col]);
  169021. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169022. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169023. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169024. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169025. SCALEBITS)))];
  169026. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169027. /* K passes through unchanged */
  169028. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169029. outptr += 4;
  169030. }
  169031. }
  169032. }
  169033. /*
  169034. * Empty method for start_pass.
  169035. */
  169036. METHODDEF(void)
  169037. start_pass_dcolor (j_decompress_ptr)
  169038. {
  169039. /* no work needed */
  169040. }
  169041. /*
  169042. * Module initialization routine for output colorspace conversion.
  169043. */
  169044. GLOBAL(void)
  169045. jinit_color_deconverter (j_decompress_ptr cinfo)
  169046. {
  169047. my_cconvert_ptr2 cconvert;
  169048. int ci;
  169049. cconvert = (my_cconvert_ptr2)
  169050. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169051. SIZEOF(my_color_deconverter2));
  169052. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169053. cconvert->pub.start_pass = start_pass_dcolor;
  169054. /* Make sure num_components agrees with jpeg_color_space */
  169055. switch (cinfo->jpeg_color_space) {
  169056. case JCS_GRAYSCALE:
  169057. if (cinfo->num_components != 1)
  169058. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169059. break;
  169060. case JCS_RGB:
  169061. case JCS_YCbCr:
  169062. if (cinfo->num_components != 3)
  169063. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169064. break;
  169065. case JCS_CMYK:
  169066. case JCS_YCCK:
  169067. if (cinfo->num_components != 4)
  169068. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169069. break;
  169070. default: /* JCS_UNKNOWN can be anything */
  169071. if (cinfo->num_components < 1)
  169072. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169073. break;
  169074. }
  169075. /* Set out_color_components and conversion method based on requested space.
  169076. * Also clear the component_needed flags for any unused components,
  169077. * so that earlier pipeline stages can avoid useless computation.
  169078. */
  169079. switch (cinfo->out_color_space) {
  169080. case JCS_GRAYSCALE:
  169081. cinfo->out_color_components = 1;
  169082. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169083. cinfo->jpeg_color_space == JCS_YCbCr) {
  169084. cconvert->pub.color_convert = grayscale_convert2;
  169085. /* For color->grayscale conversion, only the Y (0) component is needed */
  169086. for (ci = 1; ci < cinfo->num_components; ci++)
  169087. cinfo->comp_info[ci].component_needed = FALSE;
  169088. } else
  169089. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169090. break;
  169091. case JCS_RGB:
  169092. cinfo->out_color_components = RGB_PIXELSIZE;
  169093. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169094. cconvert->pub.color_convert = ycc_rgb_convert;
  169095. build_ycc_rgb_table(cinfo);
  169096. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169097. cconvert->pub.color_convert = gray_rgb_convert;
  169098. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169099. cconvert->pub.color_convert = null_convert2;
  169100. } else
  169101. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169102. break;
  169103. case JCS_CMYK:
  169104. cinfo->out_color_components = 4;
  169105. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169106. cconvert->pub.color_convert = ycck_cmyk_convert;
  169107. build_ycc_rgb_table(cinfo);
  169108. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169109. cconvert->pub.color_convert = null_convert2;
  169110. } else
  169111. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169112. break;
  169113. default:
  169114. /* Permit null conversion to same output space */
  169115. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169116. cinfo->out_color_components = cinfo->num_components;
  169117. cconvert->pub.color_convert = null_convert2;
  169118. } else /* unsupported non-null conversion */
  169119. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169120. break;
  169121. }
  169122. if (cinfo->quantize_colors)
  169123. cinfo->output_components = 1; /* single colormapped output component */
  169124. else
  169125. cinfo->output_components = cinfo->out_color_components;
  169126. }
  169127. /*** End of inlined file: jdcolor.c ***/
  169128. #undef FIX
  169129. /*** Start of inlined file: jddctmgr.c ***/
  169130. #define JPEG_INTERNALS
  169131. /*
  169132. * The decompressor input side (jdinput.c) saves away the appropriate
  169133. * quantization table for each component at the start of the first scan
  169134. * involving that component. (This is necessary in order to correctly
  169135. * decode files that reuse Q-table slots.)
  169136. * When we are ready to make an output pass, the saved Q-table is converted
  169137. * to a multiplier table that will actually be used by the IDCT routine.
  169138. * The multiplier table contents are IDCT-method-dependent. To support
  169139. * application changes in IDCT method between scans, we can remake the
  169140. * multiplier tables if necessary.
  169141. * In buffered-image mode, the first output pass may occur before any data
  169142. * has been seen for some components, and thus before their Q-tables have
  169143. * been saved away. To handle this case, multiplier tables are preset
  169144. * to zeroes; the result of the IDCT will be a neutral gray level.
  169145. */
  169146. /* Private subobject for this module */
  169147. typedef struct {
  169148. struct jpeg_inverse_dct pub; /* public fields */
  169149. /* This array contains the IDCT method code that each multiplier table
  169150. * is currently set up for, or -1 if it's not yet set up.
  169151. * The actual multiplier tables are pointed to by dct_table in the
  169152. * per-component comp_info structures.
  169153. */
  169154. int cur_method[MAX_COMPONENTS];
  169155. } my_idct_controller;
  169156. typedef my_idct_controller * my_idct_ptr;
  169157. /* Allocated multiplier tables: big enough for any supported variant */
  169158. typedef union {
  169159. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169160. #ifdef DCT_IFAST_SUPPORTED
  169161. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169162. #endif
  169163. #ifdef DCT_FLOAT_SUPPORTED
  169164. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169165. #endif
  169166. } multiplier_table;
  169167. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169168. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169169. */
  169170. #ifdef DCT_ISLOW_SUPPORTED
  169171. #define PROVIDE_ISLOW_TABLES
  169172. #else
  169173. #ifdef IDCT_SCALING_SUPPORTED
  169174. #define PROVIDE_ISLOW_TABLES
  169175. #endif
  169176. #endif
  169177. /*
  169178. * Prepare for an output pass.
  169179. * Here we select the proper IDCT routine for each component and build
  169180. * a matching multiplier table.
  169181. */
  169182. METHODDEF(void)
  169183. start_pass (j_decompress_ptr cinfo)
  169184. {
  169185. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169186. int ci, i;
  169187. jpeg_component_info *compptr;
  169188. int method = 0;
  169189. inverse_DCT_method_ptr method_ptr = NULL;
  169190. JQUANT_TBL * qtbl;
  169191. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169192. ci++, compptr++) {
  169193. /* Select the proper IDCT routine for this component's scaling */
  169194. switch (compptr->DCT_scaled_size) {
  169195. #ifdef IDCT_SCALING_SUPPORTED
  169196. case 1:
  169197. method_ptr = jpeg_idct_1x1;
  169198. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169199. break;
  169200. case 2:
  169201. method_ptr = jpeg_idct_2x2;
  169202. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169203. break;
  169204. case 4:
  169205. method_ptr = jpeg_idct_4x4;
  169206. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169207. break;
  169208. #endif
  169209. case DCTSIZE:
  169210. switch (cinfo->dct_method) {
  169211. #ifdef DCT_ISLOW_SUPPORTED
  169212. case JDCT_ISLOW:
  169213. method_ptr = jpeg_idct_islow;
  169214. method = JDCT_ISLOW;
  169215. break;
  169216. #endif
  169217. #ifdef DCT_IFAST_SUPPORTED
  169218. case JDCT_IFAST:
  169219. method_ptr = jpeg_idct_ifast;
  169220. method = JDCT_IFAST;
  169221. break;
  169222. #endif
  169223. #ifdef DCT_FLOAT_SUPPORTED
  169224. case JDCT_FLOAT:
  169225. method_ptr = jpeg_idct_float;
  169226. method = JDCT_FLOAT;
  169227. break;
  169228. #endif
  169229. default:
  169230. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169231. break;
  169232. }
  169233. break;
  169234. default:
  169235. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169236. break;
  169237. }
  169238. idct->pub.inverse_DCT[ci] = method_ptr;
  169239. /* Create multiplier table from quant table.
  169240. * However, we can skip this if the component is uninteresting
  169241. * or if we already built the table. Also, if no quant table
  169242. * has yet been saved for the component, we leave the
  169243. * multiplier table all-zero; we'll be reading zeroes from the
  169244. * coefficient controller's buffer anyway.
  169245. */
  169246. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169247. continue;
  169248. qtbl = compptr->quant_table;
  169249. if (qtbl == NULL) /* happens if no data yet for component */
  169250. continue;
  169251. idct->cur_method[ci] = method;
  169252. switch (method) {
  169253. #ifdef PROVIDE_ISLOW_TABLES
  169254. case JDCT_ISLOW:
  169255. {
  169256. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169257. * coefficients, but are stored as ints to ensure access efficiency.
  169258. */
  169259. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169260. for (i = 0; i < DCTSIZE2; i++) {
  169261. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169262. }
  169263. }
  169264. break;
  169265. #endif
  169266. #ifdef DCT_IFAST_SUPPORTED
  169267. case JDCT_IFAST:
  169268. {
  169269. /* For AA&N IDCT method, multipliers are equal to quantization
  169270. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169271. * scalefactor[0] = 1
  169272. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169273. * For integer operation, the multiplier table is to be scaled by
  169274. * IFAST_SCALE_BITS.
  169275. */
  169276. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169277. #define CONST_BITS 14
  169278. static const INT16 aanscales[DCTSIZE2] = {
  169279. /* precomputed values scaled up by 14 bits */
  169280. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169281. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169282. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169283. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169284. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169285. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169286. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169287. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169288. };
  169289. SHIFT_TEMPS
  169290. for (i = 0; i < DCTSIZE2; i++) {
  169291. ifmtbl[i] = (IFAST_MULT_TYPE)
  169292. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169293. (INT32) aanscales[i]),
  169294. CONST_BITS-IFAST_SCALE_BITS);
  169295. }
  169296. }
  169297. break;
  169298. #endif
  169299. #ifdef DCT_FLOAT_SUPPORTED
  169300. case JDCT_FLOAT:
  169301. {
  169302. /* For float AA&N IDCT method, multipliers are equal to quantization
  169303. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169304. * scalefactor[0] = 1
  169305. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169306. */
  169307. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169308. int row, col;
  169309. static const double aanscalefactor[DCTSIZE] = {
  169310. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169311. 1.0, 0.785694958, 0.541196100, 0.275899379
  169312. };
  169313. i = 0;
  169314. for (row = 0; row < DCTSIZE; row++) {
  169315. for (col = 0; col < DCTSIZE; col++) {
  169316. fmtbl[i] = (FLOAT_MULT_TYPE)
  169317. ((double) qtbl->quantval[i] *
  169318. aanscalefactor[row] * aanscalefactor[col]);
  169319. i++;
  169320. }
  169321. }
  169322. }
  169323. break;
  169324. #endif
  169325. default:
  169326. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169327. break;
  169328. }
  169329. }
  169330. }
  169331. /*
  169332. * Initialize IDCT manager.
  169333. */
  169334. GLOBAL(void)
  169335. jinit_inverse_dct (j_decompress_ptr cinfo)
  169336. {
  169337. my_idct_ptr idct;
  169338. int ci;
  169339. jpeg_component_info *compptr;
  169340. idct = (my_idct_ptr)
  169341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169342. SIZEOF(my_idct_controller));
  169343. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169344. idct->pub.start_pass = start_pass;
  169345. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169346. ci++, compptr++) {
  169347. /* Allocate and pre-zero a multiplier table for each component */
  169348. compptr->dct_table =
  169349. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169350. SIZEOF(multiplier_table));
  169351. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169352. /* Mark multiplier table not yet set up for any method */
  169353. idct->cur_method[ci] = -1;
  169354. }
  169355. }
  169356. /*** End of inlined file: jddctmgr.c ***/
  169357. #undef CONST_BITS
  169358. #undef ASSIGN_STATE
  169359. /*** Start of inlined file: jdhuff.c ***/
  169360. #define JPEG_INTERNALS
  169361. /*** Start of inlined file: jdhuff.h ***/
  169362. /* Short forms of external names for systems with brain-damaged linkers. */
  169363. #ifndef __jdhuff_h__
  169364. #define __jdhuff_h__
  169365. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169366. #define jpeg_make_d_derived_tbl jMkDDerived
  169367. #define jpeg_fill_bit_buffer jFilBitBuf
  169368. #define jpeg_huff_decode jHufDecode
  169369. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169370. /* Derived data constructed for each Huffman table */
  169371. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169372. typedef struct {
  169373. /* Basic tables: (element [0] of each array is unused) */
  169374. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169375. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169376. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169377. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169378. * the smallest code of length k; so given a code of length k, the
  169379. * corresponding symbol is huffval[code + valoffset[k]]
  169380. */
  169381. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169382. JHUFF_TBL *pub;
  169383. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169384. * the input data stream. If the next Huffman code is no more
  169385. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169386. * the corresponding symbol directly from these tables.
  169387. */
  169388. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169389. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169390. } d_derived_tbl;
  169391. /* Expand a Huffman table definition into the derived format */
  169392. EXTERN(void) jpeg_make_d_derived_tbl
  169393. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169394. d_derived_tbl ** pdtbl));
  169395. /*
  169396. * Fetching the next N bits from the input stream is a time-critical operation
  169397. * for the Huffman decoders. We implement it with a combination of inline
  169398. * macros and out-of-line subroutines. Note that N (the number of bits
  169399. * demanded at one time) never exceeds 15 for JPEG use.
  169400. *
  169401. * We read source bytes into get_buffer and dole out bits as needed.
  169402. * If get_buffer already contains enough bits, they are fetched in-line
  169403. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169404. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169405. * as full as possible (not just to the number of bits needed; this
  169406. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169407. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169408. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169409. * at least the requested number of bits --- dummy zeroes are inserted if
  169410. * necessary.
  169411. */
  169412. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169413. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169414. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169415. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169416. * appropriately should be a win. Unfortunately we can't define the size
  169417. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169418. * because not all machines measure sizeof in 8-bit bytes.
  169419. */
  169420. typedef struct { /* Bitreading state saved across MCUs */
  169421. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169422. int bits_left; /* # of unused bits in it */
  169423. } bitread_perm_state;
  169424. typedef struct { /* Bitreading working state within an MCU */
  169425. /* Current data source location */
  169426. /* We need a copy, rather than munging the original, in case of suspension */
  169427. const JOCTET * next_input_byte; /* => next byte to read from source */
  169428. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169429. /* Bit input buffer --- note these values are kept in register variables,
  169430. * not in this struct, inside the inner loops.
  169431. */
  169432. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169433. int bits_left; /* # of unused bits in it */
  169434. /* Pointer needed by jpeg_fill_bit_buffer. */
  169435. j_decompress_ptr cinfo; /* back link to decompress master record */
  169436. } bitread_working_state;
  169437. /* Macros to declare and load/save bitread local variables. */
  169438. #define BITREAD_STATE_VARS \
  169439. register bit_buf_type get_buffer; \
  169440. register int bits_left; \
  169441. bitread_working_state br_state
  169442. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169443. br_state.cinfo = cinfop; \
  169444. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169445. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169446. get_buffer = permstate.get_buffer; \
  169447. bits_left = permstate.bits_left;
  169448. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169449. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169450. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169451. permstate.get_buffer = get_buffer; \
  169452. permstate.bits_left = bits_left
  169453. /*
  169454. * These macros provide the in-line portion of bit fetching.
  169455. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169456. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169457. * The variables get_buffer and bits_left are assumed to be locals,
  169458. * but the state struct might not be (jpeg_huff_decode needs this).
  169459. * CHECK_BIT_BUFFER(state,n,action);
  169460. * Ensure there are N bits in get_buffer; if suspend, take action.
  169461. * val = GET_BITS(n);
  169462. * Fetch next N bits.
  169463. * val = PEEK_BITS(n);
  169464. * Fetch next N bits without removing them from the buffer.
  169465. * DROP_BITS(n);
  169466. * Discard next N bits.
  169467. * The value N should be a simple variable, not an expression, because it
  169468. * is evaluated multiple times.
  169469. */
  169470. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169471. { if (bits_left < (nbits)) { \
  169472. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169473. { action; } \
  169474. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169475. #define GET_BITS(nbits) \
  169476. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169477. #define PEEK_BITS(nbits) \
  169478. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169479. #define DROP_BITS(nbits) \
  169480. (bits_left -= (nbits))
  169481. /* Load up the bit buffer to a depth of at least nbits */
  169482. EXTERN(boolean) jpeg_fill_bit_buffer
  169483. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169484. register int bits_left, int nbits));
  169485. /*
  169486. * Code for extracting next Huffman-coded symbol from input bit stream.
  169487. * Again, this is time-critical and we make the main paths be macros.
  169488. *
  169489. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169490. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169491. * or fewer bits long. The few overlength codes are handled with a loop,
  169492. * which need not be inline code.
  169493. *
  169494. * Notes about the HUFF_DECODE macro:
  169495. * 1. Near the end of the data segment, we may fail to get enough bits
  169496. * for a lookahead. In that case, we do it the hard way.
  169497. * 2. If the lookahead table contains no entry, the next code must be
  169498. * more than HUFF_LOOKAHEAD bits long.
  169499. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169500. */
  169501. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169502. { register int nb, look; \
  169503. if (bits_left < HUFF_LOOKAHEAD) { \
  169504. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169505. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169506. if (bits_left < HUFF_LOOKAHEAD) { \
  169507. nb = 1; goto slowlabel; \
  169508. } \
  169509. } \
  169510. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169511. if ((nb = htbl->look_nbits[look]) != 0) { \
  169512. DROP_BITS(nb); \
  169513. result = htbl->look_sym[look]; \
  169514. } else { \
  169515. nb = HUFF_LOOKAHEAD+1; \
  169516. slowlabel: \
  169517. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169518. { failaction; } \
  169519. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169520. } \
  169521. }
  169522. /* Out-of-line case for Huffman code fetching */
  169523. EXTERN(int) jpeg_huff_decode
  169524. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169525. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169526. #endif
  169527. /*** End of inlined file: jdhuff.h ***/
  169528. /* Declarations shared with jdphuff.c */
  169529. /*
  169530. * Expanded entropy decoder object for Huffman decoding.
  169531. *
  169532. * The savable_state subrecord contains fields that change within an MCU,
  169533. * but must not be updated permanently until we complete the MCU.
  169534. */
  169535. typedef struct {
  169536. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169537. } savable_state2;
  169538. /* This macro is to work around compilers with missing or broken
  169539. * structure assignment. You'll need to fix this code if you have
  169540. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169541. */
  169542. #ifndef NO_STRUCT_ASSIGN
  169543. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169544. #else
  169545. #if MAX_COMPS_IN_SCAN == 4
  169546. #define ASSIGN_STATE(dest,src) \
  169547. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169548. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169549. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169550. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169551. #endif
  169552. #endif
  169553. typedef struct {
  169554. struct jpeg_entropy_decoder pub; /* public fields */
  169555. /* These fields are loaded into local variables at start of each MCU.
  169556. * In case of suspension, we exit WITHOUT updating them.
  169557. */
  169558. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169559. savable_state2 saved; /* Other state at start of MCU */
  169560. /* These fields are NOT loaded into local working state. */
  169561. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169562. /* Pointers to derived tables (these workspaces have image lifespan) */
  169563. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169564. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169565. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169566. /* Pointers to derived tables to be used for each block within an MCU */
  169567. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169568. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169569. /* Whether we care about the DC and AC coefficient values for each block */
  169570. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169571. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169572. } huff_entropy_decoder2;
  169573. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169574. /*
  169575. * Initialize for a Huffman-compressed scan.
  169576. */
  169577. METHODDEF(void)
  169578. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169579. {
  169580. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169581. int ci, blkn, dctbl, actbl;
  169582. jpeg_component_info * compptr;
  169583. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169584. * This ought to be an error condition, but we make it a warning because
  169585. * there are some baseline files out there with all zeroes in these bytes.
  169586. */
  169587. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169588. cinfo->Ah != 0 || cinfo->Al != 0)
  169589. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169590. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169591. compptr = cinfo->cur_comp_info[ci];
  169592. dctbl = compptr->dc_tbl_no;
  169593. actbl = compptr->ac_tbl_no;
  169594. /* Compute derived values for Huffman tables */
  169595. /* We may do this more than once for a table, but it's not expensive */
  169596. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169597. & entropy->dc_derived_tbls[dctbl]);
  169598. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169599. & entropy->ac_derived_tbls[actbl]);
  169600. /* Initialize DC predictions to 0 */
  169601. entropy->saved.last_dc_val[ci] = 0;
  169602. }
  169603. /* Precalculate decoding info for each block in an MCU of this scan */
  169604. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169605. ci = cinfo->MCU_membership[blkn];
  169606. compptr = cinfo->cur_comp_info[ci];
  169607. /* Precalculate which table to use for each block */
  169608. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169609. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169610. /* Decide whether we really care about the coefficient values */
  169611. if (compptr->component_needed) {
  169612. entropy->dc_needed[blkn] = TRUE;
  169613. /* we don't need the ACs if producing a 1/8th-size image */
  169614. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169615. } else {
  169616. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169617. }
  169618. }
  169619. /* Initialize bitread state variables */
  169620. entropy->bitstate.bits_left = 0;
  169621. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169622. entropy->pub.insufficient_data = FALSE;
  169623. /* Initialize restart counter */
  169624. entropy->restarts_to_go = cinfo->restart_interval;
  169625. }
  169626. /*
  169627. * Compute the derived values for a Huffman table.
  169628. * This routine also performs some validation checks on the table.
  169629. *
  169630. * Note this is also used by jdphuff.c.
  169631. */
  169632. GLOBAL(void)
  169633. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169634. d_derived_tbl ** pdtbl)
  169635. {
  169636. JHUFF_TBL *htbl;
  169637. d_derived_tbl *dtbl;
  169638. int p, i, l, si, numsymbols;
  169639. int lookbits, ctr;
  169640. char huffsize[257];
  169641. unsigned int huffcode[257];
  169642. unsigned int code;
  169643. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169644. * paralleling the order of the symbols themselves in htbl->huffval[].
  169645. */
  169646. /* Find the input Huffman table */
  169647. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169648. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169649. htbl =
  169650. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169651. if (htbl == NULL)
  169652. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169653. /* Allocate a workspace if we haven't already done so. */
  169654. if (*pdtbl == NULL)
  169655. *pdtbl = (d_derived_tbl *)
  169656. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169657. SIZEOF(d_derived_tbl));
  169658. dtbl = *pdtbl;
  169659. dtbl->pub = htbl; /* fill in back link */
  169660. /* Figure C.1: make table of Huffman code length for each symbol */
  169661. p = 0;
  169662. for (l = 1; l <= 16; l++) {
  169663. i = (int) htbl->bits[l];
  169664. if (i < 0 || p + i > 256) /* protect against table overrun */
  169665. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169666. while (i--)
  169667. huffsize[p++] = (char) l;
  169668. }
  169669. huffsize[p] = 0;
  169670. numsymbols = p;
  169671. /* Figure C.2: generate the codes themselves */
  169672. /* We also validate that the counts represent a legal Huffman code tree. */
  169673. code = 0;
  169674. si = huffsize[0];
  169675. p = 0;
  169676. while (huffsize[p]) {
  169677. while (((int) huffsize[p]) == si) {
  169678. huffcode[p++] = code;
  169679. code++;
  169680. }
  169681. /* code is now 1 more than the last code used for codelength si; but
  169682. * it must still fit in si bits, since no code is allowed to be all ones.
  169683. */
  169684. if (((INT32) code) >= (((INT32) 1) << si))
  169685. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169686. code <<= 1;
  169687. si++;
  169688. }
  169689. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  169690. p = 0;
  169691. for (l = 1; l <= 16; l++) {
  169692. if (htbl->bits[l]) {
  169693. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  169694. * minus the minimum code of length l
  169695. */
  169696. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  169697. p += htbl->bits[l];
  169698. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  169699. } else {
  169700. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  169701. }
  169702. }
  169703. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  169704. /* Compute lookahead tables to speed up decoding.
  169705. * First we set all the table entries to 0, indicating "too long";
  169706. * then we iterate through the Huffman codes that are short enough and
  169707. * fill in all the entries that correspond to bit sequences starting
  169708. * with that code.
  169709. */
  169710. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  169711. p = 0;
  169712. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  169713. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169714. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  169715. /* Generate left-justified code followed by all possible bit sequences */
  169716. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  169717. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  169718. dtbl->look_nbits[lookbits] = l;
  169719. dtbl->look_sym[lookbits] = htbl->huffval[p];
  169720. lookbits++;
  169721. }
  169722. }
  169723. }
  169724. /* Validate symbols as being reasonable.
  169725. * For AC tables, we make no check, but accept all byte values 0..255.
  169726. * For DC tables, we require the symbols to be in range 0..15.
  169727. * (Tighter bounds could be applied depending on the data depth and mode,
  169728. * but this is sufficient to ensure safe decoding.)
  169729. */
  169730. if (isDC) {
  169731. for (i = 0; i < numsymbols; i++) {
  169732. int sym = htbl->huffval[i];
  169733. if (sym < 0 || sym > 15)
  169734. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  169735. }
  169736. }
  169737. }
  169738. /*
  169739. * Out-of-line code for bit fetching (shared with jdphuff.c).
  169740. * See jdhuff.h for info about usage.
  169741. * Note: current values of get_buffer and bits_left are passed as parameters,
  169742. * but are returned in the corresponding fields of the state struct.
  169743. *
  169744. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  169745. * of get_buffer to be used. (On machines with wider words, an even larger
  169746. * buffer could be used.) However, on some machines 32-bit shifts are
  169747. * quite slow and take time proportional to the number of places shifted.
  169748. * (This is true with most PC compilers, for instance.) In this case it may
  169749. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  169750. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  169751. */
  169752. #ifdef SLOW_SHIFT_32
  169753. #define MIN_GET_BITS 15 /* minimum allowable value */
  169754. #else
  169755. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  169756. #endif
  169757. GLOBAL(boolean)
  169758. jpeg_fill_bit_buffer (bitread_working_state * state,
  169759. register bit_buf_type get_buffer, register int bits_left,
  169760. int nbits)
  169761. /* Load up the bit buffer to a depth of at least nbits */
  169762. {
  169763. /* Copy heavily used state fields into locals (hopefully registers) */
  169764. register const JOCTET * next_input_byte = state->next_input_byte;
  169765. register size_t bytes_in_buffer = state->bytes_in_buffer;
  169766. j_decompress_ptr cinfo = state->cinfo;
  169767. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  169768. /* (It is assumed that no request will be for more than that many bits.) */
  169769. /* We fail to do so only if we hit a marker or are forced to suspend. */
  169770. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  169771. while (bits_left < MIN_GET_BITS) {
  169772. register int c;
  169773. /* Attempt to read a byte */
  169774. if (bytes_in_buffer == 0) {
  169775. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169776. return FALSE;
  169777. next_input_byte = cinfo->src->next_input_byte;
  169778. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169779. }
  169780. bytes_in_buffer--;
  169781. c = GETJOCTET(*next_input_byte++);
  169782. /* If it's 0xFF, check and discard stuffed zero byte */
  169783. if (c == 0xFF) {
  169784. /* Loop here to discard any padding FF's on terminating marker,
  169785. * so that we can save a valid unread_marker value. NOTE: we will
  169786. * accept multiple FF's followed by a 0 as meaning a single FF data
  169787. * byte. This data pattern is not valid according to the standard.
  169788. */
  169789. do {
  169790. if (bytes_in_buffer == 0) {
  169791. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  169792. return FALSE;
  169793. next_input_byte = cinfo->src->next_input_byte;
  169794. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  169795. }
  169796. bytes_in_buffer--;
  169797. c = GETJOCTET(*next_input_byte++);
  169798. } while (c == 0xFF);
  169799. if (c == 0) {
  169800. /* Found FF/00, which represents an FF data byte */
  169801. c = 0xFF;
  169802. } else {
  169803. /* Oops, it's actually a marker indicating end of compressed data.
  169804. * Save the marker code for later use.
  169805. * Fine point: it might appear that we should save the marker into
  169806. * bitread working state, not straight into permanent state. But
  169807. * once we have hit a marker, we cannot need to suspend within the
  169808. * current MCU, because we will read no more bytes from the data
  169809. * source. So it is OK to update permanent state right away.
  169810. */
  169811. cinfo->unread_marker = c;
  169812. /* See if we need to insert some fake zero bits. */
  169813. goto no_more_bytes;
  169814. }
  169815. }
  169816. /* OK, load c into get_buffer */
  169817. get_buffer = (get_buffer << 8) | c;
  169818. bits_left += 8;
  169819. } /* end while */
  169820. } else {
  169821. no_more_bytes:
  169822. /* We get here if we've read the marker that terminates the compressed
  169823. * data segment. There should be enough bits in the buffer register
  169824. * to satisfy the request; if so, no problem.
  169825. */
  169826. if (nbits > bits_left) {
  169827. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  169828. * the data stream, so that we can produce some kind of image.
  169829. * We use a nonvolatile flag to ensure that only one warning message
  169830. * appears per data segment.
  169831. */
  169832. if (! cinfo->entropy->insufficient_data) {
  169833. WARNMS(cinfo, JWRN_HIT_MARKER);
  169834. cinfo->entropy->insufficient_data = TRUE;
  169835. }
  169836. /* Fill the buffer with zero bits */
  169837. get_buffer <<= MIN_GET_BITS - bits_left;
  169838. bits_left = MIN_GET_BITS;
  169839. }
  169840. }
  169841. /* Unload the local registers */
  169842. state->next_input_byte = next_input_byte;
  169843. state->bytes_in_buffer = bytes_in_buffer;
  169844. state->get_buffer = get_buffer;
  169845. state->bits_left = bits_left;
  169846. return TRUE;
  169847. }
  169848. /*
  169849. * Out-of-line code for Huffman code decoding.
  169850. * See jdhuff.h for info about usage.
  169851. */
  169852. GLOBAL(int)
  169853. jpeg_huff_decode (bitread_working_state * state,
  169854. register bit_buf_type get_buffer, register int bits_left,
  169855. d_derived_tbl * htbl, int min_bits)
  169856. {
  169857. register int l = min_bits;
  169858. register INT32 code;
  169859. /* HUFF_DECODE has determined that the code is at least min_bits */
  169860. /* bits long, so fetch that many bits in one swoop. */
  169861. CHECK_BIT_BUFFER(*state, l, return -1);
  169862. code = GET_BITS(l);
  169863. /* Collect the rest of the Huffman code one bit at a time. */
  169864. /* This is per Figure F.16 in the JPEG spec. */
  169865. while (code > htbl->maxcode[l]) {
  169866. code <<= 1;
  169867. CHECK_BIT_BUFFER(*state, 1, return -1);
  169868. code |= GET_BITS(1);
  169869. l++;
  169870. }
  169871. /* Unload the local registers */
  169872. state->get_buffer = get_buffer;
  169873. state->bits_left = bits_left;
  169874. /* With garbage input we may reach the sentinel value l = 17. */
  169875. if (l > 16) {
  169876. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  169877. return 0; /* fake a zero as the safest result */
  169878. }
  169879. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  169880. }
  169881. /*
  169882. * Check for a restart marker & resynchronize decoder.
  169883. * Returns FALSE if must suspend.
  169884. */
  169885. LOCAL(boolean)
  169886. process_restart (j_decompress_ptr cinfo)
  169887. {
  169888. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169889. int ci;
  169890. /* Throw away any unused bits remaining in bit buffer; */
  169891. /* include any full bytes in next_marker's count of discarded bytes */
  169892. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  169893. entropy->bitstate.bits_left = 0;
  169894. /* Advance past the RSTn marker */
  169895. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  169896. return FALSE;
  169897. /* Re-initialize DC predictions to 0 */
  169898. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  169899. entropy->saved.last_dc_val[ci] = 0;
  169900. /* Reset restart counter */
  169901. entropy->restarts_to_go = cinfo->restart_interval;
  169902. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  169903. * against a marker. In that case we will end up treating the next data
  169904. * segment as empty, and we can avoid producing bogus output pixels by
  169905. * leaving the flag set.
  169906. */
  169907. if (cinfo->unread_marker == 0)
  169908. entropy->pub.insufficient_data = FALSE;
  169909. return TRUE;
  169910. }
  169911. /*
  169912. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  169913. * The coefficients are reordered from zigzag order into natural array order,
  169914. * but are not dequantized.
  169915. *
  169916. * The i'th block of the MCU is stored into the block pointed to by
  169917. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  169918. * (Wholesale zeroing is usually a little faster than retail...)
  169919. *
  169920. * Returns FALSE if data source requested suspension. In that case no
  169921. * changes have been made to permanent state. (Exception: some output
  169922. * coefficients may already have been assigned. This is harmless for
  169923. * this module, since we'll just re-assign them on the next call.)
  169924. */
  169925. METHODDEF(boolean)
  169926. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  169927. {
  169928. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169929. int blkn;
  169930. BITREAD_STATE_VARS;
  169931. savable_state2 state;
  169932. /* Process restart marker if needed; may have to suspend */
  169933. if (cinfo->restart_interval) {
  169934. if (entropy->restarts_to_go == 0)
  169935. if (! process_restart(cinfo))
  169936. return FALSE;
  169937. }
  169938. /* If we've run out of data, just leave the MCU set to zeroes.
  169939. * This way, we return uniform gray for the remainder of the segment.
  169940. */
  169941. if (! entropy->pub.insufficient_data) {
  169942. /* Load up working state */
  169943. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  169944. ASSIGN_STATE(state, entropy->saved);
  169945. /* Outer loop handles each block in the MCU */
  169946. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169947. JBLOCKROW block = MCU_data[blkn];
  169948. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  169949. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  169950. register int s, k, r;
  169951. /* Decode a single block's worth of coefficients */
  169952. /* Section F.2.2.1: decode the DC coefficient difference */
  169953. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  169954. if (s) {
  169955. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169956. r = GET_BITS(s);
  169957. s = HUFF_EXTEND(r, s);
  169958. }
  169959. if (entropy->dc_needed[blkn]) {
  169960. /* Convert DC difference to actual value, update last_dc_val */
  169961. int ci = cinfo->MCU_membership[blkn];
  169962. s += state.last_dc_val[ci];
  169963. state.last_dc_val[ci] = s;
  169964. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  169965. (*block)[0] = (JCOEF) s;
  169966. }
  169967. if (entropy->ac_needed[blkn]) {
  169968. /* Section F.2.2.2: decode the AC coefficients */
  169969. /* Since zeroes are skipped, output area must be cleared beforehand */
  169970. for (k = 1; k < DCTSIZE2; k++) {
  169971. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  169972. r = s >> 4;
  169973. s &= 15;
  169974. if (s) {
  169975. k += r;
  169976. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  169977. r = GET_BITS(s);
  169978. s = HUFF_EXTEND(r, s);
  169979. /* Output coefficient in natural (dezigzagged) order.
  169980. * Note: the extra entries in jpeg_natural_order[] will save us
  169981. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  169982. */
  169983. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  169984. } else {
  169985. if (r != 15)
  169986. break;
  169987. k += 15;
  169988. }
  169989. }
  169990. } else {
  169991. /* Section F.2.2.2: decode the AC coefficients */
  169992. /* In this path we just discard the values */
  169993. for (k = 1; k < DCTSIZE2; k++) {
  169994. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  169995. r = s >> 4;
  169996. s &= 15;
  169997. if (s) {
  169998. k += r;
  169999. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170000. DROP_BITS(s);
  170001. } else {
  170002. if (r != 15)
  170003. break;
  170004. k += 15;
  170005. }
  170006. }
  170007. }
  170008. }
  170009. /* Completed MCU, so update state */
  170010. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170011. ASSIGN_STATE(entropy->saved, state);
  170012. }
  170013. /* Account for restart interval (no-op if not using restarts) */
  170014. entropy->restarts_to_go--;
  170015. return TRUE;
  170016. }
  170017. /*
  170018. * Module initialization routine for Huffman entropy decoding.
  170019. */
  170020. GLOBAL(void)
  170021. jinit_huff_decoder (j_decompress_ptr cinfo)
  170022. {
  170023. huff_entropy_ptr2 entropy;
  170024. int i;
  170025. entropy = (huff_entropy_ptr2)
  170026. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170027. SIZEOF(huff_entropy_decoder2));
  170028. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170029. entropy->pub.start_pass = start_pass_huff_decoder;
  170030. entropy->pub.decode_mcu = decode_mcu;
  170031. /* Mark tables unallocated */
  170032. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170033. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170034. }
  170035. }
  170036. /*** End of inlined file: jdhuff.c ***/
  170037. /*** Start of inlined file: jdinput.c ***/
  170038. #define JPEG_INTERNALS
  170039. /* Private state */
  170040. typedef struct {
  170041. struct jpeg_input_controller pub; /* public fields */
  170042. boolean inheaders; /* TRUE until first SOS is reached */
  170043. } my_input_controller;
  170044. typedef my_input_controller * my_inputctl_ptr;
  170045. /* Forward declarations */
  170046. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170047. /*
  170048. * Routines to calculate various quantities related to the size of the image.
  170049. */
  170050. LOCAL(void)
  170051. initial_setup2 (j_decompress_ptr cinfo)
  170052. /* Called once, when first SOS marker is reached */
  170053. {
  170054. int ci;
  170055. jpeg_component_info *compptr;
  170056. /* Make sure image isn't bigger than I can handle */
  170057. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170058. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170059. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170060. /* For now, precision must match compiled-in value... */
  170061. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170062. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170063. /* Check that number of components won't exceed internal array sizes */
  170064. if (cinfo->num_components > MAX_COMPONENTS)
  170065. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170066. MAX_COMPONENTS);
  170067. /* Compute maximum sampling factors; check factor validity */
  170068. cinfo->max_h_samp_factor = 1;
  170069. cinfo->max_v_samp_factor = 1;
  170070. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170071. ci++, compptr++) {
  170072. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170073. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170074. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170075. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170076. compptr->h_samp_factor);
  170077. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170078. compptr->v_samp_factor);
  170079. }
  170080. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170081. * In the full decompressor, this will be overridden by jdmaster.c;
  170082. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170083. */
  170084. cinfo->min_DCT_scaled_size = DCTSIZE;
  170085. /* Compute dimensions of components */
  170086. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170087. ci++, compptr++) {
  170088. compptr->DCT_scaled_size = DCTSIZE;
  170089. /* Size in DCT blocks */
  170090. compptr->width_in_blocks = (JDIMENSION)
  170091. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170092. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170093. compptr->height_in_blocks = (JDIMENSION)
  170094. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170095. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170096. /* downsampled_width and downsampled_height will also be overridden by
  170097. * jdmaster.c if we are doing full decompression. The transcoder library
  170098. * doesn't use these values, but the calling application might.
  170099. */
  170100. /* Size in samples */
  170101. compptr->downsampled_width = (JDIMENSION)
  170102. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170103. (long) cinfo->max_h_samp_factor);
  170104. compptr->downsampled_height = (JDIMENSION)
  170105. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170106. (long) cinfo->max_v_samp_factor);
  170107. /* Mark component needed, until color conversion says otherwise */
  170108. compptr->component_needed = TRUE;
  170109. /* Mark no quantization table yet saved for component */
  170110. compptr->quant_table = NULL;
  170111. }
  170112. /* Compute number of fully interleaved MCU rows. */
  170113. cinfo->total_iMCU_rows = (JDIMENSION)
  170114. jdiv_round_up((long) cinfo->image_height,
  170115. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170116. /* Decide whether file contains multiple scans */
  170117. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170118. cinfo->inputctl->has_multiple_scans = TRUE;
  170119. else
  170120. cinfo->inputctl->has_multiple_scans = FALSE;
  170121. }
  170122. LOCAL(void)
  170123. per_scan_setup2 (j_decompress_ptr cinfo)
  170124. /* Do computations that are needed before processing a JPEG scan */
  170125. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170126. {
  170127. int ci, mcublks, tmp;
  170128. jpeg_component_info *compptr;
  170129. if (cinfo->comps_in_scan == 1) {
  170130. /* Noninterleaved (single-component) scan */
  170131. compptr = cinfo->cur_comp_info[0];
  170132. /* Overall image size in MCUs */
  170133. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170134. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170135. /* For noninterleaved scan, always one block per MCU */
  170136. compptr->MCU_width = 1;
  170137. compptr->MCU_height = 1;
  170138. compptr->MCU_blocks = 1;
  170139. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170140. compptr->last_col_width = 1;
  170141. /* For noninterleaved scans, it is convenient to define last_row_height
  170142. * as the number of block rows present in the last iMCU row.
  170143. */
  170144. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170145. if (tmp == 0) tmp = compptr->v_samp_factor;
  170146. compptr->last_row_height = tmp;
  170147. /* Prepare array describing MCU composition */
  170148. cinfo->blocks_in_MCU = 1;
  170149. cinfo->MCU_membership[0] = 0;
  170150. } else {
  170151. /* Interleaved (multi-component) scan */
  170152. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170153. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170154. MAX_COMPS_IN_SCAN);
  170155. /* Overall image size in MCUs */
  170156. cinfo->MCUs_per_row = (JDIMENSION)
  170157. jdiv_round_up((long) cinfo->image_width,
  170158. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170159. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170160. jdiv_round_up((long) cinfo->image_height,
  170161. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170162. cinfo->blocks_in_MCU = 0;
  170163. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170164. compptr = cinfo->cur_comp_info[ci];
  170165. /* Sampling factors give # of blocks of component in each MCU */
  170166. compptr->MCU_width = compptr->h_samp_factor;
  170167. compptr->MCU_height = compptr->v_samp_factor;
  170168. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170169. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170170. /* Figure number of non-dummy blocks in last MCU column & row */
  170171. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170172. if (tmp == 0) tmp = compptr->MCU_width;
  170173. compptr->last_col_width = tmp;
  170174. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170175. if (tmp == 0) tmp = compptr->MCU_height;
  170176. compptr->last_row_height = tmp;
  170177. /* Prepare array describing MCU composition */
  170178. mcublks = compptr->MCU_blocks;
  170179. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170180. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170181. while (mcublks-- > 0) {
  170182. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170183. }
  170184. }
  170185. }
  170186. }
  170187. /*
  170188. * Save away a copy of the Q-table referenced by each component present
  170189. * in the current scan, unless already saved during a prior scan.
  170190. *
  170191. * In a multiple-scan JPEG file, the encoder could assign different components
  170192. * the same Q-table slot number, but change table definitions between scans
  170193. * so that each component uses a different Q-table. (The IJG encoder is not
  170194. * currently capable of doing this, but other encoders might.) Since we want
  170195. * to be able to dequantize all the components at the end of the file, this
  170196. * means that we have to save away the table actually used for each component.
  170197. * We do this by copying the table at the start of the first scan containing
  170198. * the component.
  170199. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170200. * slot between scans of a component using that slot. If the encoder does so
  170201. * anyway, this decoder will simply use the Q-table values that were current
  170202. * at the start of the first scan for the component.
  170203. *
  170204. * The decompressor output side looks only at the saved quant tables,
  170205. * not at the current Q-table slots.
  170206. */
  170207. LOCAL(void)
  170208. latch_quant_tables (j_decompress_ptr cinfo)
  170209. {
  170210. int ci, qtblno;
  170211. jpeg_component_info *compptr;
  170212. JQUANT_TBL * qtbl;
  170213. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170214. compptr = cinfo->cur_comp_info[ci];
  170215. /* No work if we already saved Q-table for this component */
  170216. if (compptr->quant_table != NULL)
  170217. continue;
  170218. /* Make sure specified quantization table is present */
  170219. qtblno = compptr->quant_tbl_no;
  170220. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170221. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170222. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170223. /* OK, save away the quantization table */
  170224. qtbl = (JQUANT_TBL *)
  170225. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170226. SIZEOF(JQUANT_TBL));
  170227. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170228. compptr->quant_table = qtbl;
  170229. }
  170230. }
  170231. /*
  170232. * Initialize the input modules to read a scan of compressed data.
  170233. * The first call to this is done by jdmaster.c after initializing
  170234. * the entire decompressor (during jpeg_start_decompress).
  170235. * Subsequent calls come from consume_markers, below.
  170236. */
  170237. METHODDEF(void)
  170238. start_input_pass2 (j_decompress_ptr cinfo)
  170239. {
  170240. per_scan_setup2(cinfo);
  170241. latch_quant_tables(cinfo);
  170242. (*cinfo->entropy->start_pass) (cinfo);
  170243. (*cinfo->coef->start_input_pass) (cinfo);
  170244. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170245. }
  170246. /*
  170247. * Finish up after inputting a compressed-data scan.
  170248. * This is called by the coefficient controller after it's read all
  170249. * the expected data of the scan.
  170250. */
  170251. METHODDEF(void)
  170252. finish_input_pass (j_decompress_ptr cinfo)
  170253. {
  170254. cinfo->inputctl->consume_input = consume_markers;
  170255. }
  170256. /*
  170257. * Read JPEG markers before, between, or after compressed-data scans.
  170258. * Change state as necessary when a new scan is reached.
  170259. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170260. *
  170261. * The consume_input method pointer points either here or to the
  170262. * coefficient controller's consume_data routine, depending on whether
  170263. * we are reading a compressed data segment or inter-segment markers.
  170264. */
  170265. METHODDEF(int)
  170266. consume_markers (j_decompress_ptr cinfo)
  170267. {
  170268. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170269. int val;
  170270. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170271. return JPEG_REACHED_EOI;
  170272. val = (*cinfo->marker->read_markers) (cinfo);
  170273. switch (val) {
  170274. case JPEG_REACHED_SOS: /* Found SOS */
  170275. if (inputctl->inheaders) { /* 1st SOS */
  170276. initial_setup2(cinfo);
  170277. inputctl->inheaders = FALSE;
  170278. /* Note: start_input_pass must be called by jdmaster.c
  170279. * before any more input can be consumed. jdapimin.c is
  170280. * responsible for enforcing this sequencing.
  170281. */
  170282. } else { /* 2nd or later SOS marker */
  170283. if (! inputctl->pub.has_multiple_scans)
  170284. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170285. start_input_pass2(cinfo);
  170286. }
  170287. break;
  170288. case JPEG_REACHED_EOI: /* Found EOI */
  170289. inputctl->pub.eoi_reached = TRUE;
  170290. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170291. if (cinfo->marker->saw_SOF)
  170292. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170293. } else {
  170294. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170295. * if user set output_scan_number larger than number of scans.
  170296. */
  170297. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170298. cinfo->output_scan_number = cinfo->input_scan_number;
  170299. }
  170300. break;
  170301. case JPEG_SUSPENDED:
  170302. break;
  170303. }
  170304. return val;
  170305. }
  170306. /*
  170307. * Reset state to begin a fresh datastream.
  170308. */
  170309. METHODDEF(void)
  170310. reset_input_controller (j_decompress_ptr cinfo)
  170311. {
  170312. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170313. inputctl->pub.consume_input = consume_markers;
  170314. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170315. inputctl->pub.eoi_reached = FALSE;
  170316. inputctl->inheaders = TRUE;
  170317. /* Reset other modules */
  170318. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170319. (*cinfo->marker->reset_marker_reader) (cinfo);
  170320. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170321. cinfo->coef_bits = NULL;
  170322. }
  170323. /*
  170324. * Initialize the input controller module.
  170325. * This is called only once, when the decompression object is created.
  170326. */
  170327. GLOBAL(void)
  170328. jinit_input_controller (j_decompress_ptr cinfo)
  170329. {
  170330. my_inputctl_ptr inputctl;
  170331. /* Create subobject in permanent pool */
  170332. inputctl = (my_inputctl_ptr)
  170333. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170334. SIZEOF(my_input_controller));
  170335. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170336. /* Initialize method pointers */
  170337. inputctl->pub.consume_input = consume_markers;
  170338. inputctl->pub.reset_input_controller = reset_input_controller;
  170339. inputctl->pub.start_input_pass = start_input_pass2;
  170340. inputctl->pub.finish_input_pass = finish_input_pass;
  170341. /* Initialize state: can't use reset_input_controller since we don't
  170342. * want to try to reset other modules yet.
  170343. */
  170344. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170345. inputctl->pub.eoi_reached = FALSE;
  170346. inputctl->inheaders = TRUE;
  170347. }
  170348. /*** End of inlined file: jdinput.c ***/
  170349. /*** Start of inlined file: jdmainct.c ***/
  170350. #define JPEG_INTERNALS
  170351. /*
  170352. * In the current system design, the main buffer need never be a full-image
  170353. * buffer; any full-height buffers will be found inside the coefficient or
  170354. * postprocessing controllers. Nonetheless, the main controller is not
  170355. * trivial. Its responsibility is to provide context rows for upsampling/
  170356. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170357. *
  170358. * Postprocessor input data is counted in "row groups". A row group
  170359. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170360. * sample rows of each component. (We require DCT_scaled_size values to be
  170361. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170362. * values will likely be powers of two, so we actually have the stronger
  170363. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170364. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170365. * row group (times any additional scale factor that the upsampler is
  170366. * applying).
  170367. *
  170368. * The coefficient controller will deliver data to us one iMCU row at a time;
  170369. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170370. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170371. * to one row of MCUs when the image is fully interleaved.) Note that the
  170372. * number of sample rows varies across components, but the number of row
  170373. * groups does not. Some garbage sample rows may be included in the last iMCU
  170374. * row at the bottom of the image.
  170375. *
  170376. * Depending on the vertical scaling algorithm used, the upsampler may need
  170377. * access to the sample row(s) above and below its current input row group.
  170378. * The upsampler is required to set need_context_rows TRUE at global selection
  170379. * time if so. When need_context_rows is FALSE, this controller can simply
  170380. * obtain one iMCU row at a time from the coefficient controller and dole it
  170381. * out as row groups to the postprocessor.
  170382. *
  170383. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170384. * passed to postprocessing contains at least one row group's worth of samples
  170385. * above and below the row group(s) being processed. Note that the context
  170386. * rows "above" the first passed row group appear at negative row offsets in
  170387. * the passed buffer. At the top and bottom of the image, the required
  170388. * context rows are manufactured by duplicating the first or last real sample
  170389. * row; this avoids having special cases in the upsampling inner loops.
  170390. *
  170391. * The amount of context is fixed at one row group just because that's a
  170392. * convenient number for this controller to work with. The existing
  170393. * upsamplers really only need one sample row of context. An upsampler
  170394. * supporting arbitrary output rescaling might wish for more than one row
  170395. * group of context when shrinking the image; tough, we don't handle that.
  170396. * (This is justified by the assumption that downsizing will be handled mostly
  170397. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170398. * the upsample step needn't be much less than one.)
  170399. *
  170400. * To provide the desired context, we have to retain the last two row groups
  170401. * of one iMCU row while reading in the next iMCU row. (The last row group
  170402. * can't be processed until we have another row group for its below-context,
  170403. * and so we have to save the next-to-last group too for its above-context.)
  170404. * We could do this most simply by copying data around in our buffer, but
  170405. * that'd be very slow. We can avoid copying any data by creating a rather
  170406. * strange pointer structure. Here's how it works. We allocate a workspace
  170407. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170408. * of row groups per iMCU row). We create two sets of redundant pointers to
  170409. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170410. * pointer lists look like this:
  170411. * M+1 M-1
  170412. * master pointer --> 0 master pointer --> 0
  170413. * 1 1
  170414. * ... ...
  170415. * M-3 M-3
  170416. * M-2 M
  170417. * M-1 M+1
  170418. * M M-2
  170419. * M+1 M-1
  170420. * 0 0
  170421. * We read alternate iMCU rows using each master pointer; thus the last two
  170422. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170423. * The pointer lists are set up so that the required context rows appear to
  170424. * be adjacent to the proper places when we pass the pointer lists to the
  170425. * upsampler.
  170426. *
  170427. * The above pictures describe the normal state of the pointer lists.
  170428. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170429. * the first or last sample row as necessary (this is cheaper than copying
  170430. * sample rows around).
  170431. *
  170432. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170433. * situation each iMCU row provides only one row group so the buffering logic
  170434. * must be different (eg, we must read two iMCU rows before we can emit the
  170435. * first row group). For now, we simply do not support providing context
  170436. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170437. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170438. * want it quick and dirty, so a context-free upsampler is sufficient.
  170439. */
  170440. /* Private buffer controller object */
  170441. typedef struct {
  170442. struct jpeg_d_main_controller pub; /* public fields */
  170443. /* Pointer to allocated workspace (M or M+2 row groups). */
  170444. JSAMPARRAY buffer[MAX_COMPONENTS];
  170445. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170446. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170447. /* Remaining fields are only used in the context case. */
  170448. /* These are the master pointers to the funny-order pointer lists. */
  170449. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170450. int whichptr; /* indicates which pointer set is now in use */
  170451. int context_state; /* process_data state machine status */
  170452. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170453. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170454. } my_main_controller4;
  170455. typedef my_main_controller4 * my_main_ptr4;
  170456. /* context_state values: */
  170457. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170458. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170459. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170460. /* Forward declarations */
  170461. METHODDEF(void) process_data_simple_main2
  170462. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170463. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170464. METHODDEF(void) process_data_context_main
  170465. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170466. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170467. #ifdef QUANT_2PASS_SUPPORTED
  170468. METHODDEF(void) process_data_crank_post
  170469. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170470. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170471. #endif
  170472. LOCAL(void)
  170473. alloc_funny_pointers (j_decompress_ptr cinfo)
  170474. /* Allocate space for the funny pointer lists.
  170475. * This is done only once, not once per pass.
  170476. */
  170477. {
  170478. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170479. int ci, rgroup;
  170480. int M = cinfo->min_DCT_scaled_size;
  170481. jpeg_component_info *compptr;
  170482. JSAMPARRAY xbuf;
  170483. /* Get top-level space for component array pointers.
  170484. * We alloc both arrays with one call to save a few cycles.
  170485. */
  170486. main_->xbuffer[0] = (JSAMPIMAGE)
  170487. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170488. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170489. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170490. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170491. ci++, compptr++) {
  170492. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170493. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170494. /* Get space for pointer lists --- M+4 row groups in each list.
  170495. * We alloc both pointer lists with one call to save a few cycles.
  170496. */
  170497. xbuf = (JSAMPARRAY)
  170498. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170499. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170500. xbuf += rgroup; /* want one row group at negative offsets */
  170501. main_->xbuffer[0][ci] = xbuf;
  170502. xbuf += rgroup * (M + 4);
  170503. main_->xbuffer[1][ci] = xbuf;
  170504. }
  170505. }
  170506. LOCAL(void)
  170507. make_funny_pointers (j_decompress_ptr cinfo)
  170508. /* Create the funny pointer lists discussed in the comments above.
  170509. * The actual workspace is already allocated (in main->buffer),
  170510. * and the space for the pointer lists is allocated too.
  170511. * This routine just fills in the curiously ordered lists.
  170512. * This will be repeated at the beginning of each pass.
  170513. */
  170514. {
  170515. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170516. int ci, i, rgroup;
  170517. int M = cinfo->min_DCT_scaled_size;
  170518. jpeg_component_info *compptr;
  170519. JSAMPARRAY buf, xbuf0, xbuf1;
  170520. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170521. ci++, compptr++) {
  170522. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170523. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170524. xbuf0 = main_->xbuffer[0][ci];
  170525. xbuf1 = main_->xbuffer[1][ci];
  170526. /* First copy the workspace pointers as-is */
  170527. buf = main_->buffer[ci];
  170528. for (i = 0; i < rgroup * (M + 2); i++) {
  170529. xbuf0[i] = xbuf1[i] = buf[i];
  170530. }
  170531. /* In the second list, put the last four row groups in swapped order */
  170532. for (i = 0; i < rgroup * 2; i++) {
  170533. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170534. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170535. }
  170536. /* The wraparound pointers at top and bottom will be filled later
  170537. * (see set_wraparound_pointers, below). Initially we want the "above"
  170538. * pointers to duplicate the first actual data line. This only needs
  170539. * to happen in xbuffer[0].
  170540. */
  170541. for (i = 0; i < rgroup; i++) {
  170542. xbuf0[i - rgroup] = xbuf0[0];
  170543. }
  170544. }
  170545. }
  170546. LOCAL(void)
  170547. set_wraparound_pointers (j_decompress_ptr cinfo)
  170548. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170549. * This changes the pointer list state from top-of-image to the normal state.
  170550. */
  170551. {
  170552. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170553. int ci, i, rgroup;
  170554. int M = cinfo->min_DCT_scaled_size;
  170555. jpeg_component_info *compptr;
  170556. JSAMPARRAY xbuf0, xbuf1;
  170557. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170558. ci++, compptr++) {
  170559. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170560. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170561. xbuf0 = main_->xbuffer[0][ci];
  170562. xbuf1 = main_->xbuffer[1][ci];
  170563. for (i = 0; i < rgroup; i++) {
  170564. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170565. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170566. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170567. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170568. }
  170569. }
  170570. }
  170571. LOCAL(void)
  170572. set_bottom_pointers (j_decompress_ptr cinfo)
  170573. /* Change the pointer lists to duplicate the last sample row at the bottom
  170574. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170575. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170576. */
  170577. {
  170578. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170579. int ci, i, rgroup, iMCUheight, rows_left;
  170580. jpeg_component_info *compptr;
  170581. JSAMPARRAY xbuf;
  170582. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170583. ci++, compptr++) {
  170584. /* Count sample rows in one iMCU row and in one row group */
  170585. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170586. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170587. /* Count nondummy sample rows remaining for this component */
  170588. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170589. if (rows_left == 0) rows_left = iMCUheight;
  170590. /* Count nondummy row groups. Should get same answer for each component,
  170591. * so we need only do it once.
  170592. */
  170593. if (ci == 0) {
  170594. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170595. }
  170596. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170597. * last partial rowgroup and ensures at least one full rowgroup of context.
  170598. */
  170599. xbuf = main_->xbuffer[main_->whichptr][ci];
  170600. for (i = 0; i < rgroup * 2; i++) {
  170601. xbuf[rows_left + i] = xbuf[rows_left-1];
  170602. }
  170603. }
  170604. }
  170605. /*
  170606. * Initialize for a processing pass.
  170607. */
  170608. METHODDEF(void)
  170609. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170610. {
  170611. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170612. switch (pass_mode) {
  170613. case JBUF_PASS_THRU:
  170614. if (cinfo->upsample->need_context_rows) {
  170615. main_->pub.process_data = process_data_context_main;
  170616. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170617. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170618. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170619. main_->iMCU_row_ctr = 0;
  170620. } else {
  170621. /* Simple case with no context needed */
  170622. main_->pub.process_data = process_data_simple_main2;
  170623. }
  170624. main_->buffer_full = FALSE; /* Mark buffer empty */
  170625. main_->rowgroup_ctr = 0;
  170626. break;
  170627. #ifdef QUANT_2PASS_SUPPORTED
  170628. case JBUF_CRANK_DEST:
  170629. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170630. main_->pub.process_data = process_data_crank_post;
  170631. break;
  170632. #endif
  170633. default:
  170634. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170635. break;
  170636. }
  170637. }
  170638. /*
  170639. * Process some data.
  170640. * This handles the simple case where no context is required.
  170641. */
  170642. METHODDEF(void)
  170643. process_data_simple_main2 (j_decompress_ptr cinfo,
  170644. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170645. JDIMENSION out_rows_avail)
  170646. {
  170647. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170648. JDIMENSION rowgroups_avail;
  170649. /* Read input data if we haven't filled the main buffer yet */
  170650. if (! main_->buffer_full) {
  170651. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170652. return; /* suspension forced, can do nothing more */
  170653. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170654. }
  170655. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170656. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170657. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170658. * to the postprocessor. The postprocessor has to check for bottom
  170659. * of image anyway (at row resolution), so no point in us doing it too.
  170660. */
  170661. /* Feed the postprocessor */
  170662. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  170663. &main_->rowgroup_ctr, rowgroups_avail,
  170664. output_buf, out_row_ctr, out_rows_avail);
  170665. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  170666. if (main_->rowgroup_ctr >= rowgroups_avail) {
  170667. main_->buffer_full = FALSE;
  170668. main_->rowgroup_ctr = 0;
  170669. }
  170670. }
  170671. /*
  170672. * Process some data.
  170673. * This handles the case where context rows must be provided.
  170674. */
  170675. METHODDEF(void)
  170676. process_data_context_main (j_decompress_ptr cinfo,
  170677. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170678. JDIMENSION out_rows_avail)
  170679. {
  170680. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170681. /* Read input data if we haven't filled the main buffer yet */
  170682. if (! main_->buffer_full) {
  170683. if (! (*cinfo->coef->decompress_data) (cinfo,
  170684. main_->xbuffer[main_->whichptr]))
  170685. return; /* suspension forced, can do nothing more */
  170686. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170687. main_->iMCU_row_ctr++; /* count rows received */
  170688. }
  170689. /* Postprocessor typically will not swallow all the input data it is handed
  170690. * in one call (due to filling the output buffer first). Must be prepared
  170691. * to exit and restart. This switch lets us keep track of how far we got.
  170692. * Note that each case falls through to the next on successful completion.
  170693. */
  170694. switch (main_->context_state) {
  170695. case CTX_POSTPONED_ROW:
  170696. /* Call postprocessor using previously set pointers for postponed row */
  170697. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170698. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170699. output_buf, out_row_ctr, out_rows_avail);
  170700. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170701. return; /* Need to suspend */
  170702. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170703. if (*out_row_ctr >= out_rows_avail)
  170704. return; /* Postprocessor exactly filled output buf */
  170705. /*FALLTHROUGH*/
  170706. case CTX_PREPARE_FOR_IMCU:
  170707. /* Prepare to process first M-1 row groups of this iMCU row */
  170708. main_->rowgroup_ctr = 0;
  170709. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  170710. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  170711. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  170712. */
  170713. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  170714. set_bottom_pointers(cinfo);
  170715. main_->context_state = CTX_PROCESS_IMCU;
  170716. /*FALLTHROUGH*/
  170717. case CTX_PROCESS_IMCU:
  170718. /* Call postprocessor using previously set pointers */
  170719. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  170720. &main_->rowgroup_ctr, main_->rowgroups_avail,
  170721. output_buf, out_row_ctr, out_rows_avail);
  170722. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  170723. return; /* Need to suspend */
  170724. /* After the first iMCU, change wraparound pointers to normal state */
  170725. if (main_->iMCU_row_ctr == 1)
  170726. set_wraparound_pointers(cinfo);
  170727. /* Prepare to load new iMCU row using other xbuffer list */
  170728. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  170729. main_->buffer_full = FALSE;
  170730. /* Still need to process last row group of this iMCU row, */
  170731. /* which is saved at index M+1 of the other xbuffer */
  170732. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  170733. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  170734. main_->context_state = CTX_POSTPONED_ROW;
  170735. }
  170736. }
  170737. /*
  170738. * Process some data.
  170739. * Final pass of two-pass quantization: just call the postprocessor.
  170740. * Source data will be the postprocessor controller's internal buffer.
  170741. */
  170742. #ifdef QUANT_2PASS_SUPPORTED
  170743. METHODDEF(void)
  170744. process_data_crank_post (j_decompress_ptr cinfo,
  170745. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170746. JDIMENSION out_rows_avail)
  170747. {
  170748. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  170749. (JDIMENSION *) NULL, (JDIMENSION) 0,
  170750. output_buf, out_row_ctr, out_rows_avail);
  170751. }
  170752. #endif /* QUANT_2PASS_SUPPORTED */
  170753. /*
  170754. * Initialize main buffer controller.
  170755. */
  170756. GLOBAL(void)
  170757. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170758. {
  170759. my_main_ptr4 main_;
  170760. int ci, rgroup, ngroups;
  170761. jpeg_component_info *compptr;
  170762. main_ = (my_main_ptr4)
  170763. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170764. SIZEOF(my_main_controller4));
  170765. cinfo->main = (struct jpeg_d_main_controller *) main_;
  170766. main_->pub.start_pass = start_pass_main2;
  170767. if (need_full_buffer) /* shouldn't happen */
  170768. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170769. /* Allocate the workspace.
  170770. * ngroups is the number of row groups we need.
  170771. */
  170772. if (cinfo->upsample->need_context_rows) {
  170773. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  170774. ERREXIT(cinfo, JERR_NOTIMPL);
  170775. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  170776. ngroups = cinfo->min_DCT_scaled_size + 2;
  170777. } else {
  170778. ngroups = cinfo->min_DCT_scaled_size;
  170779. }
  170780. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170781. ci++, compptr++) {
  170782. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170783. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170784. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  170785. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170786. compptr->width_in_blocks * compptr->DCT_scaled_size,
  170787. (JDIMENSION) (rgroup * ngroups));
  170788. }
  170789. }
  170790. /*** End of inlined file: jdmainct.c ***/
  170791. /*** Start of inlined file: jdmarker.c ***/
  170792. #define JPEG_INTERNALS
  170793. /* Private state */
  170794. typedef struct {
  170795. struct jpeg_marker_reader pub; /* public fields */
  170796. /* Application-overridable marker processing methods */
  170797. jpeg_marker_parser_method process_COM;
  170798. jpeg_marker_parser_method process_APPn[16];
  170799. /* Limit on marker data length to save for each marker type */
  170800. unsigned int length_limit_COM;
  170801. unsigned int length_limit_APPn[16];
  170802. /* Status of COM/APPn marker saving */
  170803. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  170804. unsigned int bytes_read; /* data bytes read so far in marker */
  170805. /* Note: cur_marker is not linked into marker_list until it's all read. */
  170806. } my_marker_reader;
  170807. typedef my_marker_reader * my_marker_ptr2;
  170808. /*
  170809. * Macros for fetching data from the data source module.
  170810. *
  170811. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  170812. * the current restart point; we update them only when we have reached a
  170813. * suitable place to restart if a suspension occurs.
  170814. */
  170815. /* Declare and initialize local copies of input pointer/count */
  170816. #define INPUT_VARS(cinfo) \
  170817. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  170818. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  170819. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  170820. /* Unload the local copies --- do this only at a restart boundary */
  170821. #define INPUT_SYNC(cinfo) \
  170822. ( datasrc->next_input_byte = next_input_byte, \
  170823. datasrc->bytes_in_buffer = bytes_in_buffer )
  170824. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  170825. #define INPUT_RELOAD(cinfo) \
  170826. ( next_input_byte = datasrc->next_input_byte, \
  170827. bytes_in_buffer = datasrc->bytes_in_buffer )
  170828. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  170829. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  170830. * but we must reload the local copies after a successful fill.
  170831. */
  170832. #define MAKE_BYTE_AVAIL(cinfo,action) \
  170833. if (bytes_in_buffer == 0) { \
  170834. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  170835. { action; } \
  170836. INPUT_RELOAD(cinfo); \
  170837. }
  170838. /* Read a byte into variable V.
  170839. * If must suspend, take the specified action (typically "return FALSE").
  170840. */
  170841. #define INPUT_BYTE(cinfo,V,action) \
  170842. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170843. bytes_in_buffer--; \
  170844. V = GETJOCTET(*next_input_byte++); )
  170845. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  170846. * V should be declared unsigned int or perhaps INT32.
  170847. */
  170848. #define INPUT_2BYTES(cinfo,V,action) \
  170849. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  170850. bytes_in_buffer--; \
  170851. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  170852. MAKE_BYTE_AVAIL(cinfo,action); \
  170853. bytes_in_buffer--; \
  170854. V += GETJOCTET(*next_input_byte++); )
  170855. /*
  170856. * Routines to process JPEG markers.
  170857. *
  170858. * Entry condition: JPEG marker itself has been read and its code saved
  170859. * in cinfo->unread_marker; input restart point is just after the marker.
  170860. *
  170861. * Exit: if return TRUE, have read and processed any parameters, and have
  170862. * updated the restart point to point after the parameters.
  170863. * If return FALSE, was forced to suspend before reaching end of
  170864. * marker parameters; restart point has not been moved. Same routine
  170865. * will be called again after application supplies more input data.
  170866. *
  170867. * This approach to suspension assumes that all of a marker's parameters
  170868. * can fit into a single input bufferload. This should hold for "normal"
  170869. * markers. Some COM/APPn markers might have large parameter segments
  170870. * that might not fit. If we are simply dropping such a marker, we use
  170871. * skip_input_data to get past it, and thereby put the problem on the
  170872. * source manager's shoulders. If we are saving the marker's contents
  170873. * into memory, we use a slightly different convention: when forced to
  170874. * suspend, the marker processor updates the restart point to the end of
  170875. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  170876. * On resumption, cinfo->unread_marker still contains the marker code,
  170877. * but the data source will point to the next chunk of marker data.
  170878. * The marker processor must retain internal state to deal with this.
  170879. *
  170880. * Note that we don't bother to avoid duplicate trace messages if a
  170881. * suspension occurs within marker parameters. Other side effects
  170882. * require more care.
  170883. */
  170884. LOCAL(boolean)
  170885. get_soi (j_decompress_ptr cinfo)
  170886. /* Process an SOI marker */
  170887. {
  170888. int i;
  170889. TRACEMS(cinfo, 1, JTRC_SOI);
  170890. if (cinfo->marker->saw_SOI)
  170891. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  170892. /* Reset all parameters that are defined to be reset by SOI */
  170893. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  170894. cinfo->arith_dc_L[i] = 0;
  170895. cinfo->arith_dc_U[i] = 1;
  170896. cinfo->arith_ac_K[i] = 5;
  170897. }
  170898. cinfo->restart_interval = 0;
  170899. /* Set initial assumptions for colorspace etc */
  170900. cinfo->jpeg_color_space = JCS_UNKNOWN;
  170901. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  170902. cinfo->saw_JFIF_marker = FALSE;
  170903. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  170904. cinfo->JFIF_minor_version = 1;
  170905. cinfo->density_unit = 0;
  170906. cinfo->X_density = 1;
  170907. cinfo->Y_density = 1;
  170908. cinfo->saw_Adobe_marker = FALSE;
  170909. cinfo->Adobe_transform = 0;
  170910. cinfo->marker->saw_SOI = TRUE;
  170911. return TRUE;
  170912. }
  170913. LOCAL(boolean)
  170914. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  170915. /* Process a SOFn marker */
  170916. {
  170917. INT32 length;
  170918. int c, ci;
  170919. jpeg_component_info * compptr;
  170920. INPUT_VARS(cinfo);
  170921. cinfo->progressive_mode = is_prog;
  170922. cinfo->arith_code = is_arith;
  170923. INPUT_2BYTES(cinfo, length, return FALSE);
  170924. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  170925. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  170926. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  170927. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  170928. length -= 8;
  170929. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  170930. (int) cinfo->image_width, (int) cinfo->image_height,
  170931. cinfo->num_components);
  170932. if (cinfo->marker->saw_SOF)
  170933. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  170934. /* We don't support files in which the image height is initially specified */
  170935. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  170936. /* might as well have a general sanity check. */
  170937. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  170938. || cinfo->num_components <= 0)
  170939. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  170940. if (length != (cinfo->num_components * 3))
  170941. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170942. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  170943. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  170944. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170945. cinfo->num_components * SIZEOF(jpeg_component_info));
  170946. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170947. ci++, compptr++) {
  170948. compptr->component_index = ci;
  170949. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  170950. INPUT_BYTE(cinfo, c, return FALSE);
  170951. compptr->h_samp_factor = (c >> 4) & 15;
  170952. compptr->v_samp_factor = (c ) & 15;
  170953. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  170954. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  170955. compptr->component_id, compptr->h_samp_factor,
  170956. compptr->v_samp_factor, compptr->quant_tbl_no);
  170957. }
  170958. cinfo->marker->saw_SOF = TRUE;
  170959. INPUT_SYNC(cinfo);
  170960. return TRUE;
  170961. }
  170962. LOCAL(boolean)
  170963. get_sos (j_decompress_ptr cinfo)
  170964. /* Process a SOS marker */
  170965. {
  170966. INT32 length;
  170967. int i, ci, n, c, cc;
  170968. jpeg_component_info * compptr;
  170969. INPUT_VARS(cinfo);
  170970. if (! cinfo->marker->saw_SOF)
  170971. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  170972. INPUT_2BYTES(cinfo, length, return FALSE);
  170973. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  170974. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  170975. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  170976. ERREXIT(cinfo, JERR_BAD_LENGTH);
  170977. cinfo->comps_in_scan = n;
  170978. /* Collect the component-spec parameters */
  170979. for (i = 0; i < n; i++) {
  170980. INPUT_BYTE(cinfo, cc, return FALSE);
  170981. INPUT_BYTE(cinfo, c, return FALSE);
  170982. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170983. ci++, compptr++) {
  170984. if (cc == compptr->component_id)
  170985. goto id_found;
  170986. }
  170987. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  170988. id_found:
  170989. cinfo->cur_comp_info[i] = compptr;
  170990. compptr->dc_tbl_no = (c >> 4) & 15;
  170991. compptr->ac_tbl_no = (c ) & 15;
  170992. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  170993. compptr->dc_tbl_no, compptr->ac_tbl_no);
  170994. }
  170995. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  170996. INPUT_BYTE(cinfo, c, return FALSE);
  170997. cinfo->Ss = c;
  170998. INPUT_BYTE(cinfo, c, return FALSE);
  170999. cinfo->Se = c;
  171000. INPUT_BYTE(cinfo, c, return FALSE);
  171001. cinfo->Ah = (c >> 4) & 15;
  171002. cinfo->Al = (c ) & 15;
  171003. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171004. cinfo->Ah, cinfo->Al);
  171005. /* Prepare to scan data & restart markers */
  171006. cinfo->marker->next_restart_num = 0;
  171007. /* Count another SOS marker */
  171008. cinfo->input_scan_number++;
  171009. INPUT_SYNC(cinfo);
  171010. return TRUE;
  171011. }
  171012. #ifdef D_ARITH_CODING_SUPPORTED
  171013. LOCAL(boolean)
  171014. get_dac (j_decompress_ptr cinfo)
  171015. /* Process a DAC marker */
  171016. {
  171017. INT32 length;
  171018. int index, val;
  171019. INPUT_VARS(cinfo);
  171020. INPUT_2BYTES(cinfo, length, return FALSE);
  171021. length -= 2;
  171022. while (length > 0) {
  171023. INPUT_BYTE(cinfo, index, return FALSE);
  171024. INPUT_BYTE(cinfo, val, return FALSE);
  171025. length -= 2;
  171026. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171027. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171028. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171029. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171030. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171031. } else { /* define DC table */
  171032. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171033. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171034. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171035. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171036. }
  171037. }
  171038. if (length != 0)
  171039. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171040. INPUT_SYNC(cinfo);
  171041. return TRUE;
  171042. }
  171043. #else /* ! D_ARITH_CODING_SUPPORTED */
  171044. #define get_dac(cinfo) skip_variable(cinfo)
  171045. #endif /* D_ARITH_CODING_SUPPORTED */
  171046. LOCAL(boolean)
  171047. get_dht (j_decompress_ptr cinfo)
  171048. /* Process a DHT marker */
  171049. {
  171050. INT32 length;
  171051. UINT8 bits[17];
  171052. UINT8 huffval[256];
  171053. int i, index, count;
  171054. JHUFF_TBL **htblptr;
  171055. INPUT_VARS(cinfo);
  171056. INPUT_2BYTES(cinfo, length, return FALSE);
  171057. length -= 2;
  171058. while (length > 16) {
  171059. INPUT_BYTE(cinfo, index, return FALSE);
  171060. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171061. bits[0] = 0;
  171062. count = 0;
  171063. for (i = 1; i <= 16; i++) {
  171064. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171065. count += bits[i];
  171066. }
  171067. length -= 1 + 16;
  171068. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171069. bits[1], bits[2], bits[3], bits[4],
  171070. bits[5], bits[6], bits[7], bits[8]);
  171071. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171072. bits[9], bits[10], bits[11], bits[12],
  171073. bits[13], bits[14], bits[15], bits[16]);
  171074. /* Here we just do minimal validation of the counts to avoid walking
  171075. * off the end of our table space. jdhuff.c will check more carefully.
  171076. */
  171077. if (count > 256 || ((INT32) count) > length)
  171078. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171079. for (i = 0; i < count; i++)
  171080. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171081. length -= count;
  171082. if (index & 0x10) { /* AC table definition */
  171083. index -= 0x10;
  171084. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171085. } else { /* DC table definition */
  171086. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171087. }
  171088. if (index < 0 || index >= NUM_HUFF_TBLS)
  171089. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171090. if (*htblptr == NULL)
  171091. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171092. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171093. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171094. }
  171095. if (length != 0)
  171096. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171097. INPUT_SYNC(cinfo);
  171098. return TRUE;
  171099. }
  171100. LOCAL(boolean)
  171101. get_dqt (j_decompress_ptr cinfo)
  171102. /* Process a DQT marker */
  171103. {
  171104. INT32 length;
  171105. int n, i, prec;
  171106. unsigned int tmp;
  171107. JQUANT_TBL *quant_ptr;
  171108. INPUT_VARS(cinfo);
  171109. INPUT_2BYTES(cinfo, length, return FALSE);
  171110. length -= 2;
  171111. while (length > 0) {
  171112. INPUT_BYTE(cinfo, n, return FALSE);
  171113. prec = n >> 4;
  171114. n &= 0x0F;
  171115. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171116. if (n >= NUM_QUANT_TBLS)
  171117. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171118. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171119. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171120. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171121. for (i = 0; i < DCTSIZE2; i++) {
  171122. if (prec)
  171123. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171124. else
  171125. INPUT_BYTE(cinfo, tmp, return FALSE);
  171126. /* We convert the zigzag-order table to natural array order. */
  171127. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171128. }
  171129. if (cinfo->err->trace_level >= 2) {
  171130. for (i = 0; i < DCTSIZE2; i += 8) {
  171131. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171132. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171133. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171134. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171135. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171136. }
  171137. }
  171138. length -= DCTSIZE2+1;
  171139. if (prec) length -= DCTSIZE2;
  171140. }
  171141. if (length != 0)
  171142. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171143. INPUT_SYNC(cinfo);
  171144. return TRUE;
  171145. }
  171146. LOCAL(boolean)
  171147. get_dri (j_decompress_ptr cinfo)
  171148. /* Process a DRI marker */
  171149. {
  171150. INT32 length;
  171151. unsigned int tmp;
  171152. INPUT_VARS(cinfo);
  171153. INPUT_2BYTES(cinfo, length, return FALSE);
  171154. if (length != 4)
  171155. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171156. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171157. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171158. cinfo->restart_interval = tmp;
  171159. INPUT_SYNC(cinfo);
  171160. return TRUE;
  171161. }
  171162. /*
  171163. * Routines for processing APPn and COM markers.
  171164. * These are either saved in memory or discarded, per application request.
  171165. * APP0 and APP14 are specially checked to see if they are
  171166. * JFIF and Adobe markers, respectively.
  171167. */
  171168. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171169. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171170. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171171. LOCAL(void)
  171172. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171173. unsigned int datalen, INT32 remaining)
  171174. /* Examine first few bytes from an APP0.
  171175. * Take appropriate action if it is a JFIF marker.
  171176. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171177. */
  171178. {
  171179. INT32 totallen = (INT32) datalen + remaining;
  171180. if (datalen >= APP0_DATA_LEN &&
  171181. GETJOCTET(data[0]) == 0x4A &&
  171182. GETJOCTET(data[1]) == 0x46 &&
  171183. GETJOCTET(data[2]) == 0x49 &&
  171184. GETJOCTET(data[3]) == 0x46 &&
  171185. GETJOCTET(data[4]) == 0) {
  171186. /* Found JFIF APP0 marker: save info */
  171187. cinfo->saw_JFIF_marker = TRUE;
  171188. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171189. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171190. cinfo->density_unit = GETJOCTET(data[7]);
  171191. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171192. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171193. /* Check version.
  171194. * Major version must be 1, anything else signals an incompatible change.
  171195. * (We used to treat this as an error, but now it's a nonfatal warning,
  171196. * because some bozo at Hijaak couldn't read the spec.)
  171197. * Minor version should be 0..2, but process anyway if newer.
  171198. */
  171199. if (cinfo->JFIF_major_version != 1)
  171200. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171201. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171202. /* Generate trace messages */
  171203. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171204. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171205. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171206. /* Validate thumbnail dimensions and issue appropriate messages */
  171207. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171208. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171209. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171210. totallen -= APP0_DATA_LEN;
  171211. if (totallen !=
  171212. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171213. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171214. } else if (datalen >= 6 &&
  171215. GETJOCTET(data[0]) == 0x4A &&
  171216. GETJOCTET(data[1]) == 0x46 &&
  171217. GETJOCTET(data[2]) == 0x58 &&
  171218. GETJOCTET(data[3]) == 0x58 &&
  171219. GETJOCTET(data[4]) == 0) {
  171220. /* Found JFIF "JFXX" extension APP0 marker */
  171221. /* The library doesn't actually do anything with these,
  171222. * but we try to produce a helpful trace message.
  171223. */
  171224. switch (GETJOCTET(data[5])) {
  171225. case 0x10:
  171226. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171227. break;
  171228. case 0x11:
  171229. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171230. break;
  171231. case 0x13:
  171232. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171233. break;
  171234. default:
  171235. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171236. GETJOCTET(data[5]), (int) totallen);
  171237. break;
  171238. }
  171239. } else {
  171240. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171241. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171242. }
  171243. }
  171244. LOCAL(void)
  171245. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171246. unsigned int datalen, INT32 remaining)
  171247. /* Examine first few bytes from an APP14.
  171248. * Take appropriate action if it is an Adobe marker.
  171249. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171250. */
  171251. {
  171252. unsigned int version, flags0, flags1, transform;
  171253. if (datalen >= APP14_DATA_LEN &&
  171254. GETJOCTET(data[0]) == 0x41 &&
  171255. GETJOCTET(data[1]) == 0x64 &&
  171256. GETJOCTET(data[2]) == 0x6F &&
  171257. GETJOCTET(data[3]) == 0x62 &&
  171258. GETJOCTET(data[4]) == 0x65) {
  171259. /* Found Adobe APP14 marker */
  171260. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171261. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171262. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171263. transform = GETJOCTET(data[11]);
  171264. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171265. cinfo->saw_Adobe_marker = TRUE;
  171266. cinfo->Adobe_transform = (UINT8) transform;
  171267. } else {
  171268. /* Start of APP14 does not match "Adobe", or too short */
  171269. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171270. }
  171271. }
  171272. METHODDEF(boolean)
  171273. get_interesting_appn (j_decompress_ptr cinfo)
  171274. /* Process an APP0 or APP14 marker without saving it */
  171275. {
  171276. INT32 length;
  171277. JOCTET b[APPN_DATA_LEN];
  171278. unsigned int i, numtoread;
  171279. INPUT_VARS(cinfo);
  171280. INPUT_2BYTES(cinfo, length, return FALSE);
  171281. length -= 2;
  171282. /* get the interesting part of the marker data */
  171283. if (length >= APPN_DATA_LEN)
  171284. numtoread = APPN_DATA_LEN;
  171285. else if (length > 0)
  171286. numtoread = (unsigned int) length;
  171287. else
  171288. numtoread = 0;
  171289. for (i = 0; i < numtoread; i++)
  171290. INPUT_BYTE(cinfo, b[i], return FALSE);
  171291. length -= numtoread;
  171292. /* process it */
  171293. switch (cinfo->unread_marker) {
  171294. case M_APP0:
  171295. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171296. break;
  171297. case M_APP14:
  171298. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171299. break;
  171300. default:
  171301. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171302. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171303. break;
  171304. }
  171305. /* skip any remaining data -- could be lots */
  171306. INPUT_SYNC(cinfo);
  171307. if (length > 0)
  171308. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171309. return TRUE;
  171310. }
  171311. #ifdef SAVE_MARKERS_SUPPORTED
  171312. METHODDEF(boolean)
  171313. save_marker (j_decompress_ptr cinfo)
  171314. /* Save an APPn or COM marker into the marker list */
  171315. {
  171316. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171317. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171318. unsigned int bytes_read, data_length;
  171319. JOCTET FAR * data;
  171320. INT32 length = 0;
  171321. INPUT_VARS(cinfo);
  171322. if (cur_marker == NULL) {
  171323. /* begin reading a marker */
  171324. INPUT_2BYTES(cinfo, length, return FALSE);
  171325. length -= 2;
  171326. if (length >= 0) { /* watch out for bogus length word */
  171327. /* figure out how much we want to save */
  171328. unsigned int limit;
  171329. if (cinfo->unread_marker == (int) M_COM)
  171330. limit = marker->length_limit_COM;
  171331. else
  171332. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171333. if ((unsigned int) length < limit)
  171334. limit = (unsigned int) length;
  171335. /* allocate and initialize the marker item */
  171336. cur_marker = (jpeg_saved_marker_ptr)
  171337. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171338. SIZEOF(struct jpeg_marker_struct) + limit);
  171339. cur_marker->next = NULL;
  171340. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171341. cur_marker->original_length = (unsigned int) length;
  171342. cur_marker->data_length = limit;
  171343. /* data area is just beyond the jpeg_marker_struct */
  171344. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171345. marker->cur_marker = cur_marker;
  171346. marker->bytes_read = 0;
  171347. bytes_read = 0;
  171348. data_length = limit;
  171349. } else {
  171350. /* deal with bogus length word */
  171351. bytes_read = data_length = 0;
  171352. data = NULL;
  171353. }
  171354. } else {
  171355. /* resume reading a marker */
  171356. bytes_read = marker->bytes_read;
  171357. data_length = cur_marker->data_length;
  171358. data = cur_marker->data + bytes_read;
  171359. }
  171360. while (bytes_read < data_length) {
  171361. INPUT_SYNC(cinfo); /* move the restart point to here */
  171362. marker->bytes_read = bytes_read;
  171363. /* If there's not at least one byte in buffer, suspend */
  171364. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171365. /* Copy bytes with reasonable rapidity */
  171366. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171367. *data++ = *next_input_byte++;
  171368. bytes_in_buffer--;
  171369. bytes_read++;
  171370. }
  171371. }
  171372. /* Done reading what we want to read */
  171373. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171374. /* Add new marker to end of list */
  171375. if (cinfo->marker_list == NULL) {
  171376. cinfo->marker_list = cur_marker;
  171377. } else {
  171378. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171379. while (prev->next != NULL)
  171380. prev = prev->next;
  171381. prev->next = cur_marker;
  171382. }
  171383. /* Reset pointer & calc remaining data length */
  171384. data = cur_marker->data;
  171385. length = cur_marker->original_length - data_length;
  171386. }
  171387. /* Reset to initial state for next marker */
  171388. marker->cur_marker = NULL;
  171389. /* Process the marker if interesting; else just make a generic trace msg */
  171390. switch (cinfo->unread_marker) {
  171391. case M_APP0:
  171392. examine_app0(cinfo, data, data_length, length);
  171393. break;
  171394. case M_APP14:
  171395. examine_app14(cinfo, data, data_length, length);
  171396. break;
  171397. default:
  171398. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171399. (int) (data_length + length));
  171400. break;
  171401. }
  171402. /* skip any remaining data -- could be lots */
  171403. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171404. if (length > 0)
  171405. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171406. return TRUE;
  171407. }
  171408. #endif /* SAVE_MARKERS_SUPPORTED */
  171409. METHODDEF(boolean)
  171410. skip_variable (j_decompress_ptr cinfo)
  171411. /* Skip over an unknown or uninteresting variable-length marker */
  171412. {
  171413. INT32 length;
  171414. INPUT_VARS(cinfo);
  171415. INPUT_2BYTES(cinfo, length, return FALSE);
  171416. length -= 2;
  171417. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171418. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171419. if (length > 0)
  171420. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171421. return TRUE;
  171422. }
  171423. /*
  171424. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171425. * Returns FALSE if had to suspend before reaching a marker;
  171426. * in that case cinfo->unread_marker is unchanged.
  171427. *
  171428. * Note that the result might not be a valid marker code,
  171429. * but it will never be 0 or FF.
  171430. */
  171431. LOCAL(boolean)
  171432. next_marker (j_decompress_ptr cinfo)
  171433. {
  171434. int c;
  171435. INPUT_VARS(cinfo);
  171436. for (;;) {
  171437. INPUT_BYTE(cinfo, c, return FALSE);
  171438. /* Skip any non-FF bytes.
  171439. * This may look a bit inefficient, but it will not occur in a valid file.
  171440. * We sync after each discarded byte so that a suspending data source
  171441. * can discard the byte from its buffer.
  171442. */
  171443. while (c != 0xFF) {
  171444. cinfo->marker->discarded_bytes++;
  171445. INPUT_SYNC(cinfo);
  171446. INPUT_BYTE(cinfo, c, return FALSE);
  171447. }
  171448. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171449. * pad bytes, so don't count them in discarded_bytes. We assume there
  171450. * will not be so many consecutive FF bytes as to overflow a suspending
  171451. * data source's input buffer.
  171452. */
  171453. do {
  171454. INPUT_BYTE(cinfo, c, return FALSE);
  171455. } while (c == 0xFF);
  171456. if (c != 0)
  171457. break; /* found a valid marker, exit loop */
  171458. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171459. * Discard it and loop back to try again.
  171460. */
  171461. cinfo->marker->discarded_bytes += 2;
  171462. INPUT_SYNC(cinfo);
  171463. }
  171464. if (cinfo->marker->discarded_bytes != 0) {
  171465. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171466. cinfo->marker->discarded_bytes = 0;
  171467. }
  171468. cinfo->unread_marker = c;
  171469. INPUT_SYNC(cinfo);
  171470. return TRUE;
  171471. }
  171472. LOCAL(boolean)
  171473. first_marker (j_decompress_ptr cinfo)
  171474. /* Like next_marker, but used to obtain the initial SOI marker. */
  171475. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171476. * we might well scan an entire input file before realizing it ain't JPEG.
  171477. * If an application wants to process non-JFIF files, it must seek to the
  171478. * SOI before calling the JPEG library.
  171479. */
  171480. {
  171481. int c, c2;
  171482. INPUT_VARS(cinfo);
  171483. INPUT_BYTE(cinfo, c, return FALSE);
  171484. INPUT_BYTE(cinfo, c2, return FALSE);
  171485. if (c != 0xFF || c2 != (int) M_SOI)
  171486. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171487. cinfo->unread_marker = c2;
  171488. INPUT_SYNC(cinfo);
  171489. return TRUE;
  171490. }
  171491. /*
  171492. * Read markers until SOS or EOI.
  171493. *
  171494. * Returns same codes as are defined for jpeg_consume_input:
  171495. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171496. */
  171497. METHODDEF(int)
  171498. read_markers (j_decompress_ptr cinfo)
  171499. {
  171500. /* Outer loop repeats once for each marker. */
  171501. for (;;) {
  171502. /* Collect the marker proper, unless we already did. */
  171503. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171504. if (cinfo->unread_marker == 0) {
  171505. if (! cinfo->marker->saw_SOI) {
  171506. if (! first_marker(cinfo))
  171507. return JPEG_SUSPENDED;
  171508. } else {
  171509. if (! next_marker(cinfo))
  171510. return JPEG_SUSPENDED;
  171511. }
  171512. }
  171513. /* At this point cinfo->unread_marker contains the marker code and the
  171514. * input point is just past the marker proper, but before any parameters.
  171515. * A suspension will cause us to return with this state still true.
  171516. */
  171517. switch (cinfo->unread_marker) {
  171518. case M_SOI:
  171519. if (! get_soi(cinfo))
  171520. return JPEG_SUSPENDED;
  171521. break;
  171522. case M_SOF0: /* Baseline */
  171523. case M_SOF1: /* Extended sequential, Huffman */
  171524. if (! get_sof(cinfo, FALSE, FALSE))
  171525. return JPEG_SUSPENDED;
  171526. break;
  171527. case M_SOF2: /* Progressive, Huffman */
  171528. if (! get_sof(cinfo, TRUE, FALSE))
  171529. return JPEG_SUSPENDED;
  171530. break;
  171531. case M_SOF9: /* Extended sequential, arithmetic */
  171532. if (! get_sof(cinfo, FALSE, TRUE))
  171533. return JPEG_SUSPENDED;
  171534. break;
  171535. case M_SOF10: /* Progressive, arithmetic */
  171536. if (! get_sof(cinfo, TRUE, TRUE))
  171537. return JPEG_SUSPENDED;
  171538. break;
  171539. /* Currently unsupported SOFn types */
  171540. case M_SOF3: /* Lossless, Huffman */
  171541. case M_SOF5: /* Differential sequential, Huffman */
  171542. case M_SOF6: /* Differential progressive, Huffman */
  171543. case M_SOF7: /* Differential lossless, Huffman */
  171544. case M_JPG: /* Reserved for JPEG extensions */
  171545. case M_SOF11: /* Lossless, arithmetic */
  171546. case M_SOF13: /* Differential sequential, arithmetic */
  171547. case M_SOF14: /* Differential progressive, arithmetic */
  171548. case M_SOF15: /* Differential lossless, arithmetic */
  171549. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171550. break;
  171551. case M_SOS:
  171552. if (! get_sos(cinfo))
  171553. return JPEG_SUSPENDED;
  171554. cinfo->unread_marker = 0; /* processed the marker */
  171555. return JPEG_REACHED_SOS;
  171556. case M_EOI:
  171557. TRACEMS(cinfo, 1, JTRC_EOI);
  171558. cinfo->unread_marker = 0; /* processed the marker */
  171559. return JPEG_REACHED_EOI;
  171560. case M_DAC:
  171561. if (! get_dac(cinfo))
  171562. return JPEG_SUSPENDED;
  171563. break;
  171564. case M_DHT:
  171565. if (! get_dht(cinfo))
  171566. return JPEG_SUSPENDED;
  171567. break;
  171568. case M_DQT:
  171569. if (! get_dqt(cinfo))
  171570. return JPEG_SUSPENDED;
  171571. break;
  171572. case M_DRI:
  171573. if (! get_dri(cinfo))
  171574. return JPEG_SUSPENDED;
  171575. break;
  171576. case M_APP0:
  171577. case M_APP1:
  171578. case M_APP2:
  171579. case M_APP3:
  171580. case M_APP4:
  171581. case M_APP5:
  171582. case M_APP6:
  171583. case M_APP7:
  171584. case M_APP8:
  171585. case M_APP9:
  171586. case M_APP10:
  171587. case M_APP11:
  171588. case M_APP12:
  171589. case M_APP13:
  171590. case M_APP14:
  171591. case M_APP15:
  171592. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171593. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171594. return JPEG_SUSPENDED;
  171595. break;
  171596. case M_COM:
  171597. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171598. return JPEG_SUSPENDED;
  171599. break;
  171600. case M_RST0: /* these are all parameterless */
  171601. case M_RST1:
  171602. case M_RST2:
  171603. case M_RST3:
  171604. case M_RST4:
  171605. case M_RST5:
  171606. case M_RST6:
  171607. case M_RST7:
  171608. case M_TEM:
  171609. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171610. break;
  171611. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171612. if (! skip_variable(cinfo))
  171613. return JPEG_SUSPENDED;
  171614. break;
  171615. default: /* must be DHP, EXP, JPGn, or RESn */
  171616. /* For now, we treat the reserved markers as fatal errors since they are
  171617. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171618. * Once the JPEG 3 version-number marker is well defined, this code
  171619. * ought to change!
  171620. */
  171621. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171622. break;
  171623. }
  171624. /* Successfully processed marker, so reset state variable */
  171625. cinfo->unread_marker = 0;
  171626. } /* end loop */
  171627. }
  171628. /*
  171629. * Read a restart marker, which is expected to appear next in the datastream;
  171630. * if the marker is not there, take appropriate recovery action.
  171631. * Returns FALSE if suspension is required.
  171632. *
  171633. * This is called by the entropy decoder after it has read an appropriate
  171634. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171635. * has already read a marker from the data source. Under normal conditions
  171636. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171637. * it holds a marker which the decoder will be unable to read past.
  171638. */
  171639. METHODDEF(boolean)
  171640. read_restart_marker (j_decompress_ptr cinfo)
  171641. {
  171642. /* Obtain a marker unless we already did. */
  171643. /* Note that next_marker will complain if it skips any data. */
  171644. if (cinfo->unread_marker == 0) {
  171645. if (! next_marker(cinfo))
  171646. return FALSE;
  171647. }
  171648. if (cinfo->unread_marker ==
  171649. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171650. /* Normal case --- swallow the marker and let entropy decoder continue */
  171651. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171652. cinfo->unread_marker = 0;
  171653. } else {
  171654. /* Uh-oh, the restart markers have been messed up. */
  171655. /* Let the data source manager determine how to resync. */
  171656. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171657. cinfo->marker->next_restart_num))
  171658. return FALSE;
  171659. }
  171660. /* Update next-restart state */
  171661. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  171662. return TRUE;
  171663. }
  171664. /*
  171665. * This is the default resync_to_restart method for data source managers
  171666. * to use if they don't have any better approach. Some data source managers
  171667. * may be able to back up, or may have additional knowledge about the data
  171668. * which permits a more intelligent recovery strategy; such managers would
  171669. * presumably supply their own resync method.
  171670. *
  171671. * read_restart_marker calls resync_to_restart if it finds a marker other than
  171672. * the restart marker it was expecting. (This code is *not* used unless
  171673. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  171674. * the marker code actually found (might be anything, except 0 or FF).
  171675. * The desired restart marker number (0..7) is passed as a parameter.
  171676. * This routine is supposed to apply whatever error recovery strategy seems
  171677. * appropriate in order to position the input stream to the next data segment.
  171678. * Note that cinfo->unread_marker is treated as a marker appearing before
  171679. * the current data-source input point; usually it should be reset to zero
  171680. * before returning.
  171681. * Returns FALSE if suspension is required.
  171682. *
  171683. * This implementation is substantially constrained by wanting to treat the
  171684. * input as a data stream; this means we can't back up. Therefore, we have
  171685. * only the following actions to work with:
  171686. * 1. Simply discard the marker and let the entropy decoder resume at next
  171687. * byte of file.
  171688. * 2. Read forward until we find another marker, discarding intervening
  171689. * data. (In theory we could look ahead within the current bufferload,
  171690. * without having to discard data if we don't find the desired marker.
  171691. * This idea is not implemented here, in part because it makes behavior
  171692. * dependent on buffer size and chance buffer-boundary positions.)
  171693. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  171694. * This will cause the entropy decoder to process an empty data segment,
  171695. * inserting dummy zeroes, and then we will reprocess the marker.
  171696. *
  171697. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  171698. * appropriate if the found marker is a future restart marker (indicating
  171699. * that we have missed the desired restart marker, probably because it got
  171700. * corrupted).
  171701. * We apply #2 or #3 if the found marker is a restart marker no more than
  171702. * two counts behind or ahead of the expected one. We also apply #2 if the
  171703. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  171704. * If the found marker is a restart marker more than 2 counts away, we do #1
  171705. * (too much risk that the marker is erroneous; with luck we will be able to
  171706. * resync at some future point).
  171707. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  171708. * overrunning the end of a scan. An implementation limited to single-scan
  171709. * files might find it better to apply #2 for markers other than EOI, since
  171710. * any other marker would have to be bogus data in that case.
  171711. */
  171712. GLOBAL(boolean)
  171713. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  171714. {
  171715. int marker = cinfo->unread_marker;
  171716. int action = 1;
  171717. /* Always put up a warning. */
  171718. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  171719. /* Outer loop handles repeated decision after scanning forward. */
  171720. for (;;) {
  171721. if (marker < (int) M_SOF0)
  171722. action = 2; /* invalid marker */
  171723. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  171724. action = 3; /* valid non-restart marker */
  171725. else {
  171726. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  171727. marker == ((int) M_RST0 + ((desired+2) & 7)))
  171728. action = 3; /* one of the next two expected restarts */
  171729. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  171730. marker == ((int) M_RST0 + ((desired-2) & 7)))
  171731. action = 2; /* a prior restart, so advance */
  171732. else
  171733. action = 1; /* desired restart or too far away */
  171734. }
  171735. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  171736. switch (action) {
  171737. case 1:
  171738. /* Discard marker and let entropy decoder resume processing. */
  171739. cinfo->unread_marker = 0;
  171740. return TRUE;
  171741. case 2:
  171742. /* Scan to the next marker, and repeat the decision loop. */
  171743. if (! next_marker(cinfo))
  171744. return FALSE;
  171745. marker = cinfo->unread_marker;
  171746. break;
  171747. case 3:
  171748. /* Return without advancing past this marker. */
  171749. /* Entropy decoder will be forced to process an empty segment. */
  171750. return TRUE;
  171751. }
  171752. } /* end loop */
  171753. }
  171754. /*
  171755. * Reset marker processing state to begin a fresh datastream.
  171756. */
  171757. METHODDEF(void)
  171758. reset_marker_reader (j_decompress_ptr cinfo)
  171759. {
  171760. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171761. cinfo->comp_info = NULL; /* until allocated by get_sof */
  171762. cinfo->input_scan_number = 0; /* no SOS seen yet */
  171763. cinfo->unread_marker = 0; /* no pending marker */
  171764. marker->pub.saw_SOI = FALSE; /* set internal state too */
  171765. marker->pub.saw_SOF = FALSE;
  171766. marker->pub.discarded_bytes = 0;
  171767. marker->cur_marker = NULL;
  171768. }
  171769. /*
  171770. * Initialize the marker reader module.
  171771. * This is called only once, when the decompression object is created.
  171772. */
  171773. GLOBAL(void)
  171774. jinit_marker_reader (j_decompress_ptr cinfo)
  171775. {
  171776. my_marker_ptr2 marker;
  171777. int i;
  171778. /* Create subobject in permanent pool */
  171779. marker = (my_marker_ptr2)
  171780. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171781. SIZEOF(my_marker_reader));
  171782. cinfo->marker = (struct jpeg_marker_reader *) marker;
  171783. /* Initialize public method pointers */
  171784. marker->pub.reset_marker_reader = reset_marker_reader;
  171785. marker->pub.read_markers = read_markers;
  171786. marker->pub.read_restart_marker = read_restart_marker;
  171787. /* Initialize COM/APPn processing.
  171788. * By default, we examine and then discard APP0 and APP14,
  171789. * but simply discard COM and all other APPn.
  171790. */
  171791. marker->process_COM = skip_variable;
  171792. marker->length_limit_COM = 0;
  171793. for (i = 0; i < 16; i++) {
  171794. marker->process_APPn[i] = skip_variable;
  171795. marker->length_limit_APPn[i] = 0;
  171796. }
  171797. marker->process_APPn[0] = get_interesting_appn;
  171798. marker->process_APPn[14] = get_interesting_appn;
  171799. /* Reset marker processing state */
  171800. reset_marker_reader(cinfo);
  171801. }
  171802. /*
  171803. * Control saving of COM and APPn markers into marker_list.
  171804. */
  171805. #ifdef SAVE_MARKERS_SUPPORTED
  171806. GLOBAL(void)
  171807. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  171808. unsigned int length_limit)
  171809. {
  171810. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171811. long maxlength;
  171812. jpeg_marker_parser_method processor;
  171813. /* Length limit mustn't be larger than what we can allocate
  171814. * (should only be a concern in a 16-bit environment).
  171815. */
  171816. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  171817. if (((long) length_limit) > maxlength)
  171818. length_limit = (unsigned int) maxlength;
  171819. /* Choose processor routine to use.
  171820. * APP0/APP14 have special requirements.
  171821. */
  171822. if (length_limit) {
  171823. processor = save_marker;
  171824. /* If saving APP0/APP14, save at least enough for our internal use. */
  171825. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  171826. length_limit = APP0_DATA_LEN;
  171827. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  171828. length_limit = APP14_DATA_LEN;
  171829. } else {
  171830. processor = skip_variable;
  171831. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  171832. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  171833. processor = get_interesting_appn;
  171834. }
  171835. if (marker_code == (int) M_COM) {
  171836. marker->process_COM = processor;
  171837. marker->length_limit_COM = length_limit;
  171838. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  171839. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  171840. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  171841. } else
  171842. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171843. }
  171844. #endif /* SAVE_MARKERS_SUPPORTED */
  171845. /*
  171846. * Install a special processing method for COM or APPn markers.
  171847. */
  171848. GLOBAL(void)
  171849. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  171850. jpeg_marker_parser_method routine)
  171851. {
  171852. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171853. if (marker_code == (int) M_COM)
  171854. marker->process_COM = routine;
  171855. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  171856. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  171857. else
  171858. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  171859. }
  171860. /*** End of inlined file: jdmarker.c ***/
  171861. /*** Start of inlined file: jdmaster.c ***/
  171862. #define JPEG_INTERNALS
  171863. /* Private state */
  171864. typedef struct {
  171865. struct jpeg_decomp_master pub; /* public fields */
  171866. int pass_number; /* # of passes completed */
  171867. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  171868. /* Saved references to initialized quantizer modules,
  171869. * in case we need to switch modes.
  171870. */
  171871. struct jpeg_color_quantizer * quantizer_1pass;
  171872. struct jpeg_color_quantizer * quantizer_2pass;
  171873. } my_decomp_master;
  171874. typedef my_decomp_master * my_master_ptr6;
  171875. /*
  171876. * Determine whether merged upsample/color conversion should be used.
  171877. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  171878. */
  171879. LOCAL(boolean)
  171880. use_merged_upsample (j_decompress_ptr cinfo)
  171881. {
  171882. #ifdef UPSAMPLE_MERGING_SUPPORTED
  171883. /* Merging is the equivalent of plain box-filter upsampling */
  171884. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  171885. return FALSE;
  171886. /* jdmerge.c only supports YCC=>RGB color conversion */
  171887. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  171888. cinfo->out_color_space != JCS_RGB ||
  171889. cinfo->out_color_components != RGB_PIXELSIZE)
  171890. return FALSE;
  171891. /* and it only handles 2h1v or 2h2v sampling ratios */
  171892. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  171893. cinfo->comp_info[1].h_samp_factor != 1 ||
  171894. cinfo->comp_info[2].h_samp_factor != 1 ||
  171895. cinfo->comp_info[0].v_samp_factor > 2 ||
  171896. cinfo->comp_info[1].v_samp_factor != 1 ||
  171897. cinfo->comp_info[2].v_samp_factor != 1)
  171898. return FALSE;
  171899. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  171900. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171901. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  171902. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  171903. return FALSE;
  171904. /* ??? also need to test for upsample-time rescaling, when & if supported */
  171905. return TRUE; /* by golly, it'll work... */
  171906. #else
  171907. return FALSE;
  171908. #endif
  171909. }
  171910. /*
  171911. * Compute output image dimensions and related values.
  171912. * NOTE: this is exported for possible use by application.
  171913. * Hence it mustn't do anything that can't be done twice.
  171914. * Also note that it may be called before the master module is initialized!
  171915. */
  171916. GLOBAL(void)
  171917. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  171918. /* Do computations that are needed before master selection phase */
  171919. {
  171920. #ifdef IDCT_SCALING_SUPPORTED
  171921. int ci;
  171922. jpeg_component_info *compptr;
  171923. #endif
  171924. /* Prevent application from calling me at wrong times */
  171925. if (cinfo->global_state != DSTATE_READY)
  171926. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  171927. #ifdef IDCT_SCALING_SUPPORTED
  171928. /* Compute actual output image dimensions and DCT scaling choices. */
  171929. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  171930. /* Provide 1/8 scaling */
  171931. cinfo->output_width = (JDIMENSION)
  171932. jdiv_round_up((long) cinfo->image_width, 8L);
  171933. cinfo->output_height = (JDIMENSION)
  171934. jdiv_round_up((long) cinfo->image_height, 8L);
  171935. cinfo->min_DCT_scaled_size = 1;
  171936. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  171937. /* Provide 1/4 scaling */
  171938. cinfo->output_width = (JDIMENSION)
  171939. jdiv_round_up((long) cinfo->image_width, 4L);
  171940. cinfo->output_height = (JDIMENSION)
  171941. jdiv_round_up((long) cinfo->image_height, 4L);
  171942. cinfo->min_DCT_scaled_size = 2;
  171943. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  171944. /* Provide 1/2 scaling */
  171945. cinfo->output_width = (JDIMENSION)
  171946. jdiv_round_up((long) cinfo->image_width, 2L);
  171947. cinfo->output_height = (JDIMENSION)
  171948. jdiv_round_up((long) cinfo->image_height, 2L);
  171949. cinfo->min_DCT_scaled_size = 4;
  171950. } else {
  171951. /* Provide 1/1 scaling */
  171952. cinfo->output_width = cinfo->image_width;
  171953. cinfo->output_height = cinfo->image_height;
  171954. cinfo->min_DCT_scaled_size = DCTSIZE;
  171955. }
  171956. /* In selecting the actual DCT scaling for each component, we try to
  171957. * scale up the chroma components via IDCT scaling rather than upsampling.
  171958. * This saves time if the upsampler gets to use 1:1 scaling.
  171959. * Note this code assumes that the supported DCT scalings are powers of 2.
  171960. */
  171961. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171962. ci++, compptr++) {
  171963. int ssize = cinfo->min_DCT_scaled_size;
  171964. while (ssize < DCTSIZE &&
  171965. (compptr->h_samp_factor * ssize * 2 <=
  171966. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  171967. (compptr->v_samp_factor * ssize * 2 <=
  171968. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  171969. ssize = ssize * 2;
  171970. }
  171971. compptr->DCT_scaled_size = ssize;
  171972. }
  171973. /* Recompute downsampled dimensions of components;
  171974. * application needs to know these if using raw downsampled data.
  171975. */
  171976. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171977. ci++, compptr++) {
  171978. /* Size in samples, after IDCT scaling */
  171979. compptr->downsampled_width = (JDIMENSION)
  171980. jdiv_round_up((long) cinfo->image_width *
  171981. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  171982. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171983. compptr->downsampled_height = (JDIMENSION)
  171984. jdiv_round_up((long) cinfo->image_height *
  171985. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  171986. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171987. }
  171988. #else /* !IDCT_SCALING_SUPPORTED */
  171989. /* Hardwire it to "no scaling" */
  171990. cinfo->output_width = cinfo->image_width;
  171991. cinfo->output_height = cinfo->image_height;
  171992. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  171993. * and has computed unscaled downsampled_width and downsampled_height.
  171994. */
  171995. #endif /* IDCT_SCALING_SUPPORTED */
  171996. /* Report number of components in selected colorspace. */
  171997. /* Probably this should be in the color conversion module... */
  171998. switch (cinfo->out_color_space) {
  171999. case JCS_GRAYSCALE:
  172000. cinfo->out_color_components = 1;
  172001. break;
  172002. case JCS_RGB:
  172003. #if RGB_PIXELSIZE != 3
  172004. cinfo->out_color_components = RGB_PIXELSIZE;
  172005. break;
  172006. #endif /* else share code with YCbCr */
  172007. case JCS_YCbCr:
  172008. cinfo->out_color_components = 3;
  172009. break;
  172010. case JCS_CMYK:
  172011. case JCS_YCCK:
  172012. cinfo->out_color_components = 4;
  172013. break;
  172014. default: /* else must be same colorspace as in file */
  172015. cinfo->out_color_components = cinfo->num_components;
  172016. break;
  172017. }
  172018. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172019. cinfo->out_color_components);
  172020. /* See if upsampler will want to emit more than one row at a time */
  172021. if (use_merged_upsample(cinfo))
  172022. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172023. else
  172024. cinfo->rec_outbuf_height = 1;
  172025. }
  172026. /*
  172027. * Several decompression processes need to range-limit values to the range
  172028. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172029. * due to noise introduced by quantization, roundoff error, etc. These
  172030. * processes are inner loops and need to be as fast as possible. On most
  172031. * machines, particularly CPUs with pipelines or instruction prefetch,
  172032. * a (subscript-check-less) C table lookup
  172033. * x = sample_range_limit[x];
  172034. * is faster than explicit tests
  172035. * if (x < 0) x = 0;
  172036. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172037. * These processes all use a common table prepared by the routine below.
  172038. *
  172039. * For most steps we can mathematically guarantee that the initial value
  172040. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172041. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172042. * limiting step (just after the IDCT), a wildly out-of-range value is
  172043. * possible if the input data is corrupt. To avoid any chance of indexing
  172044. * off the end of memory and getting a bad-pointer trap, we perform the
  172045. * post-IDCT limiting thus:
  172046. * x = range_limit[x & MASK];
  172047. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172048. * samples. Under normal circumstances this is more than enough range and
  172049. * a correct output will be generated; with bogus input data the mask will
  172050. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172051. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172052. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172053. * So the post-IDCT limiting table ends up looking like this:
  172054. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172055. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172056. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172057. * 0,1,...,CENTERJSAMPLE-1
  172058. * Negative inputs select values from the upper half of the table after
  172059. * masking.
  172060. *
  172061. * We can save some space by overlapping the start of the post-IDCT table
  172062. * with the simpler range limiting table. The post-IDCT table begins at
  172063. * sample_range_limit + CENTERJSAMPLE.
  172064. *
  172065. * Note that the table is allocated in near data space on PCs; it's small
  172066. * enough and used often enough to justify this.
  172067. */
  172068. LOCAL(void)
  172069. prepare_range_limit_table (j_decompress_ptr cinfo)
  172070. /* Allocate and fill in the sample_range_limit table */
  172071. {
  172072. JSAMPLE * table;
  172073. int i;
  172074. table = (JSAMPLE *)
  172075. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172076. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172077. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172078. cinfo->sample_range_limit = table;
  172079. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172080. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172081. /* Main part of "simple" table: limit[x] = x */
  172082. for (i = 0; i <= MAXJSAMPLE; i++)
  172083. table[i] = (JSAMPLE) i;
  172084. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172085. /* End of simple table, rest of first half of post-IDCT table */
  172086. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172087. table[i] = MAXJSAMPLE;
  172088. /* Second half of post-IDCT table */
  172089. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172090. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172091. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172092. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172093. }
  172094. /*
  172095. * Master selection of decompression modules.
  172096. * This is done once at jpeg_start_decompress time. We determine
  172097. * which modules will be used and give them appropriate initialization calls.
  172098. * We also initialize the decompressor input side to begin consuming data.
  172099. *
  172100. * Since jpeg_read_header has finished, we know what is in the SOF
  172101. * and (first) SOS markers. We also have all the application parameter
  172102. * settings.
  172103. */
  172104. LOCAL(void)
  172105. master_selection (j_decompress_ptr cinfo)
  172106. {
  172107. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172108. boolean use_c_buffer;
  172109. long samplesperrow;
  172110. JDIMENSION jd_samplesperrow;
  172111. /* Initialize dimensions and other stuff */
  172112. jpeg_calc_output_dimensions(cinfo);
  172113. prepare_range_limit_table(cinfo);
  172114. /* Width of an output scanline must be representable as JDIMENSION. */
  172115. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172116. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172117. if ((long) jd_samplesperrow != samplesperrow)
  172118. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172119. /* Initialize my private state */
  172120. master->pass_number = 0;
  172121. master->using_merged_upsample = use_merged_upsample(cinfo);
  172122. /* Color quantizer selection */
  172123. master->quantizer_1pass = NULL;
  172124. master->quantizer_2pass = NULL;
  172125. /* No mode changes if not using buffered-image mode. */
  172126. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172127. cinfo->enable_1pass_quant = FALSE;
  172128. cinfo->enable_external_quant = FALSE;
  172129. cinfo->enable_2pass_quant = FALSE;
  172130. }
  172131. if (cinfo->quantize_colors) {
  172132. if (cinfo->raw_data_out)
  172133. ERREXIT(cinfo, JERR_NOTIMPL);
  172134. /* 2-pass quantizer only works in 3-component color space. */
  172135. if (cinfo->out_color_components != 3) {
  172136. cinfo->enable_1pass_quant = TRUE;
  172137. cinfo->enable_external_quant = FALSE;
  172138. cinfo->enable_2pass_quant = FALSE;
  172139. cinfo->colormap = NULL;
  172140. } else if (cinfo->colormap != NULL) {
  172141. cinfo->enable_external_quant = TRUE;
  172142. } else if (cinfo->two_pass_quantize) {
  172143. cinfo->enable_2pass_quant = TRUE;
  172144. } else {
  172145. cinfo->enable_1pass_quant = TRUE;
  172146. }
  172147. if (cinfo->enable_1pass_quant) {
  172148. #ifdef QUANT_1PASS_SUPPORTED
  172149. jinit_1pass_quantizer(cinfo);
  172150. master->quantizer_1pass = cinfo->cquantize;
  172151. #else
  172152. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172153. #endif
  172154. }
  172155. /* We use the 2-pass code to map to external colormaps. */
  172156. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172157. #ifdef QUANT_2PASS_SUPPORTED
  172158. jinit_2pass_quantizer(cinfo);
  172159. master->quantizer_2pass = cinfo->cquantize;
  172160. #else
  172161. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172162. #endif
  172163. }
  172164. /* If both quantizers are initialized, the 2-pass one is left active;
  172165. * this is necessary for starting with quantization to an external map.
  172166. */
  172167. }
  172168. /* Post-processing: in particular, color conversion first */
  172169. if (! cinfo->raw_data_out) {
  172170. if (master->using_merged_upsample) {
  172171. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172172. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172173. #else
  172174. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172175. #endif
  172176. } else {
  172177. jinit_color_deconverter(cinfo);
  172178. jinit_upsampler(cinfo);
  172179. }
  172180. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172181. }
  172182. /* Inverse DCT */
  172183. jinit_inverse_dct(cinfo);
  172184. /* Entropy decoding: either Huffman or arithmetic coding. */
  172185. if (cinfo->arith_code) {
  172186. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172187. } else {
  172188. if (cinfo->progressive_mode) {
  172189. #ifdef D_PROGRESSIVE_SUPPORTED
  172190. jinit_phuff_decoder(cinfo);
  172191. #else
  172192. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172193. #endif
  172194. } else
  172195. jinit_huff_decoder(cinfo);
  172196. }
  172197. /* Initialize principal buffer controllers. */
  172198. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172199. jinit_d_coef_controller(cinfo, use_c_buffer);
  172200. if (! cinfo->raw_data_out)
  172201. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172202. /* We can now tell the memory manager to allocate virtual arrays. */
  172203. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172204. /* Initialize input side of decompressor to consume first scan. */
  172205. (*cinfo->inputctl->start_input_pass) (cinfo);
  172206. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172207. /* If jpeg_start_decompress will read the whole file, initialize
  172208. * progress monitoring appropriately. The input step is counted
  172209. * as one pass.
  172210. */
  172211. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172212. cinfo->inputctl->has_multiple_scans) {
  172213. int nscans;
  172214. /* Estimate number of scans to set pass_limit. */
  172215. if (cinfo->progressive_mode) {
  172216. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172217. nscans = 2 + 3 * cinfo->num_components;
  172218. } else {
  172219. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172220. nscans = cinfo->num_components;
  172221. }
  172222. cinfo->progress->pass_counter = 0L;
  172223. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172224. cinfo->progress->completed_passes = 0;
  172225. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172226. /* Count the input pass as done */
  172227. master->pass_number++;
  172228. }
  172229. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172230. }
  172231. /*
  172232. * Per-pass setup.
  172233. * This is called at the beginning of each output pass. We determine which
  172234. * modules will be active during this pass and give them appropriate
  172235. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172236. * is a "real" output pass or a dummy pass for color quantization.
  172237. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172238. */
  172239. METHODDEF(void)
  172240. prepare_for_output_pass (j_decompress_ptr cinfo)
  172241. {
  172242. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172243. if (master->pub.is_dummy_pass) {
  172244. #ifdef QUANT_2PASS_SUPPORTED
  172245. /* Final pass of 2-pass quantization */
  172246. master->pub.is_dummy_pass = FALSE;
  172247. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172248. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172249. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172250. #else
  172251. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172252. #endif /* QUANT_2PASS_SUPPORTED */
  172253. } else {
  172254. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172255. /* Select new quantization method */
  172256. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172257. cinfo->cquantize = master->quantizer_2pass;
  172258. master->pub.is_dummy_pass = TRUE;
  172259. } else if (cinfo->enable_1pass_quant) {
  172260. cinfo->cquantize = master->quantizer_1pass;
  172261. } else {
  172262. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172263. }
  172264. }
  172265. (*cinfo->idct->start_pass) (cinfo);
  172266. (*cinfo->coef->start_output_pass) (cinfo);
  172267. if (! cinfo->raw_data_out) {
  172268. if (! master->using_merged_upsample)
  172269. (*cinfo->cconvert->start_pass) (cinfo);
  172270. (*cinfo->upsample->start_pass) (cinfo);
  172271. if (cinfo->quantize_colors)
  172272. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172273. (*cinfo->post->start_pass) (cinfo,
  172274. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172275. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172276. }
  172277. }
  172278. /* Set up progress monitor's pass info if present */
  172279. if (cinfo->progress != NULL) {
  172280. cinfo->progress->completed_passes = master->pass_number;
  172281. cinfo->progress->total_passes = master->pass_number +
  172282. (master->pub.is_dummy_pass ? 2 : 1);
  172283. /* In buffered-image mode, we assume one more output pass if EOI not
  172284. * yet reached, but no more passes if EOI has been reached.
  172285. */
  172286. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172287. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172288. }
  172289. }
  172290. }
  172291. /*
  172292. * Finish up at end of an output pass.
  172293. */
  172294. METHODDEF(void)
  172295. finish_output_pass (j_decompress_ptr cinfo)
  172296. {
  172297. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172298. if (cinfo->quantize_colors)
  172299. (*cinfo->cquantize->finish_pass) (cinfo);
  172300. master->pass_number++;
  172301. }
  172302. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172303. /*
  172304. * Switch to a new external colormap between output passes.
  172305. */
  172306. GLOBAL(void)
  172307. jpeg_new_colormap (j_decompress_ptr cinfo)
  172308. {
  172309. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172310. /* Prevent application from calling me at wrong times */
  172311. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172312. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172313. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172314. cinfo->colormap != NULL) {
  172315. /* Select 2-pass quantizer for external colormap use */
  172316. cinfo->cquantize = master->quantizer_2pass;
  172317. /* Notify quantizer of colormap change */
  172318. (*cinfo->cquantize->new_color_map) (cinfo);
  172319. master->pub.is_dummy_pass = FALSE; /* just in case */
  172320. } else
  172321. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172322. }
  172323. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172324. /*
  172325. * Initialize master decompression control and select active modules.
  172326. * This is performed at the start of jpeg_start_decompress.
  172327. */
  172328. GLOBAL(void)
  172329. jinit_master_decompress (j_decompress_ptr cinfo)
  172330. {
  172331. my_master_ptr6 master;
  172332. master = (my_master_ptr6)
  172333. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172334. SIZEOF(my_decomp_master));
  172335. cinfo->master = (struct jpeg_decomp_master *) master;
  172336. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172337. master->pub.finish_output_pass = finish_output_pass;
  172338. master->pub.is_dummy_pass = FALSE;
  172339. master_selection(cinfo);
  172340. }
  172341. /*** End of inlined file: jdmaster.c ***/
  172342. #undef FIX
  172343. /*** Start of inlined file: jdmerge.c ***/
  172344. #define JPEG_INTERNALS
  172345. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172346. /* Private subobject */
  172347. typedef struct {
  172348. struct jpeg_upsampler pub; /* public fields */
  172349. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172350. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172351. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172352. JSAMPARRAY output_buf));
  172353. /* Private state for YCC->RGB conversion */
  172354. int * Cr_r_tab; /* => table for Cr to R conversion */
  172355. int * Cb_b_tab; /* => table for Cb to B conversion */
  172356. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172357. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172358. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172359. * We need a "spare" row buffer to hold the second output row if the
  172360. * application provides just a one-row buffer; we also use the spare
  172361. * to discard the dummy last row if the image height is odd.
  172362. */
  172363. JSAMPROW spare_row;
  172364. boolean spare_full; /* T if spare buffer is occupied */
  172365. JDIMENSION out_row_width; /* samples per output row */
  172366. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172367. } my_upsampler;
  172368. typedef my_upsampler * my_upsample_ptr;
  172369. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172370. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172371. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172372. /*
  172373. * Initialize tables for YCC->RGB colorspace conversion.
  172374. * This is taken directly from jdcolor.c; see that file for more info.
  172375. */
  172376. LOCAL(void)
  172377. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172378. {
  172379. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172380. int i;
  172381. INT32 x;
  172382. SHIFT_TEMPS
  172383. upsample->Cr_r_tab = (int *)
  172384. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172385. (MAXJSAMPLE+1) * SIZEOF(int));
  172386. upsample->Cb_b_tab = (int *)
  172387. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172388. (MAXJSAMPLE+1) * SIZEOF(int));
  172389. upsample->Cr_g_tab = (INT32 *)
  172390. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172391. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172392. upsample->Cb_g_tab = (INT32 *)
  172393. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172394. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172395. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172396. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172397. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172398. /* Cr=>R value is nearest int to 1.40200 * x */
  172399. upsample->Cr_r_tab[i] = (int)
  172400. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172401. /* Cb=>B value is nearest int to 1.77200 * x */
  172402. upsample->Cb_b_tab[i] = (int)
  172403. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172404. /* Cr=>G value is scaled-up -0.71414 * x */
  172405. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172406. /* Cb=>G value is scaled-up -0.34414 * x */
  172407. /* We also add in ONE_HALF so that need not do it in inner loop */
  172408. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172409. }
  172410. }
  172411. /*
  172412. * Initialize for an upsampling pass.
  172413. */
  172414. METHODDEF(void)
  172415. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172416. {
  172417. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172418. /* Mark the spare buffer empty */
  172419. upsample->spare_full = FALSE;
  172420. /* Initialize total-height counter for detecting bottom of image */
  172421. upsample->rows_to_go = cinfo->output_height;
  172422. }
  172423. /*
  172424. * Control routine to do upsampling (and color conversion).
  172425. *
  172426. * The control routine just handles the row buffering considerations.
  172427. */
  172428. METHODDEF(void)
  172429. merged_2v_upsample (j_decompress_ptr cinfo,
  172430. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172431. JDIMENSION,
  172432. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172433. JDIMENSION out_rows_avail)
  172434. /* 2:1 vertical sampling case: may need a spare row. */
  172435. {
  172436. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172437. JSAMPROW work_ptrs[2];
  172438. JDIMENSION num_rows; /* number of rows returned to caller */
  172439. if (upsample->spare_full) {
  172440. /* If we have a spare row saved from a previous cycle, just return it. */
  172441. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172442. 1, upsample->out_row_width);
  172443. num_rows = 1;
  172444. upsample->spare_full = FALSE;
  172445. } else {
  172446. /* Figure number of rows to return to caller. */
  172447. num_rows = 2;
  172448. /* Not more than the distance to the end of the image. */
  172449. if (num_rows > upsample->rows_to_go)
  172450. num_rows = upsample->rows_to_go;
  172451. /* And not more than what the client can accept: */
  172452. out_rows_avail -= *out_row_ctr;
  172453. if (num_rows > out_rows_avail)
  172454. num_rows = out_rows_avail;
  172455. /* Create output pointer array for upsampler. */
  172456. work_ptrs[0] = output_buf[*out_row_ctr];
  172457. if (num_rows > 1) {
  172458. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172459. } else {
  172460. work_ptrs[1] = upsample->spare_row;
  172461. upsample->spare_full = TRUE;
  172462. }
  172463. /* Now do the upsampling. */
  172464. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172465. }
  172466. /* Adjust counts */
  172467. *out_row_ctr += num_rows;
  172468. upsample->rows_to_go -= num_rows;
  172469. /* When the buffer is emptied, declare this input row group consumed */
  172470. if (! upsample->spare_full)
  172471. (*in_row_group_ctr)++;
  172472. }
  172473. METHODDEF(void)
  172474. merged_1v_upsample (j_decompress_ptr cinfo,
  172475. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172476. JDIMENSION,
  172477. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172478. JDIMENSION)
  172479. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172480. {
  172481. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172482. /* Just do the upsampling. */
  172483. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172484. output_buf + *out_row_ctr);
  172485. /* Adjust counts */
  172486. (*out_row_ctr)++;
  172487. (*in_row_group_ctr)++;
  172488. }
  172489. /*
  172490. * These are the routines invoked by the control routines to do
  172491. * the actual upsampling/conversion. One row group is processed per call.
  172492. *
  172493. * Note: since we may be writing directly into application-supplied buffers,
  172494. * we have to be honest about the output width; we can't assume the buffer
  172495. * has been rounded up to an even width.
  172496. */
  172497. /*
  172498. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172499. */
  172500. METHODDEF(void)
  172501. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172502. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172503. JSAMPARRAY output_buf)
  172504. {
  172505. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172506. register int y, cred, cgreen, cblue;
  172507. int cb, cr;
  172508. register JSAMPROW outptr;
  172509. JSAMPROW inptr0, inptr1, inptr2;
  172510. JDIMENSION col;
  172511. /* copy these pointers into registers if possible */
  172512. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172513. int * Crrtab = upsample->Cr_r_tab;
  172514. int * Cbbtab = upsample->Cb_b_tab;
  172515. INT32 * Crgtab = upsample->Cr_g_tab;
  172516. INT32 * Cbgtab = upsample->Cb_g_tab;
  172517. SHIFT_TEMPS
  172518. inptr0 = input_buf[0][in_row_group_ctr];
  172519. inptr1 = input_buf[1][in_row_group_ctr];
  172520. inptr2 = input_buf[2][in_row_group_ctr];
  172521. outptr = output_buf[0];
  172522. /* Loop for each pair of output pixels */
  172523. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172524. /* Do the chroma part of the calculation */
  172525. cb = GETJSAMPLE(*inptr1++);
  172526. cr = GETJSAMPLE(*inptr2++);
  172527. cred = Crrtab[cr];
  172528. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172529. cblue = Cbbtab[cb];
  172530. /* Fetch 2 Y values and emit 2 pixels */
  172531. y = GETJSAMPLE(*inptr0++);
  172532. outptr[RGB_RED] = range_limit[y + cred];
  172533. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172534. outptr[RGB_BLUE] = range_limit[y + cblue];
  172535. outptr += RGB_PIXELSIZE;
  172536. y = GETJSAMPLE(*inptr0++);
  172537. outptr[RGB_RED] = range_limit[y + cred];
  172538. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172539. outptr[RGB_BLUE] = range_limit[y + cblue];
  172540. outptr += RGB_PIXELSIZE;
  172541. }
  172542. /* If image width is odd, do the last output column separately */
  172543. if (cinfo->output_width & 1) {
  172544. cb = GETJSAMPLE(*inptr1);
  172545. cr = GETJSAMPLE(*inptr2);
  172546. cred = Crrtab[cr];
  172547. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172548. cblue = Cbbtab[cb];
  172549. y = GETJSAMPLE(*inptr0);
  172550. outptr[RGB_RED] = range_limit[y + cred];
  172551. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172552. outptr[RGB_BLUE] = range_limit[y + cblue];
  172553. }
  172554. }
  172555. /*
  172556. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172557. */
  172558. METHODDEF(void)
  172559. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172560. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172561. JSAMPARRAY output_buf)
  172562. {
  172563. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172564. register int y, cred, cgreen, cblue;
  172565. int cb, cr;
  172566. register JSAMPROW outptr0, outptr1;
  172567. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172568. JDIMENSION col;
  172569. /* copy these pointers into registers if possible */
  172570. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172571. int * Crrtab = upsample->Cr_r_tab;
  172572. int * Cbbtab = upsample->Cb_b_tab;
  172573. INT32 * Crgtab = upsample->Cr_g_tab;
  172574. INT32 * Cbgtab = upsample->Cb_g_tab;
  172575. SHIFT_TEMPS
  172576. inptr00 = input_buf[0][in_row_group_ctr*2];
  172577. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172578. inptr1 = input_buf[1][in_row_group_ctr];
  172579. inptr2 = input_buf[2][in_row_group_ctr];
  172580. outptr0 = output_buf[0];
  172581. outptr1 = output_buf[1];
  172582. /* Loop for each group of output pixels */
  172583. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172584. /* Do the chroma part of the calculation */
  172585. cb = GETJSAMPLE(*inptr1++);
  172586. cr = GETJSAMPLE(*inptr2++);
  172587. cred = Crrtab[cr];
  172588. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172589. cblue = Cbbtab[cb];
  172590. /* Fetch 4 Y values and emit 4 pixels */
  172591. y = GETJSAMPLE(*inptr00++);
  172592. outptr0[RGB_RED] = range_limit[y + cred];
  172593. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172594. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172595. outptr0 += RGB_PIXELSIZE;
  172596. y = GETJSAMPLE(*inptr00++);
  172597. outptr0[RGB_RED] = range_limit[y + cred];
  172598. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172599. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172600. outptr0 += RGB_PIXELSIZE;
  172601. y = GETJSAMPLE(*inptr01++);
  172602. outptr1[RGB_RED] = range_limit[y + cred];
  172603. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172604. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172605. outptr1 += RGB_PIXELSIZE;
  172606. y = GETJSAMPLE(*inptr01++);
  172607. outptr1[RGB_RED] = range_limit[y + cred];
  172608. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172609. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172610. outptr1 += RGB_PIXELSIZE;
  172611. }
  172612. /* If image width is odd, do the last output column separately */
  172613. if (cinfo->output_width & 1) {
  172614. cb = GETJSAMPLE(*inptr1);
  172615. cr = GETJSAMPLE(*inptr2);
  172616. cred = Crrtab[cr];
  172617. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172618. cblue = Cbbtab[cb];
  172619. y = GETJSAMPLE(*inptr00);
  172620. outptr0[RGB_RED] = range_limit[y + cred];
  172621. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172622. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172623. y = GETJSAMPLE(*inptr01);
  172624. outptr1[RGB_RED] = range_limit[y + cred];
  172625. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172626. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172627. }
  172628. }
  172629. /*
  172630. * Module initialization routine for merged upsampling/color conversion.
  172631. *
  172632. * NB: this is called under the conditions determined by use_merged_upsample()
  172633. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172634. * of this module; no safety checks are made here.
  172635. */
  172636. GLOBAL(void)
  172637. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172638. {
  172639. my_upsample_ptr upsample;
  172640. upsample = (my_upsample_ptr)
  172641. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172642. SIZEOF(my_upsampler));
  172643. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172644. upsample->pub.start_pass = start_pass_merged_upsample;
  172645. upsample->pub.need_context_rows = FALSE;
  172646. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172647. if (cinfo->max_v_samp_factor == 2) {
  172648. upsample->pub.upsample = merged_2v_upsample;
  172649. upsample->upmethod = h2v2_merged_upsample;
  172650. /* Allocate a spare row buffer */
  172651. upsample->spare_row = (JSAMPROW)
  172652. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172653. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172654. } else {
  172655. upsample->pub.upsample = merged_1v_upsample;
  172656. upsample->upmethod = h2v1_merged_upsample;
  172657. /* No spare row needed */
  172658. upsample->spare_row = NULL;
  172659. }
  172660. build_ycc_rgb_table2(cinfo);
  172661. }
  172662. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  172663. /*** End of inlined file: jdmerge.c ***/
  172664. #undef ASSIGN_STATE
  172665. /*** Start of inlined file: jdphuff.c ***/
  172666. #define JPEG_INTERNALS
  172667. #ifdef D_PROGRESSIVE_SUPPORTED
  172668. /*
  172669. * Expanded entropy decoder object for progressive Huffman decoding.
  172670. *
  172671. * The savable_state subrecord contains fields that change within an MCU,
  172672. * but must not be updated permanently until we complete the MCU.
  172673. */
  172674. typedef struct {
  172675. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  172676. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  172677. } savable_state3;
  172678. /* This macro is to work around compilers with missing or broken
  172679. * structure assignment. You'll need to fix this code if you have
  172680. * such a compiler and you change MAX_COMPS_IN_SCAN.
  172681. */
  172682. #ifndef NO_STRUCT_ASSIGN
  172683. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  172684. #else
  172685. #if MAX_COMPS_IN_SCAN == 4
  172686. #define ASSIGN_STATE(dest,src) \
  172687. ((dest).EOBRUN = (src).EOBRUN, \
  172688. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  172689. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  172690. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  172691. (dest).last_dc_val[3] = (src).last_dc_val[3])
  172692. #endif
  172693. #endif
  172694. typedef struct {
  172695. struct jpeg_entropy_decoder pub; /* public fields */
  172696. /* These fields are loaded into local variables at start of each MCU.
  172697. * In case of suspension, we exit WITHOUT updating them.
  172698. */
  172699. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  172700. savable_state3 saved; /* Other state at start of MCU */
  172701. /* These fields are NOT loaded into local working state. */
  172702. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  172703. /* Pointers to derived tables (these workspaces have image lifespan) */
  172704. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  172705. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  172706. } phuff_entropy_decoder;
  172707. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  172708. /* Forward declarations */
  172709. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  172710. JBLOCKROW *MCU_data));
  172711. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  172712. JBLOCKROW *MCU_data));
  172713. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  172714. JBLOCKROW *MCU_data));
  172715. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  172716. JBLOCKROW *MCU_data));
  172717. /*
  172718. * Initialize for a Huffman-compressed scan.
  172719. */
  172720. METHODDEF(void)
  172721. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  172722. {
  172723. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172724. boolean is_DC_band, bad;
  172725. int ci, coefi, tbl;
  172726. int *coef_bit_ptr;
  172727. jpeg_component_info * compptr;
  172728. is_DC_band = (cinfo->Ss == 0);
  172729. /* Validate scan parameters */
  172730. bad = FALSE;
  172731. if (is_DC_band) {
  172732. if (cinfo->Se != 0)
  172733. bad = TRUE;
  172734. } else {
  172735. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  172736. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  172737. bad = TRUE;
  172738. /* AC scans may have only one component */
  172739. if (cinfo->comps_in_scan != 1)
  172740. bad = TRUE;
  172741. }
  172742. if (cinfo->Ah != 0) {
  172743. /* Successive approximation refinement scan: must have Al = Ah-1. */
  172744. if (cinfo->Al != cinfo->Ah-1)
  172745. bad = TRUE;
  172746. }
  172747. if (cinfo->Al > 13) /* need not check for < 0 */
  172748. bad = TRUE;
  172749. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  172750. * but the spec doesn't say so, and we try to be liberal about what we
  172751. * accept. Note: large Al values could result in out-of-range DC
  172752. * coefficients during early scans, leading to bizarre displays due to
  172753. * overflows in the IDCT math. But we won't crash.
  172754. */
  172755. if (bad)
  172756. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  172757. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  172758. /* Update progression status, and verify that scan order is legal.
  172759. * Note that inter-scan inconsistencies are treated as warnings
  172760. * not fatal errors ... not clear if this is right way to behave.
  172761. */
  172762. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172763. int cindex = cinfo->cur_comp_info[ci]->component_index;
  172764. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  172765. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  172766. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  172767. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  172768. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  172769. if (cinfo->Ah != expected)
  172770. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  172771. coef_bit_ptr[coefi] = cinfo->Al;
  172772. }
  172773. }
  172774. /* Select MCU decoding routine */
  172775. if (cinfo->Ah == 0) {
  172776. if (is_DC_band)
  172777. entropy->pub.decode_mcu = decode_mcu_DC_first;
  172778. else
  172779. entropy->pub.decode_mcu = decode_mcu_AC_first;
  172780. } else {
  172781. if (is_DC_band)
  172782. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  172783. else
  172784. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  172785. }
  172786. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  172787. compptr = cinfo->cur_comp_info[ci];
  172788. /* Make sure requested tables are present, and compute derived tables.
  172789. * We may build same derived table more than once, but it's not expensive.
  172790. */
  172791. if (is_DC_band) {
  172792. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  172793. tbl = compptr->dc_tbl_no;
  172794. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  172795. & entropy->derived_tbls[tbl]);
  172796. }
  172797. } else {
  172798. tbl = compptr->ac_tbl_no;
  172799. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  172800. & entropy->derived_tbls[tbl]);
  172801. /* remember the single active table */
  172802. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  172803. }
  172804. /* Initialize DC predictions to 0 */
  172805. entropy->saved.last_dc_val[ci] = 0;
  172806. }
  172807. /* Initialize bitread state variables */
  172808. entropy->bitstate.bits_left = 0;
  172809. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  172810. entropy->pub.insufficient_data = FALSE;
  172811. /* Initialize private state variables */
  172812. entropy->saved.EOBRUN = 0;
  172813. /* Initialize restart counter */
  172814. entropy->restarts_to_go = cinfo->restart_interval;
  172815. }
  172816. /*
  172817. * Check for a restart marker & resynchronize decoder.
  172818. * Returns FALSE if must suspend.
  172819. */
  172820. LOCAL(boolean)
  172821. process_restartp (j_decompress_ptr cinfo)
  172822. {
  172823. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172824. int ci;
  172825. /* Throw away any unused bits remaining in bit buffer; */
  172826. /* include any full bytes in next_marker's count of discarded bytes */
  172827. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  172828. entropy->bitstate.bits_left = 0;
  172829. /* Advance past the RSTn marker */
  172830. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  172831. return FALSE;
  172832. /* Re-initialize DC predictions to 0 */
  172833. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  172834. entropy->saved.last_dc_val[ci] = 0;
  172835. /* Re-init EOB run count, too */
  172836. entropy->saved.EOBRUN = 0;
  172837. /* Reset restart counter */
  172838. entropy->restarts_to_go = cinfo->restart_interval;
  172839. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  172840. * against a marker. In that case we will end up treating the next data
  172841. * segment as empty, and we can avoid producing bogus output pixels by
  172842. * leaving the flag set.
  172843. */
  172844. if (cinfo->unread_marker == 0)
  172845. entropy->pub.insufficient_data = FALSE;
  172846. return TRUE;
  172847. }
  172848. /*
  172849. * Huffman MCU decoding.
  172850. * Each of these routines decodes and returns one MCU's worth of
  172851. * Huffman-compressed coefficients.
  172852. * The coefficients are reordered from zigzag order into natural array order,
  172853. * but are not dequantized.
  172854. *
  172855. * The i'th block of the MCU is stored into the block pointed to by
  172856. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  172857. *
  172858. * We return FALSE if data source requested suspension. In that case no
  172859. * changes have been made to permanent state. (Exception: some output
  172860. * coefficients may already have been assigned. This is harmless for
  172861. * spectral selection, since we'll just re-assign them on the next call.
  172862. * Successive approximation AC refinement has to be more careful, however.)
  172863. */
  172864. /*
  172865. * MCU decoding for DC initial scan (either spectral selection,
  172866. * or first pass of successive approximation).
  172867. */
  172868. METHODDEF(boolean)
  172869. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172870. {
  172871. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172872. int Al = cinfo->Al;
  172873. register int s, r;
  172874. int blkn, ci;
  172875. JBLOCKROW block;
  172876. BITREAD_STATE_VARS;
  172877. savable_state3 state;
  172878. d_derived_tbl * tbl;
  172879. jpeg_component_info * compptr;
  172880. /* Process restart marker if needed; may have to suspend */
  172881. if (cinfo->restart_interval) {
  172882. if (entropy->restarts_to_go == 0)
  172883. if (! process_restartp(cinfo))
  172884. return FALSE;
  172885. }
  172886. /* If we've run out of data, just leave the MCU set to zeroes.
  172887. * This way, we return uniform gray for the remainder of the segment.
  172888. */
  172889. if (! entropy->pub.insufficient_data) {
  172890. /* Load up working state */
  172891. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172892. ASSIGN_STATE(state, entropy->saved);
  172893. /* Outer loop handles each block in the MCU */
  172894. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  172895. block = MCU_data[blkn];
  172896. ci = cinfo->MCU_membership[blkn];
  172897. compptr = cinfo->cur_comp_info[ci];
  172898. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  172899. /* Decode a single block's worth of coefficients */
  172900. /* Section F.2.2.1: decode the DC coefficient difference */
  172901. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  172902. if (s) {
  172903. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172904. r = GET_BITS(s);
  172905. s = HUFF_EXTEND(r, s);
  172906. }
  172907. /* Convert DC difference to actual value, update last_dc_val */
  172908. s += state.last_dc_val[ci];
  172909. state.last_dc_val[ci] = s;
  172910. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  172911. (*block)[0] = (JCOEF) (s << Al);
  172912. }
  172913. /* Completed MCU, so update state */
  172914. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172915. ASSIGN_STATE(entropy->saved, state);
  172916. }
  172917. /* Account for restart interval (no-op if not using restarts) */
  172918. entropy->restarts_to_go--;
  172919. return TRUE;
  172920. }
  172921. /*
  172922. * MCU decoding for AC initial scan (either spectral selection,
  172923. * or first pass of successive approximation).
  172924. */
  172925. METHODDEF(boolean)
  172926. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172927. {
  172928. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  172929. int Se = cinfo->Se;
  172930. int Al = cinfo->Al;
  172931. register int s, k, r;
  172932. unsigned int EOBRUN;
  172933. JBLOCKROW block;
  172934. BITREAD_STATE_VARS;
  172935. d_derived_tbl * tbl;
  172936. /* Process restart marker if needed; may have to suspend */
  172937. if (cinfo->restart_interval) {
  172938. if (entropy->restarts_to_go == 0)
  172939. if (! process_restartp(cinfo))
  172940. return FALSE;
  172941. }
  172942. /* If we've run out of data, just leave the MCU set to zeroes.
  172943. * This way, we return uniform gray for the remainder of the segment.
  172944. */
  172945. if (! entropy->pub.insufficient_data) {
  172946. /* Load up working state.
  172947. * We can avoid loading/saving bitread state if in an EOB run.
  172948. */
  172949. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  172950. /* There is always only one block per MCU */
  172951. if (EOBRUN > 0) /* if it's a band of zeroes... */
  172952. EOBRUN--; /* ...process it now (we do nothing) */
  172953. else {
  172954. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  172955. block = MCU_data[0];
  172956. tbl = entropy->ac_derived_tbl;
  172957. for (k = cinfo->Ss; k <= Se; k++) {
  172958. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  172959. r = s >> 4;
  172960. s &= 15;
  172961. if (s) {
  172962. k += r;
  172963. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  172964. r = GET_BITS(s);
  172965. s = HUFF_EXTEND(r, s);
  172966. /* Scale and output coefficient in natural (dezigzagged) order */
  172967. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  172968. } else {
  172969. if (r == 15) { /* ZRL */
  172970. k += 15; /* skip 15 zeroes in band */
  172971. } else { /* EOBr, run length is 2^r + appended bits */
  172972. EOBRUN = 1 << r;
  172973. if (r) { /* EOBr, r > 0 */
  172974. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  172975. r = GET_BITS(r);
  172976. EOBRUN += r;
  172977. }
  172978. EOBRUN--; /* this band is processed at this moment */
  172979. break; /* force end-of-band */
  172980. }
  172981. }
  172982. }
  172983. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  172984. }
  172985. /* Completed MCU, so update state */
  172986. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  172987. }
  172988. /* Account for restart interval (no-op if not using restarts) */
  172989. entropy->restarts_to_go--;
  172990. return TRUE;
  172991. }
  172992. /*
  172993. * MCU decoding for DC successive approximation refinement scan.
  172994. * Note: we assume such scans can be multi-component, although the spec
  172995. * is not very clear on the point.
  172996. */
  172997. METHODDEF(boolean)
  172998. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  172999. {
  173000. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173001. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173002. int blkn;
  173003. JBLOCKROW block;
  173004. BITREAD_STATE_VARS;
  173005. /* Process restart marker if needed; may have to suspend */
  173006. if (cinfo->restart_interval) {
  173007. if (entropy->restarts_to_go == 0)
  173008. if (! process_restartp(cinfo))
  173009. return FALSE;
  173010. }
  173011. /* Not worth the cycles to check insufficient_data here,
  173012. * since we will not change the data anyway if we read zeroes.
  173013. */
  173014. /* Load up working state */
  173015. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173016. /* Outer loop handles each block in the MCU */
  173017. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173018. block = MCU_data[blkn];
  173019. /* Encoded data is simply the next bit of the two's-complement DC value */
  173020. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173021. if (GET_BITS(1))
  173022. (*block)[0] |= p1;
  173023. /* Note: since we use |=, repeating the assignment later is safe */
  173024. }
  173025. /* Completed MCU, so update state */
  173026. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173027. /* Account for restart interval (no-op if not using restarts) */
  173028. entropy->restarts_to_go--;
  173029. return TRUE;
  173030. }
  173031. /*
  173032. * MCU decoding for AC successive approximation refinement scan.
  173033. */
  173034. METHODDEF(boolean)
  173035. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173036. {
  173037. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173038. int Se = cinfo->Se;
  173039. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173040. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173041. register int s, k, r;
  173042. unsigned int EOBRUN;
  173043. JBLOCKROW block;
  173044. JCOEFPTR thiscoef;
  173045. BITREAD_STATE_VARS;
  173046. d_derived_tbl * tbl;
  173047. int num_newnz;
  173048. int newnz_pos[DCTSIZE2];
  173049. /* Process restart marker if needed; may have to suspend */
  173050. if (cinfo->restart_interval) {
  173051. if (entropy->restarts_to_go == 0)
  173052. if (! process_restartp(cinfo))
  173053. return FALSE;
  173054. }
  173055. /* If we've run out of data, don't modify the MCU.
  173056. */
  173057. if (! entropy->pub.insufficient_data) {
  173058. /* Load up working state */
  173059. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173060. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173061. /* There is always only one block per MCU */
  173062. block = MCU_data[0];
  173063. tbl = entropy->ac_derived_tbl;
  173064. /* If we are forced to suspend, we must undo the assignments to any newly
  173065. * nonzero coefficients in the block, because otherwise we'd get confused
  173066. * next time about which coefficients were already nonzero.
  173067. * But we need not undo addition of bits to already-nonzero coefficients;
  173068. * instead, we can test the current bit to see if we already did it.
  173069. */
  173070. num_newnz = 0;
  173071. /* initialize coefficient loop counter to start of band */
  173072. k = cinfo->Ss;
  173073. if (EOBRUN == 0) {
  173074. for (; k <= Se; k++) {
  173075. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173076. r = s >> 4;
  173077. s &= 15;
  173078. if (s) {
  173079. if (s != 1) /* size of new coef should always be 1 */
  173080. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173081. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173082. if (GET_BITS(1))
  173083. s = p1; /* newly nonzero coef is positive */
  173084. else
  173085. s = m1; /* newly nonzero coef is negative */
  173086. } else {
  173087. if (r != 15) {
  173088. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173089. if (r) {
  173090. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173091. r = GET_BITS(r);
  173092. EOBRUN += r;
  173093. }
  173094. break; /* rest of block is handled by EOB logic */
  173095. }
  173096. /* note s = 0 for processing ZRL */
  173097. }
  173098. /* Advance over already-nonzero coefs and r still-zero coefs,
  173099. * appending correction bits to the nonzeroes. A correction bit is 1
  173100. * if the absolute value of the coefficient must be increased.
  173101. */
  173102. do {
  173103. thiscoef = *block + jpeg_natural_order[k];
  173104. if (*thiscoef != 0) {
  173105. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173106. if (GET_BITS(1)) {
  173107. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173108. if (*thiscoef >= 0)
  173109. *thiscoef += p1;
  173110. else
  173111. *thiscoef += m1;
  173112. }
  173113. }
  173114. } else {
  173115. if (--r < 0)
  173116. break; /* reached target zero coefficient */
  173117. }
  173118. k++;
  173119. } while (k <= Se);
  173120. if (s) {
  173121. int pos = jpeg_natural_order[k];
  173122. /* Output newly nonzero coefficient */
  173123. (*block)[pos] = (JCOEF) s;
  173124. /* Remember its position in case we have to suspend */
  173125. newnz_pos[num_newnz++] = pos;
  173126. }
  173127. }
  173128. }
  173129. if (EOBRUN > 0) {
  173130. /* Scan any remaining coefficient positions after the end-of-band
  173131. * (the last newly nonzero coefficient, if any). Append a correction
  173132. * bit to each already-nonzero coefficient. A correction bit is 1
  173133. * if the absolute value of the coefficient must be increased.
  173134. */
  173135. for (; k <= Se; k++) {
  173136. thiscoef = *block + jpeg_natural_order[k];
  173137. if (*thiscoef != 0) {
  173138. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173139. if (GET_BITS(1)) {
  173140. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173141. if (*thiscoef >= 0)
  173142. *thiscoef += p1;
  173143. else
  173144. *thiscoef += m1;
  173145. }
  173146. }
  173147. }
  173148. }
  173149. /* Count one block completed in EOB run */
  173150. EOBRUN--;
  173151. }
  173152. /* Completed MCU, so update state */
  173153. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173154. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173155. }
  173156. /* Account for restart interval (no-op if not using restarts) */
  173157. entropy->restarts_to_go--;
  173158. return TRUE;
  173159. undoit:
  173160. /* Re-zero any output coefficients that we made newly nonzero */
  173161. while (num_newnz > 0)
  173162. (*block)[newnz_pos[--num_newnz]] = 0;
  173163. return FALSE;
  173164. }
  173165. /*
  173166. * Module initialization routine for progressive Huffman entropy decoding.
  173167. */
  173168. GLOBAL(void)
  173169. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173170. {
  173171. phuff_entropy_ptr2 entropy;
  173172. int *coef_bit_ptr;
  173173. int ci, i;
  173174. entropy = (phuff_entropy_ptr2)
  173175. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173176. SIZEOF(phuff_entropy_decoder));
  173177. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173178. entropy->pub.start_pass = start_pass_phuff_decoder;
  173179. /* Mark derived tables unallocated */
  173180. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173181. entropy->derived_tbls[i] = NULL;
  173182. }
  173183. /* Create progression status table */
  173184. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173185. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173186. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173187. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173188. for (ci = 0; ci < cinfo->num_components; ci++)
  173189. for (i = 0; i < DCTSIZE2; i++)
  173190. *coef_bit_ptr++ = -1;
  173191. }
  173192. #endif /* D_PROGRESSIVE_SUPPORTED */
  173193. /*** End of inlined file: jdphuff.c ***/
  173194. /*** Start of inlined file: jdpostct.c ***/
  173195. #define JPEG_INTERNALS
  173196. /* Private buffer controller object */
  173197. typedef struct {
  173198. struct jpeg_d_post_controller pub; /* public fields */
  173199. /* Color quantization source buffer: this holds output data from
  173200. * the upsample/color conversion step to be passed to the quantizer.
  173201. * For two-pass color quantization, we need a full-image buffer;
  173202. * for one-pass operation, a strip buffer is sufficient.
  173203. */
  173204. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173205. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173206. JDIMENSION strip_height; /* buffer size in rows */
  173207. /* for two-pass mode only: */
  173208. JDIMENSION starting_row; /* row # of first row in current strip */
  173209. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173210. } my_post_controller;
  173211. typedef my_post_controller * my_post_ptr;
  173212. /* Forward declarations */
  173213. METHODDEF(void) post_process_1pass
  173214. JPP((j_decompress_ptr cinfo,
  173215. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173216. JDIMENSION in_row_groups_avail,
  173217. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173218. JDIMENSION out_rows_avail));
  173219. #ifdef QUANT_2PASS_SUPPORTED
  173220. METHODDEF(void) post_process_prepass
  173221. JPP((j_decompress_ptr cinfo,
  173222. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173223. JDIMENSION in_row_groups_avail,
  173224. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173225. JDIMENSION out_rows_avail));
  173226. METHODDEF(void) post_process_2pass
  173227. JPP((j_decompress_ptr cinfo,
  173228. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173229. JDIMENSION in_row_groups_avail,
  173230. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173231. JDIMENSION out_rows_avail));
  173232. #endif
  173233. /*
  173234. * Initialize for a processing pass.
  173235. */
  173236. METHODDEF(void)
  173237. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173238. {
  173239. my_post_ptr post = (my_post_ptr) cinfo->post;
  173240. switch (pass_mode) {
  173241. case JBUF_PASS_THRU:
  173242. if (cinfo->quantize_colors) {
  173243. /* Single-pass processing with color quantization. */
  173244. post->pub.post_process_data = post_process_1pass;
  173245. /* We could be doing buffered-image output before starting a 2-pass
  173246. * color quantization; in that case, jinit_d_post_controller did not
  173247. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173248. */
  173249. if (post->buffer == NULL) {
  173250. post->buffer = (*cinfo->mem->access_virt_sarray)
  173251. ((j_common_ptr) cinfo, post->whole_image,
  173252. (JDIMENSION) 0, post->strip_height, TRUE);
  173253. }
  173254. } else {
  173255. /* For single-pass processing without color quantization,
  173256. * I have no work to do; just call the upsampler directly.
  173257. */
  173258. post->pub.post_process_data = cinfo->upsample->upsample;
  173259. }
  173260. break;
  173261. #ifdef QUANT_2PASS_SUPPORTED
  173262. case JBUF_SAVE_AND_PASS:
  173263. /* First pass of 2-pass quantization */
  173264. if (post->whole_image == NULL)
  173265. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173266. post->pub.post_process_data = post_process_prepass;
  173267. break;
  173268. case JBUF_CRANK_DEST:
  173269. /* Second pass of 2-pass quantization */
  173270. if (post->whole_image == NULL)
  173271. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173272. post->pub.post_process_data = post_process_2pass;
  173273. break;
  173274. #endif /* QUANT_2PASS_SUPPORTED */
  173275. default:
  173276. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173277. break;
  173278. }
  173279. post->starting_row = post->next_row = 0;
  173280. }
  173281. /*
  173282. * Process some data in the one-pass (strip buffer) case.
  173283. * This is used for color precision reduction as well as one-pass quantization.
  173284. */
  173285. METHODDEF(void)
  173286. post_process_1pass (j_decompress_ptr cinfo,
  173287. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173288. JDIMENSION in_row_groups_avail,
  173289. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173290. JDIMENSION out_rows_avail)
  173291. {
  173292. my_post_ptr post = (my_post_ptr) cinfo->post;
  173293. JDIMENSION num_rows, max_rows;
  173294. /* Fill the buffer, but not more than what we can dump out in one go. */
  173295. /* Note we rely on the upsampler to detect bottom of image. */
  173296. max_rows = out_rows_avail - *out_row_ctr;
  173297. if (max_rows > post->strip_height)
  173298. max_rows = post->strip_height;
  173299. num_rows = 0;
  173300. (*cinfo->upsample->upsample) (cinfo,
  173301. input_buf, in_row_group_ctr, in_row_groups_avail,
  173302. post->buffer, &num_rows, max_rows);
  173303. /* Quantize and emit data. */
  173304. (*cinfo->cquantize->color_quantize) (cinfo,
  173305. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173306. *out_row_ctr += num_rows;
  173307. }
  173308. #ifdef QUANT_2PASS_SUPPORTED
  173309. /*
  173310. * Process some data in the first pass of 2-pass quantization.
  173311. */
  173312. METHODDEF(void)
  173313. post_process_prepass (j_decompress_ptr cinfo,
  173314. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173315. JDIMENSION in_row_groups_avail,
  173316. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173317. JDIMENSION)
  173318. {
  173319. my_post_ptr post = (my_post_ptr) cinfo->post;
  173320. JDIMENSION old_next_row, num_rows;
  173321. /* Reposition virtual buffer if at start of strip. */
  173322. if (post->next_row == 0) {
  173323. post->buffer = (*cinfo->mem->access_virt_sarray)
  173324. ((j_common_ptr) cinfo, post->whole_image,
  173325. post->starting_row, post->strip_height, TRUE);
  173326. }
  173327. /* Upsample some data (up to a strip height's worth). */
  173328. old_next_row = post->next_row;
  173329. (*cinfo->upsample->upsample) (cinfo,
  173330. input_buf, in_row_group_ctr, in_row_groups_avail,
  173331. post->buffer, &post->next_row, post->strip_height);
  173332. /* Allow quantizer to scan new data. No data is emitted, */
  173333. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173334. if (post->next_row > old_next_row) {
  173335. num_rows = post->next_row - old_next_row;
  173336. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173337. (JSAMPARRAY) NULL, (int) num_rows);
  173338. *out_row_ctr += num_rows;
  173339. }
  173340. /* Advance if we filled the strip. */
  173341. if (post->next_row >= post->strip_height) {
  173342. post->starting_row += post->strip_height;
  173343. post->next_row = 0;
  173344. }
  173345. }
  173346. /*
  173347. * Process some data in the second pass of 2-pass quantization.
  173348. */
  173349. METHODDEF(void)
  173350. post_process_2pass (j_decompress_ptr cinfo,
  173351. JSAMPIMAGE, JDIMENSION *,
  173352. JDIMENSION,
  173353. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173354. JDIMENSION out_rows_avail)
  173355. {
  173356. my_post_ptr post = (my_post_ptr) cinfo->post;
  173357. JDIMENSION num_rows, max_rows;
  173358. /* Reposition virtual buffer if at start of strip. */
  173359. if (post->next_row == 0) {
  173360. post->buffer = (*cinfo->mem->access_virt_sarray)
  173361. ((j_common_ptr) cinfo, post->whole_image,
  173362. post->starting_row, post->strip_height, FALSE);
  173363. }
  173364. /* Determine number of rows to emit. */
  173365. num_rows = post->strip_height - post->next_row; /* available in strip */
  173366. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173367. if (num_rows > max_rows)
  173368. num_rows = max_rows;
  173369. /* We have to check bottom of image here, can't depend on upsampler. */
  173370. max_rows = cinfo->output_height - post->starting_row;
  173371. if (num_rows > max_rows)
  173372. num_rows = max_rows;
  173373. /* Quantize and emit data. */
  173374. (*cinfo->cquantize->color_quantize) (cinfo,
  173375. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173376. (int) num_rows);
  173377. *out_row_ctr += num_rows;
  173378. /* Advance if we filled the strip. */
  173379. post->next_row += num_rows;
  173380. if (post->next_row >= post->strip_height) {
  173381. post->starting_row += post->strip_height;
  173382. post->next_row = 0;
  173383. }
  173384. }
  173385. #endif /* QUANT_2PASS_SUPPORTED */
  173386. /*
  173387. * Initialize postprocessing controller.
  173388. */
  173389. GLOBAL(void)
  173390. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173391. {
  173392. my_post_ptr post;
  173393. post = (my_post_ptr)
  173394. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173395. SIZEOF(my_post_controller));
  173396. cinfo->post = (struct jpeg_d_post_controller *) post;
  173397. post->pub.start_pass = start_pass_dpost;
  173398. post->whole_image = NULL; /* flag for no virtual arrays */
  173399. post->buffer = NULL; /* flag for no strip buffer */
  173400. /* Create the quantization buffer, if needed */
  173401. if (cinfo->quantize_colors) {
  173402. /* The buffer strip height is max_v_samp_factor, which is typically
  173403. * an efficient number of rows for upsampling to return.
  173404. * (In the presence of output rescaling, we might want to be smarter?)
  173405. */
  173406. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173407. if (need_full_buffer) {
  173408. /* Two-pass color quantization: need full-image storage. */
  173409. /* We round up the number of rows to a multiple of the strip height. */
  173410. #ifdef QUANT_2PASS_SUPPORTED
  173411. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173412. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173413. cinfo->output_width * cinfo->out_color_components,
  173414. (JDIMENSION) jround_up((long) cinfo->output_height,
  173415. (long) post->strip_height),
  173416. post->strip_height);
  173417. #else
  173418. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173419. #endif /* QUANT_2PASS_SUPPORTED */
  173420. } else {
  173421. /* One-pass color quantization: just make a strip buffer. */
  173422. post->buffer = (*cinfo->mem->alloc_sarray)
  173423. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173424. cinfo->output_width * cinfo->out_color_components,
  173425. post->strip_height);
  173426. }
  173427. }
  173428. }
  173429. /*** End of inlined file: jdpostct.c ***/
  173430. #undef FIX
  173431. /*** Start of inlined file: jdsample.c ***/
  173432. #define JPEG_INTERNALS
  173433. /* Pointer to routine to upsample a single component */
  173434. typedef JMETHOD(void, upsample1_ptr,
  173435. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173436. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173437. /* Private subobject */
  173438. typedef struct {
  173439. struct jpeg_upsampler pub; /* public fields */
  173440. /* Color conversion buffer. When using separate upsampling and color
  173441. * conversion steps, this buffer holds one upsampled row group until it
  173442. * has been color converted and output.
  173443. * Note: we do not allocate any storage for component(s) which are full-size,
  173444. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173445. * simply set to point to the input data array, thereby avoiding copying.
  173446. */
  173447. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173448. /* Per-component upsampling method pointers */
  173449. upsample1_ptr methods[MAX_COMPONENTS];
  173450. int next_row_out; /* counts rows emitted from color_buf */
  173451. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173452. /* Height of an input row group for each component. */
  173453. int rowgroup_height[MAX_COMPONENTS];
  173454. /* These arrays save pixel expansion factors so that int_expand need not
  173455. * recompute them each time. They are unused for other upsampling methods.
  173456. */
  173457. UINT8 h_expand[MAX_COMPONENTS];
  173458. UINT8 v_expand[MAX_COMPONENTS];
  173459. } my_upsampler2;
  173460. typedef my_upsampler2 * my_upsample_ptr2;
  173461. /*
  173462. * Initialize for an upsampling pass.
  173463. */
  173464. METHODDEF(void)
  173465. start_pass_upsample (j_decompress_ptr cinfo)
  173466. {
  173467. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173468. /* Mark the conversion buffer empty */
  173469. upsample->next_row_out = cinfo->max_v_samp_factor;
  173470. /* Initialize total-height counter for detecting bottom of image */
  173471. upsample->rows_to_go = cinfo->output_height;
  173472. }
  173473. /*
  173474. * Control routine to do upsampling (and color conversion).
  173475. *
  173476. * In this version we upsample each component independently.
  173477. * We upsample one row group into the conversion buffer, then apply
  173478. * color conversion a row at a time.
  173479. */
  173480. METHODDEF(void)
  173481. sep_upsample (j_decompress_ptr cinfo,
  173482. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173483. JDIMENSION,
  173484. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173485. JDIMENSION out_rows_avail)
  173486. {
  173487. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173488. int ci;
  173489. jpeg_component_info * compptr;
  173490. JDIMENSION num_rows;
  173491. /* Fill the conversion buffer, if it's empty */
  173492. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173493. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173494. ci++, compptr++) {
  173495. /* Invoke per-component upsample method. Notice we pass a POINTER
  173496. * to color_buf[ci], so that fullsize_upsample can change it.
  173497. */
  173498. (*upsample->methods[ci]) (cinfo, compptr,
  173499. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173500. upsample->color_buf + ci);
  173501. }
  173502. upsample->next_row_out = 0;
  173503. }
  173504. /* Color-convert and emit rows */
  173505. /* How many we have in the buffer: */
  173506. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173507. /* Not more than the distance to the end of the image. Need this test
  173508. * in case the image height is not a multiple of max_v_samp_factor:
  173509. */
  173510. if (num_rows > upsample->rows_to_go)
  173511. num_rows = upsample->rows_to_go;
  173512. /* And not more than what the client can accept: */
  173513. out_rows_avail -= *out_row_ctr;
  173514. if (num_rows > out_rows_avail)
  173515. num_rows = out_rows_avail;
  173516. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173517. (JDIMENSION) upsample->next_row_out,
  173518. output_buf + *out_row_ctr,
  173519. (int) num_rows);
  173520. /* Adjust counts */
  173521. *out_row_ctr += num_rows;
  173522. upsample->rows_to_go -= num_rows;
  173523. upsample->next_row_out += num_rows;
  173524. /* When the buffer is emptied, declare this input row group consumed */
  173525. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173526. (*in_row_group_ctr)++;
  173527. }
  173528. /*
  173529. * These are the routines invoked by sep_upsample to upsample pixel values
  173530. * of a single component. One row group is processed per call.
  173531. */
  173532. /*
  173533. * For full-size components, we just make color_buf[ci] point at the
  173534. * input buffer, and thus avoid copying any data. Note that this is
  173535. * safe only because sep_upsample doesn't declare the input row group
  173536. * "consumed" until we are done color converting and emitting it.
  173537. */
  173538. METHODDEF(void)
  173539. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173540. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173541. {
  173542. *output_data_ptr = input_data;
  173543. }
  173544. /*
  173545. * This is a no-op version used for "uninteresting" components.
  173546. * These components will not be referenced by color conversion.
  173547. */
  173548. METHODDEF(void)
  173549. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173550. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173551. {
  173552. *output_data_ptr = NULL; /* safety check */
  173553. }
  173554. /*
  173555. * This version handles any integral sampling ratios.
  173556. * This is not used for typical JPEG files, so it need not be fast.
  173557. * Nor, for that matter, is it particularly accurate: the algorithm is
  173558. * simple replication of the input pixel onto the corresponding output
  173559. * pixels. The hi-falutin sampling literature refers to this as a
  173560. * "box filter". A box filter tends to introduce visible artifacts,
  173561. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173562. * you would be well advised to improve this code.
  173563. */
  173564. METHODDEF(void)
  173565. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173566. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173567. {
  173568. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173569. JSAMPARRAY output_data = *output_data_ptr;
  173570. register JSAMPROW inptr, outptr;
  173571. register JSAMPLE invalue;
  173572. register int h;
  173573. JSAMPROW outend;
  173574. int h_expand, v_expand;
  173575. int inrow, outrow;
  173576. h_expand = upsample->h_expand[compptr->component_index];
  173577. v_expand = upsample->v_expand[compptr->component_index];
  173578. inrow = outrow = 0;
  173579. while (outrow < cinfo->max_v_samp_factor) {
  173580. /* Generate one output row with proper horizontal expansion */
  173581. inptr = input_data[inrow];
  173582. outptr = output_data[outrow];
  173583. outend = outptr + cinfo->output_width;
  173584. while (outptr < outend) {
  173585. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173586. for (h = h_expand; h > 0; h--) {
  173587. *outptr++ = invalue;
  173588. }
  173589. }
  173590. /* Generate any additional output rows by duplicating the first one */
  173591. if (v_expand > 1) {
  173592. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173593. v_expand-1, cinfo->output_width);
  173594. }
  173595. inrow++;
  173596. outrow += v_expand;
  173597. }
  173598. }
  173599. /*
  173600. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173601. * It's still a box filter.
  173602. */
  173603. METHODDEF(void)
  173604. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173605. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173606. {
  173607. JSAMPARRAY output_data = *output_data_ptr;
  173608. register JSAMPROW inptr, outptr;
  173609. register JSAMPLE invalue;
  173610. JSAMPROW outend;
  173611. int inrow;
  173612. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173613. inptr = input_data[inrow];
  173614. outptr = output_data[inrow];
  173615. outend = outptr + cinfo->output_width;
  173616. while (outptr < outend) {
  173617. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173618. *outptr++ = invalue;
  173619. *outptr++ = invalue;
  173620. }
  173621. }
  173622. }
  173623. /*
  173624. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173625. * It's still a box filter.
  173626. */
  173627. METHODDEF(void)
  173628. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173629. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173630. {
  173631. JSAMPARRAY output_data = *output_data_ptr;
  173632. register JSAMPROW inptr, outptr;
  173633. register JSAMPLE invalue;
  173634. JSAMPROW outend;
  173635. int inrow, outrow;
  173636. inrow = outrow = 0;
  173637. while (outrow < cinfo->max_v_samp_factor) {
  173638. inptr = input_data[inrow];
  173639. outptr = output_data[outrow];
  173640. outend = outptr + cinfo->output_width;
  173641. while (outptr < outend) {
  173642. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173643. *outptr++ = invalue;
  173644. *outptr++ = invalue;
  173645. }
  173646. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173647. 1, cinfo->output_width);
  173648. inrow++;
  173649. outrow += 2;
  173650. }
  173651. }
  173652. /*
  173653. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173654. *
  173655. * The upsampling algorithm is linear interpolation between pixel centers,
  173656. * also known as a "triangle filter". This is a good compromise between
  173657. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173658. * of the way between input pixel centers.
  173659. *
  173660. * A note about the "bias" calculations: when rounding fractional values to
  173661. * integer, we do not want to always round 0.5 up to the next integer.
  173662. * If we did that, we'd introduce a noticeable bias towards larger values.
  173663. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  173664. * alternate pixel locations (a simple ordered dither pattern).
  173665. */
  173666. METHODDEF(void)
  173667. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173668. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173669. {
  173670. JSAMPARRAY output_data = *output_data_ptr;
  173671. register JSAMPROW inptr, outptr;
  173672. register int invalue;
  173673. register JDIMENSION colctr;
  173674. int inrow;
  173675. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173676. inptr = input_data[inrow];
  173677. outptr = output_data[inrow];
  173678. /* Special case for first column */
  173679. invalue = GETJSAMPLE(*inptr++);
  173680. *outptr++ = (JSAMPLE) invalue;
  173681. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  173682. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173683. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  173684. invalue = GETJSAMPLE(*inptr++) * 3;
  173685. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  173686. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  173687. }
  173688. /* Special case for last column */
  173689. invalue = GETJSAMPLE(*inptr);
  173690. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  173691. *outptr++ = (JSAMPLE) invalue;
  173692. }
  173693. }
  173694. /*
  173695. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  173696. * Again a triangle filter; see comments for h2v1 case, above.
  173697. *
  173698. * It is OK for us to reference the adjacent input rows because we demanded
  173699. * context from the main buffer controller (see initialization code).
  173700. */
  173701. METHODDEF(void)
  173702. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173703. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173704. {
  173705. JSAMPARRAY output_data = *output_data_ptr;
  173706. register JSAMPROW inptr0, inptr1, outptr;
  173707. #if BITS_IN_JSAMPLE == 8
  173708. register int thiscolsum, lastcolsum, nextcolsum;
  173709. #else
  173710. register INT32 thiscolsum, lastcolsum, nextcolsum;
  173711. #endif
  173712. register JDIMENSION colctr;
  173713. int inrow, outrow, v;
  173714. inrow = outrow = 0;
  173715. while (outrow < cinfo->max_v_samp_factor) {
  173716. for (v = 0; v < 2; v++) {
  173717. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  173718. inptr0 = input_data[inrow];
  173719. if (v == 0) /* next nearest is row above */
  173720. inptr1 = input_data[inrow-1];
  173721. else /* next nearest is row below */
  173722. inptr1 = input_data[inrow+1];
  173723. outptr = output_data[outrow++];
  173724. /* Special case for first column */
  173725. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173726. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173727. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  173728. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173729. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173730. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  173731. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  173732. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  173733. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  173734. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173735. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  173736. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  173737. }
  173738. /* Special case for last column */
  173739. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  173740. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  173741. }
  173742. inrow++;
  173743. }
  173744. }
  173745. /*
  173746. * Module initialization routine for upsampling.
  173747. */
  173748. GLOBAL(void)
  173749. jinit_upsampler (j_decompress_ptr cinfo)
  173750. {
  173751. my_upsample_ptr2 upsample;
  173752. int ci;
  173753. jpeg_component_info * compptr;
  173754. boolean need_buffer, do_fancy;
  173755. int h_in_group, v_in_group, h_out_group, v_out_group;
  173756. upsample = (my_upsample_ptr2)
  173757. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173758. SIZEOF(my_upsampler2));
  173759. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173760. upsample->pub.start_pass = start_pass_upsample;
  173761. upsample->pub.upsample = sep_upsample;
  173762. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  173763. if (cinfo->CCIR601_sampling) /* this isn't supported */
  173764. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  173765. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  173766. * so don't ask for it.
  173767. */
  173768. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  173769. /* Verify we can handle the sampling factors, select per-component methods,
  173770. * and create storage as needed.
  173771. */
  173772. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173773. ci++, compptr++) {
  173774. /* Compute size of an "input group" after IDCT scaling. This many samples
  173775. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  173776. */
  173777. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  173778. cinfo->min_DCT_scaled_size;
  173779. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  173780. cinfo->min_DCT_scaled_size;
  173781. h_out_group = cinfo->max_h_samp_factor;
  173782. v_out_group = cinfo->max_v_samp_factor;
  173783. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  173784. need_buffer = TRUE;
  173785. if (! compptr->component_needed) {
  173786. /* Don't bother to upsample an uninteresting component. */
  173787. upsample->methods[ci] = noop_upsample;
  173788. need_buffer = FALSE;
  173789. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  173790. /* Fullsize components can be processed without any work. */
  173791. upsample->methods[ci] = fullsize_upsample;
  173792. need_buffer = FALSE;
  173793. } else if (h_in_group * 2 == h_out_group &&
  173794. v_in_group == v_out_group) {
  173795. /* Special cases for 2h1v upsampling */
  173796. if (do_fancy && compptr->downsampled_width > 2)
  173797. upsample->methods[ci] = h2v1_fancy_upsample;
  173798. else
  173799. upsample->methods[ci] = h2v1_upsample;
  173800. } else if (h_in_group * 2 == h_out_group &&
  173801. v_in_group * 2 == v_out_group) {
  173802. /* Special cases for 2h2v upsampling */
  173803. if (do_fancy && compptr->downsampled_width > 2) {
  173804. upsample->methods[ci] = h2v2_fancy_upsample;
  173805. upsample->pub.need_context_rows = TRUE;
  173806. } else
  173807. upsample->methods[ci] = h2v2_upsample;
  173808. } else if ((h_out_group % h_in_group) == 0 &&
  173809. (v_out_group % v_in_group) == 0) {
  173810. /* Generic integral-factors upsampling method */
  173811. upsample->methods[ci] = int_upsample;
  173812. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  173813. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  173814. } else
  173815. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  173816. if (need_buffer) {
  173817. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  173818. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173819. (JDIMENSION) jround_up((long) cinfo->output_width,
  173820. (long) cinfo->max_h_samp_factor),
  173821. (JDIMENSION) cinfo->max_v_samp_factor);
  173822. }
  173823. }
  173824. }
  173825. /*** End of inlined file: jdsample.c ***/
  173826. /*** Start of inlined file: jdtrans.c ***/
  173827. #define JPEG_INTERNALS
  173828. /* Forward declarations */
  173829. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  173830. /*
  173831. * Read the coefficient arrays from a JPEG file.
  173832. * jpeg_read_header must be completed before calling this.
  173833. *
  173834. * The entire image is read into a set of virtual coefficient-block arrays,
  173835. * one per component. The return value is a pointer to the array of
  173836. * virtual-array descriptors. These can be manipulated directly via the
  173837. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  173838. * To release the memory occupied by the virtual arrays, call
  173839. * jpeg_finish_decompress() when done with the data.
  173840. *
  173841. * An alternative usage is to simply obtain access to the coefficient arrays
  173842. * during a buffered-image-mode decompression operation. This is allowed
  173843. * after any jpeg_finish_output() call. The arrays can be accessed until
  173844. * jpeg_finish_decompress() is called. (Note that any call to the library
  173845. * may reposition the arrays, so don't rely on access_virt_barray() results
  173846. * to stay valid across library calls.)
  173847. *
  173848. * Returns NULL if suspended. This case need be checked only if
  173849. * a suspending data source is used.
  173850. */
  173851. GLOBAL(jvirt_barray_ptr *)
  173852. jpeg_read_coefficients (j_decompress_ptr cinfo)
  173853. {
  173854. if (cinfo->global_state == DSTATE_READY) {
  173855. /* First call: initialize active modules */
  173856. transdecode_master_selection(cinfo);
  173857. cinfo->global_state = DSTATE_RDCOEFS;
  173858. }
  173859. if (cinfo->global_state == DSTATE_RDCOEFS) {
  173860. /* Absorb whole file into the coef buffer */
  173861. for (;;) {
  173862. int retcode;
  173863. /* Call progress monitor hook if present */
  173864. if (cinfo->progress != NULL)
  173865. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  173866. /* Absorb some more input */
  173867. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  173868. if (retcode == JPEG_SUSPENDED)
  173869. return NULL;
  173870. if (retcode == JPEG_REACHED_EOI)
  173871. break;
  173872. /* Advance progress counter if appropriate */
  173873. if (cinfo->progress != NULL &&
  173874. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  173875. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  173876. /* startup underestimated number of scans; ratchet up one scan */
  173877. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  173878. }
  173879. }
  173880. }
  173881. /* Set state so that jpeg_finish_decompress does the right thing */
  173882. cinfo->global_state = DSTATE_STOPPING;
  173883. }
  173884. /* At this point we should be in state DSTATE_STOPPING if being used
  173885. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  173886. * to the coefficients during a full buffered-image-mode decompression.
  173887. */
  173888. if ((cinfo->global_state == DSTATE_STOPPING ||
  173889. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  173890. return cinfo->coef->coef_arrays;
  173891. }
  173892. /* Oops, improper usage */
  173893. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173894. return NULL; /* keep compiler happy */
  173895. }
  173896. /*
  173897. * Master selection of decompression modules for transcoding.
  173898. * This substitutes for jdmaster.c's initialization of the full decompressor.
  173899. */
  173900. LOCAL(void)
  173901. transdecode_master_selection (j_decompress_ptr cinfo)
  173902. {
  173903. /* This is effectively a buffered-image operation. */
  173904. cinfo->buffered_image = TRUE;
  173905. /* Entropy decoding: either Huffman or arithmetic coding. */
  173906. if (cinfo->arith_code) {
  173907. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173908. } else {
  173909. if (cinfo->progressive_mode) {
  173910. #ifdef D_PROGRESSIVE_SUPPORTED
  173911. jinit_phuff_decoder(cinfo);
  173912. #else
  173913. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173914. #endif
  173915. } else
  173916. jinit_huff_decoder(cinfo);
  173917. }
  173918. /* Always get a full-image coefficient buffer. */
  173919. jinit_d_coef_controller(cinfo, TRUE);
  173920. /* We can now tell the memory manager to allocate virtual arrays. */
  173921. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173922. /* Initialize input side of decompressor to consume first scan. */
  173923. (*cinfo->inputctl->start_input_pass) (cinfo);
  173924. /* Initialize progress monitoring. */
  173925. if (cinfo->progress != NULL) {
  173926. int nscans;
  173927. /* Estimate number of scans to set pass_limit. */
  173928. if (cinfo->progressive_mode) {
  173929. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173930. nscans = 2 + 3 * cinfo->num_components;
  173931. } else if (cinfo->inputctl->has_multiple_scans) {
  173932. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173933. nscans = cinfo->num_components;
  173934. } else {
  173935. nscans = 1;
  173936. }
  173937. cinfo->progress->pass_counter = 0L;
  173938. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173939. cinfo->progress->completed_passes = 0;
  173940. cinfo->progress->total_passes = 1;
  173941. }
  173942. }
  173943. /*** End of inlined file: jdtrans.c ***/
  173944. /*** Start of inlined file: jfdctflt.c ***/
  173945. #define JPEG_INTERNALS
  173946. #ifdef DCT_FLOAT_SUPPORTED
  173947. /*
  173948. * This module is specialized to the case DCTSIZE = 8.
  173949. */
  173950. #if DCTSIZE != 8
  173951. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  173952. #endif
  173953. /*
  173954. * Perform the forward DCT on one block of samples.
  173955. */
  173956. GLOBAL(void)
  173957. jpeg_fdct_float (FAST_FLOAT * data)
  173958. {
  173959. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  173960. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  173961. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  173962. FAST_FLOAT *dataptr;
  173963. int ctr;
  173964. /* Pass 1: process rows. */
  173965. dataptr = data;
  173966. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  173967. tmp0 = dataptr[0] + dataptr[7];
  173968. tmp7 = dataptr[0] - dataptr[7];
  173969. tmp1 = dataptr[1] + dataptr[6];
  173970. tmp6 = dataptr[1] - dataptr[6];
  173971. tmp2 = dataptr[2] + dataptr[5];
  173972. tmp5 = dataptr[2] - dataptr[5];
  173973. tmp3 = dataptr[3] + dataptr[4];
  173974. tmp4 = dataptr[3] - dataptr[4];
  173975. /* Even part */
  173976. tmp10 = tmp0 + tmp3; /* phase 2 */
  173977. tmp13 = tmp0 - tmp3;
  173978. tmp11 = tmp1 + tmp2;
  173979. tmp12 = tmp1 - tmp2;
  173980. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  173981. dataptr[4] = tmp10 - tmp11;
  173982. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  173983. dataptr[2] = tmp13 + z1; /* phase 5 */
  173984. dataptr[6] = tmp13 - z1;
  173985. /* Odd part */
  173986. tmp10 = tmp4 + tmp5; /* phase 2 */
  173987. tmp11 = tmp5 + tmp6;
  173988. tmp12 = tmp6 + tmp7;
  173989. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  173990. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  173991. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  173992. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  173993. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  173994. z11 = tmp7 + z3; /* phase 5 */
  173995. z13 = tmp7 - z3;
  173996. dataptr[5] = z13 + z2; /* phase 6 */
  173997. dataptr[3] = z13 - z2;
  173998. dataptr[1] = z11 + z4;
  173999. dataptr[7] = z11 - z4;
  174000. dataptr += DCTSIZE; /* advance pointer to next row */
  174001. }
  174002. /* Pass 2: process columns. */
  174003. dataptr = data;
  174004. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174005. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174006. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174007. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174008. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174009. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174010. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174011. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174012. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174013. /* Even part */
  174014. tmp10 = tmp0 + tmp3; /* phase 2 */
  174015. tmp13 = tmp0 - tmp3;
  174016. tmp11 = tmp1 + tmp2;
  174017. tmp12 = tmp1 - tmp2;
  174018. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174019. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174020. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174021. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174022. dataptr[DCTSIZE*6] = tmp13 - z1;
  174023. /* Odd part */
  174024. tmp10 = tmp4 + tmp5; /* phase 2 */
  174025. tmp11 = tmp5 + tmp6;
  174026. tmp12 = tmp6 + tmp7;
  174027. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174028. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174029. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174030. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174031. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174032. z11 = tmp7 + z3; /* phase 5 */
  174033. z13 = tmp7 - z3;
  174034. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174035. dataptr[DCTSIZE*3] = z13 - z2;
  174036. dataptr[DCTSIZE*1] = z11 + z4;
  174037. dataptr[DCTSIZE*7] = z11 - z4;
  174038. dataptr++; /* advance pointer to next column */
  174039. }
  174040. }
  174041. #endif /* DCT_FLOAT_SUPPORTED */
  174042. /*** End of inlined file: jfdctflt.c ***/
  174043. /*** Start of inlined file: jfdctint.c ***/
  174044. #define JPEG_INTERNALS
  174045. #ifdef DCT_ISLOW_SUPPORTED
  174046. /*
  174047. * This module is specialized to the case DCTSIZE = 8.
  174048. */
  174049. #if DCTSIZE != 8
  174050. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174051. #endif
  174052. /*
  174053. * The poop on this scaling stuff is as follows:
  174054. *
  174055. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174056. * larger than the true DCT outputs. The final outputs are therefore
  174057. * a factor of N larger than desired; since N=8 this can be cured by
  174058. * a simple right shift at the end of the algorithm. The advantage of
  174059. * this arrangement is that we save two multiplications per 1-D DCT,
  174060. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174061. * In the IJG code, this factor of 8 is removed by the quantization step
  174062. * (in jcdctmgr.c), NOT in this module.
  174063. *
  174064. * We have to do addition and subtraction of the integer inputs, which
  174065. * is no problem, and multiplication by fractional constants, which is
  174066. * a problem to do in integer arithmetic. We multiply all the constants
  174067. * by CONST_SCALE and convert them to integer constants (thus retaining
  174068. * CONST_BITS bits of precision in the constants). After doing a
  174069. * multiplication we have to divide the product by CONST_SCALE, with proper
  174070. * rounding, to produce the correct output. This division can be done
  174071. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174072. * as long as possible so that partial sums can be added together with
  174073. * full fractional precision.
  174074. *
  174075. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174076. * they are represented to better-than-integral precision. These outputs
  174077. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174078. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174079. * array is INT32 anyway.)
  174080. *
  174081. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174082. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174083. * shows that the values given below are the most effective.
  174084. */
  174085. #if BITS_IN_JSAMPLE == 8
  174086. #define CONST_BITS 13
  174087. #define PASS1_BITS 2
  174088. #else
  174089. #define CONST_BITS 13
  174090. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174091. #endif
  174092. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174093. * causing a lot of useless floating-point operations at run time.
  174094. * To get around this we use the following pre-calculated constants.
  174095. * If you change CONST_BITS you may want to add appropriate values.
  174096. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174097. */
  174098. #if CONST_BITS == 13
  174099. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174100. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174101. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174102. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174103. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174104. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174105. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174106. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174107. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174108. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174109. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174110. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174111. #else
  174112. #define FIX_0_298631336 FIX(0.298631336)
  174113. #define FIX_0_390180644 FIX(0.390180644)
  174114. #define FIX_0_541196100 FIX(0.541196100)
  174115. #define FIX_0_765366865 FIX(0.765366865)
  174116. #define FIX_0_899976223 FIX(0.899976223)
  174117. #define FIX_1_175875602 FIX(1.175875602)
  174118. #define FIX_1_501321110 FIX(1.501321110)
  174119. #define FIX_1_847759065 FIX(1.847759065)
  174120. #define FIX_1_961570560 FIX(1.961570560)
  174121. #define FIX_2_053119869 FIX(2.053119869)
  174122. #define FIX_2_562915447 FIX(2.562915447)
  174123. #define FIX_3_072711026 FIX(3.072711026)
  174124. #endif
  174125. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174126. * For 8-bit samples with the recommended scaling, all the variable
  174127. * and constant values involved are no more than 16 bits wide, so a
  174128. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174129. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174130. */
  174131. #if BITS_IN_JSAMPLE == 8
  174132. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174133. #else
  174134. #define MULTIPLY(var,const) ((var) * (const))
  174135. #endif
  174136. /*
  174137. * Perform the forward DCT on one block of samples.
  174138. */
  174139. GLOBAL(void)
  174140. jpeg_fdct_islow (DCTELEM * data)
  174141. {
  174142. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174143. INT32 tmp10, tmp11, tmp12, tmp13;
  174144. INT32 z1, z2, z3, z4, z5;
  174145. DCTELEM *dataptr;
  174146. int ctr;
  174147. SHIFT_TEMPS
  174148. /* Pass 1: process rows. */
  174149. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174150. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174151. dataptr = data;
  174152. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174153. tmp0 = dataptr[0] + dataptr[7];
  174154. tmp7 = dataptr[0] - dataptr[7];
  174155. tmp1 = dataptr[1] + dataptr[6];
  174156. tmp6 = dataptr[1] - dataptr[6];
  174157. tmp2 = dataptr[2] + dataptr[5];
  174158. tmp5 = dataptr[2] - dataptr[5];
  174159. tmp3 = dataptr[3] + dataptr[4];
  174160. tmp4 = dataptr[3] - dataptr[4];
  174161. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174162. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174163. */
  174164. tmp10 = tmp0 + tmp3;
  174165. tmp13 = tmp0 - tmp3;
  174166. tmp11 = tmp1 + tmp2;
  174167. tmp12 = tmp1 - tmp2;
  174168. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174169. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174170. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174171. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174172. CONST_BITS-PASS1_BITS);
  174173. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174174. CONST_BITS-PASS1_BITS);
  174175. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174176. * cK represents cos(K*pi/16).
  174177. * i0..i3 in the paper are tmp4..tmp7 here.
  174178. */
  174179. z1 = tmp4 + tmp7;
  174180. z2 = tmp5 + tmp6;
  174181. z3 = tmp4 + tmp6;
  174182. z4 = tmp5 + tmp7;
  174183. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174184. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174185. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174186. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174187. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174188. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174189. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174190. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174191. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174192. z3 += z5;
  174193. z4 += z5;
  174194. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174195. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174196. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174197. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174198. dataptr += DCTSIZE; /* advance pointer to next row */
  174199. }
  174200. /* Pass 2: process columns.
  174201. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174202. * by an overall factor of 8.
  174203. */
  174204. dataptr = data;
  174205. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174206. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174207. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174208. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174209. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174210. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174211. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174212. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174213. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174214. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174215. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174216. */
  174217. tmp10 = tmp0 + tmp3;
  174218. tmp13 = tmp0 - tmp3;
  174219. tmp11 = tmp1 + tmp2;
  174220. tmp12 = tmp1 - tmp2;
  174221. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174222. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174223. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174224. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174225. CONST_BITS+PASS1_BITS);
  174226. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174227. CONST_BITS+PASS1_BITS);
  174228. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174229. * cK represents cos(K*pi/16).
  174230. * i0..i3 in the paper are tmp4..tmp7 here.
  174231. */
  174232. z1 = tmp4 + tmp7;
  174233. z2 = tmp5 + tmp6;
  174234. z3 = tmp4 + tmp6;
  174235. z4 = tmp5 + tmp7;
  174236. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174237. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174238. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174239. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174240. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174241. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174242. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174243. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174244. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174245. z3 += z5;
  174246. z4 += z5;
  174247. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174248. CONST_BITS+PASS1_BITS);
  174249. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174250. CONST_BITS+PASS1_BITS);
  174251. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174252. CONST_BITS+PASS1_BITS);
  174253. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174254. CONST_BITS+PASS1_BITS);
  174255. dataptr++; /* advance pointer to next column */
  174256. }
  174257. }
  174258. #endif /* DCT_ISLOW_SUPPORTED */
  174259. /*** End of inlined file: jfdctint.c ***/
  174260. #undef CONST_BITS
  174261. #undef MULTIPLY
  174262. #undef FIX_0_541196100
  174263. /*** Start of inlined file: jfdctfst.c ***/
  174264. #define JPEG_INTERNALS
  174265. #ifdef DCT_IFAST_SUPPORTED
  174266. /*
  174267. * This module is specialized to the case DCTSIZE = 8.
  174268. */
  174269. #if DCTSIZE != 8
  174270. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174271. #endif
  174272. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174273. * see jfdctint.c for more details. However, we choose to descale
  174274. * (right shift) multiplication products as soon as they are formed,
  174275. * rather than carrying additional fractional bits into subsequent additions.
  174276. * This compromises accuracy slightly, but it lets us save a few shifts.
  174277. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174278. * everywhere except in the multiplications proper; this saves a good deal
  174279. * of work on 16-bit-int machines.
  174280. *
  174281. * Again to save a few shifts, the intermediate results between pass 1 and
  174282. * pass 2 are not upscaled, but are represented only to integral precision.
  174283. *
  174284. * A final compromise is to represent the multiplicative constants to only
  174285. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174286. * machines, and may also reduce the cost of multiplication (since there
  174287. * are fewer one-bits in the constants).
  174288. */
  174289. #define CONST_BITS 8
  174290. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174291. * causing a lot of useless floating-point operations at run time.
  174292. * To get around this we use the following pre-calculated constants.
  174293. * If you change CONST_BITS you may want to add appropriate values.
  174294. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174295. */
  174296. #if CONST_BITS == 8
  174297. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174298. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174299. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174300. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174301. #else
  174302. #define FIX_0_382683433 FIX(0.382683433)
  174303. #define FIX_0_541196100 FIX(0.541196100)
  174304. #define FIX_0_707106781 FIX(0.707106781)
  174305. #define FIX_1_306562965 FIX(1.306562965)
  174306. #endif
  174307. /* We can gain a little more speed, with a further compromise in accuracy,
  174308. * by omitting the addition in a descaling shift. This yields an incorrectly
  174309. * rounded result half the time...
  174310. */
  174311. #ifndef USE_ACCURATE_ROUNDING
  174312. #undef DESCALE
  174313. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174314. #endif
  174315. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174316. * descale to yield a DCTELEM result.
  174317. */
  174318. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174319. /*
  174320. * Perform the forward DCT on one block of samples.
  174321. */
  174322. GLOBAL(void)
  174323. jpeg_fdct_ifast (DCTELEM * data)
  174324. {
  174325. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174326. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174327. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174328. DCTELEM *dataptr;
  174329. int ctr;
  174330. SHIFT_TEMPS
  174331. /* Pass 1: process rows. */
  174332. dataptr = data;
  174333. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174334. tmp0 = dataptr[0] + dataptr[7];
  174335. tmp7 = dataptr[0] - dataptr[7];
  174336. tmp1 = dataptr[1] + dataptr[6];
  174337. tmp6 = dataptr[1] - dataptr[6];
  174338. tmp2 = dataptr[2] + dataptr[5];
  174339. tmp5 = dataptr[2] - dataptr[5];
  174340. tmp3 = dataptr[3] + dataptr[4];
  174341. tmp4 = dataptr[3] - dataptr[4];
  174342. /* Even part */
  174343. tmp10 = tmp0 + tmp3; /* phase 2 */
  174344. tmp13 = tmp0 - tmp3;
  174345. tmp11 = tmp1 + tmp2;
  174346. tmp12 = tmp1 - tmp2;
  174347. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174348. dataptr[4] = tmp10 - tmp11;
  174349. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174350. dataptr[2] = tmp13 + z1; /* phase 5 */
  174351. dataptr[6] = tmp13 - z1;
  174352. /* Odd part */
  174353. tmp10 = tmp4 + tmp5; /* phase 2 */
  174354. tmp11 = tmp5 + tmp6;
  174355. tmp12 = tmp6 + tmp7;
  174356. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174357. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174358. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174359. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174360. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174361. z11 = tmp7 + z3; /* phase 5 */
  174362. z13 = tmp7 - z3;
  174363. dataptr[5] = z13 + z2; /* phase 6 */
  174364. dataptr[3] = z13 - z2;
  174365. dataptr[1] = z11 + z4;
  174366. dataptr[7] = z11 - z4;
  174367. dataptr += DCTSIZE; /* advance pointer to next row */
  174368. }
  174369. /* Pass 2: process columns. */
  174370. dataptr = data;
  174371. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174372. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174373. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174374. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174375. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174376. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174377. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174378. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174379. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174380. /* Even part */
  174381. tmp10 = tmp0 + tmp3; /* phase 2 */
  174382. tmp13 = tmp0 - tmp3;
  174383. tmp11 = tmp1 + tmp2;
  174384. tmp12 = tmp1 - tmp2;
  174385. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174386. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174387. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174388. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174389. dataptr[DCTSIZE*6] = tmp13 - z1;
  174390. /* Odd part */
  174391. tmp10 = tmp4 + tmp5; /* phase 2 */
  174392. tmp11 = tmp5 + tmp6;
  174393. tmp12 = tmp6 + tmp7;
  174394. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174395. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174396. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174397. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174398. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174399. z11 = tmp7 + z3; /* phase 5 */
  174400. z13 = tmp7 - z3;
  174401. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174402. dataptr[DCTSIZE*3] = z13 - z2;
  174403. dataptr[DCTSIZE*1] = z11 + z4;
  174404. dataptr[DCTSIZE*7] = z11 - z4;
  174405. dataptr++; /* advance pointer to next column */
  174406. }
  174407. }
  174408. #endif /* DCT_IFAST_SUPPORTED */
  174409. /*** End of inlined file: jfdctfst.c ***/
  174410. #undef FIX_0_541196100
  174411. /*** Start of inlined file: jidctflt.c ***/
  174412. #define JPEG_INTERNALS
  174413. #ifdef DCT_FLOAT_SUPPORTED
  174414. /*
  174415. * This module is specialized to the case DCTSIZE = 8.
  174416. */
  174417. #if DCTSIZE != 8
  174418. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174419. #endif
  174420. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174421. * entry; produce a float result.
  174422. */
  174423. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174424. /*
  174425. * Perform dequantization and inverse DCT on one block of coefficients.
  174426. */
  174427. GLOBAL(void)
  174428. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174429. JCOEFPTR coef_block,
  174430. JSAMPARRAY output_buf, JDIMENSION output_col)
  174431. {
  174432. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174433. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174434. FAST_FLOAT z5, z10, z11, z12, z13;
  174435. JCOEFPTR inptr;
  174436. FLOAT_MULT_TYPE * quantptr;
  174437. FAST_FLOAT * wsptr;
  174438. JSAMPROW outptr;
  174439. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174440. int ctr;
  174441. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174442. SHIFT_TEMPS
  174443. /* Pass 1: process columns from input, store into work array. */
  174444. inptr = coef_block;
  174445. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174446. wsptr = workspace;
  174447. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174448. /* Due to quantization, we will usually find that many of the input
  174449. * coefficients are zero, especially the AC terms. We can exploit this
  174450. * by short-circuiting the IDCT calculation for any column in which all
  174451. * the AC terms are zero. In that case each output is equal to the
  174452. * DC coefficient (with scale factor as needed).
  174453. * With typical images and quantization tables, half or more of the
  174454. * column DCT calculations can be simplified this way.
  174455. */
  174456. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174457. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174458. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174459. inptr[DCTSIZE*7] == 0) {
  174460. /* AC terms all zero */
  174461. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174462. wsptr[DCTSIZE*0] = dcval;
  174463. wsptr[DCTSIZE*1] = dcval;
  174464. wsptr[DCTSIZE*2] = dcval;
  174465. wsptr[DCTSIZE*3] = dcval;
  174466. wsptr[DCTSIZE*4] = dcval;
  174467. wsptr[DCTSIZE*5] = dcval;
  174468. wsptr[DCTSIZE*6] = dcval;
  174469. wsptr[DCTSIZE*7] = dcval;
  174470. inptr++; /* advance pointers to next column */
  174471. quantptr++;
  174472. wsptr++;
  174473. continue;
  174474. }
  174475. /* Even part */
  174476. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174477. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174478. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174479. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174480. tmp10 = tmp0 + tmp2; /* phase 3 */
  174481. tmp11 = tmp0 - tmp2;
  174482. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174483. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174484. tmp0 = tmp10 + tmp13; /* phase 2 */
  174485. tmp3 = tmp10 - tmp13;
  174486. tmp1 = tmp11 + tmp12;
  174487. tmp2 = tmp11 - tmp12;
  174488. /* Odd part */
  174489. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174490. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174491. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174492. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174493. z13 = tmp6 + tmp5; /* phase 6 */
  174494. z10 = tmp6 - tmp5;
  174495. z11 = tmp4 + tmp7;
  174496. z12 = tmp4 - tmp7;
  174497. tmp7 = z11 + z13; /* phase 5 */
  174498. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174499. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174500. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174501. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174502. tmp6 = tmp12 - tmp7; /* phase 2 */
  174503. tmp5 = tmp11 - tmp6;
  174504. tmp4 = tmp10 + tmp5;
  174505. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174506. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174507. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174508. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174509. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174510. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174511. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174512. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174513. inptr++; /* advance pointers to next column */
  174514. quantptr++;
  174515. wsptr++;
  174516. }
  174517. /* Pass 2: process rows from work array, store into output array. */
  174518. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174519. wsptr = workspace;
  174520. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174521. outptr = output_buf[ctr] + output_col;
  174522. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174523. * However, the column calculation has created many nonzero AC terms, so
  174524. * the simplification applies less often (typically 5% to 10% of the time).
  174525. * And testing floats for zero is relatively expensive, so we don't bother.
  174526. */
  174527. /* Even part */
  174528. tmp10 = wsptr[0] + wsptr[4];
  174529. tmp11 = wsptr[0] - wsptr[4];
  174530. tmp13 = wsptr[2] + wsptr[6];
  174531. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174532. tmp0 = tmp10 + tmp13;
  174533. tmp3 = tmp10 - tmp13;
  174534. tmp1 = tmp11 + tmp12;
  174535. tmp2 = tmp11 - tmp12;
  174536. /* Odd part */
  174537. z13 = wsptr[5] + wsptr[3];
  174538. z10 = wsptr[5] - wsptr[3];
  174539. z11 = wsptr[1] + wsptr[7];
  174540. z12 = wsptr[1] - wsptr[7];
  174541. tmp7 = z11 + z13;
  174542. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174543. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174544. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174545. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174546. tmp6 = tmp12 - tmp7;
  174547. tmp5 = tmp11 - tmp6;
  174548. tmp4 = tmp10 + tmp5;
  174549. /* Final output stage: scale down by a factor of 8 and range-limit */
  174550. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174551. & RANGE_MASK];
  174552. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174553. & RANGE_MASK];
  174554. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174555. & RANGE_MASK];
  174556. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174557. & RANGE_MASK];
  174558. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174559. & RANGE_MASK];
  174560. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174561. & RANGE_MASK];
  174562. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174563. & RANGE_MASK];
  174564. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174565. & RANGE_MASK];
  174566. wsptr += DCTSIZE; /* advance pointer to next row */
  174567. }
  174568. }
  174569. #endif /* DCT_FLOAT_SUPPORTED */
  174570. /*** End of inlined file: jidctflt.c ***/
  174571. #undef CONST_BITS
  174572. #undef FIX_1_847759065
  174573. #undef MULTIPLY
  174574. #undef DEQUANTIZE
  174575. #undef DESCALE
  174576. /*** Start of inlined file: jidctfst.c ***/
  174577. #define JPEG_INTERNALS
  174578. #ifdef DCT_IFAST_SUPPORTED
  174579. /*
  174580. * This module is specialized to the case DCTSIZE = 8.
  174581. */
  174582. #if DCTSIZE != 8
  174583. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174584. #endif
  174585. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174586. * see jidctint.c for more details. However, we choose to descale
  174587. * (right shift) multiplication products as soon as they are formed,
  174588. * rather than carrying additional fractional bits into subsequent additions.
  174589. * This compromises accuracy slightly, but it lets us save a few shifts.
  174590. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174591. * everywhere except in the multiplications proper; this saves a good deal
  174592. * of work on 16-bit-int machines.
  174593. *
  174594. * The dequantized coefficients are not integers because the AA&N scaling
  174595. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174596. * so that the first and second IDCT rounds have the same input scaling.
  174597. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174598. * avoid a descaling shift; this compromises accuracy rather drastically
  174599. * for small quantization table entries, but it saves a lot of shifts.
  174600. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174601. * so we use a much larger scaling factor to preserve accuracy.
  174602. *
  174603. * A final compromise is to represent the multiplicative constants to only
  174604. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174605. * machines, and may also reduce the cost of multiplication (since there
  174606. * are fewer one-bits in the constants).
  174607. */
  174608. #if BITS_IN_JSAMPLE == 8
  174609. #define CONST_BITS 8
  174610. #define PASS1_BITS 2
  174611. #else
  174612. #define CONST_BITS 8
  174613. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174614. #endif
  174615. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174616. * causing a lot of useless floating-point operations at run time.
  174617. * To get around this we use the following pre-calculated constants.
  174618. * If you change CONST_BITS you may want to add appropriate values.
  174619. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174620. */
  174621. #if CONST_BITS == 8
  174622. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174623. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174624. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174625. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174626. #else
  174627. #define FIX_1_082392200 FIX(1.082392200)
  174628. #define FIX_1_414213562 FIX(1.414213562)
  174629. #define FIX_1_847759065 FIX(1.847759065)
  174630. #define FIX_2_613125930 FIX(2.613125930)
  174631. #endif
  174632. /* We can gain a little more speed, with a further compromise in accuracy,
  174633. * by omitting the addition in a descaling shift. This yields an incorrectly
  174634. * rounded result half the time...
  174635. */
  174636. #ifndef USE_ACCURATE_ROUNDING
  174637. #undef DESCALE
  174638. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174639. #endif
  174640. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174641. * descale to yield a DCTELEM result.
  174642. */
  174643. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174644. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174645. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174646. * multiplication will do. For 12-bit data, the multiplier table is
  174647. * declared INT32, so a 32-bit multiply will be used.
  174648. */
  174649. #if BITS_IN_JSAMPLE == 8
  174650. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174651. #else
  174652. #define DEQUANTIZE(coef,quantval) \
  174653. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174654. #endif
  174655. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174656. * We assume that int right shift is unsigned if INT32 right shift is.
  174657. */
  174658. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174659. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174660. #if BITS_IN_JSAMPLE == 8
  174661. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  174662. #else
  174663. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  174664. #endif
  174665. #define IRIGHT_SHIFT(x,shft) \
  174666. ((ishift_temp = (x)) < 0 ? \
  174667. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  174668. (ishift_temp >> (shft)))
  174669. #else
  174670. #define ISHIFT_TEMPS
  174671. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  174672. #endif
  174673. #ifdef USE_ACCURATE_ROUNDING
  174674. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  174675. #else
  174676. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  174677. #endif
  174678. /*
  174679. * Perform dequantization and inverse DCT on one block of coefficients.
  174680. */
  174681. GLOBAL(void)
  174682. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174683. JCOEFPTR coef_block,
  174684. JSAMPARRAY output_buf, JDIMENSION output_col)
  174685. {
  174686. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174687. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174688. DCTELEM z5, z10, z11, z12, z13;
  174689. JCOEFPTR inptr;
  174690. IFAST_MULT_TYPE * quantptr;
  174691. int * wsptr;
  174692. JSAMPROW outptr;
  174693. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174694. int ctr;
  174695. int workspace[DCTSIZE2]; /* buffers data between passes */
  174696. SHIFT_TEMPS /* for DESCALE */
  174697. ISHIFT_TEMPS /* for IDESCALE */
  174698. /* Pass 1: process columns from input, store into work array. */
  174699. inptr = coef_block;
  174700. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  174701. wsptr = workspace;
  174702. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174703. /* Due to quantization, we will usually find that many of the input
  174704. * coefficients are zero, especially the AC terms. We can exploit this
  174705. * by short-circuiting the IDCT calculation for any column in which all
  174706. * the AC terms are zero. In that case each output is equal to the
  174707. * DC coefficient (with scale factor as needed).
  174708. * With typical images and quantization tables, half or more of the
  174709. * column DCT calculations can be simplified this way.
  174710. */
  174711. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174712. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174713. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174714. inptr[DCTSIZE*7] == 0) {
  174715. /* AC terms all zero */
  174716. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174717. wsptr[DCTSIZE*0] = dcval;
  174718. wsptr[DCTSIZE*1] = dcval;
  174719. wsptr[DCTSIZE*2] = dcval;
  174720. wsptr[DCTSIZE*3] = dcval;
  174721. wsptr[DCTSIZE*4] = dcval;
  174722. wsptr[DCTSIZE*5] = dcval;
  174723. wsptr[DCTSIZE*6] = dcval;
  174724. wsptr[DCTSIZE*7] = dcval;
  174725. inptr++; /* advance pointers to next column */
  174726. quantptr++;
  174727. wsptr++;
  174728. continue;
  174729. }
  174730. /* Even part */
  174731. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174732. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174733. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174734. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174735. tmp10 = tmp0 + tmp2; /* phase 3 */
  174736. tmp11 = tmp0 - tmp2;
  174737. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174738. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  174739. tmp0 = tmp10 + tmp13; /* phase 2 */
  174740. tmp3 = tmp10 - tmp13;
  174741. tmp1 = tmp11 + tmp12;
  174742. tmp2 = tmp11 - tmp12;
  174743. /* Odd part */
  174744. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174745. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174746. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174747. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174748. z13 = tmp6 + tmp5; /* phase 6 */
  174749. z10 = tmp6 - tmp5;
  174750. z11 = tmp4 + tmp7;
  174751. z12 = tmp4 - tmp7;
  174752. tmp7 = z11 + z13; /* phase 5 */
  174753. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174754. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174755. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174756. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174757. tmp6 = tmp12 - tmp7; /* phase 2 */
  174758. tmp5 = tmp11 - tmp6;
  174759. tmp4 = tmp10 + tmp5;
  174760. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  174761. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  174762. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  174763. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  174764. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  174765. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  174766. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  174767. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  174768. inptr++; /* advance pointers to next column */
  174769. quantptr++;
  174770. wsptr++;
  174771. }
  174772. /* Pass 2: process rows from work array, store into output array. */
  174773. /* Note that we must descale the results by a factor of 8 == 2**3, */
  174774. /* and also undo the PASS1_BITS scaling. */
  174775. wsptr = workspace;
  174776. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174777. outptr = output_buf[ctr] + output_col;
  174778. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174779. * However, the column calculation has created many nonzero AC terms, so
  174780. * the simplification applies less often (typically 5% to 10% of the time).
  174781. * On machines with very fast multiplication, it's possible that the
  174782. * test takes more time than it's worth. In that case this section
  174783. * may be commented out.
  174784. */
  174785. #ifndef NO_ZERO_ROW_TEST
  174786. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  174787. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  174788. /* AC terms all zero */
  174789. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  174790. & RANGE_MASK];
  174791. outptr[0] = dcval;
  174792. outptr[1] = dcval;
  174793. outptr[2] = dcval;
  174794. outptr[3] = dcval;
  174795. outptr[4] = dcval;
  174796. outptr[5] = dcval;
  174797. outptr[6] = dcval;
  174798. outptr[7] = dcval;
  174799. wsptr += DCTSIZE; /* advance pointer to next row */
  174800. continue;
  174801. }
  174802. #endif
  174803. /* Even part */
  174804. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  174805. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  174806. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  174807. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  174808. - tmp13;
  174809. tmp0 = tmp10 + tmp13;
  174810. tmp3 = tmp10 - tmp13;
  174811. tmp1 = tmp11 + tmp12;
  174812. tmp2 = tmp11 - tmp12;
  174813. /* Odd part */
  174814. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  174815. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  174816. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  174817. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  174818. tmp7 = z11 + z13; /* phase 5 */
  174819. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  174820. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  174821. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  174822. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  174823. tmp6 = tmp12 - tmp7; /* phase 2 */
  174824. tmp5 = tmp11 - tmp6;
  174825. tmp4 = tmp10 + tmp5;
  174826. /* Final output stage: scale down by a factor of 8 and range-limit */
  174827. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  174828. & RANGE_MASK];
  174829. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  174830. & RANGE_MASK];
  174831. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  174832. & RANGE_MASK];
  174833. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  174834. & RANGE_MASK];
  174835. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  174836. & RANGE_MASK];
  174837. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  174838. & RANGE_MASK];
  174839. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  174840. & RANGE_MASK];
  174841. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  174842. & RANGE_MASK];
  174843. wsptr += DCTSIZE; /* advance pointer to next row */
  174844. }
  174845. }
  174846. #endif /* DCT_IFAST_SUPPORTED */
  174847. /*** End of inlined file: jidctfst.c ***/
  174848. #undef CONST_BITS
  174849. #undef FIX_1_847759065
  174850. #undef MULTIPLY
  174851. #undef DEQUANTIZE
  174852. /*** Start of inlined file: jidctint.c ***/
  174853. #define JPEG_INTERNALS
  174854. #ifdef DCT_ISLOW_SUPPORTED
  174855. /*
  174856. * This module is specialized to the case DCTSIZE = 8.
  174857. */
  174858. #if DCTSIZE != 8
  174859. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174860. #endif
  174861. /*
  174862. * The poop on this scaling stuff is as follows:
  174863. *
  174864. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  174865. * larger than the true IDCT outputs. The final outputs are therefore
  174866. * a factor of N larger than desired; since N=8 this can be cured by
  174867. * a simple right shift at the end of the algorithm. The advantage of
  174868. * this arrangement is that we save two multiplications per 1-D IDCT,
  174869. * because the y0 and y4 inputs need not be divided by sqrt(N).
  174870. *
  174871. * We have to do addition and subtraction of the integer inputs, which
  174872. * is no problem, and multiplication by fractional constants, which is
  174873. * a problem to do in integer arithmetic. We multiply all the constants
  174874. * by CONST_SCALE and convert them to integer constants (thus retaining
  174875. * CONST_BITS bits of precision in the constants). After doing a
  174876. * multiplication we have to divide the product by CONST_SCALE, with proper
  174877. * rounding, to produce the correct output. This division can be done
  174878. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174879. * as long as possible so that partial sums can be added together with
  174880. * full fractional precision.
  174881. *
  174882. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174883. * they are represented to better-than-integral precision. These outputs
  174884. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174885. * with the recommended scaling. (To scale up 12-bit sample data further, an
  174886. * intermediate INT32 array would be needed.)
  174887. *
  174888. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174889. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174890. * shows that the values given below are the most effective.
  174891. */
  174892. #if BITS_IN_JSAMPLE == 8
  174893. #define CONST_BITS 13
  174894. #define PASS1_BITS 2
  174895. #else
  174896. #define CONST_BITS 13
  174897. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174898. #endif
  174899. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174900. * causing a lot of useless floating-point operations at run time.
  174901. * To get around this we use the following pre-calculated constants.
  174902. * If you change CONST_BITS you may want to add appropriate values.
  174903. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174904. */
  174905. #if CONST_BITS == 13
  174906. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174907. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174908. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174909. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174910. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174911. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174912. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174913. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174914. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174915. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174916. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174917. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174918. #else
  174919. #define FIX_0_298631336 FIX(0.298631336)
  174920. #define FIX_0_390180644 FIX(0.390180644)
  174921. #define FIX_0_541196100 FIX(0.541196100)
  174922. #define FIX_0_765366865 FIX(0.765366865)
  174923. #define FIX_0_899976223 FIX(0.899976223)
  174924. #define FIX_1_175875602 FIX(1.175875602)
  174925. #define FIX_1_501321110 FIX(1.501321110)
  174926. #define FIX_1_847759065 FIX(1.847759065)
  174927. #define FIX_1_961570560 FIX(1.961570560)
  174928. #define FIX_2_053119869 FIX(2.053119869)
  174929. #define FIX_2_562915447 FIX(2.562915447)
  174930. #define FIX_3_072711026 FIX(3.072711026)
  174931. #endif
  174932. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174933. * For 8-bit samples with the recommended scaling, all the variable
  174934. * and constant values involved are no more than 16 bits wide, so a
  174935. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174936. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174937. */
  174938. #if BITS_IN_JSAMPLE == 8
  174939. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174940. #else
  174941. #define MULTIPLY(var,const) ((var) * (const))
  174942. #endif
  174943. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174944. * entry; produce an int result. In this module, both inputs and result
  174945. * are 16 bits or less, so either int or short multiply will work.
  174946. */
  174947. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  174948. /*
  174949. * Perform dequantization and inverse DCT on one block of coefficients.
  174950. */
  174951. GLOBAL(void)
  174952. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174953. JCOEFPTR coef_block,
  174954. JSAMPARRAY output_buf, JDIMENSION output_col)
  174955. {
  174956. INT32 tmp0, tmp1, tmp2, tmp3;
  174957. INT32 tmp10, tmp11, tmp12, tmp13;
  174958. INT32 z1, z2, z3, z4, z5;
  174959. JCOEFPTR inptr;
  174960. ISLOW_MULT_TYPE * quantptr;
  174961. int * wsptr;
  174962. JSAMPROW outptr;
  174963. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174964. int ctr;
  174965. int workspace[DCTSIZE2]; /* buffers data between passes */
  174966. SHIFT_TEMPS
  174967. /* Pass 1: process columns from input, store into work array. */
  174968. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  174969. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174970. inptr = coef_block;
  174971. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  174972. wsptr = workspace;
  174973. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174974. /* Due to quantization, we will usually find that many of the input
  174975. * coefficients are zero, especially the AC terms. We can exploit this
  174976. * by short-circuiting the IDCT calculation for any column in which all
  174977. * the AC terms are zero. In that case each output is equal to the
  174978. * DC coefficient (with scale factor as needed).
  174979. * With typical images and quantization tables, half or more of the
  174980. * column DCT calculations can be simplified this way.
  174981. */
  174982. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174983. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174984. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174985. inptr[DCTSIZE*7] == 0) {
  174986. /* AC terms all zero */
  174987. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  174988. wsptr[DCTSIZE*0] = dcval;
  174989. wsptr[DCTSIZE*1] = dcval;
  174990. wsptr[DCTSIZE*2] = dcval;
  174991. wsptr[DCTSIZE*3] = dcval;
  174992. wsptr[DCTSIZE*4] = dcval;
  174993. wsptr[DCTSIZE*5] = dcval;
  174994. wsptr[DCTSIZE*6] = dcval;
  174995. wsptr[DCTSIZE*7] = dcval;
  174996. inptr++; /* advance pointers to next column */
  174997. quantptr++;
  174998. wsptr++;
  174999. continue;
  175000. }
  175001. /* Even part: reverse the even part of the forward DCT. */
  175002. /* The rotator is sqrt(2)*c(-6). */
  175003. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175004. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175005. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175006. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175007. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175008. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175009. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175010. tmp0 = (z2 + z3) << CONST_BITS;
  175011. tmp1 = (z2 - z3) << CONST_BITS;
  175012. tmp10 = tmp0 + tmp3;
  175013. tmp13 = tmp0 - tmp3;
  175014. tmp11 = tmp1 + tmp2;
  175015. tmp12 = tmp1 - tmp2;
  175016. /* Odd part per figure 8; the matrix is unitary and hence its
  175017. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175018. */
  175019. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175020. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175021. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175022. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175023. z1 = tmp0 + tmp3;
  175024. z2 = tmp1 + tmp2;
  175025. z3 = tmp0 + tmp2;
  175026. z4 = tmp1 + tmp3;
  175027. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175028. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175029. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175030. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175031. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175032. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175033. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175034. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175035. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175036. z3 += z5;
  175037. z4 += z5;
  175038. tmp0 += z1 + z3;
  175039. tmp1 += z2 + z4;
  175040. tmp2 += z2 + z3;
  175041. tmp3 += z1 + z4;
  175042. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175043. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175044. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175045. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175046. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175047. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175048. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175049. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175050. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175051. inptr++; /* advance pointers to next column */
  175052. quantptr++;
  175053. wsptr++;
  175054. }
  175055. /* Pass 2: process rows from work array, store into output array. */
  175056. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175057. /* and also undo the PASS1_BITS scaling. */
  175058. wsptr = workspace;
  175059. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175060. outptr = output_buf[ctr] + output_col;
  175061. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175062. * However, the column calculation has created many nonzero AC terms, so
  175063. * the simplification applies less often (typically 5% to 10% of the time).
  175064. * On machines with very fast multiplication, it's possible that the
  175065. * test takes more time than it's worth. In that case this section
  175066. * may be commented out.
  175067. */
  175068. #ifndef NO_ZERO_ROW_TEST
  175069. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175070. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175071. /* AC terms all zero */
  175072. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175073. & RANGE_MASK];
  175074. outptr[0] = dcval;
  175075. outptr[1] = dcval;
  175076. outptr[2] = dcval;
  175077. outptr[3] = dcval;
  175078. outptr[4] = dcval;
  175079. outptr[5] = dcval;
  175080. outptr[6] = dcval;
  175081. outptr[7] = dcval;
  175082. wsptr += DCTSIZE; /* advance pointer to next row */
  175083. continue;
  175084. }
  175085. #endif
  175086. /* Even part: reverse the even part of the forward DCT. */
  175087. /* The rotator is sqrt(2)*c(-6). */
  175088. z2 = (INT32) wsptr[2];
  175089. z3 = (INT32) wsptr[6];
  175090. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175091. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175092. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175093. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175094. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175095. tmp10 = tmp0 + tmp3;
  175096. tmp13 = tmp0 - tmp3;
  175097. tmp11 = tmp1 + tmp2;
  175098. tmp12 = tmp1 - tmp2;
  175099. /* Odd part per figure 8; the matrix is unitary and hence its
  175100. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175101. */
  175102. tmp0 = (INT32) wsptr[7];
  175103. tmp1 = (INT32) wsptr[5];
  175104. tmp2 = (INT32) wsptr[3];
  175105. tmp3 = (INT32) wsptr[1];
  175106. z1 = tmp0 + tmp3;
  175107. z2 = tmp1 + tmp2;
  175108. z3 = tmp0 + tmp2;
  175109. z4 = tmp1 + tmp3;
  175110. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175111. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175112. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175113. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175114. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175115. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175116. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175117. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175118. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175119. z3 += z5;
  175120. z4 += z5;
  175121. tmp0 += z1 + z3;
  175122. tmp1 += z2 + z4;
  175123. tmp2 += z2 + z3;
  175124. tmp3 += z1 + z4;
  175125. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175126. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175127. CONST_BITS+PASS1_BITS+3)
  175128. & RANGE_MASK];
  175129. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175130. CONST_BITS+PASS1_BITS+3)
  175131. & RANGE_MASK];
  175132. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175133. CONST_BITS+PASS1_BITS+3)
  175134. & RANGE_MASK];
  175135. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175136. CONST_BITS+PASS1_BITS+3)
  175137. & RANGE_MASK];
  175138. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175139. CONST_BITS+PASS1_BITS+3)
  175140. & RANGE_MASK];
  175141. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175142. CONST_BITS+PASS1_BITS+3)
  175143. & RANGE_MASK];
  175144. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175145. CONST_BITS+PASS1_BITS+3)
  175146. & RANGE_MASK];
  175147. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175148. CONST_BITS+PASS1_BITS+3)
  175149. & RANGE_MASK];
  175150. wsptr += DCTSIZE; /* advance pointer to next row */
  175151. }
  175152. }
  175153. #endif /* DCT_ISLOW_SUPPORTED */
  175154. /*** End of inlined file: jidctint.c ***/
  175155. /*** Start of inlined file: jidctred.c ***/
  175156. #define JPEG_INTERNALS
  175157. #ifdef IDCT_SCALING_SUPPORTED
  175158. /*
  175159. * This module is specialized to the case DCTSIZE = 8.
  175160. */
  175161. #if DCTSIZE != 8
  175162. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175163. #endif
  175164. /* Scaling is the same as in jidctint.c. */
  175165. #if BITS_IN_JSAMPLE == 8
  175166. #define CONST_BITS 13
  175167. #define PASS1_BITS 2
  175168. #else
  175169. #define CONST_BITS 13
  175170. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175171. #endif
  175172. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175173. * causing a lot of useless floating-point operations at run time.
  175174. * To get around this we use the following pre-calculated constants.
  175175. * If you change CONST_BITS you may want to add appropriate values.
  175176. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175177. */
  175178. #if CONST_BITS == 13
  175179. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175180. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175181. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175182. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175183. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175184. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175185. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175186. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175187. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175188. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175189. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175190. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175191. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175192. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175193. #else
  175194. #define FIX_0_211164243 FIX(0.211164243)
  175195. #define FIX_0_509795579 FIX(0.509795579)
  175196. #define FIX_0_601344887 FIX(0.601344887)
  175197. #define FIX_0_720959822 FIX(0.720959822)
  175198. #define FIX_0_765366865 FIX(0.765366865)
  175199. #define FIX_0_850430095 FIX(0.850430095)
  175200. #define FIX_0_899976223 FIX(0.899976223)
  175201. #define FIX_1_061594337 FIX(1.061594337)
  175202. #define FIX_1_272758580 FIX(1.272758580)
  175203. #define FIX_1_451774981 FIX(1.451774981)
  175204. #define FIX_1_847759065 FIX(1.847759065)
  175205. #define FIX_2_172734803 FIX(2.172734803)
  175206. #define FIX_2_562915447 FIX(2.562915447)
  175207. #define FIX_3_624509785 FIX(3.624509785)
  175208. #endif
  175209. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175210. * For 8-bit samples with the recommended scaling, all the variable
  175211. * and constant values involved are no more than 16 bits wide, so a
  175212. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175213. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175214. */
  175215. #if BITS_IN_JSAMPLE == 8
  175216. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175217. #else
  175218. #define MULTIPLY(var,const) ((var) * (const))
  175219. #endif
  175220. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175221. * entry; produce an int result. In this module, both inputs and result
  175222. * are 16 bits or less, so either int or short multiply will work.
  175223. */
  175224. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175225. /*
  175226. * Perform dequantization and inverse DCT on one block of coefficients,
  175227. * producing a reduced-size 4x4 output block.
  175228. */
  175229. GLOBAL(void)
  175230. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175231. JCOEFPTR coef_block,
  175232. JSAMPARRAY output_buf, JDIMENSION output_col)
  175233. {
  175234. INT32 tmp0, tmp2, tmp10, tmp12;
  175235. INT32 z1, z2, z3, z4;
  175236. JCOEFPTR inptr;
  175237. ISLOW_MULT_TYPE * quantptr;
  175238. int * wsptr;
  175239. JSAMPROW outptr;
  175240. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175241. int ctr;
  175242. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175243. SHIFT_TEMPS
  175244. /* Pass 1: process columns from input, store into work array. */
  175245. inptr = coef_block;
  175246. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175247. wsptr = workspace;
  175248. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175249. /* Don't bother to process column 4, because second pass won't use it */
  175250. if (ctr == DCTSIZE-4)
  175251. continue;
  175252. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175253. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175254. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175255. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175256. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175257. wsptr[DCTSIZE*0] = dcval;
  175258. wsptr[DCTSIZE*1] = dcval;
  175259. wsptr[DCTSIZE*2] = dcval;
  175260. wsptr[DCTSIZE*3] = dcval;
  175261. continue;
  175262. }
  175263. /* Even part */
  175264. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175265. tmp0 <<= (CONST_BITS+1);
  175266. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175267. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175268. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175269. tmp10 = tmp0 + tmp2;
  175270. tmp12 = tmp0 - tmp2;
  175271. /* Odd part */
  175272. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175273. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175274. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175275. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175276. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175277. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175278. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175279. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175280. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175281. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175282. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175283. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175284. /* Final output stage */
  175285. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175286. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175287. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175288. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175289. }
  175290. /* Pass 2: process 4 rows from work array, store into output array. */
  175291. wsptr = workspace;
  175292. for (ctr = 0; ctr < 4; ctr++) {
  175293. outptr = output_buf[ctr] + output_col;
  175294. /* It's not clear whether a zero row test is worthwhile here ... */
  175295. #ifndef NO_ZERO_ROW_TEST
  175296. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175297. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175298. /* AC terms all zero */
  175299. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175300. & RANGE_MASK];
  175301. outptr[0] = dcval;
  175302. outptr[1] = dcval;
  175303. outptr[2] = dcval;
  175304. outptr[3] = dcval;
  175305. wsptr += DCTSIZE; /* advance pointer to next row */
  175306. continue;
  175307. }
  175308. #endif
  175309. /* Even part */
  175310. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175311. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175312. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175313. tmp10 = tmp0 + tmp2;
  175314. tmp12 = tmp0 - tmp2;
  175315. /* Odd part */
  175316. z1 = (INT32) wsptr[7];
  175317. z2 = (INT32) wsptr[5];
  175318. z3 = (INT32) wsptr[3];
  175319. z4 = (INT32) wsptr[1];
  175320. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175321. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175322. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175323. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175324. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175325. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175326. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175327. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175328. /* Final output stage */
  175329. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175330. CONST_BITS+PASS1_BITS+3+1)
  175331. & RANGE_MASK];
  175332. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175333. CONST_BITS+PASS1_BITS+3+1)
  175334. & RANGE_MASK];
  175335. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175336. CONST_BITS+PASS1_BITS+3+1)
  175337. & RANGE_MASK];
  175338. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175339. CONST_BITS+PASS1_BITS+3+1)
  175340. & RANGE_MASK];
  175341. wsptr += DCTSIZE; /* advance pointer to next row */
  175342. }
  175343. }
  175344. /*
  175345. * Perform dequantization and inverse DCT on one block of coefficients,
  175346. * producing a reduced-size 2x2 output block.
  175347. */
  175348. GLOBAL(void)
  175349. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175350. JCOEFPTR coef_block,
  175351. JSAMPARRAY output_buf, JDIMENSION output_col)
  175352. {
  175353. INT32 tmp0, tmp10, z1;
  175354. JCOEFPTR inptr;
  175355. ISLOW_MULT_TYPE * quantptr;
  175356. int * wsptr;
  175357. JSAMPROW outptr;
  175358. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175359. int ctr;
  175360. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175361. SHIFT_TEMPS
  175362. /* Pass 1: process columns from input, store into work array. */
  175363. inptr = coef_block;
  175364. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175365. wsptr = workspace;
  175366. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175367. /* Don't bother to process columns 2,4,6 */
  175368. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175369. continue;
  175370. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175371. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175372. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175373. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175374. wsptr[DCTSIZE*0] = dcval;
  175375. wsptr[DCTSIZE*1] = dcval;
  175376. continue;
  175377. }
  175378. /* Even part */
  175379. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175380. tmp10 = z1 << (CONST_BITS+2);
  175381. /* Odd part */
  175382. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175383. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175384. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175385. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175386. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175387. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175388. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175389. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175390. /* Final output stage */
  175391. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175392. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175393. }
  175394. /* Pass 2: process 2 rows from work array, store into output array. */
  175395. wsptr = workspace;
  175396. for (ctr = 0; ctr < 2; ctr++) {
  175397. outptr = output_buf[ctr] + output_col;
  175398. /* It's not clear whether a zero row test is worthwhile here ... */
  175399. #ifndef NO_ZERO_ROW_TEST
  175400. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175401. /* AC terms all zero */
  175402. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175403. & RANGE_MASK];
  175404. outptr[0] = dcval;
  175405. outptr[1] = dcval;
  175406. wsptr += DCTSIZE; /* advance pointer to next row */
  175407. continue;
  175408. }
  175409. #endif
  175410. /* Even part */
  175411. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175412. /* Odd part */
  175413. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175414. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175415. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175416. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175417. /* Final output stage */
  175418. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175419. CONST_BITS+PASS1_BITS+3+2)
  175420. & RANGE_MASK];
  175421. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175422. CONST_BITS+PASS1_BITS+3+2)
  175423. & RANGE_MASK];
  175424. wsptr += DCTSIZE; /* advance pointer to next row */
  175425. }
  175426. }
  175427. /*
  175428. * Perform dequantization and inverse DCT on one block of coefficients,
  175429. * producing a reduced-size 1x1 output block.
  175430. */
  175431. GLOBAL(void)
  175432. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175433. JCOEFPTR coef_block,
  175434. JSAMPARRAY output_buf, JDIMENSION output_col)
  175435. {
  175436. int dcval;
  175437. ISLOW_MULT_TYPE * quantptr;
  175438. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175439. SHIFT_TEMPS
  175440. /* We hardly need an inverse DCT routine for this: just take the
  175441. * average pixel value, which is one-eighth of the DC coefficient.
  175442. */
  175443. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175444. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175445. dcval = (int) DESCALE((INT32) dcval, 3);
  175446. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175447. }
  175448. #endif /* IDCT_SCALING_SUPPORTED */
  175449. /*** End of inlined file: jidctred.c ***/
  175450. /*** Start of inlined file: jmemmgr.c ***/
  175451. #define JPEG_INTERNALS
  175452. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175453. /*** Start of inlined file: jmemsys.h ***/
  175454. #ifndef __jmemsys_h__
  175455. #define __jmemsys_h__
  175456. /* Short forms of external names for systems with brain-damaged linkers. */
  175457. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175458. #define jpeg_get_small jGetSmall
  175459. #define jpeg_free_small jFreeSmall
  175460. #define jpeg_get_large jGetLarge
  175461. #define jpeg_free_large jFreeLarge
  175462. #define jpeg_mem_available jMemAvail
  175463. #define jpeg_open_backing_store jOpenBackStore
  175464. #define jpeg_mem_init jMemInit
  175465. #define jpeg_mem_term jMemTerm
  175466. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175467. /*
  175468. * These two functions are used to allocate and release small chunks of
  175469. * memory. (Typically the total amount requested through jpeg_get_small is
  175470. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175471. * Behavior should be the same as for the standard library functions malloc
  175472. * and free; in particular, jpeg_get_small must return NULL on failure.
  175473. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175474. * size of the object being freed, just in case it's needed.
  175475. * On an 80x86 machine using small-data memory model, these manage near heap.
  175476. */
  175477. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175478. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175479. size_t sizeofobject));
  175480. /*
  175481. * These two functions are used to allocate and release large chunks of
  175482. * memory (up to the total free space designated by jpeg_mem_available).
  175483. * The interface is the same as above, except that on an 80x86 machine,
  175484. * far pointers are used. On most other machines these are identical to
  175485. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175486. * in case a different allocation strategy is desirable for large chunks.
  175487. */
  175488. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175489. size_t sizeofobject));
  175490. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175491. size_t sizeofobject));
  175492. /*
  175493. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175494. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175495. * matter, but that case should never come into play). This macro is needed
  175496. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175497. * On those machines, we expect that jconfig.h will provide a proper value.
  175498. * On machines with 32-bit flat address spaces, any large constant may be used.
  175499. *
  175500. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175501. * size_t and will be a multiple of sizeof(align_type).
  175502. */
  175503. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175504. #define MAX_ALLOC_CHUNK 1000000000L
  175505. #endif
  175506. /*
  175507. * This routine computes the total space still available for allocation by
  175508. * jpeg_get_large. If more space than this is needed, backing store will be
  175509. * used. NOTE: any memory already allocated must not be counted.
  175510. *
  175511. * There is a minimum space requirement, corresponding to the minimum
  175512. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175513. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175514. * all working storage in memory, is also passed in case it is useful.
  175515. * Finally, the total space already allocated is passed. If no better
  175516. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175517. * is often a suitable calculation.
  175518. *
  175519. * It is OK for jpeg_mem_available to underestimate the space available
  175520. * (that'll just lead to more backing-store access than is really necessary).
  175521. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175522. * a slop factor from the true available space. 5% should be enough.
  175523. *
  175524. * On machines with lots of virtual memory, any large constant may be returned.
  175525. * Conversely, zero may be returned to always use the minimum amount of memory.
  175526. */
  175527. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175528. long min_bytes_needed,
  175529. long max_bytes_needed,
  175530. long already_allocated));
  175531. /*
  175532. * This structure holds whatever state is needed to access a single
  175533. * backing-store object. The read/write/close method pointers are called
  175534. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175535. * are private to the system-dependent backing store routines.
  175536. */
  175537. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175538. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175539. typedef unsigned short XMSH; /* type of extended-memory handles */
  175540. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175541. typedef union {
  175542. short file_handle; /* DOS file handle if it's a temp file */
  175543. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175544. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175545. } handle_union;
  175546. #endif /* USE_MSDOS_MEMMGR */
  175547. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175548. #include <Files.h>
  175549. #endif /* USE_MAC_MEMMGR */
  175550. //typedef struct backing_store_struct * backing_store_ptr;
  175551. typedef struct backing_store_struct {
  175552. /* Methods for reading/writing/closing this backing-store object */
  175553. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175554. struct backing_store_struct *info,
  175555. void FAR * buffer_address,
  175556. long file_offset, long byte_count));
  175557. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175558. struct backing_store_struct *info,
  175559. void FAR * buffer_address,
  175560. long file_offset, long byte_count));
  175561. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175562. struct backing_store_struct *info));
  175563. /* Private fields for system-dependent backing-store management */
  175564. #ifdef USE_MSDOS_MEMMGR
  175565. /* For the MS-DOS manager (jmemdos.c), we need: */
  175566. handle_union handle; /* reference to backing-store storage object */
  175567. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175568. #else
  175569. #ifdef USE_MAC_MEMMGR
  175570. /* For the Mac manager (jmemmac.c), we need: */
  175571. short temp_file; /* file reference number to temp file */
  175572. FSSpec tempSpec; /* the FSSpec for the temp file */
  175573. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175574. #else
  175575. /* For a typical implementation with temp files, we need: */
  175576. FILE * temp_file; /* stdio reference to temp file */
  175577. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175578. #endif
  175579. #endif
  175580. } backing_store_info;
  175581. /*
  175582. * Initial opening of a backing-store object. This must fill in the
  175583. * read/write/close pointers in the object. The read/write routines
  175584. * may take an error exit if the specified maximum file size is exceeded.
  175585. * (If jpeg_mem_available always returns a large value, this routine can
  175586. * just take an error exit.)
  175587. */
  175588. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175589. struct backing_store_struct *info,
  175590. long total_bytes_needed));
  175591. /*
  175592. * These routines take care of any system-dependent initialization and
  175593. * cleanup required. jpeg_mem_init will be called before anything is
  175594. * allocated (and, therefore, nothing in cinfo is of use except the error
  175595. * manager pointer). It should return a suitable default value for
  175596. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175597. * application. (Note that max_memory_to_use is only important if
  175598. * jpeg_mem_available chooses to consult it ... no one else will.)
  175599. * jpeg_mem_term may assume that all requested memory has been freed and that
  175600. * all opened backing-store objects have been closed.
  175601. */
  175602. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175603. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175604. #endif
  175605. /*** End of inlined file: jmemsys.h ***/
  175606. /* import the system-dependent declarations */
  175607. #ifndef NO_GETENV
  175608. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175609. extern char * getenv JPP((const char * name));
  175610. #endif
  175611. #endif
  175612. /*
  175613. * Some important notes:
  175614. * The allocation routines provided here must never return NULL.
  175615. * They should exit to error_exit if unsuccessful.
  175616. *
  175617. * It's not a good idea to try to merge the sarray and barray routines,
  175618. * even though they are textually almost the same, because samples are
  175619. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175620. * in machines where byte pointers have a different representation from
  175621. * word pointers, the resulting machine code could not be the same.
  175622. */
  175623. /*
  175624. * Many machines require storage alignment: longs must start on 4-byte
  175625. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175626. * always returns pointers that are multiples of the worst-case alignment
  175627. * requirement, and we had better do so too.
  175628. * There isn't any really portable way to determine the worst-case alignment
  175629. * requirement. This module assumes that the alignment requirement is
  175630. * multiples of sizeof(ALIGN_TYPE).
  175631. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175632. * workstations (where doubles really do need 8-byte alignment) and will work
  175633. * fine on nearly everything. If your machine has lesser alignment needs,
  175634. * you can save a few bytes by making ALIGN_TYPE smaller.
  175635. * The only place I know of where this will NOT work is certain Macintosh
  175636. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175637. * Doing 10-byte alignment is counterproductive because longwords won't be
  175638. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175639. * such a compiler.
  175640. */
  175641. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175642. #define ALIGN_TYPE double
  175643. #endif
  175644. /*
  175645. * We allocate objects from "pools", where each pool is gotten with a single
  175646. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175647. * overhead within a pool, except for alignment padding. Each pool has a
  175648. * header with a link to the next pool of the same class.
  175649. * Small and large pool headers are identical except that the latter's
  175650. * link pointer must be FAR on 80x86 machines.
  175651. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175652. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175653. * of the alignment requirement of ALIGN_TYPE.
  175654. */
  175655. typedef union small_pool_struct * small_pool_ptr;
  175656. typedef union small_pool_struct {
  175657. struct {
  175658. small_pool_ptr next; /* next in list of pools */
  175659. size_t bytes_used; /* how many bytes already used within pool */
  175660. size_t bytes_left; /* bytes still available in this pool */
  175661. } hdr;
  175662. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175663. } small_pool_hdr;
  175664. typedef union large_pool_struct FAR * large_pool_ptr;
  175665. typedef union large_pool_struct {
  175666. struct {
  175667. large_pool_ptr next; /* next in list of pools */
  175668. size_t bytes_used; /* how many bytes already used within pool */
  175669. size_t bytes_left; /* bytes still available in this pool */
  175670. } hdr;
  175671. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  175672. } large_pool_hdr;
  175673. /*
  175674. * Here is the full definition of a memory manager object.
  175675. */
  175676. typedef struct {
  175677. struct jpeg_memory_mgr pub; /* public fields */
  175678. /* Each pool identifier (lifetime class) names a linked list of pools. */
  175679. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  175680. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  175681. /* Since we only have one lifetime class of virtual arrays, only one
  175682. * linked list is necessary (for each datatype). Note that the virtual
  175683. * array control blocks being linked together are actually stored somewhere
  175684. * in the small-pool list.
  175685. */
  175686. jvirt_sarray_ptr virt_sarray_list;
  175687. jvirt_barray_ptr virt_barray_list;
  175688. /* This counts total space obtained from jpeg_get_small/large */
  175689. long total_space_allocated;
  175690. /* alloc_sarray and alloc_barray set this value for use by virtual
  175691. * array routines.
  175692. */
  175693. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  175694. } my_memory_mgr;
  175695. typedef my_memory_mgr * my_mem_ptr;
  175696. /*
  175697. * The control blocks for virtual arrays.
  175698. * Note that these blocks are allocated in the "small" pool area.
  175699. * System-dependent info for the associated backing store (if any) is hidden
  175700. * inside the backing_store_info struct.
  175701. */
  175702. struct jvirt_sarray_control {
  175703. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  175704. JDIMENSION rows_in_array; /* total virtual array height */
  175705. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  175706. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  175707. JDIMENSION rows_in_mem; /* height of memory buffer */
  175708. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175709. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175710. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175711. boolean pre_zero; /* pre-zero mode requested? */
  175712. boolean dirty; /* do current buffer contents need written? */
  175713. boolean b_s_open; /* is backing-store data valid? */
  175714. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  175715. backing_store_info b_s_info; /* System-dependent control info */
  175716. };
  175717. struct jvirt_barray_control {
  175718. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  175719. JDIMENSION rows_in_array; /* total virtual array height */
  175720. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  175721. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  175722. JDIMENSION rows_in_mem; /* height of memory buffer */
  175723. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  175724. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  175725. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  175726. boolean pre_zero; /* pre-zero mode requested? */
  175727. boolean dirty; /* do current buffer contents need written? */
  175728. boolean b_s_open; /* is backing-store data valid? */
  175729. jvirt_barray_ptr next; /* link to next virtual barray control block */
  175730. backing_store_info b_s_info; /* System-dependent control info */
  175731. };
  175732. #ifdef MEM_STATS /* optional extra stuff for statistics */
  175733. LOCAL(void)
  175734. print_mem_stats (j_common_ptr cinfo, int pool_id)
  175735. {
  175736. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175737. small_pool_ptr shdr_ptr;
  175738. large_pool_ptr lhdr_ptr;
  175739. /* Since this is only a debugging stub, we can cheat a little by using
  175740. * fprintf directly rather than going through the trace message code.
  175741. * This is helpful because message parm array can't handle longs.
  175742. */
  175743. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  175744. pool_id, mem->total_space_allocated);
  175745. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  175746. lhdr_ptr = lhdr_ptr->hdr.next) {
  175747. fprintf(stderr, " Large chunk used %ld\n",
  175748. (long) lhdr_ptr->hdr.bytes_used);
  175749. }
  175750. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  175751. shdr_ptr = shdr_ptr->hdr.next) {
  175752. fprintf(stderr, " Small chunk used %ld free %ld\n",
  175753. (long) shdr_ptr->hdr.bytes_used,
  175754. (long) shdr_ptr->hdr.bytes_left);
  175755. }
  175756. }
  175757. #endif /* MEM_STATS */
  175758. LOCAL(void)
  175759. out_of_memory (j_common_ptr cinfo, int which)
  175760. /* Report an out-of-memory error and stop execution */
  175761. /* If we compiled MEM_STATS support, report alloc requests before dying */
  175762. {
  175763. #ifdef MEM_STATS
  175764. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  175765. #endif
  175766. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  175767. }
  175768. /*
  175769. * Allocation of "small" objects.
  175770. *
  175771. * For these, we use pooled storage. When a new pool must be created,
  175772. * we try to get enough space for the current request plus a "slop" factor,
  175773. * where the slop will be the amount of leftover space in the new pool.
  175774. * The speed vs. space tradeoff is largely determined by the slop values.
  175775. * A different slop value is provided for each pool class (lifetime),
  175776. * and we also distinguish the first pool of a class from later ones.
  175777. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  175778. * machines, but may be too small if longs are 64 bits or more.
  175779. */
  175780. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  175781. {
  175782. 1600, /* first PERMANENT pool */
  175783. 16000 /* first IMAGE pool */
  175784. };
  175785. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  175786. {
  175787. 0, /* additional PERMANENT pools */
  175788. 5000 /* additional IMAGE pools */
  175789. };
  175790. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  175791. METHODDEF(void *)
  175792. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175793. /* Allocate a "small" object */
  175794. {
  175795. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175796. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  175797. char * data_ptr;
  175798. size_t odd_bytes, min_request, slop;
  175799. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175800. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  175801. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  175802. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175803. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175804. if (odd_bytes > 0)
  175805. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175806. /* See if space is available in any existing pool */
  175807. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175808. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175809. prev_hdr_ptr = NULL;
  175810. hdr_ptr = mem->small_list[pool_id];
  175811. while (hdr_ptr != NULL) {
  175812. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  175813. break; /* found pool with enough space */
  175814. prev_hdr_ptr = hdr_ptr;
  175815. hdr_ptr = hdr_ptr->hdr.next;
  175816. }
  175817. /* Time to make a new pool? */
  175818. if (hdr_ptr == NULL) {
  175819. /* min_request is what we need now, slop is what will be leftover */
  175820. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  175821. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175822. slop = first_pool_slop[pool_id];
  175823. else
  175824. slop = extra_pool_slop[pool_id];
  175825. /* Don't ask for more than MAX_ALLOC_CHUNK */
  175826. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  175827. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  175828. /* Try to get space, if fail reduce slop and try again */
  175829. for (;;) {
  175830. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  175831. if (hdr_ptr != NULL)
  175832. break;
  175833. slop /= 2;
  175834. if (slop < MIN_SLOP) /* give up when it gets real small */
  175835. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  175836. }
  175837. mem->total_space_allocated += min_request + slop;
  175838. /* Success, initialize the new pool header and add to end of list */
  175839. hdr_ptr->hdr.next = NULL;
  175840. hdr_ptr->hdr.bytes_used = 0;
  175841. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  175842. if (prev_hdr_ptr == NULL) /* first pool in class? */
  175843. mem->small_list[pool_id] = hdr_ptr;
  175844. else
  175845. prev_hdr_ptr->hdr.next = hdr_ptr;
  175846. }
  175847. /* OK, allocate the object from the current pool */
  175848. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  175849. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  175850. hdr_ptr->hdr.bytes_used += sizeofobject;
  175851. hdr_ptr->hdr.bytes_left -= sizeofobject;
  175852. return (void *) data_ptr;
  175853. }
  175854. /*
  175855. * Allocation of "large" objects.
  175856. *
  175857. * The external semantics of these are the same as "small" objects,
  175858. * except that FAR pointers are used on 80x86. However the pool
  175859. * management heuristics are quite different. We assume that each
  175860. * request is large enough that it may as well be passed directly to
  175861. * jpeg_get_large; the pool management just links everything together
  175862. * so that we can free it all on demand.
  175863. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  175864. * structures. The routines that create these structures (see below)
  175865. * deliberately bunch rows together to ensure a large request size.
  175866. */
  175867. METHODDEF(void FAR *)
  175868. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  175869. /* Allocate a "large" object */
  175870. {
  175871. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175872. large_pool_ptr hdr_ptr;
  175873. size_t odd_bytes;
  175874. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  175875. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  175876. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  175877. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  175878. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  175879. if (odd_bytes > 0)
  175880. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  175881. /* Always make a new pool */
  175882. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  175883. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  175884. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  175885. SIZEOF(large_pool_hdr));
  175886. if (hdr_ptr == NULL)
  175887. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  175888. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  175889. /* Success, initialize the new pool header and add to list */
  175890. hdr_ptr->hdr.next = mem->large_list[pool_id];
  175891. /* We maintain space counts in each pool header for statistical purposes,
  175892. * even though they are not needed for allocation.
  175893. */
  175894. hdr_ptr->hdr.bytes_used = sizeofobject;
  175895. hdr_ptr->hdr.bytes_left = 0;
  175896. mem->large_list[pool_id] = hdr_ptr;
  175897. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  175898. }
  175899. /*
  175900. * Creation of 2-D sample arrays.
  175901. * The pointers are in near heap, the samples themselves in FAR heap.
  175902. *
  175903. * To minimize allocation overhead and to allow I/O of large contiguous
  175904. * blocks, we allocate the sample rows in groups of as many rows as possible
  175905. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  175906. * NB: the virtual array control routines, later in this file, know about
  175907. * this chunking of rows. The rowsperchunk value is left in the mem manager
  175908. * object so that it can be saved away if this sarray is the workspace for
  175909. * a virtual array.
  175910. */
  175911. METHODDEF(JSAMPARRAY)
  175912. alloc_sarray (j_common_ptr cinfo, int pool_id,
  175913. JDIMENSION samplesperrow, JDIMENSION numrows)
  175914. /* Allocate a 2-D sample array */
  175915. {
  175916. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175917. JSAMPARRAY result;
  175918. JSAMPROW workspace;
  175919. JDIMENSION rowsperchunk, currow, i;
  175920. long ltemp;
  175921. /* Calculate max # of rows allowed in one allocation chunk */
  175922. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175923. ((long) samplesperrow * SIZEOF(JSAMPLE));
  175924. if (ltemp <= 0)
  175925. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175926. if (ltemp < (long) numrows)
  175927. rowsperchunk = (JDIMENSION) ltemp;
  175928. else
  175929. rowsperchunk = numrows;
  175930. mem->last_rowsperchunk = rowsperchunk;
  175931. /* Get space for row pointers (small object) */
  175932. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  175933. (size_t) (numrows * SIZEOF(JSAMPROW)));
  175934. /* Get the rows themselves (large objects) */
  175935. currow = 0;
  175936. while (currow < numrows) {
  175937. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175938. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  175939. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  175940. * SIZEOF(JSAMPLE)));
  175941. for (i = rowsperchunk; i > 0; i--) {
  175942. result[currow++] = workspace;
  175943. workspace += samplesperrow;
  175944. }
  175945. }
  175946. return result;
  175947. }
  175948. /*
  175949. * Creation of 2-D coefficient-block arrays.
  175950. * This is essentially the same as the code for sample arrays, above.
  175951. */
  175952. METHODDEF(JBLOCKARRAY)
  175953. alloc_barray (j_common_ptr cinfo, int pool_id,
  175954. JDIMENSION blocksperrow, JDIMENSION numrows)
  175955. /* Allocate a 2-D coefficient-block array */
  175956. {
  175957. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  175958. JBLOCKARRAY result;
  175959. JBLOCKROW workspace;
  175960. JDIMENSION rowsperchunk, currow, i;
  175961. long ltemp;
  175962. /* Calculate max # of rows allowed in one allocation chunk */
  175963. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  175964. ((long) blocksperrow * SIZEOF(JBLOCK));
  175965. if (ltemp <= 0)
  175966. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  175967. if (ltemp < (long) numrows)
  175968. rowsperchunk = (JDIMENSION) ltemp;
  175969. else
  175970. rowsperchunk = numrows;
  175971. mem->last_rowsperchunk = rowsperchunk;
  175972. /* Get space for row pointers (small object) */
  175973. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  175974. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  175975. /* Get the rows themselves (large objects) */
  175976. currow = 0;
  175977. while (currow < numrows) {
  175978. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  175979. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  175980. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  175981. * SIZEOF(JBLOCK)));
  175982. for (i = rowsperchunk; i > 0; i--) {
  175983. result[currow++] = workspace;
  175984. workspace += blocksperrow;
  175985. }
  175986. }
  175987. return result;
  175988. }
  175989. /*
  175990. * About virtual array management:
  175991. *
  175992. * The above "normal" array routines are only used to allocate strip buffers
  175993. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  175994. * are handled as "virtual" arrays. The array is still accessed a strip at a
  175995. * time, but the memory manager must save the whole array for repeated
  175996. * accesses. The intended implementation is that there is a strip buffer in
  175997. * memory (as high as is possible given the desired memory limit), plus a
  175998. * backing file that holds the rest of the array.
  175999. *
  176000. * The request_virt_array routines are told the total size of the image and
  176001. * the maximum number of rows that will be accessed at once. The in-memory
  176002. * buffer must be at least as large as the maxaccess value.
  176003. *
  176004. * The request routines create control blocks but not the in-memory buffers.
  176005. * That is postponed until realize_virt_arrays is called. At that time the
  176006. * total amount of space needed is known (approximately, anyway), so free
  176007. * memory can be divided up fairly.
  176008. *
  176009. * The access_virt_array routines are responsible for making a specific strip
  176010. * area accessible (after reading or writing the backing file, if necessary).
  176011. * Note that the access routines are told whether the caller intends to modify
  176012. * the accessed strip; during a read-only pass this saves having to rewrite
  176013. * data to disk. The access routines are also responsible for pre-zeroing
  176014. * any newly accessed rows, if pre-zeroing was requested.
  176015. *
  176016. * In current usage, the access requests are usually for nonoverlapping
  176017. * strips; that is, successive access start_row numbers differ by exactly
  176018. * num_rows = maxaccess. This means we can get good performance with simple
  176019. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176020. * of the access height; then there will never be accesses across bufferload
  176021. * boundaries. The code will still work with overlapping access requests,
  176022. * but it doesn't handle bufferload overlaps very efficiently.
  176023. */
  176024. METHODDEF(jvirt_sarray_ptr)
  176025. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176026. JDIMENSION samplesperrow, JDIMENSION numrows,
  176027. JDIMENSION maxaccess)
  176028. /* Request a virtual 2-D sample array */
  176029. {
  176030. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176031. jvirt_sarray_ptr result;
  176032. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176033. if (pool_id != JPOOL_IMAGE)
  176034. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176035. /* get control block */
  176036. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176037. SIZEOF(struct jvirt_sarray_control));
  176038. result->mem_buffer = NULL; /* marks array not yet realized */
  176039. result->rows_in_array = numrows;
  176040. result->samplesperrow = samplesperrow;
  176041. result->maxaccess = maxaccess;
  176042. result->pre_zero = pre_zero;
  176043. result->b_s_open = FALSE; /* no associated backing-store object */
  176044. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176045. mem->virt_sarray_list = result;
  176046. return result;
  176047. }
  176048. METHODDEF(jvirt_barray_ptr)
  176049. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176050. JDIMENSION blocksperrow, JDIMENSION numrows,
  176051. JDIMENSION maxaccess)
  176052. /* Request a virtual 2-D coefficient-block array */
  176053. {
  176054. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176055. jvirt_barray_ptr result;
  176056. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176057. if (pool_id != JPOOL_IMAGE)
  176058. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176059. /* get control block */
  176060. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176061. SIZEOF(struct jvirt_barray_control));
  176062. result->mem_buffer = NULL; /* marks array not yet realized */
  176063. result->rows_in_array = numrows;
  176064. result->blocksperrow = blocksperrow;
  176065. result->maxaccess = maxaccess;
  176066. result->pre_zero = pre_zero;
  176067. result->b_s_open = FALSE; /* no associated backing-store object */
  176068. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176069. mem->virt_barray_list = result;
  176070. return result;
  176071. }
  176072. METHODDEF(void)
  176073. realize_virt_arrays (j_common_ptr cinfo)
  176074. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176075. {
  176076. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176077. long space_per_minheight, maximum_space, avail_mem;
  176078. long minheights, max_minheights;
  176079. jvirt_sarray_ptr sptr;
  176080. jvirt_barray_ptr bptr;
  176081. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176082. * and the maximum space needed (full image height in each buffer).
  176083. * These may be of use to the system-dependent jpeg_mem_available routine.
  176084. */
  176085. space_per_minheight = 0;
  176086. maximum_space = 0;
  176087. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176088. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176089. space_per_minheight += (long) sptr->maxaccess *
  176090. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176091. maximum_space += (long) sptr->rows_in_array *
  176092. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176093. }
  176094. }
  176095. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176096. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176097. space_per_minheight += (long) bptr->maxaccess *
  176098. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176099. maximum_space += (long) bptr->rows_in_array *
  176100. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176101. }
  176102. }
  176103. if (space_per_minheight <= 0)
  176104. return; /* no unrealized arrays, no work */
  176105. /* Determine amount of memory to actually use; this is system-dependent. */
  176106. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176107. mem->total_space_allocated);
  176108. /* If the maximum space needed is available, make all the buffers full
  176109. * height; otherwise parcel it out with the same number of minheights
  176110. * in each buffer.
  176111. */
  176112. if (avail_mem >= maximum_space)
  176113. max_minheights = 1000000000L;
  176114. else {
  176115. max_minheights = avail_mem / space_per_minheight;
  176116. /* If there doesn't seem to be enough space, try to get the minimum
  176117. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176118. */
  176119. if (max_minheights <= 0)
  176120. max_minheights = 1;
  176121. }
  176122. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176123. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176124. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176125. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176126. if (minheights <= max_minheights) {
  176127. /* This buffer fits in memory */
  176128. sptr->rows_in_mem = sptr->rows_in_array;
  176129. } else {
  176130. /* It doesn't fit in memory, create backing store. */
  176131. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176132. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176133. (long) sptr->rows_in_array *
  176134. (long) sptr->samplesperrow *
  176135. (long) SIZEOF(JSAMPLE));
  176136. sptr->b_s_open = TRUE;
  176137. }
  176138. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176139. sptr->samplesperrow, sptr->rows_in_mem);
  176140. sptr->rowsperchunk = mem->last_rowsperchunk;
  176141. sptr->cur_start_row = 0;
  176142. sptr->first_undef_row = 0;
  176143. sptr->dirty = FALSE;
  176144. }
  176145. }
  176146. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176147. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176148. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176149. if (minheights <= max_minheights) {
  176150. /* This buffer fits in memory */
  176151. bptr->rows_in_mem = bptr->rows_in_array;
  176152. } else {
  176153. /* It doesn't fit in memory, create backing store. */
  176154. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176155. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176156. (long) bptr->rows_in_array *
  176157. (long) bptr->blocksperrow *
  176158. (long) SIZEOF(JBLOCK));
  176159. bptr->b_s_open = TRUE;
  176160. }
  176161. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176162. bptr->blocksperrow, bptr->rows_in_mem);
  176163. bptr->rowsperchunk = mem->last_rowsperchunk;
  176164. bptr->cur_start_row = 0;
  176165. bptr->first_undef_row = 0;
  176166. bptr->dirty = FALSE;
  176167. }
  176168. }
  176169. }
  176170. LOCAL(void)
  176171. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176172. /* Do backing store read or write of a virtual sample array */
  176173. {
  176174. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176175. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176176. file_offset = ptr->cur_start_row * bytesperrow;
  176177. /* Loop to read or write each allocation chunk in mem_buffer */
  176178. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176179. /* One chunk, but check for short chunk at end of buffer */
  176180. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176181. /* Transfer no more than is currently defined */
  176182. thisrow = (long) ptr->cur_start_row + i;
  176183. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176184. /* Transfer no more than fits in file */
  176185. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176186. if (rows <= 0) /* this chunk might be past end of file! */
  176187. break;
  176188. byte_count = rows * bytesperrow;
  176189. if (writing)
  176190. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176191. (void FAR *) ptr->mem_buffer[i],
  176192. file_offset, byte_count);
  176193. else
  176194. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176195. (void FAR *) ptr->mem_buffer[i],
  176196. file_offset, byte_count);
  176197. file_offset += byte_count;
  176198. }
  176199. }
  176200. LOCAL(void)
  176201. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176202. /* Do backing store read or write of a virtual coefficient-block array */
  176203. {
  176204. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176205. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176206. file_offset = ptr->cur_start_row * bytesperrow;
  176207. /* Loop to read or write each allocation chunk in mem_buffer */
  176208. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176209. /* One chunk, but check for short chunk at end of buffer */
  176210. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176211. /* Transfer no more than is currently defined */
  176212. thisrow = (long) ptr->cur_start_row + i;
  176213. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176214. /* Transfer no more than fits in file */
  176215. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176216. if (rows <= 0) /* this chunk might be past end of file! */
  176217. break;
  176218. byte_count = rows * bytesperrow;
  176219. if (writing)
  176220. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176221. (void FAR *) ptr->mem_buffer[i],
  176222. file_offset, byte_count);
  176223. else
  176224. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176225. (void FAR *) ptr->mem_buffer[i],
  176226. file_offset, byte_count);
  176227. file_offset += byte_count;
  176228. }
  176229. }
  176230. METHODDEF(JSAMPARRAY)
  176231. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176232. JDIMENSION start_row, JDIMENSION num_rows,
  176233. boolean writable)
  176234. /* Access the part of a virtual sample array starting at start_row */
  176235. /* and extending for num_rows rows. writable is true if */
  176236. /* caller intends to modify the accessed area. */
  176237. {
  176238. JDIMENSION end_row = start_row + num_rows;
  176239. JDIMENSION undef_row;
  176240. /* debugging check */
  176241. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176242. ptr->mem_buffer == NULL)
  176243. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176244. /* Make the desired part of the virtual array accessible */
  176245. if (start_row < ptr->cur_start_row ||
  176246. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176247. if (! ptr->b_s_open)
  176248. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176249. /* Flush old buffer contents if necessary */
  176250. if (ptr->dirty) {
  176251. do_sarray_io(cinfo, ptr, TRUE);
  176252. ptr->dirty = FALSE;
  176253. }
  176254. /* Decide what part of virtual array to access.
  176255. * Algorithm: if target address > current window, assume forward scan,
  176256. * load starting at target address. If target address < current window,
  176257. * assume backward scan, load so that target area is top of window.
  176258. * Note that when switching from forward write to forward read, will have
  176259. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176260. */
  176261. if (start_row > ptr->cur_start_row) {
  176262. ptr->cur_start_row = start_row;
  176263. } else {
  176264. /* use long arithmetic here to avoid overflow & unsigned problems */
  176265. long ltemp;
  176266. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176267. if (ltemp < 0)
  176268. ltemp = 0; /* don't fall off front end of file */
  176269. ptr->cur_start_row = (JDIMENSION) ltemp;
  176270. }
  176271. /* Read in the selected part of the array.
  176272. * During the initial write pass, we will do no actual read
  176273. * because the selected part is all undefined.
  176274. */
  176275. do_sarray_io(cinfo, ptr, FALSE);
  176276. }
  176277. /* Ensure the accessed part of the array is defined; prezero if needed.
  176278. * To improve locality of access, we only prezero the part of the array
  176279. * that the caller is about to access, not the entire in-memory array.
  176280. */
  176281. if (ptr->first_undef_row < end_row) {
  176282. if (ptr->first_undef_row < start_row) {
  176283. if (writable) /* writer skipped over a section of array */
  176284. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176285. undef_row = start_row; /* but reader is allowed to read ahead */
  176286. } else {
  176287. undef_row = ptr->first_undef_row;
  176288. }
  176289. if (writable)
  176290. ptr->first_undef_row = end_row;
  176291. if (ptr->pre_zero) {
  176292. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176293. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176294. end_row -= ptr->cur_start_row;
  176295. while (undef_row < end_row) {
  176296. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176297. undef_row++;
  176298. }
  176299. } else {
  176300. if (! writable) /* reader looking at undefined data */
  176301. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176302. }
  176303. }
  176304. /* Flag the buffer dirty if caller will write in it */
  176305. if (writable)
  176306. ptr->dirty = TRUE;
  176307. /* Return address of proper part of the buffer */
  176308. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176309. }
  176310. METHODDEF(JBLOCKARRAY)
  176311. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176312. JDIMENSION start_row, JDIMENSION num_rows,
  176313. boolean writable)
  176314. /* Access the part of a virtual block array starting at start_row */
  176315. /* and extending for num_rows rows. writable is true if */
  176316. /* caller intends to modify the accessed area. */
  176317. {
  176318. JDIMENSION end_row = start_row + num_rows;
  176319. JDIMENSION undef_row;
  176320. /* debugging check */
  176321. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176322. ptr->mem_buffer == NULL)
  176323. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176324. /* Make the desired part of the virtual array accessible */
  176325. if (start_row < ptr->cur_start_row ||
  176326. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176327. if (! ptr->b_s_open)
  176328. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176329. /* Flush old buffer contents if necessary */
  176330. if (ptr->dirty) {
  176331. do_barray_io(cinfo, ptr, TRUE);
  176332. ptr->dirty = FALSE;
  176333. }
  176334. /* Decide what part of virtual array to access.
  176335. * Algorithm: if target address > current window, assume forward scan,
  176336. * load starting at target address. If target address < current window,
  176337. * assume backward scan, load so that target area is top of window.
  176338. * Note that when switching from forward write to forward read, will have
  176339. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176340. */
  176341. if (start_row > ptr->cur_start_row) {
  176342. ptr->cur_start_row = start_row;
  176343. } else {
  176344. /* use long arithmetic here to avoid overflow & unsigned problems */
  176345. long ltemp;
  176346. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176347. if (ltemp < 0)
  176348. ltemp = 0; /* don't fall off front end of file */
  176349. ptr->cur_start_row = (JDIMENSION) ltemp;
  176350. }
  176351. /* Read in the selected part of the array.
  176352. * During the initial write pass, we will do no actual read
  176353. * because the selected part is all undefined.
  176354. */
  176355. do_barray_io(cinfo, ptr, FALSE);
  176356. }
  176357. /* Ensure the accessed part of the array is defined; prezero if needed.
  176358. * To improve locality of access, we only prezero the part of the array
  176359. * that the caller is about to access, not the entire in-memory array.
  176360. */
  176361. if (ptr->first_undef_row < end_row) {
  176362. if (ptr->first_undef_row < start_row) {
  176363. if (writable) /* writer skipped over a section of array */
  176364. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176365. undef_row = start_row; /* but reader is allowed to read ahead */
  176366. } else {
  176367. undef_row = ptr->first_undef_row;
  176368. }
  176369. if (writable)
  176370. ptr->first_undef_row = end_row;
  176371. if (ptr->pre_zero) {
  176372. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176373. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176374. end_row -= ptr->cur_start_row;
  176375. while (undef_row < end_row) {
  176376. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176377. undef_row++;
  176378. }
  176379. } else {
  176380. if (! writable) /* reader looking at undefined data */
  176381. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176382. }
  176383. }
  176384. /* Flag the buffer dirty if caller will write in it */
  176385. if (writable)
  176386. ptr->dirty = TRUE;
  176387. /* Return address of proper part of the buffer */
  176388. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176389. }
  176390. /*
  176391. * Release all objects belonging to a specified pool.
  176392. */
  176393. METHODDEF(void)
  176394. free_pool (j_common_ptr cinfo, int pool_id)
  176395. {
  176396. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176397. small_pool_ptr shdr_ptr;
  176398. large_pool_ptr lhdr_ptr;
  176399. size_t space_freed;
  176400. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176401. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176402. #ifdef MEM_STATS
  176403. if (cinfo->err->trace_level > 1)
  176404. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176405. #endif
  176406. /* If freeing IMAGE pool, close any virtual arrays first */
  176407. if (pool_id == JPOOL_IMAGE) {
  176408. jvirt_sarray_ptr sptr;
  176409. jvirt_barray_ptr bptr;
  176410. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176411. if (sptr->b_s_open) { /* there may be no backing store */
  176412. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176413. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176414. }
  176415. }
  176416. mem->virt_sarray_list = NULL;
  176417. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176418. if (bptr->b_s_open) { /* there may be no backing store */
  176419. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176420. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176421. }
  176422. }
  176423. mem->virt_barray_list = NULL;
  176424. }
  176425. /* Release large objects */
  176426. lhdr_ptr = mem->large_list[pool_id];
  176427. mem->large_list[pool_id] = NULL;
  176428. while (lhdr_ptr != NULL) {
  176429. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176430. space_freed = lhdr_ptr->hdr.bytes_used +
  176431. lhdr_ptr->hdr.bytes_left +
  176432. SIZEOF(large_pool_hdr);
  176433. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176434. mem->total_space_allocated -= space_freed;
  176435. lhdr_ptr = next_lhdr_ptr;
  176436. }
  176437. /* Release small objects */
  176438. shdr_ptr = mem->small_list[pool_id];
  176439. mem->small_list[pool_id] = NULL;
  176440. while (shdr_ptr != NULL) {
  176441. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176442. space_freed = shdr_ptr->hdr.bytes_used +
  176443. shdr_ptr->hdr.bytes_left +
  176444. SIZEOF(small_pool_hdr);
  176445. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176446. mem->total_space_allocated -= space_freed;
  176447. shdr_ptr = next_shdr_ptr;
  176448. }
  176449. }
  176450. /*
  176451. * Close up shop entirely.
  176452. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176453. */
  176454. METHODDEF(void)
  176455. self_destruct (j_common_ptr cinfo)
  176456. {
  176457. int pool;
  176458. /* Close all backing store, release all memory.
  176459. * Releasing pools in reverse order might help avoid fragmentation
  176460. * with some (brain-damaged) malloc libraries.
  176461. */
  176462. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176463. free_pool(cinfo, pool);
  176464. }
  176465. /* Release the memory manager control block too. */
  176466. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176467. cinfo->mem = NULL; /* ensures I will be called only once */
  176468. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176469. }
  176470. /*
  176471. * Memory manager initialization.
  176472. * When this is called, only the error manager pointer is valid in cinfo!
  176473. */
  176474. GLOBAL(void)
  176475. jinit_memory_mgr (j_common_ptr cinfo)
  176476. {
  176477. my_mem_ptr mem;
  176478. long max_to_use;
  176479. int pool;
  176480. size_t test_mac;
  176481. cinfo->mem = NULL; /* for safety if init fails */
  176482. /* Check for configuration errors.
  176483. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176484. * doesn't reflect any real hardware alignment requirement.
  176485. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176486. * in common if and only if X is a power of 2, ie has only one one-bit.
  176487. * Some compilers may give an "unreachable code" warning here; ignore it.
  176488. */
  176489. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176490. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176491. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176492. * a multiple of SIZEOF(ALIGN_TYPE).
  176493. * Again, an "unreachable code" warning may be ignored here.
  176494. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176495. */
  176496. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176497. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176498. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176499. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176500. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176501. /* Attempt to allocate memory manager's control block */
  176502. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176503. if (mem == NULL) {
  176504. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176505. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176506. }
  176507. /* OK, fill in the method pointers */
  176508. mem->pub.alloc_small = alloc_small;
  176509. mem->pub.alloc_large = alloc_large;
  176510. mem->pub.alloc_sarray = alloc_sarray;
  176511. mem->pub.alloc_barray = alloc_barray;
  176512. mem->pub.request_virt_sarray = request_virt_sarray;
  176513. mem->pub.request_virt_barray = request_virt_barray;
  176514. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176515. mem->pub.access_virt_sarray = access_virt_sarray;
  176516. mem->pub.access_virt_barray = access_virt_barray;
  176517. mem->pub.free_pool = free_pool;
  176518. mem->pub.self_destruct = self_destruct;
  176519. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176520. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176521. /* Initialize working state */
  176522. mem->pub.max_memory_to_use = max_to_use;
  176523. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176524. mem->small_list[pool] = NULL;
  176525. mem->large_list[pool] = NULL;
  176526. }
  176527. mem->virt_sarray_list = NULL;
  176528. mem->virt_barray_list = NULL;
  176529. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176530. /* Declare ourselves open for business */
  176531. cinfo->mem = & mem->pub;
  176532. /* Check for an environment variable JPEGMEM; if found, override the
  176533. * default max_memory setting from jpeg_mem_init. Note that the
  176534. * surrounding application may again override this value.
  176535. * If your system doesn't support getenv(), define NO_GETENV to disable
  176536. * this feature.
  176537. */
  176538. #ifndef NO_GETENV
  176539. { char * memenv;
  176540. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176541. char ch = 'x';
  176542. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176543. if (ch == 'm' || ch == 'M')
  176544. max_to_use *= 1000L;
  176545. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176546. }
  176547. }
  176548. }
  176549. #endif
  176550. }
  176551. /*** End of inlined file: jmemmgr.c ***/
  176552. /*** Start of inlined file: jmemnobs.c ***/
  176553. #define JPEG_INTERNALS
  176554. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176555. extern void * malloc JPP((size_t size));
  176556. extern void free JPP((void *ptr));
  176557. #endif
  176558. /*
  176559. * Memory allocation and freeing are controlled by the regular library
  176560. * routines malloc() and free().
  176561. */
  176562. GLOBAL(void *)
  176563. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176564. {
  176565. return (void *) malloc(sizeofobject);
  176566. }
  176567. GLOBAL(void)
  176568. jpeg_free_small (j_common_ptr , void * object, size_t)
  176569. {
  176570. free(object);
  176571. }
  176572. /*
  176573. * "Large" objects are treated the same as "small" ones.
  176574. * NB: although we include FAR keywords in the routine declarations,
  176575. * this file won't actually work in 80x86 small/medium model; at least,
  176576. * you probably won't be able to process useful-size images in only 64KB.
  176577. */
  176578. GLOBAL(void FAR *)
  176579. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176580. {
  176581. return (void FAR *) malloc(sizeofobject);
  176582. }
  176583. GLOBAL(void)
  176584. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176585. {
  176586. free(object);
  176587. }
  176588. /*
  176589. * This routine computes the total memory space available for allocation.
  176590. * Here we always say, "we got all you want bud!"
  176591. */
  176592. GLOBAL(long)
  176593. jpeg_mem_available (j_common_ptr, long,
  176594. long max_bytes_needed, long)
  176595. {
  176596. return max_bytes_needed;
  176597. }
  176598. /*
  176599. * Backing store (temporary file) management.
  176600. * Since jpeg_mem_available always promised the moon,
  176601. * this should never be called and we can just error out.
  176602. */
  176603. GLOBAL(void)
  176604. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176605. long )
  176606. {
  176607. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176608. }
  176609. /*
  176610. * These routines take care of any system-dependent initialization and
  176611. * cleanup required. Here, there isn't any.
  176612. */
  176613. GLOBAL(long)
  176614. jpeg_mem_init (j_common_ptr)
  176615. {
  176616. return 0; /* just set max_memory_to_use to 0 */
  176617. }
  176618. GLOBAL(void)
  176619. jpeg_mem_term (j_common_ptr)
  176620. {
  176621. /* no work */
  176622. }
  176623. /*** End of inlined file: jmemnobs.c ***/
  176624. /*** Start of inlined file: jquant1.c ***/
  176625. #define JPEG_INTERNALS
  176626. #ifdef QUANT_1PASS_SUPPORTED
  176627. /*
  176628. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176629. * high quality, colormapped output capability. A 2-pass quantizer usually
  176630. * gives better visual quality; however, for quantized grayscale output this
  176631. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176632. * quantizer, though you can turn it off if you really want to.
  176633. *
  176634. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176635. * image. We use a map consisting of all combinations of Ncolors[i] color
  176636. * values for the i'th component. The Ncolors[] values are chosen so that
  176637. * their product, the total number of colors, is no more than that requested.
  176638. * (In most cases, the product will be somewhat less.)
  176639. *
  176640. * Since the colormap is orthogonal, the representative value for each color
  176641. * component can be determined without considering the other components;
  176642. * then these indexes can be combined into a colormap index by a standard
  176643. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176644. * can be precalculated and stored in the lookup table colorindex[].
  176645. * colorindex[i][j] maps pixel value j in component i to the nearest
  176646. * representative value (grid plane) for that component; this index is
  176647. * multiplied by the array stride for component i, so that the
  176648. * index of the colormap entry closest to a given pixel value is just
  176649. * sum( colorindex[component-number][pixel-component-value] )
  176650. * Aside from being fast, this scheme allows for variable spacing between
  176651. * representative values with no additional lookup cost.
  176652. *
  176653. * If gamma correction has been applied in color conversion, it might be wise
  176654. * to adjust the color grid spacing so that the representative colors are
  176655. * equidistant in linear space. At this writing, gamma correction is not
  176656. * implemented by jdcolor, so nothing is done here.
  176657. */
  176658. /* Declarations for ordered dithering.
  176659. *
  176660. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176661. * dithering is described in many references, for instance Dale Schumacher's
  176662. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  176663. * In place of Schumacher's comparisons against a "threshold" value, we add a
  176664. * "dither" value to the input pixel and then round the result to the nearest
  176665. * output value. The dither value is equivalent to (0.5 - threshold) times
  176666. * the distance between output values. For ordered dithering, we assume that
  176667. * the output colors are equally spaced; if not, results will probably be
  176668. * worse, since the dither may be too much or too little at a given point.
  176669. *
  176670. * The normal calculation would be to form pixel value + dither, range-limit
  176671. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  176672. * We can skip the separate range-limiting step by extending the colorindex
  176673. * table in both directions.
  176674. */
  176675. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  176676. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  176677. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  176678. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  176679. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  176680. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  176681. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  176682. /* Bayer's order-4 dither array. Generated by the code given in
  176683. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  176684. * The values in this array must range from 0 to ODITHER_CELLS-1.
  176685. */
  176686. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  176687. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  176688. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  176689. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  176690. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  176691. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  176692. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  176693. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  176694. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  176695. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  176696. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  176697. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  176698. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  176699. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  176700. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  176701. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  176702. };
  176703. /* Declarations for Floyd-Steinberg dithering.
  176704. *
  176705. * Errors are accumulated into the array fserrors[], at a resolution of
  176706. * 1/16th of a pixel count. The error at a given pixel is propagated
  176707. * to its not-yet-processed neighbors using the standard F-S fractions,
  176708. * ... (here) 7/16
  176709. * 3/16 5/16 1/16
  176710. * We work left-to-right on even rows, right-to-left on odd rows.
  176711. *
  176712. * We can get away with a single array (holding one row's worth of errors)
  176713. * by using it to store the current row's errors at pixel columns not yet
  176714. * processed, but the next row's errors at columns already processed. We
  176715. * need only a few extra variables to hold the errors immediately around the
  176716. * current column. (If we are lucky, those variables are in registers, but
  176717. * even if not, they're probably cheaper to access than array elements are.)
  176718. *
  176719. * The fserrors[] array is indexed [component#][position].
  176720. * We provide (#columns + 2) entries per component; the extra entry at each
  176721. * end saves us from special-casing the first and last pixels.
  176722. *
  176723. * Note: on a wide image, we might not have enough room in a PC's near data
  176724. * segment to hold the error array; so it is allocated with alloc_large.
  176725. */
  176726. #if BITS_IN_JSAMPLE == 8
  176727. typedef INT16 FSERROR; /* 16 bits should be enough */
  176728. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  176729. #else
  176730. typedef INT32 FSERROR; /* may need more than 16 bits */
  176731. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  176732. #endif
  176733. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  176734. /* Private subobject */
  176735. #define MAX_Q_COMPS 4 /* max components I can handle */
  176736. typedef struct {
  176737. struct jpeg_color_quantizer pub; /* public fields */
  176738. /* Initially allocated colormap is saved here */
  176739. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  176740. int sv_actual; /* number of entries in use */
  176741. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  176742. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  176743. * premultiplied as described above. Since colormap indexes must fit into
  176744. * JSAMPLEs, the entries of this array will too.
  176745. */
  176746. boolean is_padded; /* is the colorindex padded for odither? */
  176747. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  176748. /* Variables for ordered dithering */
  176749. int row_index; /* cur row's vertical index in dither matrix */
  176750. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  176751. /* Variables for Floyd-Steinberg dithering */
  176752. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  176753. boolean on_odd_row; /* flag to remember which row we are on */
  176754. } my_cquantizer;
  176755. typedef my_cquantizer * my_cquantize_ptr;
  176756. /*
  176757. * Policy-making subroutines for create_colormap and create_colorindex.
  176758. * These routines determine the colormap to be used. The rest of the module
  176759. * only assumes that the colormap is orthogonal.
  176760. *
  176761. * * select_ncolors decides how to divvy up the available colors
  176762. * among the components.
  176763. * * output_value defines the set of representative values for a component.
  176764. * * largest_input_value defines the mapping from input values to
  176765. * representative values for a component.
  176766. * Note that the latter two routines may impose different policies for
  176767. * different components, though this is not currently done.
  176768. */
  176769. LOCAL(int)
  176770. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  176771. /* Determine allocation of desired colors to components, */
  176772. /* and fill in Ncolors[] array to indicate choice. */
  176773. /* Return value is total number of colors (product of Ncolors[] values). */
  176774. {
  176775. int nc = cinfo->out_color_components; /* number of color components */
  176776. int max_colors = cinfo->desired_number_of_colors;
  176777. int total_colors, iroot, i, j;
  176778. boolean changed;
  176779. long temp;
  176780. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  176781. /* We can allocate at least the nc'th root of max_colors per component. */
  176782. /* Compute floor(nc'th root of max_colors). */
  176783. iroot = 1;
  176784. do {
  176785. iroot++;
  176786. temp = iroot; /* set temp = iroot ** nc */
  176787. for (i = 1; i < nc; i++)
  176788. temp *= iroot;
  176789. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  176790. iroot--; /* now iroot = floor(root) */
  176791. /* Must have at least 2 color values per component */
  176792. if (iroot < 2)
  176793. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  176794. /* Initialize to iroot color values for each component */
  176795. total_colors = 1;
  176796. for (i = 0; i < nc; i++) {
  176797. Ncolors[i] = iroot;
  176798. total_colors *= iroot;
  176799. }
  176800. /* We may be able to increment the count for one or more components without
  176801. * exceeding max_colors, though we know not all can be incremented.
  176802. * Sometimes, the first component can be incremented more than once!
  176803. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  176804. * In RGB colorspace, try to increment G first, then R, then B.
  176805. */
  176806. do {
  176807. changed = FALSE;
  176808. for (i = 0; i < nc; i++) {
  176809. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  176810. /* calculate new total_colors if Ncolors[j] is incremented */
  176811. temp = total_colors / Ncolors[j];
  176812. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  176813. if (temp > (long) max_colors)
  176814. break; /* won't fit, done with this pass */
  176815. Ncolors[j]++; /* OK, apply the increment */
  176816. total_colors = (int) temp;
  176817. changed = TRUE;
  176818. }
  176819. } while (changed);
  176820. return total_colors;
  176821. }
  176822. LOCAL(int)
  176823. output_value (j_decompress_ptr, int, int j, int maxj)
  176824. /* Return j'th output value, where j will range from 0 to maxj */
  176825. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  176826. {
  176827. /* We always provide values 0 and MAXJSAMPLE for each component;
  176828. * any additional values are equally spaced between these limits.
  176829. * (Forcing the upper and lower values to the limits ensures that
  176830. * dithering can't produce a color outside the selected gamut.)
  176831. */
  176832. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  176833. }
  176834. LOCAL(int)
  176835. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  176836. /* Return largest input value that should map to j'th output value */
  176837. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  176838. {
  176839. /* Breakpoints are halfway between values returned by output_value */
  176840. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  176841. }
  176842. /*
  176843. * Create the colormap.
  176844. */
  176845. LOCAL(void)
  176846. create_colormap (j_decompress_ptr cinfo)
  176847. {
  176848. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176849. JSAMPARRAY colormap; /* Created colormap */
  176850. int total_colors; /* Number of distinct output colors */
  176851. int i,j,k, nci, blksize, blkdist, ptr, val;
  176852. /* Select number of colors for each component */
  176853. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  176854. /* Report selected color counts */
  176855. if (cinfo->out_color_components == 3)
  176856. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  176857. total_colors, cquantize->Ncolors[0],
  176858. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  176859. else
  176860. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  176861. /* Allocate and fill in the colormap. */
  176862. /* The colors are ordered in the map in standard row-major order, */
  176863. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  176864. colormap = (*cinfo->mem->alloc_sarray)
  176865. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176866. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  176867. /* blksize is number of adjacent repeated entries for a component */
  176868. /* blkdist is distance between groups of identical entries for a component */
  176869. blkdist = total_colors;
  176870. for (i = 0; i < cinfo->out_color_components; i++) {
  176871. /* fill in colormap entries for i'th color component */
  176872. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176873. blksize = blkdist / nci;
  176874. for (j = 0; j < nci; j++) {
  176875. /* Compute j'th output value (out of nci) for component */
  176876. val = output_value(cinfo, i, j, nci-1);
  176877. /* Fill in all colormap entries that have this value of this component */
  176878. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  176879. /* fill in blksize entries beginning at ptr */
  176880. for (k = 0; k < blksize; k++)
  176881. colormap[i][ptr+k] = (JSAMPLE) val;
  176882. }
  176883. }
  176884. blkdist = blksize; /* blksize of this color is blkdist of next */
  176885. }
  176886. /* Save the colormap in private storage,
  176887. * where it will survive color quantization mode changes.
  176888. */
  176889. cquantize->sv_colormap = colormap;
  176890. cquantize->sv_actual = total_colors;
  176891. }
  176892. /*
  176893. * Create the color index table.
  176894. */
  176895. LOCAL(void)
  176896. create_colorindex (j_decompress_ptr cinfo)
  176897. {
  176898. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176899. JSAMPROW indexptr;
  176900. int i,j,k, nci, blksize, val, pad;
  176901. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  176902. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  176903. * This is not necessary in the other dithering modes. However, we
  176904. * flag whether it was done in case user changes dithering mode.
  176905. */
  176906. if (cinfo->dither_mode == JDITHER_ORDERED) {
  176907. pad = MAXJSAMPLE*2;
  176908. cquantize->is_padded = TRUE;
  176909. } else {
  176910. pad = 0;
  176911. cquantize->is_padded = FALSE;
  176912. }
  176913. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  176914. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176915. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  176916. (JDIMENSION) cinfo->out_color_components);
  176917. /* blksize is number of adjacent repeated entries for a component */
  176918. blksize = cquantize->sv_actual;
  176919. for (i = 0; i < cinfo->out_color_components; i++) {
  176920. /* fill in colorindex entries for i'th color component */
  176921. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176922. blksize = blksize / nci;
  176923. /* adjust colorindex pointers to provide padding at negative indexes. */
  176924. if (pad)
  176925. cquantize->colorindex[i] += MAXJSAMPLE;
  176926. /* in loop, val = index of current output value, */
  176927. /* and k = largest j that maps to current val */
  176928. indexptr = cquantize->colorindex[i];
  176929. val = 0;
  176930. k = largest_input_value(cinfo, i, 0, nci-1);
  176931. for (j = 0; j <= MAXJSAMPLE; j++) {
  176932. while (j > k) /* advance val if past boundary */
  176933. k = largest_input_value(cinfo, i, ++val, nci-1);
  176934. /* premultiply so that no multiplication needed in main processing */
  176935. indexptr[j] = (JSAMPLE) (val * blksize);
  176936. }
  176937. /* Pad at both ends if necessary */
  176938. if (pad)
  176939. for (j = 1; j <= MAXJSAMPLE; j++) {
  176940. indexptr[-j] = indexptr[0];
  176941. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  176942. }
  176943. }
  176944. }
  176945. /*
  176946. * Create an ordered-dither array for a component having ncolors
  176947. * distinct output values.
  176948. */
  176949. LOCAL(ODITHER_MATRIX_PTR)
  176950. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  176951. {
  176952. ODITHER_MATRIX_PTR odither;
  176953. int j,k;
  176954. INT32 num,den;
  176955. odither = (ODITHER_MATRIX_PTR)
  176956. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  176957. SIZEOF(ODITHER_MATRIX));
  176958. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  176959. * Hence the dither value for the matrix cell with fill order f
  176960. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  176961. * On 16-bit-int machine, be careful to avoid overflow.
  176962. */
  176963. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  176964. for (j = 0; j < ODITHER_SIZE; j++) {
  176965. for (k = 0; k < ODITHER_SIZE; k++) {
  176966. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  176967. * MAXJSAMPLE;
  176968. /* Ensure round towards zero despite C's lack of consistency
  176969. * about rounding negative values in integer division...
  176970. */
  176971. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  176972. }
  176973. }
  176974. return odither;
  176975. }
  176976. /*
  176977. * Create the ordered-dither tables.
  176978. * Components having the same number of representative colors may
  176979. * share a dither table.
  176980. */
  176981. LOCAL(void)
  176982. create_odither_tables (j_decompress_ptr cinfo)
  176983. {
  176984. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  176985. ODITHER_MATRIX_PTR odither;
  176986. int i, j, nci;
  176987. for (i = 0; i < cinfo->out_color_components; i++) {
  176988. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  176989. odither = NULL; /* search for matching prior component */
  176990. for (j = 0; j < i; j++) {
  176991. if (nci == cquantize->Ncolors[j]) {
  176992. odither = cquantize->odither[j];
  176993. break;
  176994. }
  176995. }
  176996. if (odither == NULL) /* need a new table? */
  176997. odither = make_odither_array(cinfo, nci);
  176998. cquantize->odither[i] = odither;
  176999. }
  177000. }
  177001. /*
  177002. * Map some rows of pixels to the output colormapped representation.
  177003. */
  177004. METHODDEF(void)
  177005. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177006. JSAMPARRAY output_buf, int num_rows)
  177007. /* General case, no dithering */
  177008. {
  177009. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177010. JSAMPARRAY colorindex = cquantize->colorindex;
  177011. register int pixcode, ci;
  177012. register JSAMPROW ptrin, ptrout;
  177013. int row;
  177014. JDIMENSION col;
  177015. JDIMENSION width = cinfo->output_width;
  177016. register int nc = cinfo->out_color_components;
  177017. for (row = 0; row < num_rows; row++) {
  177018. ptrin = input_buf[row];
  177019. ptrout = output_buf[row];
  177020. for (col = width; col > 0; col--) {
  177021. pixcode = 0;
  177022. for (ci = 0; ci < nc; ci++) {
  177023. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177024. }
  177025. *ptrout++ = (JSAMPLE) pixcode;
  177026. }
  177027. }
  177028. }
  177029. METHODDEF(void)
  177030. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177031. JSAMPARRAY output_buf, int num_rows)
  177032. /* Fast path for out_color_components==3, no dithering */
  177033. {
  177034. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177035. register int pixcode;
  177036. register JSAMPROW ptrin, ptrout;
  177037. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177038. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177039. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177040. int row;
  177041. JDIMENSION col;
  177042. JDIMENSION width = cinfo->output_width;
  177043. for (row = 0; row < num_rows; row++) {
  177044. ptrin = input_buf[row];
  177045. ptrout = output_buf[row];
  177046. for (col = width; col > 0; col--) {
  177047. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177048. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177049. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177050. *ptrout++ = (JSAMPLE) pixcode;
  177051. }
  177052. }
  177053. }
  177054. METHODDEF(void)
  177055. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177056. JSAMPARRAY output_buf, int num_rows)
  177057. /* General case, with ordered dithering */
  177058. {
  177059. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177060. register JSAMPROW input_ptr;
  177061. register JSAMPROW output_ptr;
  177062. JSAMPROW colorindex_ci;
  177063. int * dither; /* points to active row of dither matrix */
  177064. int row_index, col_index; /* current indexes into dither matrix */
  177065. int nc = cinfo->out_color_components;
  177066. int ci;
  177067. int row;
  177068. JDIMENSION col;
  177069. JDIMENSION width = cinfo->output_width;
  177070. for (row = 0; row < num_rows; row++) {
  177071. /* Initialize output values to 0 so can process components separately */
  177072. jzero_far((void FAR *) output_buf[row],
  177073. (size_t) (width * SIZEOF(JSAMPLE)));
  177074. row_index = cquantize->row_index;
  177075. for (ci = 0; ci < nc; ci++) {
  177076. input_ptr = input_buf[row] + ci;
  177077. output_ptr = output_buf[row];
  177078. colorindex_ci = cquantize->colorindex[ci];
  177079. dither = cquantize->odither[ci][row_index];
  177080. col_index = 0;
  177081. for (col = width; col > 0; col--) {
  177082. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177083. * select output value, accumulate into output code for this pixel.
  177084. * Range-limiting need not be done explicitly, as we have extended
  177085. * the colorindex table to produce the right answers for out-of-range
  177086. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177087. * required amount of padding.
  177088. */
  177089. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177090. input_ptr += nc;
  177091. output_ptr++;
  177092. col_index = (col_index + 1) & ODITHER_MASK;
  177093. }
  177094. }
  177095. /* Advance row index for next row */
  177096. row_index = (row_index + 1) & ODITHER_MASK;
  177097. cquantize->row_index = row_index;
  177098. }
  177099. }
  177100. METHODDEF(void)
  177101. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177102. JSAMPARRAY output_buf, int num_rows)
  177103. /* Fast path for out_color_components==3, with ordered dithering */
  177104. {
  177105. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177106. register int pixcode;
  177107. register JSAMPROW input_ptr;
  177108. register JSAMPROW output_ptr;
  177109. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177110. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177111. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177112. int * dither0; /* points to active row of dither matrix */
  177113. int * dither1;
  177114. int * dither2;
  177115. int row_index, col_index; /* current indexes into dither matrix */
  177116. int row;
  177117. JDIMENSION col;
  177118. JDIMENSION width = cinfo->output_width;
  177119. for (row = 0; row < num_rows; row++) {
  177120. row_index = cquantize->row_index;
  177121. input_ptr = input_buf[row];
  177122. output_ptr = output_buf[row];
  177123. dither0 = cquantize->odither[0][row_index];
  177124. dither1 = cquantize->odither[1][row_index];
  177125. dither2 = cquantize->odither[2][row_index];
  177126. col_index = 0;
  177127. for (col = width; col > 0; col--) {
  177128. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177129. dither0[col_index]]);
  177130. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177131. dither1[col_index]]);
  177132. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177133. dither2[col_index]]);
  177134. *output_ptr++ = (JSAMPLE) pixcode;
  177135. col_index = (col_index + 1) & ODITHER_MASK;
  177136. }
  177137. row_index = (row_index + 1) & ODITHER_MASK;
  177138. cquantize->row_index = row_index;
  177139. }
  177140. }
  177141. METHODDEF(void)
  177142. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177143. JSAMPARRAY output_buf, int num_rows)
  177144. /* General case, with Floyd-Steinberg dithering */
  177145. {
  177146. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177147. register LOCFSERROR cur; /* current error or pixel value */
  177148. LOCFSERROR belowerr; /* error for pixel below cur */
  177149. LOCFSERROR bpreverr; /* error for below/prev col */
  177150. LOCFSERROR bnexterr; /* error for below/next col */
  177151. LOCFSERROR delta;
  177152. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177153. register JSAMPROW input_ptr;
  177154. register JSAMPROW output_ptr;
  177155. JSAMPROW colorindex_ci;
  177156. JSAMPROW colormap_ci;
  177157. int pixcode;
  177158. int nc = cinfo->out_color_components;
  177159. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177160. int dirnc; /* dir * nc */
  177161. int ci;
  177162. int row;
  177163. JDIMENSION col;
  177164. JDIMENSION width = cinfo->output_width;
  177165. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177166. SHIFT_TEMPS
  177167. for (row = 0; row < num_rows; row++) {
  177168. /* Initialize output values to 0 so can process components separately */
  177169. jzero_far((void FAR *) output_buf[row],
  177170. (size_t) (width * SIZEOF(JSAMPLE)));
  177171. for (ci = 0; ci < nc; ci++) {
  177172. input_ptr = input_buf[row] + ci;
  177173. output_ptr = output_buf[row];
  177174. if (cquantize->on_odd_row) {
  177175. /* work right to left in this row */
  177176. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177177. output_ptr += width-1;
  177178. dir = -1;
  177179. dirnc = -nc;
  177180. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177181. } else {
  177182. /* work left to right in this row */
  177183. dir = 1;
  177184. dirnc = nc;
  177185. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177186. }
  177187. colorindex_ci = cquantize->colorindex[ci];
  177188. colormap_ci = cquantize->sv_colormap[ci];
  177189. /* Preset error values: no error propagated to first pixel from left */
  177190. cur = 0;
  177191. /* and no error propagated to row below yet */
  177192. belowerr = bpreverr = 0;
  177193. for (col = width; col > 0; col--) {
  177194. /* cur holds the error propagated from the previous pixel on the
  177195. * current line. Add the error propagated from the previous line
  177196. * to form the complete error correction term for this pixel, and
  177197. * round the error term (which is expressed * 16) to an integer.
  177198. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177199. * for either sign of the error value.
  177200. * Note: errorptr points to *previous* column's array entry.
  177201. */
  177202. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177203. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177204. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177205. * of the range_limit array.
  177206. */
  177207. cur += GETJSAMPLE(*input_ptr);
  177208. cur = GETJSAMPLE(range_limit[cur]);
  177209. /* Select output value, accumulate into output code for this pixel */
  177210. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177211. *output_ptr += (JSAMPLE) pixcode;
  177212. /* Compute actual representation error at this pixel */
  177213. /* Note: we can do this even though we don't have the final */
  177214. /* pixel code, because the colormap is orthogonal. */
  177215. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177216. /* Compute error fractions to be propagated to adjacent pixels.
  177217. * Add these into the running sums, and simultaneously shift the
  177218. * next-line error sums left by 1 column.
  177219. */
  177220. bnexterr = cur;
  177221. delta = cur * 2;
  177222. cur += delta; /* form error * 3 */
  177223. errorptr[0] = (FSERROR) (bpreverr + cur);
  177224. cur += delta; /* form error * 5 */
  177225. bpreverr = belowerr + cur;
  177226. belowerr = bnexterr;
  177227. cur += delta; /* form error * 7 */
  177228. /* At this point cur contains the 7/16 error value to be propagated
  177229. * to the next pixel on the current line, and all the errors for the
  177230. * next line have been shifted over. We are therefore ready to move on.
  177231. */
  177232. input_ptr += dirnc; /* advance input ptr to next column */
  177233. output_ptr += dir; /* advance output ptr to next column */
  177234. errorptr += dir; /* advance errorptr to current column */
  177235. }
  177236. /* Post-loop cleanup: we must unload the final error value into the
  177237. * final fserrors[] entry. Note we need not unload belowerr because
  177238. * it is for the dummy column before or after the actual array.
  177239. */
  177240. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177241. }
  177242. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177243. }
  177244. }
  177245. /*
  177246. * Allocate workspace for Floyd-Steinberg errors.
  177247. */
  177248. LOCAL(void)
  177249. alloc_fs_workspace (j_decompress_ptr cinfo)
  177250. {
  177251. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177252. size_t arraysize;
  177253. int i;
  177254. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177255. for (i = 0; i < cinfo->out_color_components; i++) {
  177256. cquantize->fserrors[i] = (FSERRPTR)
  177257. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177258. }
  177259. }
  177260. /*
  177261. * Initialize for one-pass color quantization.
  177262. */
  177263. METHODDEF(void)
  177264. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177265. {
  177266. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177267. size_t arraysize;
  177268. int i;
  177269. /* Install my colormap. */
  177270. cinfo->colormap = cquantize->sv_colormap;
  177271. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177272. /* Initialize for desired dithering mode. */
  177273. switch (cinfo->dither_mode) {
  177274. case JDITHER_NONE:
  177275. if (cinfo->out_color_components == 3)
  177276. cquantize->pub.color_quantize = color_quantize3;
  177277. else
  177278. cquantize->pub.color_quantize = color_quantize;
  177279. break;
  177280. case JDITHER_ORDERED:
  177281. if (cinfo->out_color_components == 3)
  177282. cquantize->pub.color_quantize = quantize3_ord_dither;
  177283. else
  177284. cquantize->pub.color_quantize = quantize_ord_dither;
  177285. cquantize->row_index = 0; /* initialize state for ordered dither */
  177286. /* If user changed to ordered dither from another mode,
  177287. * we must recreate the color index table with padding.
  177288. * This will cost extra space, but probably isn't very likely.
  177289. */
  177290. if (! cquantize->is_padded)
  177291. create_colorindex(cinfo);
  177292. /* Create ordered-dither tables if we didn't already. */
  177293. if (cquantize->odither[0] == NULL)
  177294. create_odither_tables(cinfo);
  177295. break;
  177296. case JDITHER_FS:
  177297. cquantize->pub.color_quantize = quantize_fs_dither;
  177298. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177299. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177300. if (cquantize->fserrors[0] == NULL)
  177301. alloc_fs_workspace(cinfo);
  177302. /* Initialize the propagated errors to zero. */
  177303. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177304. for (i = 0; i < cinfo->out_color_components; i++)
  177305. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177306. break;
  177307. default:
  177308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177309. break;
  177310. }
  177311. }
  177312. /*
  177313. * Finish up at the end of the pass.
  177314. */
  177315. METHODDEF(void)
  177316. finish_pass_1_quant (j_decompress_ptr)
  177317. {
  177318. /* no work in 1-pass case */
  177319. }
  177320. /*
  177321. * Switch to a new external colormap between output passes.
  177322. * Shouldn't get to this module!
  177323. */
  177324. METHODDEF(void)
  177325. new_color_map_1_quant (j_decompress_ptr cinfo)
  177326. {
  177327. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177328. }
  177329. /*
  177330. * Module initialization routine for 1-pass color quantization.
  177331. */
  177332. GLOBAL(void)
  177333. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177334. {
  177335. my_cquantize_ptr cquantize;
  177336. cquantize = (my_cquantize_ptr)
  177337. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177338. SIZEOF(my_cquantizer));
  177339. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177340. cquantize->pub.start_pass = start_pass_1_quant;
  177341. cquantize->pub.finish_pass = finish_pass_1_quant;
  177342. cquantize->pub.new_color_map = new_color_map_1_quant;
  177343. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177344. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177345. /* Make sure my internal arrays won't overflow */
  177346. if (cinfo->out_color_components > MAX_Q_COMPS)
  177347. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177348. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177349. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177350. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177351. /* Create the colormap and color index table. */
  177352. create_colormap(cinfo);
  177353. create_colorindex(cinfo);
  177354. /* Allocate Floyd-Steinberg workspace now if requested.
  177355. * We do this now since it is FAR storage and may affect the memory
  177356. * manager's space calculations. If the user changes to FS dither
  177357. * mode in a later pass, we will allocate the space then, and will
  177358. * possibly overrun the max_memory_to_use setting.
  177359. */
  177360. if (cinfo->dither_mode == JDITHER_FS)
  177361. alloc_fs_workspace(cinfo);
  177362. }
  177363. #endif /* QUANT_1PASS_SUPPORTED */
  177364. /*** End of inlined file: jquant1.c ***/
  177365. /*** Start of inlined file: jquant2.c ***/
  177366. #define JPEG_INTERNALS
  177367. #ifdef QUANT_2PASS_SUPPORTED
  177368. /*
  177369. * This module implements the well-known Heckbert paradigm for color
  177370. * quantization. Most of the ideas used here can be traced back to
  177371. * Heckbert's seminal paper
  177372. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177373. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177374. *
  177375. * In the first pass over the image, we accumulate a histogram showing the
  177376. * usage count of each possible color. To keep the histogram to a reasonable
  177377. * size, we reduce the precision of the input; typical practice is to retain
  177378. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177379. * in the same histogram cell.
  177380. *
  177381. * Next, the color-selection step begins with a box representing the whole
  177382. * color space, and repeatedly splits the "largest" remaining box until we
  177383. * have as many boxes as desired colors. Then the mean color in each
  177384. * remaining box becomes one of the possible output colors.
  177385. *
  177386. * The second pass over the image maps each input pixel to the closest output
  177387. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177388. * This mapping is logically trivial, but making it go fast enough requires
  177389. * considerable care.
  177390. *
  177391. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177392. * the "largest" box and deciding where to cut it. The particular policies
  177393. * used here have proved out well in experimental comparisons, but better ones
  177394. * may yet be found.
  177395. *
  177396. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177397. * space, processing the raw upsampled data without a color conversion step.
  177398. * This allowed the color conversion math to be done only once per colormap
  177399. * entry, not once per pixel. However, that optimization precluded other
  177400. * useful optimizations (such as merging color conversion with upsampling)
  177401. * and it also interfered with desired capabilities such as quantizing to an
  177402. * externally-supplied colormap. We have therefore abandoned that approach.
  177403. * The present code works in the post-conversion color space, typically RGB.
  177404. *
  177405. * To improve the visual quality of the results, we actually work in scaled
  177406. * RGB space, giving G distances more weight than R, and R in turn more than
  177407. * B. To do everything in integer math, we must use integer scale factors.
  177408. * The 2/3/1 scale factors used here correspond loosely to the relative
  177409. * weights of the colors in the NTSC grayscale equation.
  177410. * If you want to use this code to quantize a non-RGB color space, you'll
  177411. * probably need to change these scale factors.
  177412. */
  177413. #define R_SCALE 2 /* scale R distances by this much */
  177414. #define G_SCALE 3 /* scale G distances by this much */
  177415. #define B_SCALE 1 /* and B by this much */
  177416. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177417. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177418. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177419. * you'll get compile errors until you extend this logic. In that case
  177420. * you'll probably want to tweak the histogram sizes too.
  177421. */
  177422. #if RGB_RED == 0
  177423. #define C0_SCALE R_SCALE
  177424. #endif
  177425. #if RGB_BLUE == 0
  177426. #define C0_SCALE B_SCALE
  177427. #endif
  177428. #if RGB_GREEN == 1
  177429. #define C1_SCALE G_SCALE
  177430. #endif
  177431. #if RGB_RED == 2
  177432. #define C2_SCALE R_SCALE
  177433. #endif
  177434. #if RGB_BLUE == 2
  177435. #define C2_SCALE B_SCALE
  177436. #endif
  177437. /*
  177438. * First we have the histogram data structure and routines for creating it.
  177439. *
  177440. * The number of bits of precision can be adjusted by changing these symbols.
  177441. * We recommend keeping 6 bits for G and 5 each for R and B.
  177442. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177443. * better results; if you are short of memory, 5 bits all around will save
  177444. * some space but degrade the results.
  177445. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177446. * (preferably unsigned long) for each cell. In practice this is overkill;
  177447. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177448. * and clamping those that do overflow to the maximum value will give close-
  177449. * enough results. This reduces the recommended histogram size from 256Kb
  177450. * to 128Kb, which is a useful savings on PC-class machines.
  177451. * (In the second pass the histogram space is re-used for pixel mapping data;
  177452. * in that capacity, each cell must be able to store zero to the number of
  177453. * desired colors. 16 bits/cell is plenty for that too.)
  177454. * Since the JPEG code is intended to run in small memory model on 80x86
  177455. * machines, we can't just allocate the histogram in one chunk. Instead
  177456. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177457. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177458. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177459. * on 80x86 machines, the pointer row is in near memory but the actual
  177460. * arrays are in far memory (same arrangement as we use for image arrays).
  177461. */
  177462. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177463. /* These will do the right thing for either R,G,B or B,G,R color order,
  177464. * but you may not like the results for other color orders.
  177465. */
  177466. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177467. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177468. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177469. /* Number of elements along histogram axes. */
  177470. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177471. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177472. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177473. /* These are the amounts to shift an input value to get a histogram index. */
  177474. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177475. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177476. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177477. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177478. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177479. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177480. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177481. typedef hist2d * hist3d; /* type for top-level pointer */
  177482. /* Declarations for Floyd-Steinberg dithering.
  177483. *
  177484. * Errors are accumulated into the array fserrors[], at a resolution of
  177485. * 1/16th of a pixel count. The error at a given pixel is propagated
  177486. * to its not-yet-processed neighbors using the standard F-S fractions,
  177487. * ... (here) 7/16
  177488. * 3/16 5/16 1/16
  177489. * We work left-to-right on even rows, right-to-left on odd rows.
  177490. *
  177491. * We can get away with a single array (holding one row's worth of errors)
  177492. * by using it to store the current row's errors at pixel columns not yet
  177493. * processed, but the next row's errors at columns already processed. We
  177494. * need only a few extra variables to hold the errors immediately around the
  177495. * current column. (If we are lucky, those variables are in registers, but
  177496. * even if not, they're probably cheaper to access than array elements are.)
  177497. *
  177498. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177499. * each end saves us from special-casing the first and last pixels.
  177500. * Each entry is three values long, one value for each color component.
  177501. *
  177502. * Note: on a wide image, we might not have enough room in a PC's near data
  177503. * segment to hold the error array; so it is allocated with alloc_large.
  177504. */
  177505. #if BITS_IN_JSAMPLE == 8
  177506. typedef INT16 FSERROR; /* 16 bits should be enough */
  177507. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177508. #else
  177509. typedef INT32 FSERROR; /* may need more than 16 bits */
  177510. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177511. #endif
  177512. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177513. /* Private subobject */
  177514. typedef struct {
  177515. struct jpeg_color_quantizer pub; /* public fields */
  177516. /* Space for the eventually created colormap is stashed here */
  177517. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177518. int desired; /* desired # of colors = size of colormap */
  177519. /* Variables for accumulating image statistics */
  177520. hist3d histogram; /* pointer to the histogram */
  177521. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177522. /* Variables for Floyd-Steinberg dithering */
  177523. FSERRPTR fserrors; /* accumulated errors */
  177524. boolean on_odd_row; /* flag to remember which row we are on */
  177525. int * error_limiter; /* table for clamping the applied error */
  177526. } my_cquantizer2;
  177527. typedef my_cquantizer2 * my_cquantize_ptr2;
  177528. /*
  177529. * Prescan some rows of pixels.
  177530. * In this module the prescan simply updates the histogram, which has been
  177531. * initialized to zeroes by start_pass.
  177532. * An output_buf parameter is required by the method signature, but no data
  177533. * is actually output (in fact the buffer controller is probably passing a
  177534. * NULL pointer).
  177535. */
  177536. METHODDEF(void)
  177537. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177538. JSAMPARRAY, int num_rows)
  177539. {
  177540. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177541. register JSAMPROW ptr;
  177542. register histptr histp;
  177543. register hist3d histogram = cquantize->histogram;
  177544. int row;
  177545. JDIMENSION col;
  177546. JDIMENSION width = cinfo->output_width;
  177547. for (row = 0; row < num_rows; row++) {
  177548. ptr = input_buf[row];
  177549. for (col = width; col > 0; col--) {
  177550. /* get pixel value and index into the histogram */
  177551. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177552. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177553. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177554. /* increment, check for overflow and undo increment if so. */
  177555. if (++(*histp) <= 0)
  177556. (*histp)--;
  177557. ptr += 3;
  177558. }
  177559. }
  177560. }
  177561. /*
  177562. * Next we have the really interesting routines: selection of a colormap
  177563. * given the completed histogram.
  177564. * These routines work with a list of "boxes", each representing a rectangular
  177565. * subset of the input color space (to histogram precision).
  177566. */
  177567. typedef struct {
  177568. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177569. int c0min, c0max;
  177570. int c1min, c1max;
  177571. int c2min, c2max;
  177572. /* The volume (actually 2-norm) of the box */
  177573. INT32 volume;
  177574. /* The number of nonzero histogram cells within this box */
  177575. long colorcount;
  177576. } box;
  177577. typedef box * boxptr;
  177578. LOCAL(boxptr)
  177579. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177580. /* Find the splittable box with the largest color population */
  177581. /* Returns NULL if no splittable boxes remain */
  177582. {
  177583. register boxptr boxp;
  177584. register int i;
  177585. register long maxc = 0;
  177586. boxptr which = NULL;
  177587. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177588. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177589. which = boxp;
  177590. maxc = boxp->colorcount;
  177591. }
  177592. }
  177593. return which;
  177594. }
  177595. LOCAL(boxptr)
  177596. find_biggest_volume (boxptr boxlist, int numboxes)
  177597. /* Find the splittable box with the largest (scaled) volume */
  177598. /* Returns NULL if no splittable boxes remain */
  177599. {
  177600. register boxptr boxp;
  177601. register int i;
  177602. register INT32 maxv = 0;
  177603. boxptr which = NULL;
  177604. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177605. if (boxp->volume > maxv) {
  177606. which = boxp;
  177607. maxv = boxp->volume;
  177608. }
  177609. }
  177610. return which;
  177611. }
  177612. LOCAL(void)
  177613. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177614. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177615. /* and recompute its volume and population */
  177616. {
  177617. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177618. hist3d histogram = cquantize->histogram;
  177619. histptr histp;
  177620. int c0,c1,c2;
  177621. int c0min,c0max,c1min,c1max,c2min,c2max;
  177622. INT32 dist0,dist1,dist2;
  177623. long ccount;
  177624. c0min = boxp->c0min; c0max = boxp->c0max;
  177625. c1min = boxp->c1min; c1max = boxp->c1max;
  177626. c2min = boxp->c2min; c2max = boxp->c2max;
  177627. if (c0max > c0min)
  177628. for (c0 = c0min; c0 <= c0max; c0++)
  177629. for (c1 = c1min; c1 <= c1max; c1++) {
  177630. histp = & histogram[c0][c1][c2min];
  177631. for (c2 = c2min; c2 <= c2max; c2++)
  177632. if (*histp++ != 0) {
  177633. boxp->c0min = c0min = c0;
  177634. goto have_c0min;
  177635. }
  177636. }
  177637. have_c0min:
  177638. if (c0max > c0min)
  177639. for (c0 = c0max; c0 >= c0min; c0--)
  177640. for (c1 = c1min; c1 <= c1max; c1++) {
  177641. histp = & histogram[c0][c1][c2min];
  177642. for (c2 = c2min; c2 <= c2max; c2++)
  177643. if (*histp++ != 0) {
  177644. boxp->c0max = c0max = c0;
  177645. goto have_c0max;
  177646. }
  177647. }
  177648. have_c0max:
  177649. if (c1max > c1min)
  177650. for (c1 = c1min; c1 <= c1max; c1++)
  177651. for (c0 = c0min; c0 <= c0max; c0++) {
  177652. histp = & histogram[c0][c1][c2min];
  177653. for (c2 = c2min; c2 <= c2max; c2++)
  177654. if (*histp++ != 0) {
  177655. boxp->c1min = c1min = c1;
  177656. goto have_c1min;
  177657. }
  177658. }
  177659. have_c1min:
  177660. if (c1max > c1min)
  177661. for (c1 = c1max; c1 >= c1min; c1--)
  177662. for (c0 = c0min; c0 <= c0max; c0++) {
  177663. histp = & histogram[c0][c1][c2min];
  177664. for (c2 = c2min; c2 <= c2max; c2++)
  177665. if (*histp++ != 0) {
  177666. boxp->c1max = c1max = c1;
  177667. goto have_c1max;
  177668. }
  177669. }
  177670. have_c1max:
  177671. if (c2max > c2min)
  177672. for (c2 = c2min; c2 <= c2max; c2++)
  177673. for (c0 = c0min; c0 <= c0max; c0++) {
  177674. histp = & histogram[c0][c1min][c2];
  177675. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177676. if (*histp != 0) {
  177677. boxp->c2min = c2min = c2;
  177678. goto have_c2min;
  177679. }
  177680. }
  177681. have_c2min:
  177682. if (c2max > c2min)
  177683. for (c2 = c2max; c2 >= c2min; c2--)
  177684. for (c0 = c0min; c0 <= c0max; c0++) {
  177685. histp = & histogram[c0][c1min][c2];
  177686. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  177687. if (*histp != 0) {
  177688. boxp->c2max = c2max = c2;
  177689. goto have_c2max;
  177690. }
  177691. }
  177692. have_c2max:
  177693. /* Update box volume.
  177694. * We use 2-norm rather than real volume here; this biases the method
  177695. * against making long narrow boxes, and it has the side benefit that
  177696. * a box is splittable iff norm > 0.
  177697. * Since the differences are expressed in histogram-cell units,
  177698. * we have to shift back to JSAMPLE units to get consistent distances;
  177699. * after which, we scale according to the selected distance scale factors.
  177700. */
  177701. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  177702. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  177703. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  177704. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  177705. /* Now scan remaining volume of box and compute population */
  177706. ccount = 0;
  177707. for (c0 = c0min; c0 <= c0max; c0++)
  177708. for (c1 = c1min; c1 <= c1max; c1++) {
  177709. histp = & histogram[c0][c1][c2min];
  177710. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  177711. if (*histp != 0) {
  177712. ccount++;
  177713. }
  177714. }
  177715. boxp->colorcount = ccount;
  177716. }
  177717. LOCAL(int)
  177718. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  177719. int desired_colors)
  177720. /* Repeatedly select and split the largest box until we have enough boxes */
  177721. {
  177722. int n,lb;
  177723. int c0,c1,c2,cmax;
  177724. register boxptr b1,b2;
  177725. while (numboxes < desired_colors) {
  177726. /* Select box to split.
  177727. * Current algorithm: by population for first half, then by volume.
  177728. */
  177729. if (numboxes*2 <= desired_colors) {
  177730. b1 = find_biggest_color_pop(boxlist, numboxes);
  177731. } else {
  177732. b1 = find_biggest_volume(boxlist, numboxes);
  177733. }
  177734. if (b1 == NULL) /* no splittable boxes left! */
  177735. break;
  177736. b2 = &boxlist[numboxes]; /* where new box will go */
  177737. /* Copy the color bounds to the new box. */
  177738. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  177739. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  177740. /* Choose which axis to split the box on.
  177741. * Current algorithm: longest scaled axis.
  177742. * See notes in update_box about scaling distances.
  177743. */
  177744. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  177745. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  177746. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  177747. /* We want to break any ties in favor of green, then red, blue last.
  177748. * This code does the right thing for R,G,B or B,G,R color orders only.
  177749. */
  177750. #if RGB_RED == 0
  177751. cmax = c1; n = 1;
  177752. if (c0 > cmax) { cmax = c0; n = 0; }
  177753. if (c2 > cmax) { n = 2; }
  177754. #else
  177755. cmax = c1; n = 1;
  177756. if (c2 > cmax) { cmax = c2; n = 2; }
  177757. if (c0 > cmax) { n = 0; }
  177758. #endif
  177759. /* Choose split point along selected axis, and update box bounds.
  177760. * Current algorithm: split at halfway point.
  177761. * (Since the box has been shrunk to minimum volume,
  177762. * any split will produce two nonempty subboxes.)
  177763. * Note that lb value is max for lower box, so must be < old max.
  177764. */
  177765. switch (n) {
  177766. case 0:
  177767. lb = (b1->c0max + b1->c0min) / 2;
  177768. b1->c0max = lb;
  177769. b2->c0min = lb+1;
  177770. break;
  177771. case 1:
  177772. lb = (b1->c1max + b1->c1min) / 2;
  177773. b1->c1max = lb;
  177774. b2->c1min = lb+1;
  177775. break;
  177776. case 2:
  177777. lb = (b1->c2max + b1->c2min) / 2;
  177778. b1->c2max = lb;
  177779. b2->c2min = lb+1;
  177780. break;
  177781. }
  177782. /* Update stats for boxes */
  177783. update_box(cinfo, b1);
  177784. update_box(cinfo, b2);
  177785. numboxes++;
  177786. }
  177787. return numboxes;
  177788. }
  177789. LOCAL(void)
  177790. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  177791. /* Compute representative color for a box, put it in colormap[icolor] */
  177792. {
  177793. /* Current algorithm: mean weighted by pixels (not colors) */
  177794. /* Note it is important to get the rounding correct! */
  177795. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177796. hist3d histogram = cquantize->histogram;
  177797. histptr histp;
  177798. int c0,c1,c2;
  177799. int c0min,c0max,c1min,c1max,c2min,c2max;
  177800. long count;
  177801. long total = 0;
  177802. long c0total = 0;
  177803. long c1total = 0;
  177804. long c2total = 0;
  177805. c0min = boxp->c0min; c0max = boxp->c0max;
  177806. c1min = boxp->c1min; c1max = boxp->c1max;
  177807. c2min = boxp->c2min; c2max = boxp->c2max;
  177808. for (c0 = c0min; c0 <= c0max; c0++)
  177809. for (c1 = c1min; c1 <= c1max; c1++) {
  177810. histp = & histogram[c0][c1][c2min];
  177811. for (c2 = c2min; c2 <= c2max; c2++) {
  177812. if ((count = *histp++) != 0) {
  177813. total += count;
  177814. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  177815. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  177816. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  177817. }
  177818. }
  177819. }
  177820. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  177821. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  177822. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  177823. }
  177824. LOCAL(void)
  177825. select_colors (j_decompress_ptr cinfo, int desired_colors)
  177826. /* Master routine for color selection */
  177827. {
  177828. boxptr boxlist;
  177829. int numboxes;
  177830. int i;
  177831. /* Allocate workspace for box list */
  177832. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  177833. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  177834. /* Initialize one box containing whole space */
  177835. numboxes = 1;
  177836. boxlist[0].c0min = 0;
  177837. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  177838. boxlist[0].c1min = 0;
  177839. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  177840. boxlist[0].c2min = 0;
  177841. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  177842. /* Shrink it to actually-used volume and set its statistics */
  177843. update_box(cinfo, & boxlist[0]);
  177844. /* Perform median-cut to produce final box list */
  177845. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  177846. /* Compute the representative color for each box, fill colormap */
  177847. for (i = 0; i < numboxes; i++)
  177848. compute_color(cinfo, & boxlist[i], i);
  177849. cinfo->actual_number_of_colors = numboxes;
  177850. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  177851. }
  177852. /*
  177853. * These routines are concerned with the time-critical task of mapping input
  177854. * colors to the nearest color in the selected colormap.
  177855. *
  177856. * We re-use the histogram space as an "inverse color map", essentially a
  177857. * cache for the results of nearest-color searches. All colors within a
  177858. * histogram cell will be mapped to the same colormap entry, namely the one
  177859. * closest to the cell's center. This may not be quite the closest entry to
  177860. * the actual input color, but it's almost as good. A zero in the cache
  177861. * indicates we haven't found the nearest color for that cell yet; the array
  177862. * is cleared to zeroes before starting the mapping pass. When we find the
  177863. * nearest color for a cell, its colormap index plus one is recorded in the
  177864. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  177865. * when they need to use an unfilled entry in the cache.
  177866. *
  177867. * Our method of efficiently finding nearest colors is based on the "locally
  177868. * sorted search" idea described by Heckbert and on the incremental distance
  177869. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  177870. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  177871. * the distances from a given colormap entry to each cell of the histogram can
  177872. * be computed quickly using an incremental method: the differences between
  177873. * distances to adjacent cells themselves differ by a constant. This allows a
  177874. * fairly fast implementation of the "brute force" approach of computing the
  177875. * distance from every colormap entry to every histogram cell. Unfortunately,
  177876. * it needs a work array to hold the best-distance-so-far for each histogram
  177877. * cell (because the inner loop has to be over cells, not colormap entries).
  177878. * The work array elements have to be INT32s, so the work array would need
  177879. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  177880. *
  177881. * To get around these problems, we apply Thomas' method to compute the
  177882. * nearest colors for only the cells within a small subbox of the histogram.
  177883. * The work array need be only as big as the subbox, so the memory usage
  177884. * problem is solved. Furthermore, we need not fill subboxes that are never
  177885. * referenced in pass2; many images use only part of the color gamut, so a
  177886. * fair amount of work is saved. An additional advantage of this
  177887. * approach is that we can apply Heckbert's locality criterion to quickly
  177888. * eliminate colormap entries that are far away from the subbox; typically
  177889. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  177890. * and we need not compute their distances to individual cells in the subbox.
  177891. * The speed of this approach is heavily influenced by the subbox size: too
  177892. * small means too much overhead, too big loses because Heckbert's criterion
  177893. * can't eliminate as many colormap entries. Empirically the best subbox
  177894. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  177895. *
  177896. * Thomas' article also describes a refined method which is asymptotically
  177897. * faster than the brute-force method, but it is also far more complex and
  177898. * cannot efficiently be applied to small subboxes. It is therefore not
  177899. * useful for programs intended to be portable to DOS machines. On machines
  177900. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  177901. * refined method might be faster than the present code --- but then again,
  177902. * it might not be any faster, and it's certainly more complicated.
  177903. */
  177904. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  177905. #define BOX_C0_LOG (HIST_C0_BITS-3)
  177906. #define BOX_C1_LOG (HIST_C1_BITS-3)
  177907. #define BOX_C2_LOG (HIST_C2_BITS-3)
  177908. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  177909. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  177910. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  177911. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  177912. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  177913. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  177914. /*
  177915. * The next three routines implement inverse colormap filling. They could
  177916. * all be folded into one big routine, but splitting them up this way saves
  177917. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  177918. * and may allow some compilers to produce better code by registerizing more
  177919. * inner-loop variables.
  177920. */
  177921. LOCAL(int)
  177922. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  177923. JSAMPLE colorlist[])
  177924. /* Locate the colormap entries close enough to an update box to be candidates
  177925. * for the nearest entry to some cell(s) in the update box. The update box
  177926. * is specified by the center coordinates of its first cell. The number of
  177927. * candidate colormap entries is returned, and their colormap indexes are
  177928. * placed in colorlist[].
  177929. * This routine uses Heckbert's "locally sorted search" criterion to select
  177930. * the colors that need further consideration.
  177931. */
  177932. {
  177933. int numcolors = cinfo->actual_number_of_colors;
  177934. int maxc0, maxc1, maxc2;
  177935. int centerc0, centerc1, centerc2;
  177936. int i, x, ncolors;
  177937. INT32 minmaxdist, min_dist, max_dist, tdist;
  177938. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  177939. /* Compute true coordinates of update box's upper corner and center.
  177940. * Actually we compute the coordinates of the center of the upper-corner
  177941. * histogram cell, which are the upper bounds of the volume we care about.
  177942. * Note that since ">>" rounds down, the "center" values may be closer to
  177943. * min than to max; hence comparisons to them must be "<=", not "<".
  177944. */
  177945. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  177946. centerc0 = (minc0 + maxc0) >> 1;
  177947. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  177948. centerc1 = (minc1 + maxc1) >> 1;
  177949. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  177950. centerc2 = (minc2 + maxc2) >> 1;
  177951. /* For each color in colormap, find:
  177952. * 1. its minimum squared-distance to any point in the update box
  177953. * (zero if color is within update box);
  177954. * 2. its maximum squared-distance to any point in the update box.
  177955. * Both of these can be found by considering only the corners of the box.
  177956. * We save the minimum distance for each color in mindist[];
  177957. * only the smallest maximum distance is of interest.
  177958. */
  177959. minmaxdist = 0x7FFFFFFFL;
  177960. for (i = 0; i < numcolors; i++) {
  177961. /* We compute the squared-c0-distance term, then add in the other two. */
  177962. x = GETJSAMPLE(cinfo->colormap[0][i]);
  177963. if (x < minc0) {
  177964. tdist = (x - minc0) * C0_SCALE;
  177965. min_dist = tdist*tdist;
  177966. tdist = (x - maxc0) * C0_SCALE;
  177967. max_dist = tdist*tdist;
  177968. } else if (x > maxc0) {
  177969. tdist = (x - maxc0) * C0_SCALE;
  177970. min_dist = tdist*tdist;
  177971. tdist = (x - minc0) * C0_SCALE;
  177972. max_dist = tdist*tdist;
  177973. } else {
  177974. /* within cell range so no contribution to min_dist */
  177975. min_dist = 0;
  177976. if (x <= centerc0) {
  177977. tdist = (x - maxc0) * C0_SCALE;
  177978. max_dist = tdist*tdist;
  177979. } else {
  177980. tdist = (x - minc0) * C0_SCALE;
  177981. max_dist = tdist*tdist;
  177982. }
  177983. }
  177984. x = GETJSAMPLE(cinfo->colormap[1][i]);
  177985. if (x < minc1) {
  177986. tdist = (x - minc1) * C1_SCALE;
  177987. min_dist += tdist*tdist;
  177988. tdist = (x - maxc1) * C1_SCALE;
  177989. max_dist += tdist*tdist;
  177990. } else if (x > maxc1) {
  177991. tdist = (x - maxc1) * C1_SCALE;
  177992. min_dist += tdist*tdist;
  177993. tdist = (x - minc1) * C1_SCALE;
  177994. max_dist += tdist*tdist;
  177995. } else {
  177996. /* within cell range so no contribution to min_dist */
  177997. if (x <= centerc1) {
  177998. tdist = (x - maxc1) * C1_SCALE;
  177999. max_dist += tdist*tdist;
  178000. } else {
  178001. tdist = (x - minc1) * C1_SCALE;
  178002. max_dist += tdist*tdist;
  178003. }
  178004. }
  178005. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178006. if (x < minc2) {
  178007. tdist = (x - minc2) * C2_SCALE;
  178008. min_dist += tdist*tdist;
  178009. tdist = (x - maxc2) * C2_SCALE;
  178010. max_dist += tdist*tdist;
  178011. } else if (x > maxc2) {
  178012. tdist = (x - maxc2) * C2_SCALE;
  178013. min_dist += tdist*tdist;
  178014. tdist = (x - minc2) * C2_SCALE;
  178015. max_dist += tdist*tdist;
  178016. } else {
  178017. /* within cell range so no contribution to min_dist */
  178018. if (x <= centerc2) {
  178019. tdist = (x - maxc2) * C2_SCALE;
  178020. max_dist += tdist*tdist;
  178021. } else {
  178022. tdist = (x - minc2) * C2_SCALE;
  178023. max_dist += tdist*tdist;
  178024. }
  178025. }
  178026. mindist[i] = min_dist; /* save away the results */
  178027. if (max_dist < minmaxdist)
  178028. minmaxdist = max_dist;
  178029. }
  178030. /* Now we know that no cell in the update box is more than minmaxdist
  178031. * away from some colormap entry. Therefore, only colors that are
  178032. * within minmaxdist of some part of the box need be considered.
  178033. */
  178034. ncolors = 0;
  178035. for (i = 0; i < numcolors; i++) {
  178036. if (mindist[i] <= minmaxdist)
  178037. colorlist[ncolors++] = (JSAMPLE) i;
  178038. }
  178039. return ncolors;
  178040. }
  178041. LOCAL(void)
  178042. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178043. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178044. /* Find the closest colormap entry for each cell in the update box,
  178045. * given the list of candidate colors prepared by find_nearby_colors.
  178046. * Return the indexes of the closest entries in the bestcolor[] array.
  178047. * This routine uses Thomas' incremental distance calculation method to
  178048. * find the distance from a colormap entry to successive cells in the box.
  178049. */
  178050. {
  178051. int ic0, ic1, ic2;
  178052. int i, icolor;
  178053. register INT32 * bptr; /* pointer into bestdist[] array */
  178054. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178055. INT32 dist0, dist1; /* initial distance values */
  178056. register INT32 dist2; /* current distance in inner loop */
  178057. INT32 xx0, xx1; /* distance increments */
  178058. register INT32 xx2;
  178059. INT32 inc0, inc1, inc2; /* initial values for increments */
  178060. /* This array holds the distance to the nearest-so-far color for each cell */
  178061. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178062. /* Initialize best-distance for each cell of the update box */
  178063. bptr = bestdist;
  178064. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178065. *bptr++ = 0x7FFFFFFFL;
  178066. /* For each color selected by find_nearby_colors,
  178067. * compute its distance to the center of each cell in the box.
  178068. * If that's less than best-so-far, update best distance and color number.
  178069. */
  178070. /* Nominal steps between cell centers ("x" in Thomas article) */
  178071. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178072. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178073. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178074. for (i = 0; i < numcolors; i++) {
  178075. icolor = GETJSAMPLE(colorlist[i]);
  178076. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178077. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178078. dist0 = inc0*inc0;
  178079. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178080. dist0 += inc1*inc1;
  178081. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178082. dist0 += inc2*inc2;
  178083. /* Form the initial difference increments */
  178084. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178085. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178086. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178087. /* Now loop over all cells in box, updating distance per Thomas method */
  178088. bptr = bestdist;
  178089. cptr = bestcolor;
  178090. xx0 = inc0;
  178091. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178092. dist1 = dist0;
  178093. xx1 = inc1;
  178094. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178095. dist2 = dist1;
  178096. xx2 = inc2;
  178097. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178098. if (dist2 < *bptr) {
  178099. *bptr = dist2;
  178100. *cptr = (JSAMPLE) icolor;
  178101. }
  178102. dist2 += xx2;
  178103. xx2 += 2 * STEP_C2 * STEP_C2;
  178104. bptr++;
  178105. cptr++;
  178106. }
  178107. dist1 += xx1;
  178108. xx1 += 2 * STEP_C1 * STEP_C1;
  178109. }
  178110. dist0 += xx0;
  178111. xx0 += 2 * STEP_C0 * STEP_C0;
  178112. }
  178113. }
  178114. }
  178115. LOCAL(void)
  178116. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178117. /* Fill the inverse-colormap entries in the update box that contains */
  178118. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178119. /* we can fill as many others as we wish.) */
  178120. {
  178121. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178122. hist3d histogram = cquantize->histogram;
  178123. int minc0, minc1, minc2; /* lower left corner of update box */
  178124. int ic0, ic1, ic2;
  178125. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178126. register histptr cachep; /* pointer into main cache array */
  178127. /* This array lists the candidate colormap indexes. */
  178128. JSAMPLE colorlist[MAXNUMCOLORS];
  178129. int numcolors; /* number of candidate colors */
  178130. /* This array holds the actually closest colormap index for each cell. */
  178131. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178132. /* Convert cell coordinates to update box ID */
  178133. c0 >>= BOX_C0_LOG;
  178134. c1 >>= BOX_C1_LOG;
  178135. c2 >>= BOX_C2_LOG;
  178136. /* Compute true coordinates of update box's origin corner.
  178137. * Actually we compute the coordinates of the center of the corner
  178138. * histogram cell, which are the lower bounds of the volume we care about.
  178139. */
  178140. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178141. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178142. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178143. /* Determine which colormap entries are close enough to be candidates
  178144. * for the nearest entry to some cell in the update box.
  178145. */
  178146. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178147. /* Determine the actually nearest colors. */
  178148. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178149. bestcolor);
  178150. /* Save the best color numbers (plus 1) in the main cache array */
  178151. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178152. c1 <<= BOX_C1_LOG;
  178153. c2 <<= BOX_C2_LOG;
  178154. cptr = bestcolor;
  178155. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178156. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178157. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178158. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178159. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178160. }
  178161. }
  178162. }
  178163. }
  178164. /*
  178165. * Map some rows of pixels to the output colormapped representation.
  178166. */
  178167. METHODDEF(void)
  178168. pass2_no_dither (j_decompress_ptr cinfo,
  178169. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178170. /* This version performs no dithering */
  178171. {
  178172. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178173. hist3d histogram = cquantize->histogram;
  178174. register JSAMPROW inptr, outptr;
  178175. register histptr cachep;
  178176. register int c0, c1, c2;
  178177. int row;
  178178. JDIMENSION col;
  178179. JDIMENSION width = cinfo->output_width;
  178180. for (row = 0; row < num_rows; row++) {
  178181. inptr = input_buf[row];
  178182. outptr = output_buf[row];
  178183. for (col = width; col > 0; col--) {
  178184. /* get pixel value and index into the cache */
  178185. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178186. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178187. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178188. cachep = & histogram[c0][c1][c2];
  178189. /* If we have not seen this color before, find nearest colormap entry */
  178190. /* and update the cache */
  178191. if (*cachep == 0)
  178192. fill_inverse_cmap(cinfo, c0,c1,c2);
  178193. /* Now emit the colormap index for this cell */
  178194. *outptr++ = (JSAMPLE) (*cachep - 1);
  178195. }
  178196. }
  178197. }
  178198. METHODDEF(void)
  178199. pass2_fs_dither (j_decompress_ptr cinfo,
  178200. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178201. /* This version performs Floyd-Steinberg dithering */
  178202. {
  178203. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178204. hist3d histogram = cquantize->histogram;
  178205. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178206. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178207. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178208. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178209. JSAMPROW inptr; /* => current input pixel */
  178210. JSAMPROW outptr; /* => current output pixel */
  178211. histptr cachep;
  178212. int dir; /* +1 or -1 depending on direction */
  178213. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178214. int row;
  178215. JDIMENSION col;
  178216. JDIMENSION width = cinfo->output_width;
  178217. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178218. int *error_limit = cquantize->error_limiter;
  178219. JSAMPROW colormap0 = cinfo->colormap[0];
  178220. JSAMPROW colormap1 = cinfo->colormap[1];
  178221. JSAMPROW colormap2 = cinfo->colormap[2];
  178222. SHIFT_TEMPS
  178223. for (row = 0; row < num_rows; row++) {
  178224. inptr = input_buf[row];
  178225. outptr = output_buf[row];
  178226. if (cquantize->on_odd_row) {
  178227. /* work right to left in this row */
  178228. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178229. outptr += width-1;
  178230. dir = -1;
  178231. dir3 = -3;
  178232. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178233. cquantize->on_odd_row = FALSE; /* flip for next time */
  178234. } else {
  178235. /* work left to right in this row */
  178236. dir = 1;
  178237. dir3 = 3;
  178238. errorptr = cquantize->fserrors; /* => entry before first real column */
  178239. cquantize->on_odd_row = TRUE; /* flip for next time */
  178240. }
  178241. /* Preset error values: no error propagated to first pixel from left */
  178242. cur0 = cur1 = cur2 = 0;
  178243. /* and no error propagated to row below yet */
  178244. belowerr0 = belowerr1 = belowerr2 = 0;
  178245. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178246. for (col = width; col > 0; col--) {
  178247. /* curN holds the error propagated from the previous pixel on the
  178248. * current line. Add the error propagated from the previous line
  178249. * to form the complete error correction term for this pixel, and
  178250. * round the error term (which is expressed * 16) to an integer.
  178251. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178252. * for either sign of the error value.
  178253. * Note: errorptr points to *previous* column's array entry.
  178254. */
  178255. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178256. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178257. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178258. /* Limit the error using transfer function set by init_error_limit.
  178259. * See comments with init_error_limit for rationale.
  178260. */
  178261. cur0 = error_limit[cur0];
  178262. cur1 = error_limit[cur1];
  178263. cur2 = error_limit[cur2];
  178264. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178265. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178266. * this sets the required size of the range_limit array.
  178267. */
  178268. cur0 += GETJSAMPLE(inptr[0]);
  178269. cur1 += GETJSAMPLE(inptr[1]);
  178270. cur2 += GETJSAMPLE(inptr[2]);
  178271. cur0 = GETJSAMPLE(range_limit[cur0]);
  178272. cur1 = GETJSAMPLE(range_limit[cur1]);
  178273. cur2 = GETJSAMPLE(range_limit[cur2]);
  178274. /* Index into the cache with adjusted pixel value */
  178275. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178276. /* If we have not seen this color before, find nearest colormap */
  178277. /* entry and update the cache */
  178278. if (*cachep == 0)
  178279. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178280. /* Now emit the colormap index for this cell */
  178281. { register int pixcode = *cachep - 1;
  178282. *outptr = (JSAMPLE) pixcode;
  178283. /* Compute representation error for this pixel */
  178284. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178285. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178286. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178287. }
  178288. /* Compute error fractions to be propagated to adjacent pixels.
  178289. * Add these into the running sums, and simultaneously shift the
  178290. * next-line error sums left by 1 column.
  178291. */
  178292. { register LOCFSERROR bnexterr, delta;
  178293. bnexterr = cur0; /* Process component 0 */
  178294. delta = cur0 * 2;
  178295. cur0 += delta; /* form error * 3 */
  178296. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178297. cur0 += delta; /* form error * 5 */
  178298. bpreverr0 = belowerr0 + cur0;
  178299. belowerr0 = bnexterr;
  178300. cur0 += delta; /* form error * 7 */
  178301. bnexterr = cur1; /* Process component 1 */
  178302. delta = cur1 * 2;
  178303. cur1 += delta; /* form error * 3 */
  178304. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178305. cur1 += delta; /* form error * 5 */
  178306. bpreverr1 = belowerr1 + cur1;
  178307. belowerr1 = bnexterr;
  178308. cur1 += delta; /* form error * 7 */
  178309. bnexterr = cur2; /* Process component 2 */
  178310. delta = cur2 * 2;
  178311. cur2 += delta; /* form error * 3 */
  178312. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178313. cur2 += delta; /* form error * 5 */
  178314. bpreverr2 = belowerr2 + cur2;
  178315. belowerr2 = bnexterr;
  178316. cur2 += delta; /* form error * 7 */
  178317. }
  178318. /* At this point curN contains the 7/16 error value to be propagated
  178319. * to the next pixel on the current line, and all the errors for the
  178320. * next line have been shifted over. We are therefore ready to move on.
  178321. */
  178322. inptr += dir3; /* Advance pixel pointers to next column */
  178323. outptr += dir;
  178324. errorptr += dir3; /* advance errorptr to current column */
  178325. }
  178326. /* Post-loop cleanup: we must unload the final error values into the
  178327. * final fserrors[] entry. Note we need not unload belowerrN because
  178328. * it is for the dummy column before or after the actual array.
  178329. */
  178330. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178331. errorptr[1] = (FSERROR) bpreverr1;
  178332. errorptr[2] = (FSERROR) bpreverr2;
  178333. }
  178334. }
  178335. /*
  178336. * Initialize the error-limiting transfer function (lookup table).
  178337. * The raw F-S error computation can potentially compute error values of up to
  178338. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178339. * much less, otherwise obviously wrong pixels will be created. (Typical
  178340. * effects include weird fringes at color-area boundaries, isolated bright
  178341. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178342. * is to ensure that the "corners" of the color cube are allocated as output
  178343. * colors; then repeated errors in the same direction cannot cause cascading
  178344. * error buildup. However, that only prevents the error from getting
  178345. * completely out of hand; Aaron Giles reports that error limiting improves
  178346. * the results even with corner colors allocated.
  178347. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178348. * well, but the smoother transfer function used below is even better. Thanks
  178349. * to Aaron Giles for this idea.
  178350. */
  178351. LOCAL(void)
  178352. init_error_limit (j_decompress_ptr cinfo)
  178353. /* Allocate and fill in the error_limiter table */
  178354. {
  178355. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178356. int * table;
  178357. int in, out;
  178358. table = (int *) (*cinfo->mem->alloc_small)
  178359. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178360. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178361. cquantize->error_limiter = table;
  178362. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178363. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178364. out = 0;
  178365. for (in = 0; in < STEPSIZE; in++, out++) {
  178366. table[in] = out; table[-in] = -out;
  178367. }
  178368. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178369. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178370. table[in] = out; table[-in] = -out;
  178371. }
  178372. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178373. for (; in <= MAXJSAMPLE; in++) {
  178374. table[in] = out; table[-in] = -out;
  178375. }
  178376. #undef STEPSIZE
  178377. }
  178378. /*
  178379. * Finish up at the end of each pass.
  178380. */
  178381. METHODDEF(void)
  178382. finish_pass1 (j_decompress_ptr cinfo)
  178383. {
  178384. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178385. /* Select the representative colors and fill in cinfo->colormap */
  178386. cinfo->colormap = cquantize->sv_colormap;
  178387. select_colors(cinfo, cquantize->desired);
  178388. /* Force next pass to zero the color index table */
  178389. cquantize->needs_zeroed = TRUE;
  178390. }
  178391. METHODDEF(void)
  178392. finish_pass2 (j_decompress_ptr)
  178393. {
  178394. /* no work */
  178395. }
  178396. /*
  178397. * Initialize for each processing pass.
  178398. */
  178399. METHODDEF(void)
  178400. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178401. {
  178402. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178403. hist3d histogram = cquantize->histogram;
  178404. int i;
  178405. /* Only F-S dithering or no dithering is supported. */
  178406. /* If user asks for ordered dither, give him F-S. */
  178407. if (cinfo->dither_mode != JDITHER_NONE)
  178408. cinfo->dither_mode = JDITHER_FS;
  178409. if (is_pre_scan) {
  178410. /* Set up method pointers */
  178411. cquantize->pub.color_quantize = prescan_quantize;
  178412. cquantize->pub.finish_pass = finish_pass1;
  178413. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178414. } else {
  178415. /* Set up method pointers */
  178416. if (cinfo->dither_mode == JDITHER_FS)
  178417. cquantize->pub.color_quantize = pass2_fs_dither;
  178418. else
  178419. cquantize->pub.color_quantize = pass2_no_dither;
  178420. cquantize->pub.finish_pass = finish_pass2;
  178421. /* Make sure color count is acceptable */
  178422. i = cinfo->actual_number_of_colors;
  178423. if (i < 1)
  178424. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178425. if (i > MAXNUMCOLORS)
  178426. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178427. if (cinfo->dither_mode == JDITHER_FS) {
  178428. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178429. (3 * SIZEOF(FSERROR)));
  178430. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178431. if (cquantize->fserrors == NULL)
  178432. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178433. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178434. /* Initialize the propagated errors to zero. */
  178435. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178436. /* Make the error-limit table if we didn't already. */
  178437. if (cquantize->error_limiter == NULL)
  178438. init_error_limit(cinfo);
  178439. cquantize->on_odd_row = FALSE;
  178440. }
  178441. }
  178442. /* Zero the histogram or inverse color map, if necessary */
  178443. if (cquantize->needs_zeroed) {
  178444. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178445. jzero_far((void FAR *) histogram[i],
  178446. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178447. }
  178448. cquantize->needs_zeroed = FALSE;
  178449. }
  178450. }
  178451. /*
  178452. * Switch to a new external colormap between output passes.
  178453. */
  178454. METHODDEF(void)
  178455. new_color_map_2_quant (j_decompress_ptr cinfo)
  178456. {
  178457. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178458. /* Reset the inverse color map */
  178459. cquantize->needs_zeroed = TRUE;
  178460. }
  178461. /*
  178462. * Module initialization routine for 2-pass color quantization.
  178463. */
  178464. GLOBAL(void)
  178465. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178466. {
  178467. my_cquantize_ptr2 cquantize;
  178468. int i;
  178469. cquantize = (my_cquantize_ptr2)
  178470. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178471. SIZEOF(my_cquantizer2));
  178472. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178473. cquantize->pub.start_pass = start_pass_2_quant;
  178474. cquantize->pub.new_color_map = new_color_map_2_quant;
  178475. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178476. cquantize->error_limiter = NULL;
  178477. /* Make sure jdmaster didn't give me a case I can't handle */
  178478. if (cinfo->out_color_components != 3)
  178479. ERREXIT(cinfo, JERR_NOTIMPL);
  178480. /* Allocate the histogram/inverse colormap storage */
  178481. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178482. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178483. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178484. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178485. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178486. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178487. }
  178488. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178489. /* Allocate storage for the completed colormap, if required.
  178490. * We do this now since it is FAR storage and may affect
  178491. * the memory manager's space calculations.
  178492. */
  178493. if (cinfo->enable_2pass_quant) {
  178494. /* Make sure color count is acceptable */
  178495. int desired = cinfo->desired_number_of_colors;
  178496. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178497. if (desired < 8)
  178498. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178499. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178500. if (desired > MAXNUMCOLORS)
  178501. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178502. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178503. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178504. cquantize->desired = desired;
  178505. } else
  178506. cquantize->sv_colormap = NULL;
  178507. /* Only F-S dithering or no dithering is supported. */
  178508. /* If user asks for ordered dither, give him F-S. */
  178509. if (cinfo->dither_mode != JDITHER_NONE)
  178510. cinfo->dither_mode = JDITHER_FS;
  178511. /* Allocate Floyd-Steinberg workspace if necessary.
  178512. * This isn't really needed until pass 2, but again it is FAR storage.
  178513. * Although we will cope with a later change in dither_mode,
  178514. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178515. */
  178516. if (cinfo->dither_mode == JDITHER_FS) {
  178517. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178518. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178519. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178520. /* Might as well create the error-limiting table too. */
  178521. init_error_limit(cinfo);
  178522. }
  178523. }
  178524. #endif /* QUANT_2PASS_SUPPORTED */
  178525. /*** End of inlined file: jquant2.c ***/
  178526. /*** Start of inlined file: jutils.c ***/
  178527. #define JPEG_INTERNALS
  178528. /*
  178529. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178530. * of a DCT block read in natural order (left to right, top to bottom).
  178531. */
  178532. #if 0 /* This table is not actually needed in v6a */
  178533. const int jpeg_zigzag_order[DCTSIZE2] = {
  178534. 0, 1, 5, 6, 14, 15, 27, 28,
  178535. 2, 4, 7, 13, 16, 26, 29, 42,
  178536. 3, 8, 12, 17, 25, 30, 41, 43,
  178537. 9, 11, 18, 24, 31, 40, 44, 53,
  178538. 10, 19, 23, 32, 39, 45, 52, 54,
  178539. 20, 22, 33, 38, 46, 51, 55, 60,
  178540. 21, 34, 37, 47, 50, 56, 59, 61,
  178541. 35, 36, 48, 49, 57, 58, 62, 63
  178542. };
  178543. #endif
  178544. /*
  178545. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178546. * of zigzag order.
  178547. *
  178548. * When reading corrupted data, the Huffman decoders could attempt
  178549. * to reference an entry beyond the end of this array (if the decoded
  178550. * zero run length reaches past the end of the block). To prevent
  178551. * wild stores without adding an inner-loop test, we put some extra
  178552. * "63"s after the real entries. This will cause the extra coefficient
  178553. * to be stored in location 63 of the block, not somewhere random.
  178554. * The worst case would be a run-length of 15, which means we need 16
  178555. * fake entries.
  178556. */
  178557. const int jpeg_natural_order[DCTSIZE2+16] = {
  178558. 0, 1, 8, 16, 9, 2, 3, 10,
  178559. 17, 24, 32, 25, 18, 11, 4, 5,
  178560. 12, 19, 26, 33, 40, 48, 41, 34,
  178561. 27, 20, 13, 6, 7, 14, 21, 28,
  178562. 35, 42, 49, 56, 57, 50, 43, 36,
  178563. 29, 22, 15, 23, 30, 37, 44, 51,
  178564. 58, 59, 52, 45, 38, 31, 39, 46,
  178565. 53, 60, 61, 54, 47, 55, 62, 63,
  178566. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178567. 63, 63, 63, 63, 63, 63, 63, 63
  178568. };
  178569. /*
  178570. * Arithmetic utilities
  178571. */
  178572. GLOBAL(long)
  178573. jdiv_round_up (long a, long b)
  178574. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178575. /* Assumes a >= 0, b > 0 */
  178576. {
  178577. return (a + b - 1L) / b;
  178578. }
  178579. GLOBAL(long)
  178580. jround_up (long a, long b)
  178581. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178582. /* Assumes a >= 0, b > 0 */
  178583. {
  178584. a += b - 1L;
  178585. return a - (a % b);
  178586. }
  178587. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178588. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178589. * are FAR and we're assuming a small-pointer memory model. However, some
  178590. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178591. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178592. * Otherwise, the routines below do it the hard way. (The performance cost
  178593. * is not all that great, because these routines aren't very heavily used.)
  178594. */
  178595. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178596. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178597. #define FMEMZERO(target,size) MEMZERO(target,size)
  178598. #else /* 80x86 case, define if we can */
  178599. #ifdef USE_FMEM
  178600. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178601. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178602. #endif
  178603. #endif
  178604. GLOBAL(void)
  178605. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178606. JSAMPARRAY output_array, int dest_row,
  178607. int num_rows, JDIMENSION num_cols)
  178608. /* Copy some rows of samples from one place to another.
  178609. * num_rows rows are copied from input_array[source_row++]
  178610. * to output_array[dest_row++]; these areas may overlap for duplication.
  178611. * The source and destination arrays must be at least as wide as num_cols.
  178612. */
  178613. {
  178614. register JSAMPROW inptr, outptr;
  178615. #ifdef FMEMCOPY
  178616. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178617. #else
  178618. register JDIMENSION count;
  178619. #endif
  178620. register int row;
  178621. input_array += source_row;
  178622. output_array += dest_row;
  178623. for (row = num_rows; row > 0; row--) {
  178624. inptr = *input_array++;
  178625. outptr = *output_array++;
  178626. #ifdef FMEMCOPY
  178627. FMEMCOPY(outptr, inptr, count);
  178628. #else
  178629. for (count = num_cols; count > 0; count--)
  178630. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178631. #endif
  178632. }
  178633. }
  178634. GLOBAL(void)
  178635. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178636. JDIMENSION num_blocks)
  178637. /* Copy a row of coefficient blocks from one place to another. */
  178638. {
  178639. #ifdef FMEMCOPY
  178640. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178641. #else
  178642. register JCOEFPTR inptr, outptr;
  178643. register long count;
  178644. inptr = (JCOEFPTR) input_row;
  178645. outptr = (JCOEFPTR) output_row;
  178646. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178647. *outptr++ = *inptr++;
  178648. }
  178649. #endif
  178650. }
  178651. GLOBAL(void)
  178652. jzero_far (void FAR * target, size_t bytestozero)
  178653. /* Zero out a chunk of FAR memory. */
  178654. /* This might be sample-array data, block-array data, or alloc_large data. */
  178655. {
  178656. #ifdef FMEMZERO
  178657. FMEMZERO(target, bytestozero);
  178658. #else
  178659. register char FAR * ptr = (char FAR *) target;
  178660. register size_t count;
  178661. for (count = bytestozero; count > 0; count--) {
  178662. *ptr++ = 0;
  178663. }
  178664. #endif
  178665. }
  178666. /*** End of inlined file: jutils.c ***/
  178667. /*** Start of inlined file: transupp.c ***/
  178668. /* Although this file really shouldn't have access to the library internals,
  178669. * it's helpful to let it call jround_up() and jcopy_block_row().
  178670. */
  178671. #define JPEG_INTERNALS
  178672. /*** Start of inlined file: transupp.h ***/
  178673. /* If you happen not to want the image transform support, disable it here */
  178674. #ifndef TRANSFORMS_SUPPORTED
  178675. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  178676. #endif
  178677. /* Short forms of external names for systems with brain-damaged linkers. */
  178678. #ifdef NEED_SHORT_EXTERNAL_NAMES
  178679. #define jtransform_request_workspace jTrRequest
  178680. #define jtransform_adjust_parameters jTrAdjust
  178681. #define jtransform_execute_transformation jTrExec
  178682. #define jcopy_markers_setup jCMrkSetup
  178683. #define jcopy_markers_execute jCMrkExec
  178684. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  178685. /*
  178686. * Codes for supported types of image transformations.
  178687. */
  178688. typedef enum {
  178689. JXFORM_NONE, /* no transformation */
  178690. JXFORM_FLIP_H, /* horizontal flip */
  178691. JXFORM_FLIP_V, /* vertical flip */
  178692. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  178693. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  178694. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  178695. JXFORM_ROT_180, /* 180-degree rotation */
  178696. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  178697. } JXFORM_CODE;
  178698. /*
  178699. * Although rotating and flipping data expressed as DCT coefficients is not
  178700. * hard, there is an asymmetry in the JPEG format specification for images
  178701. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  178702. * image edges are padded out to the next iMCU boundary with junk data; but
  178703. * no padding is possible at the top and left edges. If we were to flip
  178704. * the whole image including the pad data, then pad garbage would become
  178705. * visible at the top and/or left, and real pixels would disappear into the
  178706. * pad margins --- perhaps permanently, since encoders & decoders may not
  178707. * bother to preserve DCT blocks that appear to be completely outside the
  178708. * nominal image area. So, we have to exclude any partial iMCUs from the
  178709. * basic transformation.
  178710. *
  178711. * Transpose is the only transformation that can handle partial iMCUs at the
  178712. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  178713. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  178714. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  178715. * The other transforms are defined as combinations of these basic transforms
  178716. * and process edge blocks in a way that preserves the equivalence.
  178717. *
  178718. * The "trim" option causes untransformable partial iMCUs to be dropped;
  178719. * this is not strictly lossless, but it usually gives the best-looking
  178720. * result for odd-size images. Note that when this option is active,
  178721. * the expected mathematical equivalences between the transforms may not hold.
  178722. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  178723. * followed by -rot 180 -trim trims both edges.)
  178724. *
  178725. * We also offer a "force to grayscale" option, which simply discards the
  178726. * chrominance channels of a YCbCr image. This is lossless in the sense that
  178727. * the luminance channel is preserved exactly. It's not the same kind of
  178728. * thing as the rotate/flip transformations, but it's convenient to handle it
  178729. * as part of this package, mainly because the transformation routines have to
  178730. * be aware of the option to know how many components to work on.
  178731. */
  178732. typedef struct {
  178733. /* Options: set by caller */
  178734. JXFORM_CODE transform; /* image transform operator */
  178735. boolean trim; /* if TRUE, trim partial MCUs as needed */
  178736. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  178737. /* Internal workspace: caller should not touch these */
  178738. int num_components; /* # of components in workspace */
  178739. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  178740. } jpeg_transform_info;
  178741. #if TRANSFORMS_SUPPORTED
  178742. /* Request any required workspace */
  178743. EXTERN(void) jtransform_request_workspace
  178744. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  178745. /* Adjust output image parameters */
  178746. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  178747. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178748. jvirt_barray_ptr *src_coef_arrays,
  178749. jpeg_transform_info *info));
  178750. /* Execute the actual transformation, if any */
  178751. EXTERN(void) jtransform_execute_transformation
  178752. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178753. jvirt_barray_ptr *src_coef_arrays,
  178754. jpeg_transform_info *info));
  178755. #endif /* TRANSFORMS_SUPPORTED */
  178756. /*
  178757. * Support for copying optional markers from source to destination file.
  178758. */
  178759. typedef enum {
  178760. JCOPYOPT_NONE, /* copy no optional markers */
  178761. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  178762. JCOPYOPT_ALL /* copy all optional markers */
  178763. } JCOPY_OPTION;
  178764. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  178765. /* Setup decompression object to save desired markers in memory */
  178766. EXTERN(void) jcopy_markers_setup
  178767. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  178768. /* Copy markers saved in the given source object to the destination object */
  178769. EXTERN(void) jcopy_markers_execute
  178770. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178771. JCOPY_OPTION option));
  178772. /*** End of inlined file: transupp.h ***/
  178773. /* My own external interface */
  178774. #if TRANSFORMS_SUPPORTED
  178775. /*
  178776. * Lossless image transformation routines. These routines work on DCT
  178777. * coefficient arrays and thus do not require any lossy decompression
  178778. * or recompression of the image.
  178779. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  178780. *
  178781. * Horizontal flipping is done in-place, using a single top-to-bottom
  178782. * pass through the virtual source array. It will thus be much the
  178783. * fastest option for images larger than main memory.
  178784. *
  178785. * The other routines require a set of destination virtual arrays, so they
  178786. * need twice as much memory as jpegtran normally does. The destination
  178787. * arrays are always written in normal scan order (top to bottom) because
  178788. * the virtual array manager expects this. The source arrays will be scanned
  178789. * in the corresponding order, which means multiple passes through the source
  178790. * arrays for most of the transforms. That could result in much thrashing
  178791. * if the image is larger than main memory.
  178792. *
  178793. * Some notes about the operating environment of the individual transform
  178794. * routines:
  178795. * 1. Both the source and destination virtual arrays are allocated from the
  178796. * source JPEG object, and therefore should be manipulated by calling the
  178797. * source's memory manager.
  178798. * 2. The destination's component count should be used. It may be smaller
  178799. * than the source's when forcing to grayscale.
  178800. * 3. Likewise the destination's sampling factors should be used. When
  178801. * forcing to grayscale the destination's sampling factors will be all 1,
  178802. * and we may as well take that as the effective iMCU size.
  178803. * 4. When "trim" is in effect, the destination's dimensions will be the
  178804. * trimmed values but the source's will be untrimmed.
  178805. * 5. All the routines assume that the source and destination buffers are
  178806. * padded out to a full iMCU boundary. This is true, although for the
  178807. * source buffer it is an undocumented property of jdcoefct.c.
  178808. * Notes 2,3,4 boil down to this: generally we should use the destination's
  178809. * dimensions and ignore the source's.
  178810. */
  178811. LOCAL(void)
  178812. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178813. jvirt_barray_ptr *src_coef_arrays)
  178814. /* Horizontal flip; done in-place, so no separate dest array is required */
  178815. {
  178816. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  178817. int ci, k, offset_y;
  178818. JBLOCKARRAY buffer;
  178819. JCOEFPTR ptr1, ptr2;
  178820. JCOEF temp1, temp2;
  178821. jpeg_component_info *compptr;
  178822. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  178823. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  178824. * mirroring by changing the signs of odd-numbered columns.
  178825. * Partial iMCUs at the right edge are left untouched.
  178826. */
  178827. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178828. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178829. compptr = dstinfo->comp_info + ci;
  178830. comp_width = MCU_cols * compptr->h_samp_factor;
  178831. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  178832. blk_y += compptr->v_samp_factor) {
  178833. buffer = (*srcinfo->mem->access_virt_barray)
  178834. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  178835. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178836. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178837. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  178838. ptr1 = buffer[offset_y][blk_x];
  178839. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  178840. /* this unrolled loop doesn't need to know which row it's on... */
  178841. for (k = 0; k < DCTSIZE2; k += 2) {
  178842. temp1 = *ptr1; /* swap even column */
  178843. temp2 = *ptr2;
  178844. *ptr1++ = temp2;
  178845. *ptr2++ = temp1;
  178846. temp1 = *ptr1; /* swap odd column with sign change */
  178847. temp2 = *ptr2;
  178848. *ptr1++ = -temp2;
  178849. *ptr2++ = -temp1;
  178850. }
  178851. }
  178852. }
  178853. }
  178854. }
  178855. }
  178856. LOCAL(void)
  178857. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178858. jvirt_barray_ptr *src_coef_arrays,
  178859. jvirt_barray_ptr *dst_coef_arrays)
  178860. /* Vertical flip */
  178861. {
  178862. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  178863. int ci, i, j, offset_y;
  178864. JBLOCKARRAY src_buffer, dst_buffer;
  178865. JBLOCKROW src_row_ptr, dst_row_ptr;
  178866. JCOEFPTR src_ptr, dst_ptr;
  178867. jpeg_component_info *compptr;
  178868. /* We output into a separate array because we can't touch different
  178869. * rows of the source virtual array simultaneously. Otherwise, this
  178870. * is a pretty straightforward analog of horizontal flip.
  178871. * Within a DCT block, vertical mirroring is done by changing the signs
  178872. * of odd-numbered rows.
  178873. * Partial iMCUs at the bottom edge are copied verbatim.
  178874. */
  178875. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  178876. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178877. compptr = dstinfo->comp_info + ci;
  178878. comp_height = MCU_rows * compptr->v_samp_factor;
  178879. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178880. dst_blk_y += compptr->v_samp_factor) {
  178881. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178882. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178883. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178884. if (dst_blk_y < comp_height) {
  178885. /* Row is within the mirrorable area. */
  178886. src_buffer = (*srcinfo->mem->access_virt_barray)
  178887. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  178888. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  178889. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178890. } else {
  178891. /* Bottom-edge blocks will be copied verbatim. */
  178892. src_buffer = (*srcinfo->mem->access_virt_barray)
  178893. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  178894. (JDIMENSION) compptr->v_samp_factor, FALSE);
  178895. }
  178896. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178897. if (dst_blk_y < comp_height) {
  178898. /* Row is within the mirrorable area. */
  178899. dst_row_ptr = dst_buffer[offset_y];
  178900. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  178901. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178902. dst_blk_x++) {
  178903. dst_ptr = dst_row_ptr[dst_blk_x];
  178904. src_ptr = src_row_ptr[dst_blk_x];
  178905. for (i = 0; i < DCTSIZE; i += 2) {
  178906. /* copy even row */
  178907. for (j = 0; j < DCTSIZE; j++)
  178908. *dst_ptr++ = *src_ptr++;
  178909. /* copy odd row with sign change */
  178910. for (j = 0; j < DCTSIZE; j++)
  178911. *dst_ptr++ = - *src_ptr++;
  178912. }
  178913. }
  178914. } else {
  178915. /* Just copy row verbatim. */
  178916. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  178917. compptr->width_in_blocks);
  178918. }
  178919. }
  178920. }
  178921. }
  178922. }
  178923. LOCAL(void)
  178924. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178925. jvirt_barray_ptr *src_coef_arrays,
  178926. jvirt_barray_ptr *dst_coef_arrays)
  178927. /* Transpose source into destination */
  178928. {
  178929. JDIMENSION dst_blk_x, dst_blk_y;
  178930. int ci, i, j, offset_x, offset_y;
  178931. JBLOCKARRAY src_buffer, dst_buffer;
  178932. JCOEFPTR src_ptr, dst_ptr;
  178933. jpeg_component_info *compptr;
  178934. /* Transposing pixels within a block just requires transposing the
  178935. * DCT coefficients.
  178936. * Partial iMCUs at the edges require no special treatment; we simply
  178937. * process all the available DCT blocks for every component.
  178938. */
  178939. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178940. compptr = dstinfo->comp_info + ci;
  178941. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178942. dst_blk_y += compptr->v_samp_factor) {
  178943. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178944. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178945. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178946. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178947. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178948. dst_blk_x += compptr->h_samp_factor) {
  178949. src_buffer = (*srcinfo->mem->access_virt_barray)
  178950. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178951. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178952. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178953. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  178954. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  178955. for (i = 0; i < DCTSIZE; i++)
  178956. for (j = 0; j < DCTSIZE; j++)
  178957. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  178958. }
  178959. }
  178960. }
  178961. }
  178962. }
  178963. }
  178964. LOCAL(void)
  178965. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  178966. jvirt_barray_ptr *src_coef_arrays,
  178967. jvirt_barray_ptr *dst_coef_arrays)
  178968. /* 90 degree rotation is equivalent to
  178969. * 1. Transposing the image;
  178970. * 2. Horizontal mirroring.
  178971. * These two steps are merged into a single processing routine.
  178972. */
  178973. {
  178974. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  178975. int ci, i, j, offset_x, offset_y;
  178976. JBLOCKARRAY src_buffer, dst_buffer;
  178977. JCOEFPTR src_ptr, dst_ptr;
  178978. jpeg_component_info *compptr;
  178979. /* Because of the horizontal mirror step, we can't process partial iMCUs
  178980. * at the (output) right edge properly. They just get transposed and
  178981. * not mirrored.
  178982. */
  178983. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  178984. for (ci = 0; ci < dstinfo->num_components; ci++) {
  178985. compptr = dstinfo->comp_info + ci;
  178986. comp_width = MCU_cols * compptr->h_samp_factor;
  178987. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  178988. dst_blk_y += compptr->v_samp_factor) {
  178989. dst_buffer = (*srcinfo->mem->access_virt_barray)
  178990. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  178991. (JDIMENSION) compptr->v_samp_factor, TRUE);
  178992. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  178993. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  178994. dst_blk_x += compptr->h_samp_factor) {
  178995. src_buffer = (*srcinfo->mem->access_virt_barray)
  178996. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  178997. (JDIMENSION) compptr->h_samp_factor, FALSE);
  178998. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  178999. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179000. if (dst_blk_x < comp_width) {
  179001. /* Block is within the mirrorable area. */
  179002. dst_ptr = dst_buffer[offset_y]
  179003. [comp_width - dst_blk_x - offset_x - 1];
  179004. for (i = 0; i < DCTSIZE; i++) {
  179005. for (j = 0; j < DCTSIZE; j++)
  179006. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179007. i++;
  179008. for (j = 0; j < DCTSIZE; j++)
  179009. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179010. }
  179011. } else {
  179012. /* Edge blocks are transposed but not mirrored. */
  179013. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179014. for (i = 0; i < DCTSIZE; i++)
  179015. for (j = 0; j < DCTSIZE; j++)
  179016. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179017. }
  179018. }
  179019. }
  179020. }
  179021. }
  179022. }
  179023. }
  179024. LOCAL(void)
  179025. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179026. jvirt_barray_ptr *src_coef_arrays,
  179027. jvirt_barray_ptr *dst_coef_arrays)
  179028. /* 270 degree rotation is equivalent to
  179029. * 1. Horizontal mirroring;
  179030. * 2. Transposing the image.
  179031. * These two steps are merged into a single processing routine.
  179032. */
  179033. {
  179034. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179035. int ci, i, j, offset_x, offset_y;
  179036. JBLOCKARRAY src_buffer, dst_buffer;
  179037. JCOEFPTR src_ptr, dst_ptr;
  179038. jpeg_component_info *compptr;
  179039. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179040. * at the (output) bottom edge properly. They just get transposed and
  179041. * not mirrored.
  179042. */
  179043. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179044. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179045. compptr = dstinfo->comp_info + ci;
  179046. comp_height = MCU_rows * compptr->v_samp_factor;
  179047. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179048. dst_blk_y += compptr->v_samp_factor) {
  179049. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179050. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179051. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179052. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179053. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179054. dst_blk_x += compptr->h_samp_factor) {
  179055. src_buffer = (*srcinfo->mem->access_virt_barray)
  179056. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179057. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179058. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179059. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179060. if (dst_blk_y < comp_height) {
  179061. /* Block is within the mirrorable area. */
  179062. src_ptr = src_buffer[offset_x]
  179063. [comp_height - dst_blk_y - offset_y - 1];
  179064. for (i = 0; i < DCTSIZE; i++) {
  179065. for (j = 0; j < DCTSIZE; j++) {
  179066. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179067. j++;
  179068. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179069. }
  179070. }
  179071. } else {
  179072. /* Edge blocks are transposed but not mirrored. */
  179073. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179074. for (i = 0; i < DCTSIZE; i++)
  179075. for (j = 0; j < DCTSIZE; j++)
  179076. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179077. }
  179078. }
  179079. }
  179080. }
  179081. }
  179082. }
  179083. }
  179084. LOCAL(void)
  179085. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179086. jvirt_barray_ptr *src_coef_arrays,
  179087. jvirt_barray_ptr *dst_coef_arrays)
  179088. /* 180 degree rotation is equivalent to
  179089. * 1. Vertical mirroring;
  179090. * 2. Horizontal mirroring.
  179091. * These two steps are merged into a single processing routine.
  179092. */
  179093. {
  179094. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179095. int ci, i, j, offset_y;
  179096. JBLOCKARRAY src_buffer, dst_buffer;
  179097. JBLOCKROW src_row_ptr, dst_row_ptr;
  179098. JCOEFPTR src_ptr, dst_ptr;
  179099. jpeg_component_info *compptr;
  179100. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179101. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179102. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179103. compptr = dstinfo->comp_info + ci;
  179104. comp_width = MCU_cols * compptr->h_samp_factor;
  179105. comp_height = MCU_rows * compptr->v_samp_factor;
  179106. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179107. dst_blk_y += compptr->v_samp_factor) {
  179108. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179109. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179110. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179111. if (dst_blk_y < comp_height) {
  179112. /* Row is within the vertically mirrorable area. */
  179113. src_buffer = (*srcinfo->mem->access_virt_barray)
  179114. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179115. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179116. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179117. } else {
  179118. /* Bottom-edge rows are only mirrored horizontally. */
  179119. src_buffer = (*srcinfo->mem->access_virt_barray)
  179120. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179121. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179122. }
  179123. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179124. if (dst_blk_y < comp_height) {
  179125. /* Row is within the mirrorable area. */
  179126. dst_row_ptr = dst_buffer[offset_y];
  179127. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179128. /* Process the blocks that can be mirrored both ways. */
  179129. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179130. dst_ptr = dst_row_ptr[dst_blk_x];
  179131. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179132. for (i = 0; i < DCTSIZE; i += 2) {
  179133. /* For even row, negate every odd column. */
  179134. for (j = 0; j < DCTSIZE; j += 2) {
  179135. *dst_ptr++ = *src_ptr++;
  179136. *dst_ptr++ = - *src_ptr++;
  179137. }
  179138. /* For odd row, negate every even column. */
  179139. for (j = 0; j < DCTSIZE; j += 2) {
  179140. *dst_ptr++ = - *src_ptr++;
  179141. *dst_ptr++ = *src_ptr++;
  179142. }
  179143. }
  179144. }
  179145. /* Any remaining right-edge blocks are only mirrored vertically. */
  179146. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179147. dst_ptr = dst_row_ptr[dst_blk_x];
  179148. src_ptr = src_row_ptr[dst_blk_x];
  179149. for (i = 0; i < DCTSIZE; i += 2) {
  179150. for (j = 0; j < DCTSIZE; j++)
  179151. *dst_ptr++ = *src_ptr++;
  179152. for (j = 0; j < DCTSIZE; j++)
  179153. *dst_ptr++ = - *src_ptr++;
  179154. }
  179155. }
  179156. } else {
  179157. /* Remaining rows are just mirrored horizontally. */
  179158. dst_row_ptr = dst_buffer[offset_y];
  179159. src_row_ptr = src_buffer[offset_y];
  179160. /* Process the blocks that can be mirrored. */
  179161. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179162. dst_ptr = dst_row_ptr[dst_blk_x];
  179163. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179164. for (i = 0; i < DCTSIZE2; i += 2) {
  179165. *dst_ptr++ = *src_ptr++;
  179166. *dst_ptr++ = - *src_ptr++;
  179167. }
  179168. }
  179169. /* Any remaining right-edge blocks are only copied. */
  179170. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179171. dst_ptr = dst_row_ptr[dst_blk_x];
  179172. src_ptr = src_row_ptr[dst_blk_x];
  179173. for (i = 0; i < DCTSIZE2; i++)
  179174. *dst_ptr++ = *src_ptr++;
  179175. }
  179176. }
  179177. }
  179178. }
  179179. }
  179180. }
  179181. LOCAL(void)
  179182. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179183. jvirt_barray_ptr *src_coef_arrays,
  179184. jvirt_barray_ptr *dst_coef_arrays)
  179185. /* Transverse transpose is equivalent to
  179186. * 1. 180 degree rotation;
  179187. * 2. Transposition;
  179188. * or
  179189. * 1. Horizontal mirroring;
  179190. * 2. Transposition;
  179191. * 3. Horizontal mirroring.
  179192. * These steps are merged into a single processing routine.
  179193. */
  179194. {
  179195. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179196. int ci, i, j, offset_x, offset_y;
  179197. JBLOCKARRAY src_buffer, dst_buffer;
  179198. JCOEFPTR src_ptr, dst_ptr;
  179199. jpeg_component_info *compptr;
  179200. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179201. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179202. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179203. compptr = dstinfo->comp_info + ci;
  179204. comp_width = MCU_cols * compptr->h_samp_factor;
  179205. comp_height = MCU_rows * compptr->v_samp_factor;
  179206. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179207. dst_blk_y += compptr->v_samp_factor) {
  179208. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179209. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179210. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179211. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179212. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179213. dst_blk_x += compptr->h_samp_factor) {
  179214. src_buffer = (*srcinfo->mem->access_virt_barray)
  179215. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179216. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179217. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179218. if (dst_blk_y < comp_height) {
  179219. src_ptr = src_buffer[offset_x]
  179220. [comp_height - dst_blk_y - offset_y - 1];
  179221. if (dst_blk_x < comp_width) {
  179222. /* Block is within the mirrorable area. */
  179223. dst_ptr = dst_buffer[offset_y]
  179224. [comp_width - dst_blk_x - offset_x - 1];
  179225. for (i = 0; i < DCTSIZE; i++) {
  179226. for (j = 0; j < DCTSIZE; j++) {
  179227. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179228. j++;
  179229. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179230. }
  179231. i++;
  179232. for (j = 0; j < DCTSIZE; j++) {
  179233. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179234. j++;
  179235. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179236. }
  179237. }
  179238. } else {
  179239. /* Right-edge blocks are mirrored in y only */
  179240. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179241. for (i = 0; i < DCTSIZE; i++) {
  179242. for (j = 0; j < DCTSIZE; j++) {
  179243. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179244. j++;
  179245. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179246. }
  179247. }
  179248. }
  179249. } else {
  179250. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179251. if (dst_blk_x < comp_width) {
  179252. /* Bottom-edge blocks are mirrored in x only */
  179253. dst_ptr = dst_buffer[offset_y]
  179254. [comp_width - dst_blk_x - offset_x - 1];
  179255. for (i = 0; i < DCTSIZE; i++) {
  179256. for (j = 0; j < DCTSIZE; j++)
  179257. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179258. i++;
  179259. for (j = 0; j < DCTSIZE; j++)
  179260. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179261. }
  179262. } else {
  179263. /* At lower right corner, just transpose, no mirroring */
  179264. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179265. for (i = 0; i < DCTSIZE; i++)
  179266. for (j = 0; j < DCTSIZE; j++)
  179267. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179268. }
  179269. }
  179270. }
  179271. }
  179272. }
  179273. }
  179274. }
  179275. }
  179276. /* Request any required workspace.
  179277. *
  179278. * We allocate the workspace virtual arrays from the source decompression
  179279. * object, so that all the arrays (both the original data and the workspace)
  179280. * will be taken into account while making memory management decisions.
  179281. * Hence, this routine must be called after jpeg_read_header (which reads
  179282. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179283. * the source's virtual arrays).
  179284. */
  179285. GLOBAL(void)
  179286. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179287. jpeg_transform_info *info)
  179288. {
  179289. jvirt_barray_ptr *coef_arrays = NULL;
  179290. jpeg_component_info *compptr;
  179291. int ci;
  179292. if (info->force_grayscale &&
  179293. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179294. srcinfo->num_components == 3) {
  179295. /* We'll only process the first component */
  179296. info->num_components = 1;
  179297. } else {
  179298. /* Process all the components */
  179299. info->num_components = srcinfo->num_components;
  179300. }
  179301. switch (info->transform) {
  179302. case JXFORM_NONE:
  179303. case JXFORM_FLIP_H:
  179304. /* Don't need a workspace array */
  179305. break;
  179306. case JXFORM_FLIP_V:
  179307. case JXFORM_ROT_180:
  179308. /* Need workspace arrays having same dimensions as source image.
  179309. * Note that we allocate arrays padded out to the next iMCU boundary,
  179310. * so that transform routines need not worry about missing edge blocks.
  179311. */
  179312. coef_arrays = (jvirt_barray_ptr *)
  179313. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179314. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179315. for (ci = 0; ci < info->num_components; ci++) {
  179316. compptr = srcinfo->comp_info + ci;
  179317. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179318. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179319. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179320. (long) compptr->h_samp_factor),
  179321. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179322. (long) compptr->v_samp_factor),
  179323. (JDIMENSION) compptr->v_samp_factor);
  179324. }
  179325. break;
  179326. case JXFORM_TRANSPOSE:
  179327. case JXFORM_TRANSVERSE:
  179328. case JXFORM_ROT_90:
  179329. case JXFORM_ROT_270:
  179330. /* Need workspace arrays having transposed dimensions.
  179331. * Note that we allocate arrays padded out to the next iMCU boundary,
  179332. * so that transform routines need not worry about missing edge blocks.
  179333. */
  179334. coef_arrays = (jvirt_barray_ptr *)
  179335. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179336. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179337. for (ci = 0; ci < info->num_components; ci++) {
  179338. compptr = srcinfo->comp_info + ci;
  179339. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179340. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179341. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179342. (long) compptr->v_samp_factor),
  179343. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179344. (long) compptr->h_samp_factor),
  179345. (JDIMENSION) compptr->h_samp_factor);
  179346. }
  179347. break;
  179348. }
  179349. info->workspace_coef_arrays = coef_arrays;
  179350. }
  179351. /* Transpose destination image parameters */
  179352. LOCAL(void)
  179353. transpose_critical_parameters (j_compress_ptr dstinfo)
  179354. {
  179355. int tblno, i, j, ci, itemp;
  179356. jpeg_component_info *compptr;
  179357. JQUANT_TBL *qtblptr;
  179358. JDIMENSION dtemp;
  179359. UINT16 qtemp;
  179360. /* Transpose basic image dimensions */
  179361. dtemp = dstinfo->image_width;
  179362. dstinfo->image_width = dstinfo->image_height;
  179363. dstinfo->image_height = dtemp;
  179364. /* Transpose sampling factors */
  179365. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179366. compptr = dstinfo->comp_info + ci;
  179367. itemp = compptr->h_samp_factor;
  179368. compptr->h_samp_factor = compptr->v_samp_factor;
  179369. compptr->v_samp_factor = itemp;
  179370. }
  179371. /* Transpose quantization tables */
  179372. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179373. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179374. if (qtblptr != NULL) {
  179375. for (i = 0; i < DCTSIZE; i++) {
  179376. for (j = 0; j < i; j++) {
  179377. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179378. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179379. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179380. }
  179381. }
  179382. }
  179383. }
  179384. }
  179385. /* Trim off any partial iMCUs on the indicated destination edge */
  179386. LOCAL(void)
  179387. trim_right_edge (j_compress_ptr dstinfo)
  179388. {
  179389. int ci, max_h_samp_factor;
  179390. JDIMENSION MCU_cols;
  179391. /* We have to compute max_h_samp_factor ourselves,
  179392. * because it hasn't been set yet in the destination
  179393. * (and we don't want to use the source's value).
  179394. */
  179395. max_h_samp_factor = 1;
  179396. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179397. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179398. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179399. }
  179400. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179401. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179402. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179403. }
  179404. LOCAL(void)
  179405. trim_bottom_edge (j_compress_ptr dstinfo)
  179406. {
  179407. int ci, max_v_samp_factor;
  179408. JDIMENSION MCU_rows;
  179409. /* We have to compute max_v_samp_factor ourselves,
  179410. * because it hasn't been set yet in the destination
  179411. * (and we don't want to use the source's value).
  179412. */
  179413. max_v_samp_factor = 1;
  179414. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179415. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179416. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179417. }
  179418. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179419. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179420. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179421. }
  179422. /* Adjust output image parameters as needed.
  179423. *
  179424. * This must be called after jpeg_copy_critical_parameters()
  179425. * and before jpeg_write_coefficients().
  179426. *
  179427. * The return value is the set of virtual coefficient arrays to be written
  179428. * (either the ones allocated by jtransform_request_workspace, or the
  179429. * original source data arrays). The caller will need to pass this value
  179430. * to jpeg_write_coefficients().
  179431. */
  179432. GLOBAL(jvirt_barray_ptr *)
  179433. jtransform_adjust_parameters (j_decompress_ptr,
  179434. j_compress_ptr dstinfo,
  179435. jvirt_barray_ptr *src_coef_arrays,
  179436. jpeg_transform_info *info)
  179437. {
  179438. /* If force-to-grayscale is requested, adjust destination parameters */
  179439. if (info->force_grayscale) {
  179440. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179441. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179442. * will get set to 1, which typically won't match the source.
  179443. * In fact we do this even if the source is already grayscale; that
  179444. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179445. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179446. */
  179447. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179448. dstinfo->num_components == 3) ||
  179449. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179450. dstinfo->num_components == 1)) {
  179451. /* We have to preserve the source's quantization table number. */
  179452. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179453. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179454. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179455. } else {
  179456. /* Sorry, can't do it */
  179457. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179458. }
  179459. }
  179460. /* Correct the destination's image dimensions etc if necessary */
  179461. switch (info->transform) {
  179462. case JXFORM_NONE:
  179463. /* Nothing to do */
  179464. break;
  179465. case JXFORM_FLIP_H:
  179466. if (info->trim)
  179467. trim_right_edge(dstinfo);
  179468. break;
  179469. case JXFORM_FLIP_V:
  179470. if (info->trim)
  179471. trim_bottom_edge(dstinfo);
  179472. break;
  179473. case JXFORM_TRANSPOSE:
  179474. transpose_critical_parameters(dstinfo);
  179475. /* transpose does NOT have to trim anything */
  179476. break;
  179477. case JXFORM_TRANSVERSE:
  179478. transpose_critical_parameters(dstinfo);
  179479. if (info->trim) {
  179480. trim_right_edge(dstinfo);
  179481. trim_bottom_edge(dstinfo);
  179482. }
  179483. break;
  179484. case JXFORM_ROT_90:
  179485. transpose_critical_parameters(dstinfo);
  179486. if (info->trim)
  179487. trim_right_edge(dstinfo);
  179488. break;
  179489. case JXFORM_ROT_180:
  179490. if (info->trim) {
  179491. trim_right_edge(dstinfo);
  179492. trim_bottom_edge(dstinfo);
  179493. }
  179494. break;
  179495. case JXFORM_ROT_270:
  179496. transpose_critical_parameters(dstinfo);
  179497. if (info->trim)
  179498. trim_bottom_edge(dstinfo);
  179499. break;
  179500. }
  179501. /* Return the appropriate output data set */
  179502. if (info->workspace_coef_arrays != NULL)
  179503. return info->workspace_coef_arrays;
  179504. return src_coef_arrays;
  179505. }
  179506. /* Execute the actual transformation, if any.
  179507. *
  179508. * This must be called *after* jpeg_write_coefficients, because it depends
  179509. * on jpeg_write_coefficients to have computed subsidiary values such as
  179510. * the per-component width and height fields in the destination object.
  179511. *
  179512. * Note that some transformations will modify the source data arrays!
  179513. */
  179514. GLOBAL(void)
  179515. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179516. j_compress_ptr dstinfo,
  179517. jvirt_barray_ptr *src_coef_arrays,
  179518. jpeg_transform_info *info)
  179519. {
  179520. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179521. switch (info->transform) {
  179522. case JXFORM_NONE:
  179523. break;
  179524. case JXFORM_FLIP_H:
  179525. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179526. break;
  179527. case JXFORM_FLIP_V:
  179528. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179529. break;
  179530. case JXFORM_TRANSPOSE:
  179531. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179532. break;
  179533. case JXFORM_TRANSVERSE:
  179534. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179535. break;
  179536. case JXFORM_ROT_90:
  179537. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179538. break;
  179539. case JXFORM_ROT_180:
  179540. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179541. break;
  179542. case JXFORM_ROT_270:
  179543. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179544. break;
  179545. }
  179546. }
  179547. #endif /* TRANSFORMS_SUPPORTED */
  179548. /* Setup decompression object to save desired markers in memory.
  179549. * This must be called before jpeg_read_header() to have the desired effect.
  179550. */
  179551. GLOBAL(void)
  179552. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179553. {
  179554. #ifdef SAVE_MARKERS_SUPPORTED
  179555. int m;
  179556. /* Save comments except under NONE option */
  179557. if (option != JCOPYOPT_NONE) {
  179558. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179559. }
  179560. /* Save all types of APPn markers iff ALL option */
  179561. if (option == JCOPYOPT_ALL) {
  179562. for (m = 0; m < 16; m++)
  179563. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179564. }
  179565. #endif /* SAVE_MARKERS_SUPPORTED */
  179566. }
  179567. /* Copy markers saved in the given source object to the destination object.
  179568. * This should be called just after jpeg_start_compress() or
  179569. * jpeg_write_coefficients().
  179570. * Note that those routines will have written the SOI, and also the
  179571. * JFIF APP0 or Adobe APP14 markers if selected.
  179572. */
  179573. GLOBAL(void)
  179574. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179575. JCOPY_OPTION)
  179576. {
  179577. jpeg_saved_marker_ptr marker;
  179578. /* In the current implementation, we don't actually need to examine the
  179579. * option flag here; we just copy everything that got saved.
  179580. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179581. * if the encoder library already wrote one.
  179582. */
  179583. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179584. if (dstinfo->write_JFIF_header &&
  179585. marker->marker == JPEG_APP0 &&
  179586. marker->data_length >= 5 &&
  179587. GETJOCTET(marker->data[0]) == 0x4A &&
  179588. GETJOCTET(marker->data[1]) == 0x46 &&
  179589. GETJOCTET(marker->data[2]) == 0x49 &&
  179590. GETJOCTET(marker->data[3]) == 0x46 &&
  179591. GETJOCTET(marker->data[4]) == 0)
  179592. continue; /* reject duplicate JFIF */
  179593. if (dstinfo->write_Adobe_marker &&
  179594. marker->marker == JPEG_APP0+14 &&
  179595. marker->data_length >= 5 &&
  179596. GETJOCTET(marker->data[0]) == 0x41 &&
  179597. GETJOCTET(marker->data[1]) == 0x64 &&
  179598. GETJOCTET(marker->data[2]) == 0x6F &&
  179599. GETJOCTET(marker->data[3]) == 0x62 &&
  179600. GETJOCTET(marker->data[4]) == 0x65)
  179601. continue; /* reject duplicate Adobe */
  179602. #ifdef NEED_FAR_POINTERS
  179603. /* We could use jpeg_write_marker if the data weren't FAR... */
  179604. {
  179605. unsigned int i;
  179606. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179607. for (i = 0; i < marker->data_length; i++)
  179608. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179609. }
  179610. #else
  179611. jpeg_write_marker(dstinfo, marker->marker,
  179612. marker->data, marker->data_length);
  179613. #endif
  179614. }
  179615. }
  179616. /*** End of inlined file: transupp.c ***/
  179617. #else
  179618. #define JPEG_INTERNALS
  179619. #undef FAR
  179620. #include <jpeglib.h>
  179621. #endif
  179622. }
  179623. #undef max
  179624. #undef min
  179625. #if JUCE_MSVC
  179626. #pragma warning (pop)
  179627. #endif
  179628. BEGIN_JUCE_NAMESPACE
  179629. namespace JPEGHelpers
  179630. {
  179631. using namespace jpeglibNamespace;
  179632. #if ! JUCE_MSVC
  179633. using jpeglibNamespace::boolean;
  179634. #endif
  179635. struct JPEGDecodingFailure {};
  179636. void fatalErrorHandler (j_common_ptr)
  179637. {
  179638. throw JPEGDecodingFailure();
  179639. }
  179640. void silentErrorCallback1 (j_common_ptr) {}
  179641. void silentErrorCallback2 (j_common_ptr, int) {}
  179642. void silentErrorCallback3 (j_common_ptr, char*) {}
  179643. void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179644. {
  179645. zerostruct (err);
  179646. err.error_exit = fatalErrorHandler;
  179647. err.emit_message = silentErrorCallback2;
  179648. err.output_message = silentErrorCallback1;
  179649. err.format_message = silentErrorCallback3;
  179650. err.reset_error_mgr = silentErrorCallback1;
  179651. }
  179652. void dummyCallback1 (j_decompress_ptr)
  179653. {
  179654. }
  179655. void jpegSkip (j_decompress_ptr decompStruct, long num)
  179656. {
  179657. decompStruct->src->next_input_byte += num;
  179658. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179659. decompStruct->src->bytes_in_buffer -= num;
  179660. }
  179661. boolean jpegFill (j_decompress_ptr)
  179662. {
  179663. return 0;
  179664. }
  179665. const int jpegBufferSize = 512;
  179666. struct JuceJpegDest : public jpeg_destination_mgr
  179667. {
  179668. OutputStream* output;
  179669. char* buffer;
  179670. };
  179671. void jpegWriteInit (j_compress_ptr)
  179672. {
  179673. }
  179674. void jpegWriteTerminate (j_compress_ptr cinfo)
  179675. {
  179676. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179677. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  179678. dest->output->write (dest->buffer, (int) numToWrite);
  179679. }
  179680. boolean jpegWriteFlush (j_compress_ptr cinfo)
  179681. {
  179682. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  179683. const int numToWrite = jpegBufferSize;
  179684. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  179685. dest->free_in_buffer = jpegBufferSize;
  179686. return dest->output->write (dest->buffer, numToWrite);
  179687. }
  179688. }
  179689. JPEGImageFormat::JPEGImageFormat()
  179690. : quality (-1.0f)
  179691. {
  179692. }
  179693. JPEGImageFormat::~JPEGImageFormat() {}
  179694. void JPEGImageFormat::setQuality (const float newQuality)
  179695. {
  179696. quality = newQuality;
  179697. }
  179698. const String JPEGImageFormat::getFormatName()
  179699. {
  179700. return "JPEG";
  179701. }
  179702. bool JPEGImageFormat::canUnderstand (InputStream& in)
  179703. {
  179704. const int bytesNeeded = 10;
  179705. uint8 header [bytesNeeded];
  179706. if (in.read (header, bytesNeeded) == bytesNeeded)
  179707. {
  179708. return header[0] == 0xff
  179709. && header[1] == 0xd8
  179710. && header[2] == 0xff
  179711. && (header[3] == 0xe0 || header[3] == 0xe1);
  179712. }
  179713. return false;
  179714. }
  179715. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179716. const Image juce_loadWithCoreImage (InputStream& input);
  179717. #endif
  179718. const Image JPEGImageFormat::decodeImage (InputStream& in)
  179719. {
  179720. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  179721. return juce_loadWithCoreImage (in);
  179722. #else
  179723. using namespace jpeglibNamespace;
  179724. using namespace JPEGHelpers;
  179725. MemoryOutputStream mb;
  179726. mb.writeFromInputStream (in, -1);
  179727. Image image;
  179728. if (mb.getDataSize() > 16)
  179729. {
  179730. struct jpeg_decompress_struct jpegDecompStruct;
  179731. struct jpeg_error_mgr jerr;
  179732. setupSilentErrorHandler (jerr);
  179733. jpegDecompStruct.err = &jerr;
  179734. jpeg_create_decompress (&jpegDecompStruct);
  179735. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  179736. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  179737. jpegDecompStruct.src->init_source = dummyCallback1;
  179738. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  179739. jpegDecompStruct.src->skip_input_data = jpegSkip;
  179740. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  179741. jpegDecompStruct.src->term_source = dummyCallback1;
  179742. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  179743. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  179744. try
  179745. {
  179746. jpeg_read_header (&jpegDecompStruct, TRUE);
  179747. jpeg_calc_output_dimensions (&jpegDecompStruct);
  179748. const int width = jpegDecompStruct.output_width;
  179749. const int height = jpegDecompStruct.output_height;
  179750. jpegDecompStruct.out_color_space = JCS_RGB;
  179751. JSAMPARRAY buffer
  179752. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  179753. JPOOL_IMAGE,
  179754. width * 3, 1);
  179755. if (jpeg_start_decompress (&jpegDecompStruct))
  179756. {
  179757. image = Image (Image::RGB, width, height, false);
  179758. image.getProperties()->set ("originalImageHadAlpha", false);
  179759. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  179760. const Image::BitmapData destData (image, true);
  179761. for (int y = 0; y < height; ++y)
  179762. {
  179763. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  179764. const uint8* src = *buffer;
  179765. uint8* dest = destData.getLinePointer (y);
  179766. if (hasAlphaChan)
  179767. {
  179768. for (int i = width; --i >= 0;)
  179769. {
  179770. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179771. ((PixelARGB*) dest)->premultiply();
  179772. dest += destData.pixelStride;
  179773. src += 3;
  179774. }
  179775. }
  179776. else
  179777. {
  179778. for (int i = width; --i >= 0;)
  179779. {
  179780. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  179781. dest += destData.pixelStride;
  179782. src += 3;
  179783. }
  179784. }
  179785. }
  179786. jpeg_finish_decompress (&jpegDecompStruct);
  179787. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  179788. }
  179789. jpeg_destroy_decompress (&jpegDecompStruct);
  179790. }
  179791. catch (...)
  179792. {}
  179793. }
  179794. return image;
  179795. #endif
  179796. }
  179797. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  179798. {
  179799. using namespace jpeglibNamespace;
  179800. using namespace JPEGHelpers;
  179801. if (image.hasAlphaChannel())
  179802. {
  179803. // this method could fill the background in white and still save the image..
  179804. jassertfalse;
  179805. return true;
  179806. }
  179807. struct jpeg_compress_struct jpegCompStruct;
  179808. struct jpeg_error_mgr jerr;
  179809. setupSilentErrorHandler (jerr);
  179810. jpegCompStruct.err = &jerr;
  179811. jpeg_create_compress (&jpegCompStruct);
  179812. JuceJpegDest dest;
  179813. jpegCompStruct.dest = &dest;
  179814. dest.output = &out;
  179815. HeapBlock <char> tempBuffer (jpegBufferSize);
  179816. dest.buffer = tempBuffer;
  179817. dest.next_output_byte = (JOCTET*) dest.buffer;
  179818. dest.free_in_buffer = jpegBufferSize;
  179819. dest.init_destination = jpegWriteInit;
  179820. dest.empty_output_buffer = jpegWriteFlush;
  179821. dest.term_destination = jpegWriteTerminate;
  179822. jpegCompStruct.image_width = image.getWidth();
  179823. jpegCompStruct.image_height = image.getHeight();
  179824. jpegCompStruct.input_components = 3;
  179825. jpegCompStruct.in_color_space = JCS_RGB;
  179826. jpegCompStruct.write_JFIF_header = 1;
  179827. jpegCompStruct.X_density = 72;
  179828. jpegCompStruct.Y_density = 72;
  179829. jpeg_set_defaults (&jpegCompStruct);
  179830. jpegCompStruct.dct_method = JDCT_FLOAT;
  179831. jpegCompStruct.optimize_coding = 1;
  179832. //jpegCompStruct.smoothing_factor = 10;
  179833. if (quality < 0.0f)
  179834. quality = 0.85f;
  179835. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  179836. jpeg_start_compress (&jpegCompStruct, TRUE);
  179837. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  179838. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  179839. JPOOL_IMAGE, strideBytes, 1);
  179840. const Image::BitmapData srcData (image, false);
  179841. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  179842. {
  179843. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  179844. uint8* dst = *buffer;
  179845. for (int i = jpegCompStruct.image_width; --i >= 0;)
  179846. {
  179847. *dst++ = ((const PixelRGB*) src)->getRed();
  179848. *dst++ = ((const PixelRGB*) src)->getGreen();
  179849. *dst++ = ((const PixelRGB*) src)->getBlue();
  179850. src += srcData.pixelStride;
  179851. }
  179852. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  179853. }
  179854. jpeg_finish_compress (&jpegCompStruct);
  179855. jpeg_destroy_compress (&jpegCompStruct);
  179856. out.flush();
  179857. return true;
  179858. }
  179859. END_JUCE_NAMESPACE
  179860. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  179861. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  179862. #if JUCE_MSVC
  179863. #pragma warning (push)
  179864. #pragma warning (disable: 4390 4611)
  179865. #ifdef __INTEL_COMPILER
  179866. #pragma warning (disable: 2544 2545)
  179867. #endif
  179868. #endif
  179869. namespace zlibNamespace
  179870. {
  179871. #if JUCE_INCLUDE_ZLIB_CODE
  179872. #undef OS_CODE
  179873. #undef fdopen
  179874. #undef OS_CODE
  179875. #else
  179876. #include <zlib.h>
  179877. #endif
  179878. }
  179879. namespace pnglibNamespace
  179880. {
  179881. using namespace zlibNamespace;
  179882. #if JUCE_INCLUDE_PNGLIB_CODE
  179883. #if _MSC_VER != 1310
  179884. using ::calloc; // (causes conflict in VS.NET 2003)
  179885. using ::malloc;
  179886. using ::free;
  179887. #endif
  179888. using ::abs;
  179889. #define PNG_INTERNAL
  179890. #define NO_DUMMY_DECL
  179891. #define PNG_SETJMP_NOT_SUPPORTED
  179892. /*** Start of inlined file: png.h ***/
  179893. /* png.h - header file for PNG reference library
  179894. *
  179895. * libpng version 1.2.21 - October 4, 2007
  179896. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  179897. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179898. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179899. *
  179900. * Authors and maintainers:
  179901. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  179902. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  179903. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  179904. * See also "Contributing Authors", below.
  179905. *
  179906. * Note about libpng version numbers:
  179907. *
  179908. * Due to various miscommunications, unforeseen code incompatibilities
  179909. * and occasional factors outside the authors' control, version numbering
  179910. * on the library has not always been consistent and straightforward.
  179911. * The following table summarizes matters since version 0.89c, which was
  179912. * the first widely used release:
  179913. *
  179914. * source png.h png.h shared-lib
  179915. * version string int version
  179916. * ------- ------ ----- ----------
  179917. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  179918. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  179919. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  179920. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  179921. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  179922. * 0.97c 0.97 97 2.0.97
  179923. * 0.98 0.98 98 2.0.98
  179924. * 0.99 0.99 98 2.0.99
  179925. * 0.99a-m 0.99 99 2.0.99
  179926. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  179927. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  179928. * 1.0.1 png.h string is 10001 2.1.0
  179929. * 1.0.1a-e identical to the 10002 from here on, the shared library
  179930. * 1.0.2 source version) 10002 is 2.V where V is the source code
  179931. * 1.0.2a-b 10003 version, except as noted.
  179932. * 1.0.3 10003
  179933. * 1.0.3a-d 10004
  179934. * 1.0.4 10004
  179935. * 1.0.4a-f 10005
  179936. * 1.0.5 (+ 2 patches) 10005
  179937. * 1.0.5a-d 10006
  179938. * 1.0.5e-r 10100 (not source compatible)
  179939. * 1.0.5s-v 10006 (not binary compatible)
  179940. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  179941. * 1.0.6d-f 10007 (still binary incompatible)
  179942. * 1.0.6g 10007
  179943. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  179944. * 1.0.6i 10007 10.6i
  179945. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  179946. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  179947. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  179948. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  179949. * 1.0.7 1 10007 (still compatible)
  179950. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  179951. * 1.0.8rc1 1 10008 2.1.0.8rc1
  179952. * 1.0.8 1 10008 2.1.0.8
  179953. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  179954. * 1.0.9rc1 1 10009 2.1.0.9rc1
  179955. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  179956. * 1.0.9rc2 1 10009 2.1.0.9rc2
  179957. * 1.0.9 1 10009 2.1.0.9
  179958. * 1.0.10beta1 1 10010 2.1.0.10beta1
  179959. * 1.0.10rc1 1 10010 2.1.0.10rc1
  179960. * 1.0.10 1 10010 2.1.0.10
  179961. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  179962. * 1.0.11rc1 1 10011 2.1.0.11rc1
  179963. * 1.0.11 1 10011 2.1.0.11
  179964. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  179965. * 1.0.12rc1 2 10012 2.1.0.12rc1
  179966. * 1.0.12 2 10012 2.1.0.12
  179967. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  179968. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  179969. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  179970. * 1.2.0rc1 3 10200 3.1.2.0rc1
  179971. * 1.2.0 3 10200 3.1.2.0
  179972. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  179973. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  179974. * 1.2.1 3 10201 3.1.2.1
  179975. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  179976. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  179977. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  179978. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  179979. * 1.0.13 10 10013 10.so.0.1.0.13
  179980. * 1.2.2 12 10202 12.so.0.1.2.2
  179981. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  179982. * 1.2.3 12 10203 12.so.0.1.2.3
  179983. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  179984. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  179985. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  179986. * 1.0.14 10 10014 10.so.0.1.0.14
  179987. * 1.2.4 13 10204 12.so.0.1.2.4
  179988. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  179989. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  179990. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  179991. * 1.0.15 10 10015 10.so.0.1.0.15
  179992. * 1.2.5 13 10205 12.so.0.1.2.5
  179993. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  179994. * 1.0.16 10 10016 10.so.0.1.0.16
  179995. * 1.2.6 13 10206 12.so.0.1.2.6
  179996. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  179997. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  179998. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  179999. * 1.0.17 10 10017 10.so.0.1.0.17
  180000. * 1.2.7 13 10207 12.so.0.1.2.7
  180001. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180002. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180003. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180004. * 1.0.18 10 10018 10.so.0.1.0.18
  180005. * 1.2.8 13 10208 12.so.0.1.2.8
  180006. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180007. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180008. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180009. * 1.2.9 13 10209 12.so.0.9[.0]
  180010. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180011. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180012. * 1.2.10 13 10210 12.so.0.10[.0]
  180013. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180014. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180015. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180016. * 1.0.19 10 10019 10.so.0.19[.0]
  180017. * 1.2.11 13 10211 12.so.0.11[.0]
  180018. * 1.0.20 10 10020 10.so.0.20[.0]
  180019. * 1.2.12 13 10212 12.so.0.12[.0]
  180020. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180021. * 1.0.21 10 10021 10.so.0.21[.0]
  180022. * 1.2.13 13 10213 12.so.0.13[.0]
  180023. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180024. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180025. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180026. * 1.0.22 10 10022 10.so.0.22[.0]
  180027. * 1.2.14 13 10214 12.so.0.14[.0]
  180028. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180029. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180030. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180031. * 1.0.23 10 10023 10.so.0.23[.0]
  180032. * 1.2.15 13 10215 12.so.0.15[.0]
  180033. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180034. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180035. * 1.0.24 10 10024 10.so.0.24[.0]
  180036. * 1.2.16 13 10216 12.so.0.16[.0]
  180037. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180038. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180039. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180040. * 1.0.25 10 10025 10.so.0.25[.0]
  180041. * 1.2.17 13 10217 12.so.0.17[.0]
  180042. * 1.0.26 10 10026 10.so.0.26[.0]
  180043. * 1.2.18 13 10218 12.so.0.18[.0]
  180044. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180045. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180046. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180047. * 1.0.27 10 10027 10.so.0.27[.0]
  180048. * 1.2.19 13 10219 12.so.0.19[.0]
  180049. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180050. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180051. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180052. * 1.0.28 10 10028 10.so.0.28[.0]
  180053. * 1.2.20 13 10220 12.so.0.20[.0]
  180054. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180055. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180056. * 1.0.29 10 10029 10.so.0.29[.0]
  180057. * 1.2.21 13 10221 12.so.0.21[.0]
  180058. *
  180059. * Henceforth the source version will match the shared-library major
  180060. * and minor numbers; the shared-library major version number will be
  180061. * used for changes in backward compatibility, as it is intended. The
  180062. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180063. * for applications, is an unsigned integer of the form xyyzz corresponding
  180064. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180065. * were given the previous public release number plus a letter, until
  180066. * version 1.0.6j; from then on they were given the upcoming public
  180067. * release number plus "betaNN" or "rcN".
  180068. *
  180069. * Binary incompatibility exists only when applications make direct access
  180070. * to the info_ptr or png_ptr members through png.h, and the compiled
  180071. * application is loaded with a different version of the library.
  180072. *
  180073. * DLLNUM will change each time there are forward or backward changes
  180074. * in binary compatibility (e.g., when a new feature is added).
  180075. *
  180076. * See libpng.txt or libpng.3 for more information. The PNG specification
  180077. * is available as a W3C Recommendation and as an ISO Specification,
  180078. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180079. */
  180080. /*
  180081. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180082. *
  180083. * If you modify libpng you may insert additional notices immediately following
  180084. * this sentence.
  180085. *
  180086. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180087. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180088. * distributed according to the same disclaimer and license as libpng-1.2.5
  180089. * with the following individual added to the list of Contributing Authors:
  180090. *
  180091. * Cosmin Truta
  180092. *
  180093. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180094. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180095. * distributed according to the same disclaimer and license as libpng-1.0.6
  180096. * with the following individuals added to the list of Contributing Authors:
  180097. *
  180098. * Simon-Pierre Cadieux
  180099. * Eric S. Raymond
  180100. * Gilles Vollant
  180101. *
  180102. * and with the following additions to the disclaimer:
  180103. *
  180104. * There is no warranty against interference with your enjoyment of the
  180105. * library or against infringement. There is no warranty that our
  180106. * efforts or the library will fulfill any of your particular purposes
  180107. * or needs. This library is provided with all faults, and the entire
  180108. * risk of satisfactory quality, performance, accuracy, and effort is with
  180109. * the user.
  180110. *
  180111. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180112. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180113. * distributed according to the same disclaimer and license as libpng-0.96,
  180114. * with the following individuals added to the list of Contributing Authors:
  180115. *
  180116. * Tom Lane
  180117. * Glenn Randers-Pehrson
  180118. * Willem van Schaik
  180119. *
  180120. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180121. * Copyright (c) 1996, 1997 Andreas Dilger
  180122. * Distributed according to the same disclaimer and license as libpng-0.88,
  180123. * with the following individuals added to the list of Contributing Authors:
  180124. *
  180125. * John Bowler
  180126. * Kevin Bracey
  180127. * Sam Bushell
  180128. * Magnus Holmgren
  180129. * Greg Roelofs
  180130. * Tom Tanner
  180131. *
  180132. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180133. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180134. *
  180135. * For the purposes of this copyright and license, "Contributing Authors"
  180136. * is defined as the following set of individuals:
  180137. *
  180138. * Andreas Dilger
  180139. * Dave Martindale
  180140. * Guy Eric Schalnat
  180141. * Paul Schmidt
  180142. * Tim Wegner
  180143. *
  180144. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180145. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180146. * including, without limitation, the warranties of merchantability and of
  180147. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180148. * assume no liability for direct, indirect, incidental, special, exemplary,
  180149. * or consequential damages, which may result from the use of the PNG
  180150. * Reference Library, even if advised of the possibility of such damage.
  180151. *
  180152. * Permission is hereby granted to use, copy, modify, and distribute this
  180153. * source code, or portions hereof, for any purpose, without fee, subject
  180154. * to the following restrictions:
  180155. *
  180156. * 1. The origin of this source code must not be misrepresented.
  180157. *
  180158. * 2. Altered versions must be plainly marked as such and
  180159. * must not be misrepresented as being the original source.
  180160. *
  180161. * 3. This Copyright notice may not be removed or altered from
  180162. * any source or altered source distribution.
  180163. *
  180164. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180165. * fee, and encourage the use of this source code as a component to
  180166. * supporting the PNG file format in commercial products. If you use this
  180167. * source code in a product, acknowledgment is not required but would be
  180168. * appreciated.
  180169. */
  180170. /*
  180171. * A "png_get_copyright" function is available, for convenient use in "about"
  180172. * boxes and the like:
  180173. *
  180174. * printf("%s",png_get_copyright(NULL));
  180175. *
  180176. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180177. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180178. */
  180179. /*
  180180. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180181. * certification mark of the Open Source Initiative.
  180182. */
  180183. /*
  180184. * The contributing authors would like to thank all those who helped
  180185. * with testing, bug fixes, and patience. This wouldn't have been
  180186. * possible without all of you.
  180187. *
  180188. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180189. */
  180190. /*
  180191. * Y2K compliance in libpng:
  180192. * =========================
  180193. *
  180194. * October 4, 2007
  180195. *
  180196. * Since the PNG Development group is an ad-hoc body, we can't make
  180197. * an official declaration.
  180198. *
  180199. * This is your unofficial assurance that libpng from version 0.71 and
  180200. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180201. * versions were also Y2K compliant.
  180202. *
  180203. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180204. * that will hold years up to 65535. The other two hold the date in text
  180205. * format, and will hold years up to 9999.
  180206. *
  180207. * The integer is
  180208. * "png_uint_16 year" in png_time_struct.
  180209. *
  180210. * The strings are
  180211. * "png_charp time_buffer" in png_struct and
  180212. * "near_time_buffer", which is a local character string in png.c.
  180213. *
  180214. * There are seven time-related functions:
  180215. * png.c: png_convert_to_rfc_1123() in png.c
  180216. * (formerly png_convert_to_rfc_1152() in error)
  180217. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180218. * png_convert_from_time_t() in pngwrite.c
  180219. * png_get_tIME() in pngget.c
  180220. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180221. * png_set_tIME() in pngset.c
  180222. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180223. *
  180224. * All handle dates properly in a Y2K environment. The
  180225. * png_convert_from_time_t() function calls gmtime() to convert from system
  180226. * clock time, which returns (year - 1900), which we properly convert to
  180227. * the full 4-digit year. There is a possibility that applications using
  180228. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180229. * function, or that they are incorrectly passing only a 2-digit year
  180230. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180231. * but this is not under our control. The libpng documentation has always
  180232. * stated that it works with 4-digit years, and the APIs have been
  180233. * documented as such.
  180234. *
  180235. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180236. * integer to hold the year, and can hold years as large as 65535.
  180237. *
  180238. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180239. * no date-related code.
  180240. *
  180241. * Glenn Randers-Pehrson
  180242. * libpng maintainer
  180243. * PNG Development Group
  180244. */
  180245. #ifndef PNG_H
  180246. #define PNG_H
  180247. /* This is not the place to learn how to use libpng. The file libpng.txt
  180248. * describes how to use libpng, and the file example.c summarizes it
  180249. * with some code on which to build. This file is useful for looking
  180250. * at the actual function definitions and structure components.
  180251. */
  180252. /* Version information for png.h - this should match the version in png.c */
  180253. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180254. #define PNG_HEADER_VERSION_STRING \
  180255. " libpng version 1.2.21 - October 4, 2007\n"
  180256. #define PNG_LIBPNG_VER_SONUM 0
  180257. #define PNG_LIBPNG_VER_DLLNUM 13
  180258. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180259. #define PNG_LIBPNG_VER_MAJOR 1
  180260. #define PNG_LIBPNG_VER_MINOR 2
  180261. #define PNG_LIBPNG_VER_RELEASE 21
  180262. /* This should match the numeric part of the final component of
  180263. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180264. #define PNG_LIBPNG_VER_BUILD 0
  180265. /* Release Status */
  180266. #define PNG_LIBPNG_BUILD_ALPHA 1
  180267. #define PNG_LIBPNG_BUILD_BETA 2
  180268. #define PNG_LIBPNG_BUILD_RC 3
  180269. #define PNG_LIBPNG_BUILD_STABLE 4
  180270. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180271. /* Release-Specific Flags */
  180272. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180273. PNG_LIBPNG_BUILD_STABLE only */
  180274. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180275. PNG_LIBPNG_BUILD_SPECIAL */
  180276. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180277. PNG_LIBPNG_BUILD_PRIVATE */
  180278. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180279. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180280. * We must not include leading zeros.
  180281. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180282. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180283. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180284. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180285. #ifndef PNG_VERSION_INFO_ONLY
  180286. /* include the compression library's header */
  180287. #endif
  180288. /* include all user configurable info, including optional assembler routines */
  180289. /*** Start of inlined file: pngconf.h ***/
  180290. /* pngconf.h - machine configurable file for libpng
  180291. *
  180292. * libpng version 1.2.21 - October 4, 2007
  180293. * For conditions of distribution and use, see copyright notice in png.h
  180294. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180295. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180296. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180297. */
  180298. /* Any machine specific code is near the front of this file, so if you
  180299. * are configuring libpng for a machine, you may want to read the section
  180300. * starting here down to where it starts to typedef png_color, png_text,
  180301. * and png_info.
  180302. */
  180303. #ifndef PNGCONF_H
  180304. #define PNGCONF_H
  180305. #define PNG_1_2_X
  180306. // These are some Juce config settings that should remove any unnecessary code bloat..
  180307. #define PNG_NO_STDIO 1
  180308. #define PNG_DEBUG 0
  180309. #define PNG_NO_WARNINGS 1
  180310. #define PNG_NO_ERROR_TEXT 1
  180311. #define PNG_NO_ERROR_NUMBERS 1
  180312. #define PNG_NO_USER_MEM 1
  180313. #define PNG_NO_READ_iCCP 1
  180314. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180315. #define PNG_NO_READ_USER_CHUNKS 1
  180316. #define PNG_NO_READ_iTXt 1
  180317. #define PNG_NO_READ_sCAL 1
  180318. #define PNG_NO_READ_sPLT 1
  180319. #define png_error(a, b) png_err(a)
  180320. #define png_warning(a, b)
  180321. #define png_chunk_error(a, b) png_err(a)
  180322. #define png_chunk_warning(a, b)
  180323. /*
  180324. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180325. * includes the resource compiler for Windows DLL configurations.
  180326. */
  180327. #ifdef PNG_USER_CONFIG
  180328. # ifndef PNG_USER_PRIVATEBUILD
  180329. # define PNG_USER_PRIVATEBUILD
  180330. # endif
  180331. #include "pngusr.h"
  180332. #endif
  180333. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180334. #ifdef PNG_CONFIGURE_LIBPNG
  180335. #ifdef HAVE_CONFIG_H
  180336. #include "config.h"
  180337. #endif
  180338. #endif
  180339. /*
  180340. * Added at libpng-1.2.8
  180341. *
  180342. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180343. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180344. * the DLL was built>
  180345. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180346. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180347. * distinguish your DLL from those of the official release. These
  180348. * correspond to the trailing letters that come after the version
  180349. * number and must match your private DLL name>
  180350. * e.g. // private DLL "libpng13gx.dll"
  180351. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180352. *
  180353. * The following macros are also at your disposal if you want to complete the
  180354. * DLL VERSIONINFO structure.
  180355. * - PNG_USER_VERSIONINFO_COMMENTS
  180356. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180357. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180358. */
  180359. #ifdef __STDC__
  180360. #ifdef SPECIALBUILD
  180361. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180362. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180363. #endif
  180364. #ifdef PRIVATEBUILD
  180365. # pragma message("PRIVATEBUILD is deprecated.\
  180366. Use PNG_USER_PRIVATEBUILD instead.")
  180367. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180368. #endif
  180369. #endif /* __STDC__ */
  180370. #ifndef PNG_VERSION_INFO_ONLY
  180371. /* End of material added to libpng-1.2.8 */
  180372. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180373. Restored at libpng-1.2.21 */
  180374. # define PNG_WARN_UNINITIALIZED_ROW 1
  180375. /* End of material added at libpng-1.2.19/1.2.21 */
  180376. /* This is the size of the compression buffer, and thus the size of
  180377. * an IDAT chunk. Make this whatever size you feel is best for your
  180378. * machine. One of these will be allocated per png_struct. When this
  180379. * is full, it writes the data to the disk, and does some other
  180380. * calculations. Making this an extremely small size will slow
  180381. * the library down, but you may want to experiment to determine
  180382. * where it becomes significant, if you are concerned with memory
  180383. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180384. * this describes the size of the buffer available to read the data in.
  180385. * Unless this gets smaller than the size of a row (compressed),
  180386. * it should not make much difference how big this is.
  180387. */
  180388. #ifndef PNG_ZBUF_SIZE
  180389. # define PNG_ZBUF_SIZE 8192
  180390. #endif
  180391. /* Enable if you want a write-only libpng */
  180392. #ifndef PNG_NO_READ_SUPPORTED
  180393. # define PNG_READ_SUPPORTED
  180394. #endif
  180395. /* Enable if you want a read-only libpng */
  180396. #ifndef PNG_NO_WRITE_SUPPORTED
  180397. # define PNG_WRITE_SUPPORTED
  180398. #endif
  180399. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180400. support PNGs that are embedded in MNG datastreams */
  180401. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180402. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180403. # define PNG_MNG_FEATURES_SUPPORTED
  180404. # endif
  180405. #endif
  180406. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180407. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180408. # define PNG_FLOATING_POINT_SUPPORTED
  180409. # endif
  180410. #endif
  180411. /* If you are running on a machine where you cannot allocate more
  180412. * than 64K of memory at once, uncomment this. While libpng will not
  180413. * normally need that much memory in a chunk (unless you load up a very
  180414. * large file), zlib needs to know how big of a chunk it can use, and
  180415. * libpng thus makes sure to check any memory allocation to verify it
  180416. * will fit into memory.
  180417. #define PNG_MAX_MALLOC_64K
  180418. */
  180419. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180420. # define PNG_MAX_MALLOC_64K
  180421. #endif
  180422. /* Special munging to support doing things the 'cygwin' way:
  180423. * 'Normal' png-on-win32 defines/defaults:
  180424. * PNG_BUILD_DLL -- building dll
  180425. * PNG_USE_DLL -- building an application, linking to dll
  180426. * (no define) -- building static library, or building an
  180427. * application and linking to the static lib
  180428. * 'Cygwin' defines/defaults:
  180429. * PNG_BUILD_DLL -- (ignored) building the dll
  180430. * (no define) -- (ignored) building an application, linking to the dll
  180431. * PNG_STATIC -- (ignored) building the static lib, or building an
  180432. * application that links to the static lib.
  180433. * ALL_STATIC -- (ignored) building various static libs, or building an
  180434. * application that links to the static libs.
  180435. * Thus,
  180436. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180437. * this bit of #ifdefs will define the 'correct' config variables based on
  180438. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180439. * unnecessary.
  180440. *
  180441. * Also, the precedence order is:
  180442. * ALL_STATIC (since we can't #undef something outside our namespace)
  180443. * PNG_BUILD_DLL
  180444. * PNG_STATIC
  180445. * (nothing) == PNG_USE_DLL
  180446. *
  180447. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180448. * of auto-import in binutils, we no longer need to worry about
  180449. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180450. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180451. * to __declspec() stuff. However, we DO need to worry about
  180452. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180453. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180454. */
  180455. #if defined(__CYGWIN__)
  180456. # if defined(ALL_STATIC)
  180457. # if defined(PNG_BUILD_DLL)
  180458. # undef PNG_BUILD_DLL
  180459. # endif
  180460. # if defined(PNG_USE_DLL)
  180461. # undef PNG_USE_DLL
  180462. # endif
  180463. # if defined(PNG_DLL)
  180464. # undef PNG_DLL
  180465. # endif
  180466. # if !defined(PNG_STATIC)
  180467. # define PNG_STATIC
  180468. # endif
  180469. # else
  180470. # if defined (PNG_BUILD_DLL)
  180471. # if defined(PNG_STATIC)
  180472. # undef PNG_STATIC
  180473. # endif
  180474. # if defined(PNG_USE_DLL)
  180475. # undef PNG_USE_DLL
  180476. # endif
  180477. # if !defined(PNG_DLL)
  180478. # define PNG_DLL
  180479. # endif
  180480. # else
  180481. # if defined(PNG_STATIC)
  180482. # if defined(PNG_USE_DLL)
  180483. # undef PNG_USE_DLL
  180484. # endif
  180485. # if defined(PNG_DLL)
  180486. # undef PNG_DLL
  180487. # endif
  180488. # else
  180489. # if !defined(PNG_USE_DLL)
  180490. # define PNG_USE_DLL
  180491. # endif
  180492. # if !defined(PNG_DLL)
  180493. # define PNG_DLL
  180494. # endif
  180495. # endif
  180496. # endif
  180497. # endif
  180498. #endif
  180499. /* This protects us against compilers that run on a windowing system
  180500. * and thus don't have or would rather us not use the stdio types:
  180501. * stdin, stdout, and stderr. The only one currently used is stderr
  180502. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180503. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180504. * will also prevent these, plus will prevent the entire set of stdio
  180505. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180506. * unless (PNG_DEBUG > 0) has been #defined.
  180507. *
  180508. * #define PNG_NO_CONSOLE_IO
  180509. * #define PNG_NO_STDIO
  180510. */
  180511. #if defined(_WIN32_WCE)
  180512. # include <windows.h>
  180513. /* Console I/O functions are not supported on WindowsCE */
  180514. # define PNG_NO_CONSOLE_IO
  180515. # ifdef PNG_DEBUG
  180516. # undef PNG_DEBUG
  180517. # endif
  180518. #endif
  180519. #ifdef PNG_BUILD_DLL
  180520. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180521. # ifndef PNG_NO_CONSOLE_IO
  180522. # define PNG_NO_CONSOLE_IO
  180523. # endif
  180524. # endif
  180525. #endif
  180526. # ifdef PNG_NO_STDIO
  180527. # ifndef PNG_NO_CONSOLE_IO
  180528. # define PNG_NO_CONSOLE_IO
  180529. # endif
  180530. # ifdef PNG_DEBUG
  180531. # if (PNG_DEBUG > 0)
  180532. # include <stdio.h>
  180533. # endif
  180534. # endif
  180535. # else
  180536. # if !defined(_WIN32_WCE)
  180537. /* "stdio.h" functions are not supported on WindowsCE */
  180538. # include <stdio.h>
  180539. # endif
  180540. # endif
  180541. /* This macro protects us against machines that don't have function
  180542. * prototypes (ie K&R style headers). If your compiler does not handle
  180543. * function prototypes, define this macro and use the included ansi2knr.
  180544. * I've always been able to use _NO_PROTO as the indicator, but you may
  180545. * need to drag the empty declaration out in front of here, or change the
  180546. * ifdef to suit your own needs.
  180547. */
  180548. #ifndef PNGARG
  180549. #ifdef OF /* zlib prototype munger */
  180550. # define PNGARG(arglist) OF(arglist)
  180551. #else
  180552. #ifdef _NO_PROTO
  180553. # define PNGARG(arglist) ()
  180554. # ifndef PNG_TYPECAST_NULL
  180555. # define PNG_TYPECAST_NULL
  180556. # endif
  180557. #else
  180558. # define PNGARG(arglist) arglist
  180559. #endif /* _NO_PROTO */
  180560. #endif /* OF */
  180561. #endif /* PNGARG */
  180562. /* Try to determine if we are compiling on a Mac. Note that testing for
  180563. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180564. * on non-Mac platforms.
  180565. */
  180566. #ifndef MACOS
  180567. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180568. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180569. # define MACOS
  180570. # endif
  180571. #endif
  180572. /* enough people need this for various reasons to include it here */
  180573. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180574. # include <sys/types.h>
  180575. #endif
  180576. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180577. # define PNG_SETJMP_SUPPORTED
  180578. #endif
  180579. #ifdef PNG_SETJMP_SUPPORTED
  180580. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180581. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180582. */
  180583. # ifdef __linux__
  180584. # ifdef _BSD_SOURCE
  180585. # define PNG_SAVE_BSD_SOURCE
  180586. # undef _BSD_SOURCE
  180587. # endif
  180588. # ifdef _SETJMP_H
  180589. /* If you encounter a compiler error here, see the explanation
  180590. * near the end of INSTALL.
  180591. */
  180592. __png.h__ already includes setjmp.h;
  180593. __dont__ include it again.;
  180594. # endif
  180595. # endif /* __linux__ */
  180596. /* include setjmp.h for error handling */
  180597. # include <setjmp.h>
  180598. # ifdef __linux__
  180599. # ifdef PNG_SAVE_BSD_SOURCE
  180600. # define _BSD_SOURCE
  180601. # undef PNG_SAVE_BSD_SOURCE
  180602. # endif
  180603. # endif /* __linux__ */
  180604. #endif /* PNG_SETJMP_SUPPORTED */
  180605. #ifdef BSD
  180606. #if ! JUCE_MAC
  180607. # include <strings.h>
  180608. #endif
  180609. #else
  180610. # include <string.h>
  180611. #endif
  180612. /* Other defines for things like memory and the like can go here. */
  180613. #ifdef PNG_INTERNAL
  180614. #include <stdlib.h>
  180615. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180616. * aren't usually used outside the library (as far as I know), so it is
  180617. * debatable if they should be exported at all. In the future, when it is
  180618. * possible to have run-time registry of chunk-handling functions, some of
  180619. * these will be made available again.
  180620. #define PNG_EXTERN extern
  180621. */
  180622. #define PNG_EXTERN
  180623. /* Other defines specific to compilers can go here. Try to keep
  180624. * them inside an appropriate ifdef/endif pair for portability.
  180625. */
  180626. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180627. # if defined(MACOS)
  180628. /* We need to check that <math.h> hasn't already been included earlier
  180629. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180630. * <fp.h> if possible.
  180631. */
  180632. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180633. # include <fp.h>
  180634. # endif
  180635. # else
  180636. # include <math.h>
  180637. # endif
  180638. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180639. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180640. * MATH=68881
  180641. */
  180642. # include <m68881.h>
  180643. # endif
  180644. #endif
  180645. /* Codewarrior on NT has linking problems without this. */
  180646. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180647. # define PNG_ALWAYS_EXTERN
  180648. #endif
  180649. /* This provides the non-ANSI (far) memory allocation routines. */
  180650. #if defined(__TURBOC__) && defined(__MSDOS__)
  180651. # include <mem.h>
  180652. # include <alloc.h>
  180653. #endif
  180654. /* I have no idea why is this necessary... */
  180655. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180656. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180657. # include <malloc.h>
  180658. #endif
  180659. /* This controls how fine the dithering gets. As this allocates
  180660. * a largish chunk of memory (32K), those who are not as concerned
  180661. * with dithering quality can decrease some or all of these.
  180662. */
  180663. #ifndef PNG_DITHER_RED_BITS
  180664. # define PNG_DITHER_RED_BITS 5
  180665. #endif
  180666. #ifndef PNG_DITHER_GREEN_BITS
  180667. # define PNG_DITHER_GREEN_BITS 5
  180668. #endif
  180669. #ifndef PNG_DITHER_BLUE_BITS
  180670. # define PNG_DITHER_BLUE_BITS 5
  180671. #endif
  180672. /* This controls how fine the gamma correction becomes when you
  180673. * are only interested in 8 bits anyway. Increasing this value
  180674. * results in more memory being used, and more pow() functions
  180675. * being called to fill in the gamma tables. Don't set this value
  180676. * less then 8, and even that may not work (I haven't tested it).
  180677. */
  180678. #ifndef PNG_MAX_GAMMA_8
  180679. # define PNG_MAX_GAMMA_8 11
  180680. #endif
  180681. /* This controls how much a difference in gamma we can tolerate before
  180682. * we actually start doing gamma conversion.
  180683. */
  180684. #ifndef PNG_GAMMA_THRESHOLD
  180685. # define PNG_GAMMA_THRESHOLD 0.05
  180686. #endif
  180687. #endif /* PNG_INTERNAL */
  180688. /* The following uses const char * instead of char * for error
  180689. * and warning message functions, so some compilers won't complain.
  180690. * If you do not want to use const, define PNG_NO_CONST here.
  180691. */
  180692. #ifndef PNG_NO_CONST
  180693. # define PNG_CONST const
  180694. #else
  180695. # define PNG_CONST
  180696. #endif
  180697. /* The following defines give you the ability to remove code from the
  180698. * library that you will not be using. I wish I could figure out how to
  180699. * automate this, but I can't do that without making it seriously hard
  180700. * on the users. So if you are not using an ability, change the #define
  180701. * to and #undef, and that part of the library will not be compiled. If
  180702. * your linker can't find a function, you may want to make sure the
  180703. * ability is defined here. Some of these depend upon some others being
  180704. * defined. I haven't figured out all the interactions here, so you may
  180705. * have to experiment awhile to get everything to compile. If you are
  180706. * creating or using a shared library, you probably shouldn't touch this,
  180707. * as it will affect the size of the structures, and this will cause bad
  180708. * things to happen if the library and/or application ever change.
  180709. */
  180710. /* Any features you will not be using can be undef'ed here */
  180711. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  180712. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  180713. * on the compile line, then pick and choose which ones to define without
  180714. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  180715. * if you only want to have a png-compliant reader/writer but don't need
  180716. * any of the extra transformations. This saves about 80 kbytes in a
  180717. * typical installation of the library. (PNG_NO_* form added in version
  180718. * 1.0.1c, for consistency)
  180719. */
  180720. /* The size of the png_text structure changed in libpng-1.0.6 when
  180721. * iTXt support was added. iTXt support was turned off by default through
  180722. * libpng-1.2.x, to support old apps that malloc the png_text structure
  180723. * instead of calling png_set_text() and letting libpng malloc it. It
  180724. * was turned on by default in libpng-1.3.0.
  180725. */
  180726. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180727. # ifndef PNG_NO_iTXt_SUPPORTED
  180728. # define PNG_NO_iTXt_SUPPORTED
  180729. # endif
  180730. # ifndef PNG_NO_READ_iTXt
  180731. # define PNG_NO_READ_iTXt
  180732. # endif
  180733. # ifndef PNG_NO_WRITE_iTXt
  180734. # define PNG_NO_WRITE_iTXt
  180735. # endif
  180736. #endif
  180737. #if !defined(PNG_NO_iTXt_SUPPORTED)
  180738. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  180739. # define PNG_READ_iTXt
  180740. # endif
  180741. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  180742. # define PNG_WRITE_iTXt
  180743. # endif
  180744. #endif
  180745. /* The following support, added after version 1.0.0, can be turned off here en
  180746. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  180747. * with old applications that require the length of png_struct and png_info
  180748. * to remain unchanged.
  180749. */
  180750. #ifdef PNG_LEGACY_SUPPORTED
  180751. # define PNG_NO_FREE_ME
  180752. # define PNG_NO_READ_UNKNOWN_CHUNKS
  180753. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  180754. # define PNG_NO_READ_USER_CHUNKS
  180755. # define PNG_NO_READ_iCCP
  180756. # define PNG_NO_WRITE_iCCP
  180757. # define PNG_NO_READ_iTXt
  180758. # define PNG_NO_WRITE_iTXt
  180759. # define PNG_NO_READ_sCAL
  180760. # define PNG_NO_WRITE_sCAL
  180761. # define PNG_NO_READ_sPLT
  180762. # define PNG_NO_WRITE_sPLT
  180763. # define PNG_NO_INFO_IMAGE
  180764. # define PNG_NO_READ_RGB_TO_GRAY
  180765. # define PNG_NO_READ_USER_TRANSFORM
  180766. # define PNG_NO_WRITE_USER_TRANSFORM
  180767. # define PNG_NO_USER_MEM
  180768. # define PNG_NO_READ_EMPTY_PLTE
  180769. # define PNG_NO_MNG_FEATURES
  180770. # define PNG_NO_FIXED_POINT_SUPPORTED
  180771. #endif
  180772. /* Ignore attempt to turn off both floating and fixed point support */
  180773. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  180774. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  180775. # define PNG_FIXED_POINT_SUPPORTED
  180776. #endif
  180777. #ifndef PNG_NO_FREE_ME
  180778. # define PNG_FREE_ME_SUPPORTED
  180779. #endif
  180780. #if defined(PNG_READ_SUPPORTED)
  180781. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  180782. !defined(PNG_NO_READ_TRANSFORMS)
  180783. # define PNG_READ_TRANSFORMS_SUPPORTED
  180784. #endif
  180785. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  180786. # ifndef PNG_NO_READ_EXPAND
  180787. # define PNG_READ_EXPAND_SUPPORTED
  180788. # endif
  180789. # ifndef PNG_NO_READ_SHIFT
  180790. # define PNG_READ_SHIFT_SUPPORTED
  180791. # endif
  180792. # ifndef PNG_NO_READ_PACK
  180793. # define PNG_READ_PACK_SUPPORTED
  180794. # endif
  180795. # ifndef PNG_NO_READ_BGR
  180796. # define PNG_READ_BGR_SUPPORTED
  180797. # endif
  180798. # ifndef PNG_NO_READ_SWAP
  180799. # define PNG_READ_SWAP_SUPPORTED
  180800. # endif
  180801. # ifndef PNG_NO_READ_PACKSWAP
  180802. # define PNG_READ_PACKSWAP_SUPPORTED
  180803. # endif
  180804. # ifndef PNG_NO_READ_INVERT
  180805. # define PNG_READ_INVERT_SUPPORTED
  180806. # endif
  180807. # ifndef PNG_NO_READ_DITHER
  180808. # define PNG_READ_DITHER_SUPPORTED
  180809. # endif
  180810. # ifndef PNG_NO_READ_BACKGROUND
  180811. # define PNG_READ_BACKGROUND_SUPPORTED
  180812. # endif
  180813. # ifndef PNG_NO_READ_16_TO_8
  180814. # define PNG_READ_16_TO_8_SUPPORTED
  180815. # endif
  180816. # ifndef PNG_NO_READ_FILLER
  180817. # define PNG_READ_FILLER_SUPPORTED
  180818. # endif
  180819. # ifndef PNG_NO_READ_GAMMA
  180820. # define PNG_READ_GAMMA_SUPPORTED
  180821. # endif
  180822. # ifndef PNG_NO_READ_GRAY_TO_RGB
  180823. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  180824. # endif
  180825. # ifndef PNG_NO_READ_SWAP_ALPHA
  180826. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  180827. # endif
  180828. # ifndef PNG_NO_READ_INVERT_ALPHA
  180829. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  180830. # endif
  180831. # ifndef PNG_NO_READ_STRIP_ALPHA
  180832. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  180833. # endif
  180834. # ifndef PNG_NO_READ_USER_TRANSFORM
  180835. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  180836. # endif
  180837. # ifndef PNG_NO_READ_RGB_TO_GRAY
  180838. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  180839. # endif
  180840. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  180841. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  180842. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  180843. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  180844. #endif /* about interlacing capability! You'll */
  180845. /* still have interlacing unless you change the following line: */
  180846. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  180847. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  180848. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  180849. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  180850. # endif
  180851. #endif
  180852. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180853. /* Deprecated, will be removed from version 2.0.0.
  180854. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  180855. #ifndef PNG_NO_READ_EMPTY_PLTE
  180856. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  180857. #endif
  180858. #endif
  180859. #endif /* PNG_READ_SUPPORTED */
  180860. #if defined(PNG_WRITE_SUPPORTED)
  180861. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  180862. !defined(PNG_NO_WRITE_TRANSFORMS)
  180863. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  180864. #endif
  180865. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  180866. # ifndef PNG_NO_WRITE_SHIFT
  180867. # define PNG_WRITE_SHIFT_SUPPORTED
  180868. # endif
  180869. # ifndef PNG_NO_WRITE_PACK
  180870. # define PNG_WRITE_PACK_SUPPORTED
  180871. # endif
  180872. # ifndef PNG_NO_WRITE_BGR
  180873. # define PNG_WRITE_BGR_SUPPORTED
  180874. # endif
  180875. # ifndef PNG_NO_WRITE_SWAP
  180876. # define PNG_WRITE_SWAP_SUPPORTED
  180877. # endif
  180878. # ifndef PNG_NO_WRITE_PACKSWAP
  180879. # define PNG_WRITE_PACKSWAP_SUPPORTED
  180880. # endif
  180881. # ifndef PNG_NO_WRITE_INVERT
  180882. # define PNG_WRITE_INVERT_SUPPORTED
  180883. # endif
  180884. # ifndef PNG_NO_WRITE_FILLER
  180885. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  180886. # endif
  180887. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  180888. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  180889. # endif
  180890. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  180891. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  180892. # endif
  180893. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  180894. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  180895. # endif
  180896. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  180897. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  180898. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  180899. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  180900. encoders, but can cause trouble
  180901. if left undefined */
  180902. #endif
  180903. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  180904. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  180905. defined(PNG_FLOATING_POINT_SUPPORTED)
  180906. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  180907. #endif
  180908. #ifndef PNG_NO_WRITE_FLUSH
  180909. # define PNG_WRITE_FLUSH_SUPPORTED
  180910. #endif
  180911. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  180912. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  180913. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  180914. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  180915. #endif
  180916. #endif
  180917. #endif /* PNG_WRITE_SUPPORTED */
  180918. #ifndef PNG_1_0_X
  180919. # ifndef PNG_NO_ERROR_NUMBERS
  180920. # define PNG_ERROR_NUMBERS_SUPPORTED
  180921. # endif
  180922. #endif /* PNG_1_0_X */
  180923. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  180924. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  180925. # ifndef PNG_NO_USER_TRANSFORM_PTR
  180926. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  180927. # endif
  180928. #endif
  180929. #ifndef PNG_NO_STDIO
  180930. # define PNG_TIME_RFC1123_SUPPORTED
  180931. #endif
  180932. /* This adds extra functions in pngget.c for accessing data from the
  180933. * info pointer (added in version 0.99)
  180934. * png_get_image_width()
  180935. * png_get_image_height()
  180936. * png_get_bit_depth()
  180937. * png_get_color_type()
  180938. * png_get_compression_type()
  180939. * png_get_filter_type()
  180940. * png_get_interlace_type()
  180941. * png_get_pixel_aspect_ratio()
  180942. * png_get_pixels_per_meter()
  180943. * png_get_x_offset_pixels()
  180944. * png_get_y_offset_pixels()
  180945. * png_get_x_offset_microns()
  180946. * png_get_y_offset_microns()
  180947. */
  180948. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  180949. # define PNG_EASY_ACCESS_SUPPORTED
  180950. #endif
  180951. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  180952. * and removed from version 1.2.20. The following will be removed
  180953. * from libpng-1.4.0
  180954. */
  180955. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  180956. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  180957. # define PNG_OPTIMIZED_CODE_SUPPORTED
  180958. # endif
  180959. #endif
  180960. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  180961. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  180962. # define PNG_ASSEMBLER_CODE_SUPPORTED
  180963. # endif
  180964. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  180965. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  180966. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180967. # define PNG_NO_MMX_CODE
  180968. # endif
  180969. # endif
  180970. # if defined(__APPLE__)
  180971. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180972. # define PNG_NO_MMX_CODE
  180973. # endif
  180974. # endif
  180975. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  180976. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180977. # define PNG_NO_MMX_CODE
  180978. # endif
  180979. # endif
  180980. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  180981. # define PNG_MMX_CODE_SUPPORTED
  180982. # endif
  180983. #endif
  180984. /* end of obsolete code to be removed from libpng-1.4.0 */
  180985. #if !defined(PNG_1_0_X)
  180986. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  180987. # define PNG_USER_MEM_SUPPORTED
  180988. #endif
  180989. #endif /* PNG_1_0_X */
  180990. /* Added at libpng-1.2.6 */
  180991. #if !defined(PNG_1_0_X)
  180992. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  180993. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  180994. # define PNG_SET_USER_LIMITS_SUPPORTED
  180995. #endif
  180996. #endif
  180997. #endif /* PNG_1_0_X */
  180998. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  180999. * how large, set these limits to 0x7fffffffL
  181000. */
  181001. #ifndef PNG_USER_WIDTH_MAX
  181002. # define PNG_USER_WIDTH_MAX 1000000L
  181003. #endif
  181004. #ifndef PNG_USER_HEIGHT_MAX
  181005. # define PNG_USER_HEIGHT_MAX 1000000L
  181006. #endif
  181007. /* These are currently experimental features, define them if you want */
  181008. /* very little testing */
  181009. /*
  181010. #ifdef PNG_READ_SUPPORTED
  181011. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181012. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181013. # endif
  181014. #endif
  181015. */
  181016. /* This is only for PowerPC big-endian and 680x0 systems */
  181017. /* some testing */
  181018. /*
  181019. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181020. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181021. #endif
  181022. */
  181023. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181024. /*
  181025. #define PNG_NO_POINTER_INDEXING
  181026. */
  181027. /* These functions are turned off by default, as they will be phased out. */
  181028. /*
  181029. #define PNG_USELESS_TESTS_SUPPORTED
  181030. #define PNG_CORRECT_PALETTE_SUPPORTED
  181031. */
  181032. /* Any chunks you are not interested in, you can undef here. The
  181033. * ones that allocate memory may be expecially important (hIST,
  181034. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181035. * a bit smaller.
  181036. */
  181037. #if defined(PNG_READ_SUPPORTED) && \
  181038. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181039. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181040. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181041. #endif
  181042. #if defined(PNG_WRITE_SUPPORTED) && \
  181043. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181044. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181045. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181046. #endif
  181047. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181048. #ifdef PNG_NO_READ_TEXT
  181049. # define PNG_NO_READ_iTXt
  181050. # define PNG_NO_READ_tEXt
  181051. # define PNG_NO_READ_zTXt
  181052. #endif
  181053. #ifndef PNG_NO_READ_bKGD
  181054. # define PNG_READ_bKGD_SUPPORTED
  181055. # define PNG_bKGD_SUPPORTED
  181056. #endif
  181057. #ifndef PNG_NO_READ_cHRM
  181058. # define PNG_READ_cHRM_SUPPORTED
  181059. # define PNG_cHRM_SUPPORTED
  181060. #endif
  181061. #ifndef PNG_NO_READ_gAMA
  181062. # define PNG_READ_gAMA_SUPPORTED
  181063. # define PNG_gAMA_SUPPORTED
  181064. #endif
  181065. #ifndef PNG_NO_READ_hIST
  181066. # define PNG_READ_hIST_SUPPORTED
  181067. # define PNG_hIST_SUPPORTED
  181068. #endif
  181069. #ifndef PNG_NO_READ_iCCP
  181070. # define PNG_READ_iCCP_SUPPORTED
  181071. # define PNG_iCCP_SUPPORTED
  181072. #endif
  181073. #ifndef PNG_NO_READ_iTXt
  181074. # ifndef PNG_READ_iTXt_SUPPORTED
  181075. # define PNG_READ_iTXt_SUPPORTED
  181076. # endif
  181077. # ifndef PNG_iTXt_SUPPORTED
  181078. # define PNG_iTXt_SUPPORTED
  181079. # endif
  181080. #endif
  181081. #ifndef PNG_NO_READ_oFFs
  181082. # define PNG_READ_oFFs_SUPPORTED
  181083. # define PNG_oFFs_SUPPORTED
  181084. #endif
  181085. #ifndef PNG_NO_READ_pCAL
  181086. # define PNG_READ_pCAL_SUPPORTED
  181087. # define PNG_pCAL_SUPPORTED
  181088. #endif
  181089. #ifndef PNG_NO_READ_sCAL
  181090. # define PNG_READ_sCAL_SUPPORTED
  181091. # define PNG_sCAL_SUPPORTED
  181092. #endif
  181093. #ifndef PNG_NO_READ_pHYs
  181094. # define PNG_READ_pHYs_SUPPORTED
  181095. # define PNG_pHYs_SUPPORTED
  181096. #endif
  181097. #ifndef PNG_NO_READ_sBIT
  181098. # define PNG_READ_sBIT_SUPPORTED
  181099. # define PNG_sBIT_SUPPORTED
  181100. #endif
  181101. #ifndef PNG_NO_READ_sPLT
  181102. # define PNG_READ_sPLT_SUPPORTED
  181103. # define PNG_sPLT_SUPPORTED
  181104. #endif
  181105. #ifndef PNG_NO_READ_sRGB
  181106. # define PNG_READ_sRGB_SUPPORTED
  181107. # define PNG_sRGB_SUPPORTED
  181108. #endif
  181109. #ifndef PNG_NO_READ_tEXt
  181110. # define PNG_READ_tEXt_SUPPORTED
  181111. # define PNG_tEXt_SUPPORTED
  181112. #endif
  181113. #ifndef PNG_NO_READ_tIME
  181114. # define PNG_READ_tIME_SUPPORTED
  181115. # define PNG_tIME_SUPPORTED
  181116. #endif
  181117. #ifndef PNG_NO_READ_tRNS
  181118. # define PNG_READ_tRNS_SUPPORTED
  181119. # define PNG_tRNS_SUPPORTED
  181120. #endif
  181121. #ifndef PNG_NO_READ_zTXt
  181122. # define PNG_READ_zTXt_SUPPORTED
  181123. # define PNG_zTXt_SUPPORTED
  181124. #endif
  181125. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181126. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181127. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181128. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181129. # endif
  181130. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181131. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181132. # endif
  181133. #endif
  181134. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181135. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181136. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181137. # define PNG_USER_CHUNKS_SUPPORTED
  181138. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181139. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181140. # endif
  181141. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181142. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181143. # endif
  181144. #endif
  181145. #ifndef PNG_NO_READ_OPT_PLTE
  181146. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181147. #endif /* optional PLTE chunk in RGB and RGBA images */
  181148. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181149. defined(PNG_READ_zTXt_SUPPORTED)
  181150. # define PNG_READ_TEXT_SUPPORTED
  181151. # define PNG_TEXT_SUPPORTED
  181152. #endif
  181153. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181154. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181155. #ifdef PNG_NO_WRITE_TEXT
  181156. # define PNG_NO_WRITE_iTXt
  181157. # define PNG_NO_WRITE_tEXt
  181158. # define PNG_NO_WRITE_zTXt
  181159. #endif
  181160. #ifndef PNG_NO_WRITE_bKGD
  181161. # define PNG_WRITE_bKGD_SUPPORTED
  181162. # ifndef PNG_bKGD_SUPPORTED
  181163. # define PNG_bKGD_SUPPORTED
  181164. # endif
  181165. #endif
  181166. #ifndef PNG_NO_WRITE_cHRM
  181167. # define PNG_WRITE_cHRM_SUPPORTED
  181168. # ifndef PNG_cHRM_SUPPORTED
  181169. # define PNG_cHRM_SUPPORTED
  181170. # endif
  181171. #endif
  181172. #ifndef PNG_NO_WRITE_gAMA
  181173. # define PNG_WRITE_gAMA_SUPPORTED
  181174. # ifndef PNG_gAMA_SUPPORTED
  181175. # define PNG_gAMA_SUPPORTED
  181176. # endif
  181177. #endif
  181178. #ifndef PNG_NO_WRITE_hIST
  181179. # define PNG_WRITE_hIST_SUPPORTED
  181180. # ifndef PNG_hIST_SUPPORTED
  181181. # define PNG_hIST_SUPPORTED
  181182. # endif
  181183. #endif
  181184. #ifndef PNG_NO_WRITE_iCCP
  181185. # define PNG_WRITE_iCCP_SUPPORTED
  181186. # ifndef PNG_iCCP_SUPPORTED
  181187. # define PNG_iCCP_SUPPORTED
  181188. # endif
  181189. #endif
  181190. #ifndef PNG_NO_WRITE_iTXt
  181191. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181192. # define PNG_WRITE_iTXt_SUPPORTED
  181193. # endif
  181194. # ifndef PNG_iTXt_SUPPORTED
  181195. # define PNG_iTXt_SUPPORTED
  181196. # endif
  181197. #endif
  181198. #ifndef PNG_NO_WRITE_oFFs
  181199. # define PNG_WRITE_oFFs_SUPPORTED
  181200. # ifndef PNG_oFFs_SUPPORTED
  181201. # define PNG_oFFs_SUPPORTED
  181202. # endif
  181203. #endif
  181204. #ifndef PNG_NO_WRITE_pCAL
  181205. # define PNG_WRITE_pCAL_SUPPORTED
  181206. # ifndef PNG_pCAL_SUPPORTED
  181207. # define PNG_pCAL_SUPPORTED
  181208. # endif
  181209. #endif
  181210. #ifndef PNG_NO_WRITE_sCAL
  181211. # define PNG_WRITE_sCAL_SUPPORTED
  181212. # ifndef PNG_sCAL_SUPPORTED
  181213. # define PNG_sCAL_SUPPORTED
  181214. # endif
  181215. #endif
  181216. #ifndef PNG_NO_WRITE_pHYs
  181217. # define PNG_WRITE_pHYs_SUPPORTED
  181218. # ifndef PNG_pHYs_SUPPORTED
  181219. # define PNG_pHYs_SUPPORTED
  181220. # endif
  181221. #endif
  181222. #ifndef PNG_NO_WRITE_sBIT
  181223. # define PNG_WRITE_sBIT_SUPPORTED
  181224. # ifndef PNG_sBIT_SUPPORTED
  181225. # define PNG_sBIT_SUPPORTED
  181226. # endif
  181227. #endif
  181228. #ifndef PNG_NO_WRITE_sPLT
  181229. # define PNG_WRITE_sPLT_SUPPORTED
  181230. # ifndef PNG_sPLT_SUPPORTED
  181231. # define PNG_sPLT_SUPPORTED
  181232. # endif
  181233. #endif
  181234. #ifndef PNG_NO_WRITE_sRGB
  181235. # define PNG_WRITE_sRGB_SUPPORTED
  181236. # ifndef PNG_sRGB_SUPPORTED
  181237. # define PNG_sRGB_SUPPORTED
  181238. # endif
  181239. #endif
  181240. #ifndef PNG_NO_WRITE_tEXt
  181241. # define PNG_WRITE_tEXt_SUPPORTED
  181242. # ifndef PNG_tEXt_SUPPORTED
  181243. # define PNG_tEXt_SUPPORTED
  181244. # endif
  181245. #endif
  181246. #ifndef PNG_NO_WRITE_tIME
  181247. # define PNG_WRITE_tIME_SUPPORTED
  181248. # ifndef PNG_tIME_SUPPORTED
  181249. # define PNG_tIME_SUPPORTED
  181250. # endif
  181251. #endif
  181252. #ifndef PNG_NO_WRITE_tRNS
  181253. # define PNG_WRITE_tRNS_SUPPORTED
  181254. # ifndef PNG_tRNS_SUPPORTED
  181255. # define PNG_tRNS_SUPPORTED
  181256. # endif
  181257. #endif
  181258. #ifndef PNG_NO_WRITE_zTXt
  181259. # define PNG_WRITE_zTXt_SUPPORTED
  181260. # ifndef PNG_zTXt_SUPPORTED
  181261. # define PNG_zTXt_SUPPORTED
  181262. # endif
  181263. #endif
  181264. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181265. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181266. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181267. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181268. # endif
  181269. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181270. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181271. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181272. # endif
  181273. # endif
  181274. #endif
  181275. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181276. defined(PNG_WRITE_zTXt_SUPPORTED)
  181277. # define PNG_WRITE_TEXT_SUPPORTED
  181278. # ifndef PNG_TEXT_SUPPORTED
  181279. # define PNG_TEXT_SUPPORTED
  181280. # endif
  181281. #endif
  181282. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181283. /* Turn this off to disable png_read_png() and
  181284. * png_write_png() and leave the row_pointers member
  181285. * out of the info structure.
  181286. */
  181287. #ifndef PNG_NO_INFO_IMAGE
  181288. # define PNG_INFO_IMAGE_SUPPORTED
  181289. #endif
  181290. /* need the time information for reading tIME chunks */
  181291. #if defined(PNG_tIME_SUPPORTED)
  181292. # if !defined(_WIN32_WCE)
  181293. /* "time.h" functions are not supported on WindowsCE */
  181294. # include <time.h>
  181295. # endif
  181296. #endif
  181297. /* Some typedefs to get us started. These should be safe on most of the
  181298. * common platforms. The typedefs should be at least as large as the
  181299. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181300. * don't have to be exactly that size. Some compilers dislike passing
  181301. * unsigned shorts as function parameters, so you may be better off using
  181302. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181303. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181304. */
  181305. typedef unsigned long png_uint_32;
  181306. typedef long png_int_32;
  181307. typedef unsigned short png_uint_16;
  181308. typedef short png_int_16;
  181309. typedef unsigned char png_byte;
  181310. /* This is usually size_t. It is typedef'ed just in case you need it to
  181311. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181312. #ifdef PNG_SIZE_T
  181313. typedef PNG_SIZE_T png_size_t;
  181314. # define png_sizeof(x) png_convert_size(sizeof (x))
  181315. #else
  181316. typedef size_t png_size_t;
  181317. # define png_sizeof(x) sizeof (x)
  181318. #endif
  181319. /* The following is needed for medium model support. It cannot be in the
  181320. * PNG_INTERNAL section. Needs modification for other compilers besides
  181321. * MSC. Model independent support declares all arrays and pointers to be
  181322. * large using the far keyword. The zlib version used must also support
  181323. * model independent data. As of version zlib 1.0.4, the necessary changes
  181324. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181325. * changes that are needed. (Tim Wegner)
  181326. */
  181327. /* Separate compiler dependencies (problem here is that zlib.h always
  181328. defines FAR. (SJT) */
  181329. #ifdef __BORLANDC__
  181330. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181331. # define LDATA 1
  181332. # else
  181333. # define LDATA 0
  181334. # endif
  181335. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181336. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181337. # define PNG_MAX_MALLOC_64K
  181338. # if (LDATA != 1)
  181339. # ifndef FAR
  181340. # define FAR __far
  181341. # endif
  181342. # define USE_FAR_KEYWORD
  181343. # endif /* LDATA != 1 */
  181344. /* Possibly useful for moving data out of default segment.
  181345. * Uncomment it if you want. Could also define FARDATA as
  181346. * const if your compiler supports it. (SJT)
  181347. # define FARDATA FAR
  181348. */
  181349. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181350. #endif /* __BORLANDC__ */
  181351. /* Suggest testing for specific compiler first before testing for
  181352. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181353. * making reliance oncertain keywords suspect. (SJT)
  181354. */
  181355. /* MSC Medium model */
  181356. #if defined(FAR)
  181357. # if defined(M_I86MM)
  181358. # define USE_FAR_KEYWORD
  181359. # define FARDATA FAR
  181360. # include <dos.h>
  181361. # endif
  181362. #endif
  181363. /* SJT: default case */
  181364. #ifndef FAR
  181365. # define FAR
  181366. #endif
  181367. /* At this point FAR is always defined */
  181368. #ifndef FARDATA
  181369. # define FARDATA
  181370. #endif
  181371. /* Typedef for floating-point numbers that are converted
  181372. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181373. typedef png_int_32 png_fixed_point;
  181374. /* Add typedefs for pointers */
  181375. typedef void FAR * png_voidp;
  181376. typedef png_byte FAR * png_bytep;
  181377. typedef png_uint_32 FAR * png_uint_32p;
  181378. typedef png_int_32 FAR * png_int_32p;
  181379. typedef png_uint_16 FAR * png_uint_16p;
  181380. typedef png_int_16 FAR * png_int_16p;
  181381. typedef PNG_CONST char FAR * png_const_charp;
  181382. typedef char FAR * png_charp;
  181383. typedef png_fixed_point FAR * png_fixed_point_p;
  181384. #ifndef PNG_NO_STDIO
  181385. #if defined(_WIN32_WCE)
  181386. typedef HANDLE png_FILE_p;
  181387. #else
  181388. typedef FILE * png_FILE_p;
  181389. #endif
  181390. #endif
  181391. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181392. typedef double FAR * png_doublep;
  181393. #endif
  181394. /* Pointers to pointers; i.e. arrays */
  181395. typedef png_byte FAR * FAR * png_bytepp;
  181396. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181397. typedef png_int_32 FAR * FAR * png_int_32pp;
  181398. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181399. typedef png_int_16 FAR * FAR * png_int_16pp;
  181400. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181401. typedef char FAR * FAR * png_charpp;
  181402. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181403. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181404. typedef double FAR * FAR * png_doublepp;
  181405. #endif
  181406. /* Pointers to pointers to pointers; i.e., pointer to array */
  181407. typedef char FAR * FAR * FAR * png_charppp;
  181408. #if 0
  181409. /* SPC - Is this stuff deprecated? */
  181410. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181411. /* libpng typedefs for types in zlib. If zlib changes
  181412. * or another compression library is used, then change these.
  181413. * Eliminates need to change all the source files.
  181414. */
  181415. typedef charf * png_zcharp;
  181416. typedef charf * FAR * png_zcharpp;
  181417. typedef z_stream FAR * png_zstreamp;
  181418. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181419. /*
  181420. * Define PNG_BUILD_DLL if the module being built is a Windows
  181421. * LIBPNG DLL.
  181422. *
  181423. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181424. * It is equivalent to Microsoft predefined macro _DLL that is
  181425. * automatically defined when you compile using the share
  181426. * version of the CRT (C Run-Time library)
  181427. *
  181428. * The cygwin mods make this behavior a little different:
  181429. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181430. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181431. * -or- if you are building an application that you want to link to the
  181432. * static library.
  181433. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181434. * the other flags is defined.
  181435. */
  181436. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181437. # define PNG_DLL
  181438. #endif
  181439. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181440. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181441. * command-line override
  181442. */
  181443. #if defined(__CYGWIN__)
  181444. # if !defined(PNG_STATIC)
  181445. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181446. # undef PNG_USE_GLOBAL_ARRAYS
  181447. # endif
  181448. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181449. # define PNG_USE_LOCAL_ARRAYS
  181450. # endif
  181451. # else
  181452. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181453. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181454. # undef PNG_USE_GLOBAL_ARRAYS
  181455. # endif
  181456. # endif
  181457. # endif
  181458. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181459. # define PNG_USE_LOCAL_ARRAYS
  181460. # endif
  181461. #endif
  181462. /* Do not use global arrays (helps with building DLL's)
  181463. * They are no longer used in libpng itself, since version 1.0.5c,
  181464. * but might be required for some pre-1.0.5c applications.
  181465. */
  181466. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181467. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181468. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181469. # define PNG_USE_LOCAL_ARRAYS
  181470. # else
  181471. # define PNG_USE_GLOBAL_ARRAYS
  181472. # endif
  181473. #endif
  181474. #if defined(__CYGWIN__)
  181475. # undef PNGAPI
  181476. # define PNGAPI __cdecl
  181477. # undef PNG_IMPEXP
  181478. # define PNG_IMPEXP
  181479. #endif
  181480. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181481. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181482. * Don't ignore those warnings; you must also reset the default calling
  181483. * convention in your compiler to match your PNGAPI, and you must build
  181484. * zlib and your applications the same way you build libpng.
  181485. */
  181486. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181487. # ifndef PNG_NO_MODULEDEF
  181488. # define PNG_NO_MODULEDEF
  181489. # endif
  181490. #endif
  181491. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181492. # define PNG_IMPEXP
  181493. #endif
  181494. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181495. (( defined(_Windows) || defined(_WINDOWS) || \
  181496. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181497. # ifndef PNGAPI
  181498. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181499. # define PNGAPI __cdecl
  181500. # else
  181501. # define PNGAPI _cdecl
  181502. # endif
  181503. # endif
  181504. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181505. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181506. # define PNG_IMPEXP
  181507. # endif
  181508. # if !defined(PNG_IMPEXP)
  181509. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181510. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181511. /* Borland/Microsoft */
  181512. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181513. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181514. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181515. # else
  181516. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181517. # if defined(PNG_BUILD_DLL)
  181518. # define PNG_IMPEXP __export
  181519. # else
  181520. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181521. VC++ */
  181522. # endif /* Exists in Borland C++ for
  181523. C++ classes (== huge) */
  181524. # endif
  181525. # endif
  181526. # if !defined(PNG_IMPEXP)
  181527. # if defined(PNG_BUILD_DLL)
  181528. # define PNG_IMPEXP __declspec(dllexport)
  181529. # else
  181530. # define PNG_IMPEXP __declspec(dllimport)
  181531. # endif
  181532. # endif
  181533. # endif /* PNG_IMPEXP */
  181534. #else /* !(DLL || non-cygwin WINDOWS) */
  181535. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181536. # ifndef PNGAPI
  181537. # define PNGAPI _System
  181538. # endif
  181539. # else
  181540. # if 0 /* ... other platforms, with other meanings */
  181541. # endif
  181542. # endif
  181543. #endif
  181544. #ifndef PNGAPI
  181545. # define PNGAPI
  181546. #endif
  181547. #ifndef PNG_IMPEXP
  181548. # define PNG_IMPEXP
  181549. #endif
  181550. #ifdef PNG_BUILDSYMS
  181551. # ifndef PNG_EXPORT
  181552. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181553. # endif
  181554. # ifdef PNG_USE_GLOBAL_ARRAYS
  181555. # ifndef PNG_EXPORT_VAR
  181556. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181557. # endif
  181558. # endif
  181559. #endif
  181560. #ifndef PNG_EXPORT
  181561. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181562. #endif
  181563. #ifdef PNG_USE_GLOBAL_ARRAYS
  181564. # ifndef PNG_EXPORT_VAR
  181565. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181566. # endif
  181567. #endif
  181568. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181569. * functions that are passed far data must be model independent.
  181570. */
  181571. #ifndef PNG_ABORT
  181572. # define PNG_ABORT() abort()
  181573. #endif
  181574. #ifdef PNG_SETJMP_SUPPORTED
  181575. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181576. #else
  181577. # define png_jmpbuf(png_ptr) \
  181578. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181579. #endif
  181580. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181581. /* use this to make far-to-near assignments */
  181582. # define CHECK 1
  181583. # define NOCHECK 0
  181584. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181585. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181586. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181587. # define png_strcpy _fstrcpy
  181588. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181589. # define png_strlen _fstrlen
  181590. # define png_memcmp _fmemcmp /* SJT: added */
  181591. # define png_memcpy _fmemcpy
  181592. # define png_memset _fmemset
  181593. #else /* use the usual functions */
  181594. # define CVT_PTR(ptr) (ptr)
  181595. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181596. # ifndef PNG_NO_SNPRINTF
  181597. # ifdef _MSC_VER
  181598. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181599. # define png_snprintf2 _snprintf
  181600. # define png_snprintf6 _snprintf
  181601. # else
  181602. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181603. # define png_snprintf2 snprintf
  181604. # define png_snprintf6 snprintf
  181605. # endif
  181606. # else
  181607. /* You don't have or don't want to use snprintf(). Caution: Using
  181608. * sprintf instead of snprintf exposes your application to accidental
  181609. * or malevolent buffer overflows. If you don't have snprintf()
  181610. * as a general rule you should provide one (you can get one from
  181611. * Portable OpenSSH). */
  181612. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181613. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181614. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181615. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181616. # endif
  181617. # define png_strcpy strcpy
  181618. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181619. # define png_strlen strlen
  181620. # define png_memcmp memcmp /* SJT: added */
  181621. # define png_memcpy memcpy
  181622. # define png_memset memset
  181623. #endif
  181624. /* End of memory model independent support */
  181625. /* Just a little check that someone hasn't tried to define something
  181626. * contradictory.
  181627. */
  181628. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181629. # undef PNG_ZBUF_SIZE
  181630. # define PNG_ZBUF_SIZE 65536L
  181631. #endif
  181632. /* Added at libpng-1.2.8 */
  181633. #endif /* PNG_VERSION_INFO_ONLY */
  181634. #endif /* PNGCONF_H */
  181635. /*** End of inlined file: pngconf.h ***/
  181636. #ifdef _MSC_VER
  181637. #pragma warning (disable: 4996 4100)
  181638. #endif
  181639. /*
  181640. * Added at libpng-1.2.8 */
  181641. /* Ref MSDN: Private as priority over Special
  181642. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181643. * procedures. If this value is given, the StringFileInfo block must
  181644. * contain a PrivateBuild string.
  181645. *
  181646. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181647. * standard release procedures but is a variation of the standard
  181648. * file of the same version number. If this value is given, the
  181649. * StringFileInfo block must contain a SpecialBuild string.
  181650. */
  181651. #if defined(PNG_USER_PRIVATEBUILD)
  181652. # define PNG_LIBPNG_BUILD_TYPE \
  181653. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181654. #else
  181655. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181656. # define PNG_LIBPNG_BUILD_TYPE \
  181657. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181658. # else
  181659. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181660. # endif
  181661. #endif
  181662. #ifndef PNG_VERSION_INFO_ONLY
  181663. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181664. #ifdef __cplusplus
  181665. //extern "C" {
  181666. #endif /* __cplusplus */
  181667. /* This file is arranged in several sections. The first section contains
  181668. * structure and type definitions. The second section contains the external
  181669. * library functions, while the third has the internal library functions,
  181670. * which applications aren't expected to use directly.
  181671. */
  181672. #ifndef PNG_NO_TYPECAST_NULL
  181673. #define int_p_NULL (int *)NULL
  181674. #define png_bytep_NULL (png_bytep)NULL
  181675. #define png_bytepp_NULL (png_bytepp)NULL
  181676. #define png_doublep_NULL (png_doublep)NULL
  181677. #define png_error_ptr_NULL (png_error_ptr)NULL
  181678. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  181679. #define png_free_ptr_NULL (png_free_ptr)NULL
  181680. #define png_infopp_NULL (png_infopp)NULL
  181681. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  181682. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  181683. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  181684. #define png_structp_NULL (png_structp)NULL
  181685. #define png_uint_16p_NULL (png_uint_16p)NULL
  181686. #define png_voidp_NULL (png_voidp)NULL
  181687. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  181688. #else
  181689. #define int_p_NULL NULL
  181690. #define png_bytep_NULL NULL
  181691. #define png_bytepp_NULL NULL
  181692. #define png_doublep_NULL NULL
  181693. #define png_error_ptr_NULL NULL
  181694. #define png_flush_ptr_NULL NULL
  181695. #define png_free_ptr_NULL NULL
  181696. #define png_infopp_NULL NULL
  181697. #define png_malloc_ptr_NULL NULL
  181698. #define png_read_status_ptr_NULL NULL
  181699. #define png_rw_ptr_NULL NULL
  181700. #define png_structp_NULL NULL
  181701. #define png_uint_16p_NULL NULL
  181702. #define png_voidp_NULL NULL
  181703. #define png_write_status_ptr_NULL NULL
  181704. #endif
  181705. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  181706. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  181707. /* Version information for C files, stored in png.c. This had better match
  181708. * the version above.
  181709. */
  181710. #ifdef PNG_USE_GLOBAL_ARRAYS
  181711. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  181712. /* need room for 99.99.99beta99z */
  181713. #else
  181714. #define png_libpng_ver png_get_header_ver(NULL)
  181715. #endif
  181716. #ifdef PNG_USE_GLOBAL_ARRAYS
  181717. /* This was removed in version 1.0.5c */
  181718. /* Structures to facilitate easy interlacing. See png.c for more details */
  181719. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  181720. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  181721. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  181722. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  181723. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  181724. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  181725. /* This isn't currently used. If you need it, see png.c for more details.
  181726. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  181727. */
  181728. #endif
  181729. #endif /* PNG_NO_EXTERN */
  181730. /* Three color definitions. The order of the red, green, and blue, (and the
  181731. * exact size) is not important, although the size of the fields need to
  181732. * be png_byte or png_uint_16 (as defined below).
  181733. */
  181734. typedef struct png_color_struct
  181735. {
  181736. png_byte red;
  181737. png_byte green;
  181738. png_byte blue;
  181739. } png_color;
  181740. typedef png_color FAR * png_colorp;
  181741. typedef png_color FAR * FAR * png_colorpp;
  181742. typedef struct png_color_16_struct
  181743. {
  181744. png_byte index; /* used for palette files */
  181745. png_uint_16 red; /* for use in red green blue files */
  181746. png_uint_16 green;
  181747. png_uint_16 blue;
  181748. png_uint_16 gray; /* for use in grayscale files */
  181749. } png_color_16;
  181750. typedef png_color_16 FAR * png_color_16p;
  181751. typedef png_color_16 FAR * FAR * png_color_16pp;
  181752. typedef struct png_color_8_struct
  181753. {
  181754. png_byte red; /* for use in red green blue files */
  181755. png_byte green;
  181756. png_byte blue;
  181757. png_byte gray; /* for use in grayscale files */
  181758. png_byte alpha; /* for alpha channel files */
  181759. } png_color_8;
  181760. typedef png_color_8 FAR * png_color_8p;
  181761. typedef png_color_8 FAR * FAR * png_color_8pp;
  181762. /*
  181763. * The following two structures are used for the in-core representation
  181764. * of sPLT chunks.
  181765. */
  181766. typedef struct png_sPLT_entry_struct
  181767. {
  181768. png_uint_16 red;
  181769. png_uint_16 green;
  181770. png_uint_16 blue;
  181771. png_uint_16 alpha;
  181772. png_uint_16 frequency;
  181773. } png_sPLT_entry;
  181774. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  181775. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  181776. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  181777. * occupy the LSB of their respective members, and the MSB of each member
  181778. * is zero-filled. The frequency member always occupies the full 16 bits.
  181779. */
  181780. typedef struct png_sPLT_struct
  181781. {
  181782. png_charp name; /* palette name */
  181783. png_byte depth; /* depth of palette samples */
  181784. png_sPLT_entryp entries; /* palette entries */
  181785. png_int_32 nentries; /* number of palette entries */
  181786. } png_sPLT_t;
  181787. typedef png_sPLT_t FAR * png_sPLT_tp;
  181788. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  181789. #ifdef PNG_TEXT_SUPPORTED
  181790. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  181791. * and whether that contents is compressed or not. The "key" field
  181792. * points to a regular zero-terminated C string. The "text", "lang", and
  181793. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  181794. * However, the * structure returned by png_get_text() will always contain
  181795. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  181796. * so they can be safely used in printf() and other string-handling functions.
  181797. */
  181798. typedef struct png_text_struct
  181799. {
  181800. int compression; /* compression value:
  181801. -1: tEXt, none
  181802. 0: zTXt, deflate
  181803. 1: iTXt, none
  181804. 2: iTXt, deflate */
  181805. png_charp key; /* keyword, 1-79 character description of "text" */
  181806. png_charp text; /* comment, may be an empty string (ie "")
  181807. or a NULL pointer */
  181808. png_size_t text_length; /* length of the text string */
  181809. #ifdef PNG_iTXt_SUPPORTED
  181810. png_size_t itxt_length; /* length of the itxt string */
  181811. png_charp lang; /* language code, 0-79 characters
  181812. or a NULL pointer */
  181813. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  181814. chars or a NULL pointer */
  181815. #endif
  181816. } png_text;
  181817. typedef png_text FAR * png_textp;
  181818. typedef png_text FAR * FAR * png_textpp;
  181819. #endif
  181820. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  181821. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  181822. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  181823. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  181824. #define PNG_TEXT_COMPRESSION_NONE -1
  181825. #define PNG_TEXT_COMPRESSION_zTXt 0
  181826. #define PNG_ITXT_COMPRESSION_NONE 1
  181827. #define PNG_ITXT_COMPRESSION_zTXt 2
  181828. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  181829. /* png_time is a way to hold the time in an machine independent way.
  181830. * Two conversions are provided, both from time_t and struct tm. There
  181831. * is no portable way to convert to either of these structures, as far
  181832. * as I know. If you know of a portable way, send it to me. As a side
  181833. * note - PNG has always been Year 2000 compliant!
  181834. */
  181835. typedef struct png_time_struct
  181836. {
  181837. png_uint_16 year; /* full year, as in, 1995 */
  181838. png_byte month; /* month of year, 1 - 12 */
  181839. png_byte day; /* day of month, 1 - 31 */
  181840. png_byte hour; /* hour of day, 0 - 23 */
  181841. png_byte minute; /* minute of hour, 0 - 59 */
  181842. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  181843. } png_time;
  181844. typedef png_time FAR * png_timep;
  181845. typedef png_time FAR * FAR * png_timepp;
  181846. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181847. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  181848. * no specific support. The idea is that we can use this to queue
  181849. * up private chunks for output even though the library doesn't actually
  181850. * know about their semantics.
  181851. */
  181852. typedef struct png_unknown_chunk_t
  181853. {
  181854. png_byte name[5];
  181855. png_byte *data;
  181856. png_size_t size;
  181857. /* libpng-using applications should NOT directly modify this byte. */
  181858. png_byte location; /* mode of operation at read time */
  181859. }
  181860. png_unknown_chunk;
  181861. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  181862. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  181863. #endif
  181864. /* png_info is a structure that holds the information in a PNG file so
  181865. * that the application can find out the characteristics of the image.
  181866. * If you are reading the file, this structure will tell you what is
  181867. * in the PNG file. If you are writing the file, fill in the information
  181868. * you want to put into the PNG file, then call png_write_info().
  181869. * The names chosen should be very close to the PNG specification, so
  181870. * consult that document for information about the meaning of each field.
  181871. *
  181872. * With libpng < 0.95, it was only possible to directly set and read the
  181873. * the values in the png_info_struct, which meant that the contents and
  181874. * order of the values had to remain fixed. With libpng 0.95 and later,
  181875. * however, there are now functions that abstract the contents of
  181876. * png_info_struct from the application, so this makes it easier to use
  181877. * libpng with dynamic libraries, and even makes it possible to use
  181878. * libraries that don't have all of the libpng ancillary chunk-handing
  181879. * functionality.
  181880. *
  181881. * In any case, the order of the parameters in png_info_struct should NOT
  181882. * be changed for as long as possible to keep compatibility with applications
  181883. * that use the old direct-access method with png_info_struct.
  181884. *
  181885. * The following members may have allocated storage attached that should be
  181886. * cleaned up before the structure is discarded: palette, trans, text,
  181887. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  181888. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  181889. * are automatically freed when the info structure is deallocated, if they were
  181890. * allocated internally by libpng. This behavior can be changed by means
  181891. * of the png_data_freer() function.
  181892. *
  181893. * More allocation details: all the chunk-reading functions that
  181894. * change these members go through the corresponding png_set_*
  181895. * functions. A function to clear these members is available: see
  181896. * png_free_data(). The png_set_* functions do not depend on being
  181897. * able to point info structure members to any of the storage they are
  181898. * passed (they make their own copies), EXCEPT that the png_set_text
  181899. * functions use the same storage passed to them in the text_ptr or
  181900. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  181901. * functions do not make their own copies.
  181902. */
  181903. typedef struct png_info_struct
  181904. {
  181905. /* the following are necessary for every PNG file */
  181906. png_uint_32 width; /* width of image in pixels (from IHDR) */
  181907. png_uint_32 height; /* height of image in pixels (from IHDR) */
  181908. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  181909. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  181910. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  181911. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  181912. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  181913. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  181914. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  181915. /* The following three should have been named *_method not *_type */
  181916. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  181917. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  181918. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  181919. /* The following is informational only on read, and not used on writes. */
  181920. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  181921. png_byte pixel_depth; /* number of bits per pixel */
  181922. png_byte spare_byte; /* to align the data, and for future use */
  181923. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  181924. /* The rest of the data is optional. If you are reading, check the
  181925. * valid field to see if the information in these are valid. If you
  181926. * are writing, set the valid field to those chunks you want written,
  181927. * and initialize the appropriate fields below.
  181928. */
  181929. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181930. /* The gAMA chunk describes the gamma characteristics of the system
  181931. * on which the image was created, normally in the range [1.0, 2.5].
  181932. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  181933. */
  181934. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  181935. #endif
  181936. #if defined(PNG_sRGB_SUPPORTED)
  181937. /* GR-P, 0.96a */
  181938. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  181939. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  181940. #endif
  181941. #if defined(PNG_TEXT_SUPPORTED)
  181942. /* The tEXt, and zTXt chunks contain human-readable textual data in
  181943. * uncompressed, compressed, and optionally compressed forms, respectively.
  181944. * The data in "text" is an array of pointers to uncompressed,
  181945. * null-terminated C strings. Each chunk has a keyword that describes the
  181946. * textual data contained in that chunk. Keywords are not required to be
  181947. * unique, and the text string may be empty. Any number of text chunks may
  181948. * be in an image.
  181949. */
  181950. int num_text; /* number of comments read/to write */
  181951. int max_text; /* current size of text array */
  181952. png_textp text; /* array of comments read/to write */
  181953. #endif /* PNG_TEXT_SUPPORTED */
  181954. #if defined(PNG_tIME_SUPPORTED)
  181955. /* The tIME chunk holds the last time the displayed image data was
  181956. * modified. See the png_time struct for the contents of this struct.
  181957. */
  181958. png_time mod_time;
  181959. #endif
  181960. #if defined(PNG_sBIT_SUPPORTED)
  181961. /* The sBIT chunk specifies the number of significant high-order bits
  181962. * in the pixel data. Values are in the range [1, bit_depth], and are
  181963. * only specified for the channels in the pixel data. The contents of
  181964. * the low-order bits is not specified. Data is valid if
  181965. * (valid & PNG_INFO_sBIT) is non-zero.
  181966. */
  181967. png_color_8 sig_bit; /* significant bits in color channels */
  181968. #endif
  181969. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  181970. defined(PNG_READ_BACKGROUND_SUPPORTED)
  181971. /* The tRNS chunk supplies transparency data for paletted images and
  181972. * other image types that don't need a full alpha channel. There are
  181973. * "num_trans" transparency values for a paletted image, stored in the
  181974. * same order as the palette colors, starting from index 0. Values
  181975. * for the data are in the range [0, 255], ranging from fully transparent
  181976. * to fully opaque, respectively. For non-paletted images, there is a
  181977. * single color specified that should be treated as fully transparent.
  181978. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  181979. */
  181980. png_bytep trans; /* transparent values for paletted image */
  181981. png_color_16 trans_values; /* transparent color for non-palette image */
  181982. #endif
  181983. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181984. /* The bKGD chunk gives the suggested image background color if the
  181985. * display program does not have its own background color and the image
  181986. * is needs to composited onto a background before display. The colors
  181987. * in "background" are normally in the same color space/depth as the
  181988. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  181989. */
  181990. png_color_16 background;
  181991. #endif
  181992. #if defined(PNG_oFFs_SUPPORTED)
  181993. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  181994. * and downwards from the top-left corner of the display, page, or other
  181995. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  181996. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  181997. */
  181998. png_int_32 x_offset; /* x offset on page */
  181999. png_int_32 y_offset; /* y offset on page */
  182000. png_byte offset_unit_type; /* offset units type */
  182001. #endif
  182002. #if defined(PNG_pHYs_SUPPORTED)
  182003. /* The pHYs chunk gives the physical pixel density of the image for
  182004. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182005. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182006. */
  182007. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182008. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182009. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182010. #endif
  182011. #if defined(PNG_hIST_SUPPORTED)
  182012. /* The hIST chunk contains the relative frequency or importance of the
  182013. * various palette entries, so that a viewer can intelligently select a
  182014. * reduced-color palette, if required. Data is an array of "num_palette"
  182015. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182016. * is non-zero.
  182017. */
  182018. png_uint_16p hist;
  182019. #endif
  182020. #ifdef PNG_cHRM_SUPPORTED
  182021. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182022. * on which the PNG was created. This data allows the viewer to do gamut
  182023. * mapping of the input image to ensure that the viewer sees the same
  182024. * colors in the image as the creator. Values are in the range
  182025. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182026. */
  182027. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182028. float x_white;
  182029. float y_white;
  182030. float x_red;
  182031. float y_red;
  182032. float x_green;
  182033. float y_green;
  182034. float x_blue;
  182035. float y_blue;
  182036. #endif
  182037. #endif
  182038. #if defined(PNG_pCAL_SUPPORTED)
  182039. /* The pCAL chunk describes a transformation between the stored pixel
  182040. * values and original physical data values used to create the image.
  182041. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182042. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182043. * (possibly non-linear) transformation function given by "pcal_type"
  182044. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182045. * defines below, and the PNG-Group's PNG extensions document for a
  182046. * complete description of the transformations and how they should be
  182047. * implemented, and for a description of the ASCII parameter strings.
  182048. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182049. */
  182050. png_charp pcal_purpose; /* pCAL chunk description string */
  182051. png_int_32 pcal_X0; /* minimum value */
  182052. png_int_32 pcal_X1; /* maximum value */
  182053. png_charp pcal_units; /* Latin-1 string giving physical units */
  182054. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182055. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182056. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182057. #endif
  182058. /* New members added in libpng-1.0.6 */
  182059. #ifdef PNG_FREE_ME_SUPPORTED
  182060. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182061. #endif
  182062. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182063. /* storage for unknown chunks that the library doesn't recognize. */
  182064. png_unknown_chunkp unknown_chunks;
  182065. png_size_t unknown_chunks_num;
  182066. #endif
  182067. #if defined(PNG_iCCP_SUPPORTED)
  182068. /* iCCP chunk data. */
  182069. png_charp iccp_name; /* profile name */
  182070. png_charp iccp_profile; /* International Color Consortium profile data */
  182071. /* Note to maintainer: should be png_bytep */
  182072. png_uint_32 iccp_proflen; /* ICC profile data length */
  182073. png_byte iccp_compression; /* Always zero */
  182074. #endif
  182075. #if defined(PNG_sPLT_SUPPORTED)
  182076. /* data on sPLT chunks (there may be more than one). */
  182077. png_sPLT_tp splt_palettes;
  182078. png_uint_32 splt_palettes_num;
  182079. #endif
  182080. #if defined(PNG_sCAL_SUPPORTED)
  182081. /* The sCAL chunk describes the actual physical dimensions of the
  182082. * subject matter of the graphic. The chunk contains a unit specification
  182083. * a byte value, and two ASCII strings representing floating-point
  182084. * values. The values are width and height corresponsing to one pixel
  182085. * in the image. This external representation is converted to double
  182086. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182087. */
  182088. png_byte scal_unit; /* unit of physical scale */
  182089. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182090. double scal_pixel_width; /* width of one pixel */
  182091. double scal_pixel_height; /* height of one pixel */
  182092. #endif
  182093. #ifdef PNG_FIXED_POINT_SUPPORTED
  182094. png_charp scal_s_width; /* string containing height */
  182095. png_charp scal_s_height; /* string containing width */
  182096. #endif
  182097. #endif
  182098. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182099. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182100. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182101. png_bytepp row_pointers; /* the image bits */
  182102. #endif
  182103. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182104. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182105. #endif
  182106. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182107. png_fixed_point int_x_white;
  182108. png_fixed_point int_y_white;
  182109. png_fixed_point int_x_red;
  182110. png_fixed_point int_y_red;
  182111. png_fixed_point int_x_green;
  182112. png_fixed_point int_y_green;
  182113. png_fixed_point int_x_blue;
  182114. png_fixed_point int_y_blue;
  182115. #endif
  182116. } png_info;
  182117. typedef png_info FAR * png_infop;
  182118. typedef png_info FAR * FAR * png_infopp;
  182119. /* Maximum positive integer used in PNG is (2^31)-1 */
  182120. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182121. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182122. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182123. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182124. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182125. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182126. #endif
  182127. /* These describe the color_type field in png_info. */
  182128. /* color type masks */
  182129. #define PNG_COLOR_MASK_PALETTE 1
  182130. #define PNG_COLOR_MASK_COLOR 2
  182131. #define PNG_COLOR_MASK_ALPHA 4
  182132. /* color types. Note that not all combinations are legal */
  182133. #define PNG_COLOR_TYPE_GRAY 0
  182134. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182135. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182136. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182137. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182138. /* aliases */
  182139. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182140. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182141. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182142. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182143. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182144. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182145. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182146. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182147. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182148. /* These are for the interlacing type. These values should NOT be changed. */
  182149. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182150. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182151. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182152. /* These are for the oFFs chunk. These values should NOT be changed. */
  182153. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182154. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182155. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182156. /* These are for the pCAL chunk. These values should NOT be changed. */
  182157. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182158. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182159. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182160. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182161. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182162. /* These are for the sCAL chunk. These values should NOT be changed. */
  182163. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182164. #define PNG_SCALE_METER 1 /* meters per pixel */
  182165. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182166. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182167. /* These are for the pHYs chunk. These values should NOT be changed. */
  182168. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182169. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182170. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182171. /* These are for the sRGB chunk. These values should NOT be changed. */
  182172. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182173. #define PNG_sRGB_INTENT_RELATIVE 1
  182174. #define PNG_sRGB_INTENT_SATURATION 2
  182175. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182176. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182177. /* This is for text chunks */
  182178. #define PNG_KEYWORD_MAX_LENGTH 79
  182179. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182180. #define PNG_MAX_PALETTE_LENGTH 256
  182181. /* These determine if an ancillary chunk's data has been successfully read
  182182. * from the PNG header, or if the application has filled in the corresponding
  182183. * data in the info_struct to be written into the output file. The values
  182184. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182185. */
  182186. #define PNG_INFO_gAMA 0x0001
  182187. #define PNG_INFO_sBIT 0x0002
  182188. #define PNG_INFO_cHRM 0x0004
  182189. #define PNG_INFO_PLTE 0x0008
  182190. #define PNG_INFO_tRNS 0x0010
  182191. #define PNG_INFO_bKGD 0x0020
  182192. #define PNG_INFO_hIST 0x0040
  182193. #define PNG_INFO_pHYs 0x0080
  182194. #define PNG_INFO_oFFs 0x0100
  182195. #define PNG_INFO_tIME 0x0200
  182196. #define PNG_INFO_pCAL 0x0400
  182197. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182198. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182199. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182200. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182201. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182202. /* This is used for the transformation routines, as some of them
  182203. * change these values for the row. It also should enable using
  182204. * the routines for other purposes.
  182205. */
  182206. typedef struct png_row_info_struct
  182207. {
  182208. png_uint_32 width; /* width of row */
  182209. png_uint_32 rowbytes; /* number of bytes in row */
  182210. png_byte color_type; /* color type of row */
  182211. png_byte bit_depth; /* bit depth of row */
  182212. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182213. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182214. } png_row_info;
  182215. typedef png_row_info FAR * png_row_infop;
  182216. typedef png_row_info FAR * FAR * png_row_infopp;
  182217. /* These are the function types for the I/O functions and for the functions
  182218. * that allow the user to override the default I/O functions with his or her
  182219. * own. The png_error_ptr type should match that of user-supplied warning
  182220. * and error functions, while the png_rw_ptr type should match that of the
  182221. * user read/write data functions.
  182222. */
  182223. typedef struct png_struct_def png_struct;
  182224. typedef png_struct FAR * png_structp;
  182225. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182226. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182227. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182228. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182229. int));
  182230. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182231. int));
  182232. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182233. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182234. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182235. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182236. png_uint_32, int));
  182237. #endif
  182238. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182239. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182240. defined(PNG_LEGACY_SUPPORTED)
  182241. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182242. png_row_infop, png_bytep));
  182243. #endif
  182244. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182245. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182246. #endif
  182247. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182248. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182249. #endif
  182250. /* Transform masks for the high-level interface */
  182251. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182252. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182253. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182254. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182255. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182256. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182257. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182258. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182259. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182260. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182261. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182262. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182263. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182264. /* Flags for MNG supported features */
  182265. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182266. #define PNG_FLAG_MNG_FILTER_64 0x04
  182267. #define PNG_ALL_MNG_FEATURES 0x05
  182268. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182269. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182270. /* The structure that holds the information to read and write PNG files.
  182271. * The only people who need to care about what is inside of this are the
  182272. * people who will be modifying the library for their own special needs.
  182273. * It should NOT be accessed directly by an application, except to store
  182274. * the jmp_buf.
  182275. */
  182276. struct png_struct_def
  182277. {
  182278. #ifdef PNG_SETJMP_SUPPORTED
  182279. jmp_buf jmpbuf; /* used in png_error */
  182280. #endif
  182281. png_error_ptr error_fn; /* function for printing errors and aborting */
  182282. png_error_ptr warning_fn; /* function for printing warnings */
  182283. png_voidp error_ptr; /* user supplied struct for error functions */
  182284. png_rw_ptr write_data_fn; /* function for writing output data */
  182285. png_rw_ptr read_data_fn; /* function for reading input data */
  182286. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182287. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182288. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182289. #endif
  182290. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182291. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182292. #endif
  182293. /* These were added in libpng-1.0.2 */
  182294. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182295. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182296. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182297. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182298. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182299. png_byte user_transform_channels; /* channels in user transformed pixels */
  182300. #endif
  182301. #endif
  182302. png_uint_32 mode; /* tells us where we are in the PNG file */
  182303. png_uint_32 flags; /* flags indicating various things to libpng */
  182304. png_uint_32 transformations; /* which transformations to perform */
  182305. z_stream zstream; /* pointer to decompression structure (below) */
  182306. png_bytep zbuf; /* buffer for zlib */
  182307. png_size_t zbuf_size; /* size of zbuf */
  182308. int zlib_level; /* holds zlib compression level */
  182309. int zlib_method; /* holds zlib compression method */
  182310. int zlib_window_bits; /* holds zlib compression window bits */
  182311. int zlib_mem_level; /* holds zlib compression memory level */
  182312. int zlib_strategy; /* holds zlib compression strategy */
  182313. png_uint_32 width; /* width of image in pixels */
  182314. png_uint_32 height; /* height of image in pixels */
  182315. png_uint_32 num_rows; /* number of rows in current pass */
  182316. png_uint_32 usr_width; /* width of row at start of write */
  182317. png_uint_32 rowbytes; /* size of row in bytes */
  182318. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182319. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182320. png_uint_32 row_number; /* current row in interlace pass */
  182321. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182322. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182323. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182324. png_bytep up_row; /* buffer to save "up" row when filtering */
  182325. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182326. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182327. png_row_info row_info; /* used for transformation routines */
  182328. png_uint_32 idat_size; /* current IDAT size for read */
  182329. png_uint_32 crc; /* current chunk CRC value */
  182330. png_colorp palette; /* palette from the input file */
  182331. png_uint_16 num_palette; /* number of color entries in palette */
  182332. png_uint_16 num_trans; /* number of transparency values */
  182333. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182334. png_byte compression; /* file compression type (always 0) */
  182335. png_byte filter; /* file filter type (always 0) */
  182336. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182337. png_byte pass; /* current interlace pass (0 - 6) */
  182338. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182339. png_byte color_type; /* color type of file */
  182340. png_byte bit_depth; /* bit depth of file */
  182341. png_byte usr_bit_depth; /* bit depth of users row */
  182342. png_byte pixel_depth; /* number of bits per pixel */
  182343. png_byte channels; /* number of channels in file */
  182344. png_byte usr_channels; /* channels at start of write */
  182345. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182346. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182347. #ifdef PNG_LEGACY_SUPPORTED
  182348. png_byte filler; /* filler byte for pixel expansion */
  182349. #else
  182350. png_uint_16 filler; /* filler bytes for pixel expansion */
  182351. #endif
  182352. #endif
  182353. #if defined(PNG_bKGD_SUPPORTED)
  182354. png_byte background_gamma_type;
  182355. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182356. float background_gamma;
  182357. # endif
  182358. png_color_16 background; /* background color in screen gamma space */
  182359. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182360. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182361. #endif
  182362. #endif /* PNG_bKGD_SUPPORTED */
  182363. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182364. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182365. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182366. png_uint_32 flush_rows; /* number of rows written since last flush */
  182367. #endif
  182368. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182369. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182370. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182371. float gamma; /* file gamma value */
  182372. float screen_gamma; /* screen gamma value (display_exponent) */
  182373. #endif
  182374. #endif
  182375. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182376. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182377. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182378. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182379. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182380. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182381. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182382. #endif
  182383. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182384. png_color_8 sig_bit; /* significant bits in each available channel */
  182385. #endif
  182386. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182387. png_color_8 shift; /* shift for significant bit tranformation */
  182388. #endif
  182389. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182390. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182391. png_bytep trans; /* transparency values for paletted files */
  182392. png_color_16 trans_values; /* transparency values for non-paletted files */
  182393. #endif
  182394. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182395. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182396. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182397. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182398. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182399. png_progressive_end_ptr end_fn; /* called after image is complete */
  182400. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182401. png_bytep save_buffer; /* buffer for previously read data */
  182402. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182403. png_bytep current_buffer; /* buffer for recently used data */
  182404. png_uint_32 push_length; /* size of current input chunk */
  182405. png_uint_32 skip_length; /* bytes to skip in input data */
  182406. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182407. png_size_t save_buffer_max; /* total size of save_buffer */
  182408. png_size_t buffer_size; /* total amount of available input data */
  182409. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182410. int process_mode; /* what push library is currently doing */
  182411. int cur_palette; /* current push library palette index */
  182412. # if defined(PNG_TEXT_SUPPORTED)
  182413. png_size_t current_text_size; /* current size of text input data */
  182414. png_size_t current_text_left; /* how much text left to read in input */
  182415. png_charp current_text; /* current text chunk buffer */
  182416. png_charp current_text_ptr; /* current location in current_text */
  182417. # endif /* PNG_TEXT_SUPPORTED */
  182418. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182419. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182420. /* for the Borland special 64K segment handler */
  182421. png_bytepp offset_table_ptr;
  182422. png_bytep offset_table;
  182423. png_uint_16 offset_table_number;
  182424. png_uint_16 offset_table_count;
  182425. png_uint_16 offset_table_count_free;
  182426. #endif
  182427. #if defined(PNG_READ_DITHER_SUPPORTED)
  182428. png_bytep palette_lookup; /* lookup table for dithering */
  182429. png_bytep dither_index; /* index translation for palette files */
  182430. #endif
  182431. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182432. png_uint_16p hist; /* histogram */
  182433. #endif
  182434. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182435. png_byte heuristic_method; /* heuristic for row filter selection */
  182436. png_byte num_prev_filters; /* number of weights for previous rows */
  182437. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182438. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182439. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182440. png_uint_16p filter_costs; /* relative filter calculation cost */
  182441. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182442. #endif
  182443. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182444. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182445. #endif
  182446. /* New members added in libpng-1.0.6 */
  182447. #ifdef PNG_FREE_ME_SUPPORTED
  182448. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182449. #endif
  182450. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182451. png_voidp user_chunk_ptr;
  182452. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182453. #endif
  182454. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182455. int num_chunk_list;
  182456. png_bytep chunk_list;
  182457. #endif
  182458. /* New members added in libpng-1.0.3 */
  182459. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182460. png_byte rgb_to_gray_status;
  182461. /* These were changed from png_byte in libpng-1.0.6 */
  182462. png_uint_16 rgb_to_gray_red_coeff;
  182463. png_uint_16 rgb_to_gray_green_coeff;
  182464. png_uint_16 rgb_to_gray_blue_coeff;
  182465. #endif
  182466. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182467. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182468. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182469. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182470. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182471. #ifdef PNG_1_0_X
  182472. png_byte mng_features_permitted;
  182473. #else
  182474. png_uint_32 mng_features_permitted;
  182475. #endif /* PNG_1_0_X */
  182476. #endif
  182477. /* New member added in libpng-1.0.7 */
  182478. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182479. png_fixed_point int_gamma;
  182480. #endif
  182481. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182482. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182483. png_byte filter_type;
  182484. #endif
  182485. #if defined(PNG_1_0_X)
  182486. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182487. png_uint_32 row_buf_size;
  182488. #endif
  182489. /* New members added in libpng-1.2.0 */
  182490. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182491. # if !defined(PNG_1_0_X)
  182492. # if defined(PNG_MMX_CODE_SUPPORTED)
  182493. png_byte mmx_bitdepth_threshold;
  182494. png_uint_32 mmx_rowbytes_threshold;
  182495. # endif
  182496. png_uint_32 asm_flags;
  182497. # endif
  182498. #endif
  182499. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182500. #ifdef PNG_USER_MEM_SUPPORTED
  182501. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182502. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182503. png_free_ptr free_fn; /* function for freeing memory */
  182504. #endif
  182505. /* New member added in libpng-1.0.13 and 1.2.0 */
  182506. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182507. #if defined(PNG_READ_DITHER_SUPPORTED)
  182508. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182509. png_bytep dither_sort; /* working sort array */
  182510. png_bytep index_to_palette; /* where the original index currently is */
  182511. /* in the palette */
  182512. png_bytep palette_to_index; /* which original index points to this */
  182513. /* palette color */
  182514. #endif
  182515. /* New members added in libpng-1.0.16 and 1.2.6 */
  182516. png_byte compression_type;
  182517. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182518. png_uint_32 user_width_max;
  182519. png_uint_32 user_height_max;
  182520. #endif
  182521. /* New member added in libpng-1.0.25 and 1.2.17 */
  182522. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182523. /* storage for unknown chunk that the library doesn't recognize. */
  182524. png_unknown_chunk unknown_chunk;
  182525. #endif
  182526. };
  182527. /* This triggers a compiler error in png.c, if png.c and png.h
  182528. * do not agree upon the version number.
  182529. */
  182530. typedef png_structp version_1_2_21;
  182531. typedef png_struct FAR * FAR * png_structpp;
  182532. /* Here are the function definitions most commonly used. This is not
  182533. * the place to find out how to use libpng. See libpng.txt for the
  182534. * full explanation, see example.c for the summary. This just provides
  182535. * a simple one line description of the use of each function.
  182536. */
  182537. /* Returns the version number of the library */
  182538. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182539. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182540. * Handling more than 8 bytes from the beginning of the file is an error.
  182541. */
  182542. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182543. int num_bytes));
  182544. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182545. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182546. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182547. * start > 7 will always fail (ie return non-zero).
  182548. */
  182549. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182550. png_size_t num_to_check));
  182551. /* Simple signature checking function. This is the same as calling
  182552. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182553. */
  182554. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182555. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182556. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182557. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182558. png_error_ptr error_fn, png_error_ptr warn_fn));
  182559. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182560. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182561. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182562. png_error_ptr error_fn, png_error_ptr warn_fn));
  182563. #ifdef PNG_WRITE_SUPPORTED
  182564. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182565. PNGARG((png_structp png_ptr));
  182566. #endif
  182567. #ifdef PNG_WRITE_SUPPORTED
  182568. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182569. PNGARG((png_structp png_ptr, png_uint_32 size));
  182570. #endif
  182571. /* Reset the compression stream */
  182572. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182573. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182574. #ifdef PNG_USER_MEM_SUPPORTED
  182575. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182576. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182577. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182578. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182579. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182580. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182581. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182582. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182583. #endif
  182584. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182585. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182586. png_bytep chunk_name, png_bytep data, png_size_t length));
  182587. /* Write the start of a PNG chunk - length and chunk name. */
  182588. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182589. png_bytep chunk_name, png_uint_32 length));
  182590. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182591. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182592. png_bytep data, png_size_t length));
  182593. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182594. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182595. /* Allocate and initialize the info structure */
  182596. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182597. PNGARG((png_structp png_ptr));
  182598. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182599. /* Initialize the info structure (old interface - DEPRECATED) */
  182600. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182601. #undef png_info_init
  182602. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182603. png_sizeof(png_info));
  182604. #endif
  182605. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182606. png_size_t png_info_struct_size));
  182607. /* Writes all the PNG information before the image. */
  182608. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182609. png_infop info_ptr));
  182610. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182611. png_infop info_ptr));
  182612. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182613. /* read the information before the actual image data. */
  182614. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182615. png_infop info_ptr));
  182616. #endif
  182617. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182618. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182619. PNGARG((png_structp png_ptr, png_timep ptime));
  182620. #endif
  182621. #if !defined(_WIN32_WCE)
  182622. /* "time.h" functions are not supported on WindowsCE */
  182623. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182624. /* convert from a struct tm to png_time */
  182625. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182626. struct tm FAR * ttime));
  182627. /* convert from time_t to png_time. Uses gmtime() */
  182628. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182629. time_t ttime));
  182630. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182631. #endif /* _WIN32_WCE */
  182632. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182633. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182634. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182635. #if !defined(PNG_1_0_X)
  182636. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182637. png_ptr));
  182638. #endif
  182639. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182640. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182641. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182642. /* Deprecated */
  182643. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182644. #endif
  182645. #endif
  182646. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182647. /* Use blue, green, red order for pixels. */
  182648. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182649. #endif
  182650. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182651. /* Expand the grayscale to 24-bit RGB if necessary. */
  182652. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182653. #endif
  182654. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182655. /* Reduce RGB to grayscale. */
  182656. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182657. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182658. int error_action, double red, double green ));
  182659. #endif
  182660. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182661. int error_action, png_fixed_point red, png_fixed_point green ));
  182662. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182663. png_ptr));
  182664. #endif
  182665. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  182666. png_colorp palette));
  182667. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  182668. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  182669. #endif
  182670. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  182671. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  182672. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  182673. #endif
  182674. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  182675. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  182676. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  182677. #endif
  182678. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182679. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  182680. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  182681. png_uint_32 filler, int flags));
  182682. /* The values of the PNG_FILLER_ defines should NOT be changed */
  182683. #define PNG_FILLER_BEFORE 0
  182684. #define PNG_FILLER_AFTER 1
  182685. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  182686. #if !defined(PNG_1_0_X)
  182687. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  182688. png_uint_32 filler, int flags));
  182689. #endif
  182690. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  182691. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  182692. /* Swap bytes in 16-bit depth files. */
  182693. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  182694. #endif
  182695. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  182696. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  182697. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  182698. #endif
  182699. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  182700. /* Swap packing order of pixels in bytes. */
  182701. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  182702. #endif
  182703. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182704. /* Converts files to legal bit depths. */
  182705. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  182706. png_color_8p true_bits));
  182707. #endif
  182708. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  182709. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182710. /* Have the code handle the interlacing. Returns the number of passes. */
  182711. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  182712. #endif
  182713. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  182714. /* Invert monochrome files */
  182715. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  182716. #endif
  182717. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  182718. /* Handle alpha and tRNS by replacing with a background color. */
  182719. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182720. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  182721. png_color_16p background_color, int background_gamma_code,
  182722. int need_expand, double background_gamma));
  182723. #endif
  182724. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  182725. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  182726. #define PNG_BACKGROUND_GAMMA_FILE 2
  182727. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  182728. #endif
  182729. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  182730. /* strip the second byte of information from a 16-bit depth file. */
  182731. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  182732. #endif
  182733. #if defined(PNG_READ_DITHER_SUPPORTED)
  182734. /* Turn on dithering, and reduce the palette to the number of colors available. */
  182735. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  182736. png_colorp palette, int num_palette, int maximum_colors,
  182737. png_uint_16p histogram, int full_dither));
  182738. #endif
  182739. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182740. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  182741. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182742. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  182743. double screen_gamma, double default_file_gamma));
  182744. #endif
  182745. #endif
  182746. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182747. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182748. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182749. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  182750. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  182751. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  182752. int empty_plte_permitted));
  182753. #endif
  182754. #endif
  182755. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182756. /* Set how many lines between output flushes - 0 for no flushing */
  182757. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  182758. /* Flush the current PNG output buffer */
  182759. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  182760. #endif
  182761. /* optional update palette with requested transformations */
  182762. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  182763. /* optional call to update the users info structure */
  182764. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  182765. png_infop info_ptr));
  182766. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182767. /* read one or more rows of image data. */
  182768. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  182769. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  182770. #endif
  182771. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182772. /* read a row of data. */
  182773. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  182774. png_bytep row,
  182775. png_bytep display_row));
  182776. #endif
  182777. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182778. /* read the whole image into memory at once. */
  182779. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  182780. png_bytepp image));
  182781. #endif
  182782. /* write a row of image data */
  182783. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  182784. png_bytep row));
  182785. /* write a few rows of image data */
  182786. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  182787. png_bytepp row, png_uint_32 num_rows));
  182788. /* write the image data */
  182789. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  182790. png_bytepp image));
  182791. /* writes the end of the PNG file. */
  182792. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  182793. png_infop info_ptr));
  182794. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182795. /* read the end of the PNG file. */
  182796. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  182797. png_infop info_ptr));
  182798. #endif
  182799. /* free any memory associated with the png_info_struct */
  182800. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  182801. png_infopp info_ptr_ptr));
  182802. /* free any memory associated with the png_struct and the png_info_structs */
  182803. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  182804. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  182805. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  182806. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  182807. png_infop end_info_ptr));
  182808. /* free any memory associated with the png_struct and the png_info_structs */
  182809. extern PNG_EXPORT(void,png_destroy_write_struct)
  182810. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  182811. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  182812. extern void png_write_destroy PNGARG((png_structp png_ptr));
  182813. /* set the libpng method of handling chunk CRC errors */
  182814. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  182815. int crit_action, int ancil_action));
  182816. /* Values for png_set_crc_action() to say how to handle CRC errors in
  182817. * ancillary and critical chunks, and whether to use the data contained
  182818. * therein. Note that it is impossible to "discard" data in a critical
  182819. * chunk. For versions prior to 0.90, the action was always error/quit,
  182820. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  182821. * chunks is warn/discard. These values should NOT be changed.
  182822. *
  182823. * value action:critical action:ancillary
  182824. */
  182825. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  182826. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  182827. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  182828. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  182829. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  182830. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  182831. /* These functions give the user control over the scan-line filtering in
  182832. * libpng and the compression methods used by zlib. These functions are
  182833. * mainly useful for testing, as the defaults should work with most users.
  182834. * Those users who are tight on memory or want faster performance at the
  182835. * expense of compression can modify them. See the compression library
  182836. * header file (zlib.h) for an explination of the compression functions.
  182837. */
  182838. /* set the filtering method(s) used by libpng. Currently, the only valid
  182839. * value for "method" is 0.
  182840. */
  182841. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  182842. int filters));
  182843. /* Flags for png_set_filter() to say which filters to use. The flags
  182844. * are chosen so that they don't conflict with real filter types
  182845. * below, in case they are supplied instead of the #defined constants.
  182846. * These values should NOT be changed.
  182847. */
  182848. #define PNG_NO_FILTERS 0x00
  182849. #define PNG_FILTER_NONE 0x08
  182850. #define PNG_FILTER_SUB 0x10
  182851. #define PNG_FILTER_UP 0x20
  182852. #define PNG_FILTER_AVG 0x40
  182853. #define PNG_FILTER_PAETH 0x80
  182854. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  182855. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  182856. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  182857. * These defines should NOT be changed.
  182858. */
  182859. #define PNG_FILTER_VALUE_NONE 0
  182860. #define PNG_FILTER_VALUE_SUB 1
  182861. #define PNG_FILTER_VALUE_UP 2
  182862. #define PNG_FILTER_VALUE_AVG 3
  182863. #define PNG_FILTER_VALUE_PAETH 4
  182864. #define PNG_FILTER_VALUE_LAST 5
  182865. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  182866. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  182867. * defines, either the default (minimum-sum-of-absolute-differences), or
  182868. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  182869. *
  182870. * Weights are factors >= 1.0, indicating how important it is to keep the
  182871. * filter type consistent between rows. Larger numbers mean the current
  182872. * filter is that many times as likely to be the same as the "num_weights"
  182873. * previous filters. This is cumulative for each previous row with a weight.
  182874. * There needs to be "num_weights" values in "filter_weights", or it can be
  182875. * NULL if the weights aren't being specified. Weights have no influence on
  182876. * the selection of the first row filter. Well chosen weights can (in theory)
  182877. * improve the compression for a given image.
  182878. *
  182879. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  182880. * filter type. Higher costs indicate more decoding expense, and are
  182881. * therefore less likely to be selected over a filter with lower computational
  182882. * costs. There needs to be a value in "filter_costs" for each valid filter
  182883. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  182884. * setting the costs. Costs try to improve the speed of decompression without
  182885. * unduly increasing the compressed image size.
  182886. *
  182887. * A negative weight or cost indicates the default value is to be used, and
  182888. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  182889. * The default values for both weights and costs are currently 1.0, but may
  182890. * change if good general weighting/cost heuristics can be found. If both
  182891. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  182892. * to the UNWEIGHTED method, but with added encoding time/computation.
  182893. */
  182894. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182895. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  182896. int heuristic_method, int num_weights, png_doublep filter_weights,
  182897. png_doublep filter_costs));
  182898. #endif
  182899. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  182900. /* Heuristic used for row filter selection. These defines should NOT be
  182901. * changed.
  182902. */
  182903. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  182904. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  182905. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  182906. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  182907. /* Set the library compression level. Currently, valid values range from
  182908. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  182909. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  182910. * shown that zlib compression levels 3-6 usually perform as well as level 9
  182911. * for PNG images, and do considerably fewer caclulations. In the future,
  182912. * these values may not correspond directly to the zlib compression levels.
  182913. */
  182914. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  182915. int level));
  182916. extern PNG_EXPORT(void,png_set_compression_mem_level)
  182917. PNGARG((png_structp png_ptr, int mem_level));
  182918. extern PNG_EXPORT(void,png_set_compression_strategy)
  182919. PNGARG((png_structp png_ptr, int strategy));
  182920. extern PNG_EXPORT(void,png_set_compression_window_bits)
  182921. PNGARG((png_structp png_ptr, int window_bits));
  182922. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  182923. int method));
  182924. /* These next functions are called for input/output, memory, and error
  182925. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  182926. * and call standard C I/O routines such as fread(), fwrite(), and
  182927. * fprintf(). These functions can be made to use other I/O routines
  182928. * at run time for those applications that need to handle I/O in a
  182929. * different manner by calling png_set_???_fn(). See libpng.txt for
  182930. * more information.
  182931. */
  182932. #if !defined(PNG_NO_STDIO)
  182933. /* Initialize the input/output for the PNG file to the default functions. */
  182934. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  182935. #endif
  182936. /* Replace the (error and abort), and warning functions with user
  182937. * supplied functions. If no messages are to be printed you must still
  182938. * write and use replacement functions. The replacement error_fn should
  182939. * still do a longjmp to the last setjmp location if you are using this
  182940. * method of error handling. If error_fn or warning_fn is NULL, the
  182941. * default function will be used.
  182942. */
  182943. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  182944. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  182945. /* Return the user pointer associated with the error functions */
  182946. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  182947. /* Replace the default data output functions with a user supplied one(s).
  182948. * If buffered output is not used, then output_flush_fn can be set to NULL.
  182949. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  182950. * output_flush_fn will be ignored (and thus can be NULL).
  182951. */
  182952. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  182953. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  182954. /* Replace the default data input function with a user supplied one. */
  182955. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  182956. png_voidp io_ptr, png_rw_ptr read_data_fn));
  182957. /* Return the user pointer associated with the I/O functions */
  182958. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  182959. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  182960. png_read_status_ptr read_row_fn));
  182961. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  182962. png_write_status_ptr write_row_fn));
  182963. #ifdef PNG_USER_MEM_SUPPORTED
  182964. /* Replace the default memory allocation functions with user supplied one(s). */
  182965. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  182966. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182967. /* Return the user pointer associated with the memory functions */
  182968. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  182969. #endif
  182970. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182971. defined(PNG_LEGACY_SUPPORTED)
  182972. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  182973. png_ptr, png_user_transform_ptr read_user_transform_fn));
  182974. #endif
  182975. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182976. defined(PNG_LEGACY_SUPPORTED)
  182977. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  182978. png_ptr, png_user_transform_ptr write_user_transform_fn));
  182979. #endif
  182980. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182981. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182982. defined(PNG_LEGACY_SUPPORTED)
  182983. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  182984. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  182985. int user_transform_channels));
  182986. /* Return the user pointer associated with the user transform functions */
  182987. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  182988. PNGARG((png_structp png_ptr));
  182989. #endif
  182990. #ifdef PNG_USER_CHUNKS_SUPPORTED
  182991. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  182992. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  182993. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  182994. png_ptr));
  182995. #endif
  182996. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182997. /* Sets the function callbacks for the push reader, and a pointer to a
  182998. * user-defined structure available to the callback functions.
  182999. */
  183000. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183001. png_voidp progressive_ptr,
  183002. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183003. png_progressive_end_ptr end_fn));
  183004. /* returns the user pointer associated with the push read functions */
  183005. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183006. PNGARG((png_structp png_ptr));
  183007. /* function to be called when data becomes available */
  183008. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183009. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183010. /* function that combines rows. Not very much different than the
  183011. * png_combine_row() call. Is this even used?????
  183012. */
  183013. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183014. png_bytep old_row, png_bytep new_row));
  183015. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183016. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183017. png_uint_32 size));
  183018. #if defined(PNG_1_0_X)
  183019. # define png_malloc_warn png_malloc
  183020. #else
  183021. /* Added at libpng version 1.2.4 */
  183022. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183023. png_uint_32 size));
  183024. #endif
  183025. /* frees a pointer allocated by png_malloc() */
  183026. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183027. #if defined(PNG_1_0_X)
  183028. /* Function to allocate memory for zlib. */
  183029. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183030. uInt size));
  183031. /* Function to free memory for zlib */
  183032. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183033. #endif
  183034. /* Free data that was allocated internally */
  183035. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183036. png_infop info_ptr, png_uint_32 free_me, int num));
  183037. #ifdef PNG_FREE_ME_SUPPORTED
  183038. /* Reassign responsibility for freeing existing data, whether allocated
  183039. * by libpng or by the application */
  183040. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183041. png_infop info_ptr, int freer, png_uint_32 mask));
  183042. #endif
  183043. /* assignments for png_data_freer */
  183044. #define PNG_DESTROY_WILL_FREE_DATA 1
  183045. #define PNG_SET_WILL_FREE_DATA 1
  183046. #define PNG_USER_WILL_FREE_DATA 2
  183047. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183048. #define PNG_FREE_HIST 0x0008
  183049. #define PNG_FREE_ICCP 0x0010
  183050. #define PNG_FREE_SPLT 0x0020
  183051. #define PNG_FREE_ROWS 0x0040
  183052. #define PNG_FREE_PCAL 0x0080
  183053. #define PNG_FREE_SCAL 0x0100
  183054. #define PNG_FREE_UNKN 0x0200
  183055. #define PNG_FREE_LIST 0x0400
  183056. #define PNG_FREE_PLTE 0x1000
  183057. #define PNG_FREE_TRNS 0x2000
  183058. #define PNG_FREE_TEXT 0x4000
  183059. #define PNG_FREE_ALL 0x7fff
  183060. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183061. #ifdef PNG_USER_MEM_SUPPORTED
  183062. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183063. png_uint_32 size));
  183064. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183065. png_voidp ptr));
  183066. #endif
  183067. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183068. png_voidp s1, png_voidp s2, png_uint_32 size));
  183069. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183070. png_voidp s1, int value, png_uint_32 size));
  183071. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183072. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183073. int check));
  183074. #endif /* USE_FAR_KEYWORD */
  183075. #ifndef PNG_NO_ERROR_TEXT
  183076. /* Fatal error in PNG image of libpng - can't continue */
  183077. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183078. png_const_charp error_message));
  183079. /* The same, but the chunk name is prepended to the error string. */
  183080. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183081. png_const_charp error_message));
  183082. #else
  183083. /* Fatal error in PNG image of libpng - can't continue */
  183084. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183085. #endif
  183086. #ifndef PNG_NO_WARNINGS
  183087. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183088. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183089. png_const_charp warning_message));
  183090. #ifdef PNG_READ_SUPPORTED
  183091. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183092. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183093. png_const_charp warning_message));
  183094. #endif /* PNG_READ_SUPPORTED */
  183095. #endif /* PNG_NO_WARNINGS */
  183096. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183097. * Similarly, the png_get_<chunk> calls are used to read values from the
  183098. * png_info_struct, either storing the parameters in the passed variables, or
  183099. * setting pointers into the png_info_struct where the data is stored. The
  183100. * png_get_<chunk> functions return a non-zero value if the data was available
  183101. * in info_ptr, or return zero and do not change any of the parameters if the
  183102. * data was not available.
  183103. *
  183104. * These functions should be used instead of directly accessing png_info
  183105. * to avoid problems with future changes in the size and internal layout of
  183106. * png_info_struct.
  183107. */
  183108. /* Returns "flag" if chunk data is valid in info_ptr. */
  183109. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183110. png_infop info_ptr, png_uint_32 flag));
  183111. /* Returns number of bytes needed to hold a transformed row. */
  183112. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183113. png_infop info_ptr));
  183114. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183115. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183116. returned from png_read_png(). */
  183117. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183118. png_infop info_ptr));
  183119. /* Set row_pointers, which is an array of pointers to scanlines for use
  183120. by png_write_png(). */
  183121. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183122. png_infop info_ptr, png_bytepp row_pointers));
  183123. #endif
  183124. /* Returns number of color channels in image. */
  183125. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183126. png_infop info_ptr));
  183127. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183128. /* Returns image width in pixels. */
  183129. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183130. png_ptr, png_infop info_ptr));
  183131. /* Returns image height in pixels. */
  183132. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183133. png_ptr, png_infop info_ptr));
  183134. /* Returns image bit_depth. */
  183135. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183136. png_ptr, png_infop info_ptr));
  183137. /* Returns image color_type. */
  183138. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183139. png_ptr, png_infop info_ptr));
  183140. /* Returns image filter_type. */
  183141. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183142. png_ptr, png_infop info_ptr));
  183143. /* Returns image interlace_type. */
  183144. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183145. png_ptr, png_infop info_ptr));
  183146. /* Returns image compression_type. */
  183147. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183148. png_ptr, png_infop info_ptr));
  183149. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183150. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183151. png_ptr, png_infop info_ptr));
  183152. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183153. png_ptr, png_infop info_ptr));
  183154. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183155. png_ptr, png_infop info_ptr));
  183156. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183157. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183158. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183159. png_ptr, png_infop info_ptr));
  183160. #endif
  183161. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183162. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183163. png_ptr, png_infop info_ptr));
  183164. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183165. png_ptr, png_infop info_ptr));
  183166. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183167. png_ptr, png_infop info_ptr));
  183168. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183169. png_ptr, png_infop info_ptr));
  183170. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183171. /* Returns pointer to signature string read from PNG header */
  183172. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183173. png_infop info_ptr));
  183174. #if defined(PNG_bKGD_SUPPORTED)
  183175. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183176. png_infop info_ptr, png_color_16p *background));
  183177. #endif
  183178. #if defined(PNG_bKGD_SUPPORTED)
  183179. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183180. png_infop info_ptr, png_color_16p background));
  183181. #endif
  183182. #if defined(PNG_cHRM_SUPPORTED)
  183183. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183184. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183185. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183186. double *red_y, double *green_x, double *green_y, double *blue_x,
  183187. double *blue_y));
  183188. #endif
  183189. #ifdef PNG_FIXED_POINT_SUPPORTED
  183190. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183191. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183192. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183193. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183194. *int_blue_x, png_fixed_point *int_blue_y));
  183195. #endif
  183196. #endif
  183197. #if defined(PNG_cHRM_SUPPORTED)
  183198. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183199. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183200. png_infop info_ptr, double white_x, double white_y, double red_x,
  183201. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183202. #endif
  183203. #ifdef PNG_FIXED_POINT_SUPPORTED
  183204. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183205. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183206. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183207. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183208. png_fixed_point int_blue_y));
  183209. #endif
  183210. #endif
  183211. #if defined(PNG_gAMA_SUPPORTED)
  183212. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183213. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183214. png_infop info_ptr, double *file_gamma));
  183215. #endif
  183216. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183217. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183218. #endif
  183219. #if defined(PNG_gAMA_SUPPORTED)
  183220. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183221. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183222. png_infop info_ptr, double file_gamma));
  183223. #endif
  183224. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183225. png_infop info_ptr, png_fixed_point int_file_gamma));
  183226. #endif
  183227. #if defined(PNG_hIST_SUPPORTED)
  183228. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183229. png_infop info_ptr, png_uint_16p *hist));
  183230. #endif
  183231. #if defined(PNG_hIST_SUPPORTED)
  183232. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183233. png_infop info_ptr, png_uint_16p hist));
  183234. #endif
  183235. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183236. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183237. int *bit_depth, int *color_type, int *interlace_method,
  183238. int *compression_method, int *filter_method));
  183239. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183240. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183241. int color_type, int interlace_method, int compression_method,
  183242. int filter_method));
  183243. #if defined(PNG_oFFs_SUPPORTED)
  183244. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183245. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183246. int *unit_type));
  183247. #endif
  183248. #if defined(PNG_oFFs_SUPPORTED)
  183249. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183250. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183251. int unit_type));
  183252. #endif
  183253. #if defined(PNG_pCAL_SUPPORTED)
  183254. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183255. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183256. int *type, int *nparams, png_charp *units, png_charpp *params));
  183257. #endif
  183258. #if defined(PNG_pCAL_SUPPORTED)
  183259. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183260. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183261. int type, int nparams, png_charp units, png_charpp params));
  183262. #endif
  183263. #if defined(PNG_pHYs_SUPPORTED)
  183264. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183265. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183266. #endif
  183267. #if defined(PNG_pHYs_SUPPORTED)
  183268. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183269. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183270. #endif
  183271. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183272. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183273. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183274. png_infop info_ptr, png_colorp palette, int num_palette));
  183275. #if defined(PNG_sBIT_SUPPORTED)
  183276. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183277. png_infop info_ptr, png_color_8p *sig_bit));
  183278. #endif
  183279. #if defined(PNG_sBIT_SUPPORTED)
  183280. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183281. png_infop info_ptr, png_color_8p sig_bit));
  183282. #endif
  183283. #if defined(PNG_sRGB_SUPPORTED)
  183284. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183285. png_infop info_ptr, int *intent));
  183286. #endif
  183287. #if defined(PNG_sRGB_SUPPORTED)
  183288. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183289. png_infop info_ptr, int intent));
  183290. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183291. png_infop info_ptr, int intent));
  183292. #endif
  183293. #if defined(PNG_iCCP_SUPPORTED)
  183294. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183295. png_infop info_ptr, png_charpp name, int *compression_type,
  183296. png_charpp profile, png_uint_32 *proflen));
  183297. /* Note to maintainer: profile should be png_bytepp */
  183298. #endif
  183299. #if defined(PNG_iCCP_SUPPORTED)
  183300. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183301. png_infop info_ptr, png_charp name, int compression_type,
  183302. png_charp profile, png_uint_32 proflen));
  183303. /* Note to maintainer: profile should be png_bytep */
  183304. #endif
  183305. #if defined(PNG_sPLT_SUPPORTED)
  183306. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183307. png_infop info_ptr, png_sPLT_tpp entries));
  183308. #endif
  183309. #if defined(PNG_sPLT_SUPPORTED)
  183310. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183311. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183312. #endif
  183313. #if defined(PNG_TEXT_SUPPORTED)
  183314. /* png_get_text also returns the number of text chunks in *num_text */
  183315. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183316. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183317. #endif
  183318. /*
  183319. * Note while png_set_text() will accept a structure whose text,
  183320. * language, and translated keywords are NULL pointers, the structure
  183321. * returned by png_get_text will always contain regular
  183322. * zero-terminated C strings. They might be empty strings but
  183323. * they will never be NULL pointers.
  183324. */
  183325. #if defined(PNG_TEXT_SUPPORTED)
  183326. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183327. png_infop info_ptr, png_textp text_ptr, int num_text));
  183328. #endif
  183329. #if defined(PNG_tIME_SUPPORTED)
  183330. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183331. png_infop info_ptr, png_timep *mod_time));
  183332. #endif
  183333. #if defined(PNG_tIME_SUPPORTED)
  183334. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183335. png_infop info_ptr, png_timep mod_time));
  183336. #endif
  183337. #if defined(PNG_tRNS_SUPPORTED)
  183338. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183339. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183340. png_color_16p *trans_values));
  183341. #endif
  183342. #if defined(PNG_tRNS_SUPPORTED)
  183343. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183344. png_infop info_ptr, png_bytep trans, int num_trans,
  183345. png_color_16p trans_values));
  183346. #endif
  183347. #if defined(PNG_tRNS_SUPPORTED)
  183348. #endif
  183349. #if defined(PNG_sCAL_SUPPORTED)
  183350. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183351. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183352. png_infop info_ptr, int *unit, double *width, double *height));
  183353. #else
  183354. #ifdef PNG_FIXED_POINT_SUPPORTED
  183355. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183356. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183357. #endif
  183358. #endif
  183359. #endif /* PNG_sCAL_SUPPORTED */
  183360. #if defined(PNG_sCAL_SUPPORTED)
  183361. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183362. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183363. png_infop info_ptr, int unit, double width, double height));
  183364. #else
  183365. #ifdef PNG_FIXED_POINT_SUPPORTED
  183366. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183367. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183368. #endif
  183369. #endif
  183370. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183371. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183372. /* provide a list of chunks and how they are to be handled, if the built-in
  183373. handling or default unknown chunk handling is not desired. Any chunks not
  183374. listed will be handled in the default manner. The IHDR and IEND chunks
  183375. must not be listed.
  183376. keep = 0: follow default behaviour
  183377. = 1: do not keep
  183378. = 2: keep only if safe-to-copy
  183379. = 3: keep even if unsafe-to-copy
  183380. */
  183381. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183382. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183383. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183384. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183385. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183386. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183387. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183388. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183389. #endif
  183390. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183391. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183392. chunk_name));
  183393. #endif
  183394. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183395. If you need to turn it off for a chunk that your application has freed,
  183396. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183397. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183398. png_infop info_ptr, int mask));
  183399. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183400. /* The "params" pointer is currently not used and is for future expansion. */
  183401. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183402. png_infop info_ptr,
  183403. int transforms,
  183404. png_voidp params));
  183405. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183406. png_infop info_ptr,
  183407. int transforms,
  183408. png_voidp params));
  183409. #endif
  183410. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183411. * numbers for PNG_DEBUG mean more debugging information. This has
  183412. * only been added since version 0.95 so it is not implemented throughout
  183413. * libpng yet, but more support will be added as needed.
  183414. */
  183415. #ifdef PNG_DEBUG
  183416. #if (PNG_DEBUG > 0)
  183417. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183418. #include <crtdbg.h>
  183419. #if (PNG_DEBUG > 1)
  183420. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183421. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183422. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183423. #endif
  183424. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183425. #ifndef PNG_DEBUG_FILE
  183426. #define PNG_DEBUG_FILE stderr
  183427. #endif /* PNG_DEBUG_FILE */
  183428. #if (PNG_DEBUG > 1)
  183429. #define png_debug(l,m) \
  183430. { \
  183431. int num_tabs=l; \
  183432. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183433. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183434. }
  183435. #define png_debug1(l,m,p1) \
  183436. { \
  183437. int num_tabs=l; \
  183438. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183439. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183440. }
  183441. #define png_debug2(l,m,p1,p2) \
  183442. { \
  183443. int num_tabs=l; \
  183444. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183445. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183446. }
  183447. #endif /* (PNG_DEBUG > 1) */
  183448. #endif /* _MSC_VER */
  183449. #endif /* (PNG_DEBUG > 0) */
  183450. #endif /* PNG_DEBUG */
  183451. #ifndef png_debug
  183452. #define png_debug(l, m)
  183453. #endif
  183454. #ifndef png_debug1
  183455. #define png_debug1(l, m, p1)
  183456. #endif
  183457. #ifndef png_debug2
  183458. #define png_debug2(l, m, p1, p2)
  183459. #endif
  183460. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183461. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183462. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183463. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183464. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183465. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183466. png_ptr, png_uint_32 mng_features_permitted));
  183467. #endif
  183468. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183469. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183470. #define PNG_HANDLE_CHUNK_NEVER 1
  183471. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183472. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183473. /* Added to version 1.2.0 */
  183474. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183475. #if defined(PNG_MMX_CODE_SUPPORTED)
  183476. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183477. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183478. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183479. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183480. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183481. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183482. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183483. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183484. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183485. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183486. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183487. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183488. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183489. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183490. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183491. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183492. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183493. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183494. | PNG_MMX_READ_FLAGS \
  183495. | PNG_MMX_WRITE_FLAGS )
  183496. #define PNG_SELECT_READ 1
  183497. #define PNG_SELECT_WRITE 2
  183498. #endif /* PNG_MMX_CODE_SUPPORTED */
  183499. #if !defined(PNG_1_0_X)
  183500. /* pngget.c */
  183501. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183502. PNGARG((int flag_select, int *compilerID));
  183503. /* pngget.c */
  183504. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183505. PNGARG((int flag_select));
  183506. /* pngget.c */
  183507. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183508. PNGARG((png_structp png_ptr));
  183509. /* pngget.c */
  183510. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183511. PNGARG((png_structp png_ptr));
  183512. /* pngget.c */
  183513. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183514. PNGARG((png_structp png_ptr));
  183515. /* pngset.c */
  183516. extern PNG_EXPORT(void,png_set_asm_flags)
  183517. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183518. /* pngset.c */
  183519. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183520. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183521. png_uint_32 mmx_rowbytes_threshold));
  183522. #endif /* PNG_1_0_X */
  183523. #if !defined(PNG_1_0_X)
  183524. /* png.c, pnggccrd.c, or pngvcrd.c */
  183525. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183526. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183527. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183528. * messages before passing them to the error or warning handler. */
  183529. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183530. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183531. png_ptr, png_uint_32 strip_mode));
  183532. #endif
  183533. #endif /* PNG_1_0_X */
  183534. /* Added at libpng-1.2.6 */
  183535. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183536. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183537. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183538. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183539. png_ptr));
  183540. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183541. png_ptr));
  183542. #endif
  183543. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183544. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183545. /* With these routines we avoid an integer divide, which will be slower on
  183546. * most machines. However, it does take more operations than the corresponding
  183547. * divide method, so it may be slower on a few RISC systems. There are two
  183548. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183549. *
  183550. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183551. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183552. * standard method.
  183553. *
  183554. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183555. */
  183556. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183557. # define png_composite(composite, fg, alpha, bg) \
  183558. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183559. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183560. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183561. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183562. # define png_composite_16(composite, fg, alpha, bg) \
  183563. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183564. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183565. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183566. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183567. #else /* standard method using integer division */
  183568. # define png_composite(composite, fg, alpha, bg) \
  183569. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183570. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183571. (png_uint_16)127) / 255)
  183572. # define png_composite_16(composite, fg, alpha, bg) \
  183573. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183574. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183575. (png_uint_32)32767) / (png_uint_32)65535L)
  183576. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183577. /* Inline macros to do direct reads of bytes from the input buffer. These
  183578. * require that you are using an architecture that uses PNG byte ordering
  183579. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183580. * in big-endian mode and 680x0 are the only ones that will support this.
  183581. * The x86 line of processors definitely do not. The png_get_int_32()
  183582. * routine also assumes we are using two's complement format for negative
  183583. * values, which is almost certainly true.
  183584. */
  183585. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183586. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183587. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183588. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183589. #else
  183590. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183591. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183592. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183593. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183594. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183595. PNGARG((png_structp png_ptr, png_bytep buf));
  183596. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183597. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183598. */
  183599. extern PNG_EXPORT(void,png_save_uint_32)
  183600. PNGARG((png_bytep buf, png_uint_32 i));
  183601. extern PNG_EXPORT(void,png_save_int_32)
  183602. PNGARG((png_bytep buf, png_int_32 i));
  183603. /* Place a 16-bit number into a buffer in PNG byte order.
  183604. * The parameter is declared unsigned int, not png_uint_16,
  183605. * just to avoid potential problems on pre-ANSI C compilers.
  183606. */
  183607. extern PNG_EXPORT(void,png_save_uint_16)
  183608. PNGARG((png_bytep buf, unsigned int i));
  183609. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183610. /* ************************************************************************* */
  183611. /* These next functions are used internally in the code. They generally
  183612. * shouldn't be used unless you are writing code to add or replace some
  183613. * functionality in libpng. More information about most functions can
  183614. * be found in the files where the functions are located.
  183615. */
  183616. /* Various modes of operation, that are visible to applications because
  183617. * they are used for unknown chunk location.
  183618. */
  183619. #define PNG_HAVE_IHDR 0x01
  183620. #define PNG_HAVE_PLTE 0x02
  183621. #define PNG_HAVE_IDAT 0x04
  183622. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183623. #define PNG_HAVE_IEND 0x10
  183624. #if defined(PNG_INTERNAL)
  183625. /* More modes of operation. Note that after an init, mode is set to
  183626. * zero automatically when the structure is created.
  183627. */
  183628. #define PNG_HAVE_gAMA 0x20
  183629. #define PNG_HAVE_cHRM 0x40
  183630. #define PNG_HAVE_sRGB 0x80
  183631. #define PNG_HAVE_CHUNK_HEADER 0x100
  183632. #define PNG_WROTE_tIME 0x200
  183633. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183634. #define PNG_BACKGROUND_IS_GRAY 0x800
  183635. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183636. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183637. /* flags for the transformations the PNG library does on the image data */
  183638. #define PNG_BGR 0x0001
  183639. #define PNG_INTERLACE 0x0002
  183640. #define PNG_PACK 0x0004
  183641. #define PNG_SHIFT 0x0008
  183642. #define PNG_SWAP_BYTES 0x0010
  183643. #define PNG_INVERT_MONO 0x0020
  183644. #define PNG_DITHER 0x0040
  183645. #define PNG_BACKGROUND 0x0080
  183646. #define PNG_BACKGROUND_EXPAND 0x0100
  183647. /* 0x0200 unused */
  183648. #define PNG_16_TO_8 0x0400
  183649. #define PNG_RGBA 0x0800
  183650. #define PNG_EXPAND 0x1000
  183651. #define PNG_GAMMA 0x2000
  183652. #define PNG_GRAY_TO_RGB 0x4000
  183653. #define PNG_FILLER 0x8000L
  183654. #define PNG_PACKSWAP 0x10000L
  183655. #define PNG_SWAP_ALPHA 0x20000L
  183656. #define PNG_STRIP_ALPHA 0x40000L
  183657. #define PNG_INVERT_ALPHA 0x80000L
  183658. #define PNG_USER_TRANSFORM 0x100000L
  183659. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183660. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183661. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183662. /* 0x800000L Unused */
  183663. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183664. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183665. /* 0x4000000L unused */
  183666. /* 0x8000000L unused */
  183667. /* 0x10000000L unused */
  183668. /* 0x20000000L unused */
  183669. /* 0x40000000L unused */
  183670. /* flags for png_create_struct */
  183671. #define PNG_STRUCT_PNG 0x0001
  183672. #define PNG_STRUCT_INFO 0x0002
  183673. /* Scaling factor for filter heuristic weighting calculations */
  183674. #define PNG_WEIGHT_SHIFT 8
  183675. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  183676. #define PNG_COST_SHIFT 3
  183677. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  183678. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  183679. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  183680. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  183681. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  183682. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  183683. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  183684. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  183685. #define PNG_FLAG_ROW_INIT 0x0040
  183686. #define PNG_FLAG_FILLER_AFTER 0x0080
  183687. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  183688. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  183689. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  183690. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  183691. #define PNG_FLAG_FREE_PLTE 0x1000
  183692. #define PNG_FLAG_FREE_TRNS 0x2000
  183693. #define PNG_FLAG_FREE_HIST 0x4000
  183694. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  183695. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  183696. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  183697. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  183698. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  183699. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  183700. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  183701. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  183702. /* 0x800000L unused */
  183703. /* 0x1000000L unused */
  183704. /* 0x2000000L unused */
  183705. /* 0x4000000L unused */
  183706. /* 0x8000000L unused */
  183707. /* 0x10000000L unused */
  183708. /* 0x20000000L unused */
  183709. /* 0x40000000L unused */
  183710. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  183711. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  183712. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  183713. PNG_FLAG_CRC_CRITICAL_IGNORE)
  183714. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  183715. PNG_FLAG_CRC_CRITICAL_MASK)
  183716. /* save typing and make code easier to understand */
  183717. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  183718. abs((int)((c1).green) - (int)((c2).green)) + \
  183719. abs((int)((c1).blue) - (int)((c2).blue)))
  183720. /* Added to libpng-1.2.6 JB */
  183721. #define PNG_ROWBYTES(pixel_bits, width) \
  183722. ((pixel_bits) >= 8 ? \
  183723. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  183724. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  183725. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  183726. ideal-delta..ideal+delta. Each argument is evaluated twice.
  183727. "ideal" and "delta" should be constants, normally simple
  183728. integers, "value" a variable. Added to libpng-1.2.6 JB */
  183729. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  183730. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  183731. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  183732. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  183733. /* place to hold the signature string for a PNG file. */
  183734. #ifdef PNG_USE_GLOBAL_ARRAYS
  183735. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  183736. #else
  183737. #endif
  183738. #endif /* PNG_NO_EXTERN */
  183739. /* Constant strings for known chunk types. If you need to add a chunk,
  183740. * define the name here, and add an invocation of the macro in png.c and
  183741. * wherever it's needed.
  183742. */
  183743. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  183744. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  183745. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  183746. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  183747. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  183748. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  183749. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  183750. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  183751. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  183752. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  183753. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  183754. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  183755. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  183756. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  183757. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  183758. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  183759. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  183760. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  183761. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  183762. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  183763. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  183764. #ifdef PNG_USE_GLOBAL_ARRAYS
  183765. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  183766. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  183767. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  183768. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  183769. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  183770. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  183771. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  183772. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  183773. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  183774. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  183775. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  183776. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  183777. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  183778. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  183779. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  183780. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  183781. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  183782. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  183783. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  183784. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  183785. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  183786. #endif /* PNG_USE_GLOBAL_ARRAYS */
  183787. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183788. /* Initialize png_ptr struct for reading, and allocate any other memory.
  183789. * (old interface - DEPRECATED - use png_create_read_struct instead).
  183790. */
  183791. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  183792. #undef png_read_init
  183793. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  183794. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183795. #endif
  183796. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  183797. png_const_charp user_png_ver, png_size_t png_struct_size));
  183798. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183799. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  183800. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183801. png_info_size));
  183802. #endif
  183803. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183804. /* Initialize png_ptr struct for writing, and allocate any other memory.
  183805. * (old interface - DEPRECATED - use png_create_write_struct instead).
  183806. */
  183807. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  183808. #undef png_write_init
  183809. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  183810. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  183811. #endif
  183812. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  183813. png_const_charp user_png_ver, png_size_t png_struct_size));
  183814. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  183815. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  183816. png_info_size));
  183817. /* Allocate memory for an internal libpng struct */
  183818. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  183819. /* Free memory from internal libpng struct */
  183820. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  183821. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  183822. malloc_fn, png_voidp mem_ptr));
  183823. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  183824. png_free_ptr free_fn, png_voidp mem_ptr));
  183825. /* Free any memory that info_ptr points to and reset struct. */
  183826. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  183827. png_infop info_ptr));
  183828. #ifndef PNG_1_0_X
  183829. /* Function to allocate memory for zlib. */
  183830. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  183831. /* Function to free memory for zlib */
  183832. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  183833. #ifdef PNG_SIZE_T
  183834. /* Function to convert a sizeof an item to png_sizeof item */
  183835. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  183836. #endif
  183837. /* Next four functions are used internally as callbacks. PNGAPI is required
  183838. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  183839. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  183840. png_bytep data, png_size_t length));
  183841. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183842. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  183843. png_bytep buffer, png_size_t length));
  183844. #endif
  183845. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  183846. png_bytep data, png_size_t length));
  183847. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183848. #if !defined(PNG_NO_STDIO)
  183849. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  183850. #endif
  183851. #endif
  183852. #else /* PNG_1_0_X */
  183853. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183854. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  183855. png_bytep buffer, png_size_t length));
  183856. #endif
  183857. #endif /* PNG_1_0_X */
  183858. /* Reset the CRC variable */
  183859. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  183860. /* Write the "data" buffer to whatever output you are using. */
  183861. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  183862. png_size_t length));
  183863. /* Read data from whatever input you are using into the "data" buffer */
  183864. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  183865. png_size_t length));
  183866. /* Read bytes into buf, and update png_ptr->crc */
  183867. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  183868. png_size_t length));
  183869. /* Decompress data in a chunk that uses compression */
  183870. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  183871. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  183872. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  183873. int comp_type, png_charp chunkdata, png_size_t chunklength,
  183874. png_size_t prefix_length, png_size_t *data_length));
  183875. #endif
  183876. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  183877. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  183878. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  183879. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  183880. /* Calculate the CRC over a section of data. Note that we are only
  183881. * passing a maximum of 64K on systems that have this as a memory limit,
  183882. * since this is the maximum buffer size we can specify.
  183883. */
  183884. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  183885. png_size_t length));
  183886. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183887. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  183888. #endif
  183889. /* simple function to write the signature */
  183890. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  183891. /* write various chunks */
  183892. /* Write the IHDR chunk, and update the png_struct with the necessary
  183893. * information.
  183894. */
  183895. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  183896. png_uint_32 height,
  183897. int bit_depth, int color_type, int compression_method, int filter_method,
  183898. int interlace_method));
  183899. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  183900. png_uint_32 num_pal));
  183901. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  183902. png_size_t length));
  183903. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  183904. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  183905. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183906. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  183907. #endif
  183908. #ifdef PNG_FIXED_POINT_SUPPORTED
  183909. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  183910. file_gamma));
  183911. #endif
  183912. #endif
  183913. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  183914. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  183915. int color_type));
  183916. #endif
  183917. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  183918. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183919. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  183920. double white_x, double white_y,
  183921. double red_x, double red_y, double green_x, double green_y,
  183922. double blue_x, double blue_y));
  183923. #endif
  183924. #ifdef PNG_FIXED_POINT_SUPPORTED
  183925. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  183926. png_fixed_point int_white_x, png_fixed_point int_white_y,
  183927. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183928. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183929. png_fixed_point int_blue_y));
  183930. #endif
  183931. #endif
  183932. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  183933. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  183934. int intent));
  183935. #endif
  183936. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  183937. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  183938. png_charp name, int compression_type,
  183939. png_charp profile, int proflen));
  183940. /* Note to maintainer: profile should be png_bytep */
  183941. #endif
  183942. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  183943. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  183944. png_sPLT_tp palette));
  183945. #endif
  183946. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  183947. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  183948. png_color_16p values, int number, int color_type));
  183949. #endif
  183950. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  183951. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  183952. png_color_16p values, int color_type));
  183953. #endif
  183954. #if defined(PNG_WRITE_hIST_SUPPORTED)
  183955. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  183956. int num_hist));
  183957. #endif
  183958. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  183959. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  183960. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  183961. png_charp key, png_charpp new_key));
  183962. #endif
  183963. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  183964. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  183965. png_charp text, png_size_t text_len));
  183966. #endif
  183967. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  183968. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  183969. png_charp text, png_size_t text_len, int compression));
  183970. #endif
  183971. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  183972. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  183973. int compression, png_charp key, png_charp lang, png_charp lang_key,
  183974. png_charp text));
  183975. #endif
  183976. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  183977. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  183978. png_infop info_ptr, png_textp text_ptr, int num_text));
  183979. #endif
  183980. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  183981. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  183982. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  183983. #endif
  183984. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  183985. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  183986. png_int_32 X0, png_int_32 X1, int type, int nparams,
  183987. png_charp units, png_charpp params));
  183988. #endif
  183989. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  183990. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  183991. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  183992. int unit_type));
  183993. #endif
  183994. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183995. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  183996. png_timep mod_time));
  183997. #endif
  183998. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  183999. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184000. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184001. int unit, double width, double height));
  184002. #else
  184003. #ifdef PNG_FIXED_POINT_SUPPORTED
  184004. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184005. int unit, png_charp width, png_charp height));
  184006. #endif
  184007. #endif
  184008. #endif
  184009. /* Called when finished processing a row of data */
  184010. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184011. /* Internal use only. Called before first row of data */
  184012. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184013. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184014. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184015. #endif
  184016. /* combine a row of data, dealing with alpha, etc. if requested */
  184017. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184018. int mask));
  184019. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184020. /* expand an interlaced row */
  184021. /* OLD pre-1.0.9 interface:
  184022. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184023. png_bytep row, int pass, png_uint_32 transformations));
  184024. */
  184025. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184026. #endif
  184027. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184028. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184029. /* grab pixels out of a row for an interlaced pass */
  184030. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184031. png_bytep row, int pass));
  184032. #endif
  184033. /* unfilter a row */
  184034. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184035. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184036. /* Choose the best filter to use and filter the row data */
  184037. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184038. png_row_infop row_info));
  184039. /* Write out the filtered row. */
  184040. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184041. png_bytep filtered_row));
  184042. /* finish a row while reading, dealing with interlacing passes, etc. */
  184043. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184044. /* initialize the row buffers, etc. */
  184045. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184046. /* optional call to update the users info structure */
  184047. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184048. png_infop info_ptr));
  184049. /* these are the functions that do the transformations */
  184050. #if defined(PNG_READ_FILLER_SUPPORTED)
  184051. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184052. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184053. #endif
  184054. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184055. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184056. png_bytep row));
  184057. #endif
  184058. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184059. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184060. png_bytep row));
  184061. #endif
  184062. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184063. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184064. png_bytep row));
  184065. #endif
  184066. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184067. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184068. png_bytep row));
  184069. #endif
  184070. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184071. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184072. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184073. png_bytep row, png_uint_32 flags));
  184074. #endif
  184075. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184076. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184077. #endif
  184078. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184079. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184080. #endif
  184081. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184082. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184083. row_info, png_bytep row));
  184084. #endif
  184085. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184086. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184087. png_bytep row));
  184088. #endif
  184089. #if defined(PNG_READ_PACK_SUPPORTED)
  184090. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184091. #endif
  184092. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184093. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184094. png_color_8p sig_bits));
  184095. #endif
  184096. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184097. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184098. #endif
  184099. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184100. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184101. #endif
  184102. #if defined(PNG_READ_DITHER_SUPPORTED)
  184103. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184104. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184105. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184106. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184107. png_colorp palette, int num_palette));
  184108. # endif
  184109. #endif
  184110. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184111. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184112. #endif
  184113. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184114. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184115. png_bytep row, png_uint_32 bit_depth));
  184116. #endif
  184117. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184118. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184119. png_color_8p bit_depth));
  184120. #endif
  184121. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184122. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184123. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184124. png_color_16p trans_values, png_color_16p background,
  184125. png_color_16p background_1,
  184126. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184127. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184128. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184129. #else
  184130. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184131. png_color_16p trans_values, png_color_16p background));
  184132. #endif
  184133. #endif
  184134. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184135. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184136. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184137. int gamma_shift));
  184138. #endif
  184139. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184140. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184141. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184142. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184143. png_bytep row, png_color_16p trans_value));
  184144. #endif
  184145. /* The following decodes the appropriate chunks, and does error correction,
  184146. * then calls the appropriate callback for the chunk if it is valid.
  184147. */
  184148. /* decode the IHDR chunk */
  184149. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184150. png_uint_32 length));
  184151. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184152. png_uint_32 length));
  184153. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184154. png_uint_32 length));
  184155. #if defined(PNG_READ_bKGD_SUPPORTED)
  184156. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184157. png_uint_32 length));
  184158. #endif
  184159. #if defined(PNG_READ_cHRM_SUPPORTED)
  184160. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184161. png_uint_32 length));
  184162. #endif
  184163. #if defined(PNG_READ_gAMA_SUPPORTED)
  184164. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184165. png_uint_32 length));
  184166. #endif
  184167. #if defined(PNG_READ_hIST_SUPPORTED)
  184168. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184169. png_uint_32 length));
  184170. #endif
  184171. #if defined(PNG_READ_iCCP_SUPPORTED)
  184172. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184173. png_uint_32 length));
  184174. #endif /* PNG_READ_iCCP_SUPPORTED */
  184175. #if defined(PNG_READ_iTXt_SUPPORTED)
  184176. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184177. png_uint_32 length));
  184178. #endif
  184179. #if defined(PNG_READ_oFFs_SUPPORTED)
  184180. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184181. png_uint_32 length));
  184182. #endif
  184183. #if defined(PNG_READ_pCAL_SUPPORTED)
  184184. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184185. png_uint_32 length));
  184186. #endif
  184187. #if defined(PNG_READ_pHYs_SUPPORTED)
  184188. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184189. png_uint_32 length));
  184190. #endif
  184191. #if defined(PNG_READ_sBIT_SUPPORTED)
  184192. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184193. png_uint_32 length));
  184194. #endif
  184195. #if defined(PNG_READ_sCAL_SUPPORTED)
  184196. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184197. png_uint_32 length));
  184198. #endif
  184199. #if defined(PNG_READ_sPLT_SUPPORTED)
  184200. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184201. png_uint_32 length));
  184202. #endif /* PNG_READ_sPLT_SUPPORTED */
  184203. #if defined(PNG_READ_sRGB_SUPPORTED)
  184204. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184205. png_uint_32 length));
  184206. #endif
  184207. #if defined(PNG_READ_tEXt_SUPPORTED)
  184208. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184209. png_uint_32 length));
  184210. #endif
  184211. #if defined(PNG_READ_tIME_SUPPORTED)
  184212. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184213. png_uint_32 length));
  184214. #endif
  184215. #if defined(PNG_READ_tRNS_SUPPORTED)
  184216. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184217. png_uint_32 length));
  184218. #endif
  184219. #if defined(PNG_READ_zTXt_SUPPORTED)
  184220. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184221. png_uint_32 length));
  184222. #endif
  184223. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184224. png_infop info_ptr, png_uint_32 length));
  184225. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184226. png_bytep chunk_name));
  184227. /* handle the transformations for reading and writing */
  184228. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184229. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184230. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184231. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184232. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184233. png_infop info_ptr));
  184234. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184235. png_infop info_ptr));
  184236. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184237. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184238. png_uint_32 length));
  184239. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184240. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184241. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184242. png_bytep buffer, png_size_t buffer_length));
  184243. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184244. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184245. png_bytep buffer, png_size_t buffer_length));
  184246. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184247. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184248. png_infop info_ptr, png_uint_32 length));
  184249. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184250. png_infop info_ptr));
  184251. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184252. png_infop info_ptr));
  184253. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184254. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184255. png_infop info_ptr));
  184256. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184257. png_infop info_ptr));
  184258. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184259. #if defined(PNG_READ_tEXt_SUPPORTED)
  184260. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184261. png_infop info_ptr, png_uint_32 length));
  184262. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184263. png_infop info_ptr));
  184264. #endif
  184265. #if defined(PNG_READ_zTXt_SUPPORTED)
  184266. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184267. png_infop info_ptr, png_uint_32 length));
  184268. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184269. png_infop info_ptr));
  184270. #endif
  184271. #if defined(PNG_READ_iTXt_SUPPORTED)
  184272. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184273. png_infop info_ptr, png_uint_32 length));
  184274. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184275. png_infop info_ptr));
  184276. #endif
  184277. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184278. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184279. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184280. png_bytep row));
  184281. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184282. png_bytep row));
  184283. #endif
  184284. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184285. #if defined(PNG_MMX_CODE_SUPPORTED)
  184286. /* png.c */ /* PRIVATE */
  184287. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184288. #endif
  184289. #endif
  184290. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184291. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184292. png_infop info_ptr));
  184293. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184294. png_infop info_ptr));
  184295. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184296. png_infop info_ptr));
  184297. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184298. png_infop info_ptr));
  184299. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184300. png_infop info_ptr));
  184301. #if defined(PNG_pHYs_SUPPORTED)
  184302. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184303. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184304. #endif /* PNG_pHYs_SUPPORTED */
  184305. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184306. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184307. #endif /* PNG_INTERNAL */
  184308. #ifdef __cplusplus
  184309. //}
  184310. #endif
  184311. #endif /* PNG_VERSION_INFO_ONLY */
  184312. /* do not put anything past this line */
  184313. #endif /* PNG_H */
  184314. /*** End of inlined file: png.h ***/
  184315. #define PNG_NO_EXTERN
  184316. /*** Start of inlined file: png.c ***/
  184317. /* png.c - location for general purpose libpng functions
  184318. *
  184319. * Last changed in libpng 1.2.21 [October 4, 2007]
  184320. * For conditions of distribution and use, see copyright notice in png.h
  184321. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184322. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184323. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184324. */
  184325. #define PNG_INTERNAL
  184326. #define PNG_NO_EXTERN
  184327. /* Generate a compiler error if there is an old png.h in the search path. */
  184328. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184329. /* Version information for C files. This had better match the version
  184330. * string defined in png.h. */
  184331. #ifdef PNG_USE_GLOBAL_ARRAYS
  184332. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184333. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184334. #ifdef PNG_READ_SUPPORTED
  184335. /* png_sig was changed to a function in version 1.0.5c */
  184336. /* Place to hold the signature string for a PNG file. */
  184337. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184338. #endif /* PNG_READ_SUPPORTED */
  184339. /* Invoke global declarations for constant strings for known chunk types */
  184340. PNG_IHDR;
  184341. PNG_IDAT;
  184342. PNG_IEND;
  184343. PNG_PLTE;
  184344. PNG_bKGD;
  184345. PNG_cHRM;
  184346. PNG_gAMA;
  184347. PNG_hIST;
  184348. PNG_iCCP;
  184349. PNG_iTXt;
  184350. PNG_oFFs;
  184351. PNG_pCAL;
  184352. PNG_sCAL;
  184353. PNG_pHYs;
  184354. PNG_sBIT;
  184355. PNG_sPLT;
  184356. PNG_sRGB;
  184357. PNG_tEXt;
  184358. PNG_tIME;
  184359. PNG_tRNS;
  184360. PNG_zTXt;
  184361. #ifdef PNG_READ_SUPPORTED
  184362. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184363. /* start of interlace block */
  184364. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184365. /* offset to next interlace block */
  184366. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184367. /* start of interlace block in the y direction */
  184368. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184369. /* offset to next interlace block in the y direction */
  184370. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184371. /* Height of interlace block. This is not currently used - if you need
  184372. * it, uncomment it here and in png.h
  184373. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184374. */
  184375. /* Mask to determine which pixels are valid in a pass */
  184376. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184377. /* Mask to determine which pixels to overwrite while displaying */
  184378. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184379. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184380. #endif /* PNG_READ_SUPPORTED */
  184381. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184382. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184383. * of the PNG file signature. If the PNG data is embedded into another
  184384. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184385. * or write any of the magic bytes before it starts on the IHDR.
  184386. */
  184387. #ifdef PNG_READ_SUPPORTED
  184388. void PNGAPI
  184389. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184390. {
  184391. if(png_ptr == NULL) return;
  184392. png_debug(1, "in png_set_sig_bytes\n");
  184393. if (num_bytes > 8)
  184394. png_error(png_ptr, "Too many bytes for PNG signature.");
  184395. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184396. }
  184397. /* Checks whether the supplied bytes match the PNG signature. We allow
  184398. * checking less than the full 8-byte signature so that those apps that
  184399. * already read the first few bytes of a file to determine the file type
  184400. * can simply check the remaining bytes for extra assurance. Returns
  184401. * an integer less than, equal to, or greater than zero if sig is found,
  184402. * respectively, to be less than, to match, or be greater than the correct
  184403. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184404. */
  184405. int PNGAPI
  184406. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184407. {
  184408. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184409. if (num_to_check > 8)
  184410. num_to_check = 8;
  184411. else if (num_to_check < 1)
  184412. return (-1);
  184413. if (start > 7)
  184414. return (-1);
  184415. if (start + num_to_check > 8)
  184416. num_to_check = 8 - start;
  184417. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184418. }
  184419. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184420. /* (Obsolete) function to check signature bytes. It does not allow one
  184421. * to check a partial signature. This function might be removed in the
  184422. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184423. */
  184424. int PNGAPI
  184425. png_check_sig(png_bytep sig, int num)
  184426. {
  184427. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184428. }
  184429. #endif
  184430. #endif /* PNG_READ_SUPPORTED */
  184431. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184432. /* Function to allocate memory for zlib and clear it to 0. */
  184433. #ifdef PNG_1_0_X
  184434. voidpf PNGAPI
  184435. #else
  184436. voidpf /* private */
  184437. #endif
  184438. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184439. {
  184440. png_voidp ptr;
  184441. png_structp p=(png_structp)png_ptr;
  184442. png_uint_32 save_flags=p->flags;
  184443. png_uint_32 num_bytes;
  184444. if(png_ptr == NULL) return (NULL);
  184445. if (items > PNG_UINT_32_MAX/size)
  184446. {
  184447. png_warning (p, "Potential overflow in png_zalloc()");
  184448. return (NULL);
  184449. }
  184450. num_bytes = (png_uint_32)items * size;
  184451. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184452. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184453. p->flags=save_flags;
  184454. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184455. if (ptr == NULL)
  184456. return ((voidpf)ptr);
  184457. if (num_bytes > (png_uint_32)0x8000L)
  184458. {
  184459. png_memset(ptr, 0, (png_size_t)0x8000L);
  184460. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184461. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184462. }
  184463. else
  184464. {
  184465. png_memset(ptr, 0, (png_size_t)num_bytes);
  184466. }
  184467. #endif
  184468. return ((voidpf)ptr);
  184469. }
  184470. /* function to free memory for zlib */
  184471. #ifdef PNG_1_0_X
  184472. void PNGAPI
  184473. #else
  184474. void /* private */
  184475. #endif
  184476. png_zfree(voidpf png_ptr, voidpf ptr)
  184477. {
  184478. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184479. }
  184480. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184481. * in case CRC is > 32 bits to leave the top bits 0.
  184482. */
  184483. void /* PRIVATE */
  184484. png_reset_crc(png_structp png_ptr)
  184485. {
  184486. png_ptr->crc = crc32(0, Z_NULL, 0);
  184487. }
  184488. /* Calculate the CRC over a section of data. We can only pass as
  184489. * much data to this routine as the largest single buffer size. We
  184490. * also check that this data will actually be used before going to the
  184491. * trouble of calculating it.
  184492. */
  184493. void /* PRIVATE */
  184494. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184495. {
  184496. int need_crc = 1;
  184497. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184498. {
  184499. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184500. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184501. need_crc = 0;
  184502. }
  184503. else /* critical */
  184504. {
  184505. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184506. need_crc = 0;
  184507. }
  184508. if (need_crc)
  184509. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184510. }
  184511. /* Allocate the memory for an info_struct for the application. We don't
  184512. * really need the png_ptr, but it could potentially be useful in the
  184513. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184514. * and png_info_init() so that applications that want to use a shared
  184515. * libpng don't have to be recompiled if png_info changes size.
  184516. */
  184517. png_infop PNGAPI
  184518. png_create_info_struct(png_structp png_ptr)
  184519. {
  184520. png_infop info_ptr;
  184521. png_debug(1, "in png_create_info_struct\n");
  184522. if(png_ptr == NULL) return (NULL);
  184523. #ifdef PNG_USER_MEM_SUPPORTED
  184524. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184525. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184526. #else
  184527. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184528. #endif
  184529. if (info_ptr != NULL)
  184530. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184531. return (info_ptr);
  184532. }
  184533. /* This function frees the memory associated with a single info struct.
  184534. * Normally, one would use either png_destroy_read_struct() or
  184535. * png_destroy_write_struct() to free an info struct, but this may be
  184536. * useful for some applications.
  184537. */
  184538. void PNGAPI
  184539. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184540. {
  184541. png_infop info_ptr = NULL;
  184542. if(png_ptr == NULL) return;
  184543. png_debug(1, "in png_destroy_info_struct\n");
  184544. if (info_ptr_ptr != NULL)
  184545. info_ptr = *info_ptr_ptr;
  184546. if (info_ptr != NULL)
  184547. {
  184548. png_info_destroy(png_ptr, info_ptr);
  184549. #ifdef PNG_USER_MEM_SUPPORTED
  184550. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184551. png_ptr->mem_ptr);
  184552. #else
  184553. png_destroy_struct((png_voidp)info_ptr);
  184554. #endif
  184555. *info_ptr_ptr = NULL;
  184556. }
  184557. }
  184558. /* Initialize the info structure. This is now an internal function (0.89)
  184559. * and applications using it are urged to use png_create_info_struct()
  184560. * instead.
  184561. */
  184562. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184563. #undef png_info_init
  184564. void PNGAPI
  184565. png_info_init(png_infop info_ptr)
  184566. {
  184567. /* We only come here via pre-1.0.12-compiled applications */
  184568. png_info_init_3(&info_ptr, 0);
  184569. }
  184570. #endif
  184571. void PNGAPI
  184572. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184573. {
  184574. png_infop info_ptr = *ptr_ptr;
  184575. if(info_ptr == NULL) return;
  184576. png_debug(1, "in png_info_init_3\n");
  184577. if(png_sizeof(png_info) > png_info_struct_size)
  184578. {
  184579. png_destroy_struct(info_ptr);
  184580. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184581. *ptr_ptr = info_ptr;
  184582. }
  184583. /* set everything to 0 */
  184584. png_memset(info_ptr, 0, png_sizeof (png_info));
  184585. }
  184586. #ifdef PNG_FREE_ME_SUPPORTED
  184587. void PNGAPI
  184588. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184589. int freer, png_uint_32 mask)
  184590. {
  184591. png_debug(1, "in png_data_freer\n");
  184592. if (png_ptr == NULL || info_ptr == NULL)
  184593. return;
  184594. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184595. info_ptr->free_me |= mask;
  184596. else if(freer == PNG_USER_WILL_FREE_DATA)
  184597. info_ptr->free_me &= ~mask;
  184598. else
  184599. png_warning(png_ptr,
  184600. "Unknown freer parameter in png_data_freer.");
  184601. }
  184602. #endif
  184603. void PNGAPI
  184604. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184605. int num)
  184606. {
  184607. png_debug(1, "in png_free_data\n");
  184608. if (png_ptr == NULL || info_ptr == NULL)
  184609. return;
  184610. #if defined(PNG_TEXT_SUPPORTED)
  184611. /* free text item num or (if num == -1) all text items */
  184612. #ifdef PNG_FREE_ME_SUPPORTED
  184613. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184614. #else
  184615. if (mask & PNG_FREE_TEXT)
  184616. #endif
  184617. {
  184618. if (num != -1)
  184619. {
  184620. if (info_ptr->text && info_ptr->text[num].key)
  184621. {
  184622. png_free(png_ptr, info_ptr->text[num].key);
  184623. info_ptr->text[num].key = NULL;
  184624. }
  184625. }
  184626. else
  184627. {
  184628. int i;
  184629. for (i = 0; i < info_ptr->num_text; i++)
  184630. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184631. png_free(png_ptr, info_ptr->text);
  184632. info_ptr->text = NULL;
  184633. info_ptr->num_text=0;
  184634. }
  184635. }
  184636. #endif
  184637. #if defined(PNG_tRNS_SUPPORTED)
  184638. /* free any tRNS entry */
  184639. #ifdef PNG_FREE_ME_SUPPORTED
  184640. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184641. #else
  184642. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184643. #endif
  184644. {
  184645. png_free(png_ptr, info_ptr->trans);
  184646. info_ptr->valid &= ~PNG_INFO_tRNS;
  184647. #ifndef PNG_FREE_ME_SUPPORTED
  184648. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184649. #endif
  184650. info_ptr->trans = NULL;
  184651. }
  184652. #endif
  184653. #if defined(PNG_sCAL_SUPPORTED)
  184654. /* free any sCAL entry */
  184655. #ifdef PNG_FREE_ME_SUPPORTED
  184656. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184657. #else
  184658. if (mask & PNG_FREE_SCAL)
  184659. #endif
  184660. {
  184661. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184662. png_free(png_ptr, info_ptr->scal_s_width);
  184663. png_free(png_ptr, info_ptr->scal_s_height);
  184664. info_ptr->scal_s_width = NULL;
  184665. info_ptr->scal_s_height = NULL;
  184666. #endif
  184667. info_ptr->valid &= ~PNG_INFO_sCAL;
  184668. }
  184669. #endif
  184670. #if defined(PNG_pCAL_SUPPORTED)
  184671. /* free any pCAL entry */
  184672. #ifdef PNG_FREE_ME_SUPPORTED
  184673. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  184674. #else
  184675. if (mask & PNG_FREE_PCAL)
  184676. #endif
  184677. {
  184678. png_free(png_ptr, info_ptr->pcal_purpose);
  184679. png_free(png_ptr, info_ptr->pcal_units);
  184680. info_ptr->pcal_purpose = NULL;
  184681. info_ptr->pcal_units = NULL;
  184682. if (info_ptr->pcal_params != NULL)
  184683. {
  184684. int i;
  184685. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  184686. {
  184687. png_free(png_ptr, info_ptr->pcal_params[i]);
  184688. info_ptr->pcal_params[i]=NULL;
  184689. }
  184690. png_free(png_ptr, info_ptr->pcal_params);
  184691. info_ptr->pcal_params = NULL;
  184692. }
  184693. info_ptr->valid &= ~PNG_INFO_pCAL;
  184694. }
  184695. #endif
  184696. #if defined(PNG_iCCP_SUPPORTED)
  184697. /* free any iCCP entry */
  184698. #ifdef PNG_FREE_ME_SUPPORTED
  184699. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  184700. #else
  184701. if (mask & PNG_FREE_ICCP)
  184702. #endif
  184703. {
  184704. png_free(png_ptr, info_ptr->iccp_name);
  184705. png_free(png_ptr, info_ptr->iccp_profile);
  184706. info_ptr->iccp_name = NULL;
  184707. info_ptr->iccp_profile = NULL;
  184708. info_ptr->valid &= ~PNG_INFO_iCCP;
  184709. }
  184710. #endif
  184711. #if defined(PNG_sPLT_SUPPORTED)
  184712. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  184713. #ifdef PNG_FREE_ME_SUPPORTED
  184714. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  184715. #else
  184716. if (mask & PNG_FREE_SPLT)
  184717. #endif
  184718. {
  184719. if (num != -1)
  184720. {
  184721. if(info_ptr->splt_palettes)
  184722. {
  184723. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  184724. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  184725. info_ptr->splt_palettes[num].name = NULL;
  184726. info_ptr->splt_palettes[num].entries = NULL;
  184727. }
  184728. }
  184729. else
  184730. {
  184731. if(info_ptr->splt_palettes_num)
  184732. {
  184733. int i;
  184734. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  184735. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  184736. png_free(png_ptr, info_ptr->splt_palettes);
  184737. info_ptr->splt_palettes = NULL;
  184738. info_ptr->splt_palettes_num = 0;
  184739. }
  184740. info_ptr->valid &= ~PNG_INFO_sPLT;
  184741. }
  184742. }
  184743. #endif
  184744. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184745. if(png_ptr->unknown_chunk.data)
  184746. {
  184747. png_free(png_ptr, png_ptr->unknown_chunk.data);
  184748. png_ptr->unknown_chunk.data = NULL;
  184749. }
  184750. #ifdef PNG_FREE_ME_SUPPORTED
  184751. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  184752. #else
  184753. if (mask & PNG_FREE_UNKN)
  184754. #endif
  184755. {
  184756. if (num != -1)
  184757. {
  184758. if(info_ptr->unknown_chunks)
  184759. {
  184760. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  184761. info_ptr->unknown_chunks[num].data = NULL;
  184762. }
  184763. }
  184764. else
  184765. {
  184766. int i;
  184767. if(info_ptr->unknown_chunks_num)
  184768. {
  184769. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  184770. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  184771. png_free(png_ptr, info_ptr->unknown_chunks);
  184772. info_ptr->unknown_chunks = NULL;
  184773. info_ptr->unknown_chunks_num = 0;
  184774. }
  184775. }
  184776. }
  184777. #endif
  184778. #if defined(PNG_hIST_SUPPORTED)
  184779. /* free any hIST entry */
  184780. #ifdef PNG_FREE_ME_SUPPORTED
  184781. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  184782. #else
  184783. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  184784. #endif
  184785. {
  184786. png_free(png_ptr, info_ptr->hist);
  184787. info_ptr->hist = NULL;
  184788. info_ptr->valid &= ~PNG_INFO_hIST;
  184789. #ifndef PNG_FREE_ME_SUPPORTED
  184790. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  184791. #endif
  184792. }
  184793. #endif
  184794. /* free any PLTE entry that was internally allocated */
  184795. #ifdef PNG_FREE_ME_SUPPORTED
  184796. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  184797. #else
  184798. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  184799. #endif
  184800. {
  184801. png_zfree(png_ptr, info_ptr->palette);
  184802. info_ptr->palette = NULL;
  184803. info_ptr->valid &= ~PNG_INFO_PLTE;
  184804. #ifndef PNG_FREE_ME_SUPPORTED
  184805. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  184806. #endif
  184807. info_ptr->num_palette = 0;
  184808. }
  184809. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184810. /* free any image bits attached to the info structure */
  184811. #ifdef PNG_FREE_ME_SUPPORTED
  184812. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  184813. #else
  184814. if (mask & PNG_FREE_ROWS)
  184815. #endif
  184816. {
  184817. if(info_ptr->row_pointers)
  184818. {
  184819. int row;
  184820. for (row = 0; row < (int)info_ptr->height; row++)
  184821. {
  184822. png_free(png_ptr, info_ptr->row_pointers[row]);
  184823. info_ptr->row_pointers[row]=NULL;
  184824. }
  184825. png_free(png_ptr, info_ptr->row_pointers);
  184826. info_ptr->row_pointers=NULL;
  184827. }
  184828. info_ptr->valid &= ~PNG_INFO_IDAT;
  184829. }
  184830. #endif
  184831. #ifdef PNG_FREE_ME_SUPPORTED
  184832. if(num == -1)
  184833. info_ptr->free_me &= ~mask;
  184834. else
  184835. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  184836. #endif
  184837. }
  184838. /* This is an internal routine to free any memory that the info struct is
  184839. * pointing to before re-using it or freeing the struct itself. Recall
  184840. * that png_free() checks for NULL pointers for us.
  184841. */
  184842. void /* PRIVATE */
  184843. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  184844. {
  184845. png_debug(1, "in png_info_destroy\n");
  184846. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  184847. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184848. if (png_ptr->num_chunk_list)
  184849. {
  184850. png_free(png_ptr, png_ptr->chunk_list);
  184851. png_ptr->chunk_list=NULL;
  184852. png_ptr->num_chunk_list=0;
  184853. }
  184854. #endif
  184855. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184856. }
  184857. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184858. /* This function returns a pointer to the io_ptr associated with the user
  184859. * functions. The application should free any memory associated with this
  184860. * pointer before png_write_destroy() or png_read_destroy() are called.
  184861. */
  184862. png_voidp PNGAPI
  184863. png_get_io_ptr(png_structp png_ptr)
  184864. {
  184865. if(png_ptr == NULL) return (NULL);
  184866. return (png_ptr->io_ptr);
  184867. }
  184868. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184869. #if !defined(PNG_NO_STDIO)
  184870. /* Initialize the default input/output functions for the PNG file. If you
  184871. * use your own read or write routines, you can call either png_set_read_fn()
  184872. * or png_set_write_fn() instead of png_init_io(). If you have defined
  184873. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  184874. * necessarily available.
  184875. */
  184876. void PNGAPI
  184877. png_init_io(png_structp png_ptr, png_FILE_p fp)
  184878. {
  184879. png_debug(1, "in png_init_io\n");
  184880. if(png_ptr == NULL) return;
  184881. png_ptr->io_ptr = (png_voidp)fp;
  184882. }
  184883. #endif
  184884. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  184885. /* Convert the supplied time into an RFC 1123 string suitable for use in
  184886. * a "Creation Time" or other text-based time string.
  184887. */
  184888. png_charp PNGAPI
  184889. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  184890. {
  184891. static PNG_CONST char short_months[12][4] =
  184892. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  184893. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  184894. if(png_ptr == NULL) return (NULL);
  184895. if (png_ptr->time_buffer == NULL)
  184896. {
  184897. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  184898. png_sizeof(char)));
  184899. }
  184900. #if defined(_WIN32_WCE)
  184901. {
  184902. wchar_t time_buf[29];
  184903. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  184904. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184905. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184906. ptime->second % 61);
  184907. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  184908. NULL, NULL);
  184909. }
  184910. #else
  184911. #ifdef USE_FAR_KEYWORD
  184912. {
  184913. char near_time_buf[29];
  184914. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  184915. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184916. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184917. ptime->second % 61);
  184918. png_memcpy(png_ptr->time_buffer, near_time_buf,
  184919. 29*png_sizeof(char));
  184920. }
  184921. #else
  184922. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  184923. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  184924. ptime->year, ptime->hour % 24, ptime->minute % 60,
  184925. ptime->second % 61);
  184926. #endif
  184927. #endif /* _WIN32_WCE */
  184928. return ((png_charp)png_ptr->time_buffer);
  184929. }
  184930. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  184931. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184932. png_charp PNGAPI
  184933. png_get_copyright(png_structp png_ptr)
  184934. {
  184935. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184936. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  184937. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  184938. Copyright (c) 1996-1997 Andreas Dilger\n\
  184939. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  184940. }
  184941. /* The following return the library version as a short string in the
  184942. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  184943. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  184944. * is defined in png.h.
  184945. * Note: now there is no difference between png_get_libpng_ver() and
  184946. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  184947. * it is guaranteed that png.c uses the correct version of png.h.
  184948. */
  184949. png_charp PNGAPI
  184950. png_get_libpng_ver(png_structp png_ptr)
  184951. {
  184952. /* Version of *.c files used when building libpng */
  184953. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184954. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184955. }
  184956. png_charp PNGAPI
  184957. png_get_header_ver(png_structp png_ptr)
  184958. {
  184959. /* Version of *.h files used when building libpng */
  184960. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184961. return ((png_charp) PNG_LIBPNG_VER_STRING);
  184962. }
  184963. png_charp PNGAPI
  184964. png_get_header_version(png_structp png_ptr)
  184965. {
  184966. /* Returns longer string containing both version and date */
  184967. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  184968. return ((png_charp) PNG_HEADER_VERSION_STRING
  184969. #ifndef PNG_READ_SUPPORTED
  184970. " (NO READ SUPPORT)"
  184971. #endif
  184972. "\n");
  184973. }
  184974. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184975. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184976. int PNGAPI
  184977. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  184978. {
  184979. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  184980. int i;
  184981. png_bytep p;
  184982. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  184983. return 0;
  184984. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  184985. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  184986. if (!png_memcmp(chunk_name, p, 4))
  184987. return ((int)*(p+4));
  184988. return 0;
  184989. }
  184990. #endif
  184991. /* This function, added to libpng-1.0.6g, is untested. */
  184992. int PNGAPI
  184993. png_reset_zstream(png_structp png_ptr)
  184994. {
  184995. if (png_ptr == NULL) return Z_STREAM_ERROR;
  184996. return (inflateReset(&png_ptr->zstream));
  184997. }
  184998. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  184999. /* This function was added to libpng-1.0.7 */
  185000. png_uint_32 PNGAPI
  185001. png_access_version_number(void)
  185002. {
  185003. /* Version of *.c files used when building libpng */
  185004. return((png_uint_32) PNG_LIBPNG_VER);
  185005. }
  185006. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185007. #if !defined(PNG_1_0_X)
  185008. /* this function was added to libpng 1.2.0 */
  185009. int PNGAPI
  185010. png_mmx_support(void)
  185011. {
  185012. /* obsolete, to be removed from libpng-1.4.0 */
  185013. return -1;
  185014. }
  185015. #endif /* PNG_1_0_X */
  185016. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185017. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185018. #ifdef PNG_SIZE_T
  185019. /* Added at libpng version 1.2.6 */
  185020. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185021. png_size_t PNGAPI
  185022. png_convert_size(size_t size)
  185023. {
  185024. if (size > (png_size_t)-1)
  185025. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185026. return ((png_size_t)size);
  185027. }
  185028. #endif /* PNG_SIZE_T */
  185029. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185030. /*** End of inlined file: png.c ***/
  185031. /*** Start of inlined file: pngerror.c ***/
  185032. /* pngerror.c - stub functions for i/o and memory allocation
  185033. *
  185034. * Last changed in libpng 1.2.20 October 4, 2007
  185035. * For conditions of distribution and use, see copyright notice in png.h
  185036. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185037. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185038. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185039. *
  185040. * This file provides a location for all error handling. Users who
  185041. * need special error handling are expected to write replacement functions
  185042. * and use png_set_error_fn() to use those functions. See the instructions
  185043. * at each function.
  185044. */
  185045. #define PNG_INTERNAL
  185046. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185047. static void /* PRIVATE */
  185048. png_default_error PNGARG((png_structp png_ptr,
  185049. png_const_charp error_message));
  185050. #ifndef PNG_NO_WARNINGS
  185051. static void /* PRIVATE */
  185052. png_default_warning PNGARG((png_structp png_ptr,
  185053. png_const_charp warning_message));
  185054. #endif /* PNG_NO_WARNINGS */
  185055. /* This function is called whenever there is a fatal error. This function
  185056. * should not be changed. If there is a need to handle errors differently,
  185057. * you should supply a replacement error function and use png_set_error_fn()
  185058. * to replace the error function at run-time.
  185059. */
  185060. #ifndef PNG_NO_ERROR_TEXT
  185061. void PNGAPI
  185062. png_error(png_structp png_ptr, png_const_charp error_message)
  185063. {
  185064. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185065. char msg[16];
  185066. if (png_ptr != NULL)
  185067. {
  185068. if (png_ptr->flags&
  185069. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185070. {
  185071. if (*error_message == '#')
  185072. {
  185073. int offset;
  185074. for (offset=1; offset<15; offset++)
  185075. if (*(error_message+offset) == ' ')
  185076. break;
  185077. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185078. {
  185079. int i;
  185080. for (i=0; i<offset-1; i++)
  185081. msg[i]=error_message[i+1];
  185082. msg[i]='\0';
  185083. error_message=msg;
  185084. }
  185085. else
  185086. error_message+=offset;
  185087. }
  185088. else
  185089. {
  185090. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185091. {
  185092. msg[0]='0';
  185093. msg[1]='\0';
  185094. error_message=msg;
  185095. }
  185096. }
  185097. }
  185098. }
  185099. #endif
  185100. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185101. (*(png_ptr->error_fn))(png_ptr, error_message);
  185102. /* If the custom handler doesn't exist, or if it returns,
  185103. use the default handler, which will not return. */
  185104. png_default_error(png_ptr, error_message);
  185105. }
  185106. #else
  185107. void PNGAPI
  185108. png_err(png_structp png_ptr)
  185109. {
  185110. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185111. (*(png_ptr->error_fn))(png_ptr, '\0');
  185112. /* If the custom handler doesn't exist, or if it returns,
  185113. use the default handler, which will not return. */
  185114. png_default_error(png_ptr, '\0');
  185115. }
  185116. #endif /* PNG_NO_ERROR_TEXT */
  185117. #ifndef PNG_NO_WARNINGS
  185118. /* This function is called whenever there is a non-fatal error. This function
  185119. * should not be changed. If there is a need to handle warnings differently,
  185120. * you should supply a replacement warning function and use
  185121. * png_set_error_fn() to replace the warning function at run-time.
  185122. */
  185123. void PNGAPI
  185124. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185125. {
  185126. int offset = 0;
  185127. if (png_ptr != NULL)
  185128. {
  185129. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185130. if (png_ptr->flags&
  185131. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185132. #endif
  185133. {
  185134. if (*warning_message == '#')
  185135. {
  185136. for (offset=1; offset<15; offset++)
  185137. if (*(warning_message+offset) == ' ')
  185138. break;
  185139. }
  185140. }
  185141. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185142. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185143. }
  185144. else
  185145. png_default_warning(png_ptr, warning_message+offset);
  185146. }
  185147. #endif /* PNG_NO_WARNINGS */
  185148. /* These utilities are used internally to build an error message that relates
  185149. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185150. * this is used to prefix the message. The message is limited in length
  185151. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185152. * if the character is invalid.
  185153. */
  185154. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185155. /*static PNG_CONST char png_digit[16] = {
  185156. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185157. 'A', 'B', 'C', 'D', 'E', 'F'
  185158. };*/
  185159. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185160. static void /* PRIVATE */
  185161. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185162. error_message)
  185163. {
  185164. int iout = 0, iin = 0;
  185165. while (iin < 4)
  185166. {
  185167. int c = png_ptr->chunk_name[iin++];
  185168. if (isnonalpha(c))
  185169. {
  185170. buffer[iout++] = '[';
  185171. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185172. buffer[iout++] = png_digit[c & 0x0f];
  185173. buffer[iout++] = ']';
  185174. }
  185175. else
  185176. {
  185177. buffer[iout++] = (png_byte)c;
  185178. }
  185179. }
  185180. if (error_message == NULL)
  185181. buffer[iout] = 0;
  185182. else
  185183. {
  185184. buffer[iout++] = ':';
  185185. buffer[iout++] = ' ';
  185186. png_strncpy(buffer+iout, error_message, 63);
  185187. buffer[iout+63] = 0;
  185188. }
  185189. }
  185190. #ifdef PNG_READ_SUPPORTED
  185191. void PNGAPI
  185192. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185193. {
  185194. char msg[18+64];
  185195. if (png_ptr == NULL)
  185196. png_error(png_ptr, error_message);
  185197. else
  185198. {
  185199. png_format_buffer(png_ptr, msg, error_message);
  185200. png_error(png_ptr, msg);
  185201. }
  185202. }
  185203. #endif /* PNG_READ_SUPPORTED */
  185204. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185205. #ifndef PNG_NO_WARNINGS
  185206. void PNGAPI
  185207. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185208. {
  185209. char msg[18+64];
  185210. if (png_ptr == NULL)
  185211. png_warning(png_ptr, warning_message);
  185212. else
  185213. {
  185214. png_format_buffer(png_ptr, msg, warning_message);
  185215. png_warning(png_ptr, msg);
  185216. }
  185217. }
  185218. #endif /* PNG_NO_WARNINGS */
  185219. /* This is the default error handling function. Note that replacements for
  185220. * this function MUST NOT RETURN, or the program will likely crash. This
  185221. * function is used by default, or if the program supplies NULL for the
  185222. * error function pointer in png_set_error_fn().
  185223. */
  185224. static void /* PRIVATE */
  185225. png_default_error(png_structp, png_const_charp error_message)
  185226. {
  185227. #ifndef PNG_NO_CONSOLE_IO
  185228. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185229. if (*error_message == '#')
  185230. {
  185231. int offset;
  185232. char error_number[16];
  185233. for (offset=0; offset<15; offset++)
  185234. {
  185235. error_number[offset] = *(error_message+offset+1);
  185236. if (*(error_message+offset) == ' ')
  185237. break;
  185238. }
  185239. if((offset > 1) && (offset < 15))
  185240. {
  185241. error_number[offset-1]='\0';
  185242. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185243. error_message+offset);
  185244. }
  185245. else
  185246. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185247. }
  185248. else
  185249. #endif
  185250. fprintf(stderr, "libpng error: %s\n", error_message);
  185251. #endif
  185252. #ifdef PNG_SETJMP_SUPPORTED
  185253. if (png_ptr)
  185254. {
  185255. # ifdef USE_FAR_KEYWORD
  185256. {
  185257. jmp_buf jmpbuf;
  185258. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185259. longjmp(jmpbuf, 1);
  185260. }
  185261. # else
  185262. longjmp(png_ptr->jmpbuf, 1);
  185263. # endif
  185264. }
  185265. #else
  185266. PNG_ABORT();
  185267. #endif
  185268. #ifdef PNG_NO_CONSOLE_IO
  185269. error_message = error_message; /* make compiler happy */
  185270. #endif
  185271. }
  185272. #ifndef PNG_NO_WARNINGS
  185273. /* This function is called when there is a warning, but the library thinks
  185274. * it can continue anyway. Replacement functions don't have to do anything
  185275. * here if you don't want them to. In the default configuration, png_ptr is
  185276. * not used, but it is passed in case it may be useful.
  185277. */
  185278. static void /* PRIVATE */
  185279. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185280. {
  185281. #ifndef PNG_NO_CONSOLE_IO
  185282. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185283. if (*warning_message == '#')
  185284. {
  185285. int offset;
  185286. char warning_number[16];
  185287. for (offset=0; offset<15; offset++)
  185288. {
  185289. warning_number[offset]=*(warning_message+offset+1);
  185290. if (*(warning_message+offset) == ' ')
  185291. break;
  185292. }
  185293. if((offset > 1) && (offset < 15))
  185294. {
  185295. warning_number[offset-1]='\0';
  185296. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185297. warning_message+offset);
  185298. }
  185299. else
  185300. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185301. }
  185302. else
  185303. # endif
  185304. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185305. #else
  185306. warning_message = warning_message; /* make compiler happy */
  185307. #endif
  185308. png_ptr = png_ptr; /* make compiler happy */
  185309. }
  185310. #endif /* PNG_NO_WARNINGS */
  185311. /* This function is called when the application wants to use another method
  185312. * of handling errors and warnings. Note that the error function MUST NOT
  185313. * return to the calling routine or serious problems will occur. The return
  185314. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185315. */
  185316. void PNGAPI
  185317. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185318. png_error_ptr error_fn, png_error_ptr warning_fn)
  185319. {
  185320. if (png_ptr == NULL)
  185321. return;
  185322. png_ptr->error_ptr = error_ptr;
  185323. png_ptr->error_fn = error_fn;
  185324. png_ptr->warning_fn = warning_fn;
  185325. }
  185326. /* This function returns a pointer to the error_ptr associated with the user
  185327. * functions. The application should free any memory associated with this
  185328. * pointer before png_write_destroy and png_read_destroy are called.
  185329. */
  185330. png_voidp PNGAPI
  185331. png_get_error_ptr(png_structp png_ptr)
  185332. {
  185333. if (png_ptr == NULL)
  185334. return NULL;
  185335. return ((png_voidp)png_ptr->error_ptr);
  185336. }
  185337. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185338. void PNGAPI
  185339. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185340. {
  185341. if(png_ptr != NULL)
  185342. {
  185343. png_ptr->flags &=
  185344. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185345. }
  185346. }
  185347. #endif
  185348. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185349. /*** End of inlined file: pngerror.c ***/
  185350. /*** Start of inlined file: pngget.c ***/
  185351. /* pngget.c - retrieval of values from info struct
  185352. *
  185353. * Last changed in libpng 1.2.15 January 5, 2007
  185354. * For conditions of distribution and use, see copyright notice in png.h
  185355. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185356. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185357. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185358. */
  185359. #define PNG_INTERNAL
  185360. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185361. png_uint_32 PNGAPI
  185362. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185363. {
  185364. if (png_ptr != NULL && info_ptr != NULL)
  185365. return(info_ptr->valid & flag);
  185366. else
  185367. return(0);
  185368. }
  185369. png_uint_32 PNGAPI
  185370. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185371. {
  185372. if (png_ptr != NULL && info_ptr != NULL)
  185373. return(info_ptr->rowbytes);
  185374. else
  185375. return(0);
  185376. }
  185377. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185378. png_bytepp PNGAPI
  185379. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185380. {
  185381. if (png_ptr != NULL && info_ptr != NULL)
  185382. return(info_ptr->row_pointers);
  185383. else
  185384. return(0);
  185385. }
  185386. #endif
  185387. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185388. /* easy access to info, added in libpng-0.99 */
  185389. png_uint_32 PNGAPI
  185390. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185391. {
  185392. if (png_ptr != NULL && info_ptr != NULL)
  185393. {
  185394. return info_ptr->width;
  185395. }
  185396. return (0);
  185397. }
  185398. png_uint_32 PNGAPI
  185399. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185400. {
  185401. if (png_ptr != NULL && info_ptr != NULL)
  185402. {
  185403. return info_ptr->height;
  185404. }
  185405. return (0);
  185406. }
  185407. png_byte PNGAPI
  185408. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185409. {
  185410. if (png_ptr != NULL && info_ptr != NULL)
  185411. {
  185412. return info_ptr->bit_depth;
  185413. }
  185414. return (0);
  185415. }
  185416. png_byte PNGAPI
  185417. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185418. {
  185419. if (png_ptr != NULL && info_ptr != NULL)
  185420. {
  185421. return info_ptr->color_type;
  185422. }
  185423. return (0);
  185424. }
  185425. png_byte PNGAPI
  185426. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185427. {
  185428. if (png_ptr != NULL && info_ptr != NULL)
  185429. {
  185430. return info_ptr->filter_type;
  185431. }
  185432. return (0);
  185433. }
  185434. png_byte PNGAPI
  185435. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185436. {
  185437. if (png_ptr != NULL && info_ptr != NULL)
  185438. {
  185439. return info_ptr->interlace_type;
  185440. }
  185441. return (0);
  185442. }
  185443. png_byte PNGAPI
  185444. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185445. {
  185446. if (png_ptr != NULL && info_ptr != NULL)
  185447. {
  185448. return info_ptr->compression_type;
  185449. }
  185450. return (0);
  185451. }
  185452. png_uint_32 PNGAPI
  185453. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185454. {
  185455. if (png_ptr != NULL && info_ptr != NULL)
  185456. #if defined(PNG_pHYs_SUPPORTED)
  185457. if (info_ptr->valid & PNG_INFO_pHYs)
  185458. {
  185459. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185460. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185461. return (0);
  185462. else return (info_ptr->x_pixels_per_unit);
  185463. }
  185464. #else
  185465. return (0);
  185466. #endif
  185467. return (0);
  185468. }
  185469. png_uint_32 PNGAPI
  185470. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185471. {
  185472. if (png_ptr != NULL && info_ptr != NULL)
  185473. #if defined(PNG_pHYs_SUPPORTED)
  185474. if (info_ptr->valid & PNG_INFO_pHYs)
  185475. {
  185476. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185477. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185478. return (0);
  185479. else return (info_ptr->y_pixels_per_unit);
  185480. }
  185481. #else
  185482. return (0);
  185483. #endif
  185484. return (0);
  185485. }
  185486. png_uint_32 PNGAPI
  185487. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185488. {
  185489. if (png_ptr != NULL && info_ptr != NULL)
  185490. #if defined(PNG_pHYs_SUPPORTED)
  185491. if (info_ptr->valid & PNG_INFO_pHYs)
  185492. {
  185493. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185494. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185495. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185496. return (0);
  185497. else return (info_ptr->x_pixels_per_unit);
  185498. }
  185499. #else
  185500. return (0);
  185501. #endif
  185502. return (0);
  185503. }
  185504. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185505. float PNGAPI
  185506. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185507. {
  185508. if (png_ptr != NULL && info_ptr != NULL)
  185509. #if defined(PNG_pHYs_SUPPORTED)
  185510. if (info_ptr->valid & PNG_INFO_pHYs)
  185511. {
  185512. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185513. if (info_ptr->x_pixels_per_unit == 0)
  185514. return ((float)0.0);
  185515. else
  185516. return ((float)((float)info_ptr->y_pixels_per_unit
  185517. /(float)info_ptr->x_pixels_per_unit));
  185518. }
  185519. #else
  185520. return (0.0);
  185521. #endif
  185522. return ((float)0.0);
  185523. }
  185524. #endif
  185525. png_int_32 PNGAPI
  185526. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185527. {
  185528. if (png_ptr != NULL && info_ptr != NULL)
  185529. #if defined(PNG_oFFs_SUPPORTED)
  185530. if (info_ptr->valid & PNG_INFO_oFFs)
  185531. {
  185532. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185533. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185534. return (0);
  185535. else return (info_ptr->x_offset);
  185536. }
  185537. #else
  185538. return (0);
  185539. #endif
  185540. return (0);
  185541. }
  185542. png_int_32 PNGAPI
  185543. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185544. {
  185545. if (png_ptr != NULL && info_ptr != NULL)
  185546. #if defined(PNG_oFFs_SUPPORTED)
  185547. if (info_ptr->valid & PNG_INFO_oFFs)
  185548. {
  185549. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185550. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185551. return (0);
  185552. else return (info_ptr->y_offset);
  185553. }
  185554. #else
  185555. return (0);
  185556. #endif
  185557. return (0);
  185558. }
  185559. png_int_32 PNGAPI
  185560. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185561. {
  185562. if (png_ptr != NULL && info_ptr != NULL)
  185563. #if defined(PNG_oFFs_SUPPORTED)
  185564. if (info_ptr->valid & PNG_INFO_oFFs)
  185565. {
  185566. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185567. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185568. return (0);
  185569. else return (info_ptr->x_offset);
  185570. }
  185571. #else
  185572. return (0);
  185573. #endif
  185574. return (0);
  185575. }
  185576. png_int_32 PNGAPI
  185577. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185578. {
  185579. if (png_ptr != NULL && info_ptr != NULL)
  185580. #if defined(PNG_oFFs_SUPPORTED)
  185581. if (info_ptr->valid & PNG_INFO_oFFs)
  185582. {
  185583. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185584. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185585. return (0);
  185586. else return (info_ptr->y_offset);
  185587. }
  185588. #else
  185589. return (0);
  185590. #endif
  185591. return (0);
  185592. }
  185593. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185594. png_uint_32 PNGAPI
  185595. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185596. {
  185597. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185598. *.0254 +.5));
  185599. }
  185600. png_uint_32 PNGAPI
  185601. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185602. {
  185603. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185604. *.0254 +.5));
  185605. }
  185606. png_uint_32 PNGAPI
  185607. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185608. {
  185609. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185610. *.0254 +.5));
  185611. }
  185612. float PNGAPI
  185613. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185614. {
  185615. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185616. *.00003937);
  185617. }
  185618. float PNGAPI
  185619. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185620. {
  185621. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185622. *.00003937);
  185623. }
  185624. #if defined(PNG_pHYs_SUPPORTED)
  185625. png_uint_32 PNGAPI
  185626. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185627. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185628. {
  185629. png_uint_32 retval = 0;
  185630. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185631. {
  185632. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185633. if (res_x != NULL)
  185634. {
  185635. *res_x = info_ptr->x_pixels_per_unit;
  185636. retval |= PNG_INFO_pHYs;
  185637. }
  185638. if (res_y != NULL)
  185639. {
  185640. *res_y = info_ptr->y_pixels_per_unit;
  185641. retval |= PNG_INFO_pHYs;
  185642. }
  185643. if (unit_type != NULL)
  185644. {
  185645. *unit_type = (int)info_ptr->phys_unit_type;
  185646. retval |= PNG_INFO_pHYs;
  185647. if(*unit_type == 1)
  185648. {
  185649. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185650. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185651. }
  185652. }
  185653. }
  185654. return (retval);
  185655. }
  185656. #endif /* PNG_pHYs_SUPPORTED */
  185657. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185658. /* png_get_channels really belongs in here, too, but it's been around longer */
  185659. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185660. png_byte PNGAPI
  185661. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185662. {
  185663. if (png_ptr != NULL && info_ptr != NULL)
  185664. return(info_ptr->channels);
  185665. else
  185666. return (0);
  185667. }
  185668. png_bytep PNGAPI
  185669. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  185670. {
  185671. if (png_ptr != NULL && info_ptr != NULL)
  185672. return(info_ptr->signature);
  185673. else
  185674. return (NULL);
  185675. }
  185676. #if defined(PNG_bKGD_SUPPORTED)
  185677. png_uint_32 PNGAPI
  185678. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  185679. png_color_16p *background)
  185680. {
  185681. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  185682. && background != NULL)
  185683. {
  185684. png_debug1(1, "in %s retrieval function\n", "bKGD");
  185685. *background = &(info_ptr->background);
  185686. return (PNG_INFO_bKGD);
  185687. }
  185688. return (0);
  185689. }
  185690. #endif
  185691. #if defined(PNG_cHRM_SUPPORTED)
  185692. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185693. png_uint_32 PNGAPI
  185694. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  185695. double *white_x, double *white_y, double *red_x, double *red_y,
  185696. double *green_x, double *green_y, double *blue_x, double *blue_y)
  185697. {
  185698. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185699. {
  185700. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185701. if (white_x != NULL)
  185702. *white_x = (double)info_ptr->x_white;
  185703. if (white_y != NULL)
  185704. *white_y = (double)info_ptr->y_white;
  185705. if (red_x != NULL)
  185706. *red_x = (double)info_ptr->x_red;
  185707. if (red_y != NULL)
  185708. *red_y = (double)info_ptr->y_red;
  185709. if (green_x != NULL)
  185710. *green_x = (double)info_ptr->x_green;
  185711. if (green_y != NULL)
  185712. *green_y = (double)info_ptr->y_green;
  185713. if (blue_x != NULL)
  185714. *blue_x = (double)info_ptr->x_blue;
  185715. if (blue_y != NULL)
  185716. *blue_y = (double)info_ptr->y_blue;
  185717. return (PNG_INFO_cHRM);
  185718. }
  185719. return (0);
  185720. }
  185721. #endif
  185722. #ifdef PNG_FIXED_POINT_SUPPORTED
  185723. png_uint_32 PNGAPI
  185724. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  185725. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  185726. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  185727. png_fixed_point *blue_x, png_fixed_point *blue_y)
  185728. {
  185729. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  185730. {
  185731. png_debug1(1, "in %s retrieval function\n", "cHRM");
  185732. if (white_x != NULL)
  185733. *white_x = info_ptr->int_x_white;
  185734. if (white_y != NULL)
  185735. *white_y = info_ptr->int_y_white;
  185736. if (red_x != NULL)
  185737. *red_x = info_ptr->int_x_red;
  185738. if (red_y != NULL)
  185739. *red_y = info_ptr->int_y_red;
  185740. if (green_x != NULL)
  185741. *green_x = info_ptr->int_x_green;
  185742. if (green_y != NULL)
  185743. *green_y = info_ptr->int_y_green;
  185744. if (blue_x != NULL)
  185745. *blue_x = info_ptr->int_x_blue;
  185746. if (blue_y != NULL)
  185747. *blue_y = info_ptr->int_y_blue;
  185748. return (PNG_INFO_cHRM);
  185749. }
  185750. return (0);
  185751. }
  185752. #endif
  185753. #endif
  185754. #if defined(PNG_gAMA_SUPPORTED)
  185755. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185756. png_uint_32 PNGAPI
  185757. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  185758. {
  185759. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185760. && file_gamma != NULL)
  185761. {
  185762. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185763. *file_gamma = (double)info_ptr->gamma;
  185764. return (PNG_INFO_gAMA);
  185765. }
  185766. return (0);
  185767. }
  185768. #endif
  185769. #ifdef PNG_FIXED_POINT_SUPPORTED
  185770. png_uint_32 PNGAPI
  185771. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  185772. png_fixed_point *int_file_gamma)
  185773. {
  185774. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  185775. && int_file_gamma != NULL)
  185776. {
  185777. png_debug1(1, "in %s retrieval function\n", "gAMA");
  185778. *int_file_gamma = info_ptr->int_gamma;
  185779. return (PNG_INFO_gAMA);
  185780. }
  185781. return (0);
  185782. }
  185783. #endif
  185784. #endif
  185785. #if defined(PNG_sRGB_SUPPORTED)
  185786. png_uint_32 PNGAPI
  185787. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  185788. {
  185789. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  185790. && file_srgb_intent != NULL)
  185791. {
  185792. png_debug1(1, "in %s retrieval function\n", "sRGB");
  185793. *file_srgb_intent = (int)info_ptr->srgb_intent;
  185794. return (PNG_INFO_sRGB);
  185795. }
  185796. return (0);
  185797. }
  185798. #endif
  185799. #if defined(PNG_iCCP_SUPPORTED)
  185800. png_uint_32 PNGAPI
  185801. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  185802. png_charpp name, int *compression_type,
  185803. png_charpp profile, png_uint_32 *proflen)
  185804. {
  185805. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  185806. && name != NULL && profile != NULL && proflen != NULL)
  185807. {
  185808. png_debug1(1, "in %s retrieval function\n", "iCCP");
  185809. *name = info_ptr->iccp_name;
  185810. *profile = info_ptr->iccp_profile;
  185811. /* compression_type is a dummy so the API won't have to change
  185812. if we introduce multiple compression types later. */
  185813. *proflen = (int)info_ptr->iccp_proflen;
  185814. *compression_type = (int)info_ptr->iccp_compression;
  185815. return (PNG_INFO_iCCP);
  185816. }
  185817. return (0);
  185818. }
  185819. #endif
  185820. #if defined(PNG_sPLT_SUPPORTED)
  185821. png_uint_32 PNGAPI
  185822. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  185823. png_sPLT_tpp spalettes)
  185824. {
  185825. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  185826. {
  185827. *spalettes = info_ptr->splt_palettes;
  185828. return ((png_uint_32)info_ptr->splt_palettes_num);
  185829. }
  185830. return (0);
  185831. }
  185832. #endif
  185833. #if defined(PNG_hIST_SUPPORTED)
  185834. png_uint_32 PNGAPI
  185835. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  185836. {
  185837. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  185838. && hist != NULL)
  185839. {
  185840. png_debug1(1, "in %s retrieval function\n", "hIST");
  185841. *hist = info_ptr->hist;
  185842. return (PNG_INFO_hIST);
  185843. }
  185844. return (0);
  185845. }
  185846. #endif
  185847. png_uint_32 PNGAPI
  185848. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  185849. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  185850. int *color_type, int *interlace_type, int *compression_type,
  185851. int *filter_type)
  185852. {
  185853. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  185854. bit_depth != NULL && color_type != NULL)
  185855. {
  185856. png_debug1(1, "in %s retrieval function\n", "IHDR");
  185857. *width = info_ptr->width;
  185858. *height = info_ptr->height;
  185859. *bit_depth = info_ptr->bit_depth;
  185860. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  185861. png_error(png_ptr, "Invalid bit depth");
  185862. *color_type = info_ptr->color_type;
  185863. if (info_ptr->color_type > 6)
  185864. png_error(png_ptr, "Invalid color type");
  185865. if (compression_type != NULL)
  185866. *compression_type = info_ptr->compression_type;
  185867. if (filter_type != NULL)
  185868. *filter_type = info_ptr->filter_type;
  185869. if (interlace_type != NULL)
  185870. *interlace_type = info_ptr->interlace_type;
  185871. /* check for potential overflow of rowbytes */
  185872. if (*width == 0 || *width > PNG_UINT_31_MAX)
  185873. png_error(png_ptr, "Invalid image width");
  185874. if (*height == 0 || *height > PNG_UINT_31_MAX)
  185875. png_error(png_ptr, "Invalid image height");
  185876. if (info_ptr->width > (PNG_UINT_32_MAX
  185877. >> 3) /* 8-byte RGBA pixels */
  185878. - 64 /* bigrowbuf hack */
  185879. - 1 /* filter byte */
  185880. - 7*8 /* rounding of width to multiple of 8 pixels */
  185881. - 8) /* extra max_pixel_depth pad */
  185882. {
  185883. png_warning(png_ptr,
  185884. "Width too large for libpng to process image data.");
  185885. }
  185886. return (1);
  185887. }
  185888. return (0);
  185889. }
  185890. #if defined(PNG_oFFs_SUPPORTED)
  185891. png_uint_32 PNGAPI
  185892. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  185893. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  185894. {
  185895. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  185896. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  185897. {
  185898. png_debug1(1, "in %s retrieval function\n", "oFFs");
  185899. *offset_x = info_ptr->x_offset;
  185900. *offset_y = info_ptr->y_offset;
  185901. *unit_type = (int)info_ptr->offset_unit_type;
  185902. return (PNG_INFO_oFFs);
  185903. }
  185904. return (0);
  185905. }
  185906. #endif
  185907. #if defined(PNG_pCAL_SUPPORTED)
  185908. png_uint_32 PNGAPI
  185909. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  185910. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  185911. png_charp *units, png_charpp *params)
  185912. {
  185913. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  185914. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  185915. nparams != NULL && units != NULL && params != NULL)
  185916. {
  185917. png_debug1(1, "in %s retrieval function\n", "pCAL");
  185918. *purpose = info_ptr->pcal_purpose;
  185919. *X0 = info_ptr->pcal_X0;
  185920. *X1 = info_ptr->pcal_X1;
  185921. *type = (int)info_ptr->pcal_type;
  185922. *nparams = (int)info_ptr->pcal_nparams;
  185923. *units = info_ptr->pcal_units;
  185924. *params = info_ptr->pcal_params;
  185925. return (PNG_INFO_pCAL);
  185926. }
  185927. return (0);
  185928. }
  185929. #endif
  185930. #if defined(PNG_sCAL_SUPPORTED)
  185931. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185932. png_uint_32 PNGAPI
  185933. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  185934. int *unit, double *width, double *height)
  185935. {
  185936. if (png_ptr != NULL && info_ptr != NULL &&
  185937. (info_ptr->valid & PNG_INFO_sCAL))
  185938. {
  185939. *unit = info_ptr->scal_unit;
  185940. *width = info_ptr->scal_pixel_width;
  185941. *height = info_ptr->scal_pixel_height;
  185942. return (PNG_INFO_sCAL);
  185943. }
  185944. return(0);
  185945. }
  185946. #else
  185947. #ifdef PNG_FIXED_POINT_SUPPORTED
  185948. png_uint_32 PNGAPI
  185949. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  185950. int *unit, png_charpp width, png_charpp height)
  185951. {
  185952. if (png_ptr != NULL && info_ptr != NULL &&
  185953. (info_ptr->valid & PNG_INFO_sCAL))
  185954. {
  185955. *unit = info_ptr->scal_unit;
  185956. *width = info_ptr->scal_s_width;
  185957. *height = info_ptr->scal_s_height;
  185958. return (PNG_INFO_sCAL);
  185959. }
  185960. return(0);
  185961. }
  185962. #endif
  185963. #endif
  185964. #endif
  185965. #if defined(PNG_pHYs_SUPPORTED)
  185966. png_uint_32 PNGAPI
  185967. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  185968. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185969. {
  185970. png_uint_32 retval = 0;
  185971. if (png_ptr != NULL && info_ptr != NULL &&
  185972. (info_ptr->valid & PNG_INFO_pHYs))
  185973. {
  185974. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185975. if (res_x != NULL)
  185976. {
  185977. *res_x = info_ptr->x_pixels_per_unit;
  185978. retval |= PNG_INFO_pHYs;
  185979. }
  185980. if (res_y != NULL)
  185981. {
  185982. *res_y = info_ptr->y_pixels_per_unit;
  185983. retval |= PNG_INFO_pHYs;
  185984. }
  185985. if (unit_type != NULL)
  185986. {
  185987. *unit_type = (int)info_ptr->phys_unit_type;
  185988. retval |= PNG_INFO_pHYs;
  185989. }
  185990. }
  185991. return (retval);
  185992. }
  185993. #endif
  185994. png_uint_32 PNGAPI
  185995. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  185996. int *num_palette)
  185997. {
  185998. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  185999. && palette != NULL)
  186000. {
  186001. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186002. *palette = info_ptr->palette;
  186003. *num_palette = info_ptr->num_palette;
  186004. png_debug1(3, "num_palette = %d\n", *num_palette);
  186005. return (PNG_INFO_PLTE);
  186006. }
  186007. return (0);
  186008. }
  186009. #if defined(PNG_sBIT_SUPPORTED)
  186010. png_uint_32 PNGAPI
  186011. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186012. {
  186013. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186014. && sig_bit != NULL)
  186015. {
  186016. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186017. *sig_bit = &(info_ptr->sig_bit);
  186018. return (PNG_INFO_sBIT);
  186019. }
  186020. return (0);
  186021. }
  186022. #endif
  186023. #if defined(PNG_TEXT_SUPPORTED)
  186024. png_uint_32 PNGAPI
  186025. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186026. int *num_text)
  186027. {
  186028. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186029. {
  186030. png_debug1(1, "in %s retrieval function\n",
  186031. (png_ptr->chunk_name[0] == '\0' ? "text"
  186032. : (png_const_charp)png_ptr->chunk_name));
  186033. if (text_ptr != NULL)
  186034. *text_ptr = info_ptr->text;
  186035. if (num_text != NULL)
  186036. *num_text = info_ptr->num_text;
  186037. return ((png_uint_32)info_ptr->num_text);
  186038. }
  186039. if (num_text != NULL)
  186040. *num_text = 0;
  186041. return(0);
  186042. }
  186043. #endif
  186044. #if defined(PNG_tIME_SUPPORTED)
  186045. png_uint_32 PNGAPI
  186046. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186047. {
  186048. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186049. && mod_time != NULL)
  186050. {
  186051. png_debug1(1, "in %s retrieval function\n", "tIME");
  186052. *mod_time = &(info_ptr->mod_time);
  186053. return (PNG_INFO_tIME);
  186054. }
  186055. return (0);
  186056. }
  186057. #endif
  186058. #if defined(PNG_tRNS_SUPPORTED)
  186059. png_uint_32 PNGAPI
  186060. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186061. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186062. {
  186063. png_uint_32 retval = 0;
  186064. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186065. {
  186066. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186067. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186068. {
  186069. if (trans != NULL)
  186070. {
  186071. *trans = info_ptr->trans;
  186072. retval |= PNG_INFO_tRNS;
  186073. }
  186074. if (trans_values != NULL)
  186075. *trans_values = &(info_ptr->trans_values);
  186076. }
  186077. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186078. {
  186079. if (trans_values != NULL)
  186080. {
  186081. *trans_values = &(info_ptr->trans_values);
  186082. retval |= PNG_INFO_tRNS;
  186083. }
  186084. if(trans != NULL)
  186085. *trans = NULL;
  186086. }
  186087. if(num_trans != NULL)
  186088. {
  186089. *num_trans = info_ptr->num_trans;
  186090. retval |= PNG_INFO_tRNS;
  186091. }
  186092. }
  186093. return (retval);
  186094. }
  186095. #endif
  186096. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186097. png_uint_32 PNGAPI
  186098. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186099. png_unknown_chunkpp unknowns)
  186100. {
  186101. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186102. {
  186103. *unknowns = info_ptr->unknown_chunks;
  186104. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186105. }
  186106. return (0);
  186107. }
  186108. #endif
  186109. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186110. png_byte PNGAPI
  186111. png_get_rgb_to_gray_status (png_structp png_ptr)
  186112. {
  186113. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186114. }
  186115. #endif
  186116. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186117. png_voidp PNGAPI
  186118. png_get_user_chunk_ptr(png_structp png_ptr)
  186119. {
  186120. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186121. }
  186122. #endif
  186123. #ifdef PNG_WRITE_SUPPORTED
  186124. png_uint_32 PNGAPI
  186125. png_get_compression_buffer_size(png_structp png_ptr)
  186126. {
  186127. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186128. }
  186129. #endif
  186130. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186131. #ifndef PNG_1_0_X
  186132. /* this function was added to libpng 1.2.0 and should exist by default */
  186133. png_uint_32 PNGAPI
  186134. png_get_asm_flags (png_structp png_ptr)
  186135. {
  186136. /* obsolete, to be removed from libpng-1.4.0 */
  186137. return (png_ptr? 0L: 0L);
  186138. }
  186139. /* this function was added to libpng 1.2.0 and should exist by default */
  186140. png_uint_32 PNGAPI
  186141. png_get_asm_flagmask (int flag_select)
  186142. {
  186143. /* obsolete, to be removed from libpng-1.4.0 */
  186144. flag_select=flag_select;
  186145. return 0L;
  186146. }
  186147. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186148. /* this function was added to libpng 1.2.0 */
  186149. png_uint_32 PNGAPI
  186150. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186151. {
  186152. /* obsolete, to be removed from libpng-1.4.0 */
  186153. flag_select=flag_select;
  186154. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186155. return 0L;
  186156. }
  186157. /* this function was added to libpng 1.2.0 */
  186158. png_byte PNGAPI
  186159. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186160. {
  186161. /* obsolete, to be removed from libpng-1.4.0 */
  186162. return (png_ptr? 0: 0);
  186163. }
  186164. /* this function was added to libpng 1.2.0 */
  186165. png_uint_32 PNGAPI
  186166. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186167. {
  186168. /* obsolete, to be removed from libpng-1.4.0 */
  186169. return (png_ptr? 0L: 0L);
  186170. }
  186171. #endif /* ?PNG_1_0_X */
  186172. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186173. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186174. /* these functions were added to libpng 1.2.6 */
  186175. png_uint_32 PNGAPI
  186176. png_get_user_width_max (png_structp png_ptr)
  186177. {
  186178. return (png_ptr? png_ptr->user_width_max : 0);
  186179. }
  186180. png_uint_32 PNGAPI
  186181. png_get_user_height_max (png_structp png_ptr)
  186182. {
  186183. return (png_ptr? png_ptr->user_height_max : 0);
  186184. }
  186185. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186186. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186187. /*** End of inlined file: pngget.c ***/
  186188. /*** Start of inlined file: pngmem.c ***/
  186189. /* pngmem.c - stub functions for memory allocation
  186190. *
  186191. * Last changed in libpng 1.2.13 November 13, 2006
  186192. * For conditions of distribution and use, see copyright notice in png.h
  186193. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186194. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186195. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186196. *
  186197. * This file provides a location for all memory allocation. Users who
  186198. * need special memory handling are expected to supply replacement
  186199. * functions for png_malloc() and png_free(), and to use
  186200. * png_create_read_struct_2() and png_create_write_struct_2() to
  186201. * identify the replacement functions.
  186202. */
  186203. #define PNG_INTERNAL
  186204. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186205. /* Borland DOS special memory handler */
  186206. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186207. /* if you change this, be sure to change the one in png.h also */
  186208. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186209. by a single call to calloc() if this is thought to improve performance. */
  186210. png_voidp /* PRIVATE */
  186211. png_create_struct(int type)
  186212. {
  186213. #ifdef PNG_USER_MEM_SUPPORTED
  186214. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186215. }
  186216. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186217. png_voidp /* PRIVATE */
  186218. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186219. {
  186220. #endif /* PNG_USER_MEM_SUPPORTED */
  186221. png_size_t size;
  186222. png_voidp struct_ptr;
  186223. if (type == PNG_STRUCT_INFO)
  186224. size = png_sizeof(png_info);
  186225. else if (type == PNG_STRUCT_PNG)
  186226. size = png_sizeof(png_struct);
  186227. else
  186228. return (png_get_copyright(NULL));
  186229. #ifdef PNG_USER_MEM_SUPPORTED
  186230. if(malloc_fn != NULL)
  186231. {
  186232. png_struct dummy_struct;
  186233. png_structp png_ptr = &dummy_struct;
  186234. png_ptr->mem_ptr=mem_ptr;
  186235. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186236. }
  186237. else
  186238. #endif /* PNG_USER_MEM_SUPPORTED */
  186239. struct_ptr = (png_voidp)farmalloc(size);
  186240. if (struct_ptr != NULL)
  186241. png_memset(struct_ptr, 0, size);
  186242. return (struct_ptr);
  186243. }
  186244. /* Free memory allocated by a png_create_struct() call */
  186245. void /* PRIVATE */
  186246. png_destroy_struct(png_voidp struct_ptr)
  186247. {
  186248. #ifdef PNG_USER_MEM_SUPPORTED
  186249. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186250. }
  186251. /* Free memory allocated by a png_create_struct() call */
  186252. void /* PRIVATE */
  186253. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186254. png_voidp mem_ptr)
  186255. {
  186256. #endif
  186257. if (struct_ptr != NULL)
  186258. {
  186259. #ifdef PNG_USER_MEM_SUPPORTED
  186260. if(free_fn != NULL)
  186261. {
  186262. png_struct dummy_struct;
  186263. png_structp png_ptr = &dummy_struct;
  186264. png_ptr->mem_ptr=mem_ptr;
  186265. (*(free_fn))(png_ptr, struct_ptr);
  186266. return;
  186267. }
  186268. #endif /* PNG_USER_MEM_SUPPORTED */
  186269. farfree (struct_ptr);
  186270. }
  186271. }
  186272. /* Allocate memory. For reasonable files, size should never exceed
  186273. * 64K. However, zlib may allocate more then 64K if you don't tell
  186274. * it not to. See zconf.h and png.h for more information. zlib does
  186275. * need to allocate exactly 64K, so whatever you call here must
  186276. * have the ability to do that.
  186277. *
  186278. * Borland seems to have a problem in DOS mode for exactly 64K.
  186279. * It gives you a segment with an offset of 8 (perhaps to store its
  186280. * memory stuff). zlib doesn't like this at all, so we have to
  186281. * detect and deal with it. This code should not be needed in
  186282. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186283. * been updated by Alexander Lehmann for version 0.89 to waste less
  186284. * memory.
  186285. *
  186286. * Note that we can't use png_size_t for the "size" declaration,
  186287. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186288. * result, we would be truncating potentially larger memory requests
  186289. * (which should cause a fatal error) and introducing major problems.
  186290. */
  186291. png_voidp PNGAPI
  186292. png_malloc(png_structp png_ptr, png_uint_32 size)
  186293. {
  186294. png_voidp ret;
  186295. if (png_ptr == NULL || size == 0)
  186296. return (NULL);
  186297. #ifdef PNG_USER_MEM_SUPPORTED
  186298. if(png_ptr->malloc_fn != NULL)
  186299. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186300. else
  186301. ret = (png_malloc_default(png_ptr, size));
  186302. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186303. png_error(png_ptr, "Out of memory!");
  186304. return (ret);
  186305. }
  186306. png_voidp PNGAPI
  186307. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186308. {
  186309. png_voidp ret;
  186310. #endif /* PNG_USER_MEM_SUPPORTED */
  186311. if (png_ptr == NULL || size == 0)
  186312. return (NULL);
  186313. #ifdef PNG_MAX_MALLOC_64K
  186314. if (size > (png_uint_32)65536L)
  186315. {
  186316. png_warning(png_ptr, "Cannot Allocate > 64K");
  186317. ret = NULL;
  186318. }
  186319. else
  186320. #endif
  186321. if (size != (size_t)size)
  186322. ret = NULL;
  186323. else if (size == (png_uint_32)65536L)
  186324. {
  186325. if (png_ptr->offset_table == NULL)
  186326. {
  186327. /* try to see if we need to do any of this fancy stuff */
  186328. ret = farmalloc(size);
  186329. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186330. {
  186331. int num_blocks;
  186332. png_uint_32 total_size;
  186333. png_bytep table;
  186334. int i;
  186335. png_byte huge * hptr;
  186336. if (ret != NULL)
  186337. {
  186338. farfree(ret);
  186339. ret = NULL;
  186340. }
  186341. if(png_ptr->zlib_window_bits > 14)
  186342. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186343. else
  186344. num_blocks = 1;
  186345. if (png_ptr->zlib_mem_level >= 7)
  186346. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186347. else
  186348. num_blocks++;
  186349. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186350. table = farmalloc(total_size);
  186351. if (table == NULL)
  186352. {
  186353. #ifndef PNG_USER_MEM_SUPPORTED
  186354. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186355. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186356. else
  186357. png_warning(png_ptr, "Out Of Memory.");
  186358. #endif
  186359. return (NULL);
  186360. }
  186361. if ((png_size_t)table & 0xfff0)
  186362. {
  186363. #ifndef PNG_USER_MEM_SUPPORTED
  186364. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186365. png_error(png_ptr,
  186366. "Farmalloc didn't return normalized pointer");
  186367. else
  186368. png_warning(png_ptr,
  186369. "Farmalloc didn't return normalized pointer");
  186370. #endif
  186371. return (NULL);
  186372. }
  186373. png_ptr->offset_table = table;
  186374. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186375. png_sizeof (png_bytep));
  186376. if (png_ptr->offset_table_ptr == NULL)
  186377. {
  186378. #ifndef PNG_USER_MEM_SUPPORTED
  186379. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186380. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186381. else
  186382. png_warning(png_ptr, "Out Of memory.");
  186383. #endif
  186384. return (NULL);
  186385. }
  186386. hptr = (png_byte huge *)table;
  186387. if ((png_size_t)hptr & 0xf)
  186388. {
  186389. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186390. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186391. }
  186392. for (i = 0; i < num_blocks; i++)
  186393. {
  186394. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186395. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186396. }
  186397. png_ptr->offset_table_number = num_blocks;
  186398. png_ptr->offset_table_count = 0;
  186399. png_ptr->offset_table_count_free = 0;
  186400. }
  186401. }
  186402. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186403. {
  186404. #ifndef PNG_USER_MEM_SUPPORTED
  186405. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186406. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186407. else
  186408. png_warning(png_ptr, "Out of Memory.");
  186409. #endif
  186410. return (NULL);
  186411. }
  186412. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186413. }
  186414. else
  186415. ret = farmalloc(size);
  186416. #ifndef PNG_USER_MEM_SUPPORTED
  186417. if (ret == NULL)
  186418. {
  186419. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186420. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186421. else
  186422. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186423. }
  186424. #endif
  186425. return (ret);
  186426. }
  186427. /* free a pointer allocated by png_malloc(). In the default
  186428. configuration, png_ptr is not used, but is passed in case it
  186429. is needed. If ptr is NULL, return without taking any action. */
  186430. void PNGAPI
  186431. png_free(png_structp png_ptr, png_voidp ptr)
  186432. {
  186433. if (png_ptr == NULL || ptr == NULL)
  186434. return;
  186435. #ifdef PNG_USER_MEM_SUPPORTED
  186436. if (png_ptr->free_fn != NULL)
  186437. {
  186438. (*(png_ptr->free_fn))(png_ptr, ptr);
  186439. return;
  186440. }
  186441. else png_free_default(png_ptr, ptr);
  186442. }
  186443. void PNGAPI
  186444. png_free_default(png_structp png_ptr, png_voidp ptr)
  186445. {
  186446. #endif /* PNG_USER_MEM_SUPPORTED */
  186447. if(png_ptr == NULL) return;
  186448. if (png_ptr->offset_table != NULL)
  186449. {
  186450. int i;
  186451. for (i = 0; i < png_ptr->offset_table_count; i++)
  186452. {
  186453. if (ptr == png_ptr->offset_table_ptr[i])
  186454. {
  186455. ptr = NULL;
  186456. png_ptr->offset_table_count_free++;
  186457. break;
  186458. }
  186459. }
  186460. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186461. {
  186462. farfree(png_ptr->offset_table);
  186463. farfree(png_ptr->offset_table_ptr);
  186464. png_ptr->offset_table = NULL;
  186465. png_ptr->offset_table_ptr = NULL;
  186466. }
  186467. }
  186468. if (ptr != NULL)
  186469. {
  186470. farfree(ptr);
  186471. }
  186472. }
  186473. #else /* Not the Borland DOS special memory handler */
  186474. /* Allocate memory for a png_struct or a png_info. The malloc and
  186475. memset can be replaced by a single call to calloc() if this is thought
  186476. to improve performance noticably. */
  186477. png_voidp /* PRIVATE */
  186478. png_create_struct(int type)
  186479. {
  186480. #ifdef PNG_USER_MEM_SUPPORTED
  186481. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186482. }
  186483. /* Allocate memory for a png_struct or a png_info. The malloc and
  186484. memset can be replaced by a single call to calloc() if this is thought
  186485. to improve performance noticably. */
  186486. png_voidp /* PRIVATE */
  186487. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186488. {
  186489. #endif /* PNG_USER_MEM_SUPPORTED */
  186490. png_size_t size;
  186491. png_voidp struct_ptr;
  186492. if (type == PNG_STRUCT_INFO)
  186493. size = png_sizeof(png_info);
  186494. else if (type == PNG_STRUCT_PNG)
  186495. size = png_sizeof(png_struct);
  186496. else
  186497. return (NULL);
  186498. #ifdef PNG_USER_MEM_SUPPORTED
  186499. if(malloc_fn != NULL)
  186500. {
  186501. png_struct dummy_struct;
  186502. png_structp png_ptr = &dummy_struct;
  186503. png_ptr->mem_ptr=mem_ptr;
  186504. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186505. if (struct_ptr != NULL)
  186506. png_memset(struct_ptr, 0, size);
  186507. return (struct_ptr);
  186508. }
  186509. #endif /* PNG_USER_MEM_SUPPORTED */
  186510. #if defined(__TURBOC__) && !defined(__FLAT__)
  186511. struct_ptr = (png_voidp)farmalloc(size);
  186512. #else
  186513. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186514. struct_ptr = (png_voidp)halloc(size,1);
  186515. # else
  186516. struct_ptr = (png_voidp)malloc(size);
  186517. # endif
  186518. #endif
  186519. if (struct_ptr != NULL)
  186520. png_memset(struct_ptr, 0, size);
  186521. return (struct_ptr);
  186522. }
  186523. /* Free memory allocated by a png_create_struct() call */
  186524. void /* PRIVATE */
  186525. png_destroy_struct(png_voidp struct_ptr)
  186526. {
  186527. #ifdef PNG_USER_MEM_SUPPORTED
  186528. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186529. }
  186530. /* Free memory allocated by a png_create_struct() call */
  186531. void /* PRIVATE */
  186532. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186533. png_voidp mem_ptr)
  186534. {
  186535. #endif /* PNG_USER_MEM_SUPPORTED */
  186536. if (struct_ptr != NULL)
  186537. {
  186538. #ifdef PNG_USER_MEM_SUPPORTED
  186539. if(free_fn != NULL)
  186540. {
  186541. png_struct dummy_struct;
  186542. png_structp png_ptr = &dummy_struct;
  186543. png_ptr->mem_ptr=mem_ptr;
  186544. (*(free_fn))(png_ptr, struct_ptr);
  186545. return;
  186546. }
  186547. #endif /* PNG_USER_MEM_SUPPORTED */
  186548. #if defined(__TURBOC__) && !defined(__FLAT__)
  186549. farfree(struct_ptr);
  186550. #else
  186551. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186552. hfree(struct_ptr);
  186553. # else
  186554. free(struct_ptr);
  186555. # endif
  186556. #endif
  186557. }
  186558. }
  186559. /* Allocate memory. For reasonable files, size should never exceed
  186560. 64K. However, zlib may allocate more then 64K if you don't tell
  186561. it not to. See zconf.h and png.h for more information. zlib does
  186562. need to allocate exactly 64K, so whatever you call here must
  186563. have the ability to do that. */
  186564. png_voidp PNGAPI
  186565. png_malloc(png_structp png_ptr, png_uint_32 size)
  186566. {
  186567. png_voidp ret;
  186568. #ifdef PNG_USER_MEM_SUPPORTED
  186569. if (png_ptr == NULL || size == 0)
  186570. return (NULL);
  186571. if(png_ptr->malloc_fn != NULL)
  186572. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186573. else
  186574. ret = (png_malloc_default(png_ptr, size));
  186575. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186576. png_error(png_ptr, "Out of Memory!");
  186577. return (ret);
  186578. }
  186579. png_voidp PNGAPI
  186580. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186581. {
  186582. png_voidp ret;
  186583. #endif /* PNG_USER_MEM_SUPPORTED */
  186584. if (png_ptr == NULL || size == 0)
  186585. return (NULL);
  186586. #ifdef PNG_MAX_MALLOC_64K
  186587. if (size > (png_uint_32)65536L)
  186588. {
  186589. #ifndef PNG_USER_MEM_SUPPORTED
  186590. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186591. png_error(png_ptr, "Cannot Allocate > 64K");
  186592. else
  186593. #endif
  186594. return NULL;
  186595. }
  186596. #endif
  186597. /* Check for overflow */
  186598. #if defined(__TURBOC__) && !defined(__FLAT__)
  186599. if (size != (unsigned long)size)
  186600. ret = NULL;
  186601. else
  186602. ret = farmalloc(size);
  186603. #else
  186604. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186605. if (size != (unsigned long)size)
  186606. ret = NULL;
  186607. else
  186608. ret = halloc(size, 1);
  186609. # else
  186610. if (size != (size_t)size)
  186611. ret = NULL;
  186612. else
  186613. ret = malloc((size_t)size);
  186614. # endif
  186615. #endif
  186616. #ifndef PNG_USER_MEM_SUPPORTED
  186617. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186618. png_error(png_ptr, "Out of Memory");
  186619. #endif
  186620. return (ret);
  186621. }
  186622. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186623. without taking any action. */
  186624. void PNGAPI
  186625. png_free(png_structp png_ptr, png_voidp ptr)
  186626. {
  186627. if (png_ptr == NULL || ptr == NULL)
  186628. return;
  186629. #ifdef PNG_USER_MEM_SUPPORTED
  186630. if (png_ptr->free_fn != NULL)
  186631. {
  186632. (*(png_ptr->free_fn))(png_ptr, ptr);
  186633. return;
  186634. }
  186635. else png_free_default(png_ptr, ptr);
  186636. }
  186637. void PNGAPI
  186638. png_free_default(png_structp png_ptr, png_voidp ptr)
  186639. {
  186640. if (png_ptr == NULL || ptr == NULL)
  186641. return;
  186642. #endif /* PNG_USER_MEM_SUPPORTED */
  186643. #if defined(__TURBOC__) && !defined(__FLAT__)
  186644. farfree(ptr);
  186645. #else
  186646. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186647. hfree(ptr);
  186648. # else
  186649. free(ptr);
  186650. # endif
  186651. #endif
  186652. }
  186653. #endif /* Not Borland DOS special memory handler */
  186654. #if defined(PNG_1_0_X)
  186655. # define png_malloc_warn png_malloc
  186656. #else
  186657. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186658. * function will set up png_malloc() to issue a png_warning and return NULL
  186659. * instead of issuing a png_error, if it fails to allocate the requested
  186660. * memory.
  186661. */
  186662. png_voidp PNGAPI
  186663. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186664. {
  186665. png_voidp ptr;
  186666. png_uint_32 save_flags;
  186667. if(png_ptr == NULL) return (NULL);
  186668. save_flags=png_ptr->flags;
  186669. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  186670. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  186671. png_ptr->flags=save_flags;
  186672. return(ptr);
  186673. }
  186674. #endif
  186675. png_voidp PNGAPI
  186676. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  186677. png_uint_32 length)
  186678. {
  186679. png_size_t size;
  186680. size = (png_size_t)length;
  186681. if ((png_uint_32)size != length)
  186682. png_error(png_ptr,"Overflow in png_memcpy_check.");
  186683. return(png_memcpy (s1, s2, size));
  186684. }
  186685. png_voidp PNGAPI
  186686. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  186687. png_uint_32 length)
  186688. {
  186689. png_size_t size;
  186690. size = (png_size_t)length;
  186691. if ((png_uint_32)size != length)
  186692. png_error(png_ptr,"Overflow in png_memset_check.");
  186693. return (png_memset (s1, value, size));
  186694. }
  186695. #ifdef PNG_USER_MEM_SUPPORTED
  186696. /* This function is called when the application wants to use another method
  186697. * of allocating and freeing memory.
  186698. */
  186699. void PNGAPI
  186700. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  186701. malloc_fn, png_free_ptr free_fn)
  186702. {
  186703. if(png_ptr != NULL) {
  186704. png_ptr->mem_ptr = mem_ptr;
  186705. png_ptr->malloc_fn = malloc_fn;
  186706. png_ptr->free_fn = free_fn;
  186707. }
  186708. }
  186709. /* This function returns a pointer to the mem_ptr associated with the user
  186710. * functions. The application should free any memory associated with this
  186711. * pointer before png_write_destroy and png_read_destroy are called.
  186712. */
  186713. png_voidp PNGAPI
  186714. png_get_mem_ptr(png_structp png_ptr)
  186715. {
  186716. if(png_ptr == NULL) return (NULL);
  186717. return ((png_voidp)png_ptr->mem_ptr);
  186718. }
  186719. #endif /* PNG_USER_MEM_SUPPORTED */
  186720. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186721. /*** End of inlined file: pngmem.c ***/
  186722. /*** Start of inlined file: pngread.c ***/
  186723. /* pngread.c - read a PNG file
  186724. *
  186725. * Last changed in libpng 1.2.20 September 7, 2007
  186726. * For conditions of distribution and use, see copyright notice in png.h
  186727. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186728. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186729. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186730. *
  186731. * This file contains routines that an application calls directly to
  186732. * read a PNG file or stream.
  186733. */
  186734. #define PNG_INTERNAL
  186735. #if defined(PNG_READ_SUPPORTED)
  186736. /* Create a PNG structure for reading, and allocate any memory needed. */
  186737. png_structp PNGAPI
  186738. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  186739. png_error_ptr error_fn, png_error_ptr warn_fn)
  186740. {
  186741. #ifdef PNG_USER_MEM_SUPPORTED
  186742. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  186743. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  186744. }
  186745. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  186746. png_structp PNGAPI
  186747. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  186748. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  186749. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  186750. {
  186751. #endif /* PNG_USER_MEM_SUPPORTED */
  186752. png_structp png_ptr;
  186753. #ifdef PNG_SETJMP_SUPPORTED
  186754. #ifdef USE_FAR_KEYWORD
  186755. jmp_buf jmpbuf;
  186756. #endif
  186757. #endif
  186758. int i;
  186759. png_debug(1, "in png_create_read_struct\n");
  186760. #ifdef PNG_USER_MEM_SUPPORTED
  186761. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  186762. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  186763. #else
  186764. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186765. #endif
  186766. if (png_ptr == NULL)
  186767. return (NULL);
  186768. /* added at libpng-1.2.6 */
  186769. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186770. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186771. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186772. #endif
  186773. #ifdef PNG_SETJMP_SUPPORTED
  186774. #ifdef USE_FAR_KEYWORD
  186775. if (setjmp(jmpbuf))
  186776. #else
  186777. if (setjmp(png_ptr->jmpbuf))
  186778. #endif
  186779. {
  186780. png_free(png_ptr, png_ptr->zbuf);
  186781. png_ptr->zbuf=NULL;
  186782. #ifdef PNG_USER_MEM_SUPPORTED
  186783. png_destroy_struct_2((png_voidp)png_ptr,
  186784. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  186785. #else
  186786. png_destroy_struct((png_voidp)png_ptr);
  186787. #endif
  186788. return (NULL);
  186789. }
  186790. #ifdef USE_FAR_KEYWORD
  186791. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186792. #endif
  186793. #endif
  186794. #ifdef PNG_USER_MEM_SUPPORTED
  186795. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  186796. #endif
  186797. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  186798. i=0;
  186799. do
  186800. {
  186801. if(user_png_ver[i] != png_libpng_ver[i])
  186802. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186803. } while (png_libpng_ver[i++]);
  186804. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  186805. {
  186806. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  186807. * we must recompile any applications that use any older library version.
  186808. * For versions after libpng 1.0, we will be compatible, so we need
  186809. * only check the first digit.
  186810. */
  186811. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  186812. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  186813. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  186814. {
  186815. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186816. char msg[80];
  186817. if (user_png_ver)
  186818. {
  186819. png_snprintf(msg, 80,
  186820. "Application was compiled with png.h from libpng-%.20s",
  186821. user_png_ver);
  186822. png_warning(png_ptr, msg);
  186823. }
  186824. png_snprintf(msg, 80,
  186825. "Application is running with png.c from libpng-%.20s",
  186826. png_libpng_ver);
  186827. png_warning(png_ptr, msg);
  186828. #endif
  186829. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186830. png_ptr->flags=0;
  186831. #endif
  186832. png_error(png_ptr,
  186833. "Incompatible libpng version in application and library");
  186834. }
  186835. }
  186836. /* initialize zbuf - compression buffer */
  186837. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186838. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186839. (png_uint_32)png_ptr->zbuf_size);
  186840. png_ptr->zstream.zalloc = png_zalloc;
  186841. png_ptr->zstream.zfree = png_zfree;
  186842. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186843. switch (inflateInit(&png_ptr->zstream))
  186844. {
  186845. case Z_OK: /* Do nothing */ break;
  186846. case Z_MEM_ERROR:
  186847. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  186848. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  186849. default: png_error(png_ptr, "Unknown zlib error");
  186850. }
  186851. png_ptr->zstream.next_out = png_ptr->zbuf;
  186852. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186853. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186854. #ifdef PNG_SETJMP_SUPPORTED
  186855. /* Applications that neglect to set up their own setjmp() and then encounter
  186856. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  186857. abort instead of returning. */
  186858. #ifdef USE_FAR_KEYWORD
  186859. if (setjmp(jmpbuf))
  186860. PNG_ABORT();
  186861. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  186862. #else
  186863. if (setjmp(png_ptr->jmpbuf))
  186864. PNG_ABORT();
  186865. #endif
  186866. #endif
  186867. return (png_ptr);
  186868. }
  186869. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186870. /* Initialize PNG structure for reading, and allocate any memory needed.
  186871. This interface is deprecated in favour of the png_create_read_struct(),
  186872. and it will disappear as of libpng-1.3.0. */
  186873. #undef png_read_init
  186874. void PNGAPI
  186875. png_read_init(png_structp png_ptr)
  186876. {
  186877. /* We only come here via pre-1.0.7-compiled applications */
  186878. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  186879. }
  186880. void PNGAPI
  186881. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  186882. png_size_t png_struct_size, png_size_t png_info_size)
  186883. {
  186884. /* We only come here via pre-1.0.12-compiled applications */
  186885. if(png_ptr == NULL) return;
  186886. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186887. if(png_sizeof(png_struct) > png_struct_size ||
  186888. png_sizeof(png_info) > png_info_size)
  186889. {
  186890. char msg[80];
  186891. png_ptr->warning_fn=NULL;
  186892. if (user_png_ver)
  186893. {
  186894. png_snprintf(msg, 80,
  186895. "Application was compiled with png.h from libpng-%.20s",
  186896. user_png_ver);
  186897. png_warning(png_ptr, msg);
  186898. }
  186899. png_snprintf(msg, 80,
  186900. "Application is running with png.c from libpng-%.20s",
  186901. png_libpng_ver);
  186902. png_warning(png_ptr, msg);
  186903. }
  186904. #endif
  186905. if(png_sizeof(png_struct) > png_struct_size)
  186906. {
  186907. png_ptr->error_fn=NULL;
  186908. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186909. png_ptr->flags=0;
  186910. #endif
  186911. png_error(png_ptr,
  186912. "The png struct allocated by the application for reading is too small.");
  186913. }
  186914. if(png_sizeof(png_info) > png_info_size)
  186915. {
  186916. png_ptr->error_fn=NULL;
  186917. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186918. png_ptr->flags=0;
  186919. #endif
  186920. png_error(png_ptr,
  186921. "The info struct allocated by application for reading is too small.");
  186922. }
  186923. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  186924. }
  186925. #endif /* PNG_1_0_X || PNG_1_2_X */
  186926. void PNGAPI
  186927. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  186928. png_size_t png_struct_size)
  186929. {
  186930. #ifdef PNG_SETJMP_SUPPORTED
  186931. jmp_buf tmp_jmp; /* to save current jump buffer */
  186932. #endif
  186933. int i=0;
  186934. png_structp png_ptr=*ptr_ptr;
  186935. if(png_ptr == NULL) return;
  186936. do
  186937. {
  186938. if(user_png_ver[i] != png_libpng_ver[i])
  186939. {
  186940. #ifdef PNG_LEGACY_SUPPORTED
  186941. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  186942. #else
  186943. png_ptr->warning_fn=NULL;
  186944. png_warning(png_ptr,
  186945. "Application uses deprecated png_read_init() and should be recompiled.");
  186946. break;
  186947. #endif
  186948. }
  186949. } while (png_libpng_ver[i++]);
  186950. png_debug(1, "in png_read_init_3\n");
  186951. #ifdef PNG_SETJMP_SUPPORTED
  186952. /* save jump buffer and error functions */
  186953. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  186954. #endif
  186955. if(png_sizeof(png_struct) > png_struct_size)
  186956. {
  186957. png_destroy_struct(png_ptr);
  186958. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  186959. png_ptr = *ptr_ptr;
  186960. }
  186961. /* reset all variables to 0 */
  186962. png_memset(png_ptr, 0, png_sizeof (png_struct));
  186963. #ifdef PNG_SETJMP_SUPPORTED
  186964. /* restore jump buffer */
  186965. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  186966. #endif
  186967. /* added at libpng-1.2.6 */
  186968. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186969. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  186970. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  186971. #endif
  186972. /* initialize zbuf - compression buffer */
  186973. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  186974. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  186975. (png_uint_32)png_ptr->zbuf_size);
  186976. png_ptr->zstream.zalloc = png_zalloc;
  186977. png_ptr->zstream.zfree = png_zfree;
  186978. png_ptr->zstream.opaque = (voidpf)png_ptr;
  186979. switch (inflateInit(&png_ptr->zstream))
  186980. {
  186981. case Z_OK: /* Do nothing */ break;
  186982. case Z_MEM_ERROR:
  186983. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  186984. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  186985. default: png_error(png_ptr, "Unknown zlib error");
  186986. }
  186987. png_ptr->zstream.next_out = png_ptr->zbuf;
  186988. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  186989. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  186990. }
  186991. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  186992. /* Read the information before the actual image data. This has been
  186993. * changed in v0.90 to allow reading a file that already has the magic
  186994. * bytes read from the stream. You can tell libpng how many bytes have
  186995. * been read from the beginning of the stream (up to the maximum of 8)
  186996. * via png_set_sig_bytes(), and we will only check the remaining bytes
  186997. * here. The application can then have access to the signature bytes we
  186998. * read if it is determined that this isn't a valid PNG file.
  186999. */
  187000. void PNGAPI
  187001. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187002. {
  187003. if(png_ptr == NULL) return;
  187004. png_debug(1, "in png_read_info\n");
  187005. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187006. if (png_ptr->sig_bytes < 8)
  187007. {
  187008. png_size_t num_checked = png_ptr->sig_bytes,
  187009. num_to_check = 8 - num_checked;
  187010. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187011. png_ptr->sig_bytes = 8;
  187012. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187013. {
  187014. if (num_checked < 4 &&
  187015. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187016. png_error(png_ptr, "Not a PNG file");
  187017. else
  187018. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187019. }
  187020. if (num_checked < 3)
  187021. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187022. }
  187023. for(;;)
  187024. {
  187025. #ifdef PNG_USE_LOCAL_ARRAYS
  187026. PNG_CONST PNG_IHDR;
  187027. PNG_CONST PNG_IDAT;
  187028. PNG_CONST PNG_IEND;
  187029. PNG_CONST PNG_PLTE;
  187030. #if defined(PNG_READ_bKGD_SUPPORTED)
  187031. PNG_CONST PNG_bKGD;
  187032. #endif
  187033. #if defined(PNG_READ_cHRM_SUPPORTED)
  187034. PNG_CONST PNG_cHRM;
  187035. #endif
  187036. #if defined(PNG_READ_gAMA_SUPPORTED)
  187037. PNG_CONST PNG_gAMA;
  187038. #endif
  187039. #if defined(PNG_READ_hIST_SUPPORTED)
  187040. PNG_CONST PNG_hIST;
  187041. #endif
  187042. #if defined(PNG_READ_iCCP_SUPPORTED)
  187043. PNG_CONST PNG_iCCP;
  187044. #endif
  187045. #if defined(PNG_READ_iTXt_SUPPORTED)
  187046. PNG_CONST PNG_iTXt;
  187047. #endif
  187048. #if defined(PNG_READ_oFFs_SUPPORTED)
  187049. PNG_CONST PNG_oFFs;
  187050. #endif
  187051. #if defined(PNG_READ_pCAL_SUPPORTED)
  187052. PNG_CONST PNG_pCAL;
  187053. #endif
  187054. #if defined(PNG_READ_pHYs_SUPPORTED)
  187055. PNG_CONST PNG_pHYs;
  187056. #endif
  187057. #if defined(PNG_READ_sBIT_SUPPORTED)
  187058. PNG_CONST PNG_sBIT;
  187059. #endif
  187060. #if defined(PNG_READ_sCAL_SUPPORTED)
  187061. PNG_CONST PNG_sCAL;
  187062. #endif
  187063. #if defined(PNG_READ_sPLT_SUPPORTED)
  187064. PNG_CONST PNG_sPLT;
  187065. #endif
  187066. #if defined(PNG_READ_sRGB_SUPPORTED)
  187067. PNG_CONST PNG_sRGB;
  187068. #endif
  187069. #if defined(PNG_READ_tEXt_SUPPORTED)
  187070. PNG_CONST PNG_tEXt;
  187071. #endif
  187072. #if defined(PNG_READ_tIME_SUPPORTED)
  187073. PNG_CONST PNG_tIME;
  187074. #endif
  187075. #if defined(PNG_READ_tRNS_SUPPORTED)
  187076. PNG_CONST PNG_tRNS;
  187077. #endif
  187078. #if defined(PNG_READ_zTXt_SUPPORTED)
  187079. PNG_CONST PNG_zTXt;
  187080. #endif
  187081. #endif /* PNG_USE_LOCAL_ARRAYS */
  187082. png_byte chunk_length[4];
  187083. png_uint_32 length;
  187084. png_read_data(png_ptr, chunk_length, 4);
  187085. length = png_get_uint_31(png_ptr,chunk_length);
  187086. png_reset_crc(png_ptr);
  187087. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187088. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187089. length);
  187090. /* This should be a binary subdivision search or a hash for
  187091. * matching the chunk name rather than a linear search.
  187092. */
  187093. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187094. if(png_ptr->mode & PNG_AFTER_IDAT)
  187095. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187096. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187097. png_handle_IHDR(png_ptr, info_ptr, length);
  187098. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187099. png_handle_IEND(png_ptr, info_ptr, length);
  187100. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187101. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187102. {
  187103. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187104. png_ptr->mode |= PNG_HAVE_IDAT;
  187105. png_handle_unknown(png_ptr, info_ptr, length);
  187106. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187107. png_ptr->mode |= PNG_HAVE_PLTE;
  187108. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187109. {
  187110. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187111. png_error(png_ptr, "Missing IHDR before IDAT");
  187112. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187113. !(png_ptr->mode & PNG_HAVE_PLTE))
  187114. png_error(png_ptr, "Missing PLTE before IDAT");
  187115. break;
  187116. }
  187117. }
  187118. #endif
  187119. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187120. png_handle_PLTE(png_ptr, info_ptr, length);
  187121. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187122. {
  187123. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187124. png_error(png_ptr, "Missing IHDR before IDAT");
  187125. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187126. !(png_ptr->mode & PNG_HAVE_PLTE))
  187127. png_error(png_ptr, "Missing PLTE before IDAT");
  187128. png_ptr->idat_size = length;
  187129. png_ptr->mode |= PNG_HAVE_IDAT;
  187130. break;
  187131. }
  187132. #if defined(PNG_READ_bKGD_SUPPORTED)
  187133. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187134. png_handle_bKGD(png_ptr, info_ptr, length);
  187135. #endif
  187136. #if defined(PNG_READ_cHRM_SUPPORTED)
  187137. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187138. png_handle_cHRM(png_ptr, info_ptr, length);
  187139. #endif
  187140. #if defined(PNG_READ_gAMA_SUPPORTED)
  187141. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187142. png_handle_gAMA(png_ptr, info_ptr, length);
  187143. #endif
  187144. #if defined(PNG_READ_hIST_SUPPORTED)
  187145. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187146. png_handle_hIST(png_ptr, info_ptr, length);
  187147. #endif
  187148. #if defined(PNG_READ_oFFs_SUPPORTED)
  187149. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187150. png_handle_oFFs(png_ptr, info_ptr, length);
  187151. #endif
  187152. #if defined(PNG_READ_pCAL_SUPPORTED)
  187153. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187154. png_handle_pCAL(png_ptr, info_ptr, length);
  187155. #endif
  187156. #if defined(PNG_READ_sCAL_SUPPORTED)
  187157. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187158. png_handle_sCAL(png_ptr, info_ptr, length);
  187159. #endif
  187160. #if defined(PNG_READ_pHYs_SUPPORTED)
  187161. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187162. png_handle_pHYs(png_ptr, info_ptr, length);
  187163. #endif
  187164. #if defined(PNG_READ_sBIT_SUPPORTED)
  187165. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187166. png_handle_sBIT(png_ptr, info_ptr, length);
  187167. #endif
  187168. #if defined(PNG_READ_sRGB_SUPPORTED)
  187169. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187170. png_handle_sRGB(png_ptr, info_ptr, length);
  187171. #endif
  187172. #if defined(PNG_READ_iCCP_SUPPORTED)
  187173. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187174. png_handle_iCCP(png_ptr, info_ptr, length);
  187175. #endif
  187176. #if defined(PNG_READ_sPLT_SUPPORTED)
  187177. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187178. png_handle_sPLT(png_ptr, info_ptr, length);
  187179. #endif
  187180. #if defined(PNG_READ_tEXt_SUPPORTED)
  187181. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187182. png_handle_tEXt(png_ptr, info_ptr, length);
  187183. #endif
  187184. #if defined(PNG_READ_tIME_SUPPORTED)
  187185. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187186. png_handle_tIME(png_ptr, info_ptr, length);
  187187. #endif
  187188. #if defined(PNG_READ_tRNS_SUPPORTED)
  187189. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187190. png_handle_tRNS(png_ptr, info_ptr, length);
  187191. #endif
  187192. #if defined(PNG_READ_zTXt_SUPPORTED)
  187193. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187194. png_handle_zTXt(png_ptr, info_ptr, length);
  187195. #endif
  187196. #if defined(PNG_READ_iTXt_SUPPORTED)
  187197. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187198. png_handle_iTXt(png_ptr, info_ptr, length);
  187199. #endif
  187200. else
  187201. png_handle_unknown(png_ptr, info_ptr, length);
  187202. }
  187203. }
  187204. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187205. /* optional call to update the users info_ptr structure */
  187206. void PNGAPI
  187207. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187208. {
  187209. png_debug(1, "in png_read_update_info\n");
  187210. if(png_ptr == NULL) return;
  187211. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187212. png_read_start_row(png_ptr);
  187213. else
  187214. png_warning(png_ptr,
  187215. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187216. png_read_transform_info(png_ptr, info_ptr);
  187217. }
  187218. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187219. /* Initialize palette, background, etc, after transformations
  187220. * are set, but before any reading takes place. This allows
  187221. * the user to obtain a gamma-corrected palette, for example.
  187222. * If the user doesn't call this, we will do it ourselves.
  187223. */
  187224. void PNGAPI
  187225. png_start_read_image(png_structp png_ptr)
  187226. {
  187227. png_debug(1, "in png_start_read_image\n");
  187228. if(png_ptr == NULL) return;
  187229. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187230. png_read_start_row(png_ptr);
  187231. }
  187232. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187233. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187234. void PNGAPI
  187235. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187236. {
  187237. #ifdef PNG_USE_LOCAL_ARRAYS
  187238. PNG_CONST PNG_IDAT;
  187239. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187240. 0xff};
  187241. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187242. #endif
  187243. int ret;
  187244. if(png_ptr == NULL) return;
  187245. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187246. png_ptr->row_number, png_ptr->pass);
  187247. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187248. png_read_start_row(png_ptr);
  187249. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187250. {
  187251. /* check for transforms that have been set but were defined out */
  187252. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187253. if (png_ptr->transformations & PNG_INVERT_MONO)
  187254. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187255. #endif
  187256. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187257. if (png_ptr->transformations & PNG_FILLER)
  187258. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187259. #endif
  187260. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187261. if (png_ptr->transformations & PNG_PACKSWAP)
  187262. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187263. #endif
  187264. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187265. if (png_ptr->transformations & PNG_PACK)
  187266. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187267. #endif
  187268. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187269. if (png_ptr->transformations & PNG_SHIFT)
  187270. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187271. #endif
  187272. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187273. if (png_ptr->transformations & PNG_BGR)
  187274. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187275. #endif
  187276. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187277. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187278. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187279. #endif
  187280. }
  187281. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187282. /* if interlaced and we do not need a new row, combine row and return */
  187283. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187284. {
  187285. switch (png_ptr->pass)
  187286. {
  187287. case 0:
  187288. if (png_ptr->row_number & 0x07)
  187289. {
  187290. if (dsp_row != NULL)
  187291. png_combine_row(png_ptr, dsp_row,
  187292. png_pass_dsp_mask[png_ptr->pass]);
  187293. png_read_finish_row(png_ptr);
  187294. return;
  187295. }
  187296. break;
  187297. case 1:
  187298. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187299. {
  187300. if (dsp_row != NULL)
  187301. png_combine_row(png_ptr, dsp_row,
  187302. png_pass_dsp_mask[png_ptr->pass]);
  187303. png_read_finish_row(png_ptr);
  187304. return;
  187305. }
  187306. break;
  187307. case 2:
  187308. if ((png_ptr->row_number & 0x07) != 4)
  187309. {
  187310. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187311. png_combine_row(png_ptr, dsp_row,
  187312. png_pass_dsp_mask[png_ptr->pass]);
  187313. png_read_finish_row(png_ptr);
  187314. return;
  187315. }
  187316. break;
  187317. case 3:
  187318. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187319. {
  187320. if (dsp_row != NULL)
  187321. png_combine_row(png_ptr, dsp_row,
  187322. png_pass_dsp_mask[png_ptr->pass]);
  187323. png_read_finish_row(png_ptr);
  187324. return;
  187325. }
  187326. break;
  187327. case 4:
  187328. if ((png_ptr->row_number & 3) != 2)
  187329. {
  187330. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187331. png_combine_row(png_ptr, dsp_row,
  187332. png_pass_dsp_mask[png_ptr->pass]);
  187333. png_read_finish_row(png_ptr);
  187334. return;
  187335. }
  187336. break;
  187337. case 5:
  187338. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187339. {
  187340. if (dsp_row != NULL)
  187341. png_combine_row(png_ptr, dsp_row,
  187342. png_pass_dsp_mask[png_ptr->pass]);
  187343. png_read_finish_row(png_ptr);
  187344. return;
  187345. }
  187346. break;
  187347. case 6:
  187348. if (!(png_ptr->row_number & 1))
  187349. {
  187350. png_read_finish_row(png_ptr);
  187351. return;
  187352. }
  187353. break;
  187354. }
  187355. }
  187356. #endif
  187357. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187358. png_error(png_ptr, "Invalid attempt to read row data");
  187359. png_ptr->zstream.next_out = png_ptr->row_buf;
  187360. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187361. do
  187362. {
  187363. if (!(png_ptr->zstream.avail_in))
  187364. {
  187365. while (!png_ptr->idat_size)
  187366. {
  187367. png_byte chunk_length[4];
  187368. png_crc_finish(png_ptr, 0);
  187369. png_read_data(png_ptr, chunk_length, 4);
  187370. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187371. png_reset_crc(png_ptr);
  187372. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187373. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187374. png_error(png_ptr, "Not enough image data");
  187375. }
  187376. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187377. png_ptr->zstream.next_in = png_ptr->zbuf;
  187378. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187379. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187380. png_crc_read(png_ptr, png_ptr->zbuf,
  187381. (png_size_t)png_ptr->zstream.avail_in);
  187382. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187383. }
  187384. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187385. if (ret == Z_STREAM_END)
  187386. {
  187387. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187388. png_ptr->idat_size)
  187389. png_error(png_ptr, "Extra compressed data");
  187390. png_ptr->mode |= PNG_AFTER_IDAT;
  187391. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187392. break;
  187393. }
  187394. if (ret != Z_OK)
  187395. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187396. "Decompression error");
  187397. } while (png_ptr->zstream.avail_out);
  187398. png_ptr->row_info.color_type = png_ptr->color_type;
  187399. png_ptr->row_info.width = png_ptr->iwidth;
  187400. png_ptr->row_info.channels = png_ptr->channels;
  187401. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187402. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187403. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187404. png_ptr->row_info.width);
  187405. if(png_ptr->row_buf[0])
  187406. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187407. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187408. (int)(png_ptr->row_buf[0]));
  187409. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187410. png_ptr->rowbytes + 1);
  187411. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187412. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187413. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187414. {
  187415. /* Intrapixel differencing */
  187416. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187417. }
  187418. #endif
  187419. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187420. png_do_read_transformations(png_ptr);
  187421. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187422. /* blow up interlaced rows to full size */
  187423. if (png_ptr->interlaced &&
  187424. (png_ptr->transformations & PNG_INTERLACE))
  187425. {
  187426. if (png_ptr->pass < 6)
  187427. /* old interface (pre-1.0.9):
  187428. png_do_read_interlace(&(png_ptr->row_info),
  187429. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187430. */
  187431. png_do_read_interlace(png_ptr);
  187432. if (dsp_row != NULL)
  187433. png_combine_row(png_ptr, dsp_row,
  187434. png_pass_dsp_mask[png_ptr->pass]);
  187435. if (row != NULL)
  187436. png_combine_row(png_ptr, row,
  187437. png_pass_mask[png_ptr->pass]);
  187438. }
  187439. else
  187440. #endif
  187441. {
  187442. if (row != NULL)
  187443. png_combine_row(png_ptr, row, 0xff);
  187444. if (dsp_row != NULL)
  187445. png_combine_row(png_ptr, dsp_row, 0xff);
  187446. }
  187447. png_read_finish_row(png_ptr);
  187448. if (png_ptr->read_row_fn != NULL)
  187449. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187450. }
  187451. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187452. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187453. /* Read one or more rows of image data. If the image is interlaced,
  187454. * and png_set_interlace_handling() has been called, the rows need to
  187455. * contain the contents of the rows from the previous pass. If the
  187456. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187457. * called, the rows contents must be initialized to the contents of the
  187458. * screen.
  187459. *
  187460. * "row" holds the actual image, and pixels are placed in it
  187461. * as they arrive. If the image is displayed after each pass, it will
  187462. * appear to "sparkle" in. "display_row" can be used to display a
  187463. * "chunky" progressive image, with finer detail added as it becomes
  187464. * available. If you do not want this "chunky" display, you may pass
  187465. * NULL for display_row. If you do not want the sparkle display, and
  187466. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187467. * If you have called png_handle_alpha(), and the image has either an
  187468. * alpha channel or a transparency chunk, you must provide a buffer for
  187469. * rows. In this case, you do not have to provide a display_row buffer
  187470. * also, but you may. If the image is not interlaced, or if you have
  187471. * not called png_set_interlace_handling(), the display_row buffer will
  187472. * be ignored, so pass NULL to it.
  187473. *
  187474. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187475. */
  187476. void PNGAPI
  187477. png_read_rows(png_structp png_ptr, png_bytepp row,
  187478. png_bytepp display_row, png_uint_32 num_rows)
  187479. {
  187480. png_uint_32 i;
  187481. png_bytepp rp;
  187482. png_bytepp dp;
  187483. png_debug(1, "in png_read_rows\n");
  187484. if(png_ptr == NULL) return;
  187485. rp = row;
  187486. dp = display_row;
  187487. if (rp != NULL && dp != NULL)
  187488. for (i = 0; i < num_rows; i++)
  187489. {
  187490. png_bytep rptr = *rp++;
  187491. png_bytep dptr = *dp++;
  187492. png_read_row(png_ptr, rptr, dptr);
  187493. }
  187494. else if(rp != NULL)
  187495. for (i = 0; i < num_rows; i++)
  187496. {
  187497. png_bytep rptr = *rp;
  187498. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187499. rp++;
  187500. }
  187501. else if(dp != NULL)
  187502. for (i = 0; i < num_rows; i++)
  187503. {
  187504. png_bytep dptr = *dp;
  187505. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187506. dp++;
  187507. }
  187508. }
  187509. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187510. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187511. /* Read the entire image. If the image has an alpha channel or a tRNS
  187512. * chunk, and you have called png_handle_alpha()[*], you will need to
  187513. * initialize the image to the current image that PNG will be overlaying.
  187514. * We set the num_rows again here, in case it was incorrectly set in
  187515. * png_read_start_row() by a call to png_read_update_info() or
  187516. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187517. * prior to either of these functions like it should have been. You can
  187518. * only call this function once. If you desire to have an image for
  187519. * each pass of a interlaced image, use png_read_rows() instead.
  187520. *
  187521. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187522. */
  187523. void PNGAPI
  187524. png_read_image(png_structp png_ptr, png_bytepp image)
  187525. {
  187526. png_uint_32 i,image_height;
  187527. int pass, j;
  187528. png_bytepp rp;
  187529. png_debug(1, "in png_read_image\n");
  187530. if(png_ptr == NULL) return;
  187531. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187532. pass = png_set_interlace_handling(png_ptr);
  187533. #else
  187534. if (png_ptr->interlaced)
  187535. png_error(png_ptr,
  187536. "Cannot read interlaced image -- interlace handler disabled.");
  187537. pass = 1;
  187538. #endif
  187539. image_height=png_ptr->height;
  187540. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187541. for (j = 0; j < pass; j++)
  187542. {
  187543. rp = image;
  187544. for (i = 0; i < image_height; i++)
  187545. {
  187546. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187547. rp++;
  187548. }
  187549. }
  187550. }
  187551. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187552. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187553. /* Read the end of the PNG file. Will not read past the end of the
  187554. * file, will verify the end is accurate, and will read any comments
  187555. * or time information at the end of the file, if info is not NULL.
  187556. */
  187557. void PNGAPI
  187558. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187559. {
  187560. png_byte chunk_length[4];
  187561. png_uint_32 length;
  187562. png_debug(1, "in png_read_end\n");
  187563. if(png_ptr == NULL) return;
  187564. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187565. do
  187566. {
  187567. #ifdef PNG_USE_LOCAL_ARRAYS
  187568. PNG_CONST PNG_IHDR;
  187569. PNG_CONST PNG_IDAT;
  187570. PNG_CONST PNG_IEND;
  187571. PNG_CONST PNG_PLTE;
  187572. #if defined(PNG_READ_bKGD_SUPPORTED)
  187573. PNG_CONST PNG_bKGD;
  187574. #endif
  187575. #if defined(PNG_READ_cHRM_SUPPORTED)
  187576. PNG_CONST PNG_cHRM;
  187577. #endif
  187578. #if defined(PNG_READ_gAMA_SUPPORTED)
  187579. PNG_CONST PNG_gAMA;
  187580. #endif
  187581. #if defined(PNG_READ_hIST_SUPPORTED)
  187582. PNG_CONST PNG_hIST;
  187583. #endif
  187584. #if defined(PNG_READ_iCCP_SUPPORTED)
  187585. PNG_CONST PNG_iCCP;
  187586. #endif
  187587. #if defined(PNG_READ_iTXt_SUPPORTED)
  187588. PNG_CONST PNG_iTXt;
  187589. #endif
  187590. #if defined(PNG_READ_oFFs_SUPPORTED)
  187591. PNG_CONST PNG_oFFs;
  187592. #endif
  187593. #if defined(PNG_READ_pCAL_SUPPORTED)
  187594. PNG_CONST PNG_pCAL;
  187595. #endif
  187596. #if defined(PNG_READ_pHYs_SUPPORTED)
  187597. PNG_CONST PNG_pHYs;
  187598. #endif
  187599. #if defined(PNG_READ_sBIT_SUPPORTED)
  187600. PNG_CONST PNG_sBIT;
  187601. #endif
  187602. #if defined(PNG_READ_sCAL_SUPPORTED)
  187603. PNG_CONST PNG_sCAL;
  187604. #endif
  187605. #if defined(PNG_READ_sPLT_SUPPORTED)
  187606. PNG_CONST PNG_sPLT;
  187607. #endif
  187608. #if defined(PNG_READ_sRGB_SUPPORTED)
  187609. PNG_CONST PNG_sRGB;
  187610. #endif
  187611. #if defined(PNG_READ_tEXt_SUPPORTED)
  187612. PNG_CONST PNG_tEXt;
  187613. #endif
  187614. #if defined(PNG_READ_tIME_SUPPORTED)
  187615. PNG_CONST PNG_tIME;
  187616. #endif
  187617. #if defined(PNG_READ_tRNS_SUPPORTED)
  187618. PNG_CONST PNG_tRNS;
  187619. #endif
  187620. #if defined(PNG_READ_zTXt_SUPPORTED)
  187621. PNG_CONST PNG_zTXt;
  187622. #endif
  187623. #endif /* PNG_USE_LOCAL_ARRAYS */
  187624. png_read_data(png_ptr, chunk_length, 4);
  187625. length = png_get_uint_31(png_ptr,chunk_length);
  187626. png_reset_crc(png_ptr);
  187627. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187628. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187629. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187630. png_handle_IHDR(png_ptr, info_ptr, length);
  187631. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187632. png_handle_IEND(png_ptr, info_ptr, length);
  187633. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187634. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187635. {
  187636. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187637. {
  187638. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187639. png_error(png_ptr, "Too many IDAT's found");
  187640. }
  187641. png_handle_unknown(png_ptr, info_ptr, length);
  187642. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187643. png_ptr->mode |= PNG_HAVE_PLTE;
  187644. }
  187645. #endif
  187646. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187647. {
  187648. /* Zero length IDATs are legal after the last IDAT has been
  187649. * read, but not after other chunks have been read.
  187650. */
  187651. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187652. png_error(png_ptr, "Too many IDAT's found");
  187653. png_crc_finish(png_ptr, length);
  187654. }
  187655. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187656. png_handle_PLTE(png_ptr, info_ptr, length);
  187657. #if defined(PNG_READ_bKGD_SUPPORTED)
  187658. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187659. png_handle_bKGD(png_ptr, info_ptr, length);
  187660. #endif
  187661. #if defined(PNG_READ_cHRM_SUPPORTED)
  187662. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187663. png_handle_cHRM(png_ptr, info_ptr, length);
  187664. #endif
  187665. #if defined(PNG_READ_gAMA_SUPPORTED)
  187666. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187667. png_handle_gAMA(png_ptr, info_ptr, length);
  187668. #endif
  187669. #if defined(PNG_READ_hIST_SUPPORTED)
  187670. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187671. png_handle_hIST(png_ptr, info_ptr, length);
  187672. #endif
  187673. #if defined(PNG_READ_oFFs_SUPPORTED)
  187674. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187675. png_handle_oFFs(png_ptr, info_ptr, length);
  187676. #endif
  187677. #if defined(PNG_READ_pCAL_SUPPORTED)
  187678. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187679. png_handle_pCAL(png_ptr, info_ptr, length);
  187680. #endif
  187681. #if defined(PNG_READ_sCAL_SUPPORTED)
  187682. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187683. png_handle_sCAL(png_ptr, info_ptr, length);
  187684. #endif
  187685. #if defined(PNG_READ_pHYs_SUPPORTED)
  187686. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187687. png_handle_pHYs(png_ptr, info_ptr, length);
  187688. #endif
  187689. #if defined(PNG_READ_sBIT_SUPPORTED)
  187690. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187691. png_handle_sBIT(png_ptr, info_ptr, length);
  187692. #endif
  187693. #if defined(PNG_READ_sRGB_SUPPORTED)
  187694. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187695. png_handle_sRGB(png_ptr, info_ptr, length);
  187696. #endif
  187697. #if defined(PNG_READ_iCCP_SUPPORTED)
  187698. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187699. png_handle_iCCP(png_ptr, info_ptr, length);
  187700. #endif
  187701. #if defined(PNG_READ_sPLT_SUPPORTED)
  187702. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187703. png_handle_sPLT(png_ptr, info_ptr, length);
  187704. #endif
  187705. #if defined(PNG_READ_tEXt_SUPPORTED)
  187706. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187707. png_handle_tEXt(png_ptr, info_ptr, length);
  187708. #endif
  187709. #if defined(PNG_READ_tIME_SUPPORTED)
  187710. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187711. png_handle_tIME(png_ptr, info_ptr, length);
  187712. #endif
  187713. #if defined(PNG_READ_tRNS_SUPPORTED)
  187714. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187715. png_handle_tRNS(png_ptr, info_ptr, length);
  187716. #endif
  187717. #if defined(PNG_READ_zTXt_SUPPORTED)
  187718. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187719. png_handle_zTXt(png_ptr, info_ptr, length);
  187720. #endif
  187721. #if defined(PNG_READ_iTXt_SUPPORTED)
  187722. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187723. png_handle_iTXt(png_ptr, info_ptr, length);
  187724. #endif
  187725. else
  187726. png_handle_unknown(png_ptr, info_ptr, length);
  187727. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  187728. }
  187729. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187730. /* free all memory used by the read */
  187731. void PNGAPI
  187732. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  187733. png_infopp end_info_ptr_ptr)
  187734. {
  187735. png_structp png_ptr = NULL;
  187736. png_infop info_ptr = NULL, end_info_ptr = NULL;
  187737. #ifdef PNG_USER_MEM_SUPPORTED
  187738. png_free_ptr free_fn;
  187739. png_voidp mem_ptr;
  187740. #endif
  187741. png_debug(1, "in png_destroy_read_struct\n");
  187742. if (png_ptr_ptr != NULL)
  187743. png_ptr = *png_ptr_ptr;
  187744. if (info_ptr_ptr != NULL)
  187745. info_ptr = *info_ptr_ptr;
  187746. if (end_info_ptr_ptr != NULL)
  187747. end_info_ptr = *end_info_ptr_ptr;
  187748. #ifdef PNG_USER_MEM_SUPPORTED
  187749. free_fn = png_ptr->free_fn;
  187750. mem_ptr = png_ptr->mem_ptr;
  187751. #endif
  187752. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  187753. if (info_ptr != NULL)
  187754. {
  187755. #if defined(PNG_TEXT_SUPPORTED)
  187756. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  187757. #endif
  187758. #ifdef PNG_USER_MEM_SUPPORTED
  187759. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  187760. (png_voidp)mem_ptr);
  187761. #else
  187762. png_destroy_struct((png_voidp)info_ptr);
  187763. #endif
  187764. *info_ptr_ptr = NULL;
  187765. }
  187766. if (end_info_ptr != NULL)
  187767. {
  187768. #if defined(PNG_READ_TEXT_SUPPORTED)
  187769. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  187770. #endif
  187771. #ifdef PNG_USER_MEM_SUPPORTED
  187772. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  187773. (png_voidp)mem_ptr);
  187774. #else
  187775. png_destroy_struct((png_voidp)end_info_ptr);
  187776. #endif
  187777. *end_info_ptr_ptr = NULL;
  187778. }
  187779. if (png_ptr != NULL)
  187780. {
  187781. #ifdef PNG_USER_MEM_SUPPORTED
  187782. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  187783. (png_voidp)mem_ptr);
  187784. #else
  187785. png_destroy_struct((png_voidp)png_ptr);
  187786. #endif
  187787. *png_ptr_ptr = NULL;
  187788. }
  187789. }
  187790. /* free all memory used by the read (old method) */
  187791. void /* PRIVATE */
  187792. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  187793. {
  187794. #ifdef PNG_SETJMP_SUPPORTED
  187795. jmp_buf tmp_jmp;
  187796. #endif
  187797. png_error_ptr error_fn;
  187798. png_error_ptr warning_fn;
  187799. png_voidp error_ptr;
  187800. #ifdef PNG_USER_MEM_SUPPORTED
  187801. png_free_ptr free_fn;
  187802. #endif
  187803. png_debug(1, "in png_read_destroy\n");
  187804. if (info_ptr != NULL)
  187805. png_info_destroy(png_ptr, info_ptr);
  187806. if (end_info_ptr != NULL)
  187807. png_info_destroy(png_ptr, end_info_ptr);
  187808. png_free(png_ptr, png_ptr->zbuf);
  187809. png_free(png_ptr, png_ptr->big_row_buf);
  187810. png_free(png_ptr, png_ptr->prev_row);
  187811. #if defined(PNG_READ_DITHER_SUPPORTED)
  187812. png_free(png_ptr, png_ptr->palette_lookup);
  187813. png_free(png_ptr, png_ptr->dither_index);
  187814. #endif
  187815. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187816. png_free(png_ptr, png_ptr->gamma_table);
  187817. #endif
  187818. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187819. png_free(png_ptr, png_ptr->gamma_from_1);
  187820. png_free(png_ptr, png_ptr->gamma_to_1);
  187821. #endif
  187822. #ifdef PNG_FREE_ME_SUPPORTED
  187823. if (png_ptr->free_me & PNG_FREE_PLTE)
  187824. png_zfree(png_ptr, png_ptr->palette);
  187825. png_ptr->free_me &= ~PNG_FREE_PLTE;
  187826. #else
  187827. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  187828. png_zfree(png_ptr, png_ptr->palette);
  187829. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  187830. #endif
  187831. #if defined(PNG_tRNS_SUPPORTED) || \
  187832. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187833. #ifdef PNG_FREE_ME_SUPPORTED
  187834. if (png_ptr->free_me & PNG_FREE_TRNS)
  187835. png_free(png_ptr, png_ptr->trans);
  187836. png_ptr->free_me &= ~PNG_FREE_TRNS;
  187837. #else
  187838. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  187839. png_free(png_ptr, png_ptr->trans);
  187840. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  187841. #endif
  187842. #endif
  187843. #if defined(PNG_READ_hIST_SUPPORTED)
  187844. #ifdef PNG_FREE_ME_SUPPORTED
  187845. if (png_ptr->free_me & PNG_FREE_HIST)
  187846. png_free(png_ptr, png_ptr->hist);
  187847. png_ptr->free_me &= ~PNG_FREE_HIST;
  187848. #else
  187849. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  187850. png_free(png_ptr, png_ptr->hist);
  187851. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  187852. #endif
  187853. #endif
  187854. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187855. if (png_ptr->gamma_16_table != NULL)
  187856. {
  187857. int i;
  187858. int istop = (1 << (8 - png_ptr->gamma_shift));
  187859. for (i = 0; i < istop; i++)
  187860. {
  187861. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  187862. }
  187863. png_free(png_ptr, png_ptr->gamma_16_table);
  187864. }
  187865. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187866. if (png_ptr->gamma_16_from_1 != NULL)
  187867. {
  187868. int i;
  187869. int istop = (1 << (8 - png_ptr->gamma_shift));
  187870. for (i = 0; i < istop; i++)
  187871. {
  187872. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  187873. }
  187874. png_free(png_ptr, png_ptr->gamma_16_from_1);
  187875. }
  187876. if (png_ptr->gamma_16_to_1 != NULL)
  187877. {
  187878. int i;
  187879. int istop = (1 << (8 - png_ptr->gamma_shift));
  187880. for (i = 0; i < istop; i++)
  187881. {
  187882. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  187883. }
  187884. png_free(png_ptr, png_ptr->gamma_16_to_1);
  187885. }
  187886. #endif
  187887. #endif
  187888. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  187889. png_free(png_ptr, png_ptr->time_buffer);
  187890. #endif
  187891. inflateEnd(&png_ptr->zstream);
  187892. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187893. png_free(png_ptr, png_ptr->save_buffer);
  187894. #endif
  187895. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  187896. #ifdef PNG_TEXT_SUPPORTED
  187897. png_free(png_ptr, png_ptr->current_text);
  187898. #endif /* PNG_TEXT_SUPPORTED */
  187899. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  187900. /* Save the important info out of the png_struct, in case it is
  187901. * being used again.
  187902. */
  187903. #ifdef PNG_SETJMP_SUPPORTED
  187904. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187905. #endif
  187906. error_fn = png_ptr->error_fn;
  187907. warning_fn = png_ptr->warning_fn;
  187908. error_ptr = png_ptr->error_ptr;
  187909. #ifdef PNG_USER_MEM_SUPPORTED
  187910. free_fn = png_ptr->free_fn;
  187911. #endif
  187912. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187913. png_ptr->error_fn = error_fn;
  187914. png_ptr->warning_fn = warning_fn;
  187915. png_ptr->error_ptr = error_ptr;
  187916. #ifdef PNG_USER_MEM_SUPPORTED
  187917. png_ptr->free_fn = free_fn;
  187918. #endif
  187919. #ifdef PNG_SETJMP_SUPPORTED
  187920. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187921. #endif
  187922. }
  187923. void PNGAPI
  187924. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  187925. {
  187926. if(png_ptr == NULL) return;
  187927. png_ptr->read_row_fn = read_row_fn;
  187928. }
  187929. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187930. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  187931. void PNGAPI
  187932. png_read_png(png_structp png_ptr, png_infop info_ptr,
  187933. int transforms,
  187934. voidp params)
  187935. {
  187936. int row;
  187937. if(png_ptr == NULL) return;
  187938. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187939. /* invert the alpha channel from opacity to transparency
  187940. */
  187941. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  187942. png_set_invert_alpha(png_ptr);
  187943. #endif
  187944. /* png_read_info() gives us all of the information from the
  187945. * PNG file before the first IDAT (image data chunk).
  187946. */
  187947. png_read_info(png_ptr, info_ptr);
  187948. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  187949. png_error(png_ptr,"Image is too high to process with png_read_png()");
  187950. /* -------------- image transformations start here ------------------- */
  187951. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187952. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  187953. */
  187954. if (transforms & PNG_TRANSFORM_STRIP_16)
  187955. png_set_strip_16(png_ptr);
  187956. #endif
  187957. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  187958. /* Strip alpha bytes from the input data without combining with
  187959. * the background (not recommended).
  187960. */
  187961. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  187962. png_set_strip_alpha(png_ptr);
  187963. #endif
  187964. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  187965. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  187966. * byte into separate bytes (useful for paletted and grayscale images).
  187967. */
  187968. if (transforms & PNG_TRANSFORM_PACKING)
  187969. png_set_packing(png_ptr);
  187970. #endif
  187971. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  187972. /* Change the order of packed pixels to least significant bit first
  187973. * (not useful if you are using png_set_packing).
  187974. */
  187975. if (transforms & PNG_TRANSFORM_PACKSWAP)
  187976. png_set_packswap(png_ptr);
  187977. #endif
  187978. #if defined(PNG_READ_EXPAND_SUPPORTED)
  187979. /* Expand paletted colors into true RGB triplets
  187980. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  187981. * Expand paletted or RGB images with transparency to full alpha
  187982. * channels so the data will be available as RGBA quartets.
  187983. */
  187984. if (transforms & PNG_TRANSFORM_EXPAND)
  187985. if ((png_ptr->bit_depth < 8) ||
  187986. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  187987. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  187988. png_set_expand(png_ptr);
  187989. #endif
  187990. /* We don't handle background color or gamma transformation or dithering.
  187991. */
  187992. #if defined(PNG_READ_INVERT_SUPPORTED)
  187993. /* invert monochrome files to have 0 as white and 1 as black
  187994. */
  187995. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  187996. png_set_invert_mono(png_ptr);
  187997. #endif
  187998. #if defined(PNG_READ_SHIFT_SUPPORTED)
  187999. /* If you want to shift the pixel values from the range [0,255] or
  188000. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188001. * colors were originally in:
  188002. */
  188003. if ((transforms & PNG_TRANSFORM_SHIFT)
  188004. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188005. {
  188006. png_color_8p sig_bit;
  188007. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188008. png_set_shift(png_ptr, sig_bit);
  188009. }
  188010. #endif
  188011. #if defined(PNG_READ_BGR_SUPPORTED)
  188012. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188013. */
  188014. if (transforms & PNG_TRANSFORM_BGR)
  188015. png_set_bgr(png_ptr);
  188016. #endif
  188017. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188018. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188019. */
  188020. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188021. png_set_swap_alpha(png_ptr);
  188022. #endif
  188023. #if defined(PNG_READ_SWAP_SUPPORTED)
  188024. /* swap bytes of 16 bit files to least significant byte first
  188025. */
  188026. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188027. png_set_swap(png_ptr);
  188028. #endif
  188029. /* We don't handle adding filler bytes */
  188030. /* Optional call to gamma correct and add the background to the palette
  188031. * and update info structure. REQUIRED if you are expecting libpng to
  188032. * update the palette for you (i.e., you selected such a transform above).
  188033. */
  188034. png_read_update_info(png_ptr, info_ptr);
  188035. /* -------------- image transformations end here ------------------- */
  188036. #ifdef PNG_FREE_ME_SUPPORTED
  188037. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188038. #endif
  188039. if(info_ptr->row_pointers == NULL)
  188040. {
  188041. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188042. info_ptr->height * png_sizeof(png_bytep));
  188043. #ifdef PNG_FREE_ME_SUPPORTED
  188044. info_ptr->free_me |= PNG_FREE_ROWS;
  188045. #endif
  188046. for (row = 0; row < (int)info_ptr->height; row++)
  188047. {
  188048. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188049. png_get_rowbytes(png_ptr, info_ptr));
  188050. }
  188051. }
  188052. png_read_image(png_ptr, info_ptr->row_pointers);
  188053. info_ptr->valid |= PNG_INFO_IDAT;
  188054. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188055. png_read_end(png_ptr, info_ptr);
  188056. transforms = transforms; /* quiet compiler warnings */
  188057. params = params;
  188058. }
  188059. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188060. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188061. #endif /* PNG_READ_SUPPORTED */
  188062. /*** End of inlined file: pngread.c ***/
  188063. /*** Start of inlined file: pngpread.c ***/
  188064. /* pngpread.c - read a png file in push mode
  188065. *
  188066. * Last changed in libpng 1.2.21 October 4, 2007
  188067. * For conditions of distribution and use, see copyright notice in png.h
  188068. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188069. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188070. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188071. */
  188072. #define PNG_INTERNAL
  188073. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188074. /* push model modes */
  188075. #define PNG_READ_SIG_MODE 0
  188076. #define PNG_READ_CHUNK_MODE 1
  188077. #define PNG_READ_IDAT_MODE 2
  188078. #define PNG_SKIP_MODE 3
  188079. #define PNG_READ_tEXt_MODE 4
  188080. #define PNG_READ_zTXt_MODE 5
  188081. #define PNG_READ_DONE_MODE 6
  188082. #define PNG_READ_iTXt_MODE 7
  188083. #define PNG_ERROR_MODE 8
  188084. void PNGAPI
  188085. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188086. png_bytep buffer, png_size_t buffer_size)
  188087. {
  188088. if(png_ptr == NULL) return;
  188089. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188090. while (png_ptr->buffer_size)
  188091. {
  188092. png_process_some_data(png_ptr, info_ptr);
  188093. }
  188094. }
  188095. /* What we do with the incoming data depends on what we were previously
  188096. * doing before we ran out of data...
  188097. */
  188098. void /* PRIVATE */
  188099. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188100. {
  188101. if(png_ptr == NULL) return;
  188102. switch (png_ptr->process_mode)
  188103. {
  188104. case PNG_READ_SIG_MODE:
  188105. {
  188106. png_push_read_sig(png_ptr, info_ptr);
  188107. break;
  188108. }
  188109. case PNG_READ_CHUNK_MODE:
  188110. {
  188111. png_push_read_chunk(png_ptr, info_ptr);
  188112. break;
  188113. }
  188114. case PNG_READ_IDAT_MODE:
  188115. {
  188116. png_push_read_IDAT(png_ptr);
  188117. break;
  188118. }
  188119. #if defined(PNG_READ_tEXt_SUPPORTED)
  188120. case PNG_READ_tEXt_MODE:
  188121. {
  188122. png_push_read_tEXt(png_ptr, info_ptr);
  188123. break;
  188124. }
  188125. #endif
  188126. #if defined(PNG_READ_zTXt_SUPPORTED)
  188127. case PNG_READ_zTXt_MODE:
  188128. {
  188129. png_push_read_zTXt(png_ptr, info_ptr);
  188130. break;
  188131. }
  188132. #endif
  188133. #if defined(PNG_READ_iTXt_SUPPORTED)
  188134. case PNG_READ_iTXt_MODE:
  188135. {
  188136. png_push_read_iTXt(png_ptr, info_ptr);
  188137. break;
  188138. }
  188139. #endif
  188140. case PNG_SKIP_MODE:
  188141. {
  188142. png_push_crc_finish(png_ptr);
  188143. break;
  188144. }
  188145. default:
  188146. {
  188147. png_ptr->buffer_size = 0;
  188148. break;
  188149. }
  188150. }
  188151. }
  188152. /* Read any remaining signature bytes from the stream and compare them with
  188153. * the correct PNG signature. It is possible that this routine is called
  188154. * with bytes already read from the signature, either because they have been
  188155. * checked by the calling application, or because of multiple calls to this
  188156. * routine.
  188157. */
  188158. void /* PRIVATE */
  188159. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188160. {
  188161. png_size_t num_checked = png_ptr->sig_bytes,
  188162. num_to_check = 8 - num_checked;
  188163. if (png_ptr->buffer_size < num_to_check)
  188164. {
  188165. num_to_check = png_ptr->buffer_size;
  188166. }
  188167. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188168. num_to_check);
  188169. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188170. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188171. {
  188172. if (num_checked < 4 &&
  188173. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188174. png_error(png_ptr, "Not a PNG file");
  188175. else
  188176. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188177. }
  188178. else
  188179. {
  188180. if (png_ptr->sig_bytes >= 8)
  188181. {
  188182. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188183. }
  188184. }
  188185. }
  188186. void /* PRIVATE */
  188187. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188188. {
  188189. #ifdef PNG_USE_LOCAL_ARRAYS
  188190. PNG_CONST PNG_IHDR;
  188191. PNG_CONST PNG_IDAT;
  188192. PNG_CONST PNG_IEND;
  188193. PNG_CONST PNG_PLTE;
  188194. #if defined(PNG_READ_bKGD_SUPPORTED)
  188195. PNG_CONST PNG_bKGD;
  188196. #endif
  188197. #if defined(PNG_READ_cHRM_SUPPORTED)
  188198. PNG_CONST PNG_cHRM;
  188199. #endif
  188200. #if defined(PNG_READ_gAMA_SUPPORTED)
  188201. PNG_CONST PNG_gAMA;
  188202. #endif
  188203. #if defined(PNG_READ_hIST_SUPPORTED)
  188204. PNG_CONST PNG_hIST;
  188205. #endif
  188206. #if defined(PNG_READ_iCCP_SUPPORTED)
  188207. PNG_CONST PNG_iCCP;
  188208. #endif
  188209. #if defined(PNG_READ_iTXt_SUPPORTED)
  188210. PNG_CONST PNG_iTXt;
  188211. #endif
  188212. #if defined(PNG_READ_oFFs_SUPPORTED)
  188213. PNG_CONST PNG_oFFs;
  188214. #endif
  188215. #if defined(PNG_READ_pCAL_SUPPORTED)
  188216. PNG_CONST PNG_pCAL;
  188217. #endif
  188218. #if defined(PNG_READ_pHYs_SUPPORTED)
  188219. PNG_CONST PNG_pHYs;
  188220. #endif
  188221. #if defined(PNG_READ_sBIT_SUPPORTED)
  188222. PNG_CONST PNG_sBIT;
  188223. #endif
  188224. #if defined(PNG_READ_sCAL_SUPPORTED)
  188225. PNG_CONST PNG_sCAL;
  188226. #endif
  188227. #if defined(PNG_READ_sRGB_SUPPORTED)
  188228. PNG_CONST PNG_sRGB;
  188229. #endif
  188230. #if defined(PNG_READ_sPLT_SUPPORTED)
  188231. PNG_CONST PNG_sPLT;
  188232. #endif
  188233. #if defined(PNG_READ_tEXt_SUPPORTED)
  188234. PNG_CONST PNG_tEXt;
  188235. #endif
  188236. #if defined(PNG_READ_tIME_SUPPORTED)
  188237. PNG_CONST PNG_tIME;
  188238. #endif
  188239. #if defined(PNG_READ_tRNS_SUPPORTED)
  188240. PNG_CONST PNG_tRNS;
  188241. #endif
  188242. #if defined(PNG_READ_zTXt_SUPPORTED)
  188243. PNG_CONST PNG_zTXt;
  188244. #endif
  188245. #endif /* PNG_USE_LOCAL_ARRAYS */
  188246. /* First we make sure we have enough data for the 4 byte chunk name
  188247. * and the 4 byte chunk length before proceeding with decoding the
  188248. * chunk data. To fully decode each of these chunks, we also make
  188249. * sure we have enough data in the buffer for the 4 byte CRC at the
  188250. * end of every chunk (except IDAT, which is handled separately).
  188251. */
  188252. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188253. {
  188254. png_byte chunk_length[4];
  188255. if (png_ptr->buffer_size < 8)
  188256. {
  188257. png_push_save_buffer(png_ptr);
  188258. return;
  188259. }
  188260. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188261. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188262. png_reset_crc(png_ptr);
  188263. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188264. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188265. }
  188266. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188267. if(png_ptr->mode & PNG_AFTER_IDAT)
  188268. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188269. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188270. {
  188271. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188272. {
  188273. png_push_save_buffer(png_ptr);
  188274. return;
  188275. }
  188276. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188277. }
  188278. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188279. {
  188280. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188281. {
  188282. png_push_save_buffer(png_ptr);
  188283. return;
  188284. }
  188285. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188286. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188287. png_push_have_end(png_ptr, info_ptr);
  188288. }
  188289. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188290. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188291. {
  188292. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188293. {
  188294. png_push_save_buffer(png_ptr);
  188295. return;
  188296. }
  188297. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188298. png_ptr->mode |= PNG_HAVE_IDAT;
  188299. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188300. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188301. png_ptr->mode |= PNG_HAVE_PLTE;
  188302. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188303. {
  188304. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188305. png_error(png_ptr, "Missing IHDR before IDAT");
  188306. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188307. !(png_ptr->mode & PNG_HAVE_PLTE))
  188308. png_error(png_ptr, "Missing PLTE before IDAT");
  188309. }
  188310. }
  188311. #endif
  188312. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188313. {
  188314. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188315. {
  188316. png_push_save_buffer(png_ptr);
  188317. return;
  188318. }
  188319. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188320. }
  188321. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188322. {
  188323. /* If we reach an IDAT chunk, this means we have read all of the
  188324. * header chunks, and we can start reading the image (or if this
  188325. * is called after the image has been read - we have an error).
  188326. */
  188327. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188328. png_error(png_ptr, "Missing IHDR before IDAT");
  188329. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188330. !(png_ptr->mode & PNG_HAVE_PLTE))
  188331. png_error(png_ptr, "Missing PLTE before IDAT");
  188332. if (png_ptr->mode & PNG_HAVE_IDAT)
  188333. {
  188334. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188335. if (png_ptr->push_length == 0)
  188336. return;
  188337. if (png_ptr->mode & PNG_AFTER_IDAT)
  188338. png_error(png_ptr, "Too many IDAT's found");
  188339. }
  188340. png_ptr->idat_size = png_ptr->push_length;
  188341. png_ptr->mode |= PNG_HAVE_IDAT;
  188342. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188343. png_push_have_info(png_ptr, info_ptr);
  188344. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188345. png_ptr->zstream.next_out = png_ptr->row_buf;
  188346. return;
  188347. }
  188348. #if defined(PNG_READ_gAMA_SUPPORTED)
  188349. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188350. {
  188351. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188352. {
  188353. png_push_save_buffer(png_ptr);
  188354. return;
  188355. }
  188356. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188357. }
  188358. #endif
  188359. #if defined(PNG_READ_sBIT_SUPPORTED)
  188360. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188361. {
  188362. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188363. {
  188364. png_push_save_buffer(png_ptr);
  188365. return;
  188366. }
  188367. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188368. }
  188369. #endif
  188370. #if defined(PNG_READ_cHRM_SUPPORTED)
  188371. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188372. {
  188373. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188374. {
  188375. png_push_save_buffer(png_ptr);
  188376. return;
  188377. }
  188378. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188379. }
  188380. #endif
  188381. #if defined(PNG_READ_sRGB_SUPPORTED)
  188382. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188383. {
  188384. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188385. {
  188386. png_push_save_buffer(png_ptr);
  188387. return;
  188388. }
  188389. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188390. }
  188391. #endif
  188392. #if defined(PNG_READ_iCCP_SUPPORTED)
  188393. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188394. {
  188395. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188396. {
  188397. png_push_save_buffer(png_ptr);
  188398. return;
  188399. }
  188400. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188401. }
  188402. #endif
  188403. #if defined(PNG_READ_sPLT_SUPPORTED)
  188404. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188405. {
  188406. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188407. {
  188408. png_push_save_buffer(png_ptr);
  188409. return;
  188410. }
  188411. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188412. }
  188413. #endif
  188414. #if defined(PNG_READ_tRNS_SUPPORTED)
  188415. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188416. {
  188417. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188418. {
  188419. png_push_save_buffer(png_ptr);
  188420. return;
  188421. }
  188422. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188423. }
  188424. #endif
  188425. #if defined(PNG_READ_bKGD_SUPPORTED)
  188426. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188427. {
  188428. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188429. {
  188430. png_push_save_buffer(png_ptr);
  188431. return;
  188432. }
  188433. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188434. }
  188435. #endif
  188436. #if defined(PNG_READ_hIST_SUPPORTED)
  188437. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188438. {
  188439. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188440. {
  188441. png_push_save_buffer(png_ptr);
  188442. return;
  188443. }
  188444. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188445. }
  188446. #endif
  188447. #if defined(PNG_READ_pHYs_SUPPORTED)
  188448. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188449. {
  188450. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188451. {
  188452. png_push_save_buffer(png_ptr);
  188453. return;
  188454. }
  188455. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188456. }
  188457. #endif
  188458. #if defined(PNG_READ_oFFs_SUPPORTED)
  188459. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188460. {
  188461. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188462. {
  188463. png_push_save_buffer(png_ptr);
  188464. return;
  188465. }
  188466. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188467. }
  188468. #endif
  188469. #if defined(PNG_READ_pCAL_SUPPORTED)
  188470. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188471. {
  188472. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188473. {
  188474. png_push_save_buffer(png_ptr);
  188475. return;
  188476. }
  188477. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188478. }
  188479. #endif
  188480. #if defined(PNG_READ_sCAL_SUPPORTED)
  188481. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188482. {
  188483. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188484. {
  188485. png_push_save_buffer(png_ptr);
  188486. return;
  188487. }
  188488. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188489. }
  188490. #endif
  188491. #if defined(PNG_READ_tIME_SUPPORTED)
  188492. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188493. {
  188494. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188495. {
  188496. png_push_save_buffer(png_ptr);
  188497. return;
  188498. }
  188499. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188500. }
  188501. #endif
  188502. #if defined(PNG_READ_tEXt_SUPPORTED)
  188503. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188504. {
  188505. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188506. {
  188507. png_push_save_buffer(png_ptr);
  188508. return;
  188509. }
  188510. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188511. }
  188512. #endif
  188513. #if defined(PNG_READ_zTXt_SUPPORTED)
  188514. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188515. {
  188516. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188517. {
  188518. png_push_save_buffer(png_ptr);
  188519. return;
  188520. }
  188521. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188522. }
  188523. #endif
  188524. #if defined(PNG_READ_iTXt_SUPPORTED)
  188525. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188526. {
  188527. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188528. {
  188529. png_push_save_buffer(png_ptr);
  188530. return;
  188531. }
  188532. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188533. }
  188534. #endif
  188535. else
  188536. {
  188537. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188538. {
  188539. png_push_save_buffer(png_ptr);
  188540. return;
  188541. }
  188542. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188543. }
  188544. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188545. }
  188546. void /* PRIVATE */
  188547. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188548. {
  188549. png_ptr->process_mode = PNG_SKIP_MODE;
  188550. png_ptr->skip_length = skip;
  188551. }
  188552. void /* PRIVATE */
  188553. png_push_crc_finish(png_structp png_ptr)
  188554. {
  188555. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188556. {
  188557. png_size_t save_size;
  188558. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188559. save_size = (png_size_t)png_ptr->skip_length;
  188560. else
  188561. save_size = png_ptr->save_buffer_size;
  188562. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188563. png_ptr->skip_length -= save_size;
  188564. png_ptr->buffer_size -= save_size;
  188565. png_ptr->save_buffer_size -= save_size;
  188566. png_ptr->save_buffer_ptr += save_size;
  188567. }
  188568. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188569. {
  188570. png_size_t save_size;
  188571. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188572. save_size = (png_size_t)png_ptr->skip_length;
  188573. else
  188574. save_size = png_ptr->current_buffer_size;
  188575. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188576. png_ptr->skip_length -= save_size;
  188577. png_ptr->buffer_size -= save_size;
  188578. png_ptr->current_buffer_size -= save_size;
  188579. png_ptr->current_buffer_ptr += save_size;
  188580. }
  188581. if (!png_ptr->skip_length)
  188582. {
  188583. if (png_ptr->buffer_size < 4)
  188584. {
  188585. png_push_save_buffer(png_ptr);
  188586. return;
  188587. }
  188588. png_crc_finish(png_ptr, 0);
  188589. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188590. }
  188591. }
  188592. void PNGAPI
  188593. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188594. {
  188595. png_bytep ptr;
  188596. if(png_ptr == NULL) return;
  188597. ptr = buffer;
  188598. if (png_ptr->save_buffer_size)
  188599. {
  188600. png_size_t save_size;
  188601. if (length < png_ptr->save_buffer_size)
  188602. save_size = length;
  188603. else
  188604. save_size = png_ptr->save_buffer_size;
  188605. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188606. length -= save_size;
  188607. ptr += save_size;
  188608. png_ptr->buffer_size -= save_size;
  188609. png_ptr->save_buffer_size -= save_size;
  188610. png_ptr->save_buffer_ptr += save_size;
  188611. }
  188612. if (length && png_ptr->current_buffer_size)
  188613. {
  188614. png_size_t save_size;
  188615. if (length < png_ptr->current_buffer_size)
  188616. save_size = length;
  188617. else
  188618. save_size = png_ptr->current_buffer_size;
  188619. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188620. png_ptr->buffer_size -= save_size;
  188621. png_ptr->current_buffer_size -= save_size;
  188622. png_ptr->current_buffer_ptr += save_size;
  188623. }
  188624. }
  188625. void /* PRIVATE */
  188626. png_push_save_buffer(png_structp png_ptr)
  188627. {
  188628. if (png_ptr->save_buffer_size)
  188629. {
  188630. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188631. {
  188632. png_size_t i,istop;
  188633. png_bytep sp;
  188634. png_bytep dp;
  188635. istop = png_ptr->save_buffer_size;
  188636. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188637. i < istop; i++, sp++, dp++)
  188638. {
  188639. *dp = *sp;
  188640. }
  188641. }
  188642. }
  188643. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188644. png_ptr->save_buffer_max)
  188645. {
  188646. png_size_t new_max;
  188647. png_bytep old_buffer;
  188648. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188649. (png_ptr->current_buffer_size + 256))
  188650. {
  188651. png_error(png_ptr, "Potential overflow of save_buffer");
  188652. }
  188653. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188654. old_buffer = png_ptr->save_buffer;
  188655. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188656. (png_uint_32)new_max);
  188657. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188658. png_free(png_ptr, old_buffer);
  188659. png_ptr->save_buffer_max = new_max;
  188660. }
  188661. if (png_ptr->current_buffer_size)
  188662. {
  188663. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188664. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188665. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  188666. png_ptr->current_buffer_size = 0;
  188667. }
  188668. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  188669. png_ptr->buffer_size = 0;
  188670. }
  188671. void /* PRIVATE */
  188672. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  188673. png_size_t buffer_length)
  188674. {
  188675. png_ptr->current_buffer = buffer;
  188676. png_ptr->current_buffer_size = buffer_length;
  188677. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  188678. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  188679. }
  188680. void /* PRIVATE */
  188681. png_push_read_IDAT(png_structp png_ptr)
  188682. {
  188683. #ifdef PNG_USE_LOCAL_ARRAYS
  188684. PNG_CONST PNG_IDAT;
  188685. #endif
  188686. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188687. {
  188688. png_byte chunk_length[4];
  188689. if (png_ptr->buffer_size < 8)
  188690. {
  188691. png_push_save_buffer(png_ptr);
  188692. return;
  188693. }
  188694. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188695. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188696. png_reset_crc(png_ptr);
  188697. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188698. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188699. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188700. {
  188701. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188702. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188703. png_error(png_ptr, "Not enough compressed data");
  188704. return;
  188705. }
  188706. png_ptr->idat_size = png_ptr->push_length;
  188707. }
  188708. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  188709. {
  188710. png_size_t save_size;
  188711. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  188712. {
  188713. save_size = (png_size_t)png_ptr->idat_size;
  188714. /* check for overflow */
  188715. if((png_uint_32)save_size != png_ptr->idat_size)
  188716. png_error(png_ptr, "save_size overflowed in pngpread");
  188717. }
  188718. else
  188719. save_size = png_ptr->save_buffer_size;
  188720. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188721. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188722. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188723. png_ptr->idat_size -= save_size;
  188724. png_ptr->buffer_size -= save_size;
  188725. png_ptr->save_buffer_size -= save_size;
  188726. png_ptr->save_buffer_ptr += save_size;
  188727. }
  188728. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  188729. {
  188730. png_size_t save_size;
  188731. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  188732. {
  188733. save_size = (png_size_t)png_ptr->idat_size;
  188734. /* check for overflow */
  188735. if((png_uint_32)save_size != png_ptr->idat_size)
  188736. png_error(png_ptr, "save_size overflowed in pngpread");
  188737. }
  188738. else
  188739. save_size = png_ptr->current_buffer_size;
  188740. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188741. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  188742. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188743. png_ptr->idat_size -= save_size;
  188744. png_ptr->buffer_size -= save_size;
  188745. png_ptr->current_buffer_size -= save_size;
  188746. png_ptr->current_buffer_ptr += save_size;
  188747. }
  188748. if (!png_ptr->idat_size)
  188749. {
  188750. if (png_ptr->buffer_size < 4)
  188751. {
  188752. png_push_save_buffer(png_ptr);
  188753. return;
  188754. }
  188755. png_crc_finish(png_ptr, 0);
  188756. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188757. png_ptr->mode |= PNG_AFTER_IDAT;
  188758. }
  188759. }
  188760. void /* PRIVATE */
  188761. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  188762. png_size_t buffer_length)
  188763. {
  188764. int ret;
  188765. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  188766. png_error(png_ptr, "Extra compression data");
  188767. png_ptr->zstream.next_in = buffer;
  188768. png_ptr->zstream.avail_in = (uInt)buffer_length;
  188769. for(;;)
  188770. {
  188771. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188772. if (ret != Z_OK)
  188773. {
  188774. if (ret == Z_STREAM_END)
  188775. {
  188776. if (png_ptr->zstream.avail_in)
  188777. png_error(png_ptr, "Extra compressed data");
  188778. if (!(png_ptr->zstream.avail_out))
  188779. {
  188780. png_push_process_row(png_ptr);
  188781. }
  188782. png_ptr->mode |= PNG_AFTER_IDAT;
  188783. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188784. break;
  188785. }
  188786. else if (ret == Z_BUF_ERROR)
  188787. break;
  188788. else
  188789. png_error(png_ptr, "Decompression Error");
  188790. }
  188791. if (!(png_ptr->zstream.avail_out))
  188792. {
  188793. if ((
  188794. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188795. png_ptr->interlaced && png_ptr->pass > 6) ||
  188796. (!png_ptr->interlaced &&
  188797. #endif
  188798. png_ptr->row_number == png_ptr->num_rows))
  188799. {
  188800. if (png_ptr->zstream.avail_in)
  188801. {
  188802. png_warning(png_ptr, "Too much data in IDAT chunks");
  188803. }
  188804. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188805. break;
  188806. }
  188807. png_push_process_row(png_ptr);
  188808. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188809. png_ptr->zstream.next_out = png_ptr->row_buf;
  188810. }
  188811. else
  188812. break;
  188813. }
  188814. }
  188815. void /* PRIVATE */
  188816. png_push_process_row(png_structp png_ptr)
  188817. {
  188818. png_ptr->row_info.color_type = png_ptr->color_type;
  188819. png_ptr->row_info.width = png_ptr->iwidth;
  188820. png_ptr->row_info.channels = png_ptr->channels;
  188821. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188822. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188823. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188824. png_ptr->row_info.width);
  188825. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188826. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188827. (int)(png_ptr->row_buf[0]));
  188828. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188829. png_ptr->rowbytes + 1);
  188830. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188831. png_do_read_transformations(png_ptr);
  188832. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188833. /* blow up interlaced rows to full size */
  188834. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188835. {
  188836. if (png_ptr->pass < 6)
  188837. /* old interface (pre-1.0.9):
  188838. png_do_read_interlace(&(png_ptr->row_info),
  188839. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188840. */
  188841. png_do_read_interlace(png_ptr);
  188842. switch (png_ptr->pass)
  188843. {
  188844. case 0:
  188845. {
  188846. int i;
  188847. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  188848. {
  188849. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188850. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  188851. }
  188852. if (png_ptr->pass == 2) /* pass 1 might be empty */
  188853. {
  188854. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188855. {
  188856. png_push_have_row(png_ptr, png_bytep_NULL);
  188857. png_read_push_finish_row(png_ptr);
  188858. }
  188859. }
  188860. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  188861. {
  188862. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188863. {
  188864. png_push_have_row(png_ptr, png_bytep_NULL);
  188865. png_read_push_finish_row(png_ptr);
  188866. }
  188867. }
  188868. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  188869. {
  188870. png_push_have_row(png_ptr, png_bytep_NULL);
  188871. png_read_push_finish_row(png_ptr);
  188872. }
  188873. break;
  188874. }
  188875. case 1:
  188876. {
  188877. int i;
  188878. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  188879. {
  188880. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188881. png_read_push_finish_row(png_ptr);
  188882. }
  188883. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  188884. {
  188885. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188886. {
  188887. png_push_have_row(png_ptr, png_bytep_NULL);
  188888. png_read_push_finish_row(png_ptr);
  188889. }
  188890. }
  188891. break;
  188892. }
  188893. case 2:
  188894. {
  188895. int i;
  188896. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188897. {
  188898. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188899. png_read_push_finish_row(png_ptr);
  188900. }
  188901. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  188902. {
  188903. png_push_have_row(png_ptr, png_bytep_NULL);
  188904. png_read_push_finish_row(png_ptr);
  188905. }
  188906. if (png_ptr->pass == 4) /* pass 3 might be empty */
  188907. {
  188908. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188909. {
  188910. png_push_have_row(png_ptr, png_bytep_NULL);
  188911. png_read_push_finish_row(png_ptr);
  188912. }
  188913. }
  188914. break;
  188915. }
  188916. case 3:
  188917. {
  188918. int i;
  188919. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  188920. {
  188921. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188922. png_read_push_finish_row(png_ptr);
  188923. }
  188924. if (png_ptr->pass == 4) /* skip top two generated rows */
  188925. {
  188926. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188927. {
  188928. png_push_have_row(png_ptr, png_bytep_NULL);
  188929. png_read_push_finish_row(png_ptr);
  188930. }
  188931. }
  188932. break;
  188933. }
  188934. case 4:
  188935. {
  188936. int i;
  188937. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188938. {
  188939. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188940. png_read_push_finish_row(png_ptr);
  188941. }
  188942. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  188943. {
  188944. png_push_have_row(png_ptr, png_bytep_NULL);
  188945. png_read_push_finish_row(png_ptr);
  188946. }
  188947. if (png_ptr->pass == 6) /* pass 5 might be empty */
  188948. {
  188949. png_push_have_row(png_ptr, png_bytep_NULL);
  188950. png_read_push_finish_row(png_ptr);
  188951. }
  188952. break;
  188953. }
  188954. case 5:
  188955. {
  188956. int i;
  188957. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  188958. {
  188959. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188960. png_read_push_finish_row(png_ptr);
  188961. }
  188962. if (png_ptr->pass == 6) /* skip top generated row */
  188963. {
  188964. png_push_have_row(png_ptr, png_bytep_NULL);
  188965. png_read_push_finish_row(png_ptr);
  188966. }
  188967. break;
  188968. }
  188969. case 6:
  188970. {
  188971. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188972. png_read_push_finish_row(png_ptr);
  188973. if (png_ptr->pass != 6)
  188974. break;
  188975. png_push_have_row(png_ptr, png_bytep_NULL);
  188976. png_read_push_finish_row(png_ptr);
  188977. }
  188978. }
  188979. }
  188980. else
  188981. #endif
  188982. {
  188983. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  188984. png_read_push_finish_row(png_ptr);
  188985. }
  188986. }
  188987. void /* PRIVATE */
  188988. png_read_push_finish_row(png_structp png_ptr)
  188989. {
  188990. #ifdef PNG_USE_LOCAL_ARRAYS
  188991. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  188992. /* start of interlace block */
  188993. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  188994. /* offset to next interlace block */
  188995. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  188996. /* start of interlace block in the y direction */
  188997. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  188998. /* offset to next interlace block in the y direction */
  188999. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189000. /* Height of interlace block. This is not currently used - if you need
  189001. * it, uncomment it here and in png.h
  189002. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189003. */
  189004. #endif
  189005. png_ptr->row_number++;
  189006. if (png_ptr->row_number < png_ptr->num_rows)
  189007. return;
  189008. if (png_ptr->interlaced)
  189009. {
  189010. png_ptr->row_number = 0;
  189011. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189012. png_ptr->rowbytes + 1);
  189013. do
  189014. {
  189015. png_ptr->pass++;
  189016. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189017. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189018. (png_ptr->pass == 5 && png_ptr->width < 2))
  189019. png_ptr->pass++;
  189020. if (png_ptr->pass > 7)
  189021. png_ptr->pass--;
  189022. if (png_ptr->pass >= 7)
  189023. break;
  189024. png_ptr->iwidth = (png_ptr->width +
  189025. png_pass_inc[png_ptr->pass] - 1 -
  189026. png_pass_start[png_ptr->pass]) /
  189027. png_pass_inc[png_ptr->pass];
  189028. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189029. png_ptr->iwidth) + 1;
  189030. if (png_ptr->transformations & PNG_INTERLACE)
  189031. break;
  189032. png_ptr->num_rows = (png_ptr->height +
  189033. png_pass_yinc[png_ptr->pass] - 1 -
  189034. png_pass_ystart[png_ptr->pass]) /
  189035. png_pass_yinc[png_ptr->pass];
  189036. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189037. }
  189038. }
  189039. #if defined(PNG_READ_tEXt_SUPPORTED)
  189040. void /* PRIVATE */
  189041. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189042. length)
  189043. {
  189044. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189045. {
  189046. png_error(png_ptr, "Out of place tEXt");
  189047. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189048. }
  189049. #ifdef PNG_MAX_MALLOC_64K
  189050. png_ptr->skip_length = 0; /* This may not be necessary */
  189051. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189052. {
  189053. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189054. png_ptr->skip_length = length - (png_uint_32)65535L;
  189055. length = (png_uint_32)65535L;
  189056. }
  189057. #endif
  189058. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189059. (png_uint_32)(length+1));
  189060. png_ptr->current_text[length] = '\0';
  189061. png_ptr->current_text_ptr = png_ptr->current_text;
  189062. png_ptr->current_text_size = (png_size_t)length;
  189063. png_ptr->current_text_left = (png_size_t)length;
  189064. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189065. }
  189066. void /* PRIVATE */
  189067. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189068. {
  189069. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189070. {
  189071. png_size_t text_size;
  189072. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189073. text_size = png_ptr->buffer_size;
  189074. else
  189075. text_size = png_ptr->current_text_left;
  189076. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189077. png_ptr->current_text_left -= text_size;
  189078. png_ptr->current_text_ptr += text_size;
  189079. }
  189080. if (!(png_ptr->current_text_left))
  189081. {
  189082. png_textp text_ptr;
  189083. png_charp text;
  189084. png_charp key;
  189085. int ret;
  189086. if (png_ptr->buffer_size < 4)
  189087. {
  189088. png_push_save_buffer(png_ptr);
  189089. return;
  189090. }
  189091. png_push_crc_finish(png_ptr);
  189092. #if defined(PNG_MAX_MALLOC_64K)
  189093. if (png_ptr->skip_length)
  189094. return;
  189095. #endif
  189096. key = png_ptr->current_text;
  189097. for (text = key; *text; text++)
  189098. /* empty loop */ ;
  189099. if (text < key + png_ptr->current_text_size)
  189100. text++;
  189101. text_ptr = (png_textp)png_malloc(png_ptr,
  189102. (png_uint_32)png_sizeof(png_text));
  189103. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189104. text_ptr->key = key;
  189105. #ifdef PNG_iTXt_SUPPORTED
  189106. text_ptr->lang = NULL;
  189107. text_ptr->lang_key = NULL;
  189108. #endif
  189109. text_ptr->text = text;
  189110. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189111. png_free(png_ptr, key);
  189112. png_free(png_ptr, text_ptr);
  189113. png_ptr->current_text = NULL;
  189114. if (ret)
  189115. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189116. }
  189117. }
  189118. #endif
  189119. #if defined(PNG_READ_zTXt_SUPPORTED)
  189120. void /* PRIVATE */
  189121. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189122. length)
  189123. {
  189124. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189125. {
  189126. png_error(png_ptr, "Out of place zTXt");
  189127. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189128. }
  189129. #ifdef PNG_MAX_MALLOC_64K
  189130. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189131. * to be able to store the uncompressed data. Actually, the threshold
  189132. * is probably around 32K, but it isn't as definite as 64K is.
  189133. */
  189134. if (length > (png_uint_32)65535L)
  189135. {
  189136. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189137. png_push_crc_skip(png_ptr, length);
  189138. return;
  189139. }
  189140. #endif
  189141. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189142. (png_uint_32)(length+1));
  189143. png_ptr->current_text[length] = '\0';
  189144. png_ptr->current_text_ptr = png_ptr->current_text;
  189145. png_ptr->current_text_size = (png_size_t)length;
  189146. png_ptr->current_text_left = (png_size_t)length;
  189147. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189148. }
  189149. void /* PRIVATE */
  189150. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189151. {
  189152. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189153. {
  189154. png_size_t text_size;
  189155. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189156. text_size = png_ptr->buffer_size;
  189157. else
  189158. text_size = png_ptr->current_text_left;
  189159. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189160. png_ptr->current_text_left -= text_size;
  189161. png_ptr->current_text_ptr += text_size;
  189162. }
  189163. if (!(png_ptr->current_text_left))
  189164. {
  189165. png_textp text_ptr;
  189166. png_charp text;
  189167. png_charp key;
  189168. int ret;
  189169. png_size_t text_size, key_size;
  189170. if (png_ptr->buffer_size < 4)
  189171. {
  189172. png_push_save_buffer(png_ptr);
  189173. return;
  189174. }
  189175. png_push_crc_finish(png_ptr);
  189176. key = png_ptr->current_text;
  189177. for (text = key; *text; text++)
  189178. /* empty loop */ ;
  189179. /* zTXt can't have zero text */
  189180. if (text >= key + png_ptr->current_text_size)
  189181. {
  189182. png_ptr->current_text = NULL;
  189183. png_free(png_ptr, key);
  189184. return;
  189185. }
  189186. text++;
  189187. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189188. {
  189189. png_ptr->current_text = NULL;
  189190. png_free(png_ptr, key);
  189191. return;
  189192. }
  189193. text++;
  189194. png_ptr->zstream.next_in = (png_bytep )text;
  189195. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189196. (text - key));
  189197. png_ptr->zstream.next_out = png_ptr->zbuf;
  189198. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189199. key_size = text - key;
  189200. text_size = 0;
  189201. text = NULL;
  189202. ret = Z_STREAM_END;
  189203. while (png_ptr->zstream.avail_in)
  189204. {
  189205. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189206. if (ret != Z_OK && ret != Z_STREAM_END)
  189207. {
  189208. inflateReset(&png_ptr->zstream);
  189209. png_ptr->zstream.avail_in = 0;
  189210. png_ptr->current_text = NULL;
  189211. png_free(png_ptr, key);
  189212. png_free(png_ptr, text);
  189213. return;
  189214. }
  189215. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189216. {
  189217. if (text == NULL)
  189218. {
  189219. text = (png_charp)png_malloc(png_ptr,
  189220. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189221. + key_size + 1));
  189222. png_memcpy(text + key_size, png_ptr->zbuf,
  189223. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189224. png_memcpy(text, key, key_size);
  189225. text_size = key_size + png_ptr->zbuf_size -
  189226. png_ptr->zstream.avail_out;
  189227. *(text + text_size) = '\0';
  189228. }
  189229. else
  189230. {
  189231. png_charp tmp;
  189232. tmp = text;
  189233. text = (png_charp)png_malloc(png_ptr, text_size +
  189234. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189235. + 1));
  189236. png_memcpy(text, tmp, text_size);
  189237. png_free(png_ptr, tmp);
  189238. png_memcpy(text + text_size, png_ptr->zbuf,
  189239. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189240. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189241. *(text + text_size) = '\0';
  189242. }
  189243. if (ret != Z_STREAM_END)
  189244. {
  189245. png_ptr->zstream.next_out = png_ptr->zbuf;
  189246. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189247. }
  189248. }
  189249. else
  189250. {
  189251. break;
  189252. }
  189253. if (ret == Z_STREAM_END)
  189254. break;
  189255. }
  189256. inflateReset(&png_ptr->zstream);
  189257. png_ptr->zstream.avail_in = 0;
  189258. if (ret != Z_STREAM_END)
  189259. {
  189260. png_ptr->current_text = NULL;
  189261. png_free(png_ptr, key);
  189262. png_free(png_ptr, text);
  189263. return;
  189264. }
  189265. png_ptr->current_text = NULL;
  189266. png_free(png_ptr, key);
  189267. key = text;
  189268. text += key_size;
  189269. text_ptr = (png_textp)png_malloc(png_ptr,
  189270. (png_uint_32)png_sizeof(png_text));
  189271. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189272. text_ptr->key = key;
  189273. #ifdef PNG_iTXt_SUPPORTED
  189274. text_ptr->lang = NULL;
  189275. text_ptr->lang_key = NULL;
  189276. #endif
  189277. text_ptr->text = text;
  189278. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189279. png_free(png_ptr, key);
  189280. png_free(png_ptr, text_ptr);
  189281. if (ret)
  189282. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189283. }
  189284. }
  189285. #endif
  189286. #if defined(PNG_READ_iTXt_SUPPORTED)
  189287. void /* PRIVATE */
  189288. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189289. length)
  189290. {
  189291. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189292. {
  189293. png_error(png_ptr, "Out of place iTXt");
  189294. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189295. }
  189296. #ifdef PNG_MAX_MALLOC_64K
  189297. png_ptr->skip_length = 0; /* This may not be necessary */
  189298. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189299. {
  189300. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189301. png_ptr->skip_length = length - (png_uint_32)65535L;
  189302. length = (png_uint_32)65535L;
  189303. }
  189304. #endif
  189305. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189306. (png_uint_32)(length+1));
  189307. png_ptr->current_text[length] = '\0';
  189308. png_ptr->current_text_ptr = png_ptr->current_text;
  189309. png_ptr->current_text_size = (png_size_t)length;
  189310. png_ptr->current_text_left = (png_size_t)length;
  189311. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189312. }
  189313. void /* PRIVATE */
  189314. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189315. {
  189316. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189317. {
  189318. png_size_t text_size;
  189319. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189320. text_size = png_ptr->buffer_size;
  189321. else
  189322. text_size = png_ptr->current_text_left;
  189323. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189324. png_ptr->current_text_left -= text_size;
  189325. png_ptr->current_text_ptr += text_size;
  189326. }
  189327. if (!(png_ptr->current_text_left))
  189328. {
  189329. png_textp text_ptr;
  189330. png_charp key;
  189331. int comp_flag;
  189332. png_charp lang;
  189333. png_charp lang_key;
  189334. png_charp text;
  189335. int ret;
  189336. if (png_ptr->buffer_size < 4)
  189337. {
  189338. png_push_save_buffer(png_ptr);
  189339. return;
  189340. }
  189341. png_push_crc_finish(png_ptr);
  189342. #if defined(PNG_MAX_MALLOC_64K)
  189343. if (png_ptr->skip_length)
  189344. return;
  189345. #endif
  189346. key = png_ptr->current_text;
  189347. for (lang = key; *lang; lang++)
  189348. /* empty loop */ ;
  189349. if (lang < key + png_ptr->current_text_size - 3)
  189350. lang++;
  189351. comp_flag = *lang++;
  189352. lang++; /* skip comp_type, always zero */
  189353. for (lang_key = lang; *lang_key; lang_key++)
  189354. /* empty loop */ ;
  189355. lang_key++; /* skip NUL separator */
  189356. text=lang_key;
  189357. if (lang_key < key + png_ptr->current_text_size - 1)
  189358. {
  189359. for (; *text; text++)
  189360. /* empty loop */ ;
  189361. }
  189362. if (text < key + png_ptr->current_text_size)
  189363. text++;
  189364. text_ptr = (png_textp)png_malloc(png_ptr,
  189365. (png_uint_32)png_sizeof(png_text));
  189366. text_ptr->compression = comp_flag + 2;
  189367. text_ptr->key = key;
  189368. text_ptr->lang = lang;
  189369. text_ptr->lang_key = lang_key;
  189370. text_ptr->text = text;
  189371. text_ptr->text_length = 0;
  189372. text_ptr->itxt_length = png_strlen(text);
  189373. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189374. png_ptr->current_text = NULL;
  189375. png_free(png_ptr, text_ptr);
  189376. if (ret)
  189377. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189378. }
  189379. }
  189380. #endif
  189381. /* This function is called when we haven't found a handler for this
  189382. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189383. * name or a critical chunk), the chunk is (currently) silently ignored.
  189384. */
  189385. void /* PRIVATE */
  189386. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189387. length)
  189388. {
  189389. png_uint_32 skip=0;
  189390. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189391. if (!(png_ptr->chunk_name[0] & 0x20))
  189392. {
  189393. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189394. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189395. PNG_HANDLE_CHUNK_ALWAYS
  189396. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189397. && png_ptr->read_user_chunk_fn == NULL
  189398. #endif
  189399. )
  189400. #endif
  189401. png_chunk_error(png_ptr, "unknown critical chunk");
  189402. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189403. }
  189404. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189405. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189406. {
  189407. #ifdef PNG_MAX_MALLOC_64K
  189408. if (length > (png_uint_32)65535L)
  189409. {
  189410. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189411. skip = length - (png_uint_32)65535L;
  189412. length = (png_uint_32)65535L;
  189413. }
  189414. #endif
  189415. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189416. (png_charp)png_ptr->chunk_name, 5);
  189417. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189418. png_ptr->unknown_chunk.size = (png_size_t)length;
  189419. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189420. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189421. if(png_ptr->read_user_chunk_fn != NULL)
  189422. {
  189423. /* callback to user unknown chunk handler */
  189424. int ret;
  189425. ret = (*(png_ptr->read_user_chunk_fn))
  189426. (png_ptr, &png_ptr->unknown_chunk);
  189427. if (ret < 0)
  189428. png_chunk_error(png_ptr, "error in user chunk");
  189429. if (ret == 0)
  189430. {
  189431. if (!(png_ptr->chunk_name[0] & 0x20))
  189432. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189433. PNG_HANDLE_CHUNK_ALWAYS)
  189434. png_chunk_error(png_ptr, "unknown critical chunk");
  189435. png_set_unknown_chunks(png_ptr, info_ptr,
  189436. &png_ptr->unknown_chunk, 1);
  189437. }
  189438. }
  189439. #else
  189440. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189441. #endif
  189442. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189443. png_ptr->unknown_chunk.data = NULL;
  189444. }
  189445. else
  189446. #endif
  189447. skip=length;
  189448. png_push_crc_skip(png_ptr, skip);
  189449. }
  189450. void /* PRIVATE */
  189451. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189452. {
  189453. if (png_ptr->info_fn != NULL)
  189454. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189455. }
  189456. void /* PRIVATE */
  189457. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189458. {
  189459. if (png_ptr->end_fn != NULL)
  189460. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189461. }
  189462. void /* PRIVATE */
  189463. png_push_have_row(png_structp png_ptr, png_bytep row)
  189464. {
  189465. if (png_ptr->row_fn != NULL)
  189466. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189467. (int)png_ptr->pass);
  189468. }
  189469. void PNGAPI
  189470. png_progressive_combine_row (png_structp png_ptr,
  189471. png_bytep old_row, png_bytep new_row)
  189472. {
  189473. #ifdef PNG_USE_LOCAL_ARRAYS
  189474. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189475. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189476. #endif
  189477. if(png_ptr == NULL) return;
  189478. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189479. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189480. }
  189481. void PNGAPI
  189482. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189483. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189484. png_progressive_end_ptr end_fn)
  189485. {
  189486. if(png_ptr == NULL) return;
  189487. png_ptr->info_fn = info_fn;
  189488. png_ptr->row_fn = row_fn;
  189489. png_ptr->end_fn = end_fn;
  189490. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189491. }
  189492. png_voidp PNGAPI
  189493. png_get_progressive_ptr(png_structp png_ptr)
  189494. {
  189495. if(png_ptr == NULL) return (NULL);
  189496. return png_ptr->io_ptr;
  189497. }
  189498. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189499. /*** End of inlined file: pngpread.c ***/
  189500. /*** Start of inlined file: pngrio.c ***/
  189501. /* pngrio.c - functions for data input
  189502. *
  189503. * Last changed in libpng 1.2.13 November 13, 2006
  189504. * For conditions of distribution and use, see copyright notice in png.h
  189505. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189506. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189507. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189508. *
  189509. * This file provides a location for all input. Users who need
  189510. * special handling are expected to write a function that has the same
  189511. * arguments as this and performs a similar function, but that possibly
  189512. * has a different input method. Note that you shouldn't change this
  189513. * function, but rather write a replacement function and then make
  189514. * libpng use it at run time with png_set_read_fn(...).
  189515. */
  189516. #define PNG_INTERNAL
  189517. #if defined(PNG_READ_SUPPORTED)
  189518. /* Read the data from whatever input you are using. The default routine
  189519. reads from a file pointer. Note that this routine sometimes gets called
  189520. with very small lengths, so you should implement some kind of simple
  189521. buffering if you are using unbuffered reads. This should never be asked
  189522. to read more then 64K on a 16 bit machine. */
  189523. void /* PRIVATE */
  189524. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189525. {
  189526. png_debug1(4,"reading %d bytes\n", (int)length);
  189527. if (png_ptr->read_data_fn != NULL)
  189528. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189529. else
  189530. png_error(png_ptr, "Call to NULL read function");
  189531. }
  189532. #if !defined(PNG_NO_STDIO)
  189533. /* This is the function that does the actual reading of data. If you are
  189534. not reading from a standard C stream, you should create a replacement
  189535. read_data function and use it at run time with png_set_read_fn(), rather
  189536. than changing the library. */
  189537. #ifndef USE_FAR_KEYWORD
  189538. void PNGAPI
  189539. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189540. {
  189541. png_size_t check;
  189542. if(png_ptr == NULL) return;
  189543. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189544. * instead of an int, which is what fread() actually returns.
  189545. */
  189546. #if defined(_WIN32_WCE)
  189547. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189548. check = 0;
  189549. #else
  189550. check = (png_size_t)fread(data, (png_size_t)1, length,
  189551. (png_FILE_p)png_ptr->io_ptr);
  189552. #endif
  189553. if (check != length)
  189554. png_error(png_ptr, "Read Error");
  189555. }
  189556. #else
  189557. /* this is the model-independent version. Since the standard I/O library
  189558. can't handle far buffers in the medium and small models, we have to copy
  189559. the data.
  189560. */
  189561. #define NEAR_BUF_SIZE 1024
  189562. #define MIN(a,b) (a <= b ? a : b)
  189563. static void PNGAPI
  189564. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189565. {
  189566. int check;
  189567. png_byte *n_data;
  189568. png_FILE_p io_ptr;
  189569. if(png_ptr == NULL) return;
  189570. /* Check if data really is near. If so, use usual code. */
  189571. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189572. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189573. if ((png_bytep)n_data == data)
  189574. {
  189575. #if defined(_WIN32_WCE)
  189576. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189577. check = 0;
  189578. #else
  189579. check = fread(n_data, 1, length, io_ptr);
  189580. #endif
  189581. }
  189582. else
  189583. {
  189584. png_byte buf[NEAR_BUF_SIZE];
  189585. png_size_t read, remaining, err;
  189586. check = 0;
  189587. remaining = length;
  189588. do
  189589. {
  189590. read = MIN(NEAR_BUF_SIZE, remaining);
  189591. #if defined(_WIN32_WCE)
  189592. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189593. err = 0;
  189594. #else
  189595. err = fread(buf, (png_size_t)1, read, io_ptr);
  189596. #endif
  189597. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189598. if(err != read)
  189599. break;
  189600. else
  189601. check += err;
  189602. data += read;
  189603. remaining -= read;
  189604. }
  189605. while (remaining != 0);
  189606. }
  189607. if ((png_uint_32)check != (png_uint_32)length)
  189608. png_error(png_ptr, "read Error");
  189609. }
  189610. #endif
  189611. #endif
  189612. /* This function allows the application to supply a new input function
  189613. for libpng if standard C streams aren't being used.
  189614. This function takes as its arguments:
  189615. png_ptr - pointer to a png input data structure
  189616. io_ptr - pointer to user supplied structure containing info about
  189617. the input functions. May be NULL.
  189618. read_data_fn - pointer to a new input function that takes as its
  189619. arguments a pointer to a png_struct, a pointer to
  189620. a location where input data can be stored, and a 32-bit
  189621. unsigned int that is the number of bytes to be read.
  189622. To exit and output any fatal error messages the new write
  189623. function should call png_error(png_ptr, "Error msg"). */
  189624. void PNGAPI
  189625. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189626. png_rw_ptr read_data_fn)
  189627. {
  189628. if(png_ptr == NULL) return;
  189629. png_ptr->io_ptr = io_ptr;
  189630. #if !defined(PNG_NO_STDIO)
  189631. if (read_data_fn != NULL)
  189632. png_ptr->read_data_fn = read_data_fn;
  189633. else
  189634. png_ptr->read_data_fn = png_default_read_data;
  189635. #else
  189636. png_ptr->read_data_fn = read_data_fn;
  189637. #endif
  189638. /* It is an error to write to a read device */
  189639. if (png_ptr->write_data_fn != NULL)
  189640. {
  189641. png_ptr->write_data_fn = NULL;
  189642. png_warning(png_ptr,
  189643. "It's an error to set both read_data_fn and write_data_fn in the ");
  189644. png_warning(png_ptr,
  189645. "same structure. Resetting write_data_fn to NULL.");
  189646. }
  189647. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189648. png_ptr->output_flush_fn = NULL;
  189649. #endif
  189650. }
  189651. #endif /* PNG_READ_SUPPORTED */
  189652. /*** End of inlined file: pngrio.c ***/
  189653. /*** Start of inlined file: pngrtran.c ***/
  189654. /* pngrtran.c - transforms the data in a row for PNG readers
  189655. *
  189656. * Last changed in libpng 1.2.21 [October 4, 2007]
  189657. * For conditions of distribution and use, see copyright notice in png.h
  189658. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189659. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189660. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189661. *
  189662. * This file contains functions optionally called by an application
  189663. * in order to tell libpng how to handle data when reading a PNG.
  189664. * Transformations that are used in both reading and writing are
  189665. * in pngtrans.c.
  189666. */
  189667. #define PNG_INTERNAL
  189668. #if defined(PNG_READ_SUPPORTED)
  189669. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  189670. void PNGAPI
  189671. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  189672. {
  189673. png_debug(1, "in png_set_crc_action\n");
  189674. /* Tell libpng how we react to CRC errors in critical chunks */
  189675. if(png_ptr == NULL) return;
  189676. switch (crit_action)
  189677. {
  189678. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189679. break;
  189680. case PNG_CRC_WARN_USE: /* warn/use data */
  189681. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189682. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  189683. break;
  189684. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189685. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189686. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  189687. PNG_FLAG_CRC_CRITICAL_IGNORE;
  189688. break;
  189689. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  189690. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  189691. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189692. case PNG_CRC_DEFAULT:
  189693. default:
  189694. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  189695. break;
  189696. }
  189697. switch (ancil_action)
  189698. {
  189699. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  189700. break;
  189701. case PNG_CRC_WARN_USE: /* warn/use data */
  189702. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189703. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  189704. break;
  189705. case PNG_CRC_QUIET_USE: /* quiet/use data */
  189706. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189707. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  189708. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189709. break;
  189710. case PNG_CRC_ERROR_QUIT: /* error/quit */
  189711. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189712. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  189713. break;
  189714. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  189715. case PNG_CRC_DEFAULT:
  189716. default:
  189717. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  189718. break;
  189719. }
  189720. }
  189721. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  189722. defined(PNG_FLOATING_POINT_SUPPORTED)
  189723. /* handle alpha and tRNS via a background color */
  189724. void PNGAPI
  189725. png_set_background(png_structp png_ptr,
  189726. png_color_16p background_color, int background_gamma_code,
  189727. int need_expand, double background_gamma)
  189728. {
  189729. png_debug(1, "in png_set_background\n");
  189730. if(png_ptr == NULL) return;
  189731. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  189732. {
  189733. png_warning(png_ptr, "Application must supply a known background gamma");
  189734. return;
  189735. }
  189736. png_ptr->transformations |= PNG_BACKGROUND;
  189737. png_memcpy(&(png_ptr->background), background_color,
  189738. png_sizeof(png_color_16));
  189739. png_ptr->background_gamma = (float)background_gamma;
  189740. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  189741. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  189742. }
  189743. #endif
  189744. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189745. /* strip 16 bit depth files to 8 bit depth */
  189746. void PNGAPI
  189747. png_set_strip_16(png_structp png_ptr)
  189748. {
  189749. png_debug(1, "in png_set_strip_16\n");
  189750. if(png_ptr == NULL) return;
  189751. png_ptr->transformations |= PNG_16_TO_8;
  189752. }
  189753. #endif
  189754. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189755. void PNGAPI
  189756. png_set_strip_alpha(png_structp png_ptr)
  189757. {
  189758. png_debug(1, "in png_set_strip_alpha\n");
  189759. if(png_ptr == NULL) return;
  189760. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  189761. }
  189762. #endif
  189763. #if defined(PNG_READ_DITHER_SUPPORTED)
  189764. /* Dither file to 8 bit. Supply a palette, the current number
  189765. * of elements in the palette, the maximum number of elements
  189766. * allowed, and a histogram if possible. If the current number
  189767. * of colors is greater then the maximum number, the palette will be
  189768. * modified to fit in the maximum number. "full_dither" indicates
  189769. * whether we need a dithering cube set up for RGB images, or if we
  189770. * simply are reducing the number of colors in a paletted image.
  189771. */
  189772. typedef struct png_dsort_struct
  189773. {
  189774. struct png_dsort_struct FAR * next;
  189775. png_byte left;
  189776. png_byte right;
  189777. } png_dsort;
  189778. typedef png_dsort FAR * png_dsortp;
  189779. typedef png_dsort FAR * FAR * png_dsortpp;
  189780. void PNGAPI
  189781. png_set_dither(png_structp png_ptr, png_colorp palette,
  189782. int num_palette, int maximum_colors, png_uint_16p histogram,
  189783. int full_dither)
  189784. {
  189785. png_debug(1, "in png_set_dither\n");
  189786. if(png_ptr == NULL) return;
  189787. png_ptr->transformations |= PNG_DITHER;
  189788. if (!full_dither)
  189789. {
  189790. int i;
  189791. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  189792. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189793. for (i = 0; i < num_palette; i++)
  189794. png_ptr->dither_index[i] = (png_byte)i;
  189795. }
  189796. if (num_palette > maximum_colors)
  189797. {
  189798. if (histogram != NULL)
  189799. {
  189800. /* This is easy enough, just throw out the least used colors.
  189801. Perhaps not the best solution, but good enough. */
  189802. int i;
  189803. /* initialize an array to sort colors */
  189804. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  189805. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189806. /* initialize the dither_sort array */
  189807. for (i = 0; i < num_palette; i++)
  189808. png_ptr->dither_sort[i] = (png_byte)i;
  189809. /* Find the least used palette entries by starting a
  189810. bubble sort, and running it until we have sorted
  189811. out enough colors. Note that we don't care about
  189812. sorting all the colors, just finding which are
  189813. least used. */
  189814. for (i = num_palette - 1; i >= maximum_colors; i--)
  189815. {
  189816. int done; /* to stop early if the list is pre-sorted */
  189817. int j;
  189818. done = 1;
  189819. for (j = 0; j < i; j++)
  189820. {
  189821. if (histogram[png_ptr->dither_sort[j]]
  189822. < histogram[png_ptr->dither_sort[j + 1]])
  189823. {
  189824. png_byte t;
  189825. t = png_ptr->dither_sort[j];
  189826. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  189827. png_ptr->dither_sort[j + 1] = t;
  189828. done = 0;
  189829. }
  189830. }
  189831. if (done)
  189832. break;
  189833. }
  189834. /* swap the palette around, and set up a table, if necessary */
  189835. if (full_dither)
  189836. {
  189837. int j = num_palette;
  189838. /* put all the useful colors within the max, but don't
  189839. move the others */
  189840. for (i = 0; i < maximum_colors; i++)
  189841. {
  189842. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189843. {
  189844. do
  189845. j--;
  189846. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189847. palette[i] = palette[j];
  189848. }
  189849. }
  189850. }
  189851. else
  189852. {
  189853. int j = num_palette;
  189854. /* move all the used colors inside the max limit, and
  189855. develop a translation table */
  189856. for (i = 0; i < maximum_colors; i++)
  189857. {
  189858. /* only move the colors we need to */
  189859. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  189860. {
  189861. png_color tmp_color;
  189862. do
  189863. j--;
  189864. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  189865. tmp_color = palette[j];
  189866. palette[j] = palette[i];
  189867. palette[i] = tmp_color;
  189868. /* indicate where the color went */
  189869. png_ptr->dither_index[j] = (png_byte)i;
  189870. png_ptr->dither_index[i] = (png_byte)j;
  189871. }
  189872. }
  189873. /* find closest color for those colors we are not using */
  189874. for (i = 0; i < num_palette; i++)
  189875. {
  189876. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  189877. {
  189878. int min_d, k, min_k, d_index;
  189879. /* find the closest color to one we threw out */
  189880. d_index = png_ptr->dither_index[i];
  189881. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  189882. for (k = 1, min_k = 0; k < maximum_colors; k++)
  189883. {
  189884. int d;
  189885. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  189886. if (d < min_d)
  189887. {
  189888. min_d = d;
  189889. min_k = k;
  189890. }
  189891. }
  189892. /* point to closest color */
  189893. png_ptr->dither_index[i] = (png_byte)min_k;
  189894. }
  189895. }
  189896. }
  189897. png_free(png_ptr, png_ptr->dither_sort);
  189898. png_ptr->dither_sort=NULL;
  189899. }
  189900. else
  189901. {
  189902. /* This is much harder to do simply (and quickly). Perhaps
  189903. we need to go through a median cut routine, but those
  189904. don't always behave themselves with only a few colors
  189905. as input. So we will just find the closest two colors,
  189906. and throw out one of them (chosen somewhat randomly).
  189907. [We don't understand this at all, so if someone wants to
  189908. work on improving it, be our guest - AED, GRP]
  189909. */
  189910. int i;
  189911. int max_d;
  189912. int num_new_palette;
  189913. png_dsortp t;
  189914. png_dsortpp hash;
  189915. t=NULL;
  189916. /* initialize palette index arrays */
  189917. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  189918. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189919. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  189920. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  189921. /* initialize the sort array */
  189922. for (i = 0; i < num_palette; i++)
  189923. {
  189924. png_ptr->index_to_palette[i] = (png_byte)i;
  189925. png_ptr->palette_to_index[i] = (png_byte)i;
  189926. }
  189927. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  189928. png_sizeof (png_dsortp)));
  189929. for (i = 0; i < 769; i++)
  189930. hash[i] = NULL;
  189931. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  189932. num_new_palette = num_palette;
  189933. /* initial wild guess at how far apart the farthest pixel
  189934. pair we will be eliminating will be. Larger
  189935. numbers mean more areas will be allocated, Smaller
  189936. numbers run the risk of not saving enough data, and
  189937. having to do this all over again.
  189938. I have not done extensive checking on this number.
  189939. */
  189940. max_d = 96;
  189941. while (num_new_palette > maximum_colors)
  189942. {
  189943. for (i = 0; i < num_new_palette - 1; i++)
  189944. {
  189945. int j;
  189946. for (j = i + 1; j < num_new_palette; j++)
  189947. {
  189948. int d;
  189949. d = PNG_COLOR_DIST(palette[i], palette[j]);
  189950. if (d <= max_d)
  189951. {
  189952. t = (png_dsortp)png_malloc_warn(png_ptr,
  189953. (png_uint_32)(png_sizeof(png_dsort)));
  189954. if (t == NULL)
  189955. break;
  189956. t->next = hash[d];
  189957. t->left = (png_byte)i;
  189958. t->right = (png_byte)j;
  189959. hash[d] = t;
  189960. }
  189961. }
  189962. if (t == NULL)
  189963. break;
  189964. }
  189965. if (t != NULL)
  189966. for (i = 0; i <= max_d; i++)
  189967. {
  189968. if (hash[i] != NULL)
  189969. {
  189970. png_dsortp p;
  189971. for (p = hash[i]; p; p = p->next)
  189972. {
  189973. if ((int)png_ptr->index_to_palette[p->left]
  189974. < num_new_palette &&
  189975. (int)png_ptr->index_to_palette[p->right]
  189976. < num_new_palette)
  189977. {
  189978. int j, next_j;
  189979. if (num_new_palette & 0x01)
  189980. {
  189981. j = p->left;
  189982. next_j = p->right;
  189983. }
  189984. else
  189985. {
  189986. j = p->right;
  189987. next_j = p->left;
  189988. }
  189989. num_new_palette--;
  189990. palette[png_ptr->index_to_palette[j]]
  189991. = palette[num_new_palette];
  189992. if (!full_dither)
  189993. {
  189994. int k;
  189995. for (k = 0; k < num_palette; k++)
  189996. {
  189997. if (png_ptr->dither_index[k] ==
  189998. png_ptr->index_to_palette[j])
  189999. png_ptr->dither_index[k] =
  190000. png_ptr->index_to_palette[next_j];
  190001. if ((int)png_ptr->dither_index[k] ==
  190002. num_new_palette)
  190003. png_ptr->dither_index[k] =
  190004. png_ptr->index_to_palette[j];
  190005. }
  190006. }
  190007. png_ptr->index_to_palette[png_ptr->palette_to_index
  190008. [num_new_palette]] = png_ptr->index_to_palette[j];
  190009. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190010. = png_ptr->palette_to_index[num_new_palette];
  190011. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190012. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190013. }
  190014. if (num_new_palette <= maximum_colors)
  190015. break;
  190016. }
  190017. if (num_new_palette <= maximum_colors)
  190018. break;
  190019. }
  190020. }
  190021. for (i = 0; i < 769; i++)
  190022. {
  190023. if (hash[i] != NULL)
  190024. {
  190025. png_dsortp p = hash[i];
  190026. while (p)
  190027. {
  190028. t = p->next;
  190029. png_free(png_ptr, p);
  190030. p = t;
  190031. }
  190032. }
  190033. hash[i] = 0;
  190034. }
  190035. max_d += 96;
  190036. }
  190037. png_free(png_ptr, hash);
  190038. png_free(png_ptr, png_ptr->palette_to_index);
  190039. png_free(png_ptr, png_ptr->index_to_palette);
  190040. png_ptr->palette_to_index=NULL;
  190041. png_ptr->index_to_palette=NULL;
  190042. }
  190043. num_palette = maximum_colors;
  190044. }
  190045. if (png_ptr->palette == NULL)
  190046. {
  190047. png_ptr->palette = palette;
  190048. }
  190049. png_ptr->num_palette = (png_uint_16)num_palette;
  190050. if (full_dither)
  190051. {
  190052. int i;
  190053. png_bytep distance;
  190054. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190055. PNG_DITHER_BLUE_BITS;
  190056. int num_red = (1 << PNG_DITHER_RED_BITS);
  190057. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190058. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190059. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190060. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190061. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190062. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190063. png_sizeof (png_byte));
  190064. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190065. png_sizeof(png_byte)));
  190066. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190067. for (i = 0; i < num_palette; i++)
  190068. {
  190069. int ir, ig, ib;
  190070. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190071. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190072. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190073. for (ir = 0; ir < num_red; ir++)
  190074. {
  190075. /* int dr = abs(ir - r); */
  190076. int dr = ((ir > r) ? ir - r : r - ir);
  190077. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190078. for (ig = 0; ig < num_green; ig++)
  190079. {
  190080. /* int dg = abs(ig - g); */
  190081. int dg = ((ig > g) ? ig - g : g - ig);
  190082. int dt = dr + dg;
  190083. int dm = ((dr > dg) ? dr : dg);
  190084. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190085. for (ib = 0; ib < num_blue; ib++)
  190086. {
  190087. int d_index = index_g | ib;
  190088. /* int db = abs(ib - b); */
  190089. int db = ((ib > b) ? ib - b : b - ib);
  190090. int dmax = ((dm > db) ? dm : db);
  190091. int d = dmax + dt + db;
  190092. if (d < (int)distance[d_index])
  190093. {
  190094. distance[d_index] = (png_byte)d;
  190095. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190096. }
  190097. }
  190098. }
  190099. }
  190100. }
  190101. png_free(png_ptr, distance);
  190102. }
  190103. }
  190104. #endif
  190105. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190106. /* Transform the image from the file_gamma to the screen_gamma. We
  190107. * only do transformations on images where the file_gamma and screen_gamma
  190108. * are not close reciprocals, otherwise it slows things down slightly, and
  190109. * also needlessly introduces small errors.
  190110. *
  190111. * We will turn off gamma transformation later if no semitransparent entries
  190112. * are present in the tRNS array for palette images. We can't do it here
  190113. * because we don't necessarily have the tRNS chunk yet.
  190114. */
  190115. void PNGAPI
  190116. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190117. {
  190118. png_debug(1, "in png_set_gamma\n");
  190119. if(png_ptr == NULL) return;
  190120. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190121. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190122. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190123. png_ptr->transformations |= PNG_GAMMA;
  190124. png_ptr->gamma = (float)file_gamma;
  190125. png_ptr->screen_gamma = (float)scrn_gamma;
  190126. }
  190127. #endif
  190128. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190129. /* Expand paletted images to RGB, expand grayscale images of
  190130. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190131. * to alpha channels.
  190132. */
  190133. void PNGAPI
  190134. png_set_expand(png_structp png_ptr)
  190135. {
  190136. png_debug(1, "in png_set_expand\n");
  190137. if(png_ptr == NULL) return;
  190138. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190139. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190140. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190141. #endif
  190142. }
  190143. /* GRR 19990627: the following three functions currently are identical
  190144. * to png_set_expand(). However, it is entirely reasonable that someone
  190145. * might wish to expand an indexed image to RGB but *not* expand a single,
  190146. * fully transparent palette entry to a full alpha channel--perhaps instead
  190147. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190148. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190149. * IOW, a future version of the library may make the transformations flag
  190150. * a bit more fine-grained, with separate bits for each of these three
  190151. * functions.
  190152. *
  190153. * More to the point, these functions make it obvious what libpng will be
  190154. * doing, whereas "expand" can (and does) mean any number of things.
  190155. *
  190156. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190157. * to expand only the sample depth but not to expand the tRNS to alpha.
  190158. */
  190159. /* Expand paletted images to RGB. */
  190160. void PNGAPI
  190161. png_set_palette_to_rgb(png_structp png_ptr)
  190162. {
  190163. png_debug(1, "in png_set_palette_to_rgb\n");
  190164. if(png_ptr == NULL) return;
  190165. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190166. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190167. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190168. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190169. #endif
  190170. }
  190171. #if !defined(PNG_1_0_X)
  190172. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190173. void PNGAPI
  190174. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190175. {
  190176. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190177. if(png_ptr == NULL) return;
  190178. png_ptr->transformations |= PNG_EXPAND;
  190179. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190180. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190181. #endif
  190182. }
  190183. #endif
  190184. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190185. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190186. /* Deprecated as of libpng-1.2.9 */
  190187. void PNGAPI
  190188. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190189. {
  190190. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190191. if(png_ptr == NULL) return;
  190192. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190193. }
  190194. #endif
  190195. /* Expand tRNS chunks to alpha channels. */
  190196. void PNGAPI
  190197. png_set_tRNS_to_alpha(png_structp png_ptr)
  190198. {
  190199. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190200. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190201. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190202. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190203. #endif
  190204. }
  190205. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190206. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190207. void PNGAPI
  190208. png_set_gray_to_rgb(png_structp png_ptr)
  190209. {
  190210. png_debug(1, "in png_set_gray_to_rgb\n");
  190211. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190212. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190213. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190214. #endif
  190215. }
  190216. #endif
  190217. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190218. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190219. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190220. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190221. */
  190222. void PNGAPI
  190223. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190224. double green)
  190225. {
  190226. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190227. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190228. if(png_ptr == NULL) return;
  190229. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190230. }
  190231. #endif
  190232. void PNGAPI
  190233. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190234. png_fixed_point red, png_fixed_point green)
  190235. {
  190236. png_debug(1, "in png_set_rgb_to_gray\n");
  190237. if(png_ptr == NULL) return;
  190238. switch(error_action)
  190239. {
  190240. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190241. break;
  190242. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190243. break;
  190244. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190245. }
  190246. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190247. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190248. png_ptr->transformations |= PNG_EXPAND;
  190249. #else
  190250. {
  190251. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190252. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190253. }
  190254. #endif
  190255. {
  190256. png_uint_16 red_int, green_int;
  190257. if(red < 0 || green < 0)
  190258. {
  190259. red_int = 6968; /* .212671 * 32768 + .5 */
  190260. green_int = 23434; /* .715160 * 32768 + .5 */
  190261. }
  190262. else if(red + green < 100000L)
  190263. {
  190264. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190265. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190266. }
  190267. else
  190268. {
  190269. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190270. red_int = 6968;
  190271. green_int = 23434;
  190272. }
  190273. png_ptr->rgb_to_gray_red_coeff = red_int;
  190274. png_ptr->rgb_to_gray_green_coeff = green_int;
  190275. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190276. }
  190277. }
  190278. #endif
  190279. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190280. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190281. defined(PNG_LEGACY_SUPPORTED)
  190282. void PNGAPI
  190283. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190284. read_user_transform_fn)
  190285. {
  190286. png_debug(1, "in png_set_read_user_transform_fn\n");
  190287. if(png_ptr == NULL) return;
  190288. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190289. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190290. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190291. #endif
  190292. #ifdef PNG_LEGACY_SUPPORTED
  190293. if(read_user_transform_fn)
  190294. png_warning(png_ptr,
  190295. "This version of libpng does not support user transforms");
  190296. #endif
  190297. }
  190298. #endif
  190299. /* Initialize everything needed for the read. This includes modifying
  190300. * the palette.
  190301. */
  190302. void /* PRIVATE */
  190303. png_init_read_transformations(png_structp png_ptr)
  190304. {
  190305. png_debug(1, "in png_init_read_transformations\n");
  190306. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190307. if(png_ptr != NULL)
  190308. #endif
  190309. {
  190310. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190311. || defined(PNG_READ_GAMMA_SUPPORTED)
  190312. int color_type = png_ptr->color_type;
  190313. #endif
  190314. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190315. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190316. /* Detect gray background and attempt to enable optimization
  190317. * for gray --> RGB case */
  190318. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190319. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190320. * background color might actually be gray yet not be flagged as such.
  190321. * This is not a problem for the current code, which uses
  190322. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190323. * png_do_gray_to_rgb() transformation.
  190324. */
  190325. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190326. !(color_type & PNG_COLOR_MASK_COLOR))
  190327. {
  190328. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190329. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190330. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190331. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190332. png_ptr->background.red == png_ptr->background.green &&
  190333. png_ptr->background.red == png_ptr->background.blue)
  190334. {
  190335. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190336. png_ptr->background.gray = png_ptr->background.red;
  190337. }
  190338. #endif
  190339. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190340. (png_ptr->transformations & PNG_EXPAND))
  190341. {
  190342. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190343. {
  190344. /* expand background and tRNS chunks */
  190345. switch (png_ptr->bit_depth)
  190346. {
  190347. case 1:
  190348. png_ptr->background.gray *= (png_uint_16)0xff;
  190349. png_ptr->background.red = png_ptr->background.green
  190350. = png_ptr->background.blue = png_ptr->background.gray;
  190351. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190352. {
  190353. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190354. png_ptr->trans_values.red = png_ptr->trans_values.green
  190355. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190356. }
  190357. break;
  190358. case 2:
  190359. png_ptr->background.gray *= (png_uint_16)0x55;
  190360. png_ptr->background.red = png_ptr->background.green
  190361. = png_ptr->background.blue = png_ptr->background.gray;
  190362. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190363. {
  190364. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190365. png_ptr->trans_values.red = png_ptr->trans_values.green
  190366. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190367. }
  190368. break;
  190369. case 4:
  190370. png_ptr->background.gray *= (png_uint_16)0x11;
  190371. png_ptr->background.red = png_ptr->background.green
  190372. = png_ptr->background.blue = png_ptr->background.gray;
  190373. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190374. {
  190375. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190376. png_ptr->trans_values.red = png_ptr->trans_values.green
  190377. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190378. }
  190379. break;
  190380. case 8:
  190381. case 16:
  190382. png_ptr->background.red = png_ptr->background.green
  190383. = png_ptr->background.blue = png_ptr->background.gray;
  190384. break;
  190385. }
  190386. }
  190387. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190388. {
  190389. png_ptr->background.red =
  190390. png_ptr->palette[png_ptr->background.index].red;
  190391. png_ptr->background.green =
  190392. png_ptr->palette[png_ptr->background.index].green;
  190393. png_ptr->background.blue =
  190394. png_ptr->palette[png_ptr->background.index].blue;
  190395. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190396. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190397. {
  190398. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190399. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190400. #endif
  190401. {
  190402. /* invert the alpha channel (in tRNS) unless the pixels are
  190403. going to be expanded, in which case leave it for later */
  190404. int i,istop;
  190405. istop=(int)png_ptr->num_trans;
  190406. for (i=0; i<istop; i++)
  190407. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190408. }
  190409. }
  190410. #endif
  190411. }
  190412. }
  190413. #endif
  190414. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190415. png_ptr->background_1 = png_ptr->background;
  190416. #endif
  190417. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190418. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190419. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190420. < PNG_GAMMA_THRESHOLD))
  190421. {
  190422. int i,k;
  190423. k=0;
  190424. for (i=0; i<png_ptr->num_trans; i++)
  190425. {
  190426. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190427. k=1; /* partial transparency is present */
  190428. }
  190429. if (k == 0)
  190430. png_ptr->transformations &= (~PNG_GAMMA);
  190431. }
  190432. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190433. png_ptr->gamma != 0.0)
  190434. {
  190435. png_build_gamma_table(png_ptr);
  190436. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190437. if (png_ptr->transformations & PNG_BACKGROUND)
  190438. {
  190439. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190440. {
  190441. /* could skip if no transparency and
  190442. */
  190443. png_color back, back_1;
  190444. png_colorp palette = png_ptr->palette;
  190445. int num_palette = png_ptr->num_palette;
  190446. int i;
  190447. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190448. {
  190449. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190450. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190451. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190452. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190453. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190454. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190455. }
  190456. else
  190457. {
  190458. double g, gs;
  190459. switch (png_ptr->background_gamma_type)
  190460. {
  190461. case PNG_BACKGROUND_GAMMA_SCREEN:
  190462. g = (png_ptr->screen_gamma);
  190463. gs = 1.0;
  190464. break;
  190465. case PNG_BACKGROUND_GAMMA_FILE:
  190466. g = 1.0 / (png_ptr->gamma);
  190467. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190468. break;
  190469. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190470. g = 1.0 / (png_ptr->background_gamma);
  190471. gs = 1.0 / (png_ptr->background_gamma *
  190472. png_ptr->screen_gamma);
  190473. break;
  190474. default:
  190475. g = 1.0; /* back_1 */
  190476. gs = 1.0; /* back */
  190477. }
  190478. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190479. {
  190480. back.red = (png_byte)png_ptr->background.red;
  190481. back.green = (png_byte)png_ptr->background.green;
  190482. back.blue = (png_byte)png_ptr->background.blue;
  190483. }
  190484. else
  190485. {
  190486. back.red = (png_byte)(pow(
  190487. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190488. back.green = (png_byte)(pow(
  190489. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190490. back.blue = (png_byte)(pow(
  190491. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190492. }
  190493. back_1.red = (png_byte)(pow(
  190494. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190495. back_1.green = (png_byte)(pow(
  190496. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190497. back_1.blue = (png_byte)(pow(
  190498. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190499. }
  190500. for (i = 0; i < num_palette; i++)
  190501. {
  190502. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190503. {
  190504. if (png_ptr->trans[i] == 0)
  190505. {
  190506. palette[i] = back;
  190507. }
  190508. else /* if (png_ptr->trans[i] != 0xff) */
  190509. {
  190510. png_byte v, w;
  190511. v = png_ptr->gamma_to_1[palette[i].red];
  190512. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190513. palette[i].red = png_ptr->gamma_from_1[w];
  190514. v = png_ptr->gamma_to_1[palette[i].green];
  190515. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190516. palette[i].green = png_ptr->gamma_from_1[w];
  190517. v = png_ptr->gamma_to_1[palette[i].blue];
  190518. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190519. palette[i].blue = png_ptr->gamma_from_1[w];
  190520. }
  190521. }
  190522. else
  190523. {
  190524. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190525. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190526. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190527. }
  190528. }
  190529. }
  190530. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190531. else
  190532. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190533. {
  190534. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190535. double g = 1.0;
  190536. double gs = 1.0;
  190537. switch (png_ptr->background_gamma_type)
  190538. {
  190539. case PNG_BACKGROUND_GAMMA_SCREEN:
  190540. g = (png_ptr->screen_gamma);
  190541. gs = 1.0;
  190542. break;
  190543. case PNG_BACKGROUND_GAMMA_FILE:
  190544. g = 1.0 / (png_ptr->gamma);
  190545. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190546. break;
  190547. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190548. g = 1.0 / (png_ptr->background_gamma);
  190549. gs = 1.0 / (png_ptr->background_gamma *
  190550. png_ptr->screen_gamma);
  190551. break;
  190552. }
  190553. png_ptr->background_1.gray = (png_uint_16)(pow(
  190554. (double)png_ptr->background.gray / m, g) * m + .5);
  190555. png_ptr->background.gray = (png_uint_16)(pow(
  190556. (double)png_ptr->background.gray / m, gs) * m + .5);
  190557. if ((png_ptr->background.red != png_ptr->background.green) ||
  190558. (png_ptr->background.red != png_ptr->background.blue) ||
  190559. (png_ptr->background.red != png_ptr->background.gray))
  190560. {
  190561. /* RGB or RGBA with color background */
  190562. png_ptr->background_1.red = (png_uint_16)(pow(
  190563. (double)png_ptr->background.red / m, g) * m + .5);
  190564. png_ptr->background_1.green = (png_uint_16)(pow(
  190565. (double)png_ptr->background.green / m, g) * m + .5);
  190566. png_ptr->background_1.blue = (png_uint_16)(pow(
  190567. (double)png_ptr->background.blue / m, g) * m + .5);
  190568. png_ptr->background.red = (png_uint_16)(pow(
  190569. (double)png_ptr->background.red / m, gs) * m + .5);
  190570. png_ptr->background.green = (png_uint_16)(pow(
  190571. (double)png_ptr->background.green / m, gs) * m + .5);
  190572. png_ptr->background.blue = (png_uint_16)(pow(
  190573. (double)png_ptr->background.blue / m, gs) * m + .5);
  190574. }
  190575. else
  190576. {
  190577. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190578. png_ptr->background_1.red = png_ptr->background_1.green
  190579. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190580. png_ptr->background.red = png_ptr->background.green
  190581. = png_ptr->background.blue = png_ptr->background.gray;
  190582. }
  190583. }
  190584. }
  190585. else
  190586. /* transformation does not include PNG_BACKGROUND */
  190587. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190588. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190589. {
  190590. png_colorp palette = png_ptr->palette;
  190591. int num_palette = png_ptr->num_palette;
  190592. int i;
  190593. for (i = 0; i < num_palette; i++)
  190594. {
  190595. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190596. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190597. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190598. }
  190599. }
  190600. }
  190601. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190602. else
  190603. #endif
  190604. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190605. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190606. /* No GAMMA transformation */
  190607. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190608. (color_type == PNG_COLOR_TYPE_PALETTE))
  190609. {
  190610. int i;
  190611. int istop = (int)png_ptr->num_trans;
  190612. png_color back;
  190613. png_colorp palette = png_ptr->palette;
  190614. back.red = (png_byte)png_ptr->background.red;
  190615. back.green = (png_byte)png_ptr->background.green;
  190616. back.blue = (png_byte)png_ptr->background.blue;
  190617. for (i = 0; i < istop; i++)
  190618. {
  190619. if (png_ptr->trans[i] == 0)
  190620. {
  190621. palette[i] = back;
  190622. }
  190623. else if (png_ptr->trans[i] != 0xff)
  190624. {
  190625. /* The png_composite() macro is defined in png.h */
  190626. png_composite(palette[i].red, palette[i].red,
  190627. png_ptr->trans[i], back.red);
  190628. png_composite(palette[i].green, palette[i].green,
  190629. png_ptr->trans[i], back.green);
  190630. png_composite(palette[i].blue, palette[i].blue,
  190631. png_ptr->trans[i], back.blue);
  190632. }
  190633. }
  190634. }
  190635. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190636. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190637. if ((png_ptr->transformations & PNG_SHIFT) &&
  190638. (color_type == PNG_COLOR_TYPE_PALETTE))
  190639. {
  190640. png_uint_16 i;
  190641. png_uint_16 istop = png_ptr->num_palette;
  190642. int sr = 8 - png_ptr->sig_bit.red;
  190643. int sg = 8 - png_ptr->sig_bit.green;
  190644. int sb = 8 - png_ptr->sig_bit.blue;
  190645. if (sr < 0 || sr > 8)
  190646. sr = 0;
  190647. if (sg < 0 || sg > 8)
  190648. sg = 0;
  190649. if (sb < 0 || sb > 8)
  190650. sb = 0;
  190651. for (i = 0; i < istop; i++)
  190652. {
  190653. png_ptr->palette[i].red >>= sr;
  190654. png_ptr->palette[i].green >>= sg;
  190655. png_ptr->palette[i].blue >>= sb;
  190656. }
  190657. }
  190658. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190659. }
  190660. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190661. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190662. if(png_ptr)
  190663. return;
  190664. #endif
  190665. }
  190666. /* Modify the info structure to reflect the transformations. The
  190667. * info should be updated so a PNG file could be written with it,
  190668. * assuming the transformations result in valid PNG data.
  190669. */
  190670. void /* PRIVATE */
  190671. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  190672. {
  190673. png_debug(1, "in png_read_transform_info\n");
  190674. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190675. if (png_ptr->transformations & PNG_EXPAND)
  190676. {
  190677. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190678. {
  190679. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  190680. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  190681. else
  190682. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  190683. info_ptr->bit_depth = 8;
  190684. info_ptr->num_trans = 0;
  190685. }
  190686. else
  190687. {
  190688. if (png_ptr->num_trans)
  190689. {
  190690. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  190691. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190692. else
  190693. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190694. }
  190695. if (info_ptr->bit_depth < 8)
  190696. info_ptr->bit_depth = 8;
  190697. info_ptr->num_trans = 0;
  190698. }
  190699. }
  190700. #endif
  190701. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190702. if (png_ptr->transformations & PNG_BACKGROUND)
  190703. {
  190704. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190705. info_ptr->num_trans = 0;
  190706. info_ptr->background = png_ptr->background;
  190707. }
  190708. #endif
  190709. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190710. if (png_ptr->transformations & PNG_GAMMA)
  190711. {
  190712. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190713. info_ptr->gamma = png_ptr->gamma;
  190714. #endif
  190715. #ifdef PNG_FIXED_POINT_SUPPORTED
  190716. info_ptr->int_gamma = png_ptr->int_gamma;
  190717. #endif
  190718. }
  190719. #endif
  190720. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190721. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  190722. info_ptr->bit_depth = 8;
  190723. #endif
  190724. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190725. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  190726. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  190727. #endif
  190728. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190729. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190730. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  190731. #endif
  190732. #if defined(PNG_READ_DITHER_SUPPORTED)
  190733. if (png_ptr->transformations & PNG_DITHER)
  190734. {
  190735. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190736. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  190737. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  190738. {
  190739. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  190740. }
  190741. }
  190742. #endif
  190743. #if defined(PNG_READ_PACK_SUPPORTED)
  190744. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  190745. info_ptr->bit_depth = 8;
  190746. #endif
  190747. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190748. info_ptr->channels = 1;
  190749. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190750. info_ptr->channels = 3;
  190751. else
  190752. info_ptr->channels = 1;
  190753. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190754. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190755. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  190756. #endif
  190757. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190758. info_ptr->channels++;
  190759. #if defined(PNG_READ_FILLER_SUPPORTED)
  190760. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  190761. if ((png_ptr->transformations & PNG_FILLER) &&
  190762. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  190763. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  190764. {
  190765. info_ptr->channels++;
  190766. /* if adding a true alpha channel not just filler */
  190767. #if !defined(PNG_1_0_X)
  190768. if (png_ptr->transformations & PNG_ADD_ALPHA)
  190769. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  190770. #endif
  190771. }
  190772. #endif
  190773. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  190774. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190775. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  190776. {
  190777. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  190778. info_ptr->bit_depth = png_ptr->user_transform_depth;
  190779. if(info_ptr->channels < png_ptr->user_transform_channels)
  190780. info_ptr->channels = png_ptr->user_transform_channels;
  190781. }
  190782. #endif
  190783. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  190784. info_ptr->bit_depth);
  190785. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  190786. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  190787. if(png_ptr)
  190788. return;
  190789. #endif
  190790. }
  190791. /* Transform the row. The order of transformations is significant,
  190792. * and is very touchy. If you add a transformation, take care to
  190793. * decide how it fits in with the other transformations here.
  190794. */
  190795. void /* PRIVATE */
  190796. png_do_read_transformations(png_structp png_ptr)
  190797. {
  190798. png_debug(1, "in png_do_read_transformations\n");
  190799. if (png_ptr->row_buf == NULL)
  190800. {
  190801. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  190802. char msg[50];
  190803. png_snprintf2(msg, 50,
  190804. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  190805. png_ptr->pass);
  190806. png_error(png_ptr, msg);
  190807. #else
  190808. png_error(png_ptr, "NULL row buffer");
  190809. #endif
  190810. }
  190811. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190812. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  190813. /* Application has failed to call either png_read_start_image()
  190814. * or png_read_update_info() after setting transforms that expand
  190815. * pixels. This check added to libpng-1.2.19 */
  190816. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  190817. png_error(png_ptr, "Uninitialized row");
  190818. #else
  190819. png_warning(png_ptr, "Uninitialized row");
  190820. #endif
  190821. #endif
  190822. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190823. if (png_ptr->transformations & PNG_EXPAND)
  190824. {
  190825. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  190826. {
  190827. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190828. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  190829. }
  190830. else
  190831. {
  190832. if (png_ptr->num_trans &&
  190833. (png_ptr->transformations & PNG_EXPAND_tRNS))
  190834. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190835. &(png_ptr->trans_values));
  190836. else
  190837. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190838. NULL);
  190839. }
  190840. }
  190841. #endif
  190842. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190843. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  190844. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190845. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  190846. #endif
  190847. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190848. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  190849. {
  190850. int rgb_error =
  190851. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  190852. if(rgb_error)
  190853. {
  190854. png_ptr->rgb_to_gray_status=1;
  190855. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190856. PNG_RGB_TO_GRAY_WARN)
  190857. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190858. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  190859. PNG_RGB_TO_GRAY_ERR)
  190860. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  190861. }
  190862. }
  190863. #endif
  190864. /*
  190865. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  190866. In most cases, the "simple transparency" should be done prior to doing
  190867. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  190868. pixel is transparent. You would also need to make sure that the
  190869. transparency information is upgraded to RGB.
  190870. To summarize, the current flow is:
  190871. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  190872. with background "in place" if transparent,
  190873. convert to RGB if necessary
  190874. - Gray + alpha -> composite with gray background and remove alpha bytes,
  190875. convert to RGB if necessary
  190876. To support RGB backgrounds for gray images we need:
  190877. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  190878. 3 or 6 bytes and composite with background
  190879. "in place" if transparent (3x compare/pixel
  190880. compared to doing composite with gray bkgrnd)
  190881. - Gray + alpha -> convert to RGB + alpha, composite with background and
  190882. remove alpha bytes (3x float operations/pixel
  190883. compared with composite on gray background)
  190884. Greg's change will do this. The reason it wasn't done before is for
  190885. performance, as this increases the per-pixel operations. If we would check
  190886. in advance if the background was gray or RGB, and position the gray-to-RGB
  190887. transform appropriately, then it would save a lot of work/time.
  190888. */
  190889. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190890. /* if gray -> RGB, do so now only if background is non-gray; else do later
  190891. * for performance reasons */
  190892. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190893. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190894. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190895. #endif
  190896. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190897. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190898. ((png_ptr->num_trans != 0 ) ||
  190899. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  190900. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190901. &(png_ptr->trans_values), &(png_ptr->background)
  190902. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190903. , &(png_ptr->background_1),
  190904. png_ptr->gamma_table, png_ptr->gamma_from_1,
  190905. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  190906. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  190907. png_ptr->gamma_shift
  190908. #endif
  190909. );
  190910. #endif
  190911. #if defined(PNG_READ_GAMMA_SUPPORTED)
  190912. if ((png_ptr->transformations & PNG_GAMMA) &&
  190913. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190914. !((png_ptr->transformations & PNG_BACKGROUND) &&
  190915. ((png_ptr->num_trans != 0) ||
  190916. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  190917. #endif
  190918. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  190919. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190920. png_ptr->gamma_table, png_ptr->gamma_16_table,
  190921. png_ptr->gamma_shift);
  190922. #endif
  190923. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190924. if (png_ptr->transformations & PNG_16_TO_8)
  190925. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190926. #endif
  190927. #if defined(PNG_READ_DITHER_SUPPORTED)
  190928. if (png_ptr->transformations & PNG_DITHER)
  190929. {
  190930. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  190931. png_ptr->palette_lookup, png_ptr->dither_index);
  190932. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  190933. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  190934. }
  190935. #endif
  190936. #if defined(PNG_READ_INVERT_SUPPORTED)
  190937. if (png_ptr->transformations & PNG_INVERT_MONO)
  190938. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190939. #endif
  190940. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190941. if (png_ptr->transformations & PNG_SHIFT)
  190942. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190943. &(png_ptr->shift));
  190944. #endif
  190945. #if defined(PNG_READ_PACK_SUPPORTED)
  190946. if (png_ptr->transformations & PNG_PACK)
  190947. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190948. #endif
  190949. #if defined(PNG_READ_BGR_SUPPORTED)
  190950. if (png_ptr->transformations & PNG_BGR)
  190951. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190952. #endif
  190953. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  190954. if (png_ptr->transformations & PNG_PACKSWAP)
  190955. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190956. #endif
  190957. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190958. /* if gray -> RGB, do so now only if we did not do so above */
  190959. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190960. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  190961. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190962. #endif
  190963. #if defined(PNG_READ_FILLER_SUPPORTED)
  190964. if (png_ptr->transformations & PNG_FILLER)
  190965. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  190966. (png_uint_32)png_ptr->filler, png_ptr->flags);
  190967. #endif
  190968. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190969. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190970. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190971. #endif
  190972. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  190973. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  190974. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190975. #endif
  190976. #if defined(PNG_READ_SWAP_SUPPORTED)
  190977. if (png_ptr->transformations & PNG_SWAP_BYTES)
  190978. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  190979. #endif
  190980. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190981. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  190982. {
  190983. if(png_ptr->read_user_transform_fn != NULL)
  190984. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  190985. (png_ptr, /* png_ptr */
  190986. &(png_ptr->row_info), /* row_info: */
  190987. /* png_uint_32 width; width of row */
  190988. /* png_uint_32 rowbytes; number of bytes in row */
  190989. /* png_byte color_type; color type of pixels */
  190990. /* png_byte bit_depth; bit depth of samples */
  190991. /* png_byte channels; number of channels (1-4) */
  190992. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  190993. png_ptr->row_buf + 1); /* start of pixel data for row */
  190994. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  190995. if(png_ptr->user_transform_depth)
  190996. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  190997. if(png_ptr->user_transform_channels)
  190998. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  190999. #endif
  191000. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191001. png_ptr->row_info.channels);
  191002. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191003. png_ptr->row_info.width);
  191004. }
  191005. #endif
  191006. }
  191007. #if defined(PNG_READ_PACK_SUPPORTED)
  191008. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191009. * without changing the actual values. Thus, if you had a row with
  191010. * a bit depth of 1, you would end up with bytes that only contained
  191011. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191012. * png_do_shift() after this.
  191013. */
  191014. void /* PRIVATE */
  191015. png_do_unpack(png_row_infop row_info, png_bytep row)
  191016. {
  191017. png_debug(1, "in png_do_unpack\n");
  191018. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191019. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191020. #else
  191021. if (row_info->bit_depth < 8)
  191022. #endif
  191023. {
  191024. png_uint_32 i;
  191025. png_uint_32 row_width=row_info->width;
  191026. switch (row_info->bit_depth)
  191027. {
  191028. case 1:
  191029. {
  191030. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191031. png_bytep dp = row + (png_size_t)row_width - 1;
  191032. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191033. for (i = 0; i < row_width; i++)
  191034. {
  191035. *dp = (png_byte)((*sp >> shift) & 0x01);
  191036. if (shift == 7)
  191037. {
  191038. shift = 0;
  191039. sp--;
  191040. }
  191041. else
  191042. shift++;
  191043. dp--;
  191044. }
  191045. break;
  191046. }
  191047. case 2:
  191048. {
  191049. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191050. png_bytep dp = row + (png_size_t)row_width - 1;
  191051. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191052. for (i = 0; i < row_width; i++)
  191053. {
  191054. *dp = (png_byte)((*sp >> shift) & 0x03);
  191055. if (shift == 6)
  191056. {
  191057. shift = 0;
  191058. sp--;
  191059. }
  191060. else
  191061. shift += 2;
  191062. dp--;
  191063. }
  191064. break;
  191065. }
  191066. case 4:
  191067. {
  191068. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191069. png_bytep dp = row + (png_size_t)row_width - 1;
  191070. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191071. for (i = 0; i < row_width; i++)
  191072. {
  191073. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191074. if (shift == 4)
  191075. {
  191076. shift = 0;
  191077. sp--;
  191078. }
  191079. else
  191080. shift = 4;
  191081. dp--;
  191082. }
  191083. break;
  191084. }
  191085. }
  191086. row_info->bit_depth = 8;
  191087. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191088. row_info->rowbytes = row_width * row_info->channels;
  191089. }
  191090. }
  191091. #endif
  191092. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191093. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191094. * pixels back to their significant bits values. Thus, if you have
  191095. * a row of bit depth 8, but only 5 are significant, this will shift
  191096. * the values back to 0 through 31.
  191097. */
  191098. void /* PRIVATE */
  191099. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191100. {
  191101. png_debug(1, "in png_do_unshift\n");
  191102. if (
  191103. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191104. row != NULL && row_info != NULL && sig_bits != NULL &&
  191105. #endif
  191106. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191107. {
  191108. int shift[4];
  191109. int channels = 0;
  191110. int c;
  191111. png_uint_16 value = 0;
  191112. png_uint_32 row_width = row_info->width;
  191113. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191114. {
  191115. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191116. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191117. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191118. }
  191119. else
  191120. {
  191121. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191122. }
  191123. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191124. {
  191125. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191126. }
  191127. for (c = 0; c < channels; c++)
  191128. {
  191129. if (shift[c] <= 0)
  191130. shift[c] = 0;
  191131. else
  191132. value = 1;
  191133. }
  191134. if (!value)
  191135. return;
  191136. switch (row_info->bit_depth)
  191137. {
  191138. case 2:
  191139. {
  191140. png_bytep bp;
  191141. png_uint_32 i;
  191142. png_uint_32 istop = row_info->rowbytes;
  191143. for (bp = row, i = 0; i < istop; i++)
  191144. {
  191145. *bp >>= 1;
  191146. *bp++ &= 0x55;
  191147. }
  191148. break;
  191149. }
  191150. case 4:
  191151. {
  191152. png_bytep bp = row;
  191153. png_uint_32 i;
  191154. png_uint_32 istop = row_info->rowbytes;
  191155. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191156. (png_byte)((int)0xf >> shift[0]));
  191157. for (i = 0; i < istop; i++)
  191158. {
  191159. *bp >>= shift[0];
  191160. *bp++ &= mask;
  191161. }
  191162. break;
  191163. }
  191164. case 8:
  191165. {
  191166. png_bytep bp = row;
  191167. png_uint_32 i;
  191168. png_uint_32 istop = row_width * channels;
  191169. for (i = 0; i < istop; i++)
  191170. {
  191171. *bp++ >>= shift[i%channels];
  191172. }
  191173. break;
  191174. }
  191175. case 16:
  191176. {
  191177. png_bytep bp = row;
  191178. png_uint_32 i;
  191179. png_uint_32 istop = channels * row_width;
  191180. for (i = 0; i < istop; i++)
  191181. {
  191182. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191183. value >>= shift[i%channels];
  191184. *bp++ = (png_byte)(value >> 8);
  191185. *bp++ = (png_byte)(value & 0xff);
  191186. }
  191187. break;
  191188. }
  191189. }
  191190. }
  191191. }
  191192. #endif
  191193. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191194. /* chop rows of bit depth 16 down to 8 */
  191195. void /* PRIVATE */
  191196. png_do_chop(png_row_infop row_info, png_bytep row)
  191197. {
  191198. png_debug(1, "in png_do_chop\n");
  191199. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191200. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191201. #else
  191202. if (row_info->bit_depth == 16)
  191203. #endif
  191204. {
  191205. png_bytep sp = row;
  191206. png_bytep dp = row;
  191207. png_uint_32 i;
  191208. png_uint_32 istop = row_info->width * row_info->channels;
  191209. for (i = 0; i<istop; i++, sp += 2, dp++)
  191210. {
  191211. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191212. /* This does a more accurate scaling of the 16-bit color
  191213. * value, rather than a simple low-byte truncation.
  191214. *
  191215. * What the ideal calculation should be:
  191216. * *dp = (((((png_uint_32)(*sp) << 8) |
  191217. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191218. *
  191219. * GRR: no, I think this is what it really should be:
  191220. * *dp = (((((png_uint_32)(*sp) << 8) |
  191221. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191222. *
  191223. * GRR: here's the exact calculation with shifts:
  191224. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191225. * *dp = (temp - (temp >> 8)) >> 8;
  191226. *
  191227. * Approximate calculation with shift/add instead of multiply/divide:
  191228. * *dp = ((((png_uint_32)(*sp) << 8) |
  191229. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191230. *
  191231. * What we actually do to avoid extra shifting and conversion:
  191232. */
  191233. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191234. #else
  191235. /* Simply discard the low order byte */
  191236. *dp = *sp;
  191237. #endif
  191238. }
  191239. row_info->bit_depth = 8;
  191240. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191241. row_info->rowbytes = row_info->width * row_info->channels;
  191242. }
  191243. }
  191244. #endif
  191245. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191246. void /* PRIVATE */
  191247. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191248. {
  191249. png_debug(1, "in png_do_read_swap_alpha\n");
  191250. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191251. if (row != NULL && row_info != NULL)
  191252. #endif
  191253. {
  191254. png_uint_32 row_width = row_info->width;
  191255. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191256. {
  191257. /* This converts from RGBA to ARGB */
  191258. if (row_info->bit_depth == 8)
  191259. {
  191260. png_bytep sp = row + row_info->rowbytes;
  191261. png_bytep dp = sp;
  191262. png_byte save;
  191263. png_uint_32 i;
  191264. for (i = 0; i < row_width; i++)
  191265. {
  191266. save = *(--sp);
  191267. *(--dp) = *(--sp);
  191268. *(--dp) = *(--sp);
  191269. *(--dp) = *(--sp);
  191270. *(--dp) = save;
  191271. }
  191272. }
  191273. /* This converts from RRGGBBAA to AARRGGBB */
  191274. else
  191275. {
  191276. png_bytep sp = row + row_info->rowbytes;
  191277. png_bytep dp = sp;
  191278. png_byte save[2];
  191279. png_uint_32 i;
  191280. for (i = 0; i < row_width; i++)
  191281. {
  191282. save[0] = *(--sp);
  191283. save[1] = *(--sp);
  191284. *(--dp) = *(--sp);
  191285. *(--dp) = *(--sp);
  191286. *(--dp) = *(--sp);
  191287. *(--dp) = *(--sp);
  191288. *(--dp) = *(--sp);
  191289. *(--dp) = *(--sp);
  191290. *(--dp) = save[0];
  191291. *(--dp) = save[1];
  191292. }
  191293. }
  191294. }
  191295. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191296. {
  191297. /* This converts from GA to AG */
  191298. if (row_info->bit_depth == 8)
  191299. {
  191300. png_bytep sp = row + row_info->rowbytes;
  191301. png_bytep dp = sp;
  191302. png_byte save;
  191303. png_uint_32 i;
  191304. for (i = 0; i < row_width; i++)
  191305. {
  191306. save = *(--sp);
  191307. *(--dp) = *(--sp);
  191308. *(--dp) = save;
  191309. }
  191310. }
  191311. /* This converts from GGAA to AAGG */
  191312. else
  191313. {
  191314. png_bytep sp = row + row_info->rowbytes;
  191315. png_bytep dp = sp;
  191316. png_byte save[2];
  191317. png_uint_32 i;
  191318. for (i = 0; i < row_width; i++)
  191319. {
  191320. save[0] = *(--sp);
  191321. save[1] = *(--sp);
  191322. *(--dp) = *(--sp);
  191323. *(--dp) = *(--sp);
  191324. *(--dp) = save[0];
  191325. *(--dp) = save[1];
  191326. }
  191327. }
  191328. }
  191329. }
  191330. }
  191331. #endif
  191332. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191333. void /* PRIVATE */
  191334. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191335. {
  191336. png_debug(1, "in png_do_read_invert_alpha\n");
  191337. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191338. if (row != NULL && row_info != NULL)
  191339. #endif
  191340. {
  191341. png_uint_32 row_width = row_info->width;
  191342. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191343. {
  191344. /* This inverts the alpha channel in RGBA */
  191345. if (row_info->bit_depth == 8)
  191346. {
  191347. png_bytep sp = row + row_info->rowbytes;
  191348. png_bytep dp = sp;
  191349. png_uint_32 i;
  191350. for (i = 0; i < row_width; i++)
  191351. {
  191352. *(--dp) = (png_byte)(255 - *(--sp));
  191353. /* This does nothing:
  191354. *(--dp) = *(--sp);
  191355. *(--dp) = *(--sp);
  191356. *(--dp) = *(--sp);
  191357. We can replace it with:
  191358. */
  191359. sp-=3;
  191360. dp=sp;
  191361. }
  191362. }
  191363. /* This inverts the alpha channel in RRGGBBAA */
  191364. else
  191365. {
  191366. png_bytep sp = row + row_info->rowbytes;
  191367. png_bytep dp = sp;
  191368. png_uint_32 i;
  191369. for (i = 0; i < row_width; i++)
  191370. {
  191371. *(--dp) = (png_byte)(255 - *(--sp));
  191372. *(--dp) = (png_byte)(255 - *(--sp));
  191373. /* This does nothing:
  191374. *(--dp) = *(--sp);
  191375. *(--dp) = *(--sp);
  191376. *(--dp) = *(--sp);
  191377. *(--dp) = *(--sp);
  191378. *(--dp) = *(--sp);
  191379. *(--dp) = *(--sp);
  191380. We can replace it with:
  191381. */
  191382. sp-=6;
  191383. dp=sp;
  191384. }
  191385. }
  191386. }
  191387. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191388. {
  191389. /* This inverts the alpha channel in GA */
  191390. if (row_info->bit_depth == 8)
  191391. {
  191392. png_bytep sp = row + row_info->rowbytes;
  191393. png_bytep dp = sp;
  191394. png_uint_32 i;
  191395. for (i = 0; i < row_width; i++)
  191396. {
  191397. *(--dp) = (png_byte)(255 - *(--sp));
  191398. *(--dp) = *(--sp);
  191399. }
  191400. }
  191401. /* This inverts the alpha channel in GGAA */
  191402. else
  191403. {
  191404. png_bytep sp = row + row_info->rowbytes;
  191405. png_bytep dp = sp;
  191406. png_uint_32 i;
  191407. for (i = 0; i < row_width; i++)
  191408. {
  191409. *(--dp) = (png_byte)(255 - *(--sp));
  191410. *(--dp) = (png_byte)(255 - *(--sp));
  191411. /*
  191412. *(--dp) = *(--sp);
  191413. *(--dp) = *(--sp);
  191414. */
  191415. sp-=2;
  191416. dp=sp;
  191417. }
  191418. }
  191419. }
  191420. }
  191421. }
  191422. #endif
  191423. #if defined(PNG_READ_FILLER_SUPPORTED)
  191424. /* Add filler channel if we have RGB color */
  191425. void /* PRIVATE */
  191426. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191427. png_uint_32 filler, png_uint_32 flags)
  191428. {
  191429. png_uint_32 i;
  191430. png_uint_32 row_width = row_info->width;
  191431. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191432. png_byte lo_filler = (png_byte)(filler & 0xff);
  191433. png_debug(1, "in png_do_read_filler\n");
  191434. if (
  191435. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191436. row != NULL && row_info != NULL &&
  191437. #endif
  191438. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191439. {
  191440. if(row_info->bit_depth == 8)
  191441. {
  191442. /* This changes the data from G to GX */
  191443. if (flags & PNG_FLAG_FILLER_AFTER)
  191444. {
  191445. png_bytep sp = row + (png_size_t)row_width;
  191446. png_bytep dp = sp + (png_size_t)row_width;
  191447. for (i = 1; i < row_width; i++)
  191448. {
  191449. *(--dp) = lo_filler;
  191450. *(--dp) = *(--sp);
  191451. }
  191452. *(--dp) = lo_filler;
  191453. row_info->channels = 2;
  191454. row_info->pixel_depth = 16;
  191455. row_info->rowbytes = row_width * 2;
  191456. }
  191457. /* This changes the data from G to XG */
  191458. else
  191459. {
  191460. png_bytep sp = row + (png_size_t)row_width;
  191461. png_bytep dp = sp + (png_size_t)row_width;
  191462. for (i = 0; i < row_width; i++)
  191463. {
  191464. *(--dp) = *(--sp);
  191465. *(--dp) = lo_filler;
  191466. }
  191467. row_info->channels = 2;
  191468. row_info->pixel_depth = 16;
  191469. row_info->rowbytes = row_width * 2;
  191470. }
  191471. }
  191472. else if(row_info->bit_depth == 16)
  191473. {
  191474. /* This changes the data from GG to GGXX */
  191475. if (flags & PNG_FLAG_FILLER_AFTER)
  191476. {
  191477. png_bytep sp = row + (png_size_t)row_width * 2;
  191478. png_bytep dp = sp + (png_size_t)row_width * 2;
  191479. for (i = 1; i < row_width; i++)
  191480. {
  191481. *(--dp) = hi_filler;
  191482. *(--dp) = lo_filler;
  191483. *(--dp) = *(--sp);
  191484. *(--dp) = *(--sp);
  191485. }
  191486. *(--dp) = hi_filler;
  191487. *(--dp) = lo_filler;
  191488. row_info->channels = 2;
  191489. row_info->pixel_depth = 32;
  191490. row_info->rowbytes = row_width * 4;
  191491. }
  191492. /* This changes the data from GG to XXGG */
  191493. else
  191494. {
  191495. png_bytep sp = row + (png_size_t)row_width * 2;
  191496. png_bytep dp = sp + (png_size_t)row_width * 2;
  191497. for (i = 0; i < row_width; i++)
  191498. {
  191499. *(--dp) = *(--sp);
  191500. *(--dp) = *(--sp);
  191501. *(--dp) = hi_filler;
  191502. *(--dp) = lo_filler;
  191503. }
  191504. row_info->channels = 2;
  191505. row_info->pixel_depth = 32;
  191506. row_info->rowbytes = row_width * 4;
  191507. }
  191508. }
  191509. } /* COLOR_TYPE == GRAY */
  191510. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191511. {
  191512. if(row_info->bit_depth == 8)
  191513. {
  191514. /* This changes the data from RGB to RGBX */
  191515. if (flags & PNG_FLAG_FILLER_AFTER)
  191516. {
  191517. png_bytep sp = row + (png_size_t)row_width * 3;
  191518. png_bytep dp = sp + (png_size_t)row_width;
  191519. for (i = 1; i < row_width; i++)
  191520. {
  191521. *(--dp) = lo_filler;
  191522. *(--dp) = *(--sp);
  191523. *(--dp) = *(--sp);
  191524. *(--dp) = *(--sp);
  191525. }
  191526. *(--dp) = lo_filler;
  191527. row_info->channels = 4;
  191528. row_info->pixel_depth = 32;
  191529. row_info->rowbytes = row_width * 4;
  191530. }
  191531. /* This changes the data from RGB to XRGB */
  191532. else
  191533. {
  191534. png_bytep sp = row + (png_size_t)row_width * 3;
  191535. png_bytep dp = sp + (png_size_t)row_width;
  191536. for (i = 0; i < row_width; i++)
  191537. {
  191538. *(--dp) = *(--sp);
  191539. *(--dp) = *(--sp);
  191540. *(--dp) = *(--sp);
  191541. *(--dp) = lo_filler;
  191542. }
  191543. row_info->channels = 4;
  191544. row_info->pixel_depth = 32;
  191545. row_info->rowbytes = row_width * 4;
  191546. }
  191547. }
  191548. else if(row_info->bit_depth == 16)
  191549. {
  191550. /* This changes the data from RRGGBB to RRGGBBXX */
  191551. if (flags & PNG_FLAG_FILLER_AFTER)
  191552. {
  191553. png_bytep sp = row + (png_size_t)row_width * 6;
  191554. png_bytep dp = sp + (png_size_t)row_width * 2;
  191555. for (i = 1; i < row_width; i++)
  191556. {
  191557. *(--dp) = hi_filler;
  191558. *(--dp) = lo_filler;
  191559. *(--dp) = *(--sp);
  191560. *(--dp) = *(--sp);
  191561. *(--dp) = *(--sp);
  191562. *(--dp) = *(--sp);
  191563. *(--dp) = *(--sp);
  191564. *(--dp) = *(--sp);
  191565. }
  191566. *(--dp) = hi_filler;
  191567. *(--dp) = lo_filler;
  191568. row_info->channels = 4;
  191569. row_info->pixel_depth = 64;
  191570. row_info->rowbytes = row_width * 8;
  191571. }
  191572. /* This changes the data from RRGGBB to XXRRGGBB */
  191573. else
  191574. {
  191575. png_bytep sp = row + (png_size_t)row_width * 6;
  191576. png_bytep dp = sp + (png_size_t)row_width * 2;
  191577. for (i = 0; i < row_width; i++)
  191578. {
  191579. *(--dp) = *(--sp);
  191580. *(--dp) = *(--sp);
  191581. *(--dp) = *(--sp);
  191582. *(--dp) = *(--sp);
  191583. *(--dp) = *(--sp);
  191584. *(--dp) = *(--sp);
  191585. *(--dp) = hi_filler;
  191586. *(--dp) = lo_filler;
  191587. }
  191588. row_info->channels = 4;
  191589. row_info->pixel_depth = 64;
  191590. row_info->rowbytes = row_width * 8;
  191591. }
  191592. }
  191593. } /* COLOR_TYPE == RGB */
  191594. }
  191595. #endif
  191596. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191597. /* expand grayscale files to RGB, with or without alpha */
  191598. void /* PRIVATE */
  191599. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191600. {
  191601. png_uint_32 i;
  191602. png_uint_32 row_width = row_info->width;
  191603. png_debug(1, "in png_do_gray_to_rgb\n");
  191604. if (row_info->bit_depth >= 8 &&
  191605. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191606. row != NULL && row_info != NULL &&
  191607. #endif
  191608. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191609. {
  191610. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191611. {
  191612. if (row_info->bit_depth == 8)
  191613. {
  191614. png_bytep sp = row + (png_size_t)row_width - 1;
  191615. png_bytep dp = sp + (png_size_t)row_width * 2;
  191616. for (i = 0; i < row_width; i++)
  191617. {
  191618. *(dp--) = *sp;
  191619. *(dp--) = *sp;
  191620. *(dp--) = *(sp--);
  191621. }
  191622. }
  191623. else
  191624. {
  191625. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191626. png_bytep dp = sp + (png_size_t)row_width * 4;
  191627. for (i = 0; i < row_width; i++)
  191628. {
  191629. *(dp--) = *sp;
  191630. *(dp--) = *(sp - 1);
  191631. *(dp--) = *sp;
  191632. *(dp--) = *(sp - 1);
  191633. *(dp--) = *(sp--);
  191634. *(dp--) = *(sp--);
  191635. }
  191636. }
  191637. }
  191638. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191639. {
  191640. if (row_info->bit_depth == 8)
  191641. {
  191642. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191643. png_bytep dp = sp + (png_size_t)row_width * 2;
  191644. for (i = 0; i < row_width; i++)
  191645. {
  191646. *(dp--) = *(sp--);
  191647. *(dp--) = *sp;
  191648. *(dp--) = *sp;
  191649. *(dp--) = *(sp--);
  191650. }
  191651. }
  191652. else
  191653. {
  191654. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191655. png_bytep dp = sp + (png_size_t)row_width * 4;
  191656. for (i = 0; i < row_width; i++)
  191657. {
  191658. *(dp--) = *(sp--);
  191659. *(dp--) = *(sp--);
  191660. *(dp--) = *sp;
  191661. *(dp--) = *(sp - 1);
  191662. *(dp--) = *sp;
  191663. *(dp--) = *(sp - 1);
  191664. *(dp--) = *(sp--);
  191665. *(dp--) = *(sp--);
  191666. }
  191667. }
  191668. }
  191669. row_info->channels += (png_byte)2;
  191670. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  191671. row_info->pixel_depth = (png_byte)(row_info->channels *
  191672. row_info->bit_depth);
  191673. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191674. }
  191675. }
  191676. #endif
  191677. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191678. /* reduce RGB files to grayscale, with or without alpha
  191679. * using the equation given in Poynton's ColorFAQ at
  191680. * <http://www.inforamp.net/~poynton/>
  191681. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  191682. *
  191683. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  191684. *
  191685. * We approximate this with
  191686. *
  191687. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  191688. *
  191689. * which can be expressed with integers as
  191690. *
  191691. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  191692. *
  191693. * The calculation is to be done in a linear colorspace.
  191694. *
  191695. * Other integer coefficents can be used via png_set_rgb_to_gray().
  191696. */
  191697. int /* PRIVATE */
  191698. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  191699. {
  191700. png_uint_32 i;
  191701. png_uint_32 row_width = row_info->width;
  191702. int rgb_error = 0;
  191703. png_debug(1, "in png_do_rgb_to_gray\n");
  191704. if (
  191705. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191706. row != NULL && row_info != NULL &&
  191707. #endif
  191708. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191709. {
  191710. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  191711. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  191712. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  191713. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191714. {
  191715. if (row_info->bit_depth == 8)
  191716. {
  191717. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191718. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191719. {
  191720. png_bytep sp = row;
  191721. png_bytep dp = row;
  191722. for (i = 0; i < row_width; i++)
  191723. {
  191724. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191725. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191726. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191727. if(red != green || red != blue)
  191728. {
  191729. rgb_error |= 1;
  191730. *(dp++) = png_ptr->gamma_from_1[
  191731. (rc*red+gc*green+bc*blue)>>15];
  191732. }
  191733. else
  191734. *(dp++) = *(sp-1);
  191735. }
  191736. }
  191737. else
  191738. #endif
  191739. {
  191740. png_bytep sp = row;
  191741. png_bytep dp = row;
  191742. for (i = 0; i < row_width; i++)
  191743. {
  191744. png_byte red = *(sp++);
  191745. png_byte green = *(sp++);
  191746. png_byte blue = *(sp++);
  191747. if(red != green || red != blue)
  191748. {
  191749. rgb_error |= 1;
  191750. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  191751. }
  191752. else
  191753. *(dp++) = *(sp-1);
  191754. }
  191755. }
  191756. }
  191757. else /* RGB bit_depth == 16 */
  191758. {
  191759. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191760. if (png_ptr->gamma_16_to_1 != NULL &&
  191761. png_ptr->gamma_16_from_1 != NULL)
  191762. {
  191763. png_bytep sp = row;
  191764. png_bytep dp = row;
  191765. for (i = 0; i < row_width; i++)
  191766. {
  191767. png_uint_16 red, green, blue, w;
  191768. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191769. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191770. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191771. if(red == green && red == blue)
  191772. w = red;
  191773. else
  191774. {
  191775. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191776. png_ptr->gamma_shift][red>>8];
  191777. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191778. png_ptr->gamma_shift][green>>8];
  191779. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191780. png_ptr->gamma_shift][blue>>8];
  191781. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  191782. + bc*blue_1)>>15);
  191783. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191784. png_ptr->gamma_shift][gray16 >> 8];
  191785. rgb_error |= 1;
  191786. }
  191787. *(dp++) = (png_byte)((w>>8) & 0xff);
  191788. *(dp++) = (png_byte)(w & 0xff);
  191789. }
  191790. }
  191791. else
  191792. #endif
  191793. {
  191794. png_bytep sp = row;
  191795. png_bytep dp = row;
  191796. for (i = 0; i < row_width; i++)
  191797. {
  191798. png_uint_16 red, green, blue, gray16;
  191799. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191800. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191801. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191802. if(red != green || red != blue)
  191803. rgb_error |= 1;
  191804. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191805. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191806. *(dp++) = (png_byte)(gray16 & 0xff);
  191807. }
  191808. }
  191809. }
  191810. }
  191811. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191812. {
  191813. if (row_info->bit_depth == 8)
  191814. {
  191815. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191816. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  191817. {
  191818. png_bytep sp = row;
  191819. png_bytep dp = row;
  191820. for (i = 0; i < row_width; i++)
  191821. {
  191822. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  191823. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  191824. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  191825. if(red != green || red != blue)
  191826. rgb_error |= 1;
  191827. *(dp++) = png_ptr->gamma_from_1
  191828. [(rc*red + gc*green + bc*blue)>>15];
  191829. *(dp++) = *(sp++); /* alpha */
  191830. }
  191831. }
  191832. else
  191833. #endif
  191834. {
  191835. png_bytep sp = row;
  191836. png_bytep dp = row;
  191837. for (i = 0; i < row_width; i++)
  191838. {
  191839. png_byte red = *(sp++);
  191840. png_byte green = *(sp++);
  191841. png_byte blue = *(sp++);
  191842. if(red != green || red != blue)
  191843. rgb_error |= 1;
  191844. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  191845. *(dp++) = *(sp++); /* alpha */
  191846. }
  191847. }
  191848. }
  191849. else /* RGBA bit_depth == 16 */
  191850. {
  191851. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  191852. if (png_ptr->gamma_16_to_1 != NULL &&
  191853. png_ptr->gamma_16_from_1 != NULL)
  191854. {
  191855. png_bytep sp = row;
  191856. png_bytep dp = row;
  191857. for (i = 0; i < row_width; i++)
  191858. {
  191859. png_uint_16 red, green, blue, w;
  191860. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191861. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191862. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  191863. if(red == green && red == blue)
  191864. w = red;
  191865. else
  191866. {
  191867. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  191868. png_ptr->gamma_shift][red>>8];
  191869. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  191870. png_ptr->gamma_shift][green>>8];
  191871. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  191872. png_ptr->gamma_shift][blue>>8];
  191873. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  191874. + gc * green_1 + bc * blue_1)>>15);
  191875. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  191876. png_ptr->gamma_shift][gray16 >> 8];
  191877. rgb_error |= 1;
  191878. }
  191879. *(dp++) = (png_byte)((w>>8) & 0xff);
  191880. *(dp++) = (png_byte)(w & 0xff);
  191881. *(dp++) = *(sp++); /* alpha */
  191882. *(dp++) = *(sp++);
  191883. }
  191884. }
  191885. else
  191886. #endif
  191887. {
  191888. png_bytep sp = row;
  191889. png_bytep dp = row;
  191890. for (i = 0; i < row_width; i++)
  191891. {
  191892. png_uint_16 red, green, blue, gray16;
  191893. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191894. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191895. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  191896. if(red != green || red != blue)
  191897. rgb_error |= 1;
  191898. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  191899. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  191900. *(dp++) = (png_byte)(gray16 & 0xff);
  191901. *(dp++) = *(sp++); /* alpha */
  191902. *(dp++) = *(sp++);
  191903. }
  191904. }
  191905. }
  191906. }
  191907. row_info->channels -= (png_byte)2;
  191908. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  191909. row_info->pixel_depth = (png_byte)(row_info->channels *
  191910. row_info->bit_depth);
  191911. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  191912. }
  191913. return rgb_error;
  191914. }
  191915. #endif
  191916. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  191917. * large of png_color. This lets grayscale images be treated as
  191918. * paletted. Most useful for gamma correction and simplification
  191919. * of code.
  191920. */
  191921. void PNGAPI
  191922. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  191923. {
  191924. int num_palette;
  191925. int color_inc;
  191926. int i;
  191927. int v;
  191928. png_debug(1, "in png_do_build_grayscale_palette\n");
  191929. if (palette == NULL)
  191930. return;
  191931. switch (bit_depth)
  191932. {
  191933. case 1:
  191934. num_palette = 2;
  191935. color_inc = 0xff;
  191936. break;
  191937. case 2:
  191938. num_palette = 4;
  191939. color_inc = 0x55;
  191940. break;
  191941. case 4:
  191942. num_palette = 16;
  191943. color_inc = 0x11;
  191944. break;
  191945. case 8:
  191946. num_palette = 256;
  191947. color_inc = 1;
  191948. break;
  191949. default:
  191950. num_palette = 0;
  191951. color_inc = 0;
  191952. break;
  191953. }
  191954. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  191955. {
  191956. palette[i].red = (png_byte)v;
  191957. palette[i].green = (png_byte)v;
  191958. palette[i].blue = (png_byte)v;
  191959. }
  191960. }
  191961. /* This function is currently unused. Do we really need it? */
  191962. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  191963. void /* PRIVATE */
  191964. png_correct_palette(png_structp png_ptr, png_colorp palette,
  191965. int num_palette)
  191966. {
  191967. png_debug(1, "in png_correct_palette\n");
  191968. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191969. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191970. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  191971. {
  191972. png_color back, back_1;
  191973. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191974. {
  191975. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191976. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191977. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191978. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191979. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191980. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191981. }
  191982. else
  191983. {
  191984. double g;
  191985. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  191986. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  191987. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  191988. {
  191989. back.red = png_ptr->background.red;
  191990. back.green = png_ptr->background.green;
  191991. back.blue = png_ptr->background.blue;
  191992. }
  191993. else
  191994. {
  191995. back.red =
  191996. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  191997. 255.0 + 0.5);
  191998. back.green =
  191999. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192000. 255.0 + 0.5);
  192001. back.blue =
  192002. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192003. 255.0 + 0.5);
  192004. }
  192005. g = 1.0 / png_ptr->background_gamma;
  192006. back_1.red =
  192007. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192008. 255.0 + 0.5);
  192009. back_1.green =
  192010. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192011. 255.0 + 0.5);
  192012. back_1.blue =
  192013. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192014. 255.0 + 0.5);
  192015. }
  192016. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192017. {
  192018. png_uint_32 i;
  192019. for (i = 0; i < (png_uint_32)num_palette; i++)
  192020. {
  192021. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192022. {
  192023. palette[i] = back;
  192024. }
  192025. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192026. {
  192027. png_byte v, w;
  192028. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192029. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192030. palette[i].red = png_ptr->gamma_from_1[w];
  192031. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192032. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192033. palette[i].green = png_ptr->gamma_from_1[w];
  192034. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192035. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192036. palette[i].blue = png_ptr->gamma_from_1[w];
  192037. }
  192038. else
  192039. {
  192040. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192041. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192042. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192043. }
  192044. }
  192045. }
  192046. else
  192047. {
  192048. int i;
  192049. for (i = 0; i < num_palette; i++)
  192050. {
  192051. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192052. {
  192053. palette[i] = back;
  192054. }
  192055. else
  192056. {
  192057. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192058. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192059. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192060. }
  192061. }
  192062. }
  192063. }
  192064. else
  192065. #endif
  192066. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192067. if (png_ptr->transformations & PNG_GAMMA)
  192068. {
  192069. int i;
  192070. for (i = 0; i < num_palette; i++)
  192071. {
  192072. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192073. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192074. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192075. }
  192076. }
  192077. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192078. else
  192079. #endif
  192080. #endif
  192081. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192082. if (png_ptr->transformations & PNG_BACKGROUND)
  192083. {
  192084. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192085. {
  192086. png_color back;
  192087. back.red = (png_byte)png_ptr->background.red;
  192088. back.green = (png_byte)png_ptr->background.green;
  192089. back.blue = (png_byte)png_ptr->background.blue;
  192090. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192091. {
  192092. if (png_ptr->trans[i] == 0)
  192093. {
  192094. palette[i].red = back.red;
  192095. palette[i].green = back.green;
  192096. palette[i].blue = back.blue;
  192097. }
  192098. else if (png_ptr->trans[i] != 0xff)
  192099. {
  192100. png_composite(palette[i].red, png_ptr->palette[i].red,
  192101. png_ptr->trans[i], back.red);
  192102. png_composite(palette[i].green, png_ptr->palette[i].green,
  192103. png_ptr->trans[i], back.green);
  192104. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192105. png_ptr->trans[i], back.blue);
  192106. }
  192107. }
  192108. }
  192109. else /* assume grayscale palette (what else could it be?) */
  192110. {
  192111. int i;
  192112. for (i = 0; i < num_palette; i++)
  192113. {
  192114. if (i == (png_byte)png_ptr->trans_values.gray)
  192115. {
  192116. palette[i].red = (png_byte)png_ptr->background.red;
  192117. palette[i].green = (png_byte)png_ptr->background.green;
  192118. palette[i].blue = (png_byte)png_ptr->background.blue;
  192119. }
  192120. }
  192121. }
  192122. }
  192123. #endif
  192124. }
  192125. #endif
  192126. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192127. /* Replace any alpha or transparency with the supplied background color.
  192128. * "background" is already in the screen gamma, while "background_1" is
  192129. * at a gamma of 1.0. Paletted files have already been taken care of.
  192130. */
  192131. void /* PRIVATE */
  192132. png_do_background(png_row_infop row_info, png_bytep row,
  192133. png_color_16p trans_values, png_color_16p background
  192134. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192135. , png_color_16p background_1,
  192136. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192137. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192138. png_uint_16pp gamma_16_to_1, int gamma_shift
  192139. #endif
  192140. )
  192141. {
  192142. png_bytep sp, dp;
  192143. png_uint_32 i;
  192144. png_uint_32 row_width=row_info->width;
  192145. int shift;
  192146. png_debug(1, "in png_do_background\n");
  192147. if (background != NULL &&
  192148. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192149. row != NULL && row_info != NULL &&
  192150. #endif
  192151. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192152. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192153. {
  192154. switch (row_info->color_type)
  192155. {
  192156. case PNG_COLOR_TYPE_GRAY:
  192157. {
  192158. switch (row_info->bit_depth)
  192159. {
  192160. case 1:
  192161. {
  192162. sp = row;
  192163. shift = 7;
  192164. for (i = 0; i < row_width; i++)
  192165. {
  192166. if ((png_uint_16)((*sp >> shift) & 0x01)
  192167. == trans_values->gray)
  192168. {
  192169. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192170. *sp |= (png_byte)(background->gray << shift);
  192171. }
  192172. if (!shift)
  192173. {
  192174. shift = 7;
  192175. sp++;
  192176. }
  192177. else
  192178. shift--;
  192179. }
  192180. break;
  192181. }
  192182. case 2:
  192183. {
  192184. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192185. if (gamma_table != NULL)
  192186. {
  192187. sp = row;
  192188. shift = 6;
  192189. for (i = 0; i < row_width; i++)
  192190. {
  192191. if ((png_uint_16)((*sp >> shift) & 0x03)
  192192. == trans_values->gray)
  192193. {
  192194. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192195. *sp |= (png_byte)(background->gray << shift);
  192196. }
  192197. else
  192198. {
  192199. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192200. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192201. (p << 4) | (p << 6)] >> 6) & 0x03);
  192202. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192203. *sp |= (png_byte)(g << shift);
  192204. }
  192205. if (!shift)
  192206. {
  192207. shift = 6;
  192208. sp++;
  192209. }
  192210. else
  192211. shift -= 2;
  192212. }
  192213. }
  192214. else
  192215. #endif
  192216. {
  192217. sp = row;
  192218. shift = 6;
  192219. for (i = 0; i < row_width; i++)
  192220. {
  192221. if ((png_uint_16)((*sp >> shift) & 0x03)
  192222. == trans_values->gray)
  192223. {
  192224. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192225. *sp |= (png_byte)(background->gray << shift);
  192226. }
  192227. if (!shift)
  192228. {
  192229. shift = 6;
  192230. sp++;
  192231. }
  192232. else
  192233. shift -= 2;
  192234. }
  192235. }
  192236. break;
  192237. }
  192238. case 4:
  192239. {
  192240. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192241. if (gamma_table != NULL)
  192242. {
  192243. sp = row;
  192244. shift = 4;
  192245. for (i = 0; i < row_width; i++)
  192246. {
  192247. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192248. == trans_values->gray)
  192249. {
  192250. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192251. *sp |= (png_byte)(background->gray << shift);
  192252. }
  192253. else
  192254. {
  192255. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192256. png_byte g = (png_byte)((gamma_table[p |
  192257. (p << 4)] >> 4) & 0x0f);
  192258. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192259. *sp |= (png_byte)(g << shift);
  192260. }
  192261. if (!shift)
  192262. {
  192263. shift = 4;
  192264. sp++;
  192265. }
  192266. else
  192267. shift -= 4;
  192268. }
  192269. }
  192270. else
  192271. #endif
  192272. {
  192273. sp = row;
  192274. shift = 4;
  192275. for (i = 0; i < row_width; i++)
  192276. {
  192277. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192278. == trans_values->gray)
  192279. {
  192280. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192281. *sp |= (png_byte)(background->gray << shift);
  192282. }
  192283. if (!shift)
  192284. {
  192285. shift = 4;
  192286. sp++;
  192287. }
  192288. else
  192289. shift -= 4;
  192290. }
  192291. }
  192292. break;
  192293. }
  192294. case 8:
  192295. {
  192296. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192297. if (gamma_table != NULL)
  192298. {
  192299. sp = row;
  192300. for (i = 0; i < row_width; i++, sp++)
  192301. {
  192302. if (*sp == trans_values->gray)
  192303. {
  192304. *sp = (png_byte)background->gray;
  192305. }
  192306. else
  192307. {
  192308. *sp = gamma_table[*sp];
  192309. }
  192310. }
  192311. }
  192312. else
  192313. #endif
  192314. {
  192315. sp = row;
  192316. for (i = 0; i < row_width; i++, sp++)
  192317. {
  192318. if (*sp == trans_values->gray)
  192319. {
  192320. *sp = (png_byte)background->gray;
  192321. }
  192322. }
  192323. }
  192324. break;
  192325. }
  192326. case 16:
  192327. {
  192328. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192329. if (gamma_16 != NULL)
  192330. {
  192331. sp = row;
  192332. for (i = 0; i < row_width; i++, sp += 2)
  192333. {
  192334. png_uint_16 v;
  192335. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192336. if (v == trans_values->gray)
  192337. {
  192338. /* background is already in screen gamma */
  192339. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192340. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192341. }
  192342. else
  192343. {
  192344. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192345. *sp = (png_byte)((v >> 8) & 0xff);
  192346. *(sp + 1) = (png_byte)(v & 0xff);
  192347. }
  192348. }
  192349. }
  192350. else
  192351. #endif
  192352. {
  192353. sp = row;
  192354. for (i = 0; i < row_width; i++, sp += 2)
  192355. {
  192356. png_uint_16 v;
  192357. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192358. if (v == trans_values->gray)
  192359. {
  192360. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192361. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192362. }
  192363. }
  192364. }
  192365. break;
  192366. }
  192367. }
  192368. break;
  192369. }
  192370. case PNG_COLOR_TYPE_RGB:
  192371. {
  192372. if (row_info->bit_depth == 8)
  192373. {
  192374. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192375. if (gamma_table != NULL)
  192376. {
  192377. sp = row;
  192378. for (i = 0; i < row_width; i++, sp += 3)
  192379. {
  192380. if (*sp == trans_values->red &&
  192381. *(sp + 1) == trans_values->green &&
  192382. *(sp + 2) == trans_values->blue)
  192383. {
  192384. *sp = (png_byte)background->red;
  192385. *(sp + 1) = (png_byte)background->green;
  192386. *(sp + 2) = (png_byte)background->blue;
  192387. }
  192388. else
  192389. {
  192390. *sp = gamma_table[*sp];
  192391. *(sp + 1) = gamma_table[*(sp + 1)];
  192392. *(sp + 2) = gamma_table[*(sp + 2)];
  192393. }
  192394. }
  192395. }
  192396. else
  192397. #endif
  192398. {
  192399. sp = row;
  192400. for (i = 0; i < row_width; i++, sp += 3)
  192401. {
  192402. if (*sp == trans_values->red &&
  192403. *(sp + 1) == trans_values->green &&
  192404. *(sp + 2) == trans_values->blue)
  192405. {
  192406. *sp = (png_byte)background->red;
  192407. *(sp + 1) = (png_byte)background->green;
  192408. *(sp + 2) = (png_byte)background->blue;
  192409. }
  192410. }
  192411. }
  192412. }
  192413. else /* if (row_info->bit_depth == 16) */
  192414. {
  192415. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192416. if (gamma_16 != NULL)
  192417. {
  192418. sp = row;
  192419. for (i = 0; i < row_width; i++, sp += 6)
  192420. {
  192421. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192422. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192423. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192424. if (r == trans_values->red && g == trans_values->green &&
  192425. b == trans_values->blue)
  192426. {
  192427. /* background is already in screen gamma */
  192428. *sp = (png_byte)((background->red >> 8) & 0xff);
  192429. *(sp + 1) = (png_byte)(background->red & 0xff);
  192430. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192431. *(sp + 3) = (png_byte)(background->green & 0xff);
  192432. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192433. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192434. }
  192435. else
  192436. {
  192437. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192438. *sp = (png_byte)((v >> 8) & 0xff);
  192439. *(sp + 1) = (png_byte)(v & 0xff);
  192440. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192441. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192442. *(sp + 3) = (png_byte)(v & 0xff);
  192443. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192444. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192445. *(sp + 5) = (png_byte)(v & 0xff);
  192446. }
  192447. }
  192448. }
  192449. else
  192450. #endif
  192451. {
  192452. sp = row;
  192453. for (i = 0; i < row_width; i++, sp += 6)
  192454. {
  192455. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192456. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192457. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192458. if (r == trans_values->red && g == trans_values->green &&
  192459. b == trans_values->blue)
  192460. {
  192461. *sp = (png_byte)((background->red >> 8) & 0xff);
  192462. *(sp + 1) = (png_byte)(background->red & 0xff);
  192463. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192464. *(sp + 3) = (png_byte)(background->green & 0xff);
  192465. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192466. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192467. }
  192468. }
  192469. }
  192470. }
  192471. break;
  192472. }
  192473. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192474. {
  192475. if (row_info->bit_depth == 8)
  192476. {
  192477. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192478. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192479. gamma_table != NULL)
  192480. {
  192481. sp = row;
  192482. dp = row;
  192483. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192484. {
  192485. png_uint_16 a = *(sp + 1);
  192486. if (a == 0xff)
  192487. {
  192488. *dp = gamma_table[*sp];
  192489. }
  192490. else if (a == 0)
  192491. {
  192492. /* background is already in screen gamma */
  192493. *dp = (png_byte)background->gray;
  192494. }
  192495. else
  192496. {
  192497. png_byte v, w;
  192498. v = gamma_to_1[*sp];
  192499. png_composite(w, v, a, background_1->gray);
  192500. *dp = gamma_from_1[w];
  192501. }
  192502. }
  192503. }
  192504. else
  192505. #endif
  192506. {
  192507. sp = row;
  192508. dp = row;
  192509. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192510. {
  192511. png_byte a = *(sp + 1);
  192512. if (a == 0xff)
  192513. {
  192514. *dp = *sp;
  192515. }
  192516. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192517. else if (a == 0)
  192518. {
  192519. *dp = (png_byte)background->gray;
  192520. }
  192521. else
  192522. {
  192523. png_composite(*dp, *sp, a, background_1->gray);
  192524. }
  192525. #else
  192526. *dp = (png_byte)background->gray;
  192527. #endif
  192528. }
  192529. }
  192530. }
  192531. else /* if (png_ptr->bit_depth == 16) */
  192532. {
  192533. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192534. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192535. gamma_16_to_1 != NULL)
  192536. {
  192537. sp = row;
  192538. dp = row;
  192539. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192540. {
  192541. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192542. if (a == (png_uint_16)0xffff)
  192543. {
  192544. png_uint_16 v;
  192545. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192546. *dp = (png_byte)((v >> 8) & 0xff);
  192547. *(dp + 1) = (png_byte)(v & 0xff);
  192548. }
  192549. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192550. else if (a == 0)
  192551. #else
  192552. else
  192553. #endif
  192554. {
  192555. /* background is already in screen gamma */
  192556. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192557. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192558. }
  192559. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192560. else
  192561. {
  192562. png_uint_16 g, v, w;
  192563. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192564. png_composite_16(v, g, a, background_1->gray);
  192565. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192566. *dp = (png_byte)((w >> 8) & 0xff);
  192567. *(dp + 1) = (png_byte)(w & 0xff);
  192568. }
  192569. #endif
  192570. }
  192571. }
  192572. else
  192573. #endif
  192574. {
  192575. sp = row;
  192576. dp = row;
  192577. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192578. {
  192579. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192580. if (a == (png_uint_16)0xffff)
  192581. {
  192582. png_memcpy(dp, sp, 2);
  192583. }
  192584. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192585. else if (a == 0)
  192586. #else
  192587. else
  192588. #endif
  192589. {
  192590. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192591. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192592. }
  192593. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192594. else
  192595. {
  192596. png_uint_16 g, v;
  192597. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192598. png_composite_16(v, g, a, background_1->gray);
  192599. *dp = (png_byte)((v >> 8) & 0xff);
  192600. *(dp + 1) = (png_byte)(v & 0xff);
  192601. }
  192602. #endif
  192603. }
  192604. }
  192605. }
  192606. break;
  192607. }
  192608. case PNG_COLOR_TYPE_RGB_ALPHA:
  192609. {
  192610. if (row_info->bit_depth == 8)
  192611. {
  192612. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192613. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192614. gamma_table != NULL)
  192615. {
  192616. sp = row;
  192617. dp = row;
  192618. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192619. {
  192620. png_byte a = *(sp + 3);
  192621. if (a == 0xff)
  192622. {
  192623. *dp = gamma_table[*sp];
  192624. *(dp + 1) = gamma_table[*(sp + 1)];
  192625. *(dp + 2) = gamma_table[*(sp + 2)];
  192626. }
  192627. else if (a == 0)
  192628. {
  192629. /* background is already in screen gamma */
  192630. *dp = (png_byte)background->red;
  192631. *(dp + 1) = (png_byte)background->green;
  192632. *(dp + 2) = (png_byte)background->blue;
  192633. }
  192634. else
  192635. {
  192636. png_byte v, w;
  192637. v = gamma_to_1[*sp];
  192638. png_composite(w, v, a, background_1->red);
  192639. *dp = gamma_from_1[w];
  192640. v = gamma_to_1[*(sp + 1)];
  192641. png_composite(w, v, a, background_1->green);
  192642. *(dp + 1) = gamma_from_1[w];
  192643. v = gamma_to_1[*(sp + 2)];
  192644. png_composite(w, v, a, background_1->blue);
  192645. *(dp + 2) = gamma_from_1[w];
  192646. }
  192647. }
  192648. }
  192649. else
  192650. #endif
  192651. {
  192652. sp = row;
  192653. dp = row;
  192654. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192655. {
  192656. png_byte a = *(sp + 3);
  192657. if (a == 0xff)
  192658. {
  192659. *dp = *sp;
  192660. *(dp + 1) = *(sp + 1);
  192661. *(dp + 2) = *(sp + 2);
  192662. }
  192663. else if (a == 0)
  192664. {
  192665. *dp = (png_byte)background->red;
  192666. *(dp + 1) = (png_byte)background->green;
  192667. *(dp + 2) = (png_byte)background->blue;
  192668. }
  192669. else
  192670. {
  192671. png_composite(*dp, *sp, a, background->red);
  192672. png_composite(*(dp + 1), *(sp + 1), a,
  192673. background->green);
  192674. png_composite(*(dp + 2), *(sp + 2), a,
  192675. background->blue);
  192676. }
  192677. }
  192678. }
  192679. }
  192680. else /* if (row_info->bit_depth == 16) */
  192681. {
  192682. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192683. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192684. gamma_16_to_1 != NULL)
  192685. {
  192686. sp = row;
  192687. dp = row;
  192688. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192689. {
  192690. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192691. << 8) + (png_uint_16)(*(sp + 7)));
  192692. if (a == (png_uint_16)0xffff)
  192693. {
  192694. png_uint_16 v;
  192695. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192696. *dp = (png_byte)((v >> 8) & 0xff);
  192697. *(dp + 1) = (png_byte)(v & 0xff);
  192698. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192699. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192700. *(dp + 3) = (png_byte)(v & 0xff);
  192701. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192702. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192703. *(dp + 5) = (png_byte)(v & 0xff);
  192704. }
  192705. else if (a == 0)
  192706. {
  192707. /* background is already in screen gamma */
  192708. *dp = (png_byte)((background->red >> 8) & 0xff);
  192709. *(dp + 1) = (png_byte)(background->red & 0xff);
  192710. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192711. *(dp + 3) = (png_byte)(background->green & 0xff);
  192712. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192713. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192714. }
  192715. else
  192716. {
  192717. png_uint_16 v, w, x;
  192718. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192719. png_composite_16(w, v, a, background_1->red);
  192720. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192721. *dp = (png_byte)((x >> 8) & 0xff);
  192722. *(dp + 1) = (png_byte)(x & 0xff);
  192723. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192724. png_composite_16(w, v, a, background_1->green);
  192725. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  192726. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  192727. *(dp + 3) = (png_byte)(x & 0xff);
  192728. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192729. png_composite_16(w, v, a, background_1->blue);
  192730. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  192731. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  192732. *(dp + 5) = (png_byte)(x & 0xff);
  192733. }
  192734. }
  192735. }
  192736. else
  192737. #endif
  192738. {
  192739. sp = row;
  192740. dp = row;
  192741. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  192742. {
  192743. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  192744. << 8) + (png_uint_16)(*(sp + 7)));
  192745. if (a == (png_uint_16)0xffff)
  192746. {
  192747. png_memcpy(dp, sp, 6);
  192748. }
  192749. else if (a == 0)
  192750. {
  192751. *dp = (png_byte)((background->red >> 8) & 0xff);
  192752. *(dp + 1) = (png_byte)(background->red & 0xff);
  192753. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192754. *(dp + 3) = (png_byte)(background->green & 0xff);
  192755. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192756. *(dp + 5) = (png_byte)(background->blue & 0xff);
  192757. }
  192758. else
  192759. {
  192760. png_uint_16 v;
  192761. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192762. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  192763. + *(sp + 3));
  192764. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  192765. + *(sp + 5));
  192766. png_composite_16(v, r, a, background->red);
  192767. *dp = (png_byte)((v >> 8) & 0xff);
  192768. *(dp + 1) = (png_byte)(v & 0xff);
  192769. png_composite_16(v, g, a, background->green);
  192770. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  192771. *(dp + 3) = (png_byte)(v & 0xff);
  192772. png_composite_16(v, b, a, background->blue);
  192773. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  192774. *(dp + 5) = (png_byte)(v & 0xff);
  192775. }
  192776. }
  192777. }
  192778. }
  192779. break;
  192780. }
  192781. }
  192782. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192783. {
  192784. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192785. row_info->channels--;
  192786. row_info->pixel_depth = (png_byte)(row_info->channels *
  192787. row_info->bit_depth);
  192788. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192789. }
  192790. }
  192791. }
  192792. #endif
  192793. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192794. /* Gamma correct the image, avoiding the alpha channel. Make sure
  192795. * you do this after you deal with the transparency issue on grayscale
  192796. * or RGB images. If your bit depth is 8, use gamma_table, if it
  192797. * is 16, use gamma_16_table and gamma_shift. Build these with
  192798. * build_gamma_table().
  192799. */
  192800. void /* PRIVATE */
  192801. png_do_gamma(png_row_infop row_info, png_bytep row,
  192802. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  192803. int gamma_shift)
  192804. {
  192805. png_bytep sp;
  192806. png_uint_32 i;
  192807. png_uint_32 row_width=row_info->width;
  192808. png_debug(1, "in png_do_gamma\n");
  192809. if (
  192810. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192811. row != NULL && row_info != NULL &&
  192812. #endif
  192813. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  192814. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  192815. {
  192816. switch (row_info->color_type)
  192817. {
  192818. case PNG_COLOR_TYPE_RGB:
  192819. {
  192820. if (row_info->bit_depth == 8)
  192821. {
  192822. sp = row;
  192823. for (i = 0; i < row_width; i++)
  192824. {
  192825. *sp = gamma_table[*sp];
  192826. sp++;
  192827. *sp = gamma_table[*sp];
  192828. sp++;
  192829. *sp = gamma_table[*sp];
  192830. sp++;
  192831. }
  192832. }
  192833. else /* if (row_info->bit_depth == 16) */
  192834. {
  192835. sp = row;
  192836. for (i = 0; i < row_width; i++)
  192837. {
  192838. png_uint_16 v;
  192839. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192840. *sp = (png_byte)((v >> 8) & 0xff);
  192841. *(sp + 1) = (png_byte)(v & 0xff);
  192842. sp += 2;
  192843. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192844. *sp = (png_byte)((v >> 8) & 0xff);
  192845. *(sp + 1) = (png_byte)(v & 0xff);
  192846. sp += 2;
  192847. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192848. *sp = (png_byte)((v >> 8) & 0xff);
  192849. *(sp + 1) = (png_byte)(v & 0xff);
  192850. sp += 2;
  192851. }
  192852. }
  192853. break;
  192854. }
  192855. case PNG_COLOR_TYPE_RGB_ALPHA:
  192856. {
  192857. if (row_info->bit_depth == 8)
  192858. {
  192859. sp = row;
  192860. for (i = 0; i < row_width; i++)
  192861. {
  192862. *sp = gamma_table[*sp];
  192863. sp++;
  192864. *sp = gamma_table[*sp];
  192865. sp++;
  192866. *sp = gamma_table[*sp];
  192867. sp++;
  192868. sp++;
  192869. }
  192870. }
  192871. else /* if (row_info->bit_depth == 16) */
  192872. {
  192873. sp = row;
  192874. for (i = 0; i < row_width; i++)
  192875. {
  192876. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192877. *sp = (png_byte)((v >> 8) & 0xff);
  192878. *(sp + 1) = (png_byte)(v & 0xff);
  192879. sp += 2;
  192880. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192881. *sp = (png_byte)((v >> 8) & 0xff);
  192882. *(sp + 1) = (png_byte)(v & 0xff);
  192883. sp += 2;
  192884. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192885. *sp = (png_byte)((v >> 8) & 0xff);
  192886. *(sp + 1) = (png_byte)(v & 0xff);
  192887. sp += 4;
  192888. }
  192889. }
  192890. break;
  192891. }
  192892. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192893. {
  192894. if (row_info->bit_depth == 8)
  192895. {
  192896. sp = row;
  192897. for (i = 0; i < row_width; i++)
  192898. {
  192899. *sp = gamma_table[*sp];
  192900. sp += 2;
  192901. }
  192902. }
  192903. else /* if (row_info->bit_depth == 16) */
  192904. {
  192905. sp = row;
  192906. for (i = 0; i < row_width; i++)
  192907. {
  192908. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192909. *sp = (png_byte)((v >> 8) & 0xff);
  192910. *(sp + 1) = (png_byte)(v & 0xff);
  192911. sp += 4;
  192912. }
  192913. }
  192914. break;
  192915. }
  192916. case PNG_COLOR_TYPE_GRAY:
  192917. {
  192918. if (row_info->bit_depth == 2)
  192919. {
  192920. sp = row;
  192921. for (i = 0; i < row_width; i += 4)
  192922. {
  192923. int a = *sp & 0xc0;
  192924. int b = *sp & 0x30;
  192925. int c = *sp & 0x0c;
  192926. int d = *sp & 0x03;
  192927. *sp = (png_byte)(
  192928. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  192929. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  192930. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  192931. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  192932. sp++;
  192933. }
  192934. }
  192935. if (row_info->bit_depth == 4)
  192936. {
  192937. sp = row;
  192938. for (i = 0; i < row_width; i += 2)
  192939. {
  192940. int msb = *sp & 0xf0;
  192941. int lsb = *sp & 0x0f;
  192942. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  192943. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  192944. sp++;
  192945. }
  192946. }
  192947. else if (row_info->bit_depth == 8)
  192948. {
  192949. sp = row;
  192950. for (i = 0; i < row_width; i++)
  192951. {
  192952. *sp = gamma_table[*sp];
  192953. sp++;
  192954. }
  192955. }
  192956. else if (row_info->bit_depth == 16)
  192957. {
  192958. sp = row;
  192959. for (i = 0; i < row_width; i++)
  192960. {
  192961. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  192962. *sp = (png_byte)((v >> 8) & 0xff);
  192963. *(sp + 1) = (png_byte)(v & 0xff);
  192964. sp += 2;
  192965. }
  192966. }
  192967. break;
  192968. }
  192969. }
  192970. }
  192971. }
  192972. #endif
  192973. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192974. /* Expands a palette row to an RGB or RGBA row depending
  192975. * upon whether you supply trans and num_trans.
  192976. */
  192977. void /* PRIVATE */
  192978. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  192979. png_colorp palette, png_bytep trans, int num_trans)
  192980. {
  192981. int shift, value;
  192982. png_bytep sp, dp;
  192983. png_uint_32 i;
  192984. png_uint_32 row_width=row_info->width;
  192985. png_debug(1, "in png_do_expand_palette\n");
  192986. if (
  192987. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192988. row != NULL && row_info != NULL &&
  192989. #endif
  192990. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  192991. {
  192992. if (row_info->bit_depth < 8)
  192993. {
  192994. switch (row_info->bit_depth)
  192995. {
  192996. case 1:
  192997. {
  192998. sp = row + (png_size_t)((row_width - 1) >> 3);
  192999. dp = row + (png_size_t)row_width - 1;
  193000. shift = 7 - (int)((row_width + 7) & 0x07);
  193001. for (i = 0; i < row_width; i++)
  193002. {
  193003. if ((*sp >> shift) & 0x01)
  193004. *dp = 1;
  193005. else
  193006. *dp = 0;
  193007. if (shift == 7)
  193008. {
  193009. shift = 0;
  193010. sp--;
  193011. }
  193012. else
  193013. shift++;
  193014. dp--;
  193015. }
  193016. break;
  193017. }
  193018. case 2:
  193019. {
  193020. sp = row + (png_size_t)((row_width - 1) >> 2);
  193021. dp = row + (png_size_t)row_width - 1;
  193022. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193023. for (i = 0; i < row_width; i++)
  193024. {
  193025. value = (*sp >> shift) & 0x03;
  193026. *dp = (png_byte)value;
  193027. if (shift == 6)
  193028. {
  193029. shift = 0;
  193030. sp--;
  193031. }
  193032. else
  193033. shift += 2;
  193034. dp--;
  193035. }
  193036. break;
  193037. }
  193038. case 4:
  193039. {
  193040. sp = row + (png_size_t)((row_width - 1) >> 1);
  193041. dp = row + (png_size_t)row_width - 1;
  193042. shift = (int)((row_width & 0x01) << 2);
  193043. for (i = 0; i < row_width; i++)
  193044. {
  193045. value = (*sp >> shift) & 0x0f;
  193046. *dp = (png_byte)value;
  193047. if (shift == 4)
  193048. {
  193049. shift = 0;
  193050. sp--;
  193051. }
  193052. else
  193053. shift += 4;
  193054. dp--;
  193055. }
  193056. break;
  193057. }
  193058. }
  193059. row_info->bit_depth = 8;
  193060. row_info->pixel_depth = 8;
  193061. row_info->rowbytes = row_width;
  193062. }
  193063. switch (row_info->bit_depth)
  193064. {
  193065. case 8:
  193066. {
  193067. if (trans != NULL)
  193068. {
  193069. sp = row + (png_size_t)row_width - 1;
  193070. dp = row + (png_size_t)(row_width << 2) - 1;
  193071. for (i = 0; i < row_width; i++)
  193072. {
  193073. if ((int)(*sp) >= num_trans)
  193074. *dp-- = 0xff;
  193075. else
  193076. *dp-- = trans[*sp];
  193077. *dp-- = palette[*sp].blue;
  193078. *dp-- = palette[*sp].green;
  193079. *dp-- = palette[*sp].red;
  193080. sp--;
  193081. }
  193082. row_info->bit_depth = 8;
  193083. row_info->pixel_depth = 32;
  193084. row_info->rowbytes = row_width * 4;
  193085. row_info->color_type = 6;
  193086. row_info->channels = 4;
  193087. }
  193088. else
  193089. {
  193090. sp = row + (png_size_t)row_width - 1;
  193091. dp = row + (png_size_t)(row_width * 3) - 1;
  193092. for (i = 0; i < row_width; i++)
  193093. {
  193094. *dp-- = palette[*sp].blue;
  193095. *dp-- = palette[*sp].green;
  193096. *dp-- = palette[*sp].red;
  193097. sp--;
  193098. }
  193099. row_info->bit_depth = 8;
  193100. row_info->pixel_depth = 24;
  193101. row_info->rowbytes = row_width * 3;
  193102. row_info->color_type = 2;
  193103. row_info->channels = 3;
  193104. }
  193105. break;
  193106. }
  193107. }
  193108. }
  193109. }
  193110. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193111. * expanded transparency value is supplied, an alpha channel is built.
  193112. */
  193113. void /* PRIVATE */
  193114. png_do_expand(png_row_infop row_info, png_bytep row,
  193115. png_color_16p trans_value)
  193116. {
  193117. int shift, value;
  193118. png_bytep sp, dp;
  193119. png_uint_32 i;
  193120. png_uint_32 row_width=row_info->width;
  193121. png_debug(1, "in png_do_expand\n");
  193122. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193123. if (row != NULL && row_info != NULL)
  193124. #endif
  193125. {
  193126. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193127. {
  193128. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193129. if (row_info->bit_depth < 8)
  193130. {
  193131. switch (row_info->bit_depth)
  193132. {
  193133. case 1:
  193134. {
  193135. gray = (png_uint_16)((gray&0x01)*0xff);
  193136. sp = row + (png_size_t)((row_width - 1) >> 3);
  193137. dp = row + (png_size_t)row_width - 1;
  193138. shift = 7 - (int)((row_width + 7) & 0x07);
  193139. for (i = 0; i < row_width; i++)
  193140. {
  193141. if ((*sp >> shift) & 0x01)
  193142. *dp = 0xff;
  193143. else
  193144. *dp = 0;
  193145. if (shift == 7)
  193146. {
  193147. shift = 0;
  193148. sp--;
  193149. }
  193150. else
  193151. shift++;
  193152. dp--;
  193153. }
  193154. break;
  193155. }
  193156. case 2:
  193157. {
  193158. gray = (png_uint_16)((gray&0x03)*0x55);
  193159. sp = row + (png_size_t)((row_width - 1) >> 2);
  193160. dp = row + (png_size_t)row_width - 1;
  193161. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193162. for (i = 0; i < row_width; i++)
  193163. {
  193164. value = (*sp >> shift) & 0x03;
  193165. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193166. (value << 6));
  193167. if (shift == 6)
  193168. {
  193169. shift = 0;
  193170. sp--;
  193171. }
  193172. else
  193173. shift += 2;
  193174. dp--;
  193175. }
  193176. break;
  193177. }
  193178. case 4:
  193179. {
  193180. gray = (png_uint_16)((gray&0x0f)*0x11);
  193181. sp = row + (png_size_t)((row_width - 1) >> 1);
  193182. dp = row + (png_size_t)row_width - 1;
  193183. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193184. for (i = 0; i < row_width; i++)
  193185. {
  193186. value = (*sp >> shift) & 0x0f;
  193187. *dp = (png_byte)(value | (value << 4));
  193188. if (shift == 4)
  193189. {
  193190. shift = 0;
  193191. sp--;
  193192. }
  193193. else
  193194. shift = 4;
  193195. dp--;
  193196. }
  193197. break;
  193198. }
  193199. }
  193200. row_info->bit_depth = 8;
  193201. row_info->pixel_depth = 8;
  193202. row_info->rowbytes = row_width;
  193203. }
  193204. if (trans_value != NULL)
  193205. {
  193206. if (row_info->bit_depth == 8)
  193207. {
  193208. gray = gray & 0xff;
  193209. sp = row + (png_size_t)row_width - 1;
  193210. dp = row + (png_size_t)(row_width << 1) - 1;
  193211. for (i = 0; i < row_width; i++)
  193212. {
  193213. if (*sp == gray)
  193214. *dp-- = 0;
  193215. else
  193216. *dp-- = 0xff;
  193217. *dp-- = *sp--;
  193218. }
  193219. }
  193220. else if (row_info->bit_depth == 16)
  193221. {
  193222. png_byte gray_high = (gray >> 8) & 0xff;
  193223. png_byte gray_low = gray & 0xff;
  193224. sp = row + row_info->rowbytes - 1;
  193225. dp = row + (row_info->rowbytes << 1) - 1;
  193226. for (i = 0; i < row_width; i++)
  193227. {
  193228. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193229. {
  193230. *dp-- = 0;
  193231. *dp-- = 0;
  193232. }
  193233. else
  193234. {
  193235. *dp-- = 0xff;
  193236. *dp-- = 0xff;
  193237. }
  193238. *dp-- = *sp--;
  193239. *dp-- = *sp--;
  193240. }
  193241. }
  193242. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193243. row_info->channels = 2;
  193244. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193245. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193246. row_width);
  193247. }
  193248. }
  193249. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193250. {
  193251. if (row_info->bit_depth == 8)
  193252. {
  193253. png_byte red = trans_value->red & 0xff;
  193254. png_byte green = trans_value->green & 0xff;
  193255. png_byte blue = trans_value->blue & 0xff;
  193256. sp = row + (png_size_t)row_info->rowbytes - 1;
  193257. dp = row + (png_size_t)(row_width << 2) - 1;
  193258. for (i = 0; i < row_width; i++)
  193259. {
  193260. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193261. *dp-- = 0;
  193262. else
  193263. *dp-- = 0xff;
  193264. *dp-- = *sp--;
  193265. *dp-- = *sp--;
  193266. *dp-- = *sp--;
  193267. }
  193268. }
  193269. else if (row_info->bit_depth == 16)
  193270. {
  193271. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193272. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193273. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193274. png_byte red_low = trans_value->red & 0xff;
  193275. png_byte green_low = trans_value->green & 0xff;
  193276. png_byte blue_low = trans_value->blue & 0xff;
  193277. sp = row + row_info->rowbytes - 1;
  193278. dp = row + (png_size_t)(row_width << 3) - 1;
  193279. for (i = 0; i < row_width; i++)
  193280. {
  193281. if (*(sp - 5) == red_high &&
  193282. *(sp - 4) == red_low &&
  193283. *(sp - 3) == green_high &&
  193284. *(sp - 2) == green_low &&
  193285. *(sp - 1) == blue_high &&
  193286. *(sp ) == blue_low)
  193287. {
  193288. *dp-- = 0;
  193289. *dp-- = 0;
  193290. }
  193291. else
  193292. {
  193293. *dp-- = 0xff;
  193294. *dp-- = 0xff;
  193295. }
  193296. *dp-- = *sp--;
  193297. *dp-- = *sp--;
  193298. *dp-- = *sp--;
  193299. *dp-- = *sp--;
  193300. *dp-- = *sp--;
  193301. *dp-- = *sp--;
  193302. }
  193303. }
  193304. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193305. row_info->channels = 4;
  193306. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193307. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193308. }
  193309. }
  193310. }
  193311. #endif
  193312. #if defined(PNG_READ_DITHER_SUPPORTED)
  193313. void /* PRIVATE */
  193314. png_do_dither(png_row_infop row_info, png_bytep row,
  193315. png_bytep palette_lookup, png_bytep dither_lookup)
  193316. {
  193317. png_bytep sp, dp;
  193318. png_uint_32 i;
  193319. png_uint_32 row_width=row_info->width;
  193320. png_debug(1, "in png_do_dither\n");
  193321. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193322. if (row != NULL && row_info != NULL)
  193323. #endif
  193324. {
  193325. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193326. palette_lookup && row_info->bit_depth == 8)
  193327. {
  193328. int r, g, b, p;
  193329. sp = row;
  193330. dp = row;
  193331. for (i = 0; i < row_width; i++)
  193332. {
  193333. r = *sp++;
  193334. g = *sp++;
  193335. b = *sp++;
  193336. /* this looks real messy, but the compiler will reduce
  193337. it down to a reasonable formula. For example, with
  193338. 5 bits per color, we get:
  193339. p = (((r >> 3) & 0x1f) << 10) |
  193340. (((g >> 3) & 0x1f) << 5) |
  193341. ((b >> 3) & 0x1f);
  193342. */
  193343. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193344. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193345. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193346. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193347. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193348. (PNG_DITHER_BLUE_BITS)) |
  193349. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193350. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193351. *dp++ = palette_lookup[p];
  193352. }
  193353. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193354. row_info->channels = 1;
  193355. row_info->pixel_depth = row_info->bit_depth;
  193356. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193357. }
  193358. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193359. palette_lookup != NULL && row_info->bit_depth == 8)
  193360. {
  193361. int r, g, b, p;
  193362. sp = row;
  193363. dp = row;
  193364. for (i = 0; i < row_width; i++)
  193365. {
  193366. r = *sp++;
  193367. g = *sp++;
  193368. b = *sp++;
  193369. sp++;
  193370. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193371. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193372. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193373. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193374. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193375. (PNG_DITHER_BLUE_BITS)) |
  193376. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193377. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193378. *dp++ = palette_lookup[p];
  193379. }
  193380. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193381. row_info->channels = 1;
  193382. row_info->pixel_depth = row_info->bit_depth;
  193383. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193384. }
  193385. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193386. dither_lookup && row_info->bit_depth == 8)
  193387. {
  193388. sp = row;
  193389. for (i = 0; i < row_width; i++, sp++)
  193390. {
  193391. *sp = dither_lookup[*sp];
  193392. }
  193393. }
  193394. }
  193395. }
  193396. #endif
  193397. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193398. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193399. static PNG_CONST int png_gamma_shift[] =
  193400. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193401. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193402. * tables, we don't make a full table if we are reducing to 8-bit in
  193403. * the future. Note also how the gamma_16 tables are segmented so that
  193404. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193405. */
  193406. void /* PRIVATE */
  193407. png_build_gamma_table(png_structp png_ptr)
  193408. {
  193409. png_debug(1, "in png_build_gamma_table\n");
  193410. if (png_ptr->bit_depth <= 8)
  193411. {
  193412. int i;
  193413. double g;
  193414. if (png_ptr->screen_gamma > .000001)
  193415. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193416. else
  193417. g = 1.0;
  193418. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193419. (png_uint_32)256);
  193420. for (i = 0; i < 256; i++)
  193421. {
  193422. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193423. g) * 255.0 + .5);
  193424. }
  193425. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193426. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193427. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193428. {
  193429. g = 1.0 / (png_ptr->gamma);
  193430. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193431. (png_uint_32)256);
  193432. for (i = 0; i < 256; i++)
  193433. {
  193434. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193435. g) * 255.0 + .5);
  193436. }
  193437. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193438. (png_uint_32)256);
  193439. if(png_ptr->screen_gamma > 0.000001)
  193440. g = 1.0 / png_ptr->screen_gamma;
  193441. else
  193442. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193443. for (i = 0; i < 256; i++)
  193444. {
  193445. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193446. g) * 255.0 + .5);
  193447. }
  193448. }
  193449. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193450. }
  193451. else
  193452. {
  193453. double g;
  193454. int i, j, shift, num;
  193455. int sig_bit;
  193456. png_uint_32 ig;
  193457. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193458. {
  193459. sig_bit = (int)png_ptr->sig_bit.red;
  193460. if ((int)png_ptr->sig_bit.green > sig_bit)
  193461. sig_bit = png_ptr->sig_bit.green;
  193462. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193463. sig_bit = png_ptr->sig_bit.blue;
  193464. }
  193465. else
  193466. {
  193467. sig_bit = (int)png_ptr->sig_bit.gray;
  193468. }
  193469. if (sig_bit > 0)
  193470. shift = 16 - sig_bit;
  193471. else
  193472. shift = 0;
  193473. if (png_ptr->transformations & PNG_16_TO_8)
  193474. {
  193475. if (shift < (16 - PNG_MAX_GAMMA_8))
  193476. shift = (16 - PNG_MAX_GAMMA_8);
  193477. }
  193478. if (shift > 8)
  193479. shift = 8;
  193480. if (shift < 0)
  193481. shift = 0;
  193482. png_ptr->gamma_shift = (png_byte)shift;
  193483. num = (1 << (8 - shift));
  193484. if (png_ptr->screen_gamma > .000001)
  193485. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193486. else
  193487. g = 1.0;
  193488. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193489. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193490. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193491. {
  193492. double fin, fout;
  193493. png_uint_32 last, max;
  193494. for (i = 0; i < num; i++)
  193495. {
  193496. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193497. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193498. }
  193499. g = 1.0 / g;
  193500. last = 0;
  193501. for (i = 0; i < 256; i++)
  193502. {
  193503. fout = ((double)i + 0.5) / 256.0;
  193504. fin = pow(fout, g);
  193505. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193506. while (last <= max)
  193507. {
  193508. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193509. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193510. (png_uint_16)i | ((png_uint_16)i << 8));
  193511. last++;
  193512. }
  193513. }
  193514. while (last < ((png_uint_32)num << 8))
  193515. {
  193516. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193517. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193518. last++;
  193519. }
  193520. }
  193521. else
  193522. {
  193523. for (i = 0; i < num; i++)
  193524. {
  193525. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193526. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193527. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193528. for (j = 0; j < 256; j++)
  193529. {
  193530. png_ptr->gamma_16_table[i][j] =
  193531. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193532. 65535.0, g) * 65535.0 + .5);
  193533. }
  193534. }
  193535. }
  193536. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193537. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193538. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193539. {
  193540. g = 1.0 / (png_ptr->gamma);
  193541. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193542. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193543. for (i = 0; i < num; i++)
  193544. {
  193545. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193546. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193547. ig = (((png_uint_32)i *
  193548. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193549. for (j = 0; j < 256; j++)
  193550. {
  193551. png_ptr->gamma_16_to_1[i][j] =
  193552. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193553. 65535.0, g) * 65535.0 + .5);
  193554. }
  193555. }
  193556. if(png_ptr->screen_gamma > 0.000001)
  193557. g = 1.0 / png_ptr->screen_gamma;
  193558. else
  193559. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193560. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193561. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193562. for (i = 0; i < num; i++)
  193563. {
  193564. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193565. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193566. ig = (((png_uint_32)i *
  193567. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193568. for (j = 0; j < 256; j++)
  193569. {
  193570. png_ptr->gamma_16_from_1[i][j] =
  193571. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193572. 65535.0, g) * 65535.0 + .5);
  193573. }
  193574. }
  193575. }
  193576. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193577. }
  193578. }
  193579. #endif
  193580. /* To do: install integer version of png_build_gamma_table here */
  193581. #endif
  193582. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193583. /* undoes intrapixel differencing */
  193584. void /* PRIVATE */
  193585. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193586. {
  193587. png_debug(1, "in png_do_read_intrapixel\n");
  193588. if (
  193589. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193590. row != NULL && row_info != NULL &&
  193591. #endif
  193592. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193593. {
  193594. int bytes_per_pixel;
  193595. png_uint_32 row_width = row_info->width;
  193596. if (row_info->bit_depth == 8)
  193597. {
  193598. png_bytep rp;
  193599. png_uint_32 i;
  193600. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193601. bytes_per_pixel = 3;
  193602. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193603. bytes_per_pixel = 4;
  193604. else
  193605. return;
  193606. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193607. {
  193608. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193609. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193610. }
  193611. }
  193612. else if (row_info->bit_depth == 16)
  193613. {
  193614. png_bytep rp;
  193615. png_uint_32 i;
  193616. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193617. bytes_per_pixel = 6;
  193618. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193619. bytes_per_pixel = 8;
  193620. else
  193621. return;
  193622. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193623. {
  193624. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193625. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193626. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193627. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193628. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193629. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193630. *(rp+1) = (png_byte)(red & 0xff);
  193631. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193632. *(rp+5) = (png_byte)(blue & 0xff);
  193633. }
  193634. }
  193635. }
  193636. }
  193637. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193638. #endif /* PNG_READ_SUPPORTED */
  193639. /*** End of inlined file: pngrtran.c ***/
  193640. /*** Start of inlined file: pngrutil.c ***/
  193641. /* pngrutil.c - utilities to read a PNG file
  193642. *
  193643. * Last changed in libpng 1.2.21 [October 4, 2007]
  193644. * For conditions of distribution and use, see copyright notice in png.h
  193645. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193646. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193647. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193648. *
  193649. * This file contains routines that are only called from within
  193650. * libpng itself during the course of reading an image.
  193651. */
  193652. #define PNG_INTERNAL
  193653. #if defined(PNG_READ_SUPPORTED)
  193654. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193655. # define WIN32_WCE_OLD
  193656. #endif
  193657. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193658. # if defined(WIN32_WCE_OLD)
  193659. /* strtod() function is not supported on WindowsCE */
  193660. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193661. {
  193662. double result = 0;
  193663. int len;
  193664. wchar_t *str, *end;
  193665. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  193666. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  193667. if ( NULL != str )
  193668. {
  193669. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  193670. result = wcstod(str, &end);
  193671. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  193672. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  193673. png_free(png_ptr, str);
  193674. }
  193675. return result;
  193676. }
  193677. # else
  193678. # define png_strtod(p,a,b) strtod(a,b)
  193679. # endif
  193680. #endif
  193681. png_uint_32 PNGAPI
  193682. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  193683. {
  193684. png_uint_32 i = png_get_uint_32(buf);
  193685. if (i > PNG_UINT_31_MAX)
  193686. png_error(png_ptr, "PNG unsigned integer out of range.");
  193687. return (i);
  193688. }
  193689. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  193690. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  193691. png_uint_32 PNGAPI
  193692. png_get_uint_32(png_bytep buf)
  193693. {
  193694. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  193695. ((png_uint_32)(*(buf + 1)) << 16) +
  193696. ((png_uint_32)(*(buf + 2)) << 8) +
  193697. (png_uint_32)(*(buf + 3));
  193698. return (i);
  193699. }
  193700. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  193701. * data is stored in the PNG file in two's complement format, and it is
  193702. * assumed that the machine format for signed integers is the same. */
  193703. png_int_32 PNGAPI
  193704. png_get_int_32(png_bytep buf)
  193705. {
  193706. png_int_32 i = ((png_int_32)(*buf) << 24) +
  193707. ((png_int_32)(*(buf + 1)) << 16) +
  193708. ((png_int_32)(*(buf + 2)) << 8) +
  193709. (png_int_32)(*(buf + 3));
  193710. return (i);
  193711. }
  193712. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  193713. png_uint_16 PNGAPI
  193714. png_get_uint_16(png_bytep buf)
  193715. {
  193716. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  193717. (png_uint_16)(*(buf + 1)));
  193718. return (i);
  193719. }
  193720. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  193721. /* Read data, and (optionally) run it through the CRC. */
  193722. void /* PRIVATE */
  193723. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  193724. {
  193725. if(png_ptr == NULL) return;
  193726. png_read_data(png_ptr, buf, length);
  193727. png_calculate_crc(png_ptr, buf, length);
  193728. }
  193729. /* Optionally skip data and then check the CRC. Depending on whether we
  193730. are reading a ancillary or critical chunk, and how the program has set
  193731. things up, we may calculate the CRC on the data and print a message.
  193732. Returns '1' if there was a CRC error, '0' otherwise. */
  193733. int /* PRIVATE */
  193734. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  193735. {
  193736. png_size_t i;
  193737. png_size_t istop = png_ptr->zbuf_size;
  193738. for (i = (png_size_t)skip; i > istop; i -= istop)
  193739. {
  193740. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  193741. }
  193742. if (i)
  193743. {
  193744. png_crc_read(png_ptr, png_ptr->zbuf, i);
  193745. }
  193746. if (png_crc_error(png_ptr))
  193747. {
  193748. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  193749. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  193750. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  193751. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  193752. {
  193753. png_chunk_warning(png_ptr, "CRC error");
  193754. }
  193755. else
  193756. {
  193757. png_chunk_error(png_ptr, "CRC error");
  193758. }
  193759. return (1);
  193760. }
  193761. return (0);
  193762. }
  193763. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  193764. the data it has read thus far. */
  193765. int /* PRIVATE */
  193766. png_crc_error(png_structp png_ptr)
  193767. {
  193768. png_byte crc_bytes[4];
  193769. png_uint_32 crc;
  193770. int need_crc = 1;
  193771. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  193772. {
  193773. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  193774. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  193775. need_crc = 0;
  193776. }
  193777. else /* critical */
  193778. {
  193779. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  193780. need_crc = 0;
  193781. }
  193782. png_read_data(png_ptr, crc_bytes, 4);
  193783. if (need_crc)
  193784. {
  193785. crc = png_get_uint_32(crc_bytes);
  193786. return ((int)(crc != png_ptr->crc));
  193787. }
  193788. else
  193789. return (0);
  193790. }
  193791. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  193792. defined(PNG_READ_iCCP_SUPPORTED)
  193793. /*
  193794. * Decompress trailing data in a chunk. The assumption is that chunkdata
  193795. * points at an allocated area holding the contents of a chunk with a
  193796. * trailing compressed part. What we get back is an allocated area
  193797. * holding the original prefix part and an uncompressed version of the
  193798. * trailing part (the malloc area passed in is freed).
  193799. */
  193800. png_charp /* PRIVATE */
  193801. png_decompress_chunk(png_structp png_ptr, int comp_type,
  193802. png_charp chunkdata, png_size_t chunklength,
  193803. png_size_t prefix_size, png_size_t *newlength)
  193804. {
  193805. static PNG_CONST char msg[] = "Error decoding compressed text";
  193806. png_charp text;
  193807. png_size_t text_size;
  193808. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  193809. {
  193810. int ret = Z_OK;
  193811. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  193812. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  193813. png_ptr->zstream.next_out = png_ptr->zbuf;
  193814. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193815. text_size = 0;
  193816. text = NULL;
  193817. while (png_ptr->zstream.avail_in)
  193818. {
  193819. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  193820. if (ret != Z_OK && ret != Z_STREAM_END)
  193821. {
  193822. if (png_ptr->zstream.msg != NULL)
  193823. png_warning(png_ptr, png_ptr->zstream.msg);
  193824. else
  193825. png_warning(png_ptr, msg);
  193826. inflateReset(&png_ptr->zstream);
  193827. png_ptr->zstream.avail_in = 0;
  193828. if (text == NULL)
  193829. {
  193830. text_size = prefix_size + png_sizeof(msg) + 1;
  193831. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  193832. if (text == NULL)
  193833. {
  193834. png_free(png_ptr,chunkdata);
  193835. png_error(png_ptr,"Not enough memory to decompress chunk");
  193836. }
  193837. png_memcpy(text, chunkdata, prefix_size);
  193838. }
  193839. text[text_size - 1] = 0x00;
  193840. /* Copy what we can of the error message into the text chunk */
  193841. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  193842. text_size = png_sizeof(msg) > text_size ? text_size :
  193843. png_sizeof(msg);
  193844. png_memcpy(text + prefix_size, msg, text_size + 1);
  193845. break;
  193846. }
  193847. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  193848. {
  193849. if (text == NULL)
  193850. {
  193851. text_size = prefix_size +
  193852. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193853. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  193854. if (text == NULL)
  193855. {
  193856. png_free(png_ptr,chunkdata);
  193857. png_error(png_ptr,"Not enough memory to decompress chunk.");
  193858. }
  193859. png_memcpy(text + prefix_size, png_ptr->zbuf,
  193860. text_size - prefix_size);
  193861. png_memcpy(text, chunkdata, prefix_size);
  193862. *(text + text_size) = 0x00;
  193863. }
  193864. else
  193865. {
  193866. png_charp tmp;
  193867. tmp = text;
  193868. text = (png_charp)png_malloc_warn(png_ptr,
  193869. (png_uint_32)(text_size +
  193870. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  193871. if (text == NULL)
  193872. {
  193873. png_free(png_ptr, tmp);
  193874. png_free(png_ptr, chunkdata);
  193875. png_error(png_ptr,"Not enough memory to decompress chunk..");
  193876. }
  193877. png_memcpy(text, tmp, text_size);
  193878. png_free(png_ptr, tmp);
  193879. png_memcpy(text + text_size, png_ptr->zbuf,
  193880. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  193881. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  193882. *(text + text_size) = 0x00;
  193883. }
  193884. if (ret == Z_STREAM_END)
  193885. break;
  193886. else
  193887. {
  193888. png_ptr->zstream.next_out = png_ptr->zbuf;
  193889. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193890. }
  193891. }
  193892. }
  193893. if (ret != Z_STREAM_END)
  193894. {
  193895. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193896. char umsg[52];
  193897. if (ret == Z_BUF_ERROR)
  193898. png_snprintf(umsg, 52,
  193899. "Buffer error in compressed datastream in %s chunk",
  193900. png_ptr->chunk_name);
  193901. else if (ret == Z_DATA_ERROR)
  193902. png_snprintf(umsg, 52,
  193903. "Data error in compressed datastream in %s chunk",
  193904. png_ptr->chunk_name);
  193905. else
  193906. png_snprintf(umsg, 52,
  193907. "Incomplete compressed datastream in %s chunk",
  193908. png_ptr->chunk_name);
  193909. png_warning(png_ptr, umsg);
  193910. #else
  193911. png_warning(png_ptr,
  193912. "Incomplete compressed datastream in chunk other than IDAT");
  193913. #endif
  193914. text_size=prefix_size;
  193915. if (text == NULL)
  193916. {
  193917. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  193918. if (text == NULL)
  193919. {
  193920. png_free(png_ptr, chunkdata);
  193921. png_error(png_ptr,"Not enough memory for text.");
  193922. }
  193923. png_memcpy(text, chunkdata, prefix_size);
  193924. }
  193925. *(text + text_size) = 0x00;
  193926. }
  193927. inflateReset(&png_ptr->zstream);
  193928. png_ptr->zstream.avail_in = 0;
  193929. png_free(png_ptr, chunkdata);
  193930. chunkdata = text;
  193931. *newlength=text_size;
  193932. }
  193933. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  193934. {
  193935. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  193936. char umsg[50];
  193937. png_snprintf(umsg, 50,
  193938. "Unknown zTXt compression type %d", comp_type);
  193939. png_warning(png_ptr, umsg);
  193940. #else
  193941. png_warning(png_ptr, "Unknown zTXt compression type");
  193942. #endif
  193943. *(chunkdata + prefix_size) = 0x00;
  193944. *newlength=prefix_size;
  193945. }
  193946. return chunkdata;
  193947. }
  193948. #endif
  193949. /* read and check the IDHR chunk */
  193950. void /* PRIVATE */
  193951. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  193952. {
  193953. png_byte buf[13];
  193954. png_uint_32 width, height;
  193955. int bit_depth, color_type, compression_type, filter_type;
  193956. int interlace_type;
  193957. png_debug(1, "in png_handle_IHDR\n");
  193958. if (png_ptr->mode & PNG_HAVE_IHDR)
  193959. png_error(png_ptr, "Out of place IHDR");
  193960. /* check the length */
  193961. if (length != 13)
  193962. png_error(png_ptr, "Invalid IHDR chunk");
  193963. png_ptr->mode |= PNG_HAVE_IHDR;
  193964. png_crc_read(png_ptr, buf, 13);
  193965. png_crc_finish(png_ptr, 0);
  193966. width = png_get_uint_31(png_ptr, buf);
  193967. height = png_get_uint_31(png_ptr, buf + 4);
  193968. bit_depth = buf[8];
  193969. color_type = buf[9];
  193970. compression_type = buf[10];
  193971. filter_type = buf[11];
  193972. interlace_type = buf[12];
  193973. /* set internal variables */
  193974. png_ptr->width = width;
  193975. png_ptr->height = height;
  193976. png_ptr->bit_depth = (png_byte)bit_depth;
  193977. png_ptr->interlaced = (png_byte)interlace_type;
  193978. png_ptr->color_type = (png_byte)color_type;
  193979. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193980. png_ptr->filter_type = (png_byte)filter_type;
  193981. #endif
  193982. png_ptr->compression_type = (png_byte)compression_type;
  193983. /* find number of channels */
  193984. switch (png_ptr->color_type)
  193985. {
  193986. case PNG_COLOR_TYPE_GRAY:
  193987. case PNG_COLOR_TYPE_PALETTE:
  193988. png_ptr->channels = 1;
  193989. break;
  193990. case PNG_COLOR_TYPE_RGB:
  193991. png_ptr->channels = 3;
  193992. break;
  193993. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193994. png_ptr->channels = 2;
  193995. break;
  193996. case PNG_COLOR_TYPE_RGB_ALPHA:
  193997. png_ptr->channels = 4;
  193998. break;
  193999. }
  194000. /* set up other useful info */
  194001. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194002. png_ptr->channels);
  194003. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194004. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194005. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194006. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194007. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194008. color_type, interlace_type, compression_type, filter_type);
  194009. }
  194010. /* read and check the palette */
  194011. void /* PRIVATE */
  194012. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194013. {
  194014. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194015. int num, i;
  194016. #ifndef PNG_NO_POINTER_INDEXING
  194017. png_colorp pal_ptr;
  194018. #endif
  194019. png_debug(1, "in png_handle_PLTE\n");
  194020. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194021. png_error(png_ptr, "Missing IHDR before PLTE");
  194022. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194023. {
  194024. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194025. png_crc_finish(png_ptr, length);
  194026. return;
  194027. }
  194028. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194029. png_error(png_ptr, "Duplicate PLTE chunk");
  194030. png_ptr->mode |= PNG_HAVE_PLTE;
  194031. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194032. {
  194033. png_warning(png_ptr,
  194034. "Ignoring PLTE chunk in grayscale PNG");
  194035. png_crc_finish(png_ptr, length);
  194036. return;
  194037. }
  194038. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194039. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194040. {
  194041. png_crc_finish(png_ptr, length);
  194042. return;
  194043. }
  194044. #endif
  194045. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194046. {
  194047. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194048. {
  194049. png_warning(png_ptr, "Invalid palette chunk");
  194050. png_crc_finish(png_ptr, length);
  194051. return;
  194052. }
  194053. else
  194054. {
  194055. png_error(png_ptr, "Invalid palette chunk");
  194056. }
  194057. }
  194058. num = (int)length / 3;
  194059. #ifndef PNG_NO_POINTER_INDEXING
  194060. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194061. {
  194062. png_byte buf[3];
  194063. png_crc_read(png_ptr, buf, 3);
  194064. pal_ptr->red = buf[0];
  194065. pal_ptr->green = buf[1];
  194066. pal_ptr->blue = buf[2];
  194067. }
  194068. #else
  194069. for (i = 0; i < num; i++)
  194070. {
  194071. png_byte buf[3];
  194072. png_crc_read(png_ptr, buf, 3);
  194073. /* don't depend upon png_color being any order */
  194074. palette[i].red = buf[0];
  194075. palette[i].green = buf[1];
  194076. palette[i].blue = buf[2];
  194077. }
  194078. #endif
  194079. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194080. whatever the normal CRC configuration tells us. However, if we
  194081. have an RGB image, the PLTE can be considered ancillary, so
  194082. we will act as though it is. */
  194083. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194084. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194085. #endif
  194086. {
  194087. png_crc_finish(png_ptr, 0);
  194088. }
  194089. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194090. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194091. {
  194092. /* If we don't want to use the data from an ancillary chunk,
  194093. we have two options: an error abort, or a warning and we
  194094. ignore the data in this chunk (which should be OK, since
  194095. it's considered ancillary for a RGB or RGBA image). */
  194096. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194097. {
  194098. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194099. {
  194100. png_chunk_error(png_ptr, "CRC error");
  194101. }
  194102. else
  194103. {
  194104. png_chunk_warning(png_ptr, "CRC error");
  194105. return;
  194106. }
  194107. }
  194108. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194109. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194110. {
  194111. png_chunk_warning(png_ptr, "CRC error");
  194112. }
  194113. }
  194114. #endif
  194115. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194116. #if defined(PNG_READ_tRNS_SUPPORTED)
  194117. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194118. {
  194119. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194120. {
  194121. if (png_ptr->num_trans > (png_uint_16)num)
  194122. {
  194123. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194124. png_ptr->num_trans = (png_uint_16)num;
  194125. }
  194126. if (info_ptr->num_trans > (png_uint_16)num)
  194127. {
  194128. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194129. info_ptr->num_trans = (png_uint_16)num;
  194130. }
  194131. }
  194132. }
  194133. #endif
  194134. }
  194135. void /* PRIVATE */
  194136. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194137. {
  194138. png_debug(1, "in png_handle_IEND\n");
  194139. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194140. {
  194141. png_error(png_ptr, "No image in file");
  194142. }
  194143. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194144. if (length != 0)
  194145. {
  194146. png_warning(png_ptr, "Incorrect IEND chunk length");
  194147. }
  194148. png_crc_finish(png_ptr, length);
  194149. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194150. }
  194151. #if defined(PNG_READ_gAMA_SUPPORTED)
  194152. void /* PRIVATE */
  194153. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194154. {
  194155. png_fixed_point igamma;
  194156. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194157. float file_gamma;
  194158. #endif
  194159. png_byte buf[4];
  194160. png_debug(1, "in png_handle_gAMA\n");
  194161. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194162. png_error(png_ptr, "Missing IHDR before gAMA");
  194163. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194164. {
  194165. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194166. png_crc_finish(png_ptr, length);
  194167. return;
  194168. }
  194169. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194170. /* Should be an error, but we can cope with it */
  194171. png_warning(png_ptr, "Out of place gAMA chunk");
  194172. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194173. #if defined(PNG_READ_sRGB_SUPPORTED)
  194174. && !(info_ptr->valid & PNG_INFO_sRGB)
  194175. #endif
  194176. )
  194177. {
  194178. png_warning(png_ptr, "Duplicate gAMA chunk");
  194179. png_crc_finish(png_ptr, length);
  194180. return;
  194181. }
  194182. if (length != 4)
  194183. {
  194184. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194185. png_crc_finish(png_ptr, length);
  194186. return;
  194187. }
  194188. png_crc_read(png_ptr, buf, 4);
  194189. if (png_crc_finish(png_ptr, 0))
  194190. return;
  194191. igamma = (png_fixed_point)png_get_uint_32(buf);
  194192. /* check for zero gamma */
  194193. if (igamma == 0)
  194194. {
  194195. png_warning(png_ptr,
  194196. "Ignoring gAMA chunk with gamma=0");
  194197. return;
  194198. }
  194199. #if defined(PNG_READ_sRGB_SUPPORTED)
  194200. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194201. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194202. {
  194203. png_warning(png_ptr,
  194204. "Ignoring incorrect gAMA value when sRGB is also present");
  194205. #ifndef PNG_NO_CONSOLE_IO
  194206. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194207. #endif
  194208. return;
  194209. }
  194210. #endif /* PNG_READ_sRGB_SUPPORTED */
  194211. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194212. file_gamma = (float)igamma / (float)100000.0;
  194213. # ifdef PNG_READ_GAMMA_SUPPORTED
  194214. png_ptr->gamma = file_gamma;
  194215. # endif
  194216. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194217. #endif
  194218. #ifdef PNG_FIXED_POINT_SUPPORTED
  194219. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194220. #endif
  194221. }
  194222. #endif
  194223. #if defined(PNG_READ_sBIT_SUPPORTED)
  194224. void /* PRIVATE */
  194225. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194226. {
  194227. png_size_t truelen;
  194228. png_byte buf[4];
  194229. png_debug(1, "in png_handle_sBIT\n");
  194230. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194231. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194232. png_error(png_ptr, "Missing IHDR before sBIT");
  194233. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194234. {
  194235. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194236. png_crc_finish(png_ptr, length);
  194237. return;
  194238. }
  194239. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194240. {
  194241. /* Should be an error, but we can cope with it */
  194242. png_warning(png_ptr, "Out of place sBIT chunk");
  194243. }
  194244. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194245. {
  194246. png_warning(png_ptr, "Duplicate sBIT chunk");
  194247. png_crc_finish(png_ptr, length);
  194248. return;
  194249. }
  194250. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194251. truelen = 3;
  194252. else
  194253. truelen = (png_size_t)png_ptr->channels;
  194254. if (length != truelen || length > 4)
  194255. {
  194256. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194257. png_crc_finish(png_ptr, length);
  194258. return;
  194259. }
  194260. png_crc_read(png_ptr, buf, truelen);
  194261. if (png_crc_finish(png_ptr, 0))
  194262. return;
  194263. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194264. {
  194265. png_ptr->sig_bit.red = buf[0];
  194266. png_ptr->sig_bit.green = buf[1];
  194267. png_ptr->sig_bit.blue = buf[2];
  194268. png_ptr->sig_bit.alpha = buf[3];
  194269. }
  194270. else
  194271. {
  194272. png_ptr->sig_bit.gray = buf[0];
  194273. png_ptr->sig_bit.red = buf[0];
  194274. png_ptr->sig_bit.green = buf[0];
  194275. png_ptr->sig_bit.blue = buf[0];
  194276. png_ptr->sig_bit.alpha = buf[1];
  194277. }
  194278. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194279. }
  194280. #endif
  194281. #if defined(PNG_READ_cHRM_SUPPORTED)
  194282. void /* PRIVATE */
  194283. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194284. {
  194285. png_byte buf[4];
  194286. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194287. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194288. #endif
  194289. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194290. int_y_green, int_x_blue, int_y_blue;
  194291. png_uint_32 uint_x, uint_y;
  194292. png_debug(1, "in png_handle_cHRM\n");
  194293. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194294. png_error(png_ptr, "Missing IHDR before cHRM");
  194295. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194296. {
  194297. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194298. png_crc_finish(png_ptr, length);
  194299. return;
  194300. }
  194301. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194302. /* Should be an error, but we can cope with it */
  194303. png_warning(png_ptr, "Missing PLTE before cHRM");
  194304. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194305. #if defined(PNG_READ_sRGB_SUPPORTED)
  194306. && !(info_ptr->valid & PNG_INFO_sRGB)
  194307. #endif
  194308. )
  194309. {
  194310. png_warning(png_ptr, "Duplicate cHRM chunk");
  194311. png_crc_finish(png_ptr, length);
  194312. return;
  194313. }
  194314. if (length != 32)
  194315. {
  194316. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194317. png_crc_finish(png_ptr, length);
  194318. return;
  194319. }
  194320. png_crc_read(png_ptr, buf, 4);
  194321. uint_x = png_get_uint_32(buf);
  194322. png_crc_read(png_ptr, buf, 4);
  194323. uint_y = png_get_uint_32(buf);
  194324. if (uint_x > 80000L || uint_y > 80000L ||
  194325. uint_x + uint_y > 100000L)
  194326. {
  194327. png_warning(png_ptr, "Invalid cHRM white point");
  194328. png_crc_finish(png_ptr, 24);
  194329. return;
  194330. }
  194331. int_x_white = (png_fixed_point)uint_x;
  194332. int_y_white = (png_fixed_point)uint_y;
  194333. png_crc_read(png_ptr, buf, 4);
  194334. uint_x = png_get_uint_32(buf);
  194335. png_crc_read(png_ptr, buf, 4);
  194336. uint_y = png_get_uint_32(buf);
  194337. if (uint_x + uint_y > 100000L)
  194338. {
  194339. png_warning(png_ptr, "Invalid cHRM red point");
  194340. png_crc_finish(png_ptr, 16);
  194341. return;
  194342. }
  194343. int_x_red = (png_fixed_point)uint_x;
  194344. int_y_red = (png_fixed_point)uint_y;
  194345. png_crc_read(png_ptr, buf, 4);
  194346. uint_x = png_get_uint_32(buf);
  194347. png_crc_read(png_ptr, buf, 4);
  194348. uint_y = png_get_uint_32(buf);
  194349. if (uint_x + uint_y > 100000L)
  194350. {
  194351. png_warning(png_ptr, "Invalid cHRM green point");
  194352. png_crc_finish(png_ptr, 8);
  194353. return;
  194354. }
  194355. int_x_green = (png_fixed_point)uint_x;
  194356. int_y_green = (png_fixed_point)uint_y;
  194357. png_crc_read(png_ptr, buf, 4);
  194358. uint_x = png_get_uint_32(buf);
  194359. png_crc_read(png_ptr, buf, 4);
  194360. uint_y = png_get_uint_32(buf);
  194361. if (uint_x + uint_y > 100000L)
  194362. {
  194363. png_warning(png_ptr, "Invalid cHRM blue point");
  194364. png_crc_finish(png_ptr, 0);
  194365. return;
  194366. }
  194367. int_x_blue = (png_fixed_point)uint_x;
  194368. int_y_blue = (png_fixed_point)uint_y;
  194369. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194370. white_x = (float)int_x_white / (float)100000.0;
  194371. white_y = (float)int_y_white / (float)100000.0;
  194372. red_x = (float)int_x_red / (float)100000.0;
  194373. red_y = (float)int_y_red / (float)100000.0;
  194374. green_x = (float)int_x_green / (float)100000.0;
  194375. green_y = (float)int_y_green / (float)100000.0;
  194376. blue_x = (float)int_x_blue / (float)100000.0;
  194377. blue_y = (float)int_y_blue / (float)100000.0;
  194378. #endif
  194379. #if defined(PNG_READ_sRGB_SUPPORTED)
  194380. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194381. {
  194382. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194383. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194384. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194385. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194386. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194387. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194388. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194389. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194390. {
  194391. png_warning(png_ptr,
  194392. "Ignoring incorrect cHRM value when sRGB is also present");
  194393. #ifndef PNG_NO_CONSOLE_IO
  194394. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194395. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194396. white_x, white_y, red_x, red_y);
  194397. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194398. green_x, green_y, blue_x, blue_y);
  194399. #else
  194400. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194401. int_x_white, int_y_white, int_x_red, int_y_red);
  194402. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194403. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194404. #endif
  194405. #endif /* PNG_NO_CONSOLE_IO */
  194406. }
  194407. png_crc_finish(png_ptr, 0);
  194408. return;
  194409. }
  194410. #endif /* PNG_READ_sRGB_SUPPORTED */
  194411. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194412. png_set_cHRM(png_ptr, info_ptr,
  194413. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194414. #endif
  194415. #ifdef PNG_FIXED_POINT_SUPPORTED
  194416. png_set_cHRM_fixed(png_ptr, info_ptr,
  194417. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194418. int_y_green, int_x_blue, int_y_blue);
  194419. #endif
  194420. if (png_crc_finish(png_ptr, 0))
  194421. return;
  194422. }
  194423. #endif
  194424. #if defined(PNG_READ_sRGB_SUPPORTED)
  194425. void /* PRIVATE */
  194426. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194427. {
  194428. int intent;
  194429. png_byte buf[1];
  194430. png_debug(1, "in png_handle_sRGB\n");
  194431. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194432. png_error(png_ptr, "Missing IHDR before sRGB");
  194433. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194434. {
  194435. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194436. png_crc_finish(png_ptr, length);
  194437. return;
  194438. }
  194439. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194440. /* Should be an error, but we can cope with it */
  194441. png_warning(png_ptr, "Out of place sRGB chunk");
  194442. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194443. {
  194444. png_warning(png_ptr, "Duplicate sRGB chunk");
  194445. png_crc_finish(png_ptr, length);
  194446. return;
  194447. }
  194448. if (length != 1)
  194449. {
  194450. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194451. png_crc_finish(png_ptr, length);
  194452. return;
  194453. }
  194454. png_crc_read(png_ptr, buf, 1);
  194455. if (png_crc_finish(png_ptr, 0))
  194456. return;
  194457. intent = buf[0];
  194458. /* check for bad intent */
  194459. if (intent >= PNG_sRGB_INTENT_LAST)
  194460. {
  194461. png_warning(png_ptr, "Unknown sRGB intent");
  194462. return;
  194463. }
  194464. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194465. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194466. {
  194467. png_fixed_point igamma;
  194468. #ifdef PNG_FIXED_POINT_SUPPORTED
  194469. igamma=info_ptr->int_gamma;
  194470. #else
  194471. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194472. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194473. # endif
  194474. #endif
  194475. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194476. {
  194477. png_warning(png_ptr,
  194478. "Ignoring incorrect gAMA value when sRGB is also present");
  194479. #ifndef PNG_NO_CONSOLE_IO
  194480. # ifdef PNG_FIXED_POINT_SUPPORTED
  194481. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194482. # else
  194483. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194484. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194485. # endif
  194486. # endif
  194487. #endif
  194488. }
  194489. }
  194490. #endif /* PNG_READ_gAMA_SUPPORTED */
  194491. #ifdef PNG_READ_cHRM_SUPPORTED
  194492. #ifdef PNG_FIXED_POINT_SUPPORTED
  194493. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194494. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194495. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194496. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194497. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194498. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194499. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194500. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194501. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194502. {
  194503. png_warning(png_ptr,
  194504. "Ignoring incorrect cHRM value when sRGB is also present");
  194505. }
  194506. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194507. #endif /* PNG_READ_cHRM_SUPPORTED */
  194508. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194509. }
  194510. #endif /* PNG_READ_sRGB_SUPPORTED */
  194511. #if defined(PNG_READ_iCCP_SUPPORTED)
  194512. void /* PRIVATE */
  194513. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194514. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194515. {
  194516. png_charp chunkdata;
  194517. png_byte compression_type;
  194518. png_bytep pC;
  194519. png_charp profile;
  194520. png_uint_32 skip = 0;
  194521. png_uint_32 profile_size, profile_length;
  194522. png_size_t slength, prefix_length, data_length;
  194523. png_debug(1, "in png_handle_iCCP\n");
  194524. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194525. png_error(png_ptr, "Missing IHDR before iCCP");
  194526. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194527. {
  194528. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194529. png_crc_finish(png_ptr, length);
  194530. return;
  194531. }
  194532. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194533. /* Should be an error, but we can cope with it */
  194534. png_warning(png_ptr, "Out of place iCCP chunk");
  194535. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194536. {
  194537. png_warning(png_ptr, "Duplicate iCCP chunk");
  194538. png_crc_finish(png_ptr, length);
  194539. return;
  194540. }
  194541. #ifdef PNG_MAX_MALLOC_64K
  194542. if (length > (png_uint_32)65535L)
  194543. {
  194544. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194545. skip = length - (png_uint_32)65535L;
  194546. length = (png_uint_32)65535L;
  194547. }
  194548. #endif
  194549. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194550. slength = (png_size_t)length;
  194551. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194552. if (png_crc_finish(png_ptr, skip))
  194553. {
  194554. png_free(png_ptr, chunkdata);
  194555. return;
  194556. }
  194557. chunkdata[slength] = 0x00;
  194558. for (profile = chunkdata; *profile; profile++)
  194559. /* empty loop to find end of name */ ;
  194560. ++profile;
  194561. /* there should be at least one zero (the compression type byte)
  194562. following the separator, and we should be on it */
  194563. if ( profile >= chunkdata + slength - 1)
  194564. {
  194565. png_free(png_ptr, chunkdata);
  194566. png_warning(png_ptr, "Malformed iCCP chunk");
  194567. return;
  194568. }
  194569. /* compression_type should always be zero */
  194570. compression_type = *profile++;
  194571. if (compression_type)
  194572. {
  194573. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194574. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194575. wrote nonzero) */
  194576. }
  194577. prefix_length = profile - chunkdata;
  194578. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194579. slength, prefix_length, &data_length);
  194580. profile_length = data_length - prefix_length;
  194581. if ( prefix_length > data_length || profile_length < 4)
  194582. {
  194583. png_free(png_ptr, chunkdata);
  194584. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194585. return;
  194586. }
  194587. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194588. pC = (png_bytep)(chunkdata+prefix_length);
  194589. profile_size = ((*(pC ))<<24) |
  194590. ((*(pC+1))<<16) |
  194591. ((*(pC+2))<< 8) |
  194592. ((*(pC+3)) );
  194593. if(profile_size < profile_length)
  194594. profile_length = profile_size;
  194595. if(profile_size > profile_length)
  194596. {
  194597. png_free(png_ptr, chunkdata);
  194598. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194599. return;
  194600. }
  194601. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194602. chunkdata + prefix_length, profile_length);
  194603. png_free(png_ptr, chunkdata);
  194604. }
  194605. #endif /* PNG_READ_iCCP_SUPPORTED */
  194606. #if defined(PNG_READ_sPLT_SUPPORTED)
  194607. void /* PRIVATE */
  194608. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194609. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194610. {
  194611. png_bytep chunkdata;
  194612. png_bytep entry_start;
  194613. png_sPLT_t new_palette;
  194614. #ifdef PNG_NO_POINTER_INDEXING
  194615. png_sPLT_entryp pp;
  194616. #endif
  194617. int data_length, entry_size, i;
  194618. png_uint_32 skip = 0;
  194619. png_size_t slength;
  194620. png_debug(1, "in png_handle_sPLT\n");
  194621. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194622. png_error(png_ptr, "Missing IHDR before sPLT");
  194623. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194624. {
  194625. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194626. png_crc_finish(png_ptr, length);
  194627. return;
  194628. }
  194629. #ifdef PNG_MAX_MALLOC_64K
  194630. if (length > (png_uint_32)65535L)
  194631. {
  194632. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194633. skip = length - (png_uint_32)65535L;
  194634. length = (png_uint_32)65535L;
  194635. }
  194636. #endif
  194637. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194638. slength = (png_size_t)length;
  194639. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194640. if (png_crc_finish(png_ptr, skip))
  194641. {
  194642. png_free(png_ptr, chunkdata);
  194643. return;
  194644. }
  194645. chunkdata[slength] = 0x00;
  194646. for (entry_start = chunkdata; *entry_start; entry_start++)
  194647. /* empty loop to find end of name */ ;
  194648. ++entry_start;
  194649. /* a sample depth should follow the separator, and we should be on it */
  194650. if (entry_start > chunkdata + slength - 2)
  194651. {
  194652. png_free(png_ptr, chunkdata);
  194653. png_warning(png_ptr, "malformed sPLT chunk");
  194654. return;
  194655. }
  194656. new_palette.depth = *entry_start++;
  194657. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194658. data_length = (slength - (entry_start - chunkdata));
  194659. /* integrity-check the data length */
  194660. if (data_length % entry_size)
  194661. {
  194662. png_free(png_ptr, chunkdata);
  194663. png_warning(png_ptr, "sPLT chunk has bad length");
  194664. return;
  194665. }
  194666. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  194667. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  194668. png_sizeof(png_sPLT_entry)))
  194669. {
  194670. png_warning(png_ptr, "sPLT chunk too long");
  194671. return;
  194672. }
  194673. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  194674. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  194675. if (new_palette.entries == NULL)
  194676. {
  194677. png_warning(png_ptr, "sPLT chunk requires too much memory");
  194678. return;
  194679. }
  194680. #ifndef PNG_NO_POINTER_INDEXING
  194681. for (i = 0; i < new_palette.nentries; i++)
  194682. {
  194683. png_sPLT_entryp pp = new_palette.entries + i;
  194684. if (new_palette.depth == 8)
  194685. {
  194686. pp->red = *entry_start++;
  194687. pp->green = *entry_start++;
  194688. pp->blue = *entry_start++;
  194689. pp->alpha = *entry_start++;
  194690. }
  194691. else
  194692. {
  194693. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  194694. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  194695. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  194696. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  194697. }
  194698. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194699. }
  194700. #else
  194701. pp = new_palette.entries;
  194702. for (i = 0; i < new_palette.nentries; i++)
  194703. {
  194704. if (new_palette.depth == 8)
  194705. {
  194706. pp[i].red = *entry_start++;
  194707. pp[i].green = *entry_start++;
  194708. pp[i].blue = *entry_start++;
  194709. pp[i].alpha = *entry_start++;
  194710. }
  194711. else
  194712. {
  194713. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  194714. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  194715. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  194716. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  194717. }
  194718. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  194719. }
  194720. #endif
  194721. /* discard all chunk data except the name and stash that */
  194722. new_palette.name = (png_charp)chunkdata;
  194723. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  194724. png_free(png_ptr, chunkdata);
  194725. png_free(png_ptr, new_palette.entries);
  194726. }
  194727. #endif /* PNG_READ_sPLT_SUPPORTED */
  194728. #if defined(PNG_READ_tRNS_SUPPORTED)
  194729. void /* PRIVATE */
  194730. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194731. {
  194732. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  194733. int bit_mask;
  194734. png_debug(1, "in png_handle_tRNS\n");
  194735. /* For non-indexed color, mask off any bits in the tRNS value that
  194736. * exceed the bit depth. Some creators were writing extra bits there.
  194737. * This is not needed for indexed color. */
  194738. bit_mask = (1 << png_ptr->bit_depth) - 1;
  194739. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194740. png_error(png_ptr, "Missing IHDR before tRNS");
  194741. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194742. {
  194743. png_warning(png_ptr, "Invalid tRNS after IDAT");
  194744. png_crc_finish(png_ptr, length);
  194745. return;
  194746. }
  194747. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194748. {
  194749. png_warning(png_ptr, "Duplicate tRNS chunk");
  194750. png_crc_finish(png_ptr, length);
  194751. return;
  194752. }
  194753. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  194754. {
  194755. png_byte buf[2];
  194756. if (length != 2)
  194757. {
  194758. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194759. png_crc_finish(png_ptr, length);
  194760. return;
  194761. }
  194762. png_crc_read(png_ptr, buf, 2);
  194763. png_ptr->num_trans = 1;
  194764. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  194765. }
  194766. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  194767. {
  194768. png_byte buf[6];
  194769. if (length != 6)
  194770. {
  194771. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194772. png_crc_finish(png_ptr, length);
  194773. return;
  194774. }
  194775. png_crc_read(png_ptr, buf, (png_size_t)length);
  194776. png_ptr->num_trans = 1;
  194777. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  194778. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  194779. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  194780. }
  194781. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194782. {
  194783. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194784. {
  194785. /* Should be an error, but we can cope with it. */
  194786. png_warning(png_ptr, "Missing PLTE before tRNS");
  194787. }
  194788. if (length > (png_uint_32)png_ptr->num_palette ||
  194789. length > PNG_MAX_PALETTE_LENGTH)
  194790. {
  194791. png_warning(png_ptr, "Incorrect tRNS chunk length");
  194792. png_crc_finish(png_ptr, length);
  194793. return;
  194794. }
  194795. if (length == 0)
  194796. {
  194797. png_warning(png_ptr, "Zero length tRNS chunk");
  194798. png_crc_finish(png_ptr, length);
  194799. return;
  194800. }
  194801. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  194802. png_ptr->num_trans = (png_uint_16)length;
  194803. }
  194804. else
  194805. {
  194806. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  194807. png_crc_finish(png_ptr, length);
  194808. return;
  194809. }
  194810. if (png_crc_finish(png_ptr, 0))
  194811. {
  194812. png_ptr->num_trans = 0;
  194813. return;
  194814. }
  194815. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  194816. &(png_ptr->trans_values));
  194817. }
  194818. #endif
  194819. #if defined(PNG_READ_bKGD_SUPPORTED)
  194820. void /* PRIVATE */
  194821. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194822. {
  194823. png_size_t truelen;
  194824. png_byte buf[6];
  194825. png_debug(1, "in png_handle_bKGD\n");
  194826. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194827. png_error(png_ptr, "Missing IHDR before bKGD");
  194828. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194829. {
  194830. png_warning(png_ptr, "Invalid bKGD after IDAT");
  194831. png_crc_finish(png_ptr, length);
  194832. return;
  194833. }
  194834. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  194835. !(png_ptr->mode & PNG_HAVE_PLTE))
  194836. {
  194837. png_warning(png_ptr, "Missing PLTE before bKGD");
  194838. png_crc_finish(png_ptr, length);
  194839. return;
  194840. }
  194841. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  194842. {
  194843. png_warning(png_ptr, "Duplicate bKGD chunk");
  194844. png_crc_finish(png_ptr, length);
  194845. return;
  194846. }
  194847. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194848. truelen = 1;
  194849. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194850. truelen = 6;
  194851. else
  194852. truelen = 2;
  194853. if (length != truelen)
  194854. {
  194855. png_warning(png_ptr, "Incorrect bKGD chunk length");
  194856. png_crc_finish(png_ptr, length);
  194857. return;
  194858. }
  194859. png_crc_read(png_ptr, buf, truelen);
  194860. if (png_crc_finish(png_ptr, 0))
  194861. return;
  194862. /* We convert the index value into RGB components so that we can allow
  194863. * arbitrary RGB values for background when we have transparency, and
  194864. * so it is easy to determine the RGB values of the background color
  194865. * from the info_ptr struct. */
  194866. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194867. {
  194868. png_ptr->background.index = buf[0];
  194869. if(info_ptr->num_palette)
  194870. {
  194871. if(buf[0] > info_ptr->num_palette)
  194872. {
  194873. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  194874. return;
  194875. }
  194876. png_ptr->background.red =
  194877. (png_uint_16)png_ptr->palette[buf[0]].red;
  194878. png_ptr->background.green =
  194879. (png_uint_16)png_ptr->palette[buf[0]].green;
  194880. png_ptr->background.blue =
  194881. (png_uint_16)png_ptr->palette[buf[0]].blue;
  194882. }
  194883. }
  194884. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  194885. {
  194886. png_ptr->background.red =
  194887. png_ptr->background.green =
  194888. png_ptr->background.blue =
  194889. png_ptr->background.gray = png_get_uint_16(buf);
  194890. }
  194891. else
  194892. {
  194893. png_ptr->background.red = png_get_uint_16(buf);
  194894. png_ptr->background.green = png_get_uint_16(buf + 2);
  194895. png_ptr->background.blue = png_get_uint_16(buf + 4);
  194896. }
  194897. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  194898. }
  194899. #endif
  194900. #if defined(PNG_READ_hIST_SUPPORTED)
  194901. void /* PRIVATE */
  194902. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194903. {
  194904. unsigned int num, i;
  194905. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  194906. png_debug(1, "in png_handle_hIST\n");
  194907. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194908. png_error(png_ptr, "Missing IHDR before hIST");
  194909. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194910. {
  194911. png_warning(png_ptr, "Invalid hIST after IDAT");
  194912. png_crc_finish(png_ptr, length);
  194913. return;
  194914. }
  194915. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  194916. {
  194917. png_warning(png_ptr, "Missing PLTE before hIST");
  194918. png_crc_finish(png_ptr, length);
  194919. return;
  194920. }
  194921. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  194922. {
  194923. png_warning(png_ptr, "Duplicate hIST chunk");
  194924. png_crc_finish(png_ptr, length);
  194925. return;
  194926. }
  194927. num = length / 2 ;
  194928. if (num != (unsigned int) png_ptr->num_palette || num >
  194929. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  194930. {
  194931. png_warning(png_ptr, "Incorrect hIST chunk length");
  194932. png_crc_finish(png_ptr, length);
  194933. return;
  194934. }
  194935. for (i = 0; i < num; i++)
  194936. {
  194937. png_byte buf[2];
  194938. png_crc_read(png_ptr, buf, 2);
  194939. readbuf[i] = png_get_uint_16(buf);
  194940. }
  194941. if (png_crc_finish(png_ptr, 0))
  194942. return;
  194943. png_set_hIST(png_ptr, info_ptr, readbuf);
  194944. }
  194945. #endif
  194946. #if defined(PNG_READ_pHYs_SUPPORTED)
  194947. void /* PRIVATE */
  194948. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194949. {
  194950. png_byte buf[9];
  194951. png_uint_32 res_x, res_y;
  194952. int unit_type;
  194953. png_debug(1, "in png_handle_pHYs\n");
  194954. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194955. png_error(png_ptr, "Missing IHDR before pHYs");
  194956. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194957. {
  194958. png_warning(png_ptr, "Invalid pHYs after IDAT");
  194959. png_crc_finish(png_ptr, length);
  194960. return;
  194961. }
  194962. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  194963. {
  194964. png_warning(png_ptr, "Duplicate pHYs chunk");
  194965. png_crc_finish(png_ptr, length);
  194966. return;
  194967. }
  194968. if (length != 9)
  194969. {
  194970. png_warning(png_ptr, "Incorrect pHYs chunk length");
  194971. png_crc_finish(png_ptr, length);
  194972. return;
  194973. }
  194974. png_crc_read(png_ptr, buf, 9);
  194975. if (png_crc_finish(png_ptr, 0))
  194976. return;
  194977. res_x = png_get_uint_32(buf);
  194978. res_y = png_get_uint_32(buf + 4);
  194979. unit_type = buf[8];
  194980. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  194981. }
  194982. #endif
  194983. #if defined(PNG_READ_oFFs_SUPPORTED)
  194984. void /* PRIVATE */
  194985. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194986. {
  194987. png_byte buf[9];
  194988. png_int_32 offset_x, offset_y;
  194989. int unit_type;
  194990. png_debug(1, "in png_handle_oFFs\n");
  194991. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194992. png_error(png_ptr, "Missing IHDR before oFFs");
  194993. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194994. {
  194995. png_warning(png_ptr, "Invalid oFFs after IDAT");
  194996. png_crc_finish(png_ptr, length);
  194997. return;
  194998. }
  194999. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195000. {
  195001. png_warning(png_ptr, "Duplicate oFFs chunk");
  195002. png_crc_finish(png_ptr, length);
  195003. return;
  195004. }
  195005. if (length != 9)
  195006. {
  195007. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195008. png_crc_finish(png_ptr, length);
  195009. return;
  195010. }
  195011. png_crc_read(png_ptr, buf, 9);
  195012. if (png_crc_finish(png_ptr, 0))
  195013. return;
  195014. offset_x = png_get_int_32(buf);
  195015. offset_y = png_get_int_32(buf + 4);
  195016. unit_type = buf[8];
  195017. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195018. }
  195019. #endif
  195020. #if defined(PNG_READ_pCAL_SUPPORTED)
  195021. /* read the pCAL chunk (described in the PNG Extensions document) */
  195022. void /* PRIVATE */
  195023. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195024. {
  195025. png_charp purpose;
  195026. png_int_32 X0, X1;
  195027. png_byte type, nparams;
  195028. png_charp buf, units, endptr;
  195029. png_charpp params;
  195030. png_size_t slength;
  195031. int i;
  195032. png_debug(1, "in png_handle_pCAL\n");
  195033. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195034. png_error(png_ptr, "Missing IHDR before pCAL");
  195035. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195036. {
  195037. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195038. png_crc_finish(png_ptr, length);
  195039. return;
  195040. }
  195041. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195042. {
  195043. png_warning(png_ptr, "Duplicate pCAL chunk");
  195044. png_crc_finish(png_ptr, length);
  195045. return;
  195046. }
  195047. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195048. length + 1);
  195049. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195050. if (purpose == NULL)
  195051. {
  195052. png_warning(png_ptr, "No memory for pCAL purpose.");
  195053. return;
  195054. }
  195055. slength = (png_size_t)length;
  195056. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195057. if (png_crc_finish(png_ptr, 0))
  195058. {
  195059. png_free(png_ptr, purpose);
  195060. return;
  195061. }
  195062. purpose[slength] = 0x00; /* null terminate the last string */
  195063. png_debug(3, "Finding end of pCAL purpose string\n");
  195064. for (buf = purpose; *buf; buf++)
  195065. /* empty loop */ ;
  195066. endptr = purpose + slength;
  195067. /* We need to have at least 12 bytes after the purpose string
  195068. in order to get the parameter information. */
  195069. if (endptr <= buf + 12)
  195070. {
  195071. png_warning(png_ptr, "Invalid pCAL data");
  195072. png_free(png_ptr, purpose);
  195073. return;
  195074. }
  195075. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195076. X0 = png_get_int_32((png_bytep)buf+1);
  195077. X1 = png_get_int_32((png_bytep)buf+5);
  195078. type = buf[9];
  195079. nparams = buf[10];
  195080. units = buf + 11;
  195081. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195082. /* Check that we have the right number of parameters for known
  195083. equation types. */
  195084. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195085. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195086. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195087. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195088. {
  195089. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195090. png_free(png_ptr, purpose);
  195091. return;
  195092. }
  195093. else if (type >= PNG_EQUATION_LAST)
  195094. {
  195095. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195096. }
  195097. for (buf = units; *buf; buf++)
  195098. /* Empty loop to move past the units string. */ ;
  195099. png_debug(3, "Allocating pCAL parameters array\n");
  195100. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195101. *png_sizeof(png_charp))) ;
  195102. if (params == NULL)
  195103. {
  195104. png_free(png_ptr, purpose);
  195105. png_warning(png_ptr, "No memory for pCAL params.");
  195106. return;
  195107. }
  195108. /* Get pointers to the start of each parameter string. */
  195109. for (i = 0; i < (int)nparams; i++)
  195110. {
  195111. buf++; /* Skip the null string terminator from previous parameter. */
  195112. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195113. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195114. /* Empty loop to move past each parameter string */ ;
  195115. /* Make sure we haven't run out of data yet */
  195116. if (buf > endptr)
  195117. {
  195118. png_warning(png_ptr, "Invalid pCAL data");
  195119. png_free(png_ptr, purpose);
  195120. png_free(png_ptr, params);
  195121. return;
  195122. }
  195123. }
  195124. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195125. units, params);
  195126. png_free(png_ptr, purpose);
  195127. png_free(png_ptr, params);
  195128. }
  195129. #endif
  195130. #if defined(PNG_READ_sCAL_SUPPORTED)
  195131. /* read the sCAL chunk */
  195132. void /* PRIVATE */
  195133. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195134. {
  195135. png_charp buffer, ep;
  195136. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195137. double width, height;
  195138. png_charp vp;
  195139. #else
  195140. #ifdef PNG_FIXED_POINT_SUPPORTED
  195141. png_charp swidth, sheight;
  195142. #endif
  195143. #endif
  195144. png_size_t slength;
  195145. png_debug(1, "in png_handle_sCAL\n");
  195146. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195147. png_error(png_ptr, "Missing IHDR before sCAL");
  195148. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195149. {
  195150. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195151. png_crc_finish(png_ptr, length);
  195152. return;
  195153. }
  195154. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195155. {
  195156. png_warning(png_ptr, "Duplicate sCAL chunk");
  195157. png_crc_finish(png_ptr, length);
  195158. return;
  195159. }
  195160. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195161. length + 1);
  195162. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195163. if (buffer == NULL)
  195164. {
  195165. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195166. return;
  195167. }
  195168. slength = (png_size_t)length;
  195169. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195170. if (png_crc_finish(png_ptr, 0))
  195171. {
  195172. png_free(png_ptr, buffer);
  195173. return;
  195174. }
  195175. buffer[slength] = 0x00; /* null terminate the last string */
  195176. ep = buffer + 1; /* skip unit byte */
  195177. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195178. width = png_strtod(png_ptr, ep, &vp);
  195179. if (*vp)
  195180. {
  195181. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195182. return;
  195183. }
  195184. #else
  195185. #ifdef PNG_FIXED_POINT_SUPPORTED
  195186. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195187. if (swidth == NULL)
  195188. {
  195189. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195190. return;
  195191. }
  195192. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195193. #endif
  195194. #endif
  195195. for (ep = buffer; *ep; ep++)
  195196. /* empty loop */ ;
  195197. ep++;
  195198. if (buffer + slength < ep)
  195199. {
  195200. png_warning(png_ptr, "Truncated sCAL chunk");
  195201. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195202. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195203. png_free(png_ptr, swidth);
  195204. #endif
  195205. png_free(png_ptr, buffer);
  195206. return;
  195207. }
  195208. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195209. height = png_strtod(png_ptr, ep, &vp);
  195210. if (*vp)
  195211. {
  195212. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195213. return;
  195214. }
  195215. #else
  195216. #ifdef PNG_FIXED_POINT_SUPPORTED
  195217. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195218. if (swidth == NULL)
  195219. {
  195220. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195221. return;
  195222. }
  195223. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195224. #endif
  195225. #endif
  195226. if (buffer + slength < ep
  195227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195228. || width <= 0. || height <= 0.
  195229. #endif
  195230. )
  195231. {
  195232. png_warning(png_ptr, "Invalid sCAL data");
  195233. png_free(png_ptr, buffer);
  195234. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195235. png_free(png_ptr, swidth);
  195236. png_free(png_ptr, sheight);
  195237. #endif
  195238. return;
  195239. }
  195240. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195241. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195242. #else
  195243. #ifdef PNG_FIXED_POINT_SUPPORTED
  195244. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195245. #endif
  195246. #endif
  195247. png_free(png_ptr, buffer);
  195248. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195249. png_free(png_ptr, swidth);
  195250. png_free(png_ptr, sheight);
  195251. #endif
  195252. }
  195253. #endif
  195254. #if defined(PNG_READ_tIME_SUPPORTED)
  195255. void /* PRIVATE */
  195256. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195257. {
  195258. png_byte buf[7];
  195259. png_time mod_time;
  195260. png_debug(1, "in png_handle_tIME\n");
  195261. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195262. png_error(png_ptr, "Out of place tIME chunk");
  195263. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195264. {
  195265. png_warning(png_ptr, "Duplicate tIME chunk");
  195266. png_crc_finish(png_ptr, length);
  195267. return;
  195268. }
  195269. if (png_ptr->mode & PNG_HAVE_IDAT)
  195270. png_ptr->mode |= PNG_AFTER_IDAT;
  195271. if (length != 7)
  195272. {
  195273. png_warning(png_ptr, "Incorrect tIME chunk length");
  195274. png_crc_finish(png_ptr, length);
  195275. return;
  195276. }
  195277. png_crc_read(png_ptr, buf, 7);
  195278. if (png_crc_finish(png_ptr, 0))
  195279. return;
  195280. mod_time.second = buf[6];
  195281. mod_time.minute = buf[5];
  195282. mod_time.hour = buf[4];
  195283. mod_time.day = buf[3];
  195284. mod_time.month = buf[2];
  195285. mod_time.year = png_get_uint_16(buf);
  195286. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195287. }
  195288. #endif
  195289. #if defined(PNG_READ_tEXt_SUPPORTED)
  195290. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195291. void /* PRIVATE */
  195292. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195293. {
  195294. png_textp text_ptr;
  195295. png_charp key;
  195296. png_charp text;
  195297. png_uint_32 skip = 0;
  195298. png_size_t slength;
  195299. int ret;
  195300. png_debug(1, "in png_handle_tEXt\n");
  195301. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195302. png_error(png_ptr, "Missing IHDR before tEXt");
  195303. if (png_ptr->mode & PNG_HAVE_IDAT)
  195304. png_ptr->mode |= PNG_AFTER_IDAT;
  195305. #ifdef PNG_MAX_MALLOC_64K
  195306. if (length > (png_uint_32)65535L)
  195307. {
  195308. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195309. skip = length - (png_uint_32)65535L;
  195310. length = (png_uint_32)65535L;
  195311. }
  195312. #endif
  195313. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195314. if (key == NULL)
  195315. {
  195316. png_warning(png_ptr, "No memory to process text chunk.");
  195317. return;
  195318. }
  195319. slength = (png_size_t)length;
  195320. png_crc_read(png_ptr, (png_bytep)key, slength);
  195321. if (png_crc_finish(png_ptr, skip))
  195322. {
  195323. png_free(png_ptr, key);
  195324. return;
  195325. }
  195326. key[slength] = 0x00;
  195327. for (text = key; *text; text++)
  195328. /* empty loop to find end of key */ ;
  195329. if (text != key + slength)
  195330. text++;
  195331. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195332. (png_uint_32)png_sizeof(png_text));
  195333. if (text_ptr == NULL)
  195334. {
  195335. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195336. png_free(png_ptr, key);
  195337. return;
  195338. }
  195339. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195340. text_ptr->key = key;
  195341. #ifdef PNG_iTXt_SUPPORTED
  195342. text_ptr->lang = NULL;
  195343. text_ptr->lang_key = NULL;
  195344. text_ptr->itxt_length = 0;
  195345. #endif
  195346. text_ptr->text = text;
  195347. text_ptr->text_length = png_strlen(text);
  195348. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195349. png_free(png_ptr, key);
  195350. png_free(png_ptr, text_ptr);
  195351. if (ret)
  195352. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195353. }
  195354. #endif
  195355. #if defined(PNG_READ_zTXt_SUPPORTED)
  195356. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195357. void /* PRIVATE */
  195358. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195359. {
  195360. png_textp text_ptr;
  195361. png_charp chunkdata;
  195362. png_charp text;
  195363. int comp_type;
  195364. int ret;
  195365. png_size_t slength, prefix_len, data_len;
  195366. png_debug(1, "in png_handle_zTXt\n");
  195367. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195368. png_error(png_ptr, "Missing IHDR before zTXt");
  195369. if (png_ptr->mode & PNG_HAVE_IDAT)
  195370. png_ptr->mode |= PNG_AFTER_IDAT;
  195371. #ifdef PNG_MAX_MALLOC_64K
  195372. /* We will no doubt have problems with chunks even half this size, but
  195373. there is no hard and fast rule to tell us where to stop. */
  195374. if (length > (png_uint_32)65535L)
  195375. {
  195376. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195377. png_crc_finish(png_ptr, length);
  195378. return;
  195379. }
  195380. #endif
  195381. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195382. if (chunkdata == NULL)
  195383. {
  195384. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195385. return;
  195386. }
  195387. slength = (png_size_t)length;
  195388. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195389. if (png_crc_finish(png_ptr, 0))
  195390. {
  195391. png_free(png_ptr, chunkdata);
  195392. return;
  195393. }
  195394. chunkdata[slength] = 0x00;
  195395. for (text = chunkdata; *text; text++)
  195396. /* empty loop */ ;
  195397. /* zTXt must have some text after the chunkdataword */
  195398. if (text >= chunkdata + slength - 2)
  195399. {
  195400. png_warning(png_ptr, "Truncated zTXt chunk");
  195401. png_free(png_ptr, chunkdata);
  195402. return;
  195403. }
  195404. else
  195405. {
  195406. comp_type = *(++text);
  195407. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195408. {
  195409. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195410. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195411. }
  195412. text++; /* skip the compression_method byte */
  195413. }
  195414. prefix_len = text - chunkdata;
  195415. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195416. (png_size_t)length, prefix_len, &data_len);
  195417. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195418. (png_uint_32)png_sizeof(png_text));
  195419. if (text_ptr == NULL)
  195420. {
  195421. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195422. png_free(png_ptr, chunkdata);
  195423. return;
  195424. }
  195425. text_ptr->compression = comp_type;
  195426. text_ptr->key = chunkdata;
  195427. #ifdef PNG_iTXt_SUPPORTED
  195428. text_ptr->lang = NULL;
  195429. text_ptr->lang_key = NULL;
  195430. text_ptr->itxt_length = 0;
  195431. #endif
  195432. text_ptr->text = chunkdata + prefix_len;
  195433. text_ptr->text_length = data_len;
  195434. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195435. png_free(png_ptr, text_ptr);
  195436. png_free(png_ptr, chunkdata);
  195437. if (ret)
  195438. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195439. }
  195440. #endif
  195441. #if defined(PNG_READ_iTXt_SUPPORTED)
  195442. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195443. void /* PRIVATE */
  195444. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195445. {
  195446. png_textp text_ptr;
  195447. png_charp chunkdata;
  195448. png_charp key, lang, text, lang_key;
  195449. int comp_flag;
  195450. int comp_type = 0;
  195451. int ret;
  195452. png_size_t slength, prefix_len, data_len;
  195453. png_debug(1, "in png_handle_iTXt\n");
  195454. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195455. png_error(png_ptr, "Missing IHDR before iTXt");
  195456. if (png_ptr->mode & PNG_HAVE_IDAT)
  195457. png_ptr->mode |= PNG_AFTER_IDAT;
  195458. #ifdef PNG_MAX_MALLOC_64K
  195459. /* We will no doubt have problems with chunks even half this size, but
  195460. there is no hard and fast rule to tell us where to stop. */
  195461. if (length > (png_uint_32)65535L)
  195462. {
  195463. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195464. png_crc_finish(png_ptr, length);
  195465. return;
  195466. }
  195467. #endif
  195468. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195469. if (chunkdata == NULL)
  195470. {
  195471. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195472. return;
  195473. }
  195474. slength = (png_size_t)length;
  195475. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195476. if (png_crc_finish(png_ptr, 0))
  195477. {
  195478. png_free(png_ptr, chunkdata);
  195479. return;
  195480. }
  195481. chunkdata[slength] = 0x00;
  195482. for (lang = chunkdata; *lang; lang++)
  195483. /* empty loop */ ;
  195484. lang++; /* skip NUL separator */
  195485. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195486. translated keyword (possibly empty), and possibly some text after the
  195487. keyword */
  195488. if (lang >= chunkdata + slength - 3)
  195489. {
  195490. png_warning(png_ptr, "Truncated iTXt chunk");
  195491. png_free(png_ptr, chunkdata);
  195492. return;
  195493. }
  195494. else
  195495. {
  195496. comp_flag = *lang++;
  195497. comp_type = *lang++;
  195498. }
  195499. for (lang_key = lang; *lang_key; lang_key++)
  195500. /* empty loop */ ;
  195501. lang_key++; /* skip NUL separator */
  195502. if (lang_key >= chunkdata + slength)
  195503. {
  195504. png_warning(png_ptr, "Truncated iTXt chunk");
  195505. png_free(png_ptr, chunkdata);
  195506. return;
  195507. }
  195508. for (text = lang_key; *text; text++)
  195509. /* empty loop */ ;
  195510. text++; /* skip NUL separator */
  195511. if (text >= chunkdata + slength)
  195512. {
  195513. png_warning(png_ptr, "Malformed iTXt chunk");
  195514. png_free(png_ptr, chunkdata);
  195515. return;
  195516. }
  195517. prefix_len = text - chunkdata;
  195518. key=chunkdata;
  195519. if (comp_flag)
  195520. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195521. (size_t)length, prefix_len, &data_len);
  195522. else
  195523. data_len=png_strlen(chunkdata + prefix_len);
  195524. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195525. (png_uint_32)png_sizeof(png_text));
  195526. if (text_ptr == NULL)
  195527. {
  195528. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195529. png_free(png_ptr, chunkdata);
  195530. return;
  195531. }
  195532. text_ptr->compression = (int)comp_flag + 1;
  195533. text_ptr->lang_key = chunkdata+(lang_key-key);
  195534. text_ptr->lang = chunkdata+(lang-key);
  195535. text_ptr->itxt_length = data_len;
  195536. text_ptr->text_length = 0;
  195537. text_ptr->key = chunkdata;
  195538. text_ptr->text = chunkdata + prefix_len;
  195539. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195540. png_free(png_ptr, text_ptr);
  195541. png_free(png_ptr, chunkdata);
  195542. if (ret)
  195543. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195544. }
  195545. #endif
  195546. /* This function is called when we haven't found a handler for a
  195547. chunk. If there isn't a problem with the chunk itself (ie bad
  195548. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195549. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195550. case it will be saved away to be written out later. */
  195551. void /* PRIVATE */
  195552. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195553. {
  195554. png_uint_32 skip = 0;
  195555. png_debug(1, "in png_handle_unknown\n");
  195556. if (png_ptr->mode & PNG_HAVE_IDAT)
  195557. {
  195558. #ifdef PNG_USE_LOCAL_ARRAYS
  195559. PNG_CONST PNG_IDAT;
  195560. #endif
  195561. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195562. png_ptr->mode |= PNG_AFTER_IDAT;
  195563. }
  195564. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195565. if (!(png_ptr->chunk_name[0] & 0x20))
  195566. {
  195567. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195568. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195569. PNG_HANDLE_CHUNK_ALWAYS
  195570. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195571. && png_ptr->read_user_chunk_fn == NULL
  195572. #endif
  195573. )
  195574. #endif
  195575. png_chunk_error(png_ptr, "unknown critical chunk");
  195576. }
  195577. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195578. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195579. (png_ptr->read_user_chunk_fn != NULL))
  195580. {
  195581. #ifdef PNG_MAX_MALLOC_64K
  195582. if (length > (png_uint_32)65535L)
  195583. {
  195584. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195585. skip = length - (png_uint_32)65535L;
  195586. length = (png_uint_32)65535L;
  195587. }
  195588. #endif
  195589. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195590. (png_charp)png_ptr->chunk_name, 5);
  195591. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195592. png_ptr->unknown_chunk.size = (png_size_t)length;
  195593. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195594. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195595. if(png_ptr->read_user_chunk_fn != NULL)
  195596. {
  195597. /* callback to user unknown chunk handler */
  195598. int ret;
  195599. ret = (*(png_ptr->read_user_chunk_fn))
  195600. (png_ptr, &png_ptr->unknown_chunk);
  195601. if (ret < 0)
  195602. png_chunk_error(png_ptr, "error in user chunk");
  195603. if (ret == 0)
  195604. {
  195605. if (!(png_ptr->chunk_name[0] & 0x20))
  195606. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195607. PNG_HANDLE_CHUNK_ALWAYS)
  195608. png_chunk_error(png_ptr, "unknown critical chunk");
  195609. png_set_unknown_chunks(png_ptr, info_ptr,
  195610. &png_ptr->unknown_chunk, 1);
  195611. }
  195612. }
  195613. #else
  195614. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195615. #endif
  195616. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195617. png_ptr->unknown_chunk.data = NULL;
  195618. }
  195619. else
  195620. #endif
  195621. skip = length;
  195622. png_crc_finish(png_ptr, skip);
  195623. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195624. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195625. #endif
  195626. }
  195627. /* This function is called to verify that a chunk name is valid.
  195628. This function can't have the "critical chunk check" incorporated
  195629. into it, since in the future we will need to be able to call user
  195630. functions to handle unknown critical chunks after we check that
  195631. the chunk name itself is valid. */
  195632. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195633. void /* PRIVATE */
  195634. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195635. {
  195636. png_debug(1, "in png_check_chunk_name\n");
  195637. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195638. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195639. {
  195640. png_chunk_error(png_ptr, "invalid chunk type");
  195641. }
  195642. }
  195643. /* Combines the row recently read in with the existing pixels in the
  195644. row. This routine takes care of alpha and transparency if requested.
  195645. This routine also handles the two methods of progressive display
  195646. of interlaced images, depending on the mask value.
  195647. The mask value describes which pixels are to be combined with
  195648. the row. The pattern always repeats every 8 pixels, so just 8
  195649. bits are needed. A one indicates the pixel is to be combined,
  195650. a zero indicates the pixel is to be skipped. This is in addition
  195651. to any alpha or transparency value associated with the pixel. If
  195652. you want all pixels to be combined, pass 0xff (255) in mask. */
  195653. void /* PRIVATE */
  195654. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195655. {
  195656. png_debug(1,"in png_combine_row\n");
  195657. if (mask == 0xff)
  195658. {
  195659. png_memcpy(row, png_ptr->row_buf + 1,
  195660. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195661. }
  195662. else
  195663. {
  195664. switch (png_ptr->row_info.pixel_depth)
  195665. {
  195666. case 1:
  195667. {
  195668. png_bytep sp = png_ptr->row_buf + 1;
  195669. png_bytep dp = row;
  195670. int s_inc, s_start, s_end;
  195671. int m = 0x80;
  195672. int shift;
  195673. png_uint_32 i;
  195674. png_uint_32 row_width = png_ptr->width;
  195675. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195676. if (png_ptr->transformations & PNG_PACKSWAP)
  195677. {
  195678. s_start = 0;
  195679. s_end = 7;
  195680. s_inc = 1;
  195681. }
  195682. else
  195683. #endif
  195684. {
  195685. s_start = 7;
  195686. s_end = 0;
  195687. s_inc = -1;
  195688. }
  195689. shift = s_start;
  195690. for (i = 0; i < row_width; i++)
  195691. {
  195692. if (m & mask)
  195693. {
  195694. int value;
  195695. value = (*sp >> shift) & 0x01;
  195696. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  195697. *dp |= (png_byte)(value << shift);
  195698. }
  195699. if (shift == s_end)
  195700. {
  195701. shift = s_start;
  195702. sp++;
  195703. dp++;
  195704. }
  195705. else
  195706. shift += s_inc;
  195707. if (m == 1)
  195708. m = 0x80;
  195709. else
  195710. m >>= 1;
  195711. }
  195712. break;
  195713. }
  195714. case 2:
  195715. {
  195716. png_bytep sp = png_ptr->row_buf + 1;
  195717. png_bytep dp = row;
  195718. int s_start, s_end, s_inc;
  195719. int m = 0x80;
  195720. int shift;
  195721. png_uint_32 i;
  195722. png_uint_32 row_width = png_ptr->width;
  195723. int value;
  195724. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195725. if (png_ptr->transformations & PNG_PACKSWAP)
  195726. {
  195727. s_start = 0;
  195728. s_end = 6;
  195729. s_inc = 2;
  195730. }
  195731. else
  195732. #endif
  195733. {
  195734. s_start = 6;
  195735. s_end = 0;
  195736. s_inc = -2;
  195737. }
  195738. shift = s_start;
  195739. for (i = 0; i < row_width; i++)
  195740. {
  195741. if (m & mask)
  195742. {
  195743. value = (*sp >> shift) & 0x03;
  195744. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  195745. *dp |= (png_byte)(value << shift);
  195746. }
  195747. if (shift == s_end)
  195748. {
  195749. shift = s_start;
  195750. sp++;
  195751. dp++;
  195752. }
  195753. else
  195754. shift += s_inc;
  195755. if (m == 1)
  195756. m = 0x80;
  195757. else
  195758. m >>= 1;
  195759. }
  195760. break;
  195761. }
  195762. case 4:
  195763. {
  195764. png_bytep sp = png_ptr->row_buf + 1;
  195765. png_bytep dp = row;
  195766. int s_start, s_end, s_inc;
  195767. int m = 0x80;
  195768. int shift;
  195769. png_uint_32 i;
  195770. png_uint_32 row_width = png_ptr->width;
  195771. int value;
  195772. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195773. if (png_ptr->transformations & PNG_PACKSWAP)
  195774. {
  195775. s_start = 0;
  195776. s_end = 4;
  195777. s_inc = 4;
  195778. }
  195779. else
  195780. #endif
  195781. {
  195782. s_start = 4;
  195783. s_end = 0;
  195784. s_inc = -4;
  195785. }
  195786. shift = s_start;
  195787. for (i = 0; i < row_width; i++)
  195788. {
  195789. if (m & mask)
  195790. {
  195791. value = (*sp >> shift) & 0xf;
  195792. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  195793. *dp |= (png_byte)(value << shift);
  195794. }
  195795. if (shift == s_end)
  195796. {
  195797. shift = s_start;
  195798. sp++;
  195799. dp++;
  195800. }
  195801. else
  195802. shift += s_inc;
  195803. if (m == 1)
  195804. m = 0x80;
  195805. else
  195806. m >>= 1;
  195807. }
  195808. break;
  195809. }
  195810. default:
  195811. {
  195812. png_bytep sp = png_ptr->row_buf + 1;
  195813. png_bytep dp = row;
  195814. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  195815. png_uint_32 i;
  195816. png_uint_32 row_width = png_ptr->width;
  195817. png_byte m = 0x80;
  195818. for (i = 0; i < row_width; i++)
  195819. {
  195820. if (m & mask)
  195821. {
  195822. png_memcpy(dp, sp, pixel_bytes);
  195823. }
  195824. sp += pixel_bytes;
  195825. dp += pixel_bytes;
  195826. if (m == 1)
  195827. m = 0x80;
  195828. else
  195829. m >>= 1;
  195830. }
  195831. break;
  195832. }
  195833. }
  195834. }
  195835. }
  195836. #ifdef PNG_READ_INTERLACING_SUPPORTED
  195837. /* OLD pre-1.0.9 interface:
  195838. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  195839. png_uint_32 transformations)
  195840. */
  195841. void /* PRIVATE */
  195842. png_do_read_interlace(png_structp png_ptr)
  195843. {
  195844. png_row_infop row_info = &(png_ptr->row_info);
  195845. png_bytep row = png_ptr->row_buf + 1;
  195846. int pass = png_ptr->pass;
  195847. png_uint_32 transformations = png_ptr->transformations;
  195848. #ifdef PNG_USE_LOCAL_ARRAYS
  195849. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195850. /* offset to next interlace block */
  195851. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195852. #endif
  195853. png_debug(1,"in png_do_read_interlace\n");
  195854. if (row != NULL && row_info != NULL)
  195855. {
  195856. png_uint_32 final_width;
  195857. final_width = row_info->width * png_pass_inc[pass];
  195858. switch (row_info->pixel_depth)
  195859. {
  195860. case 1:
  195861. {
  195862. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  195863. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  195864. int sshift, dshift;
  195865. int s_start, s_end, s_inc;
  195866. int jstop = png_pass_inc[pass];
  195867. png_byte v;
  195868. png_uint_32 i;
  195869. int j;
  195870. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195871. if (transformations & PNG_PACKSWAP)
  195872. {
  195873. sshift = (int)((row_info->width + 7) & 0x07);
  195874. dshift = (int)((final_width + 7) & 0x07);
  195875. s_start = 7;
  195876. s_end = 0;
  195877. s_inc = -1;
  195878. }
  195879. else
  195880. #endif
  195881. {
  195882. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  195883. dshift = 7 - (int)((final_width + 7) & 0x07);
  195884. s_start = 0;
  195885. s_end = 7;
  195886. s_inc = 1;
  195887. }
  195888. for (i = 0; i < row_info->width; i++)
  195889. {
  195890. v = (png_byte)((*sp >> sshift) & 0x01);
  195891. for (j = 0; j < jstop; j++)
  195892. {
  195893. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  195894. *dp |= (png_byte)(v << dshift);
  195895. if (dshift == s_end)
  195896. {
  195897. dshift = s_start;
  195898. dp--;
  195899. }
  195900. else
  195901. dshift += s_inc;
  195902. }
  195903. if (sshift == s_end)
  195904. {
  195905. sshift = s_start;
  195906. sp--;
  195907. }
  195908. else
  195909. sshift += s_inc;
  195910. }
  195911. break;
  195912. }
  195913. case 2:
  195914. {
  195915. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  195916. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  195917. int sshift, dshift;
  195918. int s_start, s_end, s_inc;
  195919. int jstop = png_pass_inc[pass];
  195920. png_uint_32 i;
  195921. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195922. if (transformations & PNG_PACKSWAP)
  195923. {
  195924. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  195925. dshift = (int)(((final_width + 3) & 0x03) << 1);
  195926. s_start = 6;
  195927. s_end = 0;
  195928. s_inc = -2;
  195929. }
  195930. else
  195931. #endif
  195932. {
  195933. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  195934. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  195935. s_start = 0;
  195936. s_end = 6;
  195937. s_inc = 2;
  195938. }
  195939. for (i = 0; i < row_info->width; i++)
  195940. {
  195941. png_byte v;
  195942. int j;
  195943. v = (png_byte)((*sp >> sshift) & 0x03);
  195944. for (j = 0; j < jstop; j++)
  195945. {
  195946. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  195947. *dp |= (png_byte)(v << dshift);
  195948. if (dshift == s_end)
  195949. {
  195950. dshift = s_start;
  195951. dp--;
  195952. }
  195953. else
  195954. dshift += s_inc;
  195955. }
  195956. if (sshift == s_end)
  195957. {
  195958. sshift = s_start;
  195959. sp--;
  195960. }
  195961. else
  195962. sshift += s_inc;
  195963. }
  195964. break;
  195965. }
  195966. case 4:
  195967. {
  195968. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  195969. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  195970. int sshift, dshift;
  195971. int s_start, s_end, s_inc;
  195972. png_uint_32 i;
  195973. int jstop = png_pass_inc[pass];
  195974. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  195975. if (transformations & PNG_PACKSWAP)
  195976. {
  195977. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  195978. dshift = (int)(((final_width + 1) & 0x01) << 2);
  195979. s_start = 4;
  195980. s_end = 0;
  195981. s_inc = -4;
  195982. }
  195983. else
  195984. #endif
  195985. {
  195986. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  195987. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  195988. s_start = 0;
  195989. s_end = 4;
  195990. s_inc = 4;
  195991. }
  195992. for (i = 0; i < row_info->width; i++)
  195993. {
  195994. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  195995. int j;
  195996. for (j = 0; j < jstop; j++)
  195997. {
  195998. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  195999. *dp |= (png_byte)(v << dshift);
  196000. if (dshift == s_end)
  196001. {
  196002. dshift = s_start;
  196003. dp--;
  196004. }
  196005. else
  196006. dshift += s_inc;
  196007. }
  196008. if (sshift == s_end)
  196009. {
  196010. sshift = s_start;
  196011. sp--;
  196012. }
  196013. else
  196014. sshift += s_inc;
  196015. }
  196016. break;
  196017. }
  196018. default:
  196019. {
  196020. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196021. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196022. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196023. int jstop = png_pass_inc[pass];
  196024. png_uint_32 i;
  196025. for (i = 0; i < row_info->width; i++)
  196026. {
  196027. png_byte v[8];
  196028. int j;
  196029. png_memcpy(v, sp, pixel_bytes);
  196030. for (j = 0; j < jstop; j++)
  196031. {
  196032. png_memcpy(dp, v, pixel_bytes);
  196033. dp -= pixel_bytes;
  196034. }
  196035. sp -= pixel_bytes;
  196036. }
  196037. break;
  196038. }
  196039. }
  196040. row_info->width = final_width;
  196041. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196042. }
  196043. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196044. transformations = transformations; /* silence compiler warning */
  196045. #endif
  196046. }
  196047. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196048. void /* PRIVATE */
  196049. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196050. png_bytep prev_row, int filter)
  196051. {
  196052. png_debug(1, "in png_read_filter_row\n");
  196053. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196054. switch (filter)
  196055. {
  196056. case PNG_FILTER_VALUE_NONE:
  196057. break;
  196058. case PNG_FILTER_VALUE_SUB:
  196059. {
  196060. png_uint_32 i;
  196061. png_uint_32 istop = row_info->rowbytes;
  196062. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196063. png_bytep rp = row + bpp;
  196064. png_bytep lp = row;
  196065. for (i = bpp; i < istop; i++)
  196066. {
  196067. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196068. rp++;
  196069. }
  196070. break;
  196071. }
  196072. case PNG_FILTER_VALUE_UP:
  196073. {
  196074. png_uint_32 i;
  196075. png_uint_32 istop = row_info->rowbytes;
  196076. png_bytep rp = row;
  196077. png_bytep pp = prev_row;
  196078. for (i = 0; i < istop; i++)
  196079. {
  196080. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196081. rp++;
  196082. }
  196083. break;
  196084. }
  196085. case PNG_FILTER_VALUE_AVG:
  196086. {
  196087. png_uint_32 i;
  196088. png_bytep rp = row;
  196089. png_bytep pp = prev_row;
  196090. png_bytep lp = row;
  196091. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196092. png_uint_32 istop = row_info->rowbytes - bpp;
  196093. for (i = 0; i < bpp; i++)
  196094. {
  196095. *rp = (png_byte)(((int)(*rp) +
  196096. ((int)(*pp++) / 2 )) & 0xff);
  196097. rp++;
  196098. }
  196099. for (i = 0; i < istop; i++)
  196100. {
  196101. *rp = (png_byte)(((int)(*rp) +
  196102. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196103. rp++;
  196104. }
  196105. break;
  196106. }
  196107. case PNG_FILTER_VALUE_PAETH:
  196108. {
  196109. png_uint_32 i;
  196110. png_bytep rp = row;
  196111. png_bytep pp = prev_row;
  196112. png_bytep lp = row;
  196113. png_bytep cp = prev_row;
  196114. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196115. png_uint_32 istop=row_info->rowbytes - bpp;
  196116. for (i = 0; i < bpp; i++)
  196117. {
  196118. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196119. rp++;
  196120. }
  196121. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196122. {
  196123. int a, b, c, pa, pb, pc, p;
  196124. a = *lp++;
  196125. b = *pp++;
  196126. c = *cp++;
  196127. p = b - c;
  196128. pc = a - c;
  196129. #ifdef PNG_USE_ABS
  196130. pa = abs(p);
  196131. pb = abs(pc);
  196132. pc = abs(p + pc);
  196133. #else
  196134. pa = p < 0 ? -p : p;
  196135. pb = pc < 0 ? -pc : pc;
  196136. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196137. #endif
  196138. /*
  196139. if (pa <= pb && pa <= pc)
  196140. p = a;
  196141. else if (pb <= pc)
  196142. p = b;
  196143. else
  196144. p = c;
  196145. */
  196146. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196147. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196148. rp++;
  196149. }
  196150. break;
  196151. }
  196152. default:
  196153. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196154. *row=0;
  196155. break;
  196156. }
  196157. }
  196158. void /* PRIVATE */
  196159. png_read_finish_row(png_structp png_ptr)
  196160. {
  196161. #ifdef PNG_USE_LOCAL_ARRAYS
  196162. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196163. /* start of interlace block */
  196164. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196165. /* offset to next interlace block */
  196166. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196167. /* start of interlace block in the y direction */
  196168. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196169. /* offset to next interlace block in the y direction */
  196170. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196171. #endif
  196172. png_debug(1, "in png_read_finish_row\n");
  196173. png_ptr->row_number++;
  196174. if (png_ptr->row_number < png_ptr->num_rows)
  196175. return;
  196176. if (png_ptr->interlaced)
  196177. {
  196178. png_ptr->row_number = 0;
  196179. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196180. png_ptr->rowbytes + 1);
  196181. do
  196182. {
  196183. png_ptr->pass++;
  196184. if (png_ptr->pass >= 7)
  196185. break;
  196186. png_ptr->iwidth = (png_ptr->width +
  196187. png_pass_inc[png_ptr->pass] - 1 -
  196188. png_pass_start[png_ptr->pass]) /
  196189. png_pass_inc[png_ptr->pass];
  196190. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196191. png_ptr->iwidth) + 1;
  196192. if (!(png_ptr->transformations & PNG_INTERLACE))
  196193. {
  196194. png_ptr->num_rows = (png_ptr->height +
  196195. png_pass_yinc[png_ptr->pass] - 1 -
  196196. png_pass_ystart[png_ptr->pass]) /
  196197. png_pass_yinc[png_ptr->pass];
  196198. if (!(png_ptr->num_rows))
  196199. continue;
  196200. }
  196201. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196202. break;
  196203. } while (png_ptr->iwidth == 0);
  196204. if (png_ptr->pass < 7)
  196205. return;
  196206. }
  196207. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196208. {
  196209. #ifdef PNG_USE_LOCAL_ARRAYS
  196210. PNG_CONST PNG_IDAT;
  196211. #endif
  196212. char extra;
  196213. int ret;
  196214. png_ptr->zstream.next_out = (Bytef *)&extra;
  196215. png_ptr->zstream.avail_out = (uInt)1;
  196216. for(;;)
  196217. {
  196218. if (!(png_ptr->zstream.avail_in))
  196219. {
  196220. while (!png_ptr->idat_size)
  196221. {
  196222. png_byte chunk_length[4];
  196223. png_crc_finish(png_ptr, 0);
  196224. png_read_data(png_ptr, chunk_length, 4);
  196225. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196226. png_reset_crc(png_ptr);
  196227. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196228. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196229. png_error(png_ptr, "Not enough image data");
  196230. }
  196231. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196232. png_ptr->zstream.next_in = png_ptr->zbuf;
  196233. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196234. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196235. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196236. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196237. }
  196238. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196239. if (ret == Z_STREAM_END)
  196240. {
  196241. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196242. png_ptr->idat_size)
  196243. png_warning(png_ptr, "Extra compressed data");
  196244. png_ptr->mode |= PNG_AFTER_IDAT;
  196245. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196246. break;
  196247. }
  196248. if (ret != Z_OK)
  196249. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196250. "Decompression Error");
  196251. if (!(png_ptr->zstream.avail_out))
  196252. {
  196253. png_warning(png_ptr, "Extra compressed data.");
  196254. png_ptr->mode |= PNG_AFTER_IDAT;
  196255. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196256. break;
  196257. }
  196258. }
  196259. png_ptr->zstream.avail_out = 0;
  196260. }
  196261. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196262. png_warning(png_ptr, "Extra compression data");
  196263. inflateReset(&png_ptr->zstream);
  196264. png_ptr->mode |= PNG_AFTER_IDAT;
  196265. }
  196266. void /* PRIVATE */
  196267. png_read_start_row(png_structp png_ptr)
  196268. {
  196269. #ifdef PNG_USE_LOCAL_ARRAYS
  196270. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196271. /* start of interlace block */
  196272. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196273. /* offset to next interlace block */
  196274. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196275. /* start of interlace block in the y direction */
  196276. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196277. /* offset to next interlace block in the y direction */
  196278. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196279. #endif
  196280. int max_pixel_depth;
  196281. png_uint_32 row_bytes;
  196282. png_debug(1, "in png_read_start_row\n");
  196283. png_ptr->zstream.avail_in = 0;
  196284. png_init_read_transformations(png_ptr);
  196285. if (png_ptr->interlaced)
  196286. {
  196287. if (!(png_ptr->transformations & PNG_INTERLACE))
  196288. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196289. png_pass_ystart[0]) / png_pass_yinc[0];
  196290. else
  196291. png_ptr->num_rows = png_ptr->height;
  196292. png_ptr->iwidth = (png_ptr->width +
  196293. png_pass_inc[png_ptr->pass] - 1 -
  196294. png_pass_start[png_ptr->pass]) /
  196295. png_pass_inc[png_ptr->pass];
  196296. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196297. png_ptr->irowbytes = (png_size_t)row_bytes;
  196298. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196299. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196300. }
  196301. else
  196302. {
  196303. png_ptr->num_rows = png_ptr->height;
  196304. png_ptr->iwidth = png_ptr->width;
  196305. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196306. }
  196307. max_pixel_depth = png_ptr->pixel_depth;
  196308. #if defined(PNG_READ_PACK_SUPPORTED)
  196309. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196310. max_pixel_depth = 8;
  196311. #endif
  196312. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196313. if (png_ptr->transformations & PNG_EXPAND)
  196314. {
  196315. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196316. {
  196317. if (png_ptr->num_trans)
  196318. max_pixel_depth = 32;
  196319. else
  196320. max_pixel_depth = 24;
  196321. }
  196322. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196323. {
  196324. if (max_pixel_depth < 8)
  196325. max_pixel_depth = 8;
  196326. if (png_ptr->num_trans)
  196327. max_pixel_depth *= 2;
  196328. }
  196329. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196330. {
  196331. if (png_ptr->num_trans)
  196332. {
  196333. max_pixel_depth *= 4;
  196334. max_pixel_depth /= 3;
  196335. }
  196336. }
  196337. }
  196338. #endif
  196339. #if defined(PNG_READ_FILLER_SUPPORTED)
  196340. if (png_ptr->transformations & (PNG_FILLER))
  196341. {
  196342. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196343. max_pixel_depth = 32;
  196344. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196345. {
  196346. if (max_pixel_depth <= 8)
  196347. max_pixel_depth = 16;
  196348. else
  196349. max_pixel_depth = 32;
  196350. }
  196351. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196352. {
  196353. if (max_pixel_depth <= 32)
  196354. max_pixel_depth = 32;
  196355. else
  196356. max_pixel_depth = 64;
  196357. }
  196358. }
  196359. #endif
  196360. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196361. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196362. {
  196363. if (
  196364. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196365. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196366. #endif
  196367. #if defined(PNG_READ_FILLER_SUPPORTED)
  196368. (png_ptr->transformations & (PNG_FILLER)) ||
  196369. #endif
  196370. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196371. {
  196372. if (max_pixel_depth <= 16)
  196373. max_pixel_depth = 32;
  196374. else
  196375. max_pixel_depth = 64;
  196376. }
  196377. else
  196378. {
  196379. if (max_pixel_depth <= 8)
  196380. {
  196381. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196382. max_pixel_depth = 32;
  196383. else
  196384. max_pixel_depth = 24;
  196385. }
  196386. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196387. max_pixel_depth = 64;
  196388. else
  196389. max_pixel_depth = 48;
  196390. }
  196391. }
  196392. #endif
  196393. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196394. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196395. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196396. {
  196397. int user_pixel_depth=png_ptr->user_transform_depth*
  196398. png_ptr->user_transform_channels;
  196399. if(user_pixel_depth > max_pixel_depth)
  196400. max_pixel_depth=user_pixel_depth;
  196401. }
  196402. #endif
  196403. /* align the width on the next larger 8 pixels. Mainly used
  196404. for interlacing */
  196405. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196406. /* calculate the maximum bytes needed, adding a byte and a pixel
  196407. for safety's sake */
  196408. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196409. 1 + ((max_pixel_depth + 7) >> 3);
  196410. #ifdef PNG_MAX_MALLOC_64K
  196411. if (row_bytes > (png_uint_32)65536L)
  196412. png_error(png_ptr, "This image requires a row greater than 64KB");
  196413. #endif
  196414. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196415. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196416. #ifdef PNG_MAX_MALLOC_64K
  196417. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196418. png_error(png_ptr, "This image requires a row greater than 64KB");
  196419. #endif
  196420. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196421. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196422. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196423. png_ptr->rowbytes + 1));
  196424. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196425. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196426. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196427. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196428. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196429. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196430. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196431. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196432. }
  196433. #endif /* PNG_READ_SUPPORTED */
  196434. /*** End of inlined file: pngrutil.c ***/
  196435. /*** Start of inlined file: pngset.c ***/
  196436. /* pngset.c - storage of image information into info struct
  196437. *
  196438. * Last changed in libpng 1.2.21 [October 4, 2007]
  196439. * For conditions of distribution and use, see copyright notice in png.h
  196440. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196441. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196442. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196443. *
  196444. * The functions here are used during reads to store data from the file
  196445. * into the info struct, and during writes to store application data
  196446. * into the info struct for writing into the file. This abstracts the
  196447. * info struct and allows us to change the structure in the future.
  196448. */
  196449. #define PNG_INTERNAL
  196450. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196451. #if defined(PNG_bKGD_SUPPORTED)
  196452. void PNGAPI
  196453. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196454. {
  196455. png_debug1(1, "in %s storage function\n", "bKGD");
  196456. if (png_ptr == NULL || info_ptr == NULL)
  196457. return;
  196458. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196459. info_ptr->valid |= PNG_INFO_bKGD;
  196460. }
  196461. #endif
  196462. #if defined(PNG_cHRM_SUPPORTED)
  196463. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196464. void PNGAPI
  196465. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196466. double white_x, double white_y, double red_x, double red_y,
  196467. double green_x, double green_y, double blue_x, double blue_y)
  196468. {
  196469. png_debug1(1, "in %s storage function\n", "cHRM");
  196470. if (png_ptr == NULL || info_ptr == NULL)
  196471. return;
  196472. if (white_x < 0.0 || white_y < 0.0 ||
  196473. red_x < 0.0 || red_y < 0.0 ||
  196474. green_x < 0.0 || green_y < 0.0 ||
  196475. blue_x < 0.0 || blue_y < 0.0)
  196476. {
  196477. png_warning(png_ptr,
  196478. "Ignoring attempt to set negative chromaticity value");
  196479. return;
  196480. }
  196481. if (white_x > 21474.83 || white_y > 21474.83 ||
  196482. red_x > 21474.83 || red_y > 21474.83 ||
  196483. green_x > 21474.83 || green_y > 21474.83 ||
  196484. blue_x > 21474.83 || blue_y > 21474.83)
  196485. {
  196486. png_warning(png_ptr,
  196487. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196488. return;
  196489. }
  196490. info_ptr->x_white = (float)white_x;
  196491. info_ptr->y_white = (float)white_y;
  196492. info_ptr->x_red = (float)red_x;
  196493. info_ptr->y_red = (float)red_y;
  196494. info_ptr->x_green = (float)green_x;
  196495. info_ptr->y_green = (float)green_y;
  196496. info_ptr->x_blue = (float)blue_x;
  196497. info_ptr->y_blue = (float)blue_y;
  196498. #ifdef PNG_FIXED_POINT_SUPPORTED
  196499. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196500. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196501. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196502. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196503. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196504. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196505. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196506. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196507. #endif
  196508. info_ptr->valid |= PNG_INFO_cHRM;
  196509. }
  196510. #endif
  196511. #ifdef PNG_FIXED_POINT_SUPPORTED
  196512. void PNGAPI
  196513. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196514. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196515. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196516. png_fixed_point blue_x, png_fixed_point blue_y)
  196517. {
  196518. png_debug1(1, "in %s storage function\n", "cHRM");
  196519. if (png_ptr == NULL || info_ptr == NULL)
  196520. return;
  196521. if (white_x < 0 || white_y < 0 ||
  196522. red_x < 0 || red_y < 0 ||
  196523. green_x < 0 || green_y < 0 ||
  196524. blue_x < 0 || blue_y < 0)
  196525. {
  196526. png_warning(png_ptr,
  196527. "Ignoring attempt to set negative chromaticity value");
  196528. return;
  196529. }
  196530. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196531. if (white_x > (double) PNG_UINT_31_MAX ||
  196532. white_y > (double) PNG_UINT_31_MAX ||
  196533. red_x > (double) PNG_UINT_31_MAX ||
  196534. red_y > (double) PNG_UINT_31_MAX ||
  196535. green_x > (double) PNG_UINT_31_MAX ||
  196536. green_y > (double) PNG_UINT_31_MAX ||
  196537. blue_x > (double) PNG_UINT_31_MAX ||
  196538. blue_y > (double) PNG_UINT_31_MAX)
  196539. #else
  196540. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196541. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196542. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196543. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196544. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196545. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196546. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196547. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196548. #endif
  196549. {
  196550. png_warning(png_ptr,
  196551. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196552. return;
  196553. }
  196554. info_ptr->int_x_white = white_x;
  196555. info_ptr->int_y_white = white_y;
  196556. info_ptr->int_x_red = red_x;
  196557. info_ptr->int_y_red = red_y;
  196558. info_ptr->int_x_green = green_x;
  196559. info_ptr->int_y_green = green_y;
  196560. info_ptr->int_x_blue = blue_x;
  196561. info_ptr->int_y_blue = blue_y;
  196562. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196563. info_ptr->x_white = (float)(white_x/100000.);
  196564. info_ptr->y_white = (float)(white_y/100000.);
  196565. info_ptr->x_red = (float)( red_x/100000.);
  196566. info_ptr->y_red = (float)( red_y/100000.);
  196567. info_ptr->x_green = (float)(green_x/100000.);
  196568. info_ptr->y_green = (float)(green_y/100000.);
  196569. info_ptr->x_blue = (float)( blue_x/100000.);
  196570. info_ptr->y_blue = (float)( blue_y/100000.);
  196571. #endif
  196572. info_ptr->valid |= PNG_INFO_cHRM;
  196573. }
  196574. #endif
  196575. #endif
  196576. #if defined(PNG_gAMA_SUPPORTED)
  196577. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196578. void PNGAPI
  196579. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196580. {
  196581. double gamma;
  196582. png_debug1(1, "in %s storage function\n", "gAMA");
  196583. if (png_ptr == NULL || info_ptr == NULL)
  196584. return;
  196585. /* Check for overflow */
  196586. if (file_gamma > 21474.83)
  196587. {
  196588. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196589. gamma=21474.83;
  196590. }
  196591. else
  196592. gamma=file_gamma;
  196593. info_ptr->gamma = (float)gamma;
  196594. #ifdef PNG_FIXED_POINT_SUPPORTED
  196595. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196596. #endif
  196597. info_ptr->valid |= PNG_INFO_gAMA;
  196598. if(gamma == 0.0)
  196599. png_warning(png_ptr, "Setting gamma=0");
  196600. }
  196601. #endif
  196602. void PNGAPI
  196603. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196604. int_gamma)
  196605. {
  196606. png_fixed_point gamma;
  196607. png_debug1(1, "in %s storage function\n", "gAMA");
  196608. if (png_ptr == NULL || info_ptr == NULL)
  196609. return;
  196610. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196611. {
  196612. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196613. gamma=PNG_UINT_31_MAX;
  196614. }
  196615. else
  196616. {
  196617. if (int_gamma < 0)
  196618. {
  196619. png_warning(png_ptr, "Setting negative gamma to zero");
  196620. gamma=0;
  196621. }
  196622. else
  196623. gamma=int_gamma;
  196624. }
  196625. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196626. info_ptr->gamma = (float)(gamma/100000.);
  196627. #endif
  196628. #ifdef PNG_FIXED_POINT_SUPPORTED
  196629. info_ptr->int_gamma = gamma;
  196630. #endif
  196631. info_ptr->valid |= PNG_INFO_gAMA;
  196632. if(gamma == 0)
  196633. png_warning(png_ptr, "Setting gamma=0");
  196634. }
  196635. #endif
  196636. #if defined(PNG_hIST_SUPPORTED)
  196637. void PNGAPI
  196638. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196639. {
  196640. int i;
  196641. png_debug1(1, "in %s storage function\n", "hIST");
  196642. if (png_ptr == NULL || info_ptr == NULL)
  196643. return;
  196644. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196645. > PNG_MAX_PALETTE_LENGTH)
  196646. {
  196647. png_warning(png_ptr,
  196648. "Invalid palette size, hIST allocation skipped.");
  196649. return;
  196650. }
  196651. #ifdef PNG_FREE_ME_SUPPORTED
  196652. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196653. #endif
  196654. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196655. 1.2.1 */
  196656. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196657. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196658. if (png_ptr->hist == NULL)
  196659. {
  196660. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196661. return;
  196662. }
  196663. for (i = 0; i < info_ptr->num_palette; i++)
  196664. png_ptr->hist[i] = hist[i];
  196665. info_ptr->hist = png_ptr->hist;
  196666. info_ptr->valid |= PNG_INFO_hIST;
  196667. #ifdef PNG_FREE_ME_SUPPORTED
  196668. info_ptr->free_me |= PNG_FREE_HIST;
  196669. #else
  196670. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  196671. #endif
  196672. }
  196673. #endif
  196674. void PNGAPI
  196675. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  196676. png_uint_32 width, png_uint_32 height, int bit_depth,
  196677. int color_type, int interlace_type, int compression_type,
  196678. int filter_type)
  196679. {
  196680. png_debug1(1, "in %s storage function\n", "IHDR");
  196681. if (png_ptr == NULL || info_ptr == NULL)
  196682. return;
  196683. /* check for width and height valid values */
  196684. if (width == 0 || height == 0)
  196685. png_error(png_ptr, "Image width or height is zero in IHDR");
  196686. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  196687. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  196688. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196689. #else
  196690. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  196691. png_error(png_ptr, "image size exceeds user limits in IHDR");
  196692. #endif
  196693. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  196694. png_error(png_ptr, "Invalid image size in IHDR");
  196695. if ( width > (PNG_UINT_32_MAX
  196696. >> 3) /* 8-byte RGBA pixels */
  196697. - 64 /* bigrowbuf hack */
  196698. - 1 /* filter byte */
  196699. - 7*8 /* rounding of width to multiple of 8 pixels */
  196700. - 8) /* extra max_pixel_depth pad */
  196701. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  196702. /* check other values */
  196703. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  196704. bit_depth != 8 && bit_depth != 16)
  196705. png_error(png_ptr, "Invalid bit depth in IHDR");
  196706. if (color_type < 0 || color_type == 1 ||
  196707. color_type == 5 || color_type > 6)
  196708. png_error(png_ptr, "Invalid color type in IHDR");
  196709. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  196710. ((color_type == PNG_COLOR_TYPE_RGB ||
  196711. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  196712. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  196713. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  196714. if (interlace_type >= PNG_INTERLACE_LAST)
  196715. png_error(png_ptr, "Unknown interlace method in IHDR");
  196716. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196717. png_error(png_ptr, "Unknown compression method in IHDR");
  196718. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196719. /* Accept filter_method 64 (intrapixel differencing) only if
  196720. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196721. * 2. Libpng did not read a PNG signature (this filter_method is only
  196722. * used in PNG datastreams that are embedded in MNG datastreams) and
  196723. * 3. The application called png_permit_mng_features with a mask that
  196724. * included PNG_FLAG_MNG_FILTER_64 and
  196725. * 4. The filter_method is 64 and
  196726. * 5. The color_type is RGB or RGBA
  196727. */
  196728. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  196729. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  196730. if(filter_type != PNG_FILTER_TYPE_BASE)
  196731. {
  196732. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196733. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  196734. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196735. (color_type == PNG_COLOR_TYPE_RGB ||
  196736. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  196737. png_error(png_ptr, "Unknown filter method in IHDR");
  196738. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  196739. png_warning(png_ptr, "Invalid filter method in IHDR");
  196740. }
  196741. #else
  196742. if(filter_type != PNG_FILTER_TYPE_BASE)
  196743. png_error(png_ptr, "Unknown filter method in IHDR");
  196744. #endif
  196745. info_ptr->width = width;
  196746. info_ptr->height = height;
  196747. info_ptr->bit_depth = (png_byte)bit_depth;
  196748. info_ptr->color_type =(png_byte) color_type;
  196749. info_ptr->compression_type = (png_byte)compression_type;
  196750. info_ptr->filter_type = (png_byte)filter_type;
  196751. info_ptr->interlace_type = (png_byte)interlace_type;
  196752. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196753. info_ptr->channels = 1;
  196754. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196755. info_ptr->channels = 3;
  196756. else
  196757. info_ptr->channels = 1;
  196758. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  196759. info_ptr->channels++;
  196760. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  196761. /* check for potential overflow */
  196762. if (width > (PNG_UINT_32_MAX
  196763. >> 3) /* 8-byte RGBA pixels */
  196764. - 64 /* bigrowbuf hack */
  196765. - 1 /* filter byte */
  196766. - 7*8 /* rounding of width to multiple of 8 pixels */
  196767. - 8) /* extra max_pixel_depth pad */
  196768. info_ptr->rowbytes = (png_size_t)0;
  196769. else
  196770. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  196771. }
  196772. #if defined(PNG_oFFs_SUPPORTED)
  196773. void PNGAPI
  196774. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  196775. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  196776. {
  196777. png_debug1(1, "in %s storage function\n", "oFFs");
  196778. if (png_ptr == NULL || info_ptr == NULL)
  196779. return;
  196780. info_ptr->x_offset = offset_x;
  196781. info_ptr->y_offset = offset_y;
  196782. info_ptr->offset_unit_type = (png_byte)unit_type;
  196783. info_ptr->valid |= PNG_INFO_oFFs;
  196784. }
  196785. #endif
  196786. #if defined(PNG_pCAL_SUPPORTED)
  196787. void PNGAPI
  196788. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  196789. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  196790. png_charp units, png_charpp params)
  196791. {
  196792. png_uint_32 length;
  196793. int i;
  196794. png_debug1(1, "in %s storage function\n", "pCAL");
  196795. if (png_ptr == NULL || info_ptr == NULL)
  196796. return;
  196797. length = png_strlen(purpose) + 1;
  196798. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  196799. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  196800. if (info_ptr->pcal_purpose == NULL)
  196801. {
  196802. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  196803. return;
  196804. }
  196805. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  196806. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  196807. info_ptr->pcal_X0 = X0;
  196808. info_ptr->pcal_X1 = X1;
  196809. info_ptr->pcal_type = (png_byte)type;
  196810. info_ptr->pcal_nparams = (png_byte)nparams;
  196811. length = png_strlen(units) + 1;
  196812. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  196813. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  196814. if (info_ptr->pcal_units == NULL)
  196815. {
  196816. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  196817. return;
  196818. }
  196819. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  196820. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  196821. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  196822. if (info_ptr->pcal_params == NULL)
  196823. {
  196824. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  196825. return;
  196826. }
  196827. info_ptr->pcal_params[nparams] = NULL;
  196828. for (i = 0; i < nparams; i++)
  196829. {
  196830. length = png_strlen(params[i]) + 1;
  196831. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  196832. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  196833. if (info_ptr->pcal_params[i] == NULL)
  196834. {
  196835. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  196836. return;
  196837. }
  196838. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  196839. }
  196840. info_ptr->valid |= PNG_INFO_pCAL;
  196841. #ifdef PNG_FREE_ME_SUPPORTED
  196842. info_ptr->free_me |= PNG_FREE_PCAL;
  196843. #endif
  196844. }
  196845. #endif
  196846. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  196847. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196848. void PNGAPI
  196849. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  196850. int unit, double width, double height)
  196851. {
  196852. png_debug1(1, "in %s storage function\n", "sCAL");
  196853. if (png_ptr == NULL || info_ptr == NULL)
  196854. return;
  196855. info_ptr->scal_unit = (png_byte)unit;
  196856. info_ptr->scal_pixel_width = width;
  196857. info_ptr->scal_pixel_height = height;
  196858. info_ptr->valid |= PNG_INFO_sCAL;
  196859. }
  196860. #else
  196861. #ifdef PNG_FIXED_POINT_SUPPORTED
  196862. void PNGAPI
  196863. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  196864. int unit, png_charp swidth, png_charp sheight)
  196865. {
  196866. png_uint_32 length;
  196867. png_debug1(1, "in %s storage function\n", "sCAL");
  196868. if (png_ptr == NULL || info_ptr == NULL)
  196869. return;
  196870. info_ptr->scal_unit = (png_byte)unit;
  196871. length = png_strlen(swidth) + 1;
  196872. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196873. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  196874. if (info_ptr->scal_s_width == NULL)
  196875. {
  196876. png_warning(png_ptr,
  196877. "Memory allocation failed while processing sCAL.");
  196878. }
  196879. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  196880. length = png_strlen(sheight) + 1;
  196881. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  196882. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  196883. if (info_ptr->scal_s_height == NULL)
  196884. {
  196885. png_free (png_ptr, info_ptr->scal_s_width);
  196886. png_warning(png_ptr,
  196887. "Memory allocation failed while processing sCAL.");
  196888. }
  196889. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  196890. info_ptr->valid |= PNG_INFO_sCAL;
  196891. #ifdef PNG_FREE_ME_SUPPORTED
  196892. info_ptr->free_me |= PNG_FREE_SCAL;
  196893. #endif
  196894. }
  196895. #endif
  196896. #endif
  196897. #endif
  196898. #if defined(PNG_pHYs_SUPPORTED)
  196899. void PNGAPI
  196900. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  196901. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  196902. {
  196903. png_debug1(1, "in %s storage function\n", "pHYs");
  196904. if (png_ptr == NULL || info_ptr == NULL)
  196905. return;
  196906. info_ptr->x_pixels_per_unit = res_x;
  196907. info_ptr->y_pixels_per_unit = res_y;
  196908. info_ptr->phys_unit_type = (png_byte)unit_type;
  196909. info_ptr->valid |= PNG_INFO_pHYs;
  196910. }
  196911. #endif
  196912. void PNGAPI
  196913. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  196914. png_colorp palette, int num_palette)
  196915. {
  196916. png_debug1(1, "in %s storage function\n", "PLTE");
  196917. if (png_ptr == NULL || info_ptr == NULL)
  196918. return;
  196919. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  196920. {
  196921. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196922. png_error(png_ptr, "Invalid palette length");
  196923. else
  196924. {
  196925. png_warning(png_ptr, "Invalid palette length");
  196926. return;
  196927. }
  196928. }
  196929. /*
  196930. * It may not actually be necessary to set png_ptr->palette here;
  196931. * we do it for backward compatibility with the way the png_handle_tRNS
  196932. * function used to do the allocation.
  196933. */
  196934. #ifdef PNG_FREE_ME_SUPPORTED
  196935. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  196936. #endif
  196937. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  196938. of num_palette entries,
  196939. in case of an invalid PNG file that has too-large sample values. */
  196940. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  196941. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  196942. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  196943. png_sizeof(png_color));
  196944. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  196945. info_ptr->palette = png_ptr->palette;
  196946. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  196947. #ifdef PNG_FREE_ME_SUPPORTED
  196948. info_ptr->free_me |= PNG_FREE_PLTE;
  196949. #else
  196950. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  196951. #endif
  196952. info_ptr->valid |= PNG_INFO_PLTE;
  196953. }
  196954. #if defined(PNG_sBIT_SUPPORTED)
  196955. void PNGAPI
  196956. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  196957. png_color_8p sig_bit)
  196958. {
  196959. png_debug1(1, "in %s storage function\n", "sBIT");
  196960. if (png_ptr == NULL || info_ptr == NULL)
  196961. return;
  196962. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  196963. info_ptr->valid |= PNG_INFO_sBIT;
  196964. }
  196965. #endif
  196966. #if defined(PNG_sRGB_SUPPORTED)
  196967. void PNGAPI
  196968. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  196969. {
  196970. png_debug1(1, "in %s storage function\n", "sRGB");
  196971. if (png_ptr == NULL || info_ptr == NULL)
  196972. return;
  196973. info_ptr->srgb_intent = (png_byte)intent;
  196974. info_ptr->valid |= PNG_INFO_sRGB;
  196975. }
  196976. void PNGAPI
  196977. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  196978. int intent)
  196979. {
  196980. #if defined(PNG_gAMA_SUPPORTED)
  196981. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196982. float file_gamma;
  196983. #endif
  196984. #ifdef PNG_FIXED_POINT_SUPPORTED
  196985. png_fixed_point int_file_gamma;
  196986. #endif
  196987. #endif
  196988. #if defined(PNG_cHRM_SUPPORTED)
  196989. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196990. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  196991. #endif
  196992. #ifdef PNG_FIXED_POINT_SUPPORTED
  196993. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  196994. int_green_y, int_blue_x, int_blue_y;
  196995. #endif
  196996. #endif
  196997. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  196998. if (png_ptr == NULL || info_ptr == NULL)
  196999. return;
  197000. png_set_sRGB(png_ptr, info_ptr, intent);
  197001. #if defined(PNG_gAMA_SUPPORTED)
  197002. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197003. file_gamma = (float).45455;
  197004. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197005. #endif
  197006. #ifdef PNG_FIXED_POINT_SUPPORTED
  197007. int_file_gamma = 45455L;
  197008. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197009. #endif
  197010. #endif
  197011. #if defined(PNG_cHRM_SUPPORTED)
  197012. #ifdef PNG_FIXED_POINT_SUPPORTED
  197013. int_white_x = 31270L;
  197014. int_white_y = 32900L;
  197015. int_red_x = 64000L;
  197016. int_red_y = 33000L;
  197017. int_green_x = 30000L;
  197018. int_green_y = 60000L;
  197019. int_blue_x = 15000L;
  197020. int_blue_y = 6000L;
  197021. png_set_cHRM_fixed(png_ptr, info_ptr,
  197022. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197023. int_blue_x, int_blue_y);
  197024. #endif
  197025. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197026. white_x = (float).3127;
  197027. white_y = (float).3290;
  197028. red_x = (float).64;
  197029. red_y = (float).33;
  197030. green_x = (float).30;
  197031. green_y = (float).60;
  197032. blue_x = (float).15;
  197033. blue_y = (float).06;
  197034. png_set_cHRM(png_ptr, info_ptr,
  197035. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197036. #endif
  197037. #endif
  197038. }
  197039. #endif
  197040. #if defined(PNG_iCCP_SUPPORTED)
  197041. void PNGAPI
  197042. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197043. png_charp name, int compression_type,
  197044. png_charp profile, png_uint_32 proflen)
  197045. {
  197046. png_charp new_iccp_name;
  197047. png_charp new_iccp_profile;
  197048. png_debug1(1, "in %s storage function\n", "iCCP");
  197049. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197050. return;
  197051. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197052. if (new_iccp_name == NULL)
  197053. {
  197054. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197055. return;
  197056. }
  197057. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197058. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197059. if (new_iccp_profile == NULL)
  197060. {
  197061. png_free (png_ptr, new_iccp_name);
  197062. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197063. return;
  197064. }
  197065. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197066. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197067. info_ptr->iccp_proflen = proflen;
  197068. info_ptr->iccp_name = new_iccp_name;
  197069. info_ptr->iccp_profile = new_iccp_profile;
  197070. /* Compression is always zero but is here so the API and info structure
  197071. * does not have to change if we introduce multiple compression types */
  197072. info_ptr->iccp_compression = (png_byte)compression_type;
  197073. #ifdef PNG_FREE_ME_SUPPORTED
  197074. info_ptr->free_me |= PNG_FREE_ICCP;
  197075. #endif
  197076. info_ptr->valid |= PNG_INFO_iCCP;
  197077. }
  197078. #endif
  197079. #if defined(PNG_TEXT_SUPPORTED)
  197080. void PNGAPI
  197081. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197082. int num_text)
  197083. {
  197084. int ret;
  197085. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197086. if (ret)
  197087. png_error(png_ptr, "Insufficient memory to store text");
  197088. }
  197089. int /* PRIVATE */
  197090. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197091. int num_text)
  197092. {
  197093. int i;
  197094. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197095. "text" : (png_const_charp)png_ptr->chunk_name));
  197096. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197097. return(0);
  197098. /* Make sure we have enough space in the "text" array in info_struct
  197099. * to hold all of the incoming text_ptr objects.
  197100. */
  197101. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197102. {
  197103. if (info_ptr->text != NULL)
  197104. {
  197105. png_textp old_text;
  197106. int old_max;
  197107. old_max = info_ptr->max_text;
  197108. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197109. old_text = info_ptr->text;
  197110. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197111. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197112. if (info_ptr->text == NULL)
  197113. {
  197114. png_free(png_ptr, old_text);
  197115. return(1);
  197116. }
  197117. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197118. png_sizeof(png_text)));
  197119. png_free(png_ptr, old_text);
  197120. }
  197121. else
  197122. {
  197123. info_ptr->max_text = num_text + 8;
  197124. info_ptr->num_text = 0;
  197125. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197126. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197127. if (info_ptr->text == NULL)
  197128. return(1);
  197129. #ifdef PNG_FREE_ME_SUPPORTED
  197130. info_ptr->free_me |= PNG_FREE_TEXT;
  197131. #endif
  197132. }
  197133. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197134. info_ptr->max_text);
  197135. }
  197136. for (i = 0; i < num_text; i++)
  197137. {
  197138. png_size_t text_length,key_len;
  197139. png_size_t lang_len,lang_key_len;
  197140. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197141. if (text_ptr[i].key == NULL)
  197142. continue;
  197143. key_len = png_strlen(text_ptr[i].key);
  197144. if(text_ptr[i].compression <= 0)
  197145. {
  197146. lang_len = 0;
  197147. lang_key_len = 0;
  197148. }
  197149. else
  197150. #ifdef PNG_iTXt_SUPPORTED
  197151. {
  197152. /* set iTXt data */
  197153. if (text_ptr[i].lang != NULL)
  197154. lang_len = png_strlen(text_ptr[i].lang);
  197155. else
  197156. lang_len = 0;
  197157. if (text_ptr[i].lang_key != NULL)
  197158. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197159. else
  197160. lang_key_len = 0;
  197161. }
  197162. #else
  197163. {
  197164. png_warning(png_ptr, "iTXt chunk not supported.");
  197165. continue;
  197166. }
  197167. #endif
  197168. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197169. {
  197170. text_length = 0;
  197171. #ifdef PNG_iTXt_SUPPORTED
  197172. if(text_ptr[i].compression > 0)
  197173. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197174. else
  197175. #endif
  197176. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197177. }
  197178. else
  197179. {
  197180. text_length = png_strlen(text_ptr[i].text);
  197181. textp->compression = text_ptr[i].compression;
  197182. }
  197183. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197184. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197185. if (textp->key == NULL)
  197186. return(1);
  197187. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197188. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197189. (int)textp->key);
  197190. png_memcpy(textp->key, text_ptr[i].key,
  197191. (png_size_t)(key_len));
  197192. *(textp->key+key_len) = '\0';
  197193. #ifdef PNG_iTXt_SUPPORTED
  197194. if (text_ptr[i].compression > 0)
  197195. {
  197196. textp->lang=textp->key + key_len + 1;
  197197. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197198. *(textp->lang+lang_len) = '\0';
  197199. textp->lang_key=textp->lang + lang_len + 1;
  197200. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197201. *(textp->lang_key+lang_key_len) = '\0';
  197202. textp->text=textp->lang_key + lang_key_len + 1;
  197203. }
  197204. else
  197205. #endif
  197206. {
  197207. #ifdef PNG_iTXt_SUPPORTED
  197208. textp->lang=NULL;
  197209. textp->lang_key=NULL;
  197210. #endif
  197211. textp->text=textp->key + key_len + 1;
  197212. }
  197213. if(text_length)
  197214. png_memcpy(textp->text, text_ptr[i].text,
  197215. (png_size_t)(text_length));
  197216. *(textp->text+text_length) = '\0';
  197217. #ifdef PNG_iTXt_SUPPORTED
  197218. if(textp->compression > 0)
  197219. {
  197220. textp->text_length = 0;
  197221. textp->itxt_length = text_length;
  197222. }
  197223. else
  197224. #endif
  197225. {
  197226. textp->text_length = text_length;
  197227. #ifdef PNG_iTXt_SUPPORTED
  197228. textp->itxt_length = 0;
  197229. #endif
  197230. }
  197231. info_ptr->num_text++;
  197232. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197233. }
  197234. return(0);
  197235. }
  197236. #endif
  197237. #if defined(PNG_tIME_SUPPORTED)
  197238. void PNGAPI
  197239. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197240. {
  197241. png_debug1(1, "in %s storage function\n", "tIME");
  197242. if (png_ptr == NULL || info_ptr == NULL ||
  197243. (png_ptr->mode & PNG_WROTE_tIME))
  197244. return;
  197245. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197246. info_ptr->valid |= PNG_INFO_tIME;
  197247. }
  197248. #endif
  197249. #if defined(PNG_tRNS_SUPPORTED)
  197250. void PNGAPI
  197251. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197252. png_bytep trans, int num_trans, png_color_16p trans_values)
  197253. {
  197254. png_debug1(1, "in %s storage function\n", "tRNS");
  197255. if (png_ptr == NULL || info_ptr == NULL)
  197256. return;
  197257. if (trans != NULL)
  197258. {
  197259. /*
  197260. * It may not actually be necessary to set png_ptr->trans here;
  197261. * we do it for backward compatibility with the way the png_handle_tRNS
  197262. * function used to do the allocation.
  197263. */
  197264. #ifdef PNG_FREE_ME_SUPPORTED
  197265. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197266. #endif
  197267. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197268. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197269. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197270. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197271. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197272. #ifdef PNG_FREE_ME_SUPPORTED
  197273. info_ptr->free_me |= PNG_FREE_TRNS;
  197274. #else
  197275. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197276. #endif
  197277. }
  197278. if (trans_values != NULL)
  197279. {
  197280. png_memcpy(&(info_ptr->trans_values), trans_values,
  197281. png_sizeof(png_color_16));
  197282. if (num_trans == 0)
  197283. num_trans = 1;
  197284. }
  197285. info_ptr->num_trans = (png_uint_16)num_trans;
  197286. info_ptr->valid |= PNG_INFO_tRNS;
  197287. }
  197288. #endif
  197289. #if defined(PNG_sPLT_SUPPORTED)
  197290. void PNGAPI
  197291. png_set_sPLT(png_structp png_ptr,
  197292. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197293. {
  197294. png_sPLT_tp np;
  197295. int i;
  197296. if (png_ptr == NULL || info_ptr == NULL)
  197297. return;
  197298. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197299. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197300. if (np == NULL)
  197301. {
  197302. png_warning(png_ptr, "No memory for sPLT palettes.");
  197303. return;
  197304. }
  197305. png_memcpy(np, info_ptr->splt_palettes,
  197306. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197307. png_free(png_ptr, info_ptr->splt_palettes);
  197308. info_ptr->splt_palettes=NULL;
  197309. for (i = 0; i < nentries; i++)
  197310. {
  197311. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197312. png_sPLT_tp from = entries + i;
  197313. to->name = (png_charp)png_malloc_warn(png_ptr,
  197314. png_strlen(from->name) + 1);
  197315. if (to->name == NULL)
  197316. {
  197317. png_warning(png_ptr,
  197318. "Out of memory while processing sPLT chunk");
  197319. }
  197320. /* TODO: use png_malloc_warn */
  197321. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197322. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197323. from->nentries * png_sizeof(png_sPLT_entry));
  197324. /* TODO: use png_malloc_warn */
  197325. png_memcpy(to->entries, from->entries,
  197326. from->nentries * png_sizeof(png_sPLT_entry));
  197327. if (to->entries == NULL)
  197328. {
  197329. png_warning(png_ptr,
  197330. "Out of memory while processing sPLT chunk");
  197331. png_free(png_ptr,to->name);
  197332. to->name = NULL;
  197333. }
  197334. to->nentries = from->nentries;
  197335. to->depth = from->depth;
  197336. }
  197337. info_ptr->splt_palettes = np;
  197338. info_ptr->splt_palettes_num += nentries;
  197339. info_ptr->valid |= PNG_INFO_sPLT;
  197340. #ifdef PNG_FREE_ME_SUPPORTED
  197341. info_ptr->free_me |= PNG_FREE_SPLT;
  197342. #endif
  197343. }
  197344. #endif /* PNG_sPLT_SUPPORTED */
  197345. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197346. void PNGAPI
  197347. png_set_unknown_chunks(png_structp png_ptr,
  197348. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197349. {
  197350. png_unknown_chunkp np;
  197351. int i;
  197352. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197353. return;
  197354. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197355. (info_ptr->unknown_chunks_num + num_unknowns) *
  197356. png_sizeof(png_unknown_chunk));
  197357. if (np == NULL)
  197358. {
  197359. png_warning(png_ptr,
  197360. "Out of memory while processing unknown chunk.");
  197361. return;
  197362. }
  197363. png_memcpy(np, info_ptr->unknown_chunks,
  197364. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197365. png_free(png_ptr, info_ptr->unknown_chunks);
  197366. info_ptr->unknown_chunks=NULL;
  197367. for (i = 0; i < num_unknowns; i++)
  197368. {
  197369. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197370. png_unknown_chunkp from = unknowns + i;
  197371. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197372. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197373. if (to->data == NULL)
  197374. {
  197375. png_warning(png_ptr,
  197376. "Out of memory while processing unknown chunk.");
  197377. }
  197378. else
  197379. {
  197380. png_memcpy(to->data, from->data, from->size);
  197381. to->size = from->size;
  197382. /* note our location in the read or write sequence */
  197383. to->location = (png_byte)(png_ptr->mode & 0xff);
  197384. }
  197385. }
  197386. info_ptr->unknown_chunks = np;
  197387. info_ptr->unknown_chunks_num += num_unknowns;
  197388. #ifdef PNG_FREE_ME_SUPPORTED
  197389. info_ptr->free_me |= PNG_FREE_UNKN;
  197390. #endif
  197391. }
  197392. void PNGAPI
  197393. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197394. int chunk, int location)
  197395. {
  197396. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197397. (int)info_ptr->unknown_chunks_num)
  197398. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197399. }
  197400. #endif
  197401. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197402. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197403. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197404. void PNGAPI
  197405. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197406. {
  197407. /* This function is deprecated in favor of png_permit_mng_features()
  197408. and will be removed from libpng-1.3.0 */
  197409. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197410. if (png_ptr == NULL)
  197411. return;
  197412. png_ptr->mng_features_permitted = (png_byte)
  197413. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197414. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197415. }
  197416. #endif
  197417. #endif
  197418. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197419. png_uint_32 PNGAPI
  197420. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197421. {
  197422. png_debug(1, "in png_permit_mng_features\n");
  197423. if (png_ptr == NULL)
  197424. return (png_uint_32)0;
  197425. png_ptr->mng_features_permitted =
  197426. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197427. return (png_uint_32)png_ptr->mng_features_permitted;
  197428. }
  197429. #endif
  197430. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197431. void PNGAPI
  197432. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197433. chunk_list, int num_chunks)
  197434. {
  197435. png_bytep new_list, p;
  197436. int i, old_num_chunks;
  197437. if (png_ptr == NULL)
  197438. return;
  197439. if (num_chunks == 0)
  197440. {
  197441. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197442. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197443. else
  197444. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197445. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197446. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197447. else
  197448. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197449. return;
  197450. }
  197451. if (chunk_list == NULL)
  197452. return;
  197453. old_num_chunks=png_ptr->num_chunk_list;
  197454. new_list=(png_bytep)png_malloc(png_ptr,
  197455. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197456. if(png_ptr->chunk_list != NULL)
  197457. {
  197458. png_memcpy(new_list, png_ptr->chunk_list,
  197459. (png_size_t)(5*old_num_chunks));
  197460. png_free(png_ptr, png_ptr->chunk_list);
  197461. png_ptr->chunk_list=NULL;
  197462. }
  197463. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197464. (png_size_t)(5*num_chunks));
  197465. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197466. *p=(png_byte)keep;
  197467. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197468. png_ptr->chunk_list=new_list;
  197469. #ifdef PNG_FREE_ME_SUPPORTED
  197470. png_ptr->free_me |= PNG_FREE_LIST;
  197471. #endif
  197472. }
  197473. #endif
  197474. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197475. void PNGAPI
  197476. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197477. png_user_chunk_ptr read_user_chunk_fn)
  197478. {
  197479. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197480. if (png_ptr == NULL)
  197481. return;
  197482. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197483. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197484. }
  197485. #endif
  197486. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197487. void PNGAPI
  197488. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197489. {
  197490. png_debug1(1, "in %s storage function\n", "rows");
  197491. if (png_ptr == NULL || info_ptr == NULL)
  197492. return;
  197493. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197494. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197495. info_ptr->row_pointers = row_pointers;
  197496. if(row_pointers)
  197497. info_ptr->valid |= PNG_INFO_IDAT;
  197498. }
  197499. #endif
  197500. #ifdef PNG_WRITE_SUPPORTED
  197501. void PNGAPI
  197502. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197503. {
  197504. if (png_ptr == NULL)
  197505. return;
  197506. if(png_ptr->zbuf)
  197507. png_free(png_ptr, png_ptr->zbuf);
  197508. png_ptr->zbuf_size = (png_size_t)size;
  197509. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197510. png_ptr->zstream.next_out = png_ptr->zbuf;
  197511. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197512. }
  197513. #endif
  197514. void PNGAPI
  197515. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197516. {
  197517. if (png_ptr && info_ptr)
  197518. info_ptr->valid &= ~(mask);
  197519. }
  197520. #ifndef PNG_1_0_X
  197521. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197522. /* function was added to libpng 1.2.0 and should always exist by default */
  197523. void PNGAPI
  197524. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197525. {
  197526. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197527. if (png_ptr != NULL)
  197528. png_ptr->asm_flags = 0;
  197529. }
  197530. /* this function was added to libpng 1.2.0 */
  197531. void PNGAPI
  197532. png_set_mmx_thresholds (png_structp png_ptr,
  197533. png_byte,
  197534. png_uint_32)
  197535. {
  197536. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197537. if (png_ptr == NULL)
  197538. return;
  197539. }
  197540. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197541. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197542. /* this function was added to libpng 1.2.6 */
  197543. void PNGAPI
  197544. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197545. png_uint_32 user_height_max)
  197546. {
  197547. /* Images with dimensions larger than these limits will be
  197548. * rejected by png_set_IHDR(). To accept any PNG datastream
  197549. * regardless of dimensions, set both limits to 0x7ffffffL.
  197550. */
  197551. if(png_ptr == NULL) return;
  197552. png_ptr->user_width_max = user_width_max;
  197553. png_ptr->user_height_max = user_height_max;
  197554. }
  197555. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197556. #endif /* ?PNG_1_0_X */
  197557. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197558. /*** End of inlined file: pngset.c ***/
  197559. /*** Start of inlined file: pngtrans.c ***/
  197560. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197561. *
  197562. * Last changed in libpng 1.2.17 May 15, 2007
  197563. * For conditions of distribution and use, see copyright notice in png.h
  197564. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197565. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197566. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197567. */
  197568. #define PNG_INTERNAL
  197569. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197570. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197571. /* turn on BGR-to-RGB mapping */
  197572. void PNGAPI
  197573. png_set_bgr(png_structp png_ptr)
  197574. {
  197575. png_debug(1, "in png_set_bgr\n");
  197576. if(png_ptr == NULL) return;
  197577. png_ptr->transformations |= PNG_BGR;
  197578. }
  197579. #endif
  197580. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197581. /* turn on 16 bit byte swapping */
  197582. void PNGAPI
  197583. png_set_swap(png_structp png_ptr)
  197584. {
  197585. png_debug(1, "in png_set_swap\n");
  197586. if(png_ptr == NULL) return;
  197587. if (png_ptr->bit_depth == 16)
  197588. png_ptr->transformations |= PNG_SWAP_BYTES;
  197589. }
  197590. #endif
  197591. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197592. /* turn on pixel packing */
  197593. void PNGAPI
  197594. png_set_packing(png_structp png_ptr)
  197595. {
  197596. png_debug(1, "in png_set_packing\n");
  197597. if(png_ptr == NULL) return;
  197598. if (png_ptr->bit_depth < 8)
  197599. {
  197600. png_ptr->transformations |= PNG_PACK;
  197601. png_ptr->usr_bit_depth = 8;
  197602. }
  197603. }
  197604. #endif
  197605. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197606. /* turn on packed pixel swapping */
  197607. void PNGAPI
  197608. png_set_packswap(png_structp png_ptr)
  197609. {
  197610. png_debug(1, "in png_set_packswap\n");
  197611. if(png_ptr == NULL) return;
  197612. if (png_ptr->bit_depth < 8)
  197613. png_ptr->transformations |= PNG_PACKSWAP;
  197614. }
  197615. #endif
  197616. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197617. void PNGAPI
  197618. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197619. {
  197620. png_debug(1, "in png_set_shift\n");
  197621. if(png_ptr == NULL) return;
  197622. png_ptr->transformations |= PNG_SHIFT;
  197623. png_ptr->shift = *true_bits;
  197624. }
  197625. #endif
  197626. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197627. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197628. int PNGAPI
  197629. png_set_interlace_handling(png_structp png_ptr)
  197630. {
  197631. png_debug(1, "in png_set_interlace handling\n");
  197632. if (png_ptr && png_ptr->interlaced)
  197633. {
  197634. png_ptr->transformations |= PNG_INTERLACE;
  197635. return (7);
  197636. }
  197637. return (1);
  197638. }
  197639. #endif
  197640. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197641. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197642. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197643. * for 48-bit input data, as well as to avoid problems with some compilers
  197644. * that don't like bytes as parameters.
  197645. */
  197646. void PNGAPI
  197647. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197648. {
  197649. png_debug(1, "in png_set_filler\n");
  197650. if(png_ptr == NULL) return;
  197651. png_ptr->transformations |= PNG_FILLER;
  197652. png_ptr->filler = (png_byte)filler;
  197653. if (filler_loc == PNG_FILLER_AFTER)
  197654. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197655. else
  197656. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197657. /* This should probably go in the "do_read_filler" routine.
  197658. * I attempted to do that in libpng-1.0.1a but that caused problems
  197659. * so I restored it in libpng-1.0.2a
  197660. */
  197661. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197662. {
  197663. png_ptr->usr_channels = 4;
  197664. }
  197665. /* Also I added this in libpng-1.0.2a (what happens when we expand
  197666. * a less-than-8-bit grayscale to GA? */
  197667. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  197668. {
  197669. png_ptr->usr_channels = 2;
  197670. }
  197671. }
  197672. #if !defined(PNG_1_0_X)
  197673. /* Added to libpng-1.2.7 */
  197674. void PNGAPI
  197675. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197676. {
  197677. png_debug(1, "in png_set_add_alpha\n");
  197678. if(png_ptr == NULL) return;
  197679. png_set_filler(png_ptr, filler, filler_loc);
  197680. png_ptr->transformations |= PNG_ADD_ALPHA;
  197681. }
  197682. #endif
  197683. #endif
  197684. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  197685. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  197686. void PNGAPI
  197687. png_set_swap_alpha(png_structp png_ptr)
  197688. {
  197689. png_debug(1, "in png_set_swap_alpha\n");
  197690. if(png_ptr == NULL) return;
  197691. png_ptr->transformations |= PNG_SWAP_ALPHA;
  197692. }
  197693. #endif
  197694. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  197695. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  197696. void PNGAPI
  197697. png_set_invert_alpha(png_structp png_ptr)
  197698. {
  197699. png_debug(1, "in png_set_invert_alpha\n");
  197700. if(png_ptr == NULL) return;
  197701. png_ptr->transformations |= PNG_INVERT_ALPHA;
  197702. }
  197703. #endif
  197704. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  197705. void PNGAPI
  197706. png_set_invert_mono(png_structp png_ptr)
  197707. {
  197708. png_debug(1, "in png_set_invert_mono\n");
  197709. if(png_ptr == NULL) return;
  197710. png_ptr->transformations |= PNG_INVERT_MONO;
  197711. }
  197712. /* invert monochrome grayscale data */
  197713. void /* PRIVATE */
  197714. png_do_invert(png_row_infop row_info, png_bytep row)
  197715. {
  197716. png_debug(1, "in png_do_invert\n");
  197717. /* This test removed from libpng version 1.0.13 and 1.2.0:
  197718. * if (row_info->bit_depth == 1 &&
  197719. */
  197720. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197721. if (row == NULL || row_info == NULL)
  197722. return;
  197723. #endif
  197724. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  197725. {
  197726. png_bytep rp = row;
  197727. png_uint_32 i;
  197728. png_uint_32 istop = row_info->rowbytes;
  197729. for (i = 0; i < istop; i++)
  197730. {
  197731. *rp = (png_byte)(~(*rp));
  197732. rp++;
  197733. }
  197734. }
  197735. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197736. row_info->bit_depth == 8)
  197737. {
  197738. png_bytep rp = row;
  197739. png_uint_32 i;
  197740. png_uint_32 istop = row_info->rowbytes;
  197741. for (i = 0; i < istop; i+=2)
  197742. {
  197743. *rp = (png_byte)(~(*rp));
  197744. rp+=2;
  197745. }
  197746. }
  197747. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  197748. row_info->bit_depth == 16)
  197749. {
  197750. png_bytep rp = row;
  197751. png_uint_32 i;
  197752. png_uint_32 istop = row_info->rowbytes;
  197753. for (i = 0; i < istop; i+=4)
  197754. {
  197755. *rp = (png_byte)(~(*rp));
  197756. *(rp+1) = (png_byte)(~(*(rp+1)));
  197757. rp+=4;
  197758. }
  197759. }
  197760. }
  197761. #endif
  197762. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197763. /* swaps byte order on 16 bit depth images */
  197764. void /* PRIVATE */
  197765. png_do_swap(png_row_infop row_info, png_bytep row)
  197766. {
  197767. png_debug(1, "in png_do_swap\n");
  197768. if (
  197769. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197770. row != NULL && row_info != NULL &&
  197771. #endif
  197772. row_info->bit_depth == 16)
  197773. {
  197774. png_bytep rp = row;
  197775. png_uint_32 i;
  197776. png_uint_32 istop= row_info->width * row_info->channels;
  197777. for (i = 0; i < istop; i++, rp += 2)
  197778. {
  197779. png_byte t = *rp;
  197780. *rp = *(rp + 1);
  197781. *(rp + 1) = t;
  197782. }
  197783. }
  197784. }
  197785. #endif
  197786. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197787. static PNG_CONST png_byte onebppswaptable[256] = {
  197788. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  197789. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  197790. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  197791. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  197792. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  197793. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  197794. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  197795. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  197796. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  197797. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  197798. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  197799. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  197800. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  197801. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  197802. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  197803. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  197804. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  197805. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  197806. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  197807. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  197808. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  197809. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  197810. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  197811. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  197812. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  197813. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  197814. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  197815. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  197816. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  197817. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  197818. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  197819. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  197820. };
  197821. static PNG_CONST png_byte twobppswaptable[256] = {
  197822. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  197823. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  197824. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  197825. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  197826. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  197827. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  197828. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  197829. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  197830. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  197831. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  197832. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  197833. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  197834. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  197835. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  197836. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  197837. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  197838. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  197839. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  197840. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  197841. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  197842. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  197843. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  197844. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  197845. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  197846. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  197847. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  197848. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  197849. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  197850. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  197851. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  197852. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  197853. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  197854. };
  197855. static PNG_CONST png_byte fourbppswaptable[256] = {
  197856. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  197857. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  197858. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  197859. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  197860. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  197861. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  197862. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  197863. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  197864. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  197865. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  197866. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  197867. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  197868. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  197869. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  197870. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  197871. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  197872. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  197873. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  197874. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  197875. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  197876. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  197877. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  197878. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  197879. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  197880. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  197881. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  197882. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  197883. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  197884. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  197885. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  197886. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  197887. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  197888. };
  197889. /* swaps pixel packing order within bytes */
  197890. void /* PRIVATE */
  197891. png_do_packswap(png_row_infop row_info, png_bytep row)
  197892. {
  197893. png_debug(1, "in png_do_packswap\n");
  197894. if (
  197895. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197896. row != NULL && row_info != NULL &&
  197897. #endif
  197898. row_info->bit_depth < 8)
  197899. {
  197900. png_bytep rp, end, table;
  197901. end = row + row_info->rowbytes;
  197902. if (row_info->bit_depth == 1)
  197903. table = (png_bytep)onebppswaptable;
  197904. else if (row_info->bit_depth == 2)
  197905. table = (png_bytep)twobppswaptable;
  197906. else if (row_info->bit_depth == 4)
  197907. table = (png_bytep)fourbppswaptable;
  197908. else
  197909. return;
  197910. for (rp = row; rp < end; rp++)
  197911. *rp = table[*rp];
  197912. }
  197913. }
  197914. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  197915. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  197916. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  197917. /* remove filler or alpha byte(s) */
  197918. void /* PRIVATE */
  197919. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  197920. {
  197921. png_debug(1, "in png_do_strip_filler\n");
  197922. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197923. if (row != NULL && row_info != NULL)
  197924. #endif
  197925. {
  197926. png_bytep sp=row;
  197927. png_bytep dp=row;
  197928. png_uint_32 row_width=row_info->width;
  197929. png_uint_32 i;
  197930. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  197931. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  197932. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  197933. row_info->channels == 4)
  197934. {
  197935. if (row_info->bit_depth == 8)
  197936. {
  197937. /* This converts from RGBX or RGBA to RGB */
  197938. if (flags & PNG_FLAG_FILLER_AFTER)
  197939. {
  197940. dp+=3; sp+=4;
  197941. for (i = 1; i < row_width; i++)
  197942. {
  197943. *dp++ = *sp++;
  197944. *dp++ = *sp++;
  197945. *dp++ = *sp++;
  197946. sp++;
  197947. }
  197948. }
  197949. /* This converts from XRGB or ARGB to RGB */
  197950. else
  197951. {
  197952. for (i = 0; i < row_width; i++)
  197953. {
  197954. sp++;
  197955. *dp++ = *sp++;
  197956. *dp++ = *sp++;
  197957. *dp++ = *sp++;
  197958. }
  197959. }
  197960. row_info->pixel_depth = 24;
  197961. row_info->rowbytes = row_width * 3;
  197962. }
  197963. else /* if (row_info->bit_depth == 16) */
  197964. {
  197965. if (flags & PNG_FLAG_FILLER_AFTER)
  197966. {
  197967. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  197968. sp += 8; dp += 6;
  197969. for (i = 1; i < row_width; i++)
  197970. {
  197971. /* This could be (although png_memcpy is probably slower):
  197972. png_memcpy(dp, sp, 6);
  197973. sp += 8;
  197974. dp += 6;
  197975. */
  197976. *dp++ = *sp++;
  197977. *dp++ = *sp++;
  197978. *dp++ = *sp++;
  197979. *dp++ = *sp++;
  197980. *dp++ = *sp++;
  197981. *dp++ = *sp++;
  197982. sp += 2;
  197983. }
  197984. }
  197985. else
  197986. {
  197987. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  197988. for (i = 0; i < row_width; i++)
  197989. {
  197990. /* This could be (although png_memcpy is probably slower):
  197991. png_memcpy(dp, sp, 6);
  197992. sp += 8;
  197993. dp += 6;
  197994. */
  197995. sp+=2;
  197996. *dp++ = *sp++;
  197997. *dp++ = *sp++;
  197998. *dp++ = *sp++;
  197999. *dp++ = *sp++;
  198000. *dp++ = *sp++;
  198001. *dp++ = *sp++;
  198002. }
  198003. }
  198004. row_info->pixel_depth = 48;
  198005. row_info->rowbytes = row_width * 6;
  198006. }
  198007. row_info->channels = 3;
  198008. }
  198009. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198010. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198011. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198012. row_info->channels == 2)
  198013. {
  198014. if (row_info->bit_depth == 8)
  198015. {
  198016. /* This converts from GX or GA to G */
  198017. if (flags & PNG_FLAG_FILLER_AFTER)
  198018. {
  198019. for (i = 0; i < row_width; i++)
  198020. {
  198021. *dp++ = *sp++;
  198022. sp++;
  198023. }
  198024. }
  198025. /* This converts from XG or AG to G */
  198026. else
  198027. {
  198028. for (i = 0; i < row_width; i++)
  198029. {
  198030. sp++;
  198031. *dp++ = *sp++;
  198032. }
  198033. }
  198034. row_info->pixel_depth = 8;
  198035. row_info->rowbytes = row_width;
  198036. }
  198037. else /* if (row_info->bit_depth == 16) */
  198038. {
  198039. if (flags & PNG_FLAG_FILLER_AFTER)
  198040. {
  198041. /* This converts from GGXX or GGAA to GG */
  198042. sp += 4; dp += 2;
  198043. for (i = 1; i < row_width; i++)
  198044. {
  198045. *dp++ = *sp++;
  198046. *dp++ = *sp++;
  198047. sp += 2;
  198048. }
  198049. }
  198050. else
  198051. {
  198052. /* This converts from XXGG or AAGG to GG */
  198053. for (i = 0; i < row_width; i++)
  198054. {
  198055. sp += 2;
  198056. *dp++ = *sp++;
  198057. *dp++ = *sp++;
  198058. }
  198059. }
  198060. row_info->pixel_depth = 16;
  198061. row_info->rowbytes = row_width * 2;
  198062. }
  198063. row_info->channels = 1;
  198064. }
  198065. if (flags & PNG_FLAG_STRIP_ALPHA)
  198066. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198067. }
  198068. }
  198069. #endif
  198070. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198071. /* swaps red and blue bytes within a pixel */
  198072. void /* PRIVATE */
  198073. png_do_bgr(png_row_infop row_info, png_bytep row)
  198074. {
  198075. png_debug(1, "in png_do_bgr\n");
  198076. if (
  198077. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198078. row != NULL && row_info != NULL &&
  198079. #endif
  198080. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198081. {
  198082. png_uint_32 row_width = row_info->width;
  198083. if (row_info->bit_depth == 8)
  198084. {
  198085. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198086. {
  198087. png_bytep rp;
  198088. png_uint_32 i;
  198089. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198090. {
  198091. png_byte save = *rp;
  198092. *rp = *(rp + 2);
  198093. *(rp + 2) = save;
  198094. }
  198095. }
  198096. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198097. {
  198098. png_bytep rp;
  198099. png_uint_32 i;
  198100. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198101. {
  198102. png_byte save = *rp;
  198103. *rp = *(rp + 2);
  198104. *(rp + 2) = save;
  198105. }
  198106. }
  198107. }
  198108. else if (row_info->bit_depth == 16)
  198109. {
  198110. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198111. {
  198112. png_bytep rp;
  198113. png_uint_32 i;
  198114. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198115. {
  198116. png_byte save = *rp;
  198117. *rp = *(rp + 4);
  198118. *(rp + 4) = save;
  198119. save = *(rp + 1);
  198120. *(rp + 1) = *(rp + 5);
  198121. *(rp + 5) = save;
  198122. }
  198123. }
  198124. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198125. {
  198126. png_bytep rp;
  198127. png_uint_32 i;
  198128. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198129. {
  198130. png_byte save = *rp;
  198131. *rp = *(rp + 4);
  198132. *(rp + 4) = save;
  198133. save = *(rp + 1);
  198134. *(rp + 1) = *(rp + 5);
  198135. *(rp + 5) = save;
  198136. }
  198137. }
  198138. }
  198139. }
  198140. }
  198141. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198142. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198143. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198144. defined(PNG_LEGACY_SUPPORTED)
  198145. void PNGAPI
  198146. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198147. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198148. {
  198149. png_debug(1, "in png_set_user_transform_info\n");
  198150. if(png_ptr == NULL) return;
  198151. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198152. png_ptr->user_transform_ptr = user_transform_ptr;
  198153. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198154. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198155. #else
  198156. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198157. png_warning(png_ptr,
  198158. "This version of libpng does not support user transform info");
  198159. #endif
  198160. }
  198161. #endif
  198162. /* This function returns a pointer to the user_transform_ptr associated with
  198163. * the user transform functions. The application should free any memory
  198164. * associated with this pointer before png_write_destroy and png_read_destroy
  198165. * are called.
  198166. */
  198167. png_voidp PNGAPI
  198168. png_get_user_transform_ptr(png_structp png_ptr)
  198169. {
  198170. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198171. if (png_ptr == NULL) return (NULL);
  198172. return ((png_voidp)png_ptr->user_transform_ptr);
  198173. #else
  198174. return (NULL);
  198175. #endif
  198176. }
  198177. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198178. /*** End of inlined file: pngtrans.c ***/
  198179. /*** Start of inlined file: pngwio.c ***/
  198180. /* pngwio.c - functions for data output
  198181. *
  198182. * Last changed in libpng 1.2.13 November 13, 2006
  198183. * For conditions of distribution and use, see copyright notice in png.h
  198184. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198185. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198186. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198187. *
  198188. * This file provides a location for all output. Users who need
  198189. * special handling are expected to write functions that have the same
  198190. * arguments as these and perform similar functions, but that possibly
  198191. * use different output methods. Note that you shouldn't change these
  198192. * functions, but rather write replacement functions and then change
  198193. * them at run time with png_set_write_fn(...).
  198194. */
  198195. #define PNG_INTERNAL
  198196. #ifdef PNG_WRITE_SUPPORTED
  198197. /* Write the data to whatever output you are using. The default routine
  198198. writes to a file pointer. Note that this routine sometimes gets called
  198199. with very small lengths, so you should implement some kind of simple
  198200. buffering if you are using unbuffered writes. This should never be asked
  198201. to write more than 64K on a 16 bit machine. */
  198202. void /* PRIVATE */
  198203. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198204. {
  198205. if (png_ptr->write_data_fn != NULL )
  198206. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198207. else
  198208. png_error(png_ptr, "Call to NULL write function");
  198209. }
  198210. #if !defined(PNG_NO_STDIO)
  198211. /* This is the function that does the actual writing of data. If you are
  198212. not writing to a standard C stream, you should create a replacement
  198213. write_data function and use it at run time with png_set_write_fn(), rather
  198214. than changing the library. */
  198215. #ifndef USE_FAR_KEYWORD
  198216. void PNGAPI
  198217. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198218. {
  198219. png_uint_32 check;
  198220. if(png_ptr == NULL) return;
  198221. #if defined(_WIN32_WCE)
  198222. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198223. check = 0;
  198224. #else
  198225. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198226. #endif
  198227. if (check != length)
  198228. png_error(png_ptr, "Write Error");
  198229. }
  198230. #else
  198231. /* this is the model-independent version. Since the standard I/O library
  198232. can't handle far buffers in the medium and small models, we have to copy
  198233. the data.
  198234. */
  198235. #define NEAR_BUF_SIZE 1024
  198236. #define MIN(a,b) (a <= b ? a : b)
  198237. void PNGAPI
  198238. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198239. {
  198240. png_uint_32 check;
  198241. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198242. png_FILE_p io_ptr;
  198243. if(png_ptr == NULL) return;
  198244. /* Check if data really is near. If so, use usual code. */
  198245. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198246. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198247. if ((png_bytep)near_data == data)
  198248. {
  198249. #if defined(_WIN32_WCE)
  198250. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198251. check = 0;
  198252. #else
  198253. check = fwrite(near_data, 1, length, io_ptr);
  198254. #endif
  198255. }
  198256. else
  198257. {
  198258. png_byte buf[NEAR_BUF_SIZE];
  198259. png_size_t written, remaining, err;
  198260. check = 0;
  198261. remaining = length;
  198262. do
  198263. {
  198264. written = MIN(NEAR_BUF_SIZE, remaining);
  198265. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198266. #if defined(_WIN32_WCE)
  198267. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198268. err = 0;
  198269. #else
  198270. err = fwrite(buf, 1, written, io_ptr);
  198271. #endif
  198272. if (err != written)
  198273. break;
  198274. else
  198275. check += err;
  198276. data += written;
  198277. remaining -= written;
  198278. }
  198279. while (remaining != 0);
  198280. }
  198281. if (check != length)
  198282. png_error(png_ptr, "Write Error");
  198283. }
  198284. #endif
  198285. #endif
  198286. /* This function is called to output any data pending writing (normally
  198287. to disk). After png_flush is called, there should be no data pending
  198288. writing in any buffers. */
  198289. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198290. void /* PRIVATE */
  198291. png_flush(png_structp png_ptr)
  198292. {
  198293. if (png_ptr->output_flush_fn != NULL)
  198294. (*(png_ptr->output_flush_fn))(png_ptr);
  198295. }
  198296. #if !defined(PNG_NO_STDIO)
  198297. void PNGAPI
  198298. png_default_flush(png_structp png_ptr)
  198299. {
  198300. #if !defined(_WIN32_WCE)
  198301. png_FILE_p io_ptr;
  198302. #endif
  198303. if(png_ptr == NULL) return;
  198304. #if !defined(_WIN32_WCE)
  198305. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198306. if (io_ptr != NULL)
  198307. fflush(io_ptr);
  198308. #endif
  198309. }
  198310. #endif
  198311. #endif
  198312. /* This function allows the application to supply new output functions for
  198313. libpng if standard C streams aren't being used.
  198314. This function takes as its arguments:
  198315. png_ptr - pointer to a png output data structure
  198316. io_ptr - pointer to user supplied structure containing info about
  198317. the output functions. May be NULL.
  198318. write_data_fn - pointer to a new output function that takes as its
  198319. arguments a pointer to a png_struct, a pointer to
  198320. data to be written, and a 32-bit unsigned int that is
  198321. the number of bytes to be written. The new write
  198322. function should call png_error(png_ptr, "Error msg")
  198323. to exit and output any fatal error messages.
  198324. flush_data_fn - pointer to a new flush function that takes as its
  198325. arguments a pointer to a png_struct. After a call to
  198326. the flush function, there should be no data in any buffers
  198327. or pending transmission. If the output method doesn't do
  198328. any buffering of ouput, a function prototype must still be
  198329. supplied although it doesn't have to do anything. If
  198330. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198331. time, output_flush_fn will be ignored, although it must be
  198332. supplied for compatibility. */
  198333. void PNGAPI
  198334. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198335. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198336. {
  198337. if(png_ptr == NULL) return;
  198338. png_ptr->io_ptr = io_ptr;
  198339. #if !defined(PNG_NO_STDIO)
  198340. if (write_data_fn != NULL)
  198341. png_ptr->write_data_fn = write_data_fn;
  198342. else
  198343. png_ptr->write_data_fn = png_default_write_data;
  198344. #else
  198345. png_ptr->write_data_fn = write_data_fn;
  198346. #endif
  198347. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198348. #if !defined(PNG_NO_STDIO)
  198349. if (output_flush_fn != NULL)
  198350. png_ptr->output_flush_fn = output_flush_fn;
  198351. else
  198352. png_ptr->output_flush_fn = png_default_flush;
  198353. #else
  198354. png_ptr->output_flush_fn = output_flush_fn;
  198355. #endif
  198356. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198357. /* It is an error to read while writing a png file */
  198358. if (png_ptr->read_data_fn != NULL)
  198359. {
  198360. png_ptr->read_data_fn = NULL;
  198361. png_warning(png_ptr,
  198362. "Attempted to set both read_data_fn and write_data_fn in");
  198363. png_warning(png_ptr,
  198364. "the same structure. Resetting read_data_fn to NULL.");
  198365. }
  198366. }
  198367. #if defined(USE_FAR_KEYWORD)
  198368. #if defined(_MSC_VER)
  198369. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198370. {
  198371. void *near_ptr;
  198372. void FAR *far_ptr;
  198373. FP_OFF(near_ptr) = FP_OFF(ptr);
  198374. far_ptr = (void FAR *)near_ptr;
  198375. if(check != 0)
  198376. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198377. png_error(png_ptr,"segment lost in conversion");
  198378. return(near_ptr);
  198379. }
  198380. # else
  198381. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198382. {
  198383. void *near_ptr;
  198384. void FAR *far_ptr;
  198385. near_ptr = (void FAR *)ptr;
  198386. far_ptr = (void FAR *)near_ptr;
  198387. if(check != 0)
  198388. if(far_ptr != ptr)
  198389. png_error(png_ptr,"segment lost in conversion");
  198390. return(near_ptr);
  198391. }
  198392. # endif
  198393. # endif
  198394. #endif /* PNG_WRITE_SUPPORTED */
  198395. /*** End of inlined file: pngwio.c ***/
  198396. /*** Start of inlined file: pngwrite.c ***/
  198397. /* pngwrite.c - general routines to write a PNG file
  198398. *
  198399. * Last changed in libpng 1.2.15 January 5, 2007
  198400. * For conditions of distribution and use, see copyright notice in png.h
  198401. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198402. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198403. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198404. */
  198405. /* get internal access to png.h */
  198406. #define PNG_INTERNAL
  198407. #ifdef PNG_WRITE_SUPPORTED
  198408. /* Writes all the PNG information. This is the suggested way to use the
  198409. * library. If you have a new chunk to add, make a function to write it,
  198410. * and put it in the correct location here. If you want the chunk written
  198411. * after the image data, put it in png_write_end(). I strongly encourage
  198412. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198413. * the chunk, as that will keep the code from breaking if you want to just
  198414. * write a plain PNG file. If you have long comments, I suggest writing
  198415. * them in png_write_end(), and compressing them.
  198416. */
  198417. void PNGAPI
  198418. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198419. {
  198420. png_debug(1, "in png_write_info_before_PLTE\n");
  198421. if (png_ptr == NULL || info_ptr == NULL)
  198422. return;
  198423. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198424. {
  198425. png_write_sig(png_ptr); /* write PNG signature */
  198426. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198427. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198428. {
  198429. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198430. png_ptr->mng_features_permitted=0;
  198431. }
  198432. #endif
  198433. /* write IHDR information. */
  198434. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198435. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198436. info_ptr->filter_type,
  198437. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198438. info_ptr->interlace_type);
  198439. #else
  198440. 0);
  198441. #endif
  198442. /* the rest of these check to see if the valid field has the appropriate
  198443. flag set, and if it does, writes the chunk. */
  198444. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198445. if (info_ptr->valid & PNG_INFO_gAMA)
  198446. {
  198447. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198448. png_write_gAMA(png_ptr, info_ptr->gamma);
  198449. #else
  198450. #ifdef PNG_FIXED_POINT_SUPPORTED
  198451. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198452. # endif
  198453. #endif
  198454. }
  198455. #endif
  198456. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198457. if (info_ptr->valid & PNG_INFO_sRGB)
  198458. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198459. #endif
  198460. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198461. if (info_ptr->valid & PNG_INFO_iCCP)
  198462. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198463. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198464. #endif
  198465. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198466. if (info_ptr->valid & PNG_INFO_sBIT)
  198467. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198468. #endif
  198469. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198470. if (info_ptr->valid & PNG_INFO_cHRM)
  198471. {
  198472. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198473. png_write_cHRM(png_ptr,
  198474. info_ptr->x_white, info_ptr->y_white,
  198475. info_ptr->x_red, info_ptr->y_red,
  198476. info_ptr->x_green, info_ptr->y_green,
  198477. info_ptr->x_blue, info_ptr->y_blue);
  198478. #else
  198479. # ifdef PNG_FIXED_POINT_SUPPORTED
  198480. png_write_cHRM_fixed(png_ptr,
  198481. info_ptr->int_x_white, info_ptr->int_y_white,
  198482. info_ptr->int_x_red, info_ptr->int_y_red,
  198483. info_ptr->int_x_green, info_ptr->int_y_green,
  198484. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198485. # endif
  198486. #endif
  198487. }
  198488. #endif
  198489. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198490. if (info_ptr->unknown_chunks_num)
  198491. {
  198492. png_unknown_chunk *up;
  198493. png_debug(5, "writing extra chunks\n");
  198494. for (up = info_ptr->unknown_chunks;
  198495. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198496. up++)
  198497. {
  198498. int keep=png_handle_as_unknown(png_ptr, up->name);
  198499. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198500. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198501. !(up->location & PNG_HAVE_IDAT) &&
  198502. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198503. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198504. {
  198505. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198506. }
  198507. }
  198508. }
  198509. #endif
  198510. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198511. }
  198512. }
  198513. void PNGAPI
  198514. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198515. {
  198516. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198517. int i;
  198518. #endif
  198519. png_debug(1, "in png_write_info\n");
  198520. if (png_ptr == NULL || info_ptr == NULL)
  198521. return;
  198522. png_write_info_before_PLTE(png_ptr, info_ptr);
  198523. if (info_ptr->valid & PNG_INFO_PLTE)
  198524. png_write_PLTE(png_ptr, info_ptr->palette,
  198525. (png_uint_32)info_ptr->num_palette);
  198526. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198527. png_error(png_ptr, "Valid palette required for paletted images");
  198528. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198529. if (info_ptr->valid & PNG_INFO_tRNS)
  198530. {
  198531. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198532. /* invert the alpha channel (in tRNS) */
  198533. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198534. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198535. {
  198536. int j;
  198537. for (j=0; j<(int)info_ptr->num_trans; j++)
  198538. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198539. }
  198540. #endif
  198541. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198542. info_ptr->num_trans, info_ptr->color_type);
  198543. }
  198544. #endif
  198545. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198546. if (info_ptr->valid & PNG_INFO_bKGD)
  198547. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198548. #endif
  198549. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198550. if (info_ptr->valid & PNG_INFO_hIST)
  198551. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198552. #endif
  198553. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198554. if (info_ptr->valid & PNG_INFO_oFFs)
  198555. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198556. info_ptr->offset_unit_type);
  198557. #endif
  198558. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198559. if (info_ptr->valid & PNG_INFO_pCAL)
  198560. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198561. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198562. info_ptr->pcal_units, info_ptr->pcal_params);
  198563. #endif
  198564. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198565. if (info_ptr->valid & PNG_INFO_sCAL)
  198566. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198567. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198568. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198569. #else
  198570. #ifdef PNG_FIXED_POINT_SUPPORTED
  198571. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198572. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198573. #else
  198574. png_warning(png_ptr,
  198575. "png_write_sCAL not supported; sCAL chunk not written.");
  198576. #endif
  198577. #endif
  198578. #endif
  198579. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198580. if (info_ptr->valid & PNG_INFO_pHYs)
  198581. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198582. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198583. #endif
  198584. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198585. if (info_ptr->valid & PNG_INFO_tIME)
  198586. {
  198587. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198588. png_ptr->mode |= PNG_WROTE_tIME;
  198589. }
  198590. #endif
  198591. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198592. if (info_ptr->valid & PNG_INFO_sPLT)
  198593. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198594. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198595. #endif
  198596. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198597. /* Check to see if we need to write text chunks */
  198598. for (i = 0; i < info_ptr->num_text; i++)
  198599. {
  198600. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198601. info_ptr->text[i].compression);
  198602. /* an internationalized chunk? */
  198603. if (info_ptr->text[i].compression > 0)
  198604. {
  198605. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198606. /* write international chunk */
  198607. png_write_iTXt(png_ptr,
  198608. info_ptr->text[i].compression,
  198609. info_ptr->text[i].key,
  198610. info_ptr->text[i].lang,
  198611. info_ptr->text[i].lang_key,
  198612. info_ptr->text[i].text);
  198613. #else
  198614. png_warning(png_ptr, "Unable to write international text");
  198615. #endif
  198616. /* Mark this chunk as written */
  198617. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198618. }
  198619. /* If we want a compressed text chunk */
  198620. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198621. {
  198622. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198623. /* write compressed chunk */
  198624. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198625. info_ptr->text[i].text, 0,
  198626. info_ptr->text[i].compression);
  198627. #else
  198628. png_warning(png_ptr, "Unable to write compressed text");
  198629. #endif
  198630. /* Mark this chunk as written */
  198631. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198632. }
  198633. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198634. {
  198635. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198636. /* write uncompressed chunk */
  198637. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198638. info_ptr->text[i].text,
  198639. 0);
  198640. #else
  198641. png_warning(png_ptr, "Unable to write uncompressed text");
  198642. #endif
  198643. /* Mark this chunk as written */
  198644. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198645. }
  198646. }
  198647. #endif
  198648. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198649. if (info_ptr->unknown_chunks_num)
  198650. {
  198651. png_unknown_chunk *up;
  198652. png_debug(5, "writing extra chunks\n");
  198653. for (up = info_ptr->unknown_chunks;
  198654. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198655. up++)
  198656. {
  198657. int keep=png_handle_as_unknown(png_ptr, up->name);
  198658. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198659. up->location && (up->location & PNG_HAVE_PLTE) &&
  198660. !(up->location & PNG_HAVE_IDAT) &&
  198661. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198662. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198663. {
  198664. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198665. }
  198666. }
  198667. }
  198668. #endif
  198669. }
  198670. /* Writes the end of the PNG file. If you don't want to write comments or
  198671. * time information, you can pass NULL for info. If you already wrote these
  198672. * in png_write_info(), do not write them again here. If you have long
  198673. * comments, I suggest writing them here, and compressing them.
  198674. */
  198675. void PNGAPI
  198676. png_write_end(png_structp png_ptr, png_infop info_ptr)
  198677. {
  198678. png_debug(1, "in png_write_end\n");
  198679. if (png_ptr == NULL)
  198680. return;
  198681. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  198682. png_error(png_ptr, "No IDATs written into file");
  198683. /* see if user wants us to write information chunks */
  198684. if (info_ptr != NULL)
  198685. {
  198686. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198687. int i; /* local index variable */
  198688. #endif
  198689. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198690. /* check to see if user has supplied a time chunk */
  198691. if ((info_ptr->valid & PNG_INFO_tIME) &&
  198692. !(png_ptr->mode & PNG_WROTE_tIME))
  198693. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198694. #endif
  198695. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198696. /* loop through comment chunks */
  198697. for (i = 0; i < info_ptr->num_text; i++)
  198698. {
  198699. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  198700. info_ptr->text[i].compression);
  198701. /* an internationalized chunk? */
  198702. if (info_ptr->text[i].compression > 0)
  198703. {
  198704. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198705. /* write international chunk */
  198706. png_write_iTXt(png_ptr,
  198707. info_ptr->text[i].compression,
  198708. info_ptr->text[i].key,
  198709. info_ptr->text[i].lang,
  198710. info_ptr->text[i].lang_key,
  198711. info_ptr->text[i].text);
  198712. #else
  198713. png_warning(png_ptr, "Unable to write international text");
  198714. #endif
  198715. /* Mark this chunk as written */
  198716. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198717. }
  198718. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  198719. {
  198720. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198721. /* write compressed chunk */
  198722. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198723. info_ptr->text[i].text, 0,
  198724. info_ptr->text[i].compression);
  198725. #else
  198726. png_warning(png_ptr, "Unable to write compressed text");
  198727. #endif
  198728. /* Mark this chunk as written */
  198729. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198730. }
  198731. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198732. {
  198733. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198734. /* write uncompressed chunk */
  198735. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198736. info_ptr->text[i].text, 0);
  198737. #else
  198738. png_warning(png_ptr, "Unable to write uncompressed text");
  198739. #endif
  198740. /* Mark this chunk as written */
  198741. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198742. }
  198743. }
  198744. #endif
  198745. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198746. if (info_ptr->unknown_chunks_num)
  198747. {
  198748. png_unknown_chunk *up;
  198749. png_debug(5, "writing extra chunks\n");
  198750. for (up = info_ptr->unknown_chunks;
  198751. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198752. up++)
  198753. {
  198754. int keep=png_handle_as_unknown(png_ptr, up->name);
  198755. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198756. up->location && (up->location & PNG_AFTER_IDAT) &&
  198757. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198758. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198759. {
  198760. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198761. }
  198762. }
  198763. }
  198764. #endif
  198765. }
  198766. png_ptr->mode |= PNG_AFTER_IDAT;
  198767. /* write end of PNG file */
  198768. png_write_IEND(png_ptr);
  198769. }
  198770. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198771. #if !defined(_WIN32_WCE)
  198772. /* "time.h" functions are not supported on WindowsCE */
  198773. void PNGAPI
  198774. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  198775. {
  198776. png_debug(1, "in png_convert_from_struct_tm\n");
  198777. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  198778. ptime->month = (png_byte)(ttime->tm_mon + 1);
  198779. ptime->day = (png_byte)ttime->tm_mday;
  198780. ptime->hour = (png_byte)ttime->tm_hour;
  198781. ptime->minute = (png_byte)ttime->tm_min;
  198782. ptime->second = (png_byte)ttime->tm_sec;
  198783. }
  198784. void PNGAPI
  198785. png_convert_from_time_t(png_timep ptime, time_t ttime)
  198786. {
  198787. struct tm *tbuf;
  198788. png_debug(1, "in png_convert_from_time_t\n");
  198789. tbuf = gmtime(&ttime);
  198790. png_convert_from_struct_tm(ptime, tbuf);
  198791. }
  198792. #endif
  198793. #endif
  198794. /* Initialize png_ptr structure, and allocate any memory needed */
  198795. png_structp PNGAPI
  198796. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  198797. png_error_ptr error_fn, png_error_ptr warn_fn)
  198798. {
  198799. #ifdef PNG_USER_MEM_SUPPORTED
  198800. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  198801. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  198802. }
  198803. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  198804. png_structp PNGAPI
  198805. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  198806. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  198807. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  198808. {
  198809. #endif /* PNG_USER_MEM_SUPPORTED */
  198810. png_structp png_ptr;
  198811. #ifdef PNG_SETJMP_SUPPORTED
  198812. #ifdef USE_FAR_KEYWORD
  198813. jmp_buf jmpbuf;
  198814. #endif
  198815. #endif
  198816. int i;
  198817. png_debug(1, "in png_create_write_struct\n");
  198818. #ifdef PNG_USER_MEM_SUPPORTED
  198819. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  198820. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  198821. #else
  198822. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  198823. #endif /* PNG_USER_MEM_SUPPORTED */
  198824. if (png_ptr == NULL)
  198825. return (NULL);
  198826. /* added at libpng-1.2.6 */
  198827. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198828. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  198829. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  198830. #endif
  198831. #ifdef PNG_SETJMP_SUPPORTED
  198832. #ifdef USE_FAR_KEYWORD
  198833. if (setjmp(jmpbuf))
  198834. #else
  198835. if (setjmp(png_ptr->jmpbuf))
  198836. #endif
  198837. {
  198838. png_free(png_ptr, png_ptr->zbuf);
  198839. png_ptr->zbuf=NULL;
  198840. png_destroy_struct(png_ptr);
  198841. return (NULL);
  198842. }
  198843. #ifdef USE_FAR_KEYWORD
  198844. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198845. #endif
  198846. #endif
  198847. #ifdef PNG_USER_MEM_SUPPORTED
  198848. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  198849. #endif /* PNG_USER_MEM_SUPPORTED */
  198850. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  198851. i=0;
  198852. do
  198853. {
  198854. if(user_png_ver[i] != png_libpng_ver[i])
  198855. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198856. } while (png_libpng_ver[i++]);
  198857. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  198858. {
  198859. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  198860. * we must recompile any applications that use any older library version.
  198861. * For versions after libpng 1.0, we will be compatible, so we need
  198862. * only check the first digit.
  198863. */
  198864. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  198865. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  198866. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  198867. {
  198868. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198869. char msg[80];
  198870. if (user_png_ver)
  198871. {
  198872. png_snprintf(msg, 80,
  198873. "Application was compiled with png.h from libpng-%.20s",
  198874. user_png_ver);
  198875. png_warning(png_ptr, msg);
  198876. }
  198877. png_snprintf(msg, 80,
  198878. "Application is running with png.c from libpng-%.20s",
  198879. png_libpng_ver);
  198880. png_warning(png_ptr, msg);
  198881. #endif
  198882. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198883. png_ptr->flags=0;
  198884. #endif
  198885. png_error(png_ptr,
  198886. "Incompatible libpng version in application and library");
  198887. }
  198888. }
  198889. /* initialize zbuf - compression buffer */
  198890. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  198891. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  198892. (png_uint_32)png_ptr->zbuf_size);
  198893. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  198894. png_flush_ptr_NULL);
  198895. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198896. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  198897. 1, png_doublep_NULL, png_doublep_NULL);
  198898. #endif
  198899. #ifdef PNG_SETJMP_SUPPORTED
  198900. /* Applications that neglect to set up their own setjmp() and then encounter
  198901. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  198902. abort instead of returning. */
  198903. #ifdef USE_FAR_KEYWORD
  198904. if (setjmp(jmpbuf))
  198905. PNG_ABORT();
  198906. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  198907. #else
  198908. if (setjmp(png_ptr->jmpbuf))
  198909. PNG_ABORT();
  198910. #endif
  198911. #endif
  198912. return (png_ptr);
  198913. }
  198914. /* Initialize png_ptr structure, and allocate any memory needed */
  198915. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198916. /* Deprecated. */
  198917. #undef png_write_init
  198918. void PNGAPI
  198919. png_write_init(png_structp png_ptr)
  198920. {
  198921. /* We only come here via pre-1.0.7-compiled applications */
  198922. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  198923. }
  198924. void PNGAPI
  198925. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  198926. png_size_t png_struct_size, png_size_t png_info_size)
  198927. {
  198928. /* We only come here via pre-1.0.12-compiled applications */
  198929. if(png_ptr == NULL) return;
  198930. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  198931. if(png_sizeof(png_struct) > png_struct_size ||
  198932. png_sizeof(png_info) > png_info_size)
  198933. {
  198934. char msg[80];
  198935. png_ptr->warning_fn=NULL;
  198936. if (user_png_ver)
  198937. {
  198938. png_snprintf(msg, 80,
  198939. "Application was compiled with png.h from libpng-%.20s",
  198940. user_png_ver);
  198941. png_warning(png_ptr, msg);
  198942. }
  198943. png_snprintf(msg, 80,
  198944. "Application is running with png.c from libpng-%.20s",
  198945. png_libpng_ver);
  198946. png_warning(png_ptr, msg);
  198947. }
  198948. #endif
  198949. if(png_sizeof(png_struct) > png_struct_size)
  198950. {
  198951. png_ptr->error_fn=NULL;
  198952. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198953. png_ptr->flags=0;
  198954. #endif
  198955. png_error(png_ptr,
  198956. "The png struct allocated by the application for writing is too small.");
  198957. }
  198958. if(png_sizeof(png_info) > png_info_size)
  198959. {
  198960. png_ptr->error_fn=NULL;
  198961. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  198962. png_ptr->flags=0;
  198963. #endif
  198964. png_error(png_ptr,
  198965. "The info struct allocated by the application for writing is too small.");
  198966. }
  198967. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  198968. }
  198969. #endif /* PNG_1_0_X || PNG_1_2_X */
  198970. void PNGAPI
  198971. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  198972. png_size_t png_struct_size)
  198973. {
  198974. png_structp png_ptr=*ptr_ptr;
  198975. #ifdef PNG_SETJMP_SUPPORTED
  198976. jmp_buf tmp_jmp; /* to save current jump buffer */
  198977. #endif
  198978. int i = 0;
  198979. if (png_ptr == NULL)
  198980. return;
  198981. do
  198982. {
  198983. if (user_png_ver[i] != png_libpng_ver[i])
  198984. {
  198985. #ifdef PNG_LEGACY_SUPPORTED
  198986. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  198987. #else
  198988. png_ptr->warning_fn=NULL;
  198989. png_warning(png_ptr,
  198990. "Application uses deprecated png_write_init() and should be recompiled.");
  198991. break;
  198992. #endif
  198993. }
  198994. } while (png_libpng_ver[i++]);
  198995. png_debug(1, "in png_write_init_3\n");
  198996. #ifdef PNG_SETJMP_SUPPORTED
  198997. /* save jump buffer and error functions */
  198998. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  198999. #endif
  199000. if (png_sizeof(png_struct) > png_struct_size)
  199001. {
  199002. png_destroy_struct(png_ptr);
  199003. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199004. *ptr_ptr = png_ptr;
  199005. }
  199006. /* reset all variables to 0 */
  199007. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199008. /* added at libpng-1.2.6 */
  199009. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199010. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199011. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199012. #endif
  199013. #ifdef PNG_SETJMP_SUPPORTED
  199014. /* restore jump buffer */
  199015. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199016. #endif
  199017. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199018. png_flush_ptr_NULL);
  199019. /* initialize zbuf - compression buffer */
  199020. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199021. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199022. (png_uint_32)png_ptr->zbuf_size);
  199023. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199024. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199025. 1, png_doublep_NULL, png_doublep_NULL);
  199026. #endif
  199027. }
  199028. /* Write a few rows of image data. If the image is interlaced,
  199029. * either you will have to write the 7 sub images, or, if you
  199030. * have called png_set_interlace_handling(), you will have to
  199031. * "write" the image seven times.
  199032. */
  199033. void PNGAPI
  199034. png_write_rows(png_structp png_ptr, png_bytepp row,
  199035. png_uint_32 num_rows)
  199036. {
  199037. png_uint_32 i; /* row counter */
  199038. png_bytepp rp; /* row pointer */
  199039. png_debug(1, "in png_write_rows\n");
  199040. if (png_ptr == NULL)
  199041. return;
  199042. /* loop through the rows */
  199043. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199044. {
  199045. png_write_row(png_ptr, *rp);
  199046. }
  199047. }
  199048. /* Write the image. You only need to call this function once, even
  199049. * if you are writing an interlaced image.
  199050. */
  199051. void PNGAPI
  199052. png_write_image(png_structp png_ptr, png_bytepp image)
  199053. {
  199054. png_uint_32 i; /* row index */
  199055. int pass, num_pass; /* pass variables */
  199056. png_bytepp rp; /* points to current row */
  199057. if (png_ptr == NULL)
  199058. return;
  199059. png_debug(1, "in png_write_image\n");
  199060. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199061. /* intialize interlace handling. If image is not interlaced,
  199062. this will set pass to 1 */
  199063. num_pass = png_set_interlace_handling(png_ptr);
  199064. #else
  199065. num_pass = 1;
  199066. #endif
  199067. /* loop through passes */
  199068. for (pass = 0; pass < num_pass; pass++)
  199069. {
  199070. /* loop through image */
  199071. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199072. {
  199073. png_write_row(png_ptr, *rp);
  199074. }
  199075. }
  199076. }
  199077. /* called by user to write a row of image data */
  199078. void PNGAPI
  199079. png_write_row(png_structp png_ptr, png_bytep row)
  199080. {
  199081. if (png_ptr == NULL)
  199082. return;
  199083. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199084. png_ptr->row_number, png_ptr->pass);
  199085. /* initialize transformations and other stuff if first time */
  199086. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199087. {
  199088. /* make sure we wrote the header info */
  199089. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199090. png_error(png_ptr,
  199091. "png_write_info was never called before png_write_row.");
  199092. /* check for transforms that have been set but were defined out */
  199093. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199094. if (png_ptr->transformations & PNG_INVERT_MONO)
  199095. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199096. #endif
  199097. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199098. if (png_ptr->transformations & PNG_FILLER)
  199099. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199100. #endif
  199101. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199102. if (png_ptr->transformations & PNG_PACKSWAP)
  199103. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199104. #endif
  199105. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199106. if (png_ptr->transformations & PNG_PACK)
  199107. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199108. #endif
  199109. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199110. if (png_ptr->transformations & PNG_SHIFT)
  199111. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199112. #endif
  199113. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199114. if (png_ptr->transformations & PNG_BGR)
  199115. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199116. #endif
  199117. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199118. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199119. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199120. #endif
  199121. png_write_start_row(png_ptr);
  199122. }
  199123. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199124. /* if interlaced and not interested in row, return */
  199125. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199126. {
  199127. switch (png_ptr->pass)
  199128. {
  199129. case 0:
  199130. if (png_ptr->row_number & 0x07)
  199131. {
  199132. png_write_finish_row(png_ptr);
  199133. return;
  199134. }
  199135. break;
  199136. case 1:
  199137. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199138. {
  199139. png_write_finish_row(png_ptr);
  199140. return;
  199141. }
  199142. break;
  199143. case 2:
  199144. if ((png_ptr->row_number & 0x07) != 4)
  199145. {
  199146. png_write_finish_row(png_ptr);
  199147. return;
  199148. }
  199149. break;
  199150. case 3:
  199151. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199152. {
  199153. png_write_finish_row(png_ptr);
  199154. return;
  199155. }
  199156. break;
  199157. case 4:
  199158. if ((png_ptr->row_number & 0x03) != 2)
  199159. {
  199160. png_write_finish_row(png_ptr);
  199161. return;
  199162. }
  199163. break;
  199164. case 5:
  199165. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199166. {
  199167. png_write_finish_row(png_ptr);
  199168. return;
  199169. }
  199170. break;
  199171. case 6:
  199172. if (!(png_ptr->row_number & 0x01))
  199173. {
  199174. png_write_finish_row(png_ptr);
  199175. return;
  199176. }
  199177. break;
  199178. }
  199179. }
  199180. #endif
  199181. /* set up row info for transformations */
  199182. png_ptr->row_info.color_type = png_ptr->color_type;
  199183. png_ptr->row_info.width = png_ptr->usr_width;
  199184. png_ptr->row_info.channels = png_ptr->usr_channels;
  199185. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199186. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199187. png_ptr->row_info.channels);
  199188. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199189. png_ptr->row_info.width);
  199190. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199191. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199192. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199193. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199194. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199195. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199196. /* Copy user's row into buffer, leaving room for filter byte. */
  199197. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199198. png_ptr->row_info.rowbytes);
  199199. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199200. /* handle interlacing */
  199201. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199202. (png_ptr->transformations & PNG_INTERLACE))
  199203. {
  199204. png_do_write_interlace(&(png_ptr->row_info),
  199205. png_ptr->row_buf + 1, png_ptr->pass);
  199206. /* this should always get caught above, but still ... */
  199207. if (!(png_ptr->row_info.width))
  199208. {
  199209. png_write_finish_row(png_ptr);
  199210. return;
  199211. }
  199212. }
  199213. #endif
  199214. /* handle other transformations */
  199215. if (png_ptr->transformations)
  199216. png_do_write_transformations(png_ptr);
  199217. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199218. /* Write filter_method 64 (intrapixel differencing) only if
  199219. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199220. * 2. Libpng did not write a PNG signature (this filter_method is only
  199221. * used in PNG datastreams that are embedded in MNG datastreams) and
  199222. * 3. The application called png_permit_mng_features with a mask that
  199223. * included PNG_FLAG_MNG_FILTER_64 and
  199224. * 4. The filter_method is 64 and
  199225. * 5. The color_type is RGB or RGBA
  199226. */
  199227. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199228. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199229. {
  199230. /* Intrapixel differencing */
  199231. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199232. }
  199233. #endif
  199234. /* Find a filter if necessary, filter the row and write it out. */
  199235. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199236. if (png_ptr->write_row_fn != NULL)
  199237. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199238. }
  199239. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199240. /* Set the automatic flush interval or 0 to turn flushing off */
  199241. void PNGAPI
  199242. png_set_flush(png_structp png_ptr, int nrows)
  199243. {
  199244. png_debug(1, "in png_set_flush\n");
  199245. if (png_ptr == NULL)
  199246. return;
  199247. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199248. }
  199249. /* flush the current output buffers now */
  199250. void PNGAPI
  199251. png_write_flush(png_structp png_ptr)
  199252. {
  199253. int wrote_IDAT;
  199254. png_debug(1, "in png_write_flush\n");
  199255. if (png_ptr == NULL)
  199256. return;
  199257. /* We have already written out all of the data */
  199258. if (png_ptr->row_number >= png_ptr->num_rows)
  199259. return;
  199260. do
  199261. {
  199262. int ret;
  199263. /* compress the data */
  199264. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199265. wrote_IDAT = 0;
  199266. /* check for compression errors */
  199267. if (ret != Z_OK)
  199268. {
  199269. if (png_ptr->zstream.msg != NULL)
  199270. png_error(png_ptr, png_ptr->zstream.msg);
  199271. else
  199272. png_error(png_ptr, "zlib error");
  199273. }
  199274. if (!(png_ptr->zstream.avail_out))
  199275. {
  199276. /* write the IDAT and reset the zlib output buffer */
  199277. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199278. png_ptr->zbuf_size);
  199279. png_ptr->zstream.next_out = png_ptr->zbuf;
  199280. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199281. wrote_IDAT = 1;
  199282. }
  199283. } while(wrote_IDAT == 1);
  199284. /* If there is any data left to be output, write it into a new IDAT */
  199285. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199286. {
  199287. /* write the IDAT and reset the zlib output buffer */
  199288. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199289. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199290. png_ptr->zstream.next_out = png_ptr->zbuf;
  199291. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199292. }
  199293. png_ptr->flush_rows = 0;
  199294. png_flush(png_ptr);
  199295. }
  199296. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199297. /* free all memory used by the write */
  199298. void PNGAPI
  199299. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199300. {
  199301. png_structp png_ptr = NULL;
  199302. png_infop info_ptr = NULL;
  199303. #ifdef PNG_USER_MEM_SUPPORTED
  199304. png_free_ptr free_fn = NULL;
  199305. png_voidp mem_ptr = NULL;
  199306. #endif
  199307. png_debug(1, "in png_destroy_write_struct\n");
  199308. if (png_ptr_ptr != NULL)
  199309. {
  199310. png_ptr = *png_ptr_ptr;
  199311. #ifdef PNG_USER_MEM_SUPPORTED
  199312. free_fn = png_ptr->free_fn;
  199313. mem_ptr = png_ptr->mem_ptr;
  199314. #endif
  199315. }
  199316. if (info_ptr_ptr != NULL)
  199317. info_ptr = *info_ptr_ptr;
  199318. if (info_ptr != NULL)
  199319. {
  199320. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199321. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199322. if (png_ptr->num_chunk_list)
  199323. {
  199324. png_free(png_ptr, png_ptr->chunk_list);
  199325. png_ptr->chunk_list=NULL;
  199326. png_ptr->num_chunk_list=0;
  199327. }
  199328. #endif
  199329. #ifdef PNG_USER_MEM_SUPPORTED
  199330. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199331. (png_voidp)mem_ptr);
  199332. #else
  199333. png_destroy_struct((png_voidp)info_ptr);
  199334. #endif
  199335. *info_ptr_ptr = NULL;
  199336. }
  199337. if (png_ptr != NULL)
  199338. {
  199339. png_write_destroy(png_ptr);
  199340. #ifdef PNG_USER_MEM_SUPPORTED
  199341. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199342. (png_voidp)mem_ptr);
  199343. #else
  199344. png_destroy_struct((png_voidp)png_ptr);
  199345. #endif
  199346. *png_ptr_ptr = NULL;
  199347. }
  199348. }
  199349. /* Free any memory used in png_ptr struct (old method) */
  199350. void /* PRIVATE */
  199351. png_write_destroy(png_structp png_ptr)
  199352. {
  199353. #ifdef PNG_SETJMP_SUPPORTED
  199354. jmp_buf tmp_jmp; /* save jump buffer */
  199355. #endif
  199356. png_error_ptr error_fn;
  199357. png_error_ptr warning_fn;
  199358. png_voidp error_ptr;
  199359. #ifdef PNG_USER_MEM_SUPPORTED
  199360. png_free_ptr free_fn;
  199361. #endif
  199362. png_debug(1, "in png_write_destroy\n");
  199363. /* free any memory zlib uses */
  199364. deflateEnd(&png_ptr->zstream);
  199365. /* free our memory. png_free checks NULL for us. */
  199366. png_free(png_ptr, png_ptr->zbuf);
  199367. png_free(png_ptr, png_ptr->row_buf);
  199368. png_free(png_ptr, png_ptr->prev_row);
  199369. png_free(png_ptr, png_ptr->sub_row);
  199370. png_free(png_ptr, png_ptr->up_row);
  199371. png_free(png_ptr, png_ptr->avg_row);
  199372. png_free(png_ptr, png_ptr->paeth_row);
  199373. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199374. png_free(png_ptr, png_ptr->time_buffer);
  199375. #endif
  199376. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199377. png_free(png_ptr, png_ptr->prev_filters);
  199378. png_free(png_ptr, png_ptr->filter_weights);
  199379. png_free(png_ptr, png_ptr->inv_filter_weights);
  199380. png_free(png_ptr, png_ptr->filter_costs);
  199381. png_free(png_ptr, png_ptr->inv_filter_costs);
  199382. #endif
  199383. #ifdef PNG_SETJMP_SUPPORTED
  199384. /* reset structure */
  199385. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199386. #endif
  199387. error_fn = png_ptr->error_fn;
  199388. warning_fn = png_ptr->warning_fn;
  199389. error_ptr = png_ptr->error_ptr;
  199390. #ifdef PNG_USER_MEM_SUPPORTED
  199391. free_fn = png_ptr->free_fn;
  199392. #endif
  199393. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199394. png_ptr->error_fn = error_fn;
  199395. png_ptr->warning_fn = warning_fn;
  199396. png_ptr->error_ptr = error_ptr;
  199397. #ifdef PNG_USER_MEM_SUPPORTED
  199398. png_ptr->free_fn = free_fn;
  199399. #endif
  199400. #ifdef PNG_SETJMP_SUPPORTED
  199401. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199402. #endif
  199403. }
  199404. /* Allow the application to select one or more row filters to use. */
  199405. void PNGAPI
  199406. png_set_filter(png_structp png_ptr, int method, int filters)
  199407. {
  199408. png_debug(1, "in png_set_filter\n");
  199409. if (png_ptr == NULL)
  199410. return;
  199411. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199412. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199413. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199414. method = PNG_FILTER_TYPE_BASE;
  199415. #endif
  199416. if (method == PNG_FILTER_TYPE_BASE)
  199417. {
  199418. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199419. {
  199420. #ifndef PNG_NO_WRITE_FILTER
  199421. case 5:
  199422. case 6:
  199423. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199424. #endif /* PNG_NO_WRITE_FILTER */
  199425. case PNG_FILTER_VALUE_NONE:
  199426. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199427. #ifndef PNG_NO_WRITE_FILTER
  199428. case PNG_FILTER_VALUE_SUB:
  199429. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199430. case PNG_FILTER_VALUE_UP:
  199431. png_ptr->do_filter=PNG_FILTER_UP; break;
  199432. case PNG_FILTER_VALUE_AVG:
  199433. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199434. case PNG_FILTER_VALUE_PAETH:
  199435. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199436. default: png_ptr->do_filter = (png_byte)filters; break;
  199437. #else
  199438. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199439. #endif /* PNG_NO_WRITE_FILTER */
  199440. }
  199441. /* If we have allocated the row_buf, this means we have already started
  199442. * with the image and we should have allocated all of the filter buffers
  199443. * that have been selected. If prev_row isn't already allocated, then
  199444. * it is too late to start using the filters that need it, since we
  199445. * will be missing the data in the previous row. If an application
  199446. * wants to start and stop using particular filters during compression,
  199447. * it should start out with all of the filters, and then add and
  199448. * remove them after the start of compression.
  199449. */
  199450. if (png_ptr->row_buf != NULL)
  199451. {
  199452. #ifndef PNG_NO_WRITE_FILTER
  199453. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199454. {
  199455. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199456. (png_ptr->rowbytes + 1));
  199457. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199458. }
  199459. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199460. {
  199461. if (png_ptr->prev_row == NULL)
  199462. {
  199463. png_warning(png_ptr, "Can't add Up filter after starting");
  199464. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199465. }
  199466. else
  199467. {
  199468. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199469. (png_ptr->rowbytes + 1));
  199470. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199471. }
  199472. }
  199473. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199474. {
  199475. if (png_ptr->prev_row == NULL)
  199476. {
  199477. png_warning(png_ptr, "Can't add Average filter after starting");
  199478. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199479. }
  199480. else
  199481. {
  199482. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199483. (png_ptr->rowbytes + 1));
  199484. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199485. }
  199486. }
  199487. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199488. png_ptr->paeth_row == NULL)
  199489. {
  199490. if (png_ptr->prev_row == NULL)
  199491. {
  199492. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199493. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199494. }
  199495. else
  199496. {
  199497. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199498. (png_ptr->rowbytes + 1));
  199499. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199500. }
  199501. }
  199502. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199503. #endif /* PNG_NO_WRITE_FILTER */
  199504. png_ptr->do_filter = PNG_FILTER_NONE;
  199505. }
  199506. }
  199507. else
  199508. png_error(png_ptr, "Unknown custom filter method");
  199509. }
  199510. /* This allows us to influence the way in which libpng chooses the "best"
  199511. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199512. * differences metric is relatively fast and effective, there is some
  199513. * question as to whether it can be improved upon by trying to keep the
  199514. * filtered data going to zlib more consistent, hopefully resulting in
  199515. * better compression.
  199516. */
  199517. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199518. void PNGAPI
  199519. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199520. int num_weights, png_doublep filter_weights,
  199521. png_doublep filter_costs)
  199522. {
  199523. int i;
  199524. png_debug(1, "in png_set_filter_heuristics\n");
  199525. if (png_ptr == NULL)
  199526. return;
  199527. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199528. {
  199529. png_warning(png_ptr, "Unknown filter heuristic method");
  199530. return;
  199531. }
  199532. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199533. {
  199534. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199535. }
  199536. if (num_weights < 0 || filter_weights == NULL ||
  199537. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199538. {
  199539. num_weights = 0;
  199540. }
  199541. png_ptr->num_prev_filters = (png_byte)num_weights;
  199542. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199543. if (num_weights > 0)
  199544. {
  199545. if (png_ptr->prev_filters == NULL)
  199546. {
  199547. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199548. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199549. /* To make sure that the weighting starts out fairly */
  199550. for (i = 0; i < num_weights; i++)
  199551. {
  199552. png_ptr->prev_filters[i] = 255;
  199553. }
  199554. }
  199555. if (png_ptr->filter_weights == NULL)
  199556. {
  199557. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199558. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199559. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199560. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199561. for (i = 0; i < num_weights; i++)
  199562. {
  199563. png_ptr->inv_filter_weights[i] =
  199564. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199565. }
  199566. }
  199567. for (i = 0; i < num_weights; i++)
  199568. {
  199569. if (filter_weights[i] < 0.0)
  199570. {
  199571. png_ptr->inv_filter_weights[i] =
  199572. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199573. }
  199574. else
  199575. {
  199576. png_ptr->inv_filter_weights[i] =
  199577. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199578. png_ptr->filter_weights[i] =
  199579. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199580. }
  199581. }
  199582. }
  199583. /* If, in the future, there are other filter methods, this would
  199584. * need to be based on png_ptr->filter.
  199585. */
  199586. if (png_ptr->filter_costs == NULL)
  199587. {
  199588. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199589. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199590. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199591. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199592. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199593. {
  199594. png_ptr->inv_filter_costs[i] =
  199595. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199596. }
  199597. }
  199598. /* Here is where we set the relative costs of the different filters. We
  199599. * should take the desired compression level into account when setting
  199600. * the costs, so that Paeth, for instance, has a high relative cost at low
  199601. * compression levels, while it has a lower relative cost at higher
  199602. * compression settings. The filter types are in order of increasing
  199603. * relative cost, so it would be possible to do this with an algorithm.
  199604. */
  199605. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199606. {
  199607. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199608. {
  199609. png_ptr->inv_filter_costs[i] =
  199610. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199611. }
  199612. else if (filter_costs[i] >= 1.0)
  199613. {
  199614. png_ptr->inv_filter_costs[i] =
  199615. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199616. png_ptr->filter_costs[i] =
  199617. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199618. }
  199619. }
  199620. }
  199621. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199622. void PNGAPI
  199623. png_set_compression_level(png_structp png_ptr, int level)
  199624. {
  199625. png_debug(1, "in png_set_compression_level\n");
  199626. if (png_ptr == NULL)
  199627. return;
  199628. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199629. png_ptr->zlib_level = level;
  199630. }
  199631. void PNGAPI
  199632. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199633. {
  199634. png_debug(1, "in png_set_compression_mem_level\n");
  199635. if (png_ptr == NULL)
  199636. return;
  199637. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199638. png_ptr->zlib_mem_level = mem_level;
  199639. }
  199640. void PNGAPI
  199641. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199642. {
  199643. png_debug(1, "in png_set_compression_strategy\n");
  199644. if (png_ptr == NULL)
  199645. return;
  199646. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199647. png_ptr->zlib_strategy = strategy;
  199648. }
  199649. void PNGAPI
  199650. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199651. {
  199652. if (png_ptr == NULL)
  199653. return;
  199654. if (window_bits > 15)
  199655. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199656. else if (window_bits < 8)
  199657. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199658. #ifndef WBITS_8_OK
  199659. /* avoid libpng bug with 256-byte windows */
  199660. if (window_bits == 8)
  199661. {
  199662. png_warning(png_ptr, "Compression window is being reset to 512");
  199663. window_bits=9;
  199664. }
  199665. #endif
  199666. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  199667. png_ptr->zlib_window_bits = window_bits;
  199668. }
  199669. void PNGAPI
  199670. png_set_compression_method(png_structp png_ptr, int method)
  199671. {
  199672. png_debug(1, "in png_set_compression_method\n");
  199673. if (png_ptr == NULL)
  199674. return;
  199675. if (method != 8)
  199676. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  199677. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  199678. png_ptr->zlib_method = method;
  199679. }
  199680. void PNGAPI
  199681. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  199682. {
  199683. if (png_ptr == NULL)
  199684. return;
  199685. png_ptr->write_row_fn = write_row_fn;
  199686. }
  199687. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199688. void PNGAPI
  199689. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  199690. write_user_transform_fn)
  199691. {
  199692. png_debug(1, "in png_set_write_user_transform_fn\n");
  199693. if (png_ptr == NULL)
  199694. return;
  199695. png_ptr->transformations |= PNG_USER_TRANSFORM;
  199696. png_ptr->write_user_transform_fn = write_user_transform_fn;
  199697. }
  199698. #endif
  199699. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  199700. void PNGAPI
  199701. png_write_png(png_structp png_ptr, png_infop info_ptr,
  199702. int transforms, voidp params)
  199703. {
  199704. if (png_ptr == NULL || info_ptr == NULL)
  199705. return;
  199706. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199707. /* invert the alpha channel from opacity to transparency */
  199708. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  199709. png_set_invert_alpha(png_ptr);
  199710. #endif
  199711. /* Write the file header information. */
  199712. png_write_info(png_ptr, info_ptr);
  199713. /* ------ these transformations don't touch the info structure ------- */
  199714. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199715. /* invert monochrome pixels */
  199716. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  199717. png_set_invert_mono(png_ptr);
  199718. #endif
  199719. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199720. /* Shift the pixels up to a legal bit depth and fill in
  199721. * as appropriate to correctly scale the image.
  199722. */
  199723. if ((transforms & PNG_TRANSFORM_SHIFT)
  199724. && (info_ptr->valid & PNG_INFO_sBIT))
  199725. png_set_shift(png_ptr, &info_ptr->sig_bit);
  199726. #endif
  199727. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199728. /* pack pixels into bytes */
  199729. if (transforms & PNG_TRANSFORM_PACKING)
  199730. png_set_packing(png_ptr);
  199731. #endif
  199732. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199733. /* swap location of alpha bytes from ARGB to RGBA */
  199734. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  199735. png_set_swap_alpha(png_ptr);
  199736. #endif
  199737. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199738. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  199739. * RGB (4 channels -> 3 channels). The second parameter is not used.
  199740. */
  199741. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  199742. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  199743. #endif
  199744. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199745. /* flip BGR pixels to RGB */
  199746. if (transforms & PNG_TRANSFORM_BGR)
  199747. png_set_bgr(png_ptr);
  199748. #endif
  199749. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199750. /* swap bytes of 16-bit files to most significant byte first */
  199751. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  199752. png_set_swap(png_ptr);
  199753. #endif
  199754. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199755. /* swap bits of 1, 2, 4 bit packed pixel formats */
  199756. if (transforms & PNG_TRANSFORM_PACKSWAP)
  199757. png_set_packswap(png_ptr);
  199758. #endif
  199759. /* ----------------------- end of transformations ------------------- */
  199760. /* write the bits */
  199761. if (info_ptr->valid & PNG_INFO_IDAT)
  199762. png_write_image(png_ptr, info_ptr->row_pointers);
  199763. /* It is REQUIRED to call this to finish writing the rest of the file */
  199764. png_write_end(png_ptr, info_ptr);
  199765. transforms = transforms; /* quiet compiler warnings */
  199766. params = params;
  199767. }
  199768. #endif
  199769. #endif /* PNG_WRITE_SUPPORTED */
  199770. /*** End of inlined file: pngwrite.c ***/
  199771. /*** Start of inlined file: pngwtran.c ***/
  199772. /* pngwtran.c - transforms the data in a row for PNG writers
  199773. *
  199774. * Last changed in libpng 1.2.9 April 14, 2006
  199775. * For conditions of distribution and use, see copyright notice in png.h
  199776. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199777. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199778. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199779. */
  199780. #define PNG_INTERNAL
  199781. #ifdef PNG_WRITE_SUPPORTED
  199782. /* Transform the data according to the user's wishes. The order of
  199783. * transformations is significant.
  199784. */
  199785. void /* PRIVATE */
  199786. png_do_write_transformations(png_structp png_ptr)
  199787. {
  199788. png_debug(1, "in png_do_write_transformations\n");
  199789. if (png_ptr == NULL)
  199790. return;
  199791. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  199792. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  199793. if(png_ptr->write_user_transform_fn != NULL)
  199794. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  199795. (png_ptr, /* png_ptr */
  199796. &(png_ptr->row_info), /* row_info: */
  199797. /* png_uint_32 width; width of row */
  199798. /* png_uint_32 rowbytes; number of bytes in row */
  199799. /* png_byte color_type; color type of pixels */
  199800. /* png_byte bit_depth; bit depth of samples */
  199801. /* png_byte channels; number of channels (1-4) */
  199802. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  199803. png_ptr->row_buf + 1); /* start of pixel data for row */
  199804. #endif
  199805. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  199806. if (png_ptr->transformations & PNG_FILLER)
  199807. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199808. png_ptr->flags);
  199809. #endif
  199810. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199811. if (png_ptr->transformations & PNG_PACKSWAP)
  199812. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199813. #endif
  199814. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199815. if (png_ptr->transformations & PNG_PACK)
  199816. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199817. (png_uint_32)png_ptr->bit_depth);
  199818. #endif
  199819. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  199820. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199821. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199822. #endif
  199823. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199824. if (png_ptr->transformations & PNG_SHIFT)
  199825. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  199826. &(png_ptr->shift));
  199827. #endif
  199828. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  199829. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  199830. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199831. #endif
  199832. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199833. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  199834. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199835. #endif
  199836. #if defined(PNG_WRITE_BGR_SUPPORTED)
  199837. if (png_ptr->transformations & PNG_BGR)
  199838. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199839. #endif
  199840. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  199841. if (png_ptr->transformations & PNG_INVERT_MONO)
  199842. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199843. #endif
  199844. }
  199845. #if defined(PNG_WRITE_PACK_SUPPORTED)
  199846. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  199847. * row_info bit depth should be 8 (one pixel per byte). The channels
  199848. * should be 1 (this only happens on grayscale and paletted images).
  199849. */
  199850. void /* PRIVATE */
  199851. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  199852. {
  199853. png_debug(1, "in png_do_pack\n");
  199854. if (row_info->bit_depth == 8 &&
  199855. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199856. row != NULL && row_info != NULL &&
  199857. #endif
  199858. row_info->channels == 1)
  199859. {
  199860. switch ((int)bit_depth)
  199861. {
  199862. case 1:
  199863. {
  199864. png_bytep sp, dp;
  199865. int mask, v;
  199866. png_uint_32 i;
  199867. png_uint_32 row_width = row_info->width;
  199868. sp = row;
  199869. dp = row;
  199870. mask = 0x80;
  199871. v = 0;
  199872. for (i = 0; i < row_width; i++)
  199873. {
  199874. if (*sp != 0)
  199875. v |= mask;
  199876. sp++;
  199877. if (mask > 1)
  199878. mask >>= 1;
  199879. else
  199880. {
  199881. mask = 0x80;
  199882. *dp = (png_byte)v;
  199883. dp++;
  199884. v = 0;
  199885. }
  199886. }
  199887. if (mask != 0x80)
  199888. *dp = (png_byte)v;
  199889. break;
  199890. }
  199891. case 2:
  199892. {
  199893. png_bytep sp, dp;
  199894. int shift, v;
  199895. png_uint_32 i;
  199896. png_uint_32 row_width = row_info->width;
  199897. sp = row;
  199898. dp = row;
  199899. shift = 6;
  199900. v = 0;
  199901. for (i = 0; i < row_width; i++)
  199902. {
  199903. png_byte value;
  199904. value = (png_byte)(*sp & 0x03);
  199905. v |= (value << shift);
  199906. if (shift == 0)
  199907. {
  199908. shift = 6;
  199909. *dp = (png_byte)v;
  199910. dp++;
  199911. v = 0;
  199912. }
  199913. else
  199914. shift -= 2;
  199915. sp++;
  199916. }
  199917. if (shift != 6)
  199918. *dp = (png_byte)v;
  199919. break;
  199920. }
  199921. case 4:
  199922. {
  199923. png_bytep sp, dp;
  199924. int shift, v;
  199925. png_uint_32 i;
  199926. png_uint_32 row_width = row_info->width;
  199927. sp = row;
  199928. dp = row;
  199929. shift = 4;
  199930. v = 0;
  199931. for (i = 0; i < row_width; i++)
  199932. {
  199933. png_byte value;
  199934. value = (png_byte)(*sp & 0x0f);
  199935. v |= (value << shift);
  199936. if (shift == 0)
  199937. {
  199938. shift = 4;
  199939. *dp = (png_byte)v;
  199940. dp++;
  199941. v = 0;
  199942. }
  199943. else
  199944. shift -= 4;
  199945. sp++;
  199946. }
  199947. if (shift != 4)
  199948. *dp = (png_byte)v;
  199949. break;
  199950. }
  199951. }
  199952. row_info->bit_depth = (png_byte)bit_depth;
  199953. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  199954. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  199955. row_info->width);
  199956. }
  199957. }
  199958. #endif
  199959. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  199960. /* Shift pixel values to take advantage of whole range. Pass the
  199961. * true number of bits in bit_depth. The row should be packed
  199962. * according to row_info->bit_depth. Thus, if you had a row of
  199963. * bit depth 4, but the pixels only had values from 0 to 7, you
  199964. * would pass 3 as bit_depth, and this routine would translate the
  199965. * data to 0 to 15.
  199966. */
  199967. void /* PRIVATE */
  199968. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  199969. {
  199970. png_debug(1, "in png_do_shift\n");
  199971. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199972. if (row != NULL && row_info != NULL &&
  199973. #else
  199974. if (
  199975. #endif
  199976. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  199977. {
  199978. int shift_start[4], shift_dec[4];
  199979. int channels = 0;
  199980. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  199981. {
  199982. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  199983. shift_dec[channels] = bit_depth->red;
  199984. channels++;
  199985. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  199986. shift_dec[channels] = bit_depth->green;
  199987. channels++;
  199988. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  199989. shift_dec[channels] = bit_depth->blue;
  199990. channels++;
  199991. }
  199992. else
  199993. {
  199994. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  199995. shift_dec[channels] = bit_depth->gray;
  199996. channels++;
  199997. }
  199998. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  199999. {
  200000. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200001. shift_dec[channels] = bit_depth->alpha;
  200002. channels++;
  200003. }
  200004. /* with low row depths, could only be grayscale, so one channel */
  200005. if (row_info->bit_depth < 8)
  200006. {
  200007. png_bytep bp = row;
  200008. png_uint_32 i;
  200009. png_byte mask;
  200010. png_uint_32 row_bytes = row_info->rowbytes;
  200011. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200012. mask = 0x55;
  200013. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200014. mask = 0x11;
  200015. else
  200016. mask = 0xff;
  200017. for (i = 0; i < row_bytes; i++, bp++)
  200018. {
  200019. png_uint_16 v;
  200020. int j;
  200021. v = *bp;
  200022. *bp = 0;
  200023. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200024. {
  200025. if (j > 0)
  200026. *bp |= (png_byte)((v << j) & 0xff);
  200027. else
  200028. *bp |= (png_byte)((v >> (-j)) & mask);
  200029. }
  200030. }
  200031. }
  200032. else if (row_info->bit_depth == 8)
  200033. {
  200034. png_bytep bp = row;
  200035. png_uint_32 i;
  200036. png_uint_32 istop = channels * row_info->width;
  200037. for (i = 0; i < istop; i++, bp++)
  200038. {
  200039. png_uint_16 v;
  200040. int j;
  200041. int c = (int)(i%channels);
  200042. v = *bp;
  200043. *bp = 0;
  200044. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200045. {
  200046. if (j > 0)
  200047. *bp |= (png_byte)((v << j) & 0xff);
  200048. else
  200049. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200050. }
  200051. }
  200052. }
  200053. else
  200054. {
  200055. png_bytep bp;
  200056. png_uint_32 i;
  200057. png_uint_32 istop = channels * row_info->width;
  200058. for (bp = row, i = 0; i < istop; i++)
  200059. {
  200060. int c = (int)(i%channels);
  200061. png_uint_16 value, v;
  200062. int j;
  200063. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200064. value = 0;
  200065. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200066. {
  200067. if (j > 0)
  200068. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200069. else
  200070. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200071. }
  200072. *bp++ = (png_byte)(value >> 8);
  200073. *bp++ = (png_byte)(value & 0xff);
  200074. }
  200075. }
  200076. }
  200077. }
  200078. #endif
  200079. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200080. void /* PRIVATE */
  200081. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200082. {
  200083. png_debug(1, "in png_do_write_swap_alpha\n");
  200084. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200085. if (row != NULL && row_info != NULL)
  200086. #endif
  200087. {
  200088. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200089. {
  200090. /* This converts from ARGB to RGBA */
  200091. if (row_info->bit_depth == 8)
  200092. {
  200093. png_bytep sp, dp;
  200094. png_uint_32 i;
  200095. png_uint_32 row_width = row_info->width;
  200096. for (i = 0, sp = dp = row; i < row_width; i++)
  200097. {
  200098. png_byte save = *(sp++);
  200099. *(dp++) = *(sp++);
  200100. *(dp++) = *(sp++);
  200101. *(dp++) = *(sp++);
  200102. *(dp++) = save;
  200103. }
  200104. }
  200105. /* This converts from AARRGGBB to RRGGBBAA */
  200106. else
  200107. {
  200108. png_bytep sp, dp;
  200109. png_uint_32 i;
  200110. png_uint_32 row_width = row_info->width;
  200111. for (i = 0, sp = dp = row; i < row_width; i++)
  200112. {
  200113. png_byte save[2];
  200114. save[0] = *(sp++);
  200115. save[1] = *(sp++);
  200116. *(dp++) = *(sp++);
  200117. *(dp++) = *(sp++);
  200118. *(dp++) = *(sp++);
  200119. *(dp++) = *(sp++);
  200120. *(dp++) = *(sp++);
  200121. *(dp++) = *(sp++);
  200122. *(dp++) = save[0];
  200123. *(dp++) = save[1];
  200124. }
  200125. }
  200126. }
  200127. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200128. {
  200129. /* This converts from AG to GA */
  200130. if (row_info->bit_depth == 8)
  200131. {
  200132. png_bytep sp, dp;
  200133. png_uint_32 i;
  200134. png_uint_32 row_width = row_info->width;
  200135. for (i = 0, sp = dp = row; i < row_width; i++)
  200136. {
  200137. png_byte save = *(sp++);
  200138. *(dp++) = *(sp++);
  200139. *(dp++) = save;
  200140. }
  200141. }
  200142. /* This converts from AAGG to GGAA */
  200143. else
  200144. {
  200145. png_bytep sp, dp;
  200146. png_uint_32 i;
  200147. png_uint_32 row_width = row_info->width;
  200148. for (i = 0, sp = dp = row; i < row_width; i++)
  200149. {
  200150. png_byte save[2];
  200151. save[0] = *(sp++);
  200152. save[1] = *(sp++);
  200153. *(dp++) = *(sp++);
  200154. *(dp++) = *(sp++);
  200155. *(dp++) = save[0];
  200156. *(dp++) = save[1];
  200157. }
  200158. }
  200159. }
  200160. }
  200161. }
  200162. #endif
  200163. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200164. void /* PRIVATE */
  200165. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200166. {
  200167. png_debug(1, "in png_do_write_invert_alpha\n");
  200168. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200169. if (row != NULL && row_info != NULL)
  200170. #endif
  200171. {
  200172. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200173. {
  200174. /* This inverts the alpha channel in RGBA */
  200175. if (row_info->bit_depth == 8)
  200176. {
  200177. png_bytep sp, dp;
  200178. png_uint_32 i;
  200179. png_uint_32 row_width = row_info->width;
  200180. for (i = 0, sp = dp = row; i < row_width; i++)
  200181. {
  200182. /* does nothing
  200183. *(dp++) = *(sp++);
  200184. *(dp++) = *(sp++);
  200185. *(dp++) = *(sp++);
  200186. */
  200187. sp+=3; dp = sp;
  200188. *(dp++) = (png_byte)(255 - *(sp++));
  200189. }
  200190. }
  200191. /* This inverts the alpha channel in RRGGBBAA */
  200192. else
  200193. {
  200194. png_bytep sp, dp;
  200195. png_uint_32 i;
  200196. png_uint_32 row_width = row_info->width;
  200197. for (i = 0, sp = dp = row; i < row_width; i++)
  200198. {
  200199. /* does nothing
  200200. *(dp++) = *(sp++);
  200201. *(dp++) = *(sp++);
  200202. *(dp++) = *(sp++);
  200203. *(dp++) = *(sp++);
  200204. *(dp++) = *(sp++);
  200205. *(dp++) = *(sp++);
  200206. */
  200207. sp+=6; dp = sp;
  200208. *(dp++) = (png_byte)(255 - *(sp++));
  200209. *(dp++) = (png_byte)(255 - *(sp++));
  200210. }
  200211. }
  200212. }
  200213. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200214. {
  200215. /* This inverts the alpha channel in GA */
  200216. if (row_info->bit_depth == 8)
  200217. {
  200218. png_bytep sp, dp;
  200219. png_uint_32 i;
  200220. png_uint_32 row_width = row_info->width;
  200221. for (i = 0, sp = dp = row; i < row_width; i++)
  200222. {
  200223. *(dp++) = *(sp++);
  200224. *(dp++) = (png_byte)(255 - *(sp++));
  200225. }
  200226. }
  200227. /* This inverts the alpha channel in GGAA */
  200228. else
  200229. {
  200230. png_bytep sp, dp;
  200231. png_uint_32 i;
  200232. png_uint_32 row_width = row_info->width;
  200233. for (i = 0, sp = dp = row; i < row_width; i++)
  200234. {
  200235. /* does nothing
  200236. *(dp++) = *(sp++);
  200237. *(dp++) = *(sp++);
  200238. */
  200239. sp+=2; dp = sp;
  200240. *(dp++) = (png_byte)(255 - *(sp++));
  200241. *(dp++) = (png_byte)(255 - *(sp++));
  200242. }
  200243. }
  200244. }
  200245. }
  200246. }
  200247. #endif
  200248. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200249. /* undoes intrapixel differencing */
  200250. void /* PRIVATE */
  200251. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200252. {
  200253. png_debug(1, "in png_do_write_intrapixel\n");
  200254. if (
  200255. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200256. row != NULL && row_info != NULL &&
  200257. #endif
  200258. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200259. {
  200260. int bytes_per_pixel;
  200261. png_uint_32 row_width = row_info->width;
  200262. if (row_info->bit_depth == 8)
  200263. {
  200264. png_bytep rp;
  200265. png_uint_32 i;
  200266. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200267. bytes_per_pixel = 3;
  200268. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200269. bytes_per_pixel = 4;
  200270. else
  200271. return;
  200272. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200273. {
  200274. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200275. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200276. }
  200277. }
  200278. else if (row_info->bit_depth == 16)
  200279. {
  200280. png_bytep rp;
  200281. png_uint_32 i;
  200282. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200283. bytes_per_pixel = 6;
  200284. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200285. bytes_per_pixel = 8;
  200286. else
  200287. return;
  200288. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200289. {
  200290. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200291. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200292. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200293. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200294. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200295. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200296. *(rp+1) = (png_byte)(red & 0xff);
  200297. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200298. *(rp+5) = (png_byte)(blue & 0xff);
  200299. }
  200300. }
  200301. }
  200302. }
  200303. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200304. #endif /* PNG_WRITE_SUPPORTED */
  200305. /*** End of inlined file: pngwtran.c ***/
  200306. /*** Start of inlined file: pngwutil.c ***/
  200307. /* pngwutil.c - utilities to write a PNG file
  200308. *
  200309. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200310. * For conditions of distribution and use, see copyright notice in png.h
  200311. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200312. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200313. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200314. */
  200315. #define PNG_INTERNAL
  200316. #ifdef PNG_WRITE_SUPPORTED
  200317. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200318. * with unsigned numbers for convenience, although one supported
  200319. * ancillary chunk uses signed (two's complement) numbers.
  200320. */
  200321. void PNGAPI
  200322. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200323. {
  200324. buf[0] = (png_byte)((i >> 24) & 0xff);
  200325. buf[1] = (png_byte)((i >> 16) & 0xff);
  200326. buf[2] = (png_byte)((i >> 8) & 0xff);
  200327. buf[3] = (png_byte)(i & 0xff);
  200328. }
  200329. /* The png_save_int_32 function assumes integers are stored in two's
  200330. * complement format. If this isn't the case, then this routine needs to
  200331. * be modified to write data in two's complement format.
  200332. */
  200333. void PNGAPI
  200334. png_save_int_32(png_bytep buf, png_int_32 i)
  200335. {
  200336. buf[0] = (png_byte)((i >> 24) & 0xff);
  200337. buf[1] = (png_byte)((i >> 16) & 0xff);
  200338. buf[2] = (png_byte)((i >> 8) & 0xff);
  200339. buf[3] = (png_byte)(i & 0xff);
  200340. }
  200341. /* Place a 16-bit number into a buffer in PNG byte order.
  200342. * The parameter is declared unsigned int, not png_uint_16,
  200343. * just to avoid potential problems on pre-ANSI C compilers.
  200344. */
  200345. void PNGAPI
  200346. png_save_uint_16(png_bytep buf, unsigned int i)
  200347. {
  200348. buf[0] = (png_byte)((i >> 8) & 0xff);
  200349. buf[1] = (png_byte)(i & 0xff);
  200350. }
  200351. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200352. * representing the chunk name. The array must be at least 4 bytes in
  200353. * length, and does not need to be null terminated. To be safe, pass the
  200354. * pre-defined chunk names here, and if you need a new one, define it
  200355. * where the others are defined. The length is the length of the data.
  200356. * All the data must be present. If that is not possible, use the
  200357. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200358. * functions instead.
  200359. */
  200360. void PNGAPI
  200361. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200362. png_bytep data, png_size_t length)
  200363. {
  200364. if(png_ptr == NULL) return;
  200365. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200366. png_write_chunk_data(png_ptr, data, length);
  200367. png_write_chunk_end(png_ptr);
  200368. }
  200369. /* Write the start of a PNG chunk. The type is the chunk type.
  200370. * The total_length is the sum of the lengths of all the data you will be
  200371. * passing in png_write_chunk_data().
  200372. */
  200373. void PNGAPI
  200374. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200375. png_uint_32 length)
  200376. {
  200377. png_byte buf[4];
  200378. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200379. if(png_ptr == NULL) return;
  200380. /* write the length */
  200381. png_save_uint_32(buf, length);
  200382. png_write_data(png_ptr, buf, (png_size_t)4);
  200383. /* write the chunk name */
  200384. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200385. /* reset the crc and run it over the chunk name */
  200386. png_reset_crc(png_ptr);
  200387. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200388. }
  200389. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200390. * Note that multiple calls to this function are allowed, and that the
  200391. * sum of the lengths from these calls *must* add up to the total_length
  200392. * given to png_write_chunk_start().
  200393. */
  200394. void PNGAPI
  200395. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200396. {
  200397. /* write the data, and run the CRC over it */
  200398. if(png_ptr == NULL) return;
  200399. if (data != NULL && length > 0)
  200400. {
  200401. png_calculate_crc(png_ptr, data, length);
  200402. png_write_data(png_ptr, data, length);
  200403. }
  200404. }
  200405. /* Finish a chunk started with png_write_chunk_start(). */
  200406. void PNGAPI
  200407. png_write_chunk_end(png_structp png_ptr)
  200408. {
  200409. png_byte buf[4];
  200410. if(png_ptr == NULL) return;
  200411. /* write the crc */
  200412. png_save_uint_32(buf, png_ptr->crc);
  200413. png_write_data(png_ptr, buf, (png_size_t)4);
  200414. }
  200415. /* Simple function to write the signature. If we have already written
  200416. * the magic bytes of the signature, or more likely, the PNG stream is
  200417. * being embedded into another stream and doesn't need its own signature,
  200418. * we should call png_set_sig_bytes() to tell libpng how many of the
  200419. * bytes have already been written.
  200420. */
  200421. void /* PRIVATE */
  200422. png_write_sig(png_structp png_ptr)
  200423. {
  200424. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200425. /* write the rest of the 8 byte signature */
  200426. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200427. (png_size_t)8 - png_ptr->sig_bytes);
  200428. if(png_ptr->sig_bytes < 3)
  200429. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200430. }
  200431. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200432. /*
  200433. * This pair of functions encapsulates the operation of (a) compressing a
  200434. * text string, and (b) issuing it later as a series of chunk data writes.
  200435. * The compression_state structure is shared context for these functions
  200436. * set up by the caller in order to make the whole mess thread-safe.
  200437. */
  200438. typedef struct
  200439. {
  200440. char *input; /* the uncompressed input data */
  200441. int input_len; /* its length */
  200442. int num_output_ptr; /* number of output pointers used */
  200443. int max_output_ptr; /* size of output_ptr */
  200444. png_charpp output_ptr; /* array of pointers to output */
  200445. } compression_state;
  200446. /* compress given text into storage in the png_ptr structure */
  200447. static int /* PRIVATE */
  200448. png_text_compress(png_structp png_ptr,
  200449. png_charp text, png_size_t text_len, int compression,
  200450. compression_state *comp)
  200451. {
  200452. int ret;
  200453. comp->num_output_ptr = 0;
  200454. comp->max_output_ptr = 0;
  200455. comp->output_ptr = NULL;
  200456. comp->input = NULL;
  200457. comp->input_len = 0;
  200458. /* we may just want to pass the text right through */
  200459. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200460. {
  200461. comp->input = text;
  200462. comp->input_len = text_len;
  200463. return((int)text_len);
  200464. }
  200465. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200466. {
  200467. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200468. char msg[50];
  200469. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200470. png_warning(png_ptr, msg);
  200471. #else
  200472. png_warning(png_ptr, "Unknown compression type");
  200473. #endif
  200474. }
  200475. /* We can't write the chunk until we find out how much data we have,
  200476. * which means we need to run the compressor first and save the
  200477. * output. This shouldn't be a problem, as the vast majority of
  200478. * comments should be reasonable, but we will set up an array of
  200479. * malloc'd pointers to be sure.
  200480. *
  200481. * If we knew the application was well behaved, we could simplify this
  200482. * greatly by assuming we can always malloc an output buffer large
  200483. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200484. * and malloc this directly. The only time this would be a bad idea is
  200485. * if we can't malloc more than 64K and we have 64K of random input
  200486. * data, or if the input string is incredibly large (although this
  200487. * wouldn't cause a failure, just a slowdown due to swapping).
  200488. */
  200489. /* set up the compression buffers */
  200490. png_ptr->zstream.avail_in = (uInt)text_len;
  200491. png_ptr->zstream.next_in = (Bytef *)text;
  200492. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200493. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200494. /* this is the same compression loop as in png_write_row() */
  200495. do
  200496. {
  200497. /* compress the data */
  200498. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200499. if (ret != Z_OK)
  200500. {
  200501. /* error */
  200502. if (png_ptr->zstream.msg != NULL)
  200503. png_error(png_ptr, png_ptr->zstream.msg);
  200504. else
  200505. png_error(png_ptr, "zlib error");
  200506. }
  200507. /* check to see if we need more room */
  200508. if (!(png_ptr->zstream.avail_out))
  200509. {
  200510. /* make sure the output array has room */
  200511. if (comp->num_output_ptr >= comp->max_output_ptr)
  200512. {
  200513. int old_max;
  200514. old_max = comp->max_output_ptr;
  200515. comp->max_output_ptr = comp->num_output_ptr + 4;
  200516. if (comp->output_ptr != NULL)
  200517. {
  200518. png_charpp old_ptr;
  200519. old_ptr = comp->output_ptr;
  200520. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200521. (png_uint_32)(comp->max_output_ptr *
  200522. png_sizeof (png_charpp)));
  200523. png_memcpy(comp->output_ptr, old_ptr, old_max
  200524. * png_sizeof (png_charp));
  200525. png_free(png_ptr, old_ptr);
  200526. }
  200527. else
  200528. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200529. (png_uint_32)(comp->max_output_ptr *
  200530. png_sizeof (png_charp)));
  200531. }
  200532. /* save the data */
  200533. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200534. (png_uint_32)png_ptr->zbuf_size);
  200535. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200536. png_ptr->zbuf_size);
  200537. comp->num_output_ptr++;
  200538. /* and reset the buffer */
  200539. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200540. png_ptr->zstream.next_out = png_ptr->zbuf;
  200541. }
  200542. /* continue until we don't have any more to compress */
  200543. } while (png_ptr->zstream.avail_in);
  200544. /* finish the compression */
  200545. do
  200546. {
  200547. /* tell zlib we are finished */
  200548. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200549. if (ret == Z_OK)
  200550. {
  200551. /* check to see if we need more room */
  200552. if (!(png_ptr->zstream.avail_out))
  200553. {
  200554. /* check to make sure our output array has room */
  200555. if (comp->num_output_ptr >= comp->max_output_ptr)
  200556. {
  200557. int old_max;
  200558. old_max = comp->max_output_ptr;
  200559. comp->max_output_ptr = comp->num_output_ptr + 4;
  200560. if (comp->output_ptr != NULL)
  200561. {
  200562. png_charpp old_ptr;
  200563. old_ptr = comp->output_ptr;
  200564. /* This could be optimized to realloc() */
  200565. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200566. (png_uint_32)(comp->max_output_ptr *
  200567. png_sizeof (png_charpp)));
  200568. png_memcpy(comp->output_ptr, old_ptr,
  200569. old_max * png_sizeof (png_charp));
  200570. png_free(png_ptr, old_ptr);
  200571. }
  200572. else
  200573. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200574. (png_uint_32)(comp->max_output_ptr *
  200575. png_sizeof (png_charp)));
  200576. }
  200577. /* save off the data */
  200578. comp->output_ptr[comp->num_output_ptr] =
  200579. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200580. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200581. png_ptr->zbuf_size);
  200582. comp->num_output_ptr++;
  200583. /* and reset the buffer pointers */
  200584. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200585. png_ptr->zstream.next_out = png_ptr->zbuf;
  200586. }
  200587. }
  200588. else if (ret != Z_STREAM_END)
  200589. {
  200590. /* we got an error */
  200591. if (png_ptr->zstream.msg != NULL)
  200592. png_error(png_ptr, png_ptr->zstream.msg);
  200593. else
  200594. png_error(png_ptr, "zlib error");
  200595. }
  200596. } while (ret != Z_STREAM_END);
  200597. /* text length is number of buffers plus last buffer */
  200598. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200599. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200600. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200601. return((int)text_len);
  200602. }
  200603. /* ship the compressed text out via chunk writes */
  200604. static void /* PRIVATE */
  200605. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200606. {
  200607. int i;
  200608. /* handle the no-compression case */
  200609. if (comp->input)
  200610. {
  200611. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200612. (png_size_t)comp->input_len);
  200613. return;
  200614. }
  200615. /* write saved output buffers, if any */
  200616. for (i = 0; i < comp->num_output_ptr; i++)
  200617. {
  200618. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200619. png_ptr->zbuf_size);
  200620. png_free(png_ptr, comp->output_ptr[i]);
  200621. comp->output_ptr[i]=NULL;
  200622. }
  200623. if (comp->max_output_ptr != 0)
  200624. png_free(png_ptr, comp->output_ptr);
  200625. comp->output_ptr=NULL;
  200626. /* write anything left in zbuf */
  200627. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200628. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200629. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200630. /* reset zlib for another zTXt/iTXt or image data */
  200631. deflateReset(&png_ptr->zstream);
  200632. png_ptr->zstream.data_type = Z_BINARY;
  200633. }
  200634. #endif
  200635. /* Write the IHDR chunk, and update the png_struct with the necessary
  200636. * information. Note that the rest of this code depends upon this
  200637. * information being correct.
  200638. */
  200639. void /* PRIVATE */
  200640. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200641. int bit_depth, int color_type, int compression_type, int filter_type,
  200642. int interlace_type)
  200643. {
  200644. #ifdef PNG_USE_LOCAL_ARRAYS
  200645. PNG_IHDR;
  200646. #endif
  200647. png_byte buf[13]; /* buffer to store the IHDR info */
  200648. png_debug(1, "in png_write_IHDR\n");
  200649. /* Check that we have valid input data from the application info */
  200650. switch (color_type)
  200651. {
  200652. case PNG_COLOR_TYPE_GRAY:
  200653. switch (bit_depth)
  200654. {
  200655. case 1:
  200656. case 2:
  200657. case 4:
  200658. case 8:
  200659. case 16: png_ptr->channels = 1; break;
  200660. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200661. }
  200662. break;
  200663. case PNG_COLOR_TYPE_RGB:
  200664. if (bit_depth != 8 && bit_depth != 16)
  200665. png_error(png_ptr, "Invalid bit depth for RGB image");
  200666. png_ptr->channels = 3;
  200667. break;
  200668. case PNG_COLOR_TYPE_PALETTE:
  200669. switch (bit_depth)
  200670. {
  200671. case 1:
  200672. case 2:
  200673. case 4:
  200674. case 8: png_ptr->channels = 1; break;
  200675. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  200676. }
  200677. break;
  200678. case PNG_COLOR_TYPE_GRAY_ALPHA:
  200679. if (bit_depth != 8 && bit_depth != 16)
  200680. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  200681. png_ptr->channels = 2;
  200682. break;
  200683. case PNG_COLOR_TYPE_RGB_ALPHA:
  200684. if (bit_depth != 8 && bit_depth != 16)
  200685. png_error(png_ptr, "Invalid bit depth for RGBA image");
  200686. png_ptr->channels = 4;
  200687. break;
  200688. default:
  200689. png_error(png_ptr, "Invalid image color type specified");
  200690. }
  200691. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200692. {
  200693. png_warning(png_ptr, "Invalid compression type specified");
  200694. compression_type = PNG_COMPRESSION_TYPE_BASE;
  200695. }
  200696. /* Write filter_method 64 (intrapixel differencing) only if
  200697. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200698. * 2. Libpng did not write a PNG signature (this filter_method is only
  200699. * used in PNG datastreams that are embedded in MNG datastreams) and
  200700. * 3. The application called png_permit_mng_features with a mask that
  200701. * included PNG_FLAG_MNG_FILTER_64 and
  200702. * 4. The filter_method is 64 and
  200703. * 5. The color_type is RGB or RGBA
  200704. */
  200705. if (
  200706. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200707. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200708. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  200709. (color_type == PNG_COLOR_TYPE_RGB ||
  200710. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  200711. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  200712. #endif
  200713. filter_type != PNG_FILTER_TYPE_BASE)
  200714. {
  200715. png_warning(png_ptr, "Invalid filter type specified");
  200716. filter_type = PNG_FILTER_TYPE_BASE;
  200717. }
  200718. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  200719. if (interlace_type != PNG_INTERLACE_NONE &&
  200720. interlace_type != PNG_INTERLACE_ADAM7)
  200721. {
  200722. png_warning(png_ptr, "Invalid interlace type specified");
  200723. interlace_type = PNG_INTERLACE_ADAM7;
  200724. }
  200725. #else
  200726. interlace_type=PNG_INTERLACE_NONE;
  200727. #endif
  200728. /* save off the relevent information */
  200729. png_ptr->bit_depth = (png_byte)bit_depth;
  200730. png_ptr->color_type = (png_byte)color_type;
  200731. png_ptr->interlaced = (png_byte)interlace_type;
  200732. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200733. png_ptr->filter_type = (png_byte)filter_type;
  200734. #endif
  200735. png_ptr->compression_type = (png_byte)compression_type;
  200736. png_ptr->width = width;
  200737. png_ptr->height = height;
  200738. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  200739. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  200740. /* set the usr info, so any transformations can modify it */
  200741. png_ptr->usr_width = png_ptr->width;
  200742. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  200743. png_ptr->usr_channels = png_ptr->channels;
  200744. /* pack the header information into the buffer */
  200745. png_save_uint_32(buf, width);
  200746. png_save_uint_32(buf + 4, height);
  200747. buf[8] = (png_byte)bit_depth;
  200748. buf[9] = (png_byte)color_type;
  200749. buf[10] = (png_byte)compression_type;
  200750. buf[11] = (png_byte)filter_type;
  200751. buf[12] = (png_byte)interlace_type;
  200752. /* write the chunk */
  200753. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  200754. /* initialize zlib with PNG info */
  200755. png_ptr->zstream.zalloc = png_zalloc;
  200756. png_ptr->zstream.zfree = png_zfree;
  200757. png_ptr->zstream.opaque = (voidpf)png_ptr;
  200758. if (!(png_ptr->do_filter))
  200759. {
  200760. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  200761. png_ptr->bit_depth < 8)
  200762. png_ptr->do_filter = PNG_FILTER_NONE;
  200763. else
  200764. png_ptr->do_filter = PNG_ALL_FILTERS;
  200765. }
  200766. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  200767. {
  200768. if (png_ptr->do_filter != PNG_FILTER_NONE)
  200769. png_ptr->zlib_strategy = Z_FILTERED;
  200770. else
  200771. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  200772. }
  200773. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  200774. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  200775. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  200776. png_ptr->zlib_mem_level = 8;
  200777. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  200778. png_ptr->zlib_window_bits = 15;
  200779. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  200780. png_ptr->zlib_method = 8;
  200781. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  200782. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  200783. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  200784. png_error(png_ptr, "zlib failed to initialize compressor");
  200785. png_ptr->zstream.next_out = png_ptr->zbuf;
  200786. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200787. /* libpng is not interested in zstream.data_type */
  200788. /* set it to a predefined value, to avoid its evaluation inside zlib */
  200789. png_ptr->zstream.data_type = Z_BINARY;
  200790. png_ptr->mode = PNG_HAVE_IHDR;
  200791. }
  200792. /* write the palette. We are careful not to trust png_color to be in the
  200793. * correct order for PNG, so people can redefine it to any convenient
  200794. * structure.
  200795. */
  200796. void /* PRIVATE */
  200797. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  200798. {
  200799. #ifdef PNG_USE_LOCAL_ARRAYS
  200800. PNG_PLTE;
  200801. #endif
  200802. png_uint_32 i;
  200803. png_colorp pal_ptr;
  200804. png_byte buf[3];
  200805. png_debug(1, "in png_write_PLTE\n");
  200806. if ((
  200807. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200808. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  200809. #endif
  200810. num_pal == 0) || num_pal > 256)
  200811. {
  200812. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  200813. {
  200814. png_error(png_ptr, "Invalid number of colors in palette");
  200815. }
  200816. else
  200817. {
  200818. png_warning(png_ptr, "Invalid number of colors in palette");
  200819. return;
  200820. }
  200821. }
  200822. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  200823. {
  200824. png_warning(png_ptr,
  200825. "Ignoring request to write a PLTE chunk in grayscale PNG");
  200826. return;
  200827. }
  200828. png_ptr->num_palette = (png_uint_16)num_pal;
  200829. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  200830. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  200831. #ifndef PNG_NO_POINTER_INDEXING
  200832. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  200833. {
  200834. buf[0] = pal_ptr->red;
  200835. buf[1] = pal_ptr->green;
  200836. buf[2] = pal_ptr->blue;
  200837. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200838. }
  200839. #else
  200840. /* This is a little slower but some buggy compilers need to do this instead */
  200841. pal_ptr=palette;
  200842. for (i = 0; i < num_pal; i++)
  200843. {
  200844. buf[0] = pal_ptr[i].red;
  200845. buf[1] = pal_ptr[i].green;
  200846. buf[2] = pal_ptr[i].blue;
  200847. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  200848. }
  200849. #endif
  200850. png_write_chunk_end(png_ptr);
  200851. png_ptr->mode |= PNG_HAVE_PLTE;
  200852. }
  200853. /* write an IDAT chunk */
  200854. void /* PRIVATE */
  200855. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  200856. {
  200857. #ifdef PNG_USE_LOCAL_ARRAYS
  200858. PNG_IDAT;
  200859. #endif
  200860. png_debug(1, "in png_write_IDAT\n");
  200861. /* Optimize the CMF field in the zlib stream. */
  200862. /* This hack of the zlib stream is compliant to the stream specification. */
  200863. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  200864. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  200865. {
  200866. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  200867. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  200868. {
  200869. /* Avoid memory underflows and multiplication overflows. */
  200870. /* The conditions below are practically always satisfied;
  200871. however, they still must be checked. */
  200872. if (length >= 2 &&
  200873. png_ptr->height < 16384 && png_ptr->width < 16384)
  200874. {
  200875. png_uint_32 uncompressed_idat_size = png_ptr->height *
  200876. ((png_ptr->width *
  200877. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  200878. unsigned int z_cinfo = z_cmf >> 4;
  200879. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  200880. while (uncompressed_idat_size <= half_z_window_size &&
  200881. half_z_window_size >= 256)
  200882. {
  200883. z_cinfo--;
  200884. half_z_window_size >>= 1;
  200885. }
  200886. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  200887. if (data[0] != (png_byte)z_cmf)
  200888. {
  200889. data[0] = (png_byte)z_cmf;
  200890. data[1] &= 0xe0;
  200891. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  200892. }
  200893. }
  200894. }
  200895. else
  200896. png_error(png_ptr,
  200897. "Invalid zlib compression method or flags in IDAT");
  200898. }
  200899. png_write_chunk(png_ptr, png_IDAT, data, length);
  200900. png_ptr->mode |= PNG_HAVE_IDAT;
  200901. }
  200902. /* write an IEND chunk */
  200903. void /* PRIVATE */
  200904. png_write_IEND(png_structp png_ptr)
  200905. {
  200906. #ifdef PNG_USE_LOCAL_ARRAYS
  200907. PNG_IEND;
  200908. #endif
  200909. png_debug(1, "in png_write_IEND\n");
  200910. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  200911. (png_size_t)0);
  200912. png_ptr->mode |= PNG_HAVE_IEND;
  200913. }
  200914. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  200915. /* write a gAMA chunk */
  200916. #ifdef PNG_FLOATING_POINT_SUPPORTED
  200917. void /* PRIVATE */
  200918. png_write_gAMA(png_structp png_ptr, double file_gamma)
  200919. {
  200920. #ifdef PNG_USE_LOCAL_ARRAYS
  200921. PNG_gAMA;
  200922. #endif
  200923. png_uint_32 igamma;
  200924. png_byte buf[4];
  200925. png_debug(1, "in png_write_gAMA\n");
  200926. /* file_gamma is saved in 1/100,000ths */
  200927. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  200928. png_save_uint_32(buf, igamma);
  200929. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200930. }
  200931. #endif
  200932. #ifdef PNG_FIXED_POINT_SUPPORTED
  200933. void /* PRIVATE */
  200934. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  200935. {
  200936. #ifdef PNG_USE_LOCAL_ARRAYS
  200937. PNG_gAMA;
  200938. #endif
  200939. png_byte buf[4];
  200940. png_debug(1, "in png_write_gAMA\n");
  200941. /* file_gamma is saved in 1/100,000ths */
  200942. png_save_uint_32(buf, (png_uint_32)file_gamma);
  200943. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  200944. }
  200945. #endif
  200946. #endif
  200947. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  200948. /* write a sRGB chunk */
  200949. void /* PRIVATE */
  200950. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  200951. {
  200952. #ifdef PNG_USE_LOCAL_ARRAYS
  200953. PNG_sRGB;
  200954. #endif
  200955. png_byte buf[1];
  200956. png_debug(1, "in png_write_sRGB\n");
  200957. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  200958. png_warning(png_ptr,
  200959. "Invalid sRGB rendering intent specified");
  200960. buf[0]=(png_byte)srgb_intent;
  200961. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  200962. }
  200963. #endif
  200964. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  200965. /* write an iCCP chunk */
  200966. void /* PRIVATE */
  200967. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  200968. png_charp profile, int profile_len)
  200969. {
  200970. #ifdef PNG_USE_LOCAL_ARRAYS
  200971. PNG_iCCP;
  200972. #endif
  200973. png_size_t name_len;
  200974. png_charp new_name;
  200975. compression_state comp;
  200976. int embedded_profile_len = 0;
  200977. png_debug(1, "in png_write_iCCP\n");
  200978. comp.num_output_ptr = 0;
  200979. comp.max_output_ptr = 0;
  200980. comp.output_ptr = NULL;
  200981. comp.input = NULL;
  200982. comp.input_len = 0;
  200983. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  200984. &new_name)) == 0)
  200985. {
  200986. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  200987. return;
  200988. }
  200989. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  200990. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  200991. if (profile == NULL)
  200992. profile_len = 0;
  200993. if (profile_len > 3)
  200994. embedded_profile_len =
  200995. ((*( (png_bytep)profile ))<<24) |
  200996. ((*( (png_bytep)profile+1))<<16) |
  200997. ((*( (png_bytep)profile+2))<< 8) |
  200998. ((*( (png_bytep)profile+3)) );
  200999. if (profile_len < embedded_profile_len)
  201000. {
  201001. png_warning(png_ptr,
  201002. "Embedded profile length too large in iCCP chunk");
  201003. return;
  201004. }
  201005. if (profile_len > embedded_profile_len)
  201006. {
  201007. png_warning(png_ptr,
  201008. "Truncating profile to actual length in iCCP chunk");
  201009. profile_len = embedded_profile_len;
  201010. }
  201011. if (profile_len)
  201012. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201013. PNG_COMPRESSION_TYPE_BASE, &comp);
  201014. /* make sure we include the NULL after the name and the compression type */
  201015. png_write_chunk_start(png_ptr, png_iCCP,
  201016. (png_uint_32)name_len+profile_len+2);
  201017. new_name[name_len+1]=0x00;
  201018. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201019. if (profile_len)
  201020. png_write_compressed_data_out(png_ptr, &comp);
  201021. png_write_chunk_end(png_ptr);
  201022. png_free(png_ptr, new_name);
  201023. }
  201024. #endif
  201025. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201026. /* write a sPLT chunk */
  201027. void /* PRIVATE */
  201028. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201029. {
  201030. #ifdef PNG_USE_LOCAL_ARRAYS
  201031. PNG_sPLT;
  201032. #endif
  201033. png_size_t name_len;
  201034. png_charp new_name;
  201035. png_byte entrybuf[10];
  201036. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201037. int palette_size = entry_size * spalette->nentries;
  201038. png_sPLT_entryp ep;
  201039. #ifdef PNG_NO_POINTER_INDEXING
  201040. int i;
  201041. #endif
  201042. png_debug(1, "in png_write_sPLT\n");
  201043. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201044. spalette->name, &new_name))==0)
  201045. {
  201046. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201047. return;
  201048. }
  201049. /* make sure we include the NULL after the name */
  201050. png_write_chunk_start(png_ptr, png_sPLT,
  201051. (png_uint_32)(name_len + 2 + palette_size));
  201052. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201053. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201054. /* loop through each palette entry, writing appropriately */
  201055. #ifndef PNG_NO_POINTER_INDEXING
  201056. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201057. {
  201058. if (spalette->depth == 8)
  201059. {
  201060. entrybuf[0] = (png_byte)ep->red;
  201061. entrybuf[1] = (png_byte)ep->green;
  201062. entrybuf[2] = (png_byte)ep->blue;
  201063. entrybuf[3] = (png_byte)ep->alpha;
  201064. png_save_uint_16(entrybuf + 4, ep->frequency);
  201065. }
  201066. else
  201067. {
  201068. png_save_uint_16(entrybuf + 0, ep->red);
  201069. png_save_uint_16(entrybuf + 2, ep->green);
  201070. png_save_uint_16(entrybuf + 4, ep->blue);
  201071. png_save_uint_16(entrybuf + 6, ep->alpha);
  201072. png_save_uint_16(entrybuf + 8, ep->frequency);
  201073. }
  201074. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201075. }
  201076. #else
  201077. ep=spalette->entries;
  201078. for (i=0; i>spalette->nentries; i++)
  201079. {
  201080. if (spalette->depth == 8)
  201081. {
  201082. entrybuf[0] = (png_byte)ep[i].red;
  201083. entrybuf[1] = (png_byte)ep[i].green;
  201084. entrybuf[2] = (png_byte)ep[i].blue;
  201085. entrybuf[3] = (png_byte)ep[i].alpha;
  201086. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201087. }
  201088. else
  201089. {
  201090. png_save_uint_16(entrybuf + 0, ep[i].red);
  201091. png_save_uint_16(entrybuf + 2, ep[i].green);
  201092. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201093. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201094. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201095. }
  201096. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201097. }
  201098. #endif
  201099. png_write_chunk_end(png_ptr);
  201100. png_free(png_ptr, new_name);
  201101. }
  201102. #endif
  201103. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201104. /* write the sBIT chunk */
  201105. void /* PRIVATE */
  201106. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201107. {
  201108. #ifdef PNG_USE_LOCAL_ARRAYS
  201109. PNG_sBIT;
  201110. #endif
  201111. png_byte buf[4];
  201112. png_size_t size;
  201113. png_debug(1, "in png_write_sBIT\n");
  201114. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201115. if (color_type & PNG_COLOR_MASK_COLOR)
  201116. {
  201117. png_byte maxbits;
  201118. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201119. png_ptr->usr_bit_depth);
  201120. if (sbit->red == 0 || sbit->red > maxbits ||
  201121. sbit->green == 0 || sbit->green > maxbits ||
  201122. sbit->blue == 0 || sbit->blue > maxbits)
  201123. {
  201124. png_warning(png_ptr, "Invalid sBIT depth specified");
  201125. return;
  201126. }
  201127. buf[0] = sbit->red;
  201128. buf[1] = sbit->green;
  201129. buf[2] = sbit->blue;
  201130. size = 3;
  201131. }
  201132. else
  201133. {
  201134. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201135. {
  201136. png_warning(png_ptr, "Invalid sBIT depth specified");
  201137. return;
  201138. }
  201139. buf[0] = sbit->gray;
  201140. size = 1;
  201141. }
  201142. if (color_type & PNG_COLOR_MASK_ALPHA)
  201143. {
  201144. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201145. {
  201146. png_warning(png_ptr, "Invalid sBIT depth specified");
  201147. return;
  201148. }
  201149. buf[size++] = sbit->alpha;
  201150. }
  201151. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201152. }
  201153. #endif
  201154. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201155. /* write the cHRM chunk */
  201156. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201157. void /* PRIVATE */
  201158. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201159. double red_x, double red_y, double green_x, double green_y,
  201160. double blue_x, double blue_y)
  201161. {
  201162. #ifdef PNG_USE_LOCAL_ARRAYS
  201163. PNG_cHRM;
  201164. #endif
  201165. png_byte buf[32];
  201166. png_uint_32 itemp;
  201167. png_debug(1, "in png_write_cHRM\n");
  201168. /* each value is saved in 1/100,000ths */
  201169. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201170. white_x + white_y > 1.0)
  201171. {
  201172. png_warning(png_ptr, "Invalid cHRM white point specified");
  201173. #if !defined(PNG_NO_CONSOLE_IO)
  201174. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201175. #endif
  201176. return;
  201177. }
  201178. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201179. png_save_uint_32(buf, itemp);
  201180. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201181. png_save_uint_32(buf + 4, itemp);
  201182. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201183. {
  201184. png_warning(png_ptr, "Invalid cHRM red point specified");
  201185. return;
  201186. }
  201187. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201188. png_save_uint_32(buf + 8, itemp);
  201189. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201190. png_save_uint_32(buf + 12, itemp);
  201191. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201192. {
  201193. png_warning(png_ptr, "Invalid cHRM green point specified");
  201194. return;
  201195. }
  201196. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201197. png_save_uint_32(buf + 16, itemp);
  201198. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201199. png_save_uint_32(buf + 20, itemp);
  201200. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201201. {
  201202. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201203. return;
  201204. }
  201205. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201206. png_save_uint_32(buf + 24, itemp);
  201207. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201208. png_save_uint_32(buf + 28, itemp);
  201209. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201210. }
  201211. #endif
  201212. #ifdef PNG_FIXED_POINT_SUPPORTED
  201213. void /* PRIVATE */
  201214. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201215. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201216. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201217. png_fixed_point blue_y)
  201218. {
  201219. #ifdef PNG_USE_LOCAL_ARRAYS
  201220. PNG_cHRM;
  201221. #endif
  201222. png_byte buf[32];
  201223. png_debug(1, "in png_write_cHRM\n");
  201224. /* each value is saved in 1/100,000ths */
  201225. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201226. {
  201227. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201228. #if !defined(PNG_NO_CONSOLE_IO)
  201229. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201230. #endif
  201231. return;
  201232. }
  201233. png_save_uint_32(buf, (png_uint_32)white_x);
  201234. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201235. if (red_x + red_y > 100000L)
  201236. {
  201237. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201238. return;
  201239. }
  201240. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201241. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201242. if (green_x + green_y > 100000L)
  201243. {
  201244. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201245. return;
  201246. }
  201247. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201248. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201249. if (blue_x + blue_y > 100000L)
  201250. {
  201251. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201252. return;
  201253. }
  201254. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201255. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201256. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201257. }
  201258. #endif
  201259. #endif
  201260. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201261. /* write the tRNS chunk */
  201262. void /* PRIVATE */
  201263. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201264. int num_trans, int color_type)
  201265. {
  201266. #ifdef PNG_USE_LOCAL_ARRAYS
  201267. PNG_tRNS;
  201268. #endif
  201269. png_byte buf[6];
  201270. png_debug(1, "in png_write_tRNS\n");
  201271. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201272. {
  201273. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201274. {
  201275. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201276. return;
  201277. }
  201278. /* write the chunk out as it is */
  201279. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201280. }
  201281. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201282. {
  201283. /* one 16 bit value */
  201284. if(tran->gray >= (1 << png_ptr->bit_depth))
  201285. {
  201286. png_warning(png_ptr,
  201287. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201288. return;
  201289. }
  201290. png_save_uint_16(buf, tran->gray);
  201291. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201292. }
  201293. else if (color_type == PNG_COLOR_TYPE_RGB)
  201294. {
  201295. /* three 16 bit values */
  201296. png_save_uint_16(buf, tran->red);
  201297. png_save_uint_16(buf + 2, tran->green);
  201298. png_save_uint_16(buf + 4, tran->blue);
  201299. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201300. {
  201301. png_warning(png_ptr,
  201302. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201303. return;
  201304. }
  201305. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201306. }
  201307. else
  201308. {
  201309. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201310. }
  201311. }
  201312. #endif
  201313. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201314. /* write the background chunk */
  201315. void /* PRIVATE */
  201316. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201317. {
  201318. #ifdef PNG_USE_LOCAL_ARRAYS
  201319. PNG_bKGD;
  201320. #endif
  201321. png_byte buf[6];
  201322. png_debug(1, "in png_write_bKGD\n");
  201323. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201324. {
  201325. if (
  201326. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201327. (png_ptr->num_palette ||
  201328. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201329. #endif
  201330. back->index > png_ptr->num_palette)
  201331. {
  201332. png_warning(png_ptr, "Invalid background palette index");
  201333. return;
  201334. }
  201335. buf[0] = back->index;
  201336. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201337. }
  201338. else if (color_type & PNG_COLOR_MASK_COLOR)
  201339. {
  201340. png_save_uint_16(buf, back->red);
  201341. png_save_uint_16(buf + 2, back->green);
  201342. png_save_uint_16(buf + 4, back->blue);
  201343. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201344. {
  201345. png_warning(png_ptr,
  201346. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201347. return;
  201348. }
  201349. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201350. }
  201351. else
  201352. {
  201353. if(back->gray >= (1 << png_ptr->bit_depth))
  201354. {
  201355. png_warning(png_ptr,
  201356. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201357. return;
  201358. }
  201359. png_save_uint_16(buf, back->gray);
  201360. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201361. }
  201362. }
  201363. #endif
  201364. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201365. /* write the histogram */
  201366. void /* PRIVATE */
  201367. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201368. {
  201369. #ifdef PNG_USE_LOCAL_ARRAYS
  201370. PNG_hIST;
  201371. #endif
  201372. int i;
  201373. png_byte buf[3];
  201374. png_debug(1, "in png_write_hIST\n");
  201375. if (num_hist > (int)png_ptr->num_palette)
  201376. {
  201377. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201378. png_ptr->num_palette);
  201379. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201380. return;
  201381. }
  201382. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201383. for (i = 0; i < num_hist; i++)
  201384. {
  201385. png_save_uint_16(buf, hist[i]);
  201386. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201387. }
  201388. png_write_chunk_end(png_ptr);
  201389. }
  201390. #endif
  201391. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201392. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201393. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201394. * and if invalid, correct the keyword rather than discarding the entire
  201395. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201396. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201397. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201398. *
  201399. * The new_key is allocated to hold the corrected keyword and must be freed
  201400. * by the calling routine. This avoids problems with trying to write to
  201401. * static keywords without having to have duplicate copies of the strings.
  201402. */
  201403. png_size_t /* PRIVATE */
  201404. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201405. {
  201406. png_size_t key_len;
  201407. png_charp kp, dp;
  201408. int kflag;
  201409. int kwarn=0;
  201410. png_debug(1, "in png_check_keyword\n");
  201411. *new_key = NULL;
  201412. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201413. {
  201414. png_warning(png_ptr, "zero length keyword");
  201415. return ((png_size_t)0);
  201416. }
  201417. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201418. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201419. if (*new_key == NULL)
  201420. {
  201421. png_warning(png_ptr, "Out of memory while procesing keyword");
  201422. return ((png_size_t)0);
  201423. }
  201424. /* Replace non-printing characters with a blank and print a warning */
  201425. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201426. {
  201427. if ((png_byte)*kp < 0x20 ||
  201428. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201429. {
  201430. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201431. char msg[40];
  201432. png_snprintf(msg, 40,
  201433. "invalid keyword character 0x%02X", (png_byte)*kp);
  201434. png_warning(png_ptr, msg);
  201435. #else
  201436. png_warning(png_ptr, "invalid character in keyword");
  201437. #endif
  201438. *dp = ' ';
  201439. }
  201440. else
  201441. {
  201442. *dp = *kp;
  201443. }
  201444. }
  201445. *dp = '\0';
  201446. /* Remove any trailing white space. */
  201447. kp = *new_key + key_len - 1;
  201448. if (*kp == ' ')
  201449. {
  201450. png_warning(png_ptr, "trailing spaces removed from keyword");
  201451. while (*kp == ' ')
  201452. {
  201453. *(kp--) = '\0';
  201454. key_len--;
  201455. }
  201456. }
  201457. /* Remove any leading white space. */
  201458. kp = *new_key;
  201459. if (*kp == ' ')
  201460. {
  201461. png_warning(png_ptr, "leading spaces removed from keyword");
  201462. while (*kp == ' ')
  201463. {
  201464. kp++;
  201465. key_len--;
  201466. }
  201467. }
  201468. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201469. /* Remove multiple internal spaces. */
  201470. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201471. {
  201472. if (*kp == ' ' && kflag == 0)
  201473. {
  201474. *(dp++) = *kp;
  201475. kflag = 1;
  201476. }
  201477. else if (*kp == ' ')
  201478. {
  201479. key_len--;
  201480. kwarn=1;
  201481. }
  201482. else
  201483. {
  201484. *(dp++) = *kp;
  201485. kflag = 0;
  201486. }
  201487. }
  201488. *dp = '\0';
  201489. if(kwarn)
  201490. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201491. if (key_len == 0)
  201492. {
  201493. png_free(png_ptr, *new_key);
  201494. *new_key=NULL;
  201495. png_warning(png_ptr, "Zero length keyword");
  201496. }
  201497. if (key_len > 79)
  201498. {
  201499. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201500. new_key[79] = '\0';
  201501. key_len = 79;
  201502. }
  201503. return (key_len);
  201504. }
  201505. #endif
  201506. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201507. /* write a tEXt chunk */
  201508. void /* PRIVATE */
  201509. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201510. png_size_t text_len)
  201511. {
  201512. #ifdef PNG_USE_LOCAL_ARRAYS
  201513. PNG_tEXt;
  201514. #endif
  201515. png_size_t key_len;
  201516. png_charp new_key;
  201517. png_debug(1, "in png_write_tEXt\n");
  201518. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201519. {
  201520. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201521. return;
  201522. }
  201523. if (text == NULL || *text == '\0')
  201524. text_len = 0;
  201525. else
  201526. text_len = png_strlen(text);
  201527. /* make sure we include the 0 after the key */
  201528. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201529. /*
  201530. * We leave it to the application to meet PNG-1.0 requirements on the
  201531. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201532. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201533. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201534. */
  201535. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201536. if (text_len)
  201537. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201538. png_write_chunk_end(png_ptr);
  201539. png_free(png_ptr, new_key);
  201540. }
  201541. #endif
  201542. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201543. /* write a compressed text chunk */
  201544. void /* PRIVATE */
  201545. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201546. png_size_t text_len, int compression)
  201547. {
  201548. #ifdef PNG_USE_LOCAL_ARRAYS
  201549. PNG_zTXt;
  201550. #endif
  201551. png_size_t key_len;
  201552. char buf[1];
  201553. png_charp new_key;
  201554. compression_state comp;
  201555. png_debug(1, "in png_write_zTXt\n");
  201556. comp.num_output_ptr = 0;
  201557. comp.max_output_ptr = 0;
  201558. comp.output_ptr = NULL;
  201559. comp.input = NULL;
  201560. comp.input_len = 0;
  201561. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201562. {
  201563. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201564. return;
  201565. }
  201566. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201567. {
  201568. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201569. png_free(png_ptr, new_key);
  201570. return;
  201571. }
  201572. text_len = png_strlen(text);
  201573. /* compute the compressed data; do it now for the length */
  201574. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201575. &comp);
  201576. /* write start of chunk */
  201577. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201578. (key_len+text_len+2));
  201579. /* write key */
  201580. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201581. png_free(png_ptr, new_key);
  201582. buf[0] = (png_byte)compression;
  201583. /* write compression */
  201584. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201585. /* write the compressed data */
  201586. png_write_compressed_data_out(png_ptr, &comp);
  201587. /* close the chunk */
  201588. png_write_chunk_end(png_ptr);
  201589. }
  201590. #endif
  201591. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201592. /* write an iTXt chunk */
  201593. void /* PRIVATE */
  201594. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201595. png_charp lang, png_charp lang_key, png_charp text)
  201596. {
  201597. #ifdef PNG_USE_LOCAL_ARRAYS
  201598. PNG_iTXt;
  201599. #endif
  201600. png_size_t lang_len, key_len, lang_key_len, text_len;
  201601. png_charp new_lang, new_key;
  201602. png_byte cbuf[2];
  201603. compression_state comp;
  201604. png_debug(1, "in png_write_iTXt\n");
  201605. comp.num_output_ptr = 0;
  201606. comp.max_output_ptr = 0;
  201607. comp.output_ptr = NULL;
  201608. comp.input = NULL;
  201609. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201610. {
  201611. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201612. return;
  201613. }
  201614. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201615. {
  201616. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201617. new_lang = NULL;
  201618. lang_len = 0;
  201619. }
  201620. if (lang_key == NULL)
  201621. lang_key_len = 0;
  201622. else
  201623. lang_key_len = png_strlen(lang_key);
  201624. if (text == NULL)
  201625. text_len = 0;
  201626. else
  201627. text_len = png_strlen(text);
  201628. /* compute the compressed data; do it now for the length */
  201629. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201630. &comp);
  201631. /* make sure we include the compression flag, the compression byte,
  201632. * and the NULs after the key, lang, and lang_key parts */
  201633. png_write_chunk_start(png_ptr, png_iTXt,
  201634. (png_uint_32)(
  201635. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201636. + key_len
  201637. + lang_len
  201638. + lang_key_len
  201639. + text_len));
  201640. /*
  201641. * We leave it to the application to meet PNG-1.0 requirements on the
  201642. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201643. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201644. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201645. */
  201646. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201647. /* set the compression flag */
  201648. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201649. compression == PNG_TEXT_COMPRESSION_NONE)
  201650. cbuf[0] = 0;
  201651. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201652. cbuf[0] = 1;
  201653. /* set the compression method */
  201654. cbuf[1] = 0;
  201655. png_write_chunk_data(png_ptr, cbuf, 2);
  201656. cbuf[0] = 0;
  201657. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201658. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201659. png_write_compressed_data_out(png_ptr, &comp);
  201660. png_write_chunk_end(png_ptr);
  201661. png_free(png_ptr, new_key);
  201662. if (new_lang)
  201663. png_free(png_ptr, new_lang);
  201664. }
  201665. #endif
  201666. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  201667. /* write the oFFs chunk */
  201668. void /* PRIVATE */
  201669. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  201670. int unit_type)
  201671. {
  201672. #ifdef PNG_USE_LOCAL_ARRAYS
  201673. PNG_oFFs;
  201674. #endif
  201675. png_byte buf[9];
  201676. png_debug(1, "in png_write_oFFs\n");
  201677. if (unit_type >= PNG_OFFSET_LAST)
  201678. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  201679. png_save_int_32(buf, x_offset);
  201680. png_save_int_32(buf + 4, y_offset);
  201681. buf[8] = (png_byte)unit_type;
  201682. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  201683. }
  201684. #endif
  201685. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  201686. /* write the pCAL chunk (described in the PNG extensions document) */
  201687. void /* PRIVATE */
  201688. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  201689. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  201690. {
  201691. #ifdef PNG_USE_LOCAL_ARRAYS
  201692. PNG_pCAL;
  201693. #endif
  201694. png_size_t purpose_len, units_len, total_len;
  201695. png_uint_32p params_len;
  201696. png_byte buf[10];
  201697. png_charp new_purpose;
  201698. int i;
  201699. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  201700. if (type >= PNG_EQUATION_LAST)
  201701. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  201702. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  201703. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  201704. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  201705. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  201706. total_len = purpose_len + units_len + 10;
  201707. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  201708. *png_sizeof(png_uint_32)));
  201709. /* Find the length of each parameter, making sure we don't count the
  201710. null terminator for the last parameter. */
  201711. for (i = 0; i < nparams; i++)
  201712. {
  201713. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  201714. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  201715. total_len += (png_size_t)params_len[i];
  201716. }
  201717. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  201718. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  201719. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  201720. png_save_int_32(buf, X0);
  201721. png_save_int_32(buf + 4, X1);
  201722. buf[8] = (png_byte)type;
  201723. buf[9] = (png_byte)nparams;
  201724. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  201725. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  201726. png_free(png_ptr, new_purpose);
  201727. for (i = 0; i < nparams; i++)
  201728. {
  201729. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  201730. (png_size_t)params_len[i]);
  201731. }
  201732. png_free(png_ptr, params_len);
  201733. png_write_chunk_end(png_ptr);
  201734. }
  201735. #endif
  201736. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  201737. /* write the sCAL chunk */
  201738. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  201739. void /* PRIVATE */
  201740. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  201741. {
  201742. #ifdef PNG_USE_LOCAL_ARRAYS
  201743. PNG_sCAL;
  201744. #endif
  201745. char buf[64];
  201746. png_size_t total_len;
  201747. png_debug(1, "in png_write_sCAL\n");
  201748. buf[0] = (char)unit;
  201749. #if defined(_WIN32_WCE)
  201750. /* sprintf() function is not supported on WindowsCE */
  201751. {
  201752. wchar_t wc_buf[32];
  201753. size_t wc_len;
  201754. swprintf(wc_buf, TEXT("%12.12e"), width);
  201755. wc_len = wcslen(wc_buf);
  201756. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  201757. total_len = wc_len + 2;
  201758. swprintf(wc_buf, TEXT("%12.12e"), height);
  201759. wc_len = wcslen(wc_buf);
  201760. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  201761. NULL, NULL);
  201762. total_len += wc_len;
  201763. }
  201764. #else
  201765. png_snprintf(buf + 1, 63, "%12.12e", width);
  201766. total_len = 1 + png_strlen(buf + 1) + 1;
  201767. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  201768. total_len += png_strlen(buf + total_len);
  201769. #endif
  201770. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201771. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  201772. }
  201773. #else
  201774. #ifdef PNG_FIXED_POINT_SUPPORTED
  201775. void /* PRIVATE */
  201776. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  201777. png_charp height)
  201778. {
  201779. #ifdef PNG_USE_LOCAL_ARRAYS
  201780. PNG_sCAL;
  201781. #endif
  201782. png_byte buf[64];
  201783. png_size_t wlen, hlen, total_len;
  201784. png_debug(1, "in png_write_sCAL_s\n");
  201785. wlen = png_strlen(width);
  201786. hlen = png_strlen(height);
  201787. total_len = wlen + hlen + 2;
  201788. if (total_len > 64)
  201789. {
  201790. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  201791. return;
  201792. }
  201793. buf[0] = (png_byte)unit;
  201794. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  201795. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  201796. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  201797. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  201798. }
  201799. #endif
  201800. #endif
  201801. #endif
  201802. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  201803. /* write the pHYs chunk */
  201804. void /* PRIVATE */
  201805. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  201806. png_uint_32 y_pixels_per_unit,
  201807. int unit_type)
  201808. {
  201809. #ifdef PNG_USE_LOCAL_ARRAYS
  201810. PNG_pHYs;
  201811. #endif
  201812. png_byte buf[9];
  201813. png_debug(1, "in png_write_pHYs\n");
  201814. if (unit_type >= PNG_RESOLUTION_LAST)
  201815. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  201816. png_save_uint_32(buf, x_pixels_per_unit);
  201817. png_save_uint_32(buf + 4, y_pixels_per_unit);
  201818. buf[8] = (png_byte)unit_type;
  201819. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  201820. }
  201821. #endif
  201822. #if defined(PNG_WRITE_tIME_SUPPORTED)
  201823. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  201824. * or png_convert_from_time_t(), or fill in the structure yourself.
  201825. */
  201826. void /* PRIVATE */
  201827. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  201828. {
  201829. #ifdef PNG_USE_LOCAL_ARRAYS
  201830. PNG_tIME;
  201831. #endif
  201832. png_byte buf[7];
  201833. png_debug(1, "in png_write_tIME\n");
  201834. if (mod_time->month > 12 || mod_time->month < 1 ||
  201835. mod_time->day > 31 || mod_time->day < 1 ||
  201836. mod_time->hour > 23 || mod_time->second > 60)
  201837. {
  201838. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  201839. return;
  201840. }
  201841. png_save_uint_16(buf, mod_time->year);
  201842. buf[2] = mod_time->month;
  201843. buf[3] = mod_time->day;
  201844. buf[4] = mod_time->hour;
  201845. buf[5] = mod_time->minute;
  201846. buf[6] = mod_time->second;
  201847. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  201848. }
  201849. #endif
  201850. /* initializes the row writing capability of libpng */
  201851. void /* PRIVATE */
  201852. png_write_start_row(png_structp png_ptr)
  201853. {
  201854. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201855. #ifdef PNG_USE_LOCAL_ARRAYS
  201856. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201857. /* start of interlace block */
  201858. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201859. /* offset to next interlace block */
  201860. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201861. /* start of interlace block in the y direction */
  201862. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201863. /* offset to next interlace block in the y direction */
  201864. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201865. #endif
  201866. #endif
  201867. png_size_t buf_size;
  201868. png_debug(1, "in png_write_start_row\n");
  201869. buf_size = (png_size_t)(PNG_ROWBYTES(
  201870. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  201871. /* set up row buffer */
  201872. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201873. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  201874. #ifndef PNG_NO_WRITE_FILTERING
  201875. /* set up filtering buffer, if using this filter */
  201876. if (png_ptr->do_filter & PNG_FILTER_SUB)
  201877. {
  201878. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  201879. (png_ptr->rowbytes + 1));
  201880. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  201881. }
  201882. /* We only need to keep the previous row if we are using one of these. */
  201883. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  201884. {
  201885. /* set up previous row buffer */
  201886. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  201887. png_memset(png_ptr->prev_row, 0, buf_size);
  201888. if (png_ptr->do_filter & PNG_FILTER_UP)
  201889. {
  201890. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  201891. (png_ptr->rowbytes + 1));
  201892. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  201893. }
  201894. if (png_ptr->do_filter & PNG_FILTER_AVG)
  201895. {
  201896. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  201897. (png_ptr->rowbytes + 1));
  201898. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  201899. }
  201900. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  201901. {
  201902. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  201903. (png_ptr->rowbytes + 1));
  201904. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  201905. }
  201906. #endif /* PNG_NO_WRITE_FILTERING */
  201907. }
  201908. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201909. /* if interlaced, we need to set up width and height of pass */
  201910. if (png_ptr->interlaced)
  201911. {
  201912. if (!(png_ptr->transformations & PNG_INTERLACE))
  201913. {
  201914. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  201915. png_pass_ystart[0]) / png_pass_yinc[0];
  201916. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  201917. png_pass_start[0]) / png_pass_inc[0];
  201918. }
  201919. else
  201920. {
  201921. png_ptr->num_rows = png_ptr->height;
  201922. png_ptr->usr_width = png_ptr->width;
  201923. }
  201924. }
  201925. else
  201926. #endif
  201927. {
  201928. png_ptr->num_rows = png_ptr->height;
  201929. png_ptr->usr_width = png_ptr->width;
  201930. }
  201931. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201932. png_ptr->zstream.next_out = png_ptr->zbuf;
  201933. }
  201934. /* Internal use only. Called when finished processing a row of data. */
  201935. void /* PRIVATE */
  201936. png_write_finish_row(png_structp png_ptr)
  201937. {
  201938. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201939. #ifdef PNG_USE_LOCAL_ARRAYS
  201940. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  201941. /* start of interlace block */
  201942. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  201943. /* offset to next interlace block */
  201944. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  201945. /* start of interlace block in the y direction */
  201946. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  201947. /* offset to next interlace block in the y direction */
  201948. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  201949. #endif
  201950. #endif
  201951. int ret;
  201952. png_debug(1, "in png_write_finish_row\n");
  201953. /* next row */
  201954. png_ptr->row_number++;
  201955. /* see if we are done */
  201956. if (png_ptr->row_number < png_ptr->num_rows)
  201957. return;
  201958. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201959. /* if interlaced, go to next pass */
  201960. if (png_ptr->interlaced)
  201961. {
  201962. png_ptr->row_number = 0;
  201963. if (png_ptr->transformations & PNG_INTERLACE)
  201964. {
  201965. png_ptr->pass++;
  201966. }
  201967. else
  201968. {
  201969. /* loop until we find a non-zero width or height pass */
  201970. do
  201971. {
  201972. png_ptr->pass++;
  201973. if (png_ptr->pass >= 7)
  201974. break;
  201975. png_ptr->usr_width = (png_ptr->width +
  201976. png_pass_inc[png_ptr->pass] - 1 -
  201977. png_pass_start[png_ptr->pass]) /
  201978. png_pass_inc[png_ptr->pass];
  201979. png_ptr->num_rows = (png_ptr->height +
  201980. png_pass_yinc[png_ptr->pass] - 1 -
  201981. png_pass_ystart[png_ptr->pass]) /
  201982. png_pass_yinc[png_ptr->pass];
  201983. if (png_ptr->transformations & PNG_INTERLACE)
  201984. break;
  201985. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  201986. }
  201987. /* reset the row above the image for the next pass */
  201988. if (png_ptr->pass < 7)
  201989. {
  201990. if (png_ptr->prev_row != NULL)
  201991. png_memset(png_ptr->prev_row, 0,
  201992. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  201993. png_ptr->usr_bit_depth,png_ptr->width))+1);
  201994. return;
  201995. }
  201996. }
  201997. #endif
  201998. /* if we get here, we've just written the last row, so we need
  201999. to flush the compressor */
  202000. do
  202001. {
  202002. /* tell the compressor we are done */
  202003. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202004. /* check for an error */
  202005. if (ret == Z_OK)
  202006. {
  202007. /* check to see if we need more room */
  202008. if (!(png_ptr->zstream.avail_out))
  202009. {
  202010. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202011. png_ptr->zstream.next_out = png_ptr->zbuf;
  202012. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202013. }
  202014. }
  202015. else if (ret != Z_STREAM_END)
  202016. {
  202017. if (png_ptr->zstream.msg != NULL)
  202018. png_error(png_ptr, png_ptr->zstream.msg);
  202019. else
  202020. png_error(png_ptr, "zlib error");
  202021. }
  202022. } while (ret != Z_STREAM_END);
  202023. /* write any extra space */
  202024. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202025. {
  202026. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202027. png_ptr->zstream.avail_out);
  202028. }
  202029. deflateReset(&png_ptr->zstream);
  202030. png_ptr->zstream.data_type = Z_BINARY;
  202031. }
  202032. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202033. /* Pick out the correct pixels for the interlace pass.
  202034. * The basic idea here is to go through the row with a source
  202035. * pointer and a destination pointer (sp and dp), and copy the
  202036. * correct pixels for the pass. As the row gets compacted,
  202037. * sp will always be >= dp, so we should never overwrite anything.
  202038. * See the default: case for the easiest code to understand.
  202039. */
  202040. void /* PRIVATE */
  202041. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202042. {
  202043. #ifdef PNG_USE_LOCAL_ARRAYS
  202044. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202045. /* start of interlace block */
  202046. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202047. /* offset to next interlace block */
  202048. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202049. #endif
  202050. png_debug(1, "in png_do_write_interlace\n");
  202051. /* we don't have to do anything on the last pass (6) */
  202052. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202053. if (row != NULL && row_info != NULL && pass < 6)
  202054. #else
  202055. if (pass < 6)
  202056. #endif
  202057. {
  202058. /* each pixel depth is handled separately */
  202059. switch (row_info->pixel_depth)
  202060. {
  202061. case 1:
  202062. {
  202063. png_bytep sp;
  202064. png_bytep dp;
  202065. int shift;
  202066. int d;
  202067. int value;
  202068. png_uint_32 i;
  202069. png_uint_32 row_width = row_info->width;
  202070. dp = row;
  202071. d = 0;
  202072. shift = 7;
  202073. for (i = png_pass_start[pass]; i < row_width;
  202074. i += png_pass_inc[pass])
  202075. {
  202076. sp = row + (png_size_t)(i >> 3);
  202077. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202078. d |= (value << shift);
  202079. if (shift == 0)
  202080. {
  202081. shift = 7;
  202082. *dp++ = (png_byte)d;
  202083. d = 0;
  202084. }
  202085. else
  202086. shift--;
  202087. }
  202088. if (shift != 7)
  202089. *dp = (png_byte)d;
  202090. break;
  202091. }
  202092. case 2:
  202093. {
  202094. png_bytep sp;
  202095. png_bytep dp;
  202096. int shift;
  202097. int d;
  202098. int value;
  202099. png_uint_32 i;
  202100. png_uint_32 row_width = row_info->width;
  202101. dp = row;
  202102. shift = 6;
  202103. d = 0;
  202104. for (i = png_pass_start[pass]; i < row_width;
  202105. i += png_pass_inc[pass])
  202106. {
  202107. sp = row + (png_size_t)(i >> 2);
  202108. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202109. d |= (value << shift);
  202110. if (shift == 0)
  202111. {
  202112. shift = 6;
  202113. *dp++ = (png_byte)d;
  202114. d = 0;
  202115. }
  202116. else
  202117. shift -= 2;
  202118. }
  202119. if (shift != 6)
  202120. *dp = (png_byte)d;
  202121. break;
  202122. }
  202123. case 4:
  202124. {
  202125. png_bytep sp;
  202126. png_bytep dp;
  202127. int shift;
  202128. int d;
  202129. int value;
  202130. png_uint_32 i;
  202131. png_uint_32 row_width = row_info->width;
  202132. dp = row;
  202133. shift = 4;
  202134. d = 0;
  202135. for (i = png_pass_start[pass]; i < row_width;
  202136. i += png_pass_inc[pass])
  202137. {
  202138. sp = row + (png_size_t)(i >> 1);
  202139. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202140. d |= (value << shift);
  202141. if (shift == 0)
  202142. {
  202143. shift = 4;
  202144. *dp++ = (png_byte)d;
  202145. d = 0;
  202146. }
  202147. else
  202148. shift -= 4;
  202149. }
  202150. if (shift != 4)
  202151. *dp = (png_byte)d;
  202152. break;
  202153. }
  202154. default:
  202155. {
  202156. png_bytep sp;
  202157. png_bytep dp;
  202158. png_uint_32 i;
  202159. png_uint_32 row_width = row_info->width;
  202160. png_size_t pixel_bytes;
  202161. /* start at the beginning */
  202162. dp = row;
  202163. /* find out how many bytes each pixel takes up */
  202164. pixel_bytes = (row_info->pixel_depth >> 3);
  202165. /* loop through the row, only looking at the pixels that
  202166. matter */
  202167. for (i = png_pass_start[pass]; i < row_width;
  202168. i += png_pass_inc[pass])
  202169. {
  202170. /* find out where the original pixel is */
  202171. sp = row + (png_size_t)i * pixel_bytes;
  202172. /* move the pixel */
  202173. if (dp != sp)
  202174. png_memcpy(dp, sp, pixel_bytes);
  202175. /* next pixel */
  202176. dp += pixel_bytes;
  202177. }
  202178. break;
  202179. }
  202180. }
  202181. /* set new row width */
  202182. row_info->width = (row_info->width +
  202183. png_pass_inc[pass] - 1 -
  202184. png_pass_start[pass]) /
  202185. png_pass_inc[pass];
  202186. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202187. row_info->width);
  202188. }
  202189. }
  202190. #endif
  202191. /* This filters the row, chooses which filter to use, if it has not already
  202192. * been specified by the application, and then writes the row out with the
  202193. * chosen filter.
  202194. */
  202195. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202196. #define PNG_HISHIFT 10
  202197. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202198. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202199. void /* PRIVATE */
  202200. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202201. {
  202202. png_bytep best_row;
  202203. #ifndef PNG_NO_WRITE_FILTER
  202204. png_bytep prev_row, row_buf;
  202205. png_uint_32 mins, bpp;
  202206. png_byte filter_to_do = png_ptr->do_filter;
  202207. png_uint_32 row_bytes = row_info->rowbytes;
  202208. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202209. int num_p_filters = (int)png_ptr->num_prev_filters;
  202210. #endif
  202211. png_debug(1, "in png_write_find_filter\n");
  202212. /* find out how many bytes offset each pixel is */
  202213. bpp = (row_info->pixel_depth + 7) >> 3;
  202214. prev_row = png_ptr->prev_row;
  202215. #endif
  202216. best_row = png_ptr->row_buf;
  202217. #ifndef PNG_NO_WRITE_FILTER
  202218. row_buf = best_row;
  202219. mins = PNG_MAXSUM;
  202220. /* The prediction method we use is to find which method provides the
  202221. * smallest value when summing the absolute values of the distances
  202222. * from zero, using anything >= 128 as negative numbers. This is known
  202223. * as the "minimum sum of absolute differences" heuristic. Other
  202224. * heuristics are the "weighted minimum sum of absolute differences"
  202225. * (experimental and can in theory improve compression), and the "zlib
  202226. * predictive" method (not implemented yet), which does test compressions
  202227. * of lines using different filter methods, and then chooses the
  202228. * (series of) filter(s) that give minimum compressed data size (VERY
  202229. * computationally expensive).
  202230. *
  202231. * GRR 980525: consider also
  202232. * (1) minimum sum of absolute differences from running average (i.e.,
  202233. * keep running sum of non-absolute differences & count of bytes)
  202234. * [track dispersion, too? restart average if dispersion too large?]
  202235. * (1b) minimum sum of absolute differences from sliding average, probably
  202236. * with window size <= deflate window (usually 32K)
  202237. * (2) minimum sum of squared differences from zero or running average
  202238. * (i.e., ~ root-mean-square approach)
  202239. */
  202240. /* We don't need to test the 'no filter' case if this is the only filter
  202241. * that has been chosen, as it doesn't actually do anything to the data.
  202242. */
  202243. if ((filter_to_do & PNG_FILTER_NONE) &&
  202244. filter_to_do != PNG_FILTER_NONE)
  202245. {
  202246. png_bytep rp;
  202247. png_uint_32 sum = 0;
  202248. png_uint_32 i;
  202249. int v;
  202250. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202251. {
  202252. v = *rp;
  202253. sum += (v < 128) ? v : 256 - v;
  202254. }
  202255. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202256. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202257. {
  202258. png_uint_32 sumhi, sumlo;
  202259. int j;
  202260. sumlo = sum & PNG_LOMASK;
  202261. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202262. /* Reduce the sum if we match any of the previous rows */
  202263. for (j = 0; j < num_p_filters; j++)
  202264. {
  202265. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202266. {
  202267. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202268. PNG_WEIGHT_SHIFT;
  202269. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202270. PNG_WEIGHT_SHIFT;
  202271. }
  202272. }
  202273. /* Factor in the cost of this filter (this is here for completeness,
  202274. * but it makes no sense to have a "cost" for the NONE filter, as
  202275. * it has the minimum possible computational cost - none).
  202276. */
  202277. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202278. PNG_COST_SHIFT;
  202279. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202280. PNG_COST_SHIFT;
  202281. if (sumhi > PNG_HIMASK)
  202282. sum = PNG_MAXSUM;
  202283. else
  202284. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202285. }
  202286. #endif
  202287. mins = sum;
  202288. }
  202289. /* sub filter */
  202290. if (filter_to_do == PNG_FILTER_SUB)
  202291. /* it's the only filter so no testing is needed */
  202292. {
  202293. png_bytep rp, lp, dp;
  202294. png_uint_32 i;
  202295. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202296. i++, rp++, dp++)
  202297. {
  202298. *dp = *rp;
  202299. }
  202300. for (lp = row_buf + 1; i < row_bytes;
  202301. i++, rp++, lp++, dp++)
  202302. {
  202303. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202304. }
  202305. best_row = png_ptr->sub_row;
  202306. }
  202307. else if (filter_to_do & PNG_FILTER_SUB)
  202308. {
  202309. png_bytep rp, dp, lp;
  202310. png_uint_32 sum = 0, lmins = mins;
  202311. png_uint_32 i;
  202312. int v;
  202313. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202314. /* We temporarily increase the "minimum sum" by the factor we
  202315. * would reduce the sum of this filter, so that we can do the
  202316. * early exit comparison without scaling the sum each time.
  202317. */
  202318. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202319. {
  202320. int j;
  202321. png_uint_32 lmhi, lmlo;
  202322. lmlo = lmins & PNG_LOMASK;
  202323. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202324. for (j = 0; j < num_p_filters; j++)
  202325. {
  202326. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202327. {
  202328. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202329. PNG_WEIGHT_SHIFT;
  202330. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202331. PNG_WEIGHT_SHIFT;
  202332. }
  202333. }
  202334. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202335. PNG_COST_SHIFT;
  202336. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202337. PNG_COST_SHIFT;
  202338. if (lmhi > PNG_HIMASK)
  202339. lmins = PNG_MAXSUM;
  202340. else
  202341. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202342. }
  202343. #endif
  202344. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202345. i++, rp++, dp++)
  202346. {
  202347. v = *dp = *rp;
  202348. sum += (v < 128) ? v : 256 - v;
  202349. }
  202350. for (lp = row_buf + 1; i < row_bytes;
  202351. i++, rp++, lp++, dp++)
  202352. {
  202353. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202354. sum += (v < 128) ? v : 256 - v;
  202355. if (sum > lmins) /* We are already worse, don't continue. */
  202356. break;
  202357. }
  202358. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202359. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202360. {
  202361. int j;
  202362. png_uint_32 sumhi, sumlo;
  202363. sumlo = sum & PNG_LOMASK;
  202364. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202365. for (j = 0; j < num_p_filters; j++)
  202366. {
  202367. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202368. {
  202369. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202370. PNG_WEIGHT_SHIFT;
  202371. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202372. PNG_WEIGHT_SHIFT;
  202373. }
  202374. }
  202375. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202376. PNG_COST_SHIFT;
  202377. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202378. PNG_COST_SHIFT;
  202379. if (sumhi > PNG_HIMASK)
  202380. sum = PNG_MAXSUM;
  202381. else
  202382. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202383. }
  202384. #endif
  202385. if (sum < mins)
  202386. {
  202387. mins = sum;
  202388. best_row = png_ptr->sub_row;
  202389. }
  202390. }
  202391. /* up filter */
  202392. if (filter_to_do == PNG_FILTER_UP)
  202393. {
  202394. png_bytep rp, dp, pp;
  202395. png_uint_32 i;
  202396. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202397. pp = prev_row + 1; i < row_bytes;
  202398. i++, rp++, pp++, dp++)
  202399. {
  202400. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202401. }
  202402. best_row = png_ptr->up_row;
  202403. }
  202404. else if (filter_to_do & PNG_FILTER_UP)
  202405. {
  202406. png_bytep rp, dp, pp;
  202407. png_uint_32 sum = 0, lmins = mins;
  202408. png_uint_32 i;
  202409. int v;
  202410. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202411. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202412. {
  202413. int j;
  202414. png_uint_32 lmhi, lmlo;
  202415. lmlo = lmins & PNG_LOMASK;
  202416. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202417. for (j = 0; j < num_p_filters; j++)
  202418. {
  202419. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202420. {
  202421. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202422. PNG_WEIGHT_SHIFT;
  202423. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202424. PNG_WEIGHT_SHIFT;
  202425. }
  202426. }
  202427. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202428. PNG_COST_SHIFT;
  202429. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202430. PNG_COST_SHIFT;
  202431. if (lmhi > PNG_HIMASK)
  202432. lmins = PNG_MAXSUM;
  202433. else
  202434. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202435. }
  202436. #endif
  202437. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202438. pp = prev_row + 1; i < row_bytes; i++)
  202439. {
  202440. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202441. sum += (v < 128) ? v : 256 - v;
  202442. if (sum > lmins) /* We are already worse, don't continue. */
  202443. break;
  202444. }
  202445. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202446. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202447. {
  202448. int j;
  202449. png_uint_32 sumhi, sumlo;
  202450. sumlo = sum & PNG_LOMASK;
  202451. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202452. for (j = 0; j < num_p_filters; j++)
  202453. {
  202454. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202455. {
  202456. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202457. PNG_WEIGHT_SHIFT;
  202458. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202459. PNG_WEIGHT_SHIFT;
  202460. }
  202461. }
  202462. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202463. PNG_COST_SHIFT;
  202464. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202465. PNG_COST_SHIFT;
  202466. if (sumhi > PNG_HIMASK)
  202467. sum = PNG_MAXSUM;
  202468. else
  202469. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202470. }
  202471. #endif
  202472. if (sum < mins)
  202473. {
  202474. mins = sum;
  202475. best_row = png_ptr->up_row;
  202476. }
  202477. }
  202478. /* avg filter */
  202479. if (filter_to_do == PNG_FILTER_AVG)
  202480. {
  202481. png_bytep rp, dp, pp, lp;
  202482. png_uint_32 i;
  202483. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202484. pp = prev_row + 1; i < bpp; i++)
  202485. {
  202486. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202487. }
  202488. for (lp = row_buf + 1; i < row_bytes; i++)
  202489. {
  202490. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202491. & 0xff);
  202492. }
  202493. best_row = png_ptr->avg_row;
  202494. }
  202495. else if (filter_to_do & PNG_FILTER_AVG)
  202496. {
  202497. png_bytep rp, dp, pp, lp;
  202498. png_uint_32 sum = 0, lmins = mins;
  202499. png_uint_32 i;
  202500. int v;
  202501. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202502. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202503. {
  202504. int j;
  202505. png_uint_32 lmhi, lmlo;
  202506. lmlo = lmins & PNG_LOMASK;
  202507. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202508. for (j = 0; j < num_p_filters; j++)
  202509. {
  202510. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202511. {
  202512. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202513. PNG_WEIGHT_SHIFT;
  202514. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202515. PNG_WEIGHT_SHIFT;
  202516. }
  202517. }
  202518. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202519. PNG_COST_SHIFT;
  202520. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202521. PNG_COST_SHIFT;
  202522. if (lmhi > PNG_HIMASK)
  202523. lmins = PNG_MAXSUM;
  202524. else
  202525. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202526. }
  202527. #endif
  202528. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202529. pp = prev_row + 1; i < bpp; i++)
  202530. {
  202531. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202532. sum += (v < 128) ? v : 256 - v;
  202533. }
  202534. for (lp = row_buf + 1; i < row_bytes; i++)
  202535. {
  202536. v = *dp++ =
  202537. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202538. sum += (v < 128) ? v : 256 - v;
  202539. if (sum > lmins) /* We are already worse, don't continue. */
  202540. break;
  202541. }
  202542. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202543. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202544. {
  202545. int j;
  202546. png_uint_32 sumhi, sumlo;
  202547. sumlo = sum & PNG_LOMASK;
  202548. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202549. for (j = 0; j < num_p_filters; j++)
  202550. {
  202551. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202552. {
  202553. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202554. PNG_WEIGHT_SHIFT;
  202555. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202556. PNG_WEIGHT_SHIFT;
  202557. }
  202558. }
  202559. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202560. PNG_COST_SHIFT;
  202561. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202562. PNG_COST_SHIFT;
  202563. if (sumhi > PNG_HIMASK)
  202564. sum = PNG_MAXSUM;
  202565. else
  202566. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202567. }
  202568. #endif
  202569. if (sum < mins)
  202570. {
  202571. mins = sum;
  202572. best_row = png_ptr->avg_row;
  202573. }
  202574. }
  202575. /* Paeth filter */
  202576. if (filter_to_do == PNG_FILTER_PAETH)
  202577. {
  202578. png_bytep rp, dp, pp, cp, lp;
  202579. png_uint_32 i;
  202580. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202581. pp = prev_row + 1; i < bpp; i++)
  202582. {
  202583. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202584. }
  202585. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202586. {
  202587. int a, b, c, pa, pb, pc, p;
  202588. b = *pp++;
  202589. c = *cp++;
  202590. a = *lp++;
  202591. p = b - c;
  202592. pc = a - c;
  202593. #ifdef PNG_USE_ABS
  202594. pa = abs(p);
  202595. pb = abs(pc);
  202596. pc = abs(p + pc);
  202597. #else
  202598. pa = p < 0 ? -p : p;
  202599. pb = pc < 0 ? -pc : pc;
  202600. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202601. #endif
  202602. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202603. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202604. }
  202605. best_row = png_ptr->paeth_row;
  202606. }
  202607. else if (filter_to_do & PNG_FILTER_PAETH)
  202608. {
  202609. png_bytep rp, dp, pp, cp, lp;
  202610. png_uint_32 sum = 0, lmins = mins;
  202611. png_uint_32 i;
  202612. int v;
  202613. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202614. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202615. {
  202616. int j;
  202617. png_uint_32 lmhi, lmlo;
  202618. lmlo = lmins & PNG_LOMASK;
  202619. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202620. for (j = 0; j < num_p_filters; j++)
  202621. {
  202622. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202623. {
  202624. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202625. PNG_WEIGHT_SHIFT;
  202626. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202627. PNG_WEIGHT_SHIFT;
  202628. }
  202629. }
  202630. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202631. PNG_COST_SHIFT;
  202632. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202633. PNG_COST_SHIFT;
  202634. if (lmhi > PNG_HIMASK)
  202635. lmins = PNG_MAXSUM;
  202636. else
  202637. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202638. }
  202639. #endif
  202640. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202641. pp = prev_row + 1; i < bpp; i++)
  202642. {
  202643. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202644. sum += (v < 128) ? v : 256 - v;
  202645. }
  202646. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202647. {
  202648. int a, b, c, pa, pb, pc, p;
  202649. b = *pp++;
  202650. c = *cp++;
  202651. a = *lp++;
  202652. #ifndef PNG_SLOW_PAETH
  202653. p = b - c;
  202654. pc = a - c;
  202655. #ifdef PNG_USE_ABS
  202656. pa = abs(p);
  202657. pb = abs(pc);
  202658. pc = abs(p + pc);
  202659. #else
  202660. pa = p < 0 ? -p : p;
  202661. pb = pc < 0 ? -pc : pc;
  202662. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202663. #endif
  202664. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202665. #else /* PNG_SLOW_PAETH */
  202666. p = a + b - c;
  202667. pa = abs(p - a);
  202668. pb = abs(p - b);
  202669. pc = abs(p - c);
  202670. if (pa <= pb && pa <= pc)
  202671. p = a;
  202672. else if (pb <= pc)
  202673. p = b;
  202674. else
  202675. p = c;
  202676. #endif /* PNG_SLOW_PAETH */
  202677. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202678. sum += (v < 128) ? v : 256 - v;
  202679. if (sum > lmins) /* We are already worse, don't continue. */
  202680. break;
  202681. }
  202682. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202683. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202684. {
  202685. int j;
  202686. png_uint_32 sumhi, sumlo;
  202687. sumlo = sum & PNG_LOMASK;
  202688. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202689. for (j = 0; j < num_p_filters; j++)
  202690. {
  202691. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202692. {
  202693. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202694. PNG_WEIGHT_SHIFT;
  202695. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202696. PNG_WEIGHT_SHIFT;
  202697. }
  202698. }
  202699. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202700. PNG_COST_SHIFT;
  202701. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202702. PNG_COST_SHIFT;
  202703. if (sumhi > PNG_HIMASK)
  202704. sum = PNG_MAXSUM;
  202705. else
  202706. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202707. }
  202708. #endif
  202709. if (sum < mins)
  202710. {
  202711. best_row = png_ptr->paeth_row;
  202712. }
  202713. }
  202714. #endif /* PNG_NO_WRITE_FILTER */
  202715. /* Do the actual writing of the filtered row data from the chosen filter. */
  202716. png_write_filtered_row(png_ptr, best_row);
  202717. #ifndef PNG_NO_WRITE_FILTER
  202718. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202719. /* Save the type of filter we picked this time for future calculations */
  202720. if (png_ptr->num_prev_filters > 0)
  202721. {
  202722. int j;
  202723. for (j = 1; j < num_p_filters; j++)
  202724. {
  202725. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  202726. }
  202727. png_ptr->prev_filters[j] = best_row[0];
  202728. }
  202729. #endif
  202730. #endif /* PNG_NO_WRITE_FILTER */
  202731. }
  202732. /* Do the actual writing of a previously filtered row. */
  202733. void /* PRIVATE */
  202734. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  202735. {
  202736. png_debug(1, "in png_write_filtered_row\n");
  202737. png_debug1(2, "filter = %d\n", filtered_row[0]);
  202738. /* set up the zlib input buffer */
  202739. png_ptr->zstream.next_in = filtered_row;
  202740. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  202741. /* repeat until we have compressed all the data */
  202742. do
  202743. {
  202744. int ret; /* return of zlib */
  202745. /* compress the data */
  202746. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  202747. /* check for compression errors */
  202748. if (ret != Z_OK)
  202749. {
  202750. if (png_ptr->zstream.msg != NULL)
  202751. png_error(png_ptr, png_ptr->zstream.msg);
  202752. else
  202753. png_error(png_ptr, "zlib error");
  202754. }
  202755. /* see if it is time to write another IDAT */
  202756. if (!(png_ptr->zstream.avail_out))
  202757. {
  202758. /* write the IDAT and reset the zlib output buffer */
  202759. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202760. png_ptr->zstream.next_out = png_ptr->zbuf;
  202761. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202762. }
  202763. /* repeat until all data has been compressed */
  202764. } while (png_ptr->zstream.avail_in);
  202765. /* swap the current and previous rows */
  202766. if (png_ptr->prev_row != NULL)
  202767. {
  202768. png_bytep tptr;
  202769. tptr = png_ptr->prev_row;
  202770. png_ptr->prev_row = png_ptr->row_buf;
  202771. png_ptr->row_buf = tptr;
  202772. }
  202773. /* finish row - updates counters and flushes zlib if last row */
  202774. png_write_finish_row(png_ptr);
  202775. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  202776. png_ptr->flush_rows++;
  202777. if (png_ptr->flush_dist > 0 &&
  202778. png_ptr->flush_rows >= png_ptr->flush_dist)
  202779. {
  202780. png_write_flush(png_ptr);
  202781. }
  202782. #endif
  202783. }
  202784. #endif /* PNG_WRITE_SUPPORTED */
  202785. /*** End of inlined file: pngwutil.c ***/
  202786. #else
  202787. extern "C"
  202788. {
  202789. #include <png.h>
  202790. #include <pngconf.h>
  202791. }
  202792. #endif
  202793. }
  202794. #undef max
  202795. #undef min
  202796. #if JUCE_MSVC
  202797. #pragma warning (pop)
  202798. #endif
  202799. BEGIN_JUCE_NAMESPACE
  202800. using ::calloc;
  202801. using ::malloc;
  202802. using ::free;
  202803. namespace PNGHelpers
  202804. {
  202805. using namespace pnglibNamespace;
  202806. void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  202807. {
  202808. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  202809. }
  202810. void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  202811. {
  202812. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  202813. }
  202814. struct PNGErrorStruct {};
  202815. void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  202816. {
  202817. throw PNGErrorStruct();
  202818. }
  202819. }
  202820. PNGImageFormat::PNGImageFormat() {}
  202821. PNGImageFormat::~PNGImageFormat() {}
  202822. const String PNGImageFormat::getFormatName()
  202823. {
  202824. return "PNG";
  202825. }
  202826. bool PNGImageFormat::canUnderstand (InputStream& in)
  202827. {
  202828. const int bytesNeeded = 4;
  202829. char header [bytesNeeded];
  202830. return in.read (header, bytesNeeded) == bytesNeeded
  202831. && header[1] == 'P'
  202832. && header[2] == 'N'
  202833. && header[3] == 'G';
  202834. }
  202835. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202836. const Image juce_loadWithCoreImage (InputStream& input);
  202837. #endif
  202838. const Image PNGImageFormat::decodeImage (InputStream& in)
  202839. {
  202840. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  202841. return juce_loadWithCoreImage (in);
  202842. #else
  202843. using namespace pnglibNamespace;
  202844. Image image;
  202845. png_structp pngReadStruct;
  202846. png_infop pngInfoStruct;
  202847. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202848. if (pngReadStruct != 0)
  202849. {
  202850. pngInfoStruct = png_create_info_struct (pngReadStruct);
  202851. if (pngInfoStruct == 0)
  202852. {
  202853. png_destroy_read_struct (&pngReadStruct, 0, 0);
  202854. return Image::null;
  202855. }
  202856. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  202857. // read the header..
  202858. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  202859. png_uint_32 width, height;
  202860. int bitDepth, colorType, interlaceType;
  202861. png_read_info (pngReadStruct, pngInfoStruct);
  202862. png_get_IHDR (pngReadStruct, pngInfoStruct,
  202863. &width, &height,
  202864. &bitDepth, &colorType,
  202865. &interlaceType, 0, 0);
  202866. if (bitDepth == 16)
  202867. png_set_strip_16 (pngReadStruct);
  202868. if (colorType == PNG_COLOR_TYPE_PALETTE)
  202869. png_set_expand (pngReadStruct);
  202870. if (bitDepth < 8)
  202871. png_set_expand (pngReadStruct);
  202872. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  202873. png_set_expand (pngReadStruct);
  202874. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  202875. png_set_gray_to_rgb (pngReadStruct);
  202876. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  202877. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  202878. || pngInfoStruct->num_trans > 0;
  202879. // Load the image into a temp buffer in the pnglib format..
  202880. HeapBlock <uint8> tempBuffer (height * (width << 2));
  202881. {
  202882. HeapBlock <png_bytep> rows (height);
  202883. for (int y = (int) height; --y >= 0;)
  202884. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  202885. png_read_image (pngReadStruct, rows);
  202886. png_read_end (pngReadStruct, pngInfoStruct);
  202887. }
  202888. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  202889. // now convert the data to a juce image format..
  202890. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  202891. (int) width, (int) height, hasAlphaChan);
  202892. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  202893. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  202894. const Image::BitmapData destData (image, true);
  202895. uint8* srcRow = tempBuffer;
  202896. uint8* destRow = destData.data;
  202897. for (int y = 0; y < (int) height; ++y)
  202898. {
  202899. const uint8* src = srcRow;
  202900. srcRow += (width << 2);
  202901. uint8* dest = destRow;
  202902. destRow += destData.lineStride;
  202903. if (hasAlphaChan)
  202904. {
  202905. for (int i = (int) width; --i >= 0;)
  202906. {
  202907. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  202908. ((PixelARGB*) dest)->premultiply();
  202909. dest += destData.pixelStride;
  202910. src += 4;
  202911. }
  202912. }
  202913. else
  202914. {
  202915. for (int i = (int) width; --i >= 0;)
  202916. {
  202917. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  202918. dest += destData.pixelStride;
  202919. src += 4;
  202920. }
  202921. }
  202922. }
  202923. }
  202924. return image;
  202925. #endif
  202926. }
  202927. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  202928. {
  202929. using namespace pnglibNamespace;
  202930. const int width = image.getWidth();
  202931. const int height = image.getHeight();
  202932. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  202933. if (pngWriteStruct == 0)
  202934. return false;
  202935. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  202936. if (pngInfoStruct == 0)
  202937. {
  202938. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  202939. return false;
  202940. }
  202941. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  202942. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  202943. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  202944. : PNG_COLOR_TYPE_RGB,
  202945. PNG_INTERLACE_NONE,
  202946. PNG_COMPRESSION_TYPE_BASE,
  202947. PNG_FILTER_TYPE_BASE);
  202948. HeapBlock <uint8> rowData (width * 4);
  202949. png_color_8 sig_bit;
  202950. sig_bit.red = 8;
  202951. sig_bit.green = 8;
  202952. sig_bit.blue = 8;
  202953. sig_bit.alpha = 8;
  202954. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  202955. png_write_info (pngWriteStruct, pngInfoStruct);
  202956. png_set_shift (pngWriteStruct, &sig_bit);
  202957. png_set_packing (pngWriteStruct);
  202958. const Image::BitmapData srcData (image, false);
  202959. for (int y = 0; y < height; ++y)
  202960. {
  202961. uint8* dst = rowData;
  202962. const uint8* src = srcData.getLinePointer (y);
  202963. if (image.hasAlphaChannel())
  202964. {
  202965. for (int i = width; --i >= 0;)
  202966. {
  202967. PixelARGB p (*(const PixelARGB*) src);
  202968. p.unpremultiply();
  202969. *dst++ = p.getRed();
  202970. *dst++ = p.getGreen();
  202971. *dst++ = p.getBlue();
  202972. *dst++ = p.getAlpha();
  202973. src += srcData.pixelStride;
  202974. }
  202975. }
  202976. else
  202977. {
  202978. for (int i = width; --i >= 0;)
  202979. {
  202980. *dst++ = ((const PixelRGB*) src)->getRed();
  202981. *dst++ = ((const PixelRGB*) src)->getGreen();
  202982. *dst++ = ((const PixelRGB*) src)->getBlue();
  202983. src += srcData.pixelStride;
  202984. }
  202985. }
  202986. png_bytep rowPtr = rowData;
  202987. png_write_rows (pngWriteStruct, &rowPtr, 1);
  202988. }
  202989. png_write_end (pngWriteStruct, pngInfoStruct);
  202990. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  202991. out.flush();
  202992. return true;
  202993. }
  202994. END_JUCE_NAMESPACE
  202995. /*** End of inlined file: juce_PNGLoader.cpp ***/
  202996. #endif
  202997. //==============================================================================
  202998. #if JUCE_BUILD_NATIVE
  202999. // Non-public headers that are needed by more than one platform must be included
  203000. // before the platform-specific sections..
  203001. BEGIN_JUCE_NAMESPACE
  203002. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203003. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203004. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203005. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203006. /**
  203007. Helper class that takes chunks of incoming midi bytes, packages them into
  203008. messages, and dispatches them to a midi callback.
  203009. */
  203010. class MidiDataConcatenator
  203011. {
  203012. public:
  203013. MidiDataConcatenator (const int initialBufferSize)
  203014. : pendingData (initialBufferSize),
  203015. pendingBytes (0), pendingDataTime (0)
  203016. {
  203017. }
  203018. void reset()
  203019. {
  203020. pendingBytes = 0;
  203021. pendingDataTime = 0;
  203022. }
  203023. void pushMidiData (const void* data, int numBytes, double time,
  203024. MidiInput* input, MidiInputCallback& callback)
  203025. {
  203026. const uint8* d = static_cast <const uint8*> (data);
  203027. while (numBytes > 0)
  203028. {
  203029. if (pendingBytes > 0 || d[0] == 0xf0)
  203030. {
  203031. processSysex (d, numBytes, time, input, callback);
  203032. }
  203033. else
  203034. {
  203035. int used = 0;
  203036. const MidiMessage m (d, numBytes, used, 0, time);
  203037. if (used <= 0)
  203038. break; // malformed message..
  203039. callback.handleIncomingMidiMessage (input, m);
  203040. numBytes -= used;
  203041. d += used;
  203042. }
  203043. }
  203044. }
  203045. private:
  203046. void processSysex (const uint8*& d, int& numBytes, double time,
  203047. MidiInput* input, MidiInputCallback& callback)
  203048. {
  203049. if (*d == 0xf0)
  203050. {
  203051. pendingBytes = 0;
  203052. pendingDataTime = time;
  203053. }
  203054. pendingData.ensureSize (pendingBytes + numBytes, false);
  203055. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203056. uint8* dest = totalMessage + pendingBytes;
  203057. do
  203058. {
  203059. if (pendingBytes > 0 && *d >= 0x80)
  203060. {
  203061. if (*d >= 0xfa || *d == 0xf8)
  203062. {
  203063. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203064. ++d;
  203065. --numBytes;
  203066. }
  203067. else
  203068. {
  203069. if (*d == 0xf7)
  203070. {
  203071. *dest++ = *d++;
  203072. pendingBytes++;
  203073. --numBytes;
  203074. }
  203075. break;
  203076. }
  203077. }
  203078. else
  203079. {
  203080. *dest++ = *d++;
  203081. pendingBytes++;
  203082. --numBytes;
  203083. }
  203084. }
  203085. while (numBytes > 0);
  203086. if (pendingBytes > 0)
  203087. {
  203088. if (totalMessage [pendingBytes - 1] == 0xf7)
  203089. {
  203090. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203091. pendingBytes = 0;
  203092. }
  203093. else
  203094. {
  203095. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203096. }
  203097. }
  203098. }
  203099. MemoryBlock pendingData;
  203100. int pendingBytes;
  203101. double pendingDataTime;
  203102. JUCE_DECLARE_NON_COPYABLE (MidiDataConcatenator);
  203103. };
  203104. #endif
  203105. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203106. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203107. END_JUCE_NAMESPACE
  203108. #if JUCE_WINDOWS
  203109. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203110. /*
  203111. This file wraps together all the win32-specific code, so that
  203112. we can include all the native headers just once, and compile all our
  203113. platform-specific stuff in one big lump, keeping it out of the way of
  203114. the rest of the codebase.
  203115. */
  203116. #if JUCE_WINDOWS
  203117. #undef JUCE_BUILD_NATIVE
  203118. #define JUCE_BUILD_NATIVE 1
  203119. BEGIN_JUCE_NAMESPACE
  203120. #define JUCE_INCLUDED_FILE 1
  203121. // Now include the actual code files..
  203122. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203123. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203124. // compiled on its own).
  203125. #if JUCE_INCLUDED_FILE
  203126. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203127. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203128. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203129. #ifndef DOXYGEN
  203130. // use with DynamicLibraryLoader to simplify importing functions
  203131. //
  203132. // functionName: function to import
  203133. // localFunctionName: name you want to use to actually call it (must be different)
  203134. // returnType: the return type
  203135. // object: the DynamicLibraryLoader to use
  203136. // params: list of params (bracketed)
  203137. //
  203138. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203139. typedef returnType (WINAPI *type##localFunctionName) params; \
  203140. type##localFunctionName localFunctionName \
  203141. = (type##localFunctionName)object.findProcAddress (#functionName);
  203142. // loads and unloads a DLL automatically
  203143. class JUCE_API DynamicLibraryLoader
  203144. {
  203145. public:
  203146. DynamicLibraryLoader (const String& name = String::empty);
  203147. ~DynamicLibraryLoader();
  203148. bool load (const String& libraryName);
  203149. void* findProcAddress (const String& functionName);
  203150. private:
  203151. void* libHandle;
  203152. };
  203153. #endif
  203154. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203155. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203156. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203157. : libHandle (0)
  203158. {
  203159. load (name);
  203160. }
  203161. DynamicLibraryLoader::~DynamicLibraryLoader()
  203162. {
  203163. load (String::empty);
  203164. }
  203165. bool DynamicLibraryLoader::load (const String& name)
  203166. {
  203167. FreeLibrary ((HMODULE) libHandle);
  203168. libHandle = name.isNotEmpty() ? LoadLibrary (name.toUTF16()) : 0;
  203169. return libHandle != 0;
  203170. }
  203171. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203172. {
  203173. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toUTF8()); // (void* cast is required for mingw)
  203174. }
  203175. #endif
  203176. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203177. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203178. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203179. // compiled on its own).
  203180. #if JUCE_INCLUDED_FILE
  203181. void Logger::outputDebugString (const String& text)
  203182. {
  203183. OutputDebugString ((text + "\n").toUTF16());
  203184. }
  203185. static int64 hiResTicksPerSecond;
  203186. static double hiResTicksScaleFactor;
  203187. #if JUCE_USE_INTRINSICS
  203188. // CPU info functions using intrinsics...
  203189. #pragma intrinsic (__cpuid)
  203190. #pragma intrinsic (__rdtsc)
  203191. const String SystemStats::getCpuVendor()
  203192. {
  203193. int info [4];
  203194. __cpuid (info, 0);
  203195. char v [12];
  203196. memcpy (v, info + 1, 4);
  203197. memcpy (v + 4, info + 3, 4);
  203198. memcpy (v + 8, info + 2, 4);
  203199. return String (v, 12);
  203200. }
  203201. #else
  203202. // CPU info functions using old fashioned inline asm...
  203203. static void juce_getCpuVendor (char* const v)
  203204. {
  203205. int vendor[4];
  203206. zeromem (vendor, 16);
  203207. #ifdef JUCE_64BIT
  203208. #else
  203209. #ifndef __MINGW32__
  203210. __try
  203211. #endif
  203212. {
  203213. #if JUCE_GCC
  203214. unsigned int dummy = 0;
  203215. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203216. #else
  203217. __asm
  203218. {
  203219. mov eax, 0
  203220. cpuid
  203221. mov [vendor], ebx
  203222. mov [vendor + 4], edx
  203223. mov [vendor + 8], ecx
  203224. }
  203225. #endif
  203226. }
  203227. #ifndef __MINGW32__
  203228. __except (EXCEPTION_EXECUTE_HANDLER)
  203229. {
  203230. *v = 0;
  203231. }
  203232. #endif
  203233. #endif
  203234. memcpy (v, vendor, 16);
  203235. }
  203236. const String SystemStats::getCpuVendor()
  203237. {
  203238. char v [16];
  203239. juce_getCpuVendor (v);
  203240. return String (v, 16);
  203241. }
  203242. #endif
  203243. void SystemStats::initialiseStats()
  203244. {
  203245. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203246. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203247. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203248. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203249. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203250. #else
  203251. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203252. #endif
  203253. {
  203254. SYSTEM_INFO systemInfo;
  203255. GetSystemInfo (&systemInfo);
  203256. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203257. }
  203258. LARGE_INTEGER f;
  203259. QueryPerformanceFrequency (&f);
  203260. hiResTicksPerSecond = f.QuadPart;
  203261. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203262. String s (SystemStats::getJUCEVersion());
  203263. const MMRESULT res = timeBeginPeriod (1);
  203264. (void) res;
  203265. jassert (res == TIMERR_NOERROR);
  203266. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203267. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203268. #endif
  203269. }
  203270. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203271. {
  203272. OSVERSIONINFO info;
  203273. info.dwOSVersionInfoSize = sizeof (info);
  203274. GetVersionEx (&info);
  203275. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203276. {
  203277. switch (info.dwMajorVersion)
  203278. {
  203279. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203280. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203281. default: jassertfalse; break; // !! not a supported OS!
  203282. }
  203283. }
  203284. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203285. {
  203286. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203287. return Win98;
  203288. }
  203289. return UnknownOS;
  203290. }
  203291. const String SystemStats::getOperatingSystemName()
  203292. {
  203293. const char* name = "Unknown OS";
  203294. switch (getOperatingSystemType())
  203295. {
  203296. case Windows7: name = "Windows 7"; break;
  203297. case WinVista: name = "Windows Vista"; break;
  203298. case WinXP: name = "Windows XP"; break;
  203299. case Win2000: name = "Windows 2000"; break;
  203300. case Win98: name = "Windows 98"; break;
  203301. default: jassertfalse; break; // !! new type of OS?
  203302. }
  203303. return name;
  203304. }
  203305. bool SystemStats::isOperatingSystem64Bit()
  203306. {
  203307. #ifdef _WIN64
  203308. return true;
  203309. #else
  203310. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203311. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203312. BOOL isWow64 = FALSE;
  203313. return (fnIsWow64Process != 0)
  203314. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203315. && (isWow64 != FALSE);
  203316. #endif
  203317. }
  203318. int SystemStats::getMemorySizeInMegabytes()
  203319. {
  203320. MEMORYSTATUSEX mem;
  203321. mem.dwLength = sizeof (mem);
  203322. GlobalMemoryStatusEx (&mem);
  203323. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203324. }
  203325. uint32 juce_millisecondsSinceStartup() throw()
  203326. {
  203327. return (uint32) timeGetTime();
  203328. }
  203329. int64 Time::getHighResolutionTicks() throw()
  203330. {
  203331. LARGE_INTEGER ticks;
  203332. QueryPerformanceCounter (&ticks);
  203333. const int64 mainCounterAsHiResTicks = (juce_millisecondsSinceStartup() * hiResTicksPerSecond) / 1000;
  203334. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203335. // fix for a very obscure PCI hardware bug that can make the counter
  203336. // sometimes jump forwards by a few seconds..
  203337. static int64 hiResTicksOffset = 0;
  203338. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203339. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203340. hiResTicksOffset = newOffset;
  203341. return ticks.QuadPart + hiResTicksOffset;
  203342. }
  203343. double Time::getMillisecondCounterHiRes() throw()
  203344. {
  203345. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203346. }
  203347. int64 Time::getHighResolutionTicksPerSecond() throw()
  203348. {
  203349. return hiResTicksPerSecond;
  203350. }
  203351. static int64 juce_getClockCycleCounter() throw()
  203352. {
  203353. #if JUCE_USE_INTRINSICS
  203354. // MS intrinsics version...
  203355. return __rdtsc();
  203356. #elif JUCE_GCC
  203357. // GNU inline asm version...
  203358. unsigned int hi = 0, lo = 0;
  203359. __asm__ __volatile__ (
  203360. "xor %%eax, %%eax \n\
  203361. xor %%edx, %%edx \n\
  203362. rdtsc \n\
  203363. movl %%eax, %[lo] \n\
  203364. movl %%edx, %[hi]"
  203365. :
  203366. : [hi] "m" (hi),
  203367. [lo] "m" (lo)
  203368. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203369. return (int64) ((((uint64) hi) << 32) | lo);
  203370. #else
  203371. // MSVC inline asm version...
  203372. unsigned int hi = 0, lo = 0;
  203373. __asm
  203374. {
  203375. xor eax, eax
  203376. xor edx, edx
  203377. rdtsc
  203378. mov lo, eax
  203379. mov hi, edx
  203380. }
  203381. return (int64) ((((uint64) hi) << 32) | lo);
  203382. #endif
  203383. }
  203384. int SystemStats::getCpuSpeedInMegaherz()
  203385. {
  203386. const int64 cycles = juce_getClockCycleCounter();
  203387. const uint32 millis = Time::getMillisecondCounter();
  203388. int lastResult = 0;
  203389. for (;;)
  203390. {
  203391. int n = 1000000;
  203392. while (--n > 0) {}
  203393. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203394. const int64 cyclesNow = juce_getClockCycleCounter();
  203395. if (millisElapsed > 80)
  203396. {
  203397. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203398. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203399. return newResult;
  203400. lastResult = newResult;
  203401. }
  203402. }
  203403. }
  203404. bool Time::setSystemTimeToThisTime() const
  203405. {
  203406. SYSTEMTIME st;
  203407. st.wDayOfWeek = 0;
  203408. st.wYear = (WORD) getYear();
  203409. st.wMonth = (WORD) (getMonth() + 1);
  203410. st.wDay = (WORD) getDayOfMonth();
  203411. st.wHour = (WORD) getHours();
  203412. st.wMinute = (WORD) getMinutes();
  203413. st.wSecond = (WORD) getSeconds();
  203414. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203415. // do this twice because of daylight saving conversion problems - the
  203416. // first one sets it up, the second one kicks it in.
  203417. return SetLocalTime (&st) != 0
  203418. && SetLocalTime (&st) != 0;
  203419. }
  203420. int SystemStats::getPageSize()
  203421. {
  203422. SYSTEM_INFO systemInfo;
  203423. GetSystemInfo (&systemInfo);
  203424. return systemInfo.dwPageSize;
  203425. }
  203426. const String SystemStats::getLogonName()
  203427. {
  203428. TCHAR text [256];
  203429. DWORD len = numElementsInArray (text) - 2;
  203430. zerostruct (text);
  203431. GetUserName (text, &len);
  203432. return String (text, len);
  203433. }
  203434. const String SystemStats::getFullUserName()
  203435. {
  203436. return getLogonName();
  203437. }
  203438. #endif
  203439. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203440. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203441. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203442. // compiled on its own).
  203443. #if JUCE_INCLUDED_FILE
  203444. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203445. extern HWND juce_messageWindowHandle;
  203446. #endif
  203447. #if ! JUCE_USE_INTRINSICS
  203448. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203449. // older ones we have to actually call the ops as win32 functions..
  203450. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203451. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203452. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203453. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203454. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203455. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203456. {
  203457. jassertfalse; // This operation isn't available in old MS compiler versions!
  203458. __int64 oldValue = *value;
  203459. if (oldValue == valueToCompare)
  203460. *value = newValue;
  203461. return oldValue;
  203462. }
  203463. #endif
  203464. CriticalSection::CriticalSection() throw()
  203465. {
  203466. // (just to check the MS haven't changed this structure and broken things...)
  203467. #if JUCE_VC7_OR_EARLIER
  203468. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203469. #else
  203470. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203471. #endif
  203472. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203473. }
  203474. CriticalSection::~CriticalSection() throw()
  203475. {
  203476. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203477. }
  203478. void CriticalSection::enter() const throw()
  203479. {
  203480. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203481. }
  203482. bool CriticalSection::tryEnter() const throw()
  203483. {
  203484. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203485. }
  203486. void CriticalSection::exit() const throw()
  203487. {
  203488. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203489. }
  203490. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203491. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203492. {
  203493. }
  203494. WaitableEvent::~WaitableEvent() throw()
  203495. {
  203496. CloseHandle (internal);
  203497. }
  203498. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203499. {
  203500. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203501. }
  203502. void WaitableEvent::signal() const throw()
  203503. {
  203504. SetEvent (internal);
  203505. }
  203506. void WaitableEvent::reset() const throw()
  203507. {
  203508. ResetEvent (internal);
  203509. }
  203510. void JUCE_API juce_threadEntryPoint (void*);
  203511. static unsigned int __stdcall threadEntryProc (void* userData)
  203512. {
  203513. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203514. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203515. GetCurrentThreadId(), TRUE);
  203516. #endif
  203517. juce_threadEntryPoint (userData);
  203518. _endthreadex (0);
  203519. return 0;
  203520. }
  203521. void Thread::launchThread()
  203522. {
  203523. unsigned int newThreadId;
  203524. threadHandle_ = (void*) _beginthreadex (0, 0, &threadEntryProc, this, 0, &newThreadId);
  203525. threadId_ = (ThreadID) newThreadId;
  203526. }
  203527. void Thread::closeThreadHandle()
  203528. {
  203529. CloseHandle ((HANDLE) threadHandle_);
  203530. threadId_ = 0;
  203531. threadHandle_ = 0;
  203532. }
  203533. void Thread::killThread()
  203534. {
  203535. if (threadHandle_ != 0)
  203536. {
  203537. #if JUCE_DEBUG
  203538. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203539. #endif
  203540. TerminateThread (threadHandle_, 0);
  203541. }
  203542. }
  203543. void Thread::setCurrentThreadName (const String& name)
  203544. {
  203545. #if JUCE_DEBUG && JUCE_MSVC
  203546. struct
  203547. {
  203548. DWORD dwType;
  203549. LPCSTR szName;
  203550. DWORD dwThreadID;
  203551. DWORD dwFlags;
  203552. } info;
  203553. info.dwType = 0x1000;
  203554. info.szName = name.toCString();
  203555. info.dwThreadID = GetCurrentThreadId();
  203556. info.dwFlags = 0;
  203557. __try
  203558. {
  203559. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203560. }
  203561. __except (EXCEPTION_CONTINUE_EXECUTION)
  203562. {}
  203563. #else
  203564. (void) name;
  203565. #endif
  203566. }
  203567. Thread::ThreadID Thread::getCurrentThreadId()
  203568. {
  203569. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203570. }
  203571. bool Thread::setThreadPriority (void* handle, int priority)
  203572. {
  203573. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203574. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203575. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203576. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203577. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203578. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203579. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203580. if (handle == 0)
  203581. handle = GetCurrentThread();
  203582. return SetThreadPriority (handle, pri) != FALSE;
  203583. }
  203584. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203585. {
  203586. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203587. }
  203588. struct SleepEvent
  203589. {
  203590. SleepEvent()
  203591. : handle (CreateEvent (0, 0, 0,
  203592. #if JUCE_DEBUG
  203593. _T("Juce Sleep Event")))
  203594. #else
  203595. 0))
  203596. #endif
  203597. {
  203598. }
  203599. HANDLE handle;
  203600. };
  203601. static SleepEvent sleepEvent;
  203602. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203603. {
  203604. if (millisecs >= 10)
  203605. {
  203606. Sleep (millisecs);
  203607. }
  203608. else
  203609. {
  203610. // unlike Sleep() this is guaranteed to return to the current thread after
  203611. // the time expires, so we'll use this for short waits, which are more likely
  203612. // to need to be accurate
  203613. WaitForSingleObject (sleepEvent.handle, millisecs);
  203614. }
  203615. }
  203616. void Thread::yield()
  203617. {
  203618. Sleep (0);
  203619. }
  203620. static int lastProcessPriority = -1;
  203621. // called by WindowDriver because Windows does wierd things to process priority
  203622. // when you swap apps, and this forces an update when the app is brought to the front.
  203623. void juce_repeatLastProcessPriority()
  203624. {
  203625. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203626. {
  203627. DWORD p;
  203628. switch (lastProcessPriority)
  203629. {
  203630. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203631. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203632. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203633. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203634. default: jassertfalse; return; // bad priority value
  203635. }
  203636. SetPriorityClass (GetCurrentProcess(), p);
  203637. }
  203638. }
  203639. void Process::setPriority (ProcessPriority prior)
  203640. {
  203641. if (lastProcessPriority != (int) prior)
  203642. {
  203643. lastProcessPriority = (int) prior;
  203644. juce_repeatLastProcessPriority();
  203645. }
  203646. }
  203647. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  203648. {
  203649. return IsDebuggerPresent() != FALSE;
  203650. }
  203651. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203652. {
  203653. return juce_isRunningUnderDebugger();
  203654. }
  203655. void Process::raisePrivilege()
  203656. {
  203657. jassertfalse; // xxx not implemented
  203658. }
  203659. void Process::lowerPrivilege()
  203660. {
  203661. jassertfalse; // xxx not implemented
  203662. }
  203663. void Process::terminate()
  203664. {
  203665. #if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203666. _CrtDumpMemoryLeaks();
  203667. #endif
  203668. // bullet in the head in case there's a problem shutting down..
  203669. ExitProcess (0);
  203670. }
  203671. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203672. {
  203673. void* result = 0;
  203674. JUCE_TRY
  203675. {
  203676. result = LoadLibrary (name.toUTF16());
  203677. }
  203678. JUCE_CATCH_ALL
  203679. return result;
  203680. }
  203681. void PlatformUtilities::freeDynamicLibrary (void* h)
  203682. {
  203683. JUCE_TRY
  203684. {
  203685. if (h != 0)
  203686. FreeLibrary ((HMODULE) h);
  203687. }
  203688. JUCE_CATCH_ALL
  203689. }
  203690. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  203691. {
  203692. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  203693. }
  203694. class InterProcessLock::Pimpl
  203695. {
  203696. public:
  203697. Pimpl (const String& name, const int timeOutMillisecs)
  203698. : handle (0), refCount (1)
  203699. {
  203700. handle = CreateMutex (0, TRUE, ("Global\\" + name.replaceCharacter ('\\','/')).toUTF16());
  203701. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  203702. {
  203703. if (timeOutMillisecs == 0)
  203704. {
  203705. close();
  203706. return;
  203707. }
  203708. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  203709. {
  203710. case WAIT_OBJECT_0:
  203711. case WAIT_ABANDONED:
  203712. break;
  203713. case WAIT_TIMEOUT:
  203714. default:
  203715. close();
  203716. break;
  203717. }
  203718. }
  203719. }
  203720. ~Pimpl()
  203721. {
  203722. close();
  203723. }
  203724. void close()
  203725. {
  203726. if (handle != 0)
  203727. {
  203728. ReleaseMutex (handle);
  203729. CloseHandle (handle);
  203730. handle = 0;
  203731. }
  203732. }
  203733. HANDLE handle;
  203734. int refCount;
  203735. };
  203736. InterProcessLock::InterProcessLock (const String& name_)
  203737. : name (name_)
  203738. {
  203739. }
  203740. InterProcessLock::~InterProcessLock()
  203741. {
  203742. }
  203743. bool InterProcessLock::enter (const int timeOutMillisecs)
  203744. {
  203745. const ScopedLock sl (lock);
  203746. if (pimpl == 0)
  203747. {
  203748. pimpl = new Pimpl (name, timeOutMillisecs);
  203749. if (pimpl->handle == 0)
  203750. pimpl = 0;
  203751. }
  203752. else
  203753. {
  203754. pimpl->refCount++;
  203755. }
  203756. return pimpl != 0;
  203757. }
  203758. void InterProcessLock::exit()
  203759. {
  203760. const ScopedLock sl (lock);
  203761. // Trying to release the lock too many times!
  203762. jassert (pimpl != 0);
  203763. if (pimpl != 0 && --(pimpl->refCount) == 0)
  203764. pimpl = 0;
  203765. }
  203766. #endif
  203767. /*** End of inlined file: juce_win32_Threads.cpp ***/
  203768. /*** Start of inlined file: juce_win32_Files.cpp ***/
  203769. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203770. // compiled on its own).
  203771. #if JUCE_INCLUDED_FILE
  203772. #ifndef CSIDL_MYMUSIC
  203773. #define CSIDL_MYMUSIC 0x000d
  203774. #endif
  203775. #ifndef CSIDL_MYVIDEO
  203776. #define CSIDL_MYVIDEO 0x000e
  203777. #endif
  203778. #ifndef INVALID_FILE_ATTRIBUTES
  203779. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  203780. #endif
  203781. namespace WindowsFileHelpers
  203782. {
  203783. int64 fileTimeToTime (const FILETIME* const ft)
  203784. {
  203785. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  203786. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  203787. }
  203788. void timeToFileTime (const int64 time, FILETIME* const ft)
  203789. {
  203790. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  203791. }
  203792. const String getDriveFromPath (String path)
  203793. {
  203794. WCHAR* p = const_cast <WCHAR*> (path.toUTF16().getAddress());
  203795. if (PathStripToRoot (p))
  203796. return String ((const WCHAR*) p);
  203797. return path;
  203798. }
  203799. int64 getDiskSpaceInfo (const String& path, const bool total)
  203800. {
  203801. ULARGE_INTEGER spc, tot, totFree;
  203802. if (GetDiskFreeSpaceEx (getDriveFromPath (path).toUTF16(), &spc, &tot, &totFree))
  203803. return total ? (int64) tot.QuadPart
  203804. : (int64) spc.QuadPart;
  203805. return 0;
  203806. }
  203807. unsigned int getWindowsDriveType (const String& path)
  203808. {
  203809. return GetDriveType (getDriveFromPath (path).toUTF16());
  203810. }
  203811. const File getSpecialFolderPath (int type)
  203812. {
  203813. WCHAR path [MAX_PATH + 256];
  203814. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  203815. return File (String (path));
  203816. return File::nonexistent;
  203817. }
  203818. }
  203819. const juce_wchar File::separator = '\\';
  203820. const String File::separatorString ("\\");
  203821. bool File::exists() const
  203822. {
  203823. return fullPath.isNotEmpty()
  203824. && GetFileAttributes (fullPath.toUTF16()) != INVALID_FILE_ATTRIBUTES;
  203825. }
  203826. bool File::existsAsFile() const
  203827. {
  203828. return fullPath.isNotEmpty()
  203829. && (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  203830. }
  203831. bool File::isDirectory() const
  203832. {
  203833. const DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203834. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  203835. }
  203836. bool File::hasWriteAccess() const
  203837. {
  203838. if (exists())
  203839. return (GetFileAttributes (fullPath.toUTF16()) & FILE_ATTRIBUTE_READONLY) == 0;
  203840. // on windows, it seems that even read-only directories can still be written into,
  203841. // so checking the parent directory's permissions would return the wrong result..
  203842. return true;
  203843. }
  203844. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  203845. {
  203846. DWORD attr = GetFileAttributes (fullPath.toUTF16());
  203847. if (attr == INVALID_FILE_ATTRIBUTES)
  203848. return false;
  203849. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  203850. return true;
  203851. if (shouldBeReadOnly)
  203852. attr |= FILE_ATTRIBUTE_READONLY;
  203853. else
  203854. attr &= ~FILE_ATTRIBUTE_READONLY;
  203855. return SetFileAttributes (fullPath.toUTF16(), attr) != FALSE;
  203856. }
  203857. bool File::isHidden() const
  203858. {
  203859. return (GetFileAttributes (getFullPathName().toUTF16()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  203860. }
  203861. bool File::deleteFile() const
  203862. {
  203863. if (! exists())
  203864. return true;
  203865. else if (isDirectory())
  203866. return RemoveDirectory (fullPath.toUTF16()) != 0;
  203867. else
  203868. return DeleteFile (fullPath.toUTF16()) != 0;
  203869. }
  203870. bool File::moveToTrash() const
  203871. {
  203872. if (! exists())
  203873. return true;
  203874. SHFILEOPSTRUCT fos;
  203875. zerostruct (fos);
  203876. // The string we pass in must be double null terminated..
  203877. String doubleNullTermPath (getFullPathName() + " ");
  203878. WCHAR* const p = const_cast <WCHAR*> (doubleNullTermPath.toUTF16().getAddress());
  203879. p [getFullPathName().length()] = 0;
  203880. fos.wFunc = FO_DELETE;
  203881. fos.pFrom = p;
  203882. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  203883. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  203884. return SHFileOperation (&fos) == 0;
  203885. }
  203886. bool File::copyInternal (const File& dest) const
  203887. {
  203888. return CopyFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16(), false) != 0;
  203889. }
  203890. bool File::moveInternal (const File& dest) const
  203891. {
  203892. return MoveFile (fullPath.toUTF16(), dest.getFullPathName().toUTF16()) != 0;
  203893. }
  203894. void File::createDirectoryInternal (const String& fileName) const
  203895. {
  203896. CreateDirectory (fileName.toUTF16(), 0);
  203897. }
  203898. int64 juce_fileSetPosition (void* handle, int64 pos)
  203899. {
  203900. LARGE_INTEGER li;
  203901. li.QuadPart = pos;
  203902. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  203903. return li.QuadPart;
  203904. }
  203905. void FileInputStream::openHandle()
  203906. {
  203907. totalSize = file.getSize();
  203908. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  203909. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  203910. if (h != INVALID_HANDLE_VALUE)
  203911. fileHandle = (void*) h;
  203912. }
  203913. void FileInputStream::closeHandle()
  203914. {
  203915. CloseHandle ((HANDLE) fileHandle);
  203916. }
  203917. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  203918. {
  203919. if (fileHandle != 0)
  203920. {
  203921. DWORD actualNum = 0;
  203922. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203923. return (size_t) actualNum;
  203924. }
  203925. return 0;
  203926. }
  203927. void FileOutputStream::openHandle()
  203928. {
  203929. HANDLE h = CreateFile (file.getFullPathName().toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203930. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203931. if (h != INVALID_HANDLE_VALUE)
  203932. {
  203933. LARGE_INTEGER li;
  203934. li.QuadPart = 0;
  203935. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  203936. if (li.LowPart != INVALID_SET_FILE_POINTER)
  203937. {
  203938. fileHandle = (void*) h;
  203939. currentPosition = li.QuadPart;
  203940. }
  203941. }
  203942. }
  203943. void FileOutputStream::closeHandle()
  203944. {
  203945. CloseHandle ((HANDLE) fileHandle);
  203946. }
  203947. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  203948. {
  203949. if (fileHandle != 0)
  203950. {
  203951. DWORD actualNum = 0;
  203952. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  203953. return (int) actualNum;
  203954. }
  203955. return 0;
  203956. }
  203957. void FileOutputStream::flushInternal()
  203958. {
  203959. if (fileHandle != 0)
  203960. FlushFileBuffers ((HANDLE) fileHandle);
  203961. }
  203962. int64 File::getSize() const
  203963. {
  203964. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203965. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203966. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  203967. return 0;
  203968. }
  203969. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  203970. {
  203971. using namespace WindowsFileHelpers;
  203972. WIN32_FILE_ATTRIBUTE_DATA attributes;
  203973. if (GetFileAttributesEx (fullPath.toUTF16(), GetFileExInfoStandard, &attributes))
  203974. {
  203975. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  203976. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  203977. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  203978. }
  203979. else
  203980. {
  203981. creationTime = accessTime = modificationTime = 0;
  203982. }
  203983. }
  203984. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  203985. {
  203986. using namespace WindowsFileHelpers;
  203987. bool ok = false;
  203988. HANDLE h = CreateFile (fullPath.toUTF16(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  203989. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  203990. if (h != INVALID_HANDLE_VALUE)
  203991. {
  203992. FILETIME m, a, c;
  203993. timeToFileTime (modificationTime, &m);
  203994. timeToFileTime (accessTime, &a);
  203995. timeToFileTime (creationTime, &c);
  203996. ok = SetFileTime (h,
  203997. creationTime > 0 ? &c : 0,
  203998. accessTime > 0 ? &a : 0,
  203999. modificationTime > 0 ? &m : 0) != 0;
  204000. CloseHandle (h);
  204001. }
  204002. return ok;
  204003. }
  204004. void File::findFileSystemRoots (Array<File>& destArray)
  204005. {
  204006. TCHAR buffer [2048];
  204007. buffer[0] = 0;
  204008. buffer[1] = 0;
  204009. GetLogicalDriveStrings (2048, buffer);
  204010. const TCHAR* n = buffer;
  204011. StringArray roots;
  204012. while (*n != 0)
  204013. {
  204014. roots.add (String (n));
  204015. while (*n++ != 0)
  204016. {}
  204017. }
  204018. roots.sort (true);
  204019. for (int i = 0; i < roots.size(); ++i)
  204020. destArray.add (roots [i]);
  204021. }
  204022. const String File::getVolumeLabel() const
  204023. {
  204024. TCHAR dest[64];
  204025. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204026. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204027. dest[0] = 0;
  204028. return dest;
  204029. }
  204030. int File::getVolumeSerialNumber() const
  204031. {
  204032. TCHAR dest[64];
  204033. DWORD serialNum;
  204034. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()).toUTF16(), dest,
  204035. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204036. return 0;
  204037. return (int) serialNum;
  204038. }
  204039. int64 File::getBytesFreeOnVolume() const
  204040. {
  204041. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204042. }
  204043. int64 File::getVolumeTotalSize() const
  204044. {
  204045. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204046. }
  204047. bool File::isOnCDRomDrive() const
  204048. {
  204049. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204050. }
  204051. bool File::isOnHardDisk() const
  204052. {
  204053. if (fullPath.isEmpty())
  204054. return false;
  204055. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204056. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204057. return n != DRIVE_REMOVABLE;
  204058. else
  204059. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204060. }
  204061. bool File::isOnRemovableDrive() const
  204062. {
  204063. if (fullPath.isEmpty())
  204064. return false;
  204065. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204066. return n == DRIVE_CDROM
  204067. || n == DRIVE_REMOTE
  204068. || n == DRIVE_REMOVABLE
  204069. || n == DRIVE_RAMDISK;
  204070. }
  204071. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204072. {
  204073. int csidlType = 0;
  204074. switch (type)
  204075. {
  204076. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204077. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204078. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204079. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204080. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204081. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204082. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204083. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204084. case tempDirectory:
  204085. {
  204086. WCHAR dest [2048];
  204087. dest[0] = 0;
  204088. GetTempPath (numElementsInArray (dest), dest);
  204089. return File (String (dest));
  204090. }
  204091. case invokedExecutableFile:
  204092. case currentExecutableFile:
  204093. case currentApplicationFile:
  204094. {
  204095. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204096. WCHAR dest [MAX_PATH + 256];
  204097. dest[0] = 0;
  204098. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204099. return File (String (dest));
  204100. }
  204101. case hostApplicationPath:
  204102. {
  204103. WCHAR dest [MAX_PATH + 256];
  204104. dest[0] = 0;
  204105. GetModuleFileName (0, dest, numElementsInArray (dest));
  204106. return File (String (dest));
  204107. }
  204108. default:
  204109. jassertfalse; // unknown type?
  204110. return File::nonexistent;
  204111. }
  204112. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204113. }
  204114. const File File::getCurrentWorkingDirectory()
  204115. {
  204116. WCHAR dest [MAX_PATH + 256];
  204117. dest[0] = 0;
  204118. GetCurrentDirectory (numElementsInArray (dest), dest);
  204119. return File (String (dest));
  204120. }
  204121. bool File::setAsCurrentWorkingDirectory() const
  204122. {
  204123. return SetCurrentDirectory (getFullPathName().toUTF16()) != FALSE;
  204124. }
  204125. const String File::getVersion() const
  204126. {
  204127. String result;
  204128. DWORD handle = 0;
  204129. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName().toUTF16(), &handle);
  204130. HeapBlock<char> buffer;
  204131. buffer.calloc (bufferSize);
  204132. if (GetFileVersionInfo (getFullPathName().toUTF16(), 0, bufferSize, buffer))
  204133. {
  204134. VS_FIXEDFILEINFO* vffi;
  204135. UINT len = 0;
  204136. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204137. {
  204138. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204139. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204140. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204141. << (int) LOWORD (vffi->dwFileVersionLS);
  204142. }
  204143. }
  204144. return result;
  204145. }
  204146. const File File::getLinkedTarget() const
  204147. {
  204148. File result (*this);
  204149. String p (getFullPathName());
  204150. if (! exists())
  204151. p += ".lnk";
  204152. else if (getFileExtension() != ".lnk")
  204153. return result;
  204154. ComSmartPtr <IShellLink> shellLink;
  204155. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204156. {
  204157. ComSmartPtr <IPersistFile> persistFile;
  204158. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204159. {
  204160. if (SUCCEEDED (persistFile->Load (p.toUTF16(), STGM_READ))
  204161. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204162. {
  204163. WIN32_FIND_DATA winFindData;
  204164. WCHAR resolvedPath [MAX_PATH];
  204165. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204166. result = File (resolvedPath);
  204167. }
  204168. }
  204169. }
  204170. return result;
  204171. }
  204172. class DirectoryIterator::NativeIterator::Pimpl
  204173. {
  204174. public:
  204175. Pimpl (const File& directory, const String& wildCard)
  204176. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204177. handle (INVALID_HANDLE_VALUE)
  204178. {
  204179. }
  204180. ~Pimpl()
  204181. {
  204182. if (handle != INVALID_HANDLE_VALUE)
  204183. FindClose (handle);
  204184. }
  204185. bool next (String& filenameFound,
  204186. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204187. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204188. {
  204189. using namespace WindowsFileHelpers;
  204190. WIN32_FIND_DATA findData;
  204191. if (handle == INVALID_HANDLE_VALUE)
  204192. {
  204193. handle = FindFirstFile (directoryWithWildCard.toUTF16(), &findData);
  204194. if (handle == INVALID_HANDLE_VALUE)
  204195. return false;
  204196. }
  204197. else
  204198. {
  204199. if (FindNextFile (handle, &findData) == 0)
  204200. return false;
  204201. }
  204202. filenameFound = findData.cFileName;
  204203. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204204. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204205. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204206. if (modTime != 0) *modTime = Time (fileTimeToTime (&findData.ftLastWriteTime));
  204207. if (creationTime != 0) *creationTime = Time (fileTimeToTime (&findData.ftCreationTime));
  204208. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204209. return true;
  204210. }
  204211. private:
  204212. const String directoryWithWildCard;
  204213. HANDLE handle;
  204214. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl);
  204215. };
  204216. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204217. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204218. {
  204219. }
  204220. DirectoryIterator::NativeIterator::~NativeIterator()
  204221. {
  204222. }
  204223. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204224. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204225. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204226. {
  204227. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204228. }
  204229. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204230. {
  204231. HINSTANCE hInstance = 0;
  204232. JUCE_TRY
  204233. {
  204234. hInstance = ShellExecute (0, 0, fileName.toUTF16(), parameters.toUTF16(), 0, SW_SHOWDEFAULT);
  204235. }
  204236. JUCE_CATCH_ALL
  204237. return hInstance > (HINSTANCE) 32;
  204238. }
  204239. void File::revealToUser() const
  204240. {
  204241. if (isDirectory())
  204242. startAsProcess();
  204243. else if (getParentDirectory().exists())
  204244. getParentDirectory().startAsProcess();
  204245. }
  204246. class NamedPipeInternal
  204247. {
  204248. public:
  204249. NamedPipeInternal (const String& file, const bool isPipe_)
  204250. : pipeH (0),
  204251. cancelEvent (0),
  204252. connected (false),
  204253. isPipe (isPipe_)
  204254. {
  204255. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204256. pipeH = isPipe ? CreateNamedPipe (file.toUTF16(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204257. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204258. : CreateFile (file.toUTF16(), GENERIC_READ | GENERIC_WRITE, 0, 0,
  204259. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204260. }
  204261. ~NamedPipeInternal()
  204262. {
  204263. disconnectPipe();
  204264. if (pipeH != 0)
  204265. CloseHandle (pipeH);
  204266. CloseHandle (cancelEvent);
  204267. }
  204268. bool connect (const int timeOutMs)
  204269. {
  204270. if (! isPipe)
  204271. return true;
  204272. if (! connected)
  204273. {
  204274. OVERLAPPED over;
  204275. zerostruct (over);
  204276. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204277. if (ConnectNamedPipe (pipeH, &over))
  204278. {
  204279. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204280. }
  204281. else
  204282. {
  204283. const int err = GetLastError();
  204284. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204285. {
  204286. HANDLE handles[] = { over.hEvent, cancelEvent };
  204287. if (WaitForMultipleObjects (2, handles, FALSE,
  204288. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204289. connected = true;
  204290. }
  204291. else if (err == ERROR_PIPE_CONNECTED)
  204292. {
  204293. connected = true;
  204294. }
  204295. }
  204296. CloseHandle (over.hEvent);
  204297. }
  204298. return connected;
  204299. }
  204300. void disconnectPipe()
  204301. {
  204302. if (connected)
  204303. {
  204304. DisconnectNamedPipe (pipeH);
  204305. connected = false;
  204306. }
  204307. }
  204308. HANDLE pipeH;
  204309. HANDLE cancelEvent;
  204310. bool connected, isPipe;
  204311. };
  204312. void NamedPipe::close()
  204313. {
  204314. cancelPendingReads();
  204315. const ScopedLock sl (lock);
  204316. delete static_cast<NamedPipeInternal*> (internal);
  204317. internal = 0;
  204318. }
  204319. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204320. {
  204321. close();
  204322. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204323. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204324. {
  204325. internal = intern.release();
  204326. return true;
  204327. }
  204328. return false;
  204329. }
  204330. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204331. {
  204332. const ScopedLock sl (lock);
  204333. int bytesRead = -1;
  204334. bool waitAgain = true;
  204335. while (waitAgain && internal != 0)
  204336. {
  204337. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204338. waitAgain = false;
  204339. if (! intern->connect (timeOutMilliseconds))
  204340. break;
  204341. if (maxBytesToRead <= 0)
  204342. return 0;
  204343. OVERLAPPED over;
  204344. zerostruct (over);
  204345. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204346. unsigned long numRead;
  204347. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204348. {
  204349. bytesRead = (int) numRead;
  204350. }
  204351. else if (GetLastError() == ERROR_IO_PENDING)
  204352. {
  204353. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204354. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204355. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204356. : INFINITE);
  204357. if (waitResult != WAIT_OBJECT_0)
  204358. {
  204359. // if the operation timed out, let's cancel it...
  204360. CancelIo (intern->pipeH);
  204361. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204362. }
  204363. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204364. {
  204365. bytesRead = (int) numRead;
  204366. }
  204367. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204368. {
  204369. intern->disconnectPipe();
  204370. waitAgain = true;
  204371. }
  204372. }
  204373. else
  204374. {
  204375. waitAgain = internal != 0;
  204376. Sleep (5);
  204377. }
  204378. CloseHandle (over.hEvent);
  204379. }
  204380. return bytesRead;
  204381. }
  204382. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204383. {
  204384. int bytesWritten = -1;
  204385. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204386. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204387. {
  204388. if (numBytesToWrite <= 0)
  204389. return 0;
  204390. OVERLAPPED over;
  204391. zerostruct (over);
  204392. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204393. unsigned long numWritten;
  204394. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204395. {
  204396. bytesWritten = (int) numWritten;
  204397. }
  204398. else if (GetLastError() == ERROR_IO_PENDING)
  204399. {
  204400. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204401. DWORD waitResult;
  204402. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204403. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204404. : INFINITE);
  204405. if (waitResult != WAIT_OBJECT_0)
  204406. {
  204407. CancelIo (intern->pipeH);
  204408. WaitForSingleObject (over.hEvent, INFINITE);
  204409. }
  204410. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204411. {
  204412. bytesWritten = (int) numWritten;
  204413. }
  204414. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204415. {
  204416. intern->disconnectPipe();
  204417. }
  204418. }
  204419. CloseHandle (over.hEvent);
  204420. }
  204421. return bytesWritten;
  204422. }
  204423. void NamedPipe::cancelPendingReads()
  204424. {
  204425. if (internal != 0)
  204426. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204427. }
  204428. #endif
  204429. /*** End of inlined file: juce_win32_Files.cpp ***/
  204430. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204431. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204432. // compiled on its own).
  204433. #if JUCE_INCLUDED_FILE
  204434. #ifndef INTERNET_FLAG_NEED_FILE
  204435. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204436. #endif
  204437. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204438. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204439. #endif
  204440. #ifndef WORKAROUND_TIMEOUT_BUG
  204441. //#define WORKAROUND_TIMEOUT_BUG 1
  204442. #endif
  204443. #if WORKAROUND_TIMEOUT_BUG
  204444. // Required because of a Microsoft bug in setting a timeout
  204445. class InternetConnectThread : public Thread
  204446. {
  204447. public:
  204448. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET sessionHandle_, HINTERNET& connection_, const bool isFtp_)
  204449. : Thread ("Internet"), uc (uc_), sessionHandle (sessionHandle_), connection (connection_), isFtp (isFtp_)
  204450. {
  204451. startThread();
  204452. }
  204453. ~InternetConnectThread()
  204454. {
  204455. stopThread (60000);
  204456. }
  204457. void run()
  204458. {
  204459. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204460. uc.nPort, _T(""), _T(""),
  204461. isFtp ? INTERNET_SERVICE_FTP
  204462. : INTERNET_SERVICE_HTTP,
  204463. 0, 0);
  204464. notify();
  204465. }
  204466. private:
  204467. URL_COMPONENTS& uc;
  204468. HINTERNET sessionHandle;
  204469. HINTERNET& connection;
  204470. const bool isFtp;
  204471. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (InternetConnectThread);
  204472. };
  204473. #endif
  204474. class WebInputStream : public InputStream
  204475. {
  204476. public:
  204477. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  204478. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204479. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  204480. : connection (0), request (0),
  204481. address (address_), headers (headers_), postData (postData_), position (0),
  204482. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  204483. {
  204484. createConnection (progressCallback, progressCallbackContext);
  204485. if (responseHeaders != 0 && ! isError())
  204486. {
  204487. DWORD bufferSizeBytes = 4096;
  204488. for (;;)
  204489. {
  204490. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204491. if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204492. {
  204493. StringArray headersArray;
  204494. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204495. for (int i = 0; i < headersArray.size(); ++i)
  204496. {
  204497. const String& header = headersArray[i];
  204498. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204499. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204500. const String previousValue ((*responseHeaders) [key]);
  204501. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204502. }
  204503. break;
  204504. }
  204505. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204506. break;
  204507. }
  204508. }
  204509. }
  204510. ~WebInputStream()
  204511. {
  204512. close();
  204513. }
  204514. bool isError() const { return request == 0; }
  204515. bool isExhausted() { return finished; }
  204516. int64 getPosition() { return position; }
  204517. int64 getTotalLength()
  204518. {
  204519. if (! isError())
  204520. {
  204521. DWORD index = 0, result = 0, size = sizeof (result);
  204522. if (HttpQueryInfo (request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204523. return (int64) result;
  204524. }
  204525. return -1;
  204526. }
  204527. int read (void* buffer, int bytesToRead)
  204528. {
  204529. DWORD bytesRead = 0;
  204530. if (! (finished || isError()))
  204531. {
  204532. InternetReadFile (request, buffer, bytesToRead, &bytesRead);
  204533. position += bytesRead;
  204534. if (bytesRead == 0)
  204535. finished = true;
  204536. }
  204537. return (int) bytesRead;
  204538. }
  204539. bool setPosition (int64 wantedPos)
  204540. {
  204541. if (isError())
  204542. return false;
  204543. if (wantedPos != position)
  204544. {
  204545. finished = false;
  204546. position = (int64) InternetSetFilePointer (request, (LONG) wantedPos, 0, FILE_BEGIN, 0);
  204547. if (position == wantedPos)
  204548. return true;
  204549. if (wantedPos < position)
  204550. {
  204551. close();
  204552. position = 0;
  204553. createConnection (0, 0);
  204554. }
  204555. skipNextBytes (wantedPos - position);
  204556. }
  204557. return true;
  204558. }
  204559. private:
  204560. HINTERNET connection, request;
  204561. String address, headers;
  204562. MemoryBlock postData;
  204563. int64 position;
  204564. bool finished;
  204565. const bool isPost;
  204566. int timeOutMs;
  204567. void close()
  204568. {
  204569. if (request != 0)
  204570. {
  204571. InternetCloseHandle (request);
  204572. request = 0;
  204573. }
  204574. if (connection != 0)
  204575. {
  204576. InternetCloseHandle (connection);
  204577. connection = 0;
  204578. }
  204579. }
  204580. void createConnection (URL::OpenStreamProgressCallback* progressCallback,
  204581. void* progressCallbackContext)
  204582. {
  204583. static HINTERNET sessionHandle = InternetOpen (_T("juce"), INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, 0);
  204584. close();
  204585. if (sessionHandle != 0)
  204586. {
  204587. // break up the url..
  204588. TCHAR file[1024], server[1024];
  204589. URL_COMPONENTS uc;
  204590. zerostruct (uc);
  204591. uc.dwStructSize = sizeof (uc);
  204592. uc.dwUrlPathLength = sizeof (file);
  204593. uc.dwHostNameLength = sizeof (server);
  204594. uc.lpszUrlPath = file;
  204595. uc.lpszHostName = server;
  204596. if (InternetCrackUrl (address.toUTF16(), 0, 0, &uc))
  204597. {
  204598. int disable = 1;
  204599. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204600. if (timeOutMs == 0)
  204601. timeOutMs = 30000;
  204602. else if (timeOutMs < 0)
  204603. timeOutMs = -1;
  204604. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204605. const bool isFtp = address.startsWithIgnoreCase ("ftp:");
  204606. #if WORKAROUND_TIMEOUT_BUG
  204607. connection = 0;
  204608. {
  204609. InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
  204610. connectThread.wait (timeOutMs);
  204611. if (connection == 0)
  204612. {
  204613. InternetCloseHandle (sessionHandle);
  204614. sessionHandle = 0;
  204615. }
  204616. }
  204617. #else
  204618. connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
  204619. _T(""), _T(""),
  204620. isFtp ? INTERNET_SERVICE_FTP
  204621. : INTERNET_SERVICE_HTTP,
  204622. 0, 0);
  204623. #endif
  204624. if (connection != 0)
  204625. {
  204626. if (isFtp)
  204627. {
  204628. request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
  204629. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
  204630. }
  204631. else
  204632. {
  204633. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204634. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204635. if (address.startsWithIgnoreCase ("https:"))
  204636. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204637. // IE7 seems to automatically work out when it's https)
  204638. request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
  204639. uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);
  204640. if (request != 0)
  204641. {
  204642. INTERNET_BUFFERS buffers;
  204643. zerostruct (buffers);
  204644. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204645. buffers.lpcszHeader = headers.toUTF16();
  204646. buffers.dwHeadersLength = headers.length();
  204647. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204648. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204649. {
  204650. int bytesSent = 0;
  204651. for (;;)
  204652. {
  204653. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204654. DWORD bytesDone = 0;
  204655. if (bytesToDo > 0
  204656. && ! InternetWriteFile (request,
  204657. static_cast <const char*> (postData.getData()) + bytesSent,
  204658. bytesToDo, &bytesDone))
  204659. {
  204660. break;
  204661. }
  204662. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204663. {
  204664. if (HttpEndRequest (request, 0, 0, 0))
  204665. return;
  204666. break;
  204667. }
  204668. bytesSent += bytesDone;
  204669. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, bytesSent, postData.getSize()))
  204670. break;
  204671. }
  204672. }
  204673. }
  204674. close();
  204675. }
  204676. }
  204677. }
  204678. }
  204679. }
  204680. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  204681. };
  204682. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  204683. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  204684. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  204685. {
  204686. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  204687. progressCallback, progressCallbackContext,
  204688. headers, timeOutMs, responseHeaders));
  204689. return wi->isError() ? 0 : wi.release();
  204690. }
  204691. namespace MACAddressHelpers
  204692. {
  204693. void getViaGetAdaptersInfo (Array<MACAddress>& result)
  204694. {
  204695. DynamicLibraryLoader dll ("iphlpapi.dll");
  204696. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204697. if (getAdaptersInfo != 0)
  204698. {
  204699. ULONG len = sizeof (IP_ADAPTER_INFO);
  204700. MemoryBlock mb;
  204701. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204702. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204703. {
  204704. mb.setSize (len);
  204705. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204706. }
  204707. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204708. {
  204709. for (PIP_ADAPTER_INFO adapter = adapterInfo; adapter != 0; adapter = adapter->Next)
  204710. {
  204711. if (adapter->AddressLength >= 6)
  204712. result.addIfNotAlreadyThere (MACAddress (adapter->Address));
  204713. }
  204714. }
  204715. }
  204716. }
  204717. void getViaNetBios (Array<MACAddress>& result)
  204718. {
  204719. DynamicLibraryLoader dll ("netapi32.dll");
  204720. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  204721. if (NetbiosCall != 0)
  204722. {
  204723. NCB ncb;
  204724. zerostruct (ncb);
  204725. struct ASTAT
  204726. {
  204727. ADAPTER_STATUS adapt;
  204728. NAME_BUFFER NameBuff [30];
  204729. };
  204730. ASTAT astat;
  204731. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  204732. LANA_ENUM enums;
  204733. zerostruct (enums);
  204734. ncb.ncb_command = NCBENUM;
  204735. ncb.ncb_buffer = (unsigned char*) &enums;
  204736. ncb.ncb_length = sizeof (LANA_ENUM);
  204737. NetbiosCall (&ncb);
  204738. for (int i = 0; i < enums.length; ++i)
  204739. {
  204740. zerostruct (ncb);
  204741. ncb.ncb_command = NCBRESET;
  204742. ncb.ncb_lana_num = enums.lana[i];
  204743. if (NetbiosCall (&ncb) == 0)
  204744. {
  204745. zerostruct (ncb);
  204746. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  204747. ncb.ncb_command = NCBASTAT;
  204748. ncb.ncb_lana_num = enums.lana[i];
  204749. ncb.ncb_buffer = (unsigned char*) &astat;
  204750. ncb.ncb_length = sizeof (ASTAT);
  204751. if (NetbiosCall (&ncb) == 0 && astat.adapt.adapter_type == 0xfe)
  204752. result.addIfNotAlreadyThere (MACAddress (astat.adapt.adapter_address));
  204753. }
  204754. }
  204755. }
  204756. }
  204757. }
  204758. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  204759. {
  204760. MACAddressHelpers::getViaGetAdaptersInfo (result);
  204761. MACAddressHelpers::getViaNetBios (result);
  204762. }
  204763. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  204764. const String& emailSubject,
  204765. const String& bodyText,
  204766. const StringArray& filesToAttach)
  204767. {
  204768. HMODULE h = LoadLibraryA ("MAPI32.dll");
  204769. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  204770. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  204771. bool ok = false;
  204772. if (mapiSendMail != 0)
  204773. {
  204774. MapiMessage message;
  204775. zerostruct (message);
  204776. message.lpszSubject = (LPSTR) emailSubject.toCString();
  204777. message.lpszNoteText = (LPSTR) bodyText.toCString();
  204778. MapiRecipDesc recip;
  204779. zerostruct (recip);
  204780. recip.ulRecipClass = MAPI_TO;
  204781. String targetEmailAddress_ (targetEmailAddress);
  204782. if (targetEmailAddress_.isEmpty())
  204783. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  204784. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  204785. message.nRecipCount = 1;
  204786. message.lpRecips = &recip;
  204787. HeapBlock <MapiFileDesc> files;
  204788. files.calloc (filesToAttach.size());
  204789. message.nFileCount = filesToAttach.size();
  204790. message.lpFiles = files;
  204791. for (int i = 0; i < filesToAttach.size(); ++i)
  204792. {
  204793. files[i].nPosition = (ULONG) -1;
  204794. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  204795. }
  204796. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  204797. }
  204798. FreeLibrary (h);
  204799. return ok;
  204800. }
  204801. #endif
  204802. /*** End of inlined file: juce_win32_Network.cpp ***/
  204803. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  204804. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204805. // compiled on its own).
  204806. #if JUCE_INCLUDED_FILE
  204807. namespace
  204808. {
  204809. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  204810. {
  204811. HKEY rootKey = 0;
  204812. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  204813. rootKey = HKEY_CURRENT_USER;
  204814. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  204815. rootKey = HKEY_LOCAL_MACHINE;
  204816. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  204817. rootKey = HKEY_CLASSES_ROOT;
  204818. if (rootKey != 0)
  204819. {
  204820. name = name.substring (name.indexOfChar ('\\') + 1);
  204821. const int lastSlash = name.lastIndexOfChar ('\\');
  204822. valueName = name.substring (lastSlash + 1);
  204823. name = name.substring (0, lastSlash);
  204824. HKEY key;
  204825. DWORD result;
  204826. if (createForWriting)
  204827. {
  204828. if (RegCreateKeyEx (rootKey, name.toUTF16(), 0, 0, REG_OPTION_NON_VOLATILE,
  204829. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  204830. return key;
  204831. }
  204832. else
  204833. {
  204834. if (RegOpenKeyEx (rootKey, name.toUTF16(), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204835. return key;
  204836. }
  204837. }
  204838. return 0;
  204839. }
  204840. }
  204841. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  204842. const String& defaultValue)
  204843. {
  204844. String valueName, result (defaultValue);
  204845. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204846. if (k != 0)
  204847. {
  204848. WCHAR buffer [2048];
  204849. unsigned long bufferSize = sizeof (buffer);
  204850. DWORD type = REG_SZ;
  204851. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  204852. {
  204853. if (type == REG_SZ)
  204854. result = buffer;
  204855. else if (type == REG_DWORD)
  204856. result = String ((int) *(DWORD*) buffer);
  204857. }
  204858. RegCloseKey (k);
  204859. }
  204860. return result;
  204861. }
  204862. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  204863. const String& value)
  204864. {
  204865. String valueName;
  204866. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204867. if (k != 0)
  204868. {
  204869. RegSetValueEx (k, valueName.toUTF16(), 0, REG_SZ,
  204870. (const BYTE*) value.toUTF16().getAddress(),
  204871. CharPointer_UTF16::getBytesRequiredFor (value.getCharPointer()));
  204872. RegCloseKey (k);
  204873. }
  204874. }
  204875. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  204876. {
  204877. bool exists = false;
  204878. String valueName;
  204879. HKEY k = findKeyForPath (regValuePath, false, valueName);
  204880. if (k != 0)
  204881. {
  204882. unsigned char buffer [2048];
  204883. unsigned long bufferSize = sizeof (buffer);
  204884. DWORD type = 0;
  204885. if (RegQueryValueEx (k, valueName.toUTF16(), 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  204886. exists = true;
  204887. RegCloseKey (k);
  204888. }
  204889. return exists;
  204890. }
  204891. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  204892. {
  204893. String valueName;
  204894. HKEY k = findKeyForPath (regValuePath, true, valueName);
  204895. if (k != 0)
  204896. {
  204897. RegDeleteValue (k, valueName.toUTF16());
  204898. RegCloseKey (k);
  204899. }
  204900. }
  204901. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  204902. {
  204903. String valueName;
  204904. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  204905. if (k != 0)
  204906. {
  204907. RegDeleteKey (k, valueName.toUTF16());
  204908. RegCloseKey (k);
  204909. }
  204910. }
  204911. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  204912. const String& symbolicDescription,
  204913. const String& fullDescription,
  204914. const File& targetExecutable,
  204915. int iconResourceNumber)
  204916. {
  204917. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  204918. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  204919. if (iconResourceNumber != 0)
  204920. setRegistryValue (key + "\\DefaultIcon\\",
  204921. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  204922. setRegistryValue (key + "\\", fullDescription);
  204923. setRegistryValue (key + "\\shell\\open\\command\\",
  204924. targetExecutable.getFullPathName() + " %1");
  204925. }
  204926. bool juce_IsRunningInWine()
  204927. {
  204928. HKEY key;
  204929. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  204930. {
  204931. RegCloseKey (key);
  204932. return true;
  204933. }
  204934. return false;
  204935. }
  204936. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  204937. {
  204938. String s (::GetCommandLineW());
  204939. StringArray tokens;
  204940. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  204941. return tokens.joinIntoString (" ", 1);
  204942. }
  204943. static void* currentModuleHandle = 0;
  204944. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  204945. {
  204946. if (currentModuleHandle == 0)
  204947. currentModuleHandle = GetModuleHandle (0);
  204948. return currentModuleHandle;
  204949. }
  204950. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  204951. {
  204952. currentModuleHandle = newHandle;
  204953. }
  204954. void PlatformUtilities::fpuReset()
  204955. {
  204956. #if JUCE_MSVC
  204957. _clearfp();
  204958. #endif
  204959. }
  204960. void PlatformUtilities::beep()
  204961. {
  204962. MessageBeep (MB_OK);
  204963. }
  204964. #endif
  204965. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  204966. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204967. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  204968. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204969. // compiled on its own).
  204970. #if JUCE_INCLUDED_FILE
  204971. static const unsigned int specialId = WM_APP + 0x4400;
  204972. static const unsigned int broadcastId = WM_APP + 0x4403;
  204973. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  204974. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  204975. HWND juce_messageWindowHandle = 0;
  204976. extern long improbableWindowNumber; // defined in windowing.cpp
  204977. #ifndef WM_APPCOMMAND
  204978. #define WM_APPCOMMAND 0x0319
  204979. #endif
  204980. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  204981. const UINT message,
  204982. const WPARAM wParam,
  204983. const LPARAM lParam) throw()
  204984. {
  204985. JUCE_TRY
  204986. {
  204987. if (h == juce_messageWindowHandle)
  204988. {
  204989. if (message == specialCallbackId)
  204990. {
  204991. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  204992. return (LRESULT) (*func) ((void*) lParam);
  204993. }
  204994. else if (message == specialId)
  204995. {
  204996. // these are trapped early in the dispatch call, but must also be checked
  204997. // here in case there are windows modal dialog boxes doing their own
  204998. // dispatch loop and not calling our version
  204999. Message* const message = reinterpret_cast <Message*> (lParam);
  205000. MessageManager::getInstance()->deliverMessage (message);
  205001. message->decReferenceCount();
  205002. return 0;
  205003. }
  205004. else if (message == broadcastId)
  205005. {
  205006. const ScopedPointer <String> messageString ((String*) lParam);
  205007. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205008. return 0;
  205009. }
  205010. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205011. {
  205012. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205013. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205014. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205015. return 0;
  205016. }
  205017. }
  205018. }
  205019. JUCE_CATCH_EXCEPTION
  205020. return DefWindowProc (h, message, wParam, lParam);
  205021. }
  205022. static bool isEventBlockedByModalComps (MSG& m)
  205023. {
  205024. if (Component::getNumCurrentlyModalComponents() == 0
  205025. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205026. return false;
  205027. switch (m.message)
  205028. {
  205029. case WM_MOUSEMOVE:
  205030. case WM_NCMOUSEMOVE:
  205031. case 0x020A: /* WM_MOUSEWHEEL */
  205032. case 0x020E: /* WM_MOUSEHWHEEL */
  205033. case WM_KEYUP:
  205034. case WM_SYSKEYUP:
  205035. case WM_CHAR:
  205036. case WM_APPCOMMAND:
  205037. case WM_LBUTTONUP:
  205038. case WM_MBUTTONUP:
  205039. case WM_RBUTTONUP:
  205040. case WM_MOUSEACTIVATE:
  205041. case WM_NCMOUSEHOVER:
  205042. case WM_MOUSEHOVER:
  205043. return true;
  205044. case WM_NCLBUTTONDOWN:
  205045. case WM_NCLBUTTONDBLCLK:
  205046. case WM_NCRBUTTONDOWN:
  205047. case WM_NCRBUTTONDBLCLK:
  205048. case WM_NCMBUTTONDOWN:
  205049. case WM_NCMBUTTONDBLCLK:
  205050. case WM_LBUTTONDOWN:
  205051. case WM_LBUTTONDBLCLK:
  205052. case WM_MBUTTONDOWN:
  205053. case WM_MBUTTONDBLCLK:
  205054. case WM_RBUTTONDOWN:
  205055. case WM_RBUTTONDBLCLK:
  205056. case WM_KEYDOWN:
  205057. case WM_SYSKEYDOWN:
  205058. {
  205059. Component* const modal = Component::getCurrentlyModalComponent (0);
  205060. if (modal != 0)
  205061. modal->inputAttemptWhenModal();
  205062. return true;
  205063. }
  205064. default:
  205065. break;
  205066. }
  205067. return false;
  205068. }
  205069. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205070. {
  205071. MSG m;
  205072. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205073. return false;
  205074. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205075. {
  205076. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205077. {
  205078. Message* const message = reinterpret_cast <Message*> (m.lParam);
  205079. MessageManager::getInstance()->deliverMessage (message);
  205080. message->decReferenceCount();
  205081. }
  205082. else if (m.message == WM_QUIT)
  205083. {
  205084. if (JUCEApplication::getInstance() != 0)
  205085. JUCEApplication::getInstance()->systemRequestedQuit();
  205086. }
  205087. else if (! isEventBlockedByModalComps (m))
  205088. {
  205089. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205090. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205091. {
  205092. // if it's someone else's window being clicked on, and the focus is
  205093. // currently on a juce window, pass the kb focus over..
  205094. HWND currentFocus = GetFocus();
  205095. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205096. SetFocus (m.hwnd);
  205097. }
  205098. TranslateMessage (&m);
  205099. DispatchMessage (&m);
  205100. }
  205101. }
  205102. return true;
  205103. }
  205104. bool juce_postMessageToSystemQueue (Message* message)
  205105. {
  205106. message->incReferenceCount();
  205107. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205108. }
  205109. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205110. void* userData)
  205111. {
  205112. if (MessageManager::getInstance()->isThisTheMessageThread())
  205113. {
  205114. return (*callback) (userData);
  205115. }
  205116. else
  205117. {
  205118. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205119. // deadlock because the message manager is blocked from running, and can't
  205120. // call your function..
  205121. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205122. return (void*) SendMessage (juce_messageWindowHandle,
  205123. specialCallbackId,
  205124. (WPARAM) callback,
  205125. (LPARAM) userData);
  205126. }
  205127. }
  205128. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205129. {
  205130. if (hwnd != juce_messageWindowHandle)
  205131. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205132. return TRUE;
  205133. }
  205134. void MessageManager::broadcastMessage (const String& value)
  205135. {
  205136. Array<void*> windows;
  205137. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205138. const String localCopy (value);
  205139. COPYDATASTRUCT data;
  205140. data.dwData = broadcastId;
  205141. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205142. data.lpData = (void*) localCopy.toUTF16().getAddress();
  205143. for (int i = windows.size(); --i >= 0;)
  205144. {
  205145. HWND hwnd = (HWND) windows.getUnchecked(i);
  205146. TCHAR windowName [64]; // no need to read longer strings than this
  205147. GetWindowText (hwnd, windowName, 64);
  205148. windowName [63] = 0;
  205149. if (String (windowName) == messageWindowName)
  205150. {
  205151. DWORD_PTR result;
  205152. SendMessageTimeout (hwnd, WM_COPYDATA,
  205153. (WPARAM) juce_messageWindowHandle,
  205154. (LPARAM) &data,
  205155. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205156. 8000,
  205157. &result);
  205158. }
  205159. }
  205160. }
  205161. static const String getMessageWindowClassName()
  205162. {
  205163. // this name has to be different for each app/dll instance because otherwise
  205164. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205165. // window class).
  205166. static int number = 0;
  205167. if (number == 0)
  205168. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205169. return "JUCEcs_" + String (number);
  205170. }
  205171. void MessageManager::doPlatformSpecificInitialisation()
  205172. {
  205173. OleInitialize (0);
  205174. const String className (getMessageWindowClassName());
  205175. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205176. WNDCLASSEX wc;
  205177. zerostruct (wc);
  205178. wc.cbSize = sizeof (wc);
  205179. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205180. wc.cbWndExtra = 4;
  205181. wc.hInstance = hmod;
  205182. wc.lpszClassName = className.toUTF16();
  205183. RegisterClassEx (&wc);
  205184. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205185. messageWindowName,
  205186. 0, 0, 0, 0, 0, 0, 0,
  205187. hmod, 0);
  205188. }
  205189. void MessageManager::doPlatformSpecificShutdown()
  205190. {
  205191. DestroyWindow (juce_messageWindowHandle);
  205192. UnregisterClass (getMessageWindowClassName().toUTF16(), 0);
  205193. OleUninitialize();
  205194. }
  205195. #endif
  205196. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205197. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205198. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205199. // compiled on its own).
  205200. #if JUCE_INCLUDED_FILE
  205201. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205202. NEWTEXTMETRICEXW*,
  205203. int type,
  205204. LPARAM lParam)
  205205. {
  205206. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205207. {
  205208. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205209. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205210. }
  205211. return 1;
  205212. }
  205213. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205214. NEWTEXTMETRICEXW*,
  205215. int type,
  205216. LPARAM lParam)
  205217. {
  205218. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205219. {
  205220. LOGFONTW lf;
  205221. zerostruct (lf);
  205222. lf.lfWeight = FW_DONTCARE;
  205223. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205224. lf.lfQuality = DEFAULT_QUALITY;
  205225. lf.lfCharSet = DEFAULT_CHARSET;
  205226. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205227. lf.lfPitchAndFamily = FF_DONTCARE;
  205228. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205229. fontName.copyToUTF16 (lf.lfFaceName, LF_FACESIZE - 1);
  205230. HDC dc = CreateCompatibleDC (0);
  205231. EnumFontFamiliesEx (dc, &lf,
  205232. (FONTENUMPROCW) &wfontEnum2,
  205233. lParam, 0);
  205234. DeleteDC (dc);
  205235. }
  205236. return 1;
  205237. }
  205238. const StringArray Font::findAllTypefaceNames()
  205239. {
  205240. StringArray results;
  205241. HDC dc = CreateCompatibleDC (0);
  205242. {
  205243. LOGFONTW lf;
  205244. zerostruct (lf);
  205245. lf.lfWeight = FW_DONTCARE;
  205246. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205247. lf.lfQuality = DEFAULT_QUALITY;
  205248. lf.lfCharSet = DEFAULT_CHARSET;
  205249. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205250. lf.lfPitchAndFamily = FF_DONTCARE;
  205251. lf.lfFaceName[0] = 0;
  205252. EnumFontFamiliesEx (dc, &lf,
  205253. (FONTENUMPROCW) &wfontEnum1,
  205254. (LPARAM) &results, 0);
  205255. }
  205256. DeleteDC (dc);
  205257. results.sort (true);
  205258. return results;
  205259. }
  205260. extern bool juce_IsRunningInWine();
  205261. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  205262. {
  205263. if (juce_IsRunningInWine())
  205264. {
  205265. // If we're running in Wine, then use fonts that might be available on Linux..
  205266. defaultSans = "Bitstream Vera Sans";
  205267. defaultSerif = "Bitstream Vera Serif";
  205268. defaultFixed = "Bitstream Vera Sans Mono";
  205269. }
  205270. else
  205271. {
  205272. defaultSans = "Verdana";
  205273. defaultSerif = "Times";
  205274. defaultFixed = "Lucida Console";
  205275. defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
  205276. }
  205277. }
  205278. class FontDCHolder : private DeletedAtShutdown
  205279. {
  205280. public:
  205281. FontDCHolder()
  205282. : fontH (0), previousFontH (0), dc (0), numKPs (0), size (0),
  205283. bold (false), italic (false)
  205284. {
  205285. }
  205286. ~FontDCHolder()
  205287. {
  205288. deleteDCAndFont();
  205289. clearSingletonInstance();
  205290. }
  205291. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205292. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205293. {
  205294. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205295. {
  205296. fontName = fontName_;
  205297. bold = bold_;
  205298. italic = italic_;
  205299. size = size_;
  205300. deleteDCAndFont();
  205301. dc = CreateCompatibleDC (0);
  205302. SetMapperFlags (dc, 0);
  205303. SetMapMode (dc, MM_TEXT);
  205304. LOGFONTW lfw;
  205305. zerostruct (lfw);
  205306. lfw.lfCharSet = DEFAULT_CHARSET;
  205307. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205308. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205309. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205310. lfw.lfQuality = PROOF_QUALITY;
  205311. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205312. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205313. fontName.copyToUTF16 (lfw.lfFaceName, LF_FACESIZE - 1);
  205314. lfw.lfHeight = size > 0 ? size : -256;
  205315. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205316. if (standardSizedFont != 0)
  205317. {
  205318. if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
  205319. {
  205320. fontH = standardSizedFont;
  205321. if (size == 0)
  205322. {
  205323. OUTLINETEXTMETRIC otm;
  205324. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205325. {
  205326. lfw.lfHeight = -(int) otm.otmEMSquare;
  205327. fontH = CreateFontIndirect (&lfw);
  205328. SelectObject (dc, fontH);
  205329. DeleteObject (standardSizedFont);
  205330. }
  205331. }
  205332. }
  205333. }
  205334. }
  205335. return dc;
  205336. }
  205337. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205338. {
  205339. if (kps == 0)
  205340. {
  205341. numKPs = GetKerningPairs (dc, 0, 0);
  205342. kps.calloc (numKPs);
  205343. GetKerningPairs (dc, numKPs, kps);
  205344. }
  205345. numKPs_ = numKPs;
  205346. return kps;
  205347. }
  205348. private:
  205349. HFONT fontH;
  205350. HGDIOBJ previousFontH;
  205351. HDC dc;
  205352. String fontName;
  205353. HeapBlock <KERNINGPAIR> kps;
  205354. int numKPs, size;
  205355. bool bold, italic;
  205356. void deleteDCAndFont()
  205357. {
  205358. if (dc != 0)
  205359. {
  205360. SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
  205361. DeleteDC (dc);
  205362. dc = 0;
  205363. }
  205364. if (fontH != 0)
  205365. {
  205366. DeleteObject (fontH);
  205367. fontH = 0;
  205368. }
  205369. kps.free();
  205370. }
  205371. JUCE_DECLARE_NON_COPYABLE (FontDCHolder);
  205372. };
  205373. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205374. class WindowsTypeface : public CustomTypeface
  205375. {
  205376. public:
  205377. WindowsTypeface (const Font& font)
  205378. {
  205379. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205380. font.isBold(), font.isItalic(), 0);
  205381. TEXTMETRIC tm;
  205382. tm.tmAscent = tm.tmHeight = 1;
  205383. tm.tmDefaultChar = 0;
  205384. GetTextMetrics (dc, &tm);
  205385. setCharacteristics (font.getTypefaceName(),
  205386. tm.tmAscent / (float) tm.tmHeight,
  205387. font.isBold(), font.isItalic(),
  205388. tm.tmDefaultChar);
  205389. }
  205390. bool loadGlyphIfPossible (juce_wchar character)
  205391. {
  205392. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205393. GLYPHMETRICS gm;
  205394. // if this is the fallback font, skip checking for the glyph's existence. This is because
  205395. // with fonts like Tahoma, GetGlyphIndices can say that a glyph doesn't exist, but it still
  205396. // gets correctly created later on.
  205397. if (! isFallbackFont)
  205398. {
  205399. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205400. WORD index = 0;
  205401. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205402. && index == 0xffff)
  205403. {
  205404. return false;
  205405. }
  205406. }
  205407. Path glyphPath;
  205408. TEXTMETRIC tm;
  205409. if (! GetTextMetrics (dc, &tm))
  205410. {
  205411. addGlyph (character, glyphPath, 0);
  205412. return true;
  205413. }
  205414. const float height = (float) tm.tmHeight;
  205415. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205416. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205417. &gm, 0, 0, &identityMatrix);
  205418. if (bufSize > 0)
  205419. {
  205420. HeapBlock<char> data (bufSize);
  205421. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205422. bufSize, data, &identityMatrix);
  205423. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205424. const float scaleX = 1.0f / height;
  205425. const float scaleY = -1.0f / height;
  205426. while ((char*) pheader < data + bufSize)
  205427. {
  205428. float x = scaleX * pheader->pfxStart.x.value;
  205429. float y = scaleY * pheader->pfxStart.y.value;
  205430. glyphPath.startNewSubPath (x, y);
  205431. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205432. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205433. while ((const char*) curve < curveEnd)
  205434. {
  205435. if (curve->wType == TT_PRIM_LINE)
  205436. {
  205437. for (int i = 0; i < curve->cpfx; ++i)
  205438. {
  205439. x = scaleX * curve->apfx[i].x.value;
  205440. y = scaleY * curve->apfx[i].y.value;
  205441. glyphPath.lineTo (x, y);
  205442. }
  205443. }
  205444. else if (curve->wType == TT_PRIM_QSPLINE)
  205445. {
  205446. for (int i = 0; i < curve->cpfx - 1; ++i)
  205447. {
  205448. const float x2 = scaleX * curve->apfx[i].x.value;
  205449. const float y2 = scaleY * curve->apfx[i].y.value;
  205450. float x3, y3;
  205451. if (i < curve->cpfx - 2)
  205452. {
  205453. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205454. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205455. }
  205456. else
  205457. {
  205458. x3 = scaleX * curve->apfx[i + 1].x.value;
  205459. y3 = scaleY * curve->apfx[i + 1].y.value;
  205460. }
  205461. glyphPath.quadraticTo (x2, y2, x3, y3);
  205462. x = x3;
  205463. y = y3;
  205464. }
  205465. }
  205466. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205467. }
  205468. pheader = (const TTPOLYGONHEADER*) curve;
  205469. glyphPath.closeSubPath();
  205470. }
  205471. }
  205472. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205473. int numKPs;
  205474. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205475. for (int i = 0; i < numKPs; ++i)
  205476. {
  205477. if (kps[i].wFirst == character)
  205478. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205479. kps[i].iKernAmount / height);
  205480. }
  205481. return true;
  205482. }
  205483. private:
  205484. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface);
  205485. };
  205486. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205487. {
  205488. return new WindowsTypeface (font);
  205489. }
  205490. #endif
  205491. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205492. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205493. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205494. // compiled on its own).
  205495. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205496. class SharedD2DFactory : public DeletedAtShutdown
  205497. {
  205498. public:
  205499. SharedD2DFactory()
  205500. {
  205501. jassertfalse; //xxx Direct2D support isn't ready for use yet!
  205502. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, d2dFactory.resetAndGetPointerAddress());
  205503. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) directWriteFactory.resetAndGetPointerAddress());
  205504. if (directWriteFactory != 0)
  205505. directWriteFactory->GetSystemFontCollection (systemFonts.resetAndGetPointerAddress());
  205506. }
  205507. ~SharedD2DFactory()
  205508. {
  205509. clearSingletonInstance();
  205510. }
  205511. juce_DeclareSingleton (SharedD2DFactory, false);
  205512. ComSmartPtr <ID2D1Factory> d2dFactory;
  205513. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205514. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205515. };
  205516. juce_ImplementSingleton (SharedD2DFactory)
  205517. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205518. {
  205519. public:
  205520. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205521. : hwnd (hwnd_),
  205522. currentState (0)
  205523. {
  205524. RECT windowRect;
  205525. GetClientRect (hwnd, &windowRect);
  205526. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205527. bounds.setSize (size.width, size.height);
  205528. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205529. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205530. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, renderingTarget.resetAndGetPointerAddress());
  205531. // xxx check for error
  205532. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), colourBrush.resetAndGetPointerAddress());
  205533. }
  205534. ~Direct2DLowLevelGraphicsContext()
  205535. {
  205536. states.clear();
  205537. }
  205538. void resized()
  205539. {
  205540. RECT windowRect;
  205541. GetClientRect (hwnd, &windowRect);
  205542. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205543. renderingTarget->Resize (size);
  205544. bounds.setSize (size.width, size.height);
  205545. }
  205546. void clear()
  205547. {
  205548. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205549. }
  205550. void start()
  205551. {
  205552. renderingTarget->BeginDraw();
  205553. saveState();
  205554. }
  205555. void end()
  205556. {
  205557. states.clear();
  205558. currentState = 0;
  205559. renderingTarget->EndDraw();
  205560. renderingTarget->CheckWindowState();
  205561. }
  205562. bool isVectorDevice() const { return false; }
  205563. void setOrigin (int x, int y)
  205564. {
  205565. currentState->origin.addXY (x, y);
  205566. }
  205567. void addTransform (const AffineTransform& transform)
  205568. {
  205569. //xxx todo
  205570. jassertfalse;
  205571. }
  205572. float getScaleFactor()
  205573. {
  205574. jassertfalse; //xxx
  205575. return 1.0f;
  205576. }
  205577. bool clipToRectangle (const Rectangle<int>& r)
  205578. {
  205579. currentState->clipToRectangle (r);
  205580. return ! isClipEmpty();
  205581. }
  205582. bool clipToRectangleList (const RectangleList& clipRegion)
  205583. {
  205584. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205585. return ! isClipEmpty();
  205586. }
  205587. void excludeClipRectangle (const Rectangle<int>&)
  205588. {
  205589. //xxx
  205590. }
  205591. void clipToPath (const Path& path, const AffineTransform& transform)
  205592. {
  205593. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205594. }
  205595. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205596. {
  205597. currentState->clipToImage (sourceImage,transform);
  205598. }
  205599. bool clipRegionIntersects (const Rectangle<int>& r)
  205600. {
  205601. const Rectangle<int> r2 (r + currentState->origin);
  205602. return currentState->clipRect.intersects (r2);
  205603. }
  205604. const Rectangle<int> getClipBounds() const
  205605. {
  205606. // xxx could this take into account complex clip regions?
  205607. return currentState->clipRect - currentState->origin;
  205608. }
  205609. bool isClipEmpty() const
  205610. {
  205611. return currentState->clipRect.isEmpty();
  205612. }
  205613. void saveState()
  205614. {
  205615. states.add (new SavedState (*this));
  205616. currentState = states.getLast();
  205617. }
  205618. void restoreState()
  205619. {
  205620. jassert (states.size() > 1) //you should never pop the last state!
  205621. states.removeLast (1);
  205622. currentState = states.getLast();
  205623. }
  205624. void beginTransparencyLayer (float opacity)
  205625. {
  205626. jassertfalse; //xxx todo
  205627. }
  205628. void endTransparencyLayer()
  205629. {
  205630. jassertfalse; //xxx todo
  205631. }
  205632. void setFill (const FillType& fillType)
  205633. {
  205634. currentState->setFill (fillType);
  205635. }
  205636. void setOpacity (float newOpacity)
  205637. {
  205638. currentState->setOpacity (newOpacity);
  205639. }
  205640. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205641. {
  205642. }
  205643. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205644. {
  205645. currentState->createBrush();
  205646. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205647. }
  205648. void fillPath (const Path& p, const AffineTransform& transform)
  205649. {
  205650. currentState->createBrush();
  205651. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205652. if (renderingTarget != 0)
  205653. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205654. }
  205655. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205656. {
  205657. const int x = currentState->origin.getX();
  205658. const int y = currentState->origin.getY();
  205659. renderingTarget->SetTransform (transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205660. D2D1_SIZE_U size;
  205661. size.width = image.getWidth();
  205662. size.height = image.getHeight();
  205663. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205664. Image img (image.convertedToFormat (Image::ARGB));
  205665. Image::BitmapData bd (img, false);
  205666. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205667. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205668. {
  205669. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205670. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, tempBitmap.resetAndGetPointerAddress());
  205671. if (tempBitmap != 0)
  205672. renderingTarget->DrawBitmap (tempBitmap);
  205673. }
  205674. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205675. }
  205676. void drawLine (const Line <float>& line)
  205677. {
  205678. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205679. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205680. line.getEnd() + currentState->origin.toFloat());
  205681. currentState->createBrush();
  205682. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205683. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205684. currentState->currentBrush);
  205685. }
  205686. void drawVerticalLine (int x, float top, float bottom)
  205687. {
  205688. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205689. currentState->createBrush();
  205690. x += currentState->origin.getX();
  205691. const int y = currentState->origin.getY();
  205692. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205693. D2D1::Point2F (x, y + bottom),
  205694. currentState->currentBrush);
  205695. }
  205696. void drawHorizontalLine (int y, float left, float right)
  205697. {
  205698. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205699. currentState->createBrush();
  205700. y += currentState->origin.getY();
  205701. const int x = currentState->origin.getX();
  205702. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205703. D2D1::Point2F (x + right, y),
  205704. currentState->currentBrush);
  205705. }
  205706. void setFont (const Font& newFont)
  205707. {
  205708. currentState->setFont (newFont);
  205709. }
  205710. const Font getFont()
  205711. {
  205712. return currentState->font;
  205713. }
  205714. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205715. {
  205716. const float x = currentState->origin.getX();
  205717. const float y = currentState->origin.getY();
  205718. currentState->createBrush();
  205719. currentState->createFont();
  205720. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  205721. float hScale = currentState->font.getHorizontalScale();
  205722. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transformToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205723. float dpiX = 0, dpiY = 0;
  205724. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  205725. UINT32 glyphNum = glyphNumber;
  205726. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  205727. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  205728. DWRITE_GLYPH_OFFSET offset;
  205729. offset.advanceOffset = 0;
  205730. offset.ascenderOffset = 0;
  205731. float glyphAdvances = 0;
  205732. DWRITE_GLYPH_RUN glyph;
  205733. glyph.fontFace = currentState->currentFontFace;
  205734. glyph.glyphCount = 1;
  205735. glyph.glyphIndices = &glyphNum1;
  205736. glyph.isSideways = FALSE;
  205737. glyph.glyphAdvances = &glyphAdvances;
  205738. glyph.glyphOffsets = &offset;
  205739. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  205740. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  205741. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205742. }
  205743. class SavedState
  205744. {
  205745. public:
  205746. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  205747. : owner (owner_), currentBrush (0),
  205748. fontScaling (1.0f), currentFontFace (0),
  205749. clipsRect (false), shouldClipRect (false),
  205750. clipsRectList (false), shouldClipRectList (false),
  205751. clipsComplex (false), shouldClipComplex (false),
  205752. clipsBitmap (false), shouldClipBitmap (false)
  205753. {
  205754. if (owner.currentState != 0)
  205755. {
  205756. // xxx seems like a very slow way to create one of these, and this is a performance
  205757. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  205758. setFill (owner.currentState->fillType);
  205759. currentBrush = owner.currentState->currentBrush;
  205760. origin = owner.currentState->origin;
  205761. clipRect = owner.currentState->clipRect;
  205762. font = owner.currentState->font;
  205763. currentFontFace = owner.currentState->currentFontFace;
  205764. }
  205765. else
  205766. {
  205767. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  205768. clipRect.setSize (size.width, size.height);
  205769. setFill (FillType (Colours::black));
  205770. }
  205771. }
  205772. ~SavedState()
  205773. {
  205774. clearClip();
  205775. clearFont();
  205776. clearFill();
  205777. clearPathClip();
  205778. clearImageClip();
  205779. complexClipLayer = 0;
  205780. bitmapMaskLayer = 0;
  205781. }
  205782. void clearClip()
  205783. {
  205784. popClips();
  205785. shouldClipRect = false;
  205786. }
  205787. void clipToRectangle (const Rectangle<int>& r)
  205788. {
  205789. clearClip();
  205790. clipRect = r + origin;
  205791. shouldClipRect = true;
  205792. pushClips();
  205793. }
  205794. void clearPathClip()
  205795. {
  205796. popClips();
  205797. if (shouldClipComplex)
  205798. {
  205799. complexClipGeometry = 0;
  205800. shouldClipComplex = false;
  205801. }
  205802. }
  205803. void clipToPath (ID2D1Geometry* geometry)
  205804. {
  205805. clearPathClip();
  205806. if (complexClipLayer == 0)
  205807. owner.renderingTarget->CreateLayer (complexClipLayer.resetAndGetPointerAddress());
  205808. complexClipGeometry = geometry;
  205809. shouldClipComplex = true;
  205810. pushClips();
  205811. }
  205812. void clearRectListClip()
  205813. {
  205814. popClips();
  205815. if (shouldClipRectList)
  205816. {
  205817. rectListGeometry = 0;
  205818. shouldClipRectList = false;
  205819. }
  205820. }
  205821. void clipToRectList (ID2D1Geometry* geometry)
  205822. {
  205823. clearRectListClip();
  205824. if (rectListLayer == 0)
  205825. owner.renderingTarget->CreateLayer (rectListLayer.resetAndGetPointerAddress());
  205826. rectListGeometry = geometry;
  205827. shouldClipRectList = true;
  205828. pushClips();
  205829. }
  205830. void clearImageClip()
  205831. {
  205832. popClips();
  205833. if (shouldClipBitmap)
  205834. {
  205835. maskBitmap = 0;
  205836. bitmapMaskBrush = 0;
  205837. shouldClipBitmap = false;
  205838. }
  205839. }
  205840. void clipToImage (const Image& image, const AffineTransform& transform)
  205841. {
  205842. clearImageClip();
  205843. if (bitmapMaskLayer == 0)
  205844. owner.renderingTarget->CreateLayer (bitmapMaskLayer.resetAndGetPointerAddress());
  205845. D2D1_BRUSH_PROPERTIES brushProps;
  205846. brushProps.opacity = 1;
  205847. brushProps.transform = transformToMatrix (transform);
  205848. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  205849. D2D1_SIZE_U size;
  205850. size.width = image.getWidth();
  205851. size.height = image.getHeight();
  205852. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205853. maskImage = image.convertedToFormat (Image::ARGB);
  205854. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  205855. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  205856. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205857. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, maskBitmap.resetAndGetPointerAddress());
  205858. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, bitmapMaskBrush.resetAndGetPointerAddress());
  205859. imageMaskLayerParams = D2D1::LayerParameters();
  205860. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  205861. shouldClipBitmap = true;
  205862. pushClips();
  205863. }
  205864. void popClips()
  205865. {
  205866. if (clipsBitmap)
  205867. {
  205868. owner.renderingTarget->PopLayer();
  205869. clipsBitmap = false;
  205870. }
  205871. if (clipsComplex)
  205872. {
  205873. owner.renderingTarget->PopLayer();
  205874. clipsComplex = false;
  205875. }
  205876. if (clipsRectList)
  205877. {
  205878. owner.renderingTarget->PopLayer();
  205879. clipsRectList = false;
  205880. }
  205881. if (clipsRect)
  205882. {
  205883. owner.renderingTarget->PopAxisAlignedClip();
  205884. clipsRect = false;
  205885. }
  205886. }
  205887. void pushClips()
  205888. {
  205889. if (shouldClipRect && ! clipsRect)
  205890. {
  205891. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  205892. clipsRect = true;
  205893. }
  205894. if (shouldClipRectList && ! clipsRectList)
  205895. {
  205896. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205897. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205898. layerParams.geometricMask = rectListGeometry;
  205899. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  205900. clipsRectList = true;
  205901. }
  205902. if (shouldClipComplex && ! clipsComplex)
  205903. {
  205904. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  205905. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  205906. layerParams.geometricMask = complexClipGeometry;
  205907. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  205908. clipsComplex = true;
  205909. }
  205910. if (shouldClipBitmap && ! clipsBitmap)
  205911. {
  205912. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  205913. clipsBitmap = true;
  205914. }
  205915. }
  205916. void setFill (const FillType& newFillType)
  205917. {
  205918. if (fillType != newFillType)
  205919. {
  205920. fillType = newFillType;
  205921. clearFill();
  205922. }
  205923. }
  205924. void clearFont()
  205925. {
  205926. currentFontFace = localFontFace = 0;
  205927. }
  205928. void setFont (const Font& newFont)
  205929. {
  205930. if (font != newFont)
  205931. {
  205932. font = newFont;
  205933. clearFont();
  205934. }
  205935. }
  205936. void createFont()
  205937. {
  205938. // xxx The font shouldn't be managed by the graphics context.
  205939. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  205940. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  205941. // WindowsTypeface class.
  205942. if (currentFontFace == 0)
  205943. {
  205944. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  205945. fontScaling = systemType->getAscent();
  205946. BOOL fontFound;
  205947. uint32 fontIndex;
  205948. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  205949. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  205950. if (! fontFound)
  205951. fontIndex = 0;
  205952. ComSmartPtr <IDWriteFontFamily> fontFam;
  205953. fonts->GetFontFamily (fontIndex, fontFam.resetAndGetPointerAddress());
  205954. ComSmartPtr <IDWriteFont> font;
  205955. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  205956. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  205957. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, font.resetAndGetPointerAddress());
  205958. font->CreateFontFace (localFontFace.resetAndGetPointerAddress());
  205959. currentFontFace = localFontFace;
  205960. }
  205961. }
  205962. void setOpacity (float newOpacity)
  205963. {
  205964. fillType.setOpacity (newOpacity);
  205965. if (currentBrush != 0)
  205966. currentBrush->SetOpacity (newOpacity);
  205967. }
  205968. void clearFill()
  205969. {
  205970. gradientStops = 0;
  205971. linearGradient = 0;
  205972. radialGradient = 0;
  205973. bitmap = 0;
  205974. bitmapBrush = 0;
  205975. currentBrush = 0;
  205976. }
  205977. void createBrush()
  205978. {
  205979. if (currentBrush == 0)
  205980. {
  205981. const int x = origin.getX();
  205982. const int y = origin.getY();
  205983. if (fillType.isColour())
  205984. {
  205985. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  205986. owner.colourBrush->SetColor (colour);
  205987. currentBrush = owner.colourBrush;
  205988. }
  205989. else if (fillType.isTiledImage())
  205990. {
  205991. D2D1_BRUSH_PROPERTIES brushProps;
  205992. brushProps.opacity = fillType.getOpacity();
  205993. brushProps.transform = transformToMatrix (fillType.transform);
  205994. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  205995. image = fillType.image;
  205996. D2D1_SIZE_U size;
  205997. size.width = image.getWidth();
  205998. size.height = image.getHeight();
  205999. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206000. this->image = image.convertedToFormat (Image::ARGB);
  206001. Image::BitmapData bd (this->image, false);
  206002. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206003. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206004. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, bitmap.resetAndGetPointerAddress());
  206005. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, bitmapBrush.resetAndGetPointerAddress());
  206006. currentBrush = bitmapBrush;
  206007. }
  206008. else if (fillType.isGradient())
  206009. {
  206010. gradientStops = 0;
  206011. D2D1_BRUSH_PROPERTIES brushProps;
  206012. brushProps.opacity = fillType.getOpacity();
  206013. brushProps.transform = transformToMatrix (fillType.transform);
  206014. const int numColors = fillType.gradient->getNumColours();
  206015. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206016. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206017. {
  206018. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206019. stops[i].position = fillType.gradient->getColourPosition(i);
  206020. }
  206021. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, gradientStops.resetAndGetPointerAddress());
  206022. if (fillType.gradient->isRadial)
  206023. {
  206024. radialGradient = 0;
  206025. const Point<float>& p1 = fillType.gradient->point1;
  206026. const Point<float>& p2 = fillType.gradient->point2;
  206027. float r = p1.getDistanceFrom (p2);
  206028. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206029. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206030. D2D1::Point2F (0, 0),
  206031. r, r);
  206032. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, radialGradient.resetAndGetPointerAddress());
  206033. currentBrush = radialGradient;
  206034. }
  206035. else
  206036. {
  206037. linearGradient = 0;
  206038. const Point<float>& p1 = fillType.gradient->point1;
  206039. const Point<float>& p2 = fillType.gradient->point2;
  206040. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206041. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206042. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206043. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, linearGradient.resetAndGetPointerAddress());
  206044. currentBrush = linearGradient;
  206045. }
  206046. }
  206047. }
  206048. }
  206049. //xxx most of these members should probably be private...
  206050. Direct2DLowLevelGraphicsContext& owner;
  206051. Point<int> origin;
  206052. Font font;
  206053. float fontScaling;
  206054. IDWriteFontFace* currentFontFace;
  206055. ComSmartPtr <IDWriteFontFace> localFontFace;
  206056. FillType fillType;
  206057. Image image;
  206058. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206059. Rectangle<int> clipRect;
  206060. bool clipsRect, shouldClipRect;
  206061. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206062. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206063. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206064. bool clipsComplex, shouldClipComplex;
  206065. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206066. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206067. ComSmartPtr <ID2D1Layer> rectListLayer;
  206068. bool clipsRectList, shouldClipRectList;
  206069. Image maskImage;
  206070. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206071. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206072. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206073. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206074. bool clipsBitmap, shouldClipBitmap;
  206075. ID2D1Brush* currentBrush;
  206076. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206077. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206078. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206079. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206080. private:
  206081. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SavedState);
  206082. };
  206083. private:
  206084. HWND hwnd;
  206085. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206086. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206087. Rectangle<int> bounds;
  206088. SavedState* currentState;
  206089. OwnedArray<SavedState> states;
  206090. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206091. {
  206092. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206093. }
  206094. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206095. {
  206096. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206097. }
  206098. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206099. {
  206100. transform.transformPoint (x, y);
  206101. return D2D1::Point2F (x, y);
  206102. }
  206103. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206104. {
  206105. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206106. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206107. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206108. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206109. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206110. }
  206111. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206112. {
  206113. ID2D1PathGeometry* p = 0;
  206114. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206115. ComSmartPtr <ID2D1GeometrySink> sink;
  206116. HRESULT hr = p->Open (sink.resetAndGetPointerAddress()); // xxx handle error
  206117. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206118. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206119. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206120. hr = sink->Close();
  206121. return p;
  206122. }
  206123. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206124. {
  206125. Path::Iterator it (path);
  206126. while (it.next())
  206127. {
  206128. switch (it.elementType)
  206129. {
  206130. case Path::Iterator::cubicTo:
  206131. {
  206132. D2D1_BEZIER_SEGMENT seg;
  206133. transform.transformPoint (it.x1, it.y1);
  206134. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206135. transform.transformPoint (it.x2, it.y2);
  206136. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206137. transform.transformPoint(it.x3, it.y3);
  206138. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206139. sink->AddBezier (seg);
  206140. break;
  206141. }
  206142. case Path::Iterator::lineTo:
  206143. {
  206144. transform.transformPoint (it.x1, it.y1);
  206145. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206146. break;
  206147. }
  206148. case Path::Iterator::quadraticTo:
  206149. {
  206150. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206151. transform.transformPoint (it.x1, it.y1);
  206152. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206153. transform.transformPoint (it.x2, it.y2);
  206154. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206155. sink->AddQuadraticBezier (seg);
  206156. break;
  206157. }
  206158. case Path::Iterator::closePath:
  206159. {
  206160. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206161. break;
  206162. }
  206163. case Path::Iterator::startNewSubPath:
  206164. {
  206165. transform.transformPoint (it.x1, it.y1);
  206166. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206167. break;
  206168. }
  206169. }
  206170. }
  206171. }
  206172. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206173. {
  206174. ID2D1PathGeometry* p = 0;
  206175. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206176. ComSmartPtr <ID2D1GeometrySink> sink;
  206177. HRESULT hr = p->Open (sink.resetAndGetPointerAddress());
  206178. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206179. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206180. hr = sink->Close();
  206181. return p;
  206182. }
  206183. static const D2D1::Matrix3x2F transformToMatrix (const AffineTransform& transform)
  206184. {
  206185. D2D1::Matrix3x2F matrix;
  206186. matrix._11 = transform.mat00;
  206187. matrix._12 = transform.mat10;
  206188. matrix._21 = transform.mat01;
  206189. matrix._22 = transform.mat11;
  206190. matrix._31 = transform.mat02;
  206191. matrix._32 = transform.mat12;
  206192. return matrix;
  206193. }
  206194. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Direct2DLowLevelGraphicsContext);
  206195. };
  206196. #endif
  206197. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206198. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206199. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206200. // compiled on its own).
  206201. #if JUCE_INCLUDED_FILE
  206202. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206203. // these are in the windows SDK, but need to be repeated here for GCC..
  206204. #ifndef GET_APPCOMMAND_LPARAM
  206205. #define FAPPCOMMAND_MASK 0xF000
  206206. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206207. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206208. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206209. #define APPCOMMAND_MEDIA_STOP 13
  206210. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206211. #define WM_APPCOMMAND 0x0319
  206212. #endif
  206213. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206214. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206215. extern bool juce_IsRunningInWine();
  206216. #ifndef ULW_ALPHA
  206217. #define ULW_ALPHA 0x00000002
  206218. #endif
  206219. #ifndef AC_SRC_ALPHA
  206220. #define AC_SRC_ALPHA 0x01
  206221. #endif
  206222. static bool shouldDeactivateTitleBar = true;
  206223. #define WM_TRAYNOTIFY WM_USER + 100
  206224. using ::abs;
  206225. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206226. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206227. bool Desktop::canUseSemiTransparentWindows() throw()
  206228. {
  206229. if (updateLayeredWindow == 0)
  206230. {
  206231. if (! juce_IsRunningInWine())
  206232. {
  206233. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206234. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206235. }
  206236. }
  206237. return updateLayeredWindow != 0;
  206238. }
  206239. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206240. {
  206241. return upright;
  206242. }
  206243. const int extendedKeyModifier = 0x10000;
  206244. const int KeyPress::spaceKey = VK_SPACE;
  206245. const int KeyPress::returnKey = VK_RETURN;
  206246. const int KeyPress::escapeKey = VK_ESCAPE;
  206247. const int KeyPress::backspaceKey = VK_BACK;
  206248. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206249. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206250. const int KeyPress::tabKey = VK_TAB;
  206251. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206252. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206253. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206254. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206255. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206256. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206257. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206258. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206259. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206260. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206261. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206262. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206263. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206264. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206265. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206266. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206267. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206268. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206269. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206270. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206271. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206272. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206273. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206274. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206275. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206276. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206277. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206278. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206279. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206280. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206281. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206282. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206283. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206284. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206285. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206286. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206287. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206288. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206289. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206290. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206291. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206292. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206293. const int KeyPress::playKey = 0x30000;
  206294. const int KeyPress::stopKey = 0x30001;
  206295. const int KeyPress::fastForwardKey = 0x30002;
  206296. const int KeyPress::rewindKey = 0x30003;
  206297. class WindowsBitmapImage : public Image::SharedImage
  206298. {
  206299. public:
  206300. HBITMAP hBitmap;
  206301. HGDIOBJ previousBitmap;
  206302. BITMAPV4HEADER bitmapInfo;
  206303. HDC hdc;
  206304. unsigned char* bitmapData;
  206305. WindowsBitmapImage (const Image::PixelFormat format_,
  206306. const int w, const int h, const bool clearImage)
  206307. : Image::SharedImage (format_, w, h)
  206308. {
  206309. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206310. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206311. zerostruct (bitmapInfo);
  206312. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206313. bitmapInfo.bV4Width = w;
  206314. bitmapInfo.bV4Height = h;
  206315. bitmapInfo.bV4Planes = 1;
  206316. bitmapInfo.bV4CSType = 1;
  206317. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206318. if (format_ == Image::ARGB)
  206319. {
  206320. bitmapInfo.bV4AlphaMask = 0xff000000;
  206321. bitmapInfo.bV4RedMask = 0xff0000;
  206322. bitmapInfo.bV4GreenMask = 0xff00;
  206323. bitmapInfo.bV4BlueMask = 0xff;
  206324. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206325. }
  206326. else
  206327. {
  206328. bitmapInfo.bV4V4Compression = BI_RGB;
  206329. }
  206330. lineStride = -((w * pixelStride + 3) & ~3);
  206331. HDC dc = GetDC (0);
  206332. hdc = CreateCompatibleDC (dc);
  206333. ReleaseDC (0, dc);
  206334. SetMapMode (hdc, MM_TEXT);
  206335. hBitmap = CreateDIBSection (hdc,
  206336. (BITMAPINFO*) &(bitmapInfo),
  206337. DIB_RGB_COLORS,
  206338. (void**) &bitmapData,
  206339. 0, 0);
  206340. previousBitmap = SelectObject (hdc, hBitmap);
  206341. if (format_ == Image::ARGB && clearImage)
  206342. zeromem (bitmapData, abs (h * lineStride));
  206343. imageData = bitmapData - (lineStride * (h - 1));
  206344. }
  206345. ~WindowsBitmapImage()
  206346. {
  206347. SelectObject (hdc, previousBitmap); // Selecting the previous bitmap before deleting the DC avoids a warning in BoundsChecker
  206348. DeleteDC (hdc);
  206349. DeleteObject (hBitmap);
  206350. }
  206351. Image::ImageType getType() const { return Image::NativeImage; }
  206352. LowLevelGraphicsContext* createLowLevelContext()
  206353. {
  206354. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206355. }
  206356. Image::SharedImage* clone()
  206357. {
  206358. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206359. for (int i = 0; i < height; ++i)
  206360. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206361. return im;
  206362. }
  206363. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206364. const int x, const int y,
  206365. const RectangleList& maskedRegion,
  206366. const uint8 updateLayeredWindowAlpha) throw()
  206367. {
  206368. static HDRAWDIB hdd = 0;
  206369. static bool needToCreateDrawDib = true;
  206370. if (needToCreateDrawDib)
  206371. {
  206372. needToCreateDrawDib = false;
  206373. HDC dc = GetDC (0);
  206374. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206375. ReleaseDC (0, dc);
  206376. // only open if we're not palettised
  206377. if (n > 8)
  206378. hdd = DrawDibOpen();
  206379. }
  206380. SetMapMode (dc, MM_TEXT);
  206381. if (transparent)
  206382. {
  206383. POINT p, pos;
  206384. SIZE size;
  206385. RECT windowBounds;
  206386. GetWindowRect (hwnd, &windowBounds);
  206387. p.x = -x;
  206388. p.y = -y;
  206389. pos.x = windowBounds.left;
  206390. pos.y = windowBounds.top;
  206391. size.cx = windowBounds.right - windowBounds.left;
  206392. size.cy = windowBounds.bottom - windowBounds.top;
  206393. BLENDFUNCTION bf;
  206394. bf.AlphaFormat = AC_SRC_ALPHA;
  206395. bf.BlendFlags = 0;
  206396. bf.BlendOp = AC_SRC_OVER;
  206397. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206398. if (! maskedRegion.isEmpty())
  206399. {
  206400. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206401. {
  206402. const Rectangle<int>& r = *i.getRectangle();
  206403. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206404. }
  206405. }
  206406. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206407. }
  206408. else
  206409. {
  206410. int savedDC = 0;
  206411. if (! maskedRegion.isEmpty())
  206412. {
  206413. savedDC = SaveDC (dc);
  206414. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206415. {
  206416. const Rectangle<int>& r = *i.getRectangle();
  206417. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206418. }
  206419. }
  206420. if (hdd == 0)
  206421. {
  206422. StretchDIBits (dc,
  206423. x, y, width, height,
  206424. 0, 0, width, height,
  206425. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206426. DIB_RGB_COLORS, SRCCOPY);
  206427. }
  206428. else
  206429. {
  206430. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206431. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206432. 0, 0, width, height, 0);
  206433. }
  206434. if (! maskedRegion.isEmpty())
  206435. RestoreDC (dc, savedDC);
  206436. }
  206437. }
  206438. private:
  206439. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsBitmapImage);
  206440. };
  206441. namespace IconConverters
  206442. {
  206443. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206444. {
  206445. Image im;
  206446. if (bitmap != 0)
  206447. {
  206448. BITMAP bm;
  206449. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206450. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206451. {
  206452. HDC tempDC = GetDC (0);
  206453. HDC dc = CreateCompatibleDC (tempDC);
  206454. ReleaseDC (0, tempDC);
  206455. SelectObject (dc, bitmap);
  206456. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206457. Image::BitmapData imageData (im, true);
  206458. for (int y = bm.bmHeight; --y >= 0;)
  206459. {
  206460. for (int x = bm.bmWidth; --x >= 0;)
  206461. {
  206462. COLORREF col = GetPixel (dc, x, y);
  206463. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  206464. (uint8) GetGValue (col),
  206465. (uint8) GetBValue (col)));
  206466. }
  206467. }
  206468. DeleteDC (dc);
  206469. }
  206470. }
  206471. return im;
  206472. }
  206473. const Image createImageFromHICON (HICON icon)
  206474. {
  206475. ICONINFO info;
  206476. if (GetIconInfo (icon, &info))
  206477. {
  206478. Image mask (createImageFromHBITMAP (info.hbmMask));
  206479. Image image (createImageFromHBITMAP (info.hbmColor));
  206480. if (mask.isValid() && image.isValid())
  206481. {
  206482. for (int y = image.getHeight(); --y >= 0;)
  206483. {
  206484. for (int x = image.getWidth(); --x >= 0;)
  206485. {
  206486. const float brightness = mask.getPixelAt (x, y).getBrightness();
  206487. if (brightness > 0.0f)
  206488. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  206489. }
  206490. }
  206491. return image;
  206492. }
  206493. }
  206494. return Image::null;
  206495. }
  206496. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  206497. {
  206498. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206499. Image bitmap (nativeBitmap);
  206500. {
  206501. Graphics g (bitmap);
  206502. g.drawImageAt (image, 0, 0);
  206503. }
  206504. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206505. ICONINFO info;
  206506. info.fIcon = isIcon;
  206507. info.xHotspot = hotspotX;
  206508. info.yHotspot = hotspotY;
  206509. info.hbmMask = mask;
  206510. info.hbmColor = nativeBitmap->hBitmap;
  206511. HICON hi = CreateIconIndirect (&info);
  206512. DeleteObject (mask);
  206513. return hi;
  206514. }
  206515. }
  206516. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206517. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206518. {
  206519. SHORT k = (SHORT) keyCode;
  206520. if ((keyCode & extendedKeyModifier) == 0
  206521. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206522. k += (SHORT) 'A' - (SHORT) 'a';
  206523. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206524. (SHORT) '+', VK_OEM_PLUS,
  206525. (SHORT) '-', VK_OEM_MINUS,
  206526. (SHORT) '.', VK_OEM_PERIOD,
  206527. (SHORT) ';', VK_OEM_1,
  206528. (SHORT) ':', VK_OEM_1,
  206529. (SHORT) '/', VK_OEM_2,
  206530. (SHORT) '?', VK_OEM_2,
  206531. (SHORT) '[', VK_OEM_4,
  206532. (SHORT) ']', VK_OEM_6 };
  206533. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206534. if (k == translatedValues [i])
  206535. k = translatedValues [i + 1];
  206536. return (GetKeyState (k) & 0x8000) != 0;
  206537. }
  206538. class Win32ComponentPeer : public ComponentPeer
  206539. {
  206540. public:
  206541. enum RenderingEngineType
  206542. {
  206543. softwareRenderingEngine = 0,
  206544. direct2DRenderingEngine
  206545. };
  206546. Win32ComponentPeer (Component* const component,
  206547. const int windowStyleFlags,
  206548. HWND parentToAddTo_)
  206549. : ComponentPeer (component, windowStyleFlags),
  206550. dontRepaint (false),
  206551. #if JUCE_DIRECT2D
  206552. currentRenderingEngine (direct2DRenderingEngine),
  206553. #else
  206554. currentRenderingEngine (softwareRenderingEngine),
  206555. #endif
  206556. fullScreen (false),
  206557. isDragging (false),
  206558. isMouseOver (false),
  206559. hasCreatedCaret (false),
  206560. constrainerIsResizing (false),
  206561. currentWindowIcon (0),
  206562. dropTarget (0),
  206563. parentToAddTo (parentToAddTo_),
  206564. updateLayeredWindowAlpha (255)
  206565. {
  206566. callFunctionIfNotLocked (&createWindowCallback, this);
  206567. setTitle (component->getName());
  206568. if ((windowStyleFlags & windowHasDropShadow) != 0
  206569. && Desktop::canUseSemiTransparentWindows())
  206570. {
  206571. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206572. if (shadower != 0)
  206573. shadower->setOwner (component);
  206574. }
  206575. }
  206576. ~Win32ComponentPeer()
  206577. {
  206578. setTaskBarIcon (Image());
  206579. shadower = 0;
  206580. // do this before the next bit to avoid messages arriving for this window
  206581. // before it's destroyed
  206582. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206583. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206584. if (currentWindowIcon != 0)
  206585. DestroyIcon (currentWindowIcon);
  206586. if (dropTarget != 0)
  206587. {
  206588. dropTarget->Release();
  206589. dropTarget = 0;
  206590. }
  206591. #if JUCE_DIRECT2D
  206592. direct2DContext = 0;
  206593. #endif
  206594. }
  206595. void* getNativeHandle() const
  206596. {
  206597. return hwnd;
  206598. }
  206599. void setVisible (bool shouldBeVisible)
  206600. {
  206601. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206602. if (shouldBeVisible)
  206603. InvalidateRect (hwnd, 0, 0);
  206604. else
  206605. lastPaintTime = 0;
  206606. }
  206607. void setTitle (const String& title)
  206608. {
  206609. SetWindowText (hwnd, title.toUTF16());
  206610. }
  206611. void setPosition (int x, int y)
  206612. {
  206613. offsetWithinParent (x, y);
  206614. SetWindowPos (hwnd, 0,
  206615. x - windowBorder.getLeft(),
  206616. y - windowBorder.getTop(),
  206617. 0, 0,
  206618. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206619. }
  206620. void repaintNowIfTransparent()
  206621. {
  206622. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206623. handlePaintMessage();
  206624. }
  206625. void updateBorderSize()
  206626. {
  206627. WINDOWINFO info;
  206628. info.cbSize = sizeof (info);
  206629. if (GetWindowInfo (hwnd, &info))
  206630. {
  206631. windowBorder = BorderSize<int> (info.rcClient.top - info.rcWindow.top,
  206632. info.rcClient.left - info.rcWindow.left,
  206633. info.rcWindow.bottom - info.rcClient.bottom,
  206634. info.rcWindow.right - info.rcClient.right);
  206635. }
  206636. #if JUCE_DIRECT2D
  206637. if (direct2DContext != 0)
  206638. direct2DContext->resized();
  206639. #endif
  206640. }
  206641. void setSize (int w, int h)
  206642. {
  206643. SetWindowPos (hwnd, 0, 0, 0,
  206644. w + windowBorder.getLeftAndRight(),
  206645. h + windowBorder.getTopAndBottom(),
  206646. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206647. updateBorderSize();
  206648. repaintNowIfTransparent();
  206649. }
  206650. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206651. {
  206652. fullScreen = isNowFullScreen;
  206653. offsetWithinParent (x, y);
  206654. SetWindowPos (hwnd, 0,
  206655. x - windowBorder.getLeft(),
  206656. y - windowBorder.getTop(),
  206657. w + windowBorder.getLeftAndRight(),
  206658. h + windowBorder.getTopAndBottom(),
  206659. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206660. updateBorderSize();
  206661. repaintNowIfTransparent();
  206662. }
  206663. const Rectangle<int> getBounds() const
  206664. {
  206665. RECT r;
  206666. GetWindowRect (hwnd, &r);
  206667. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206668. HWND parentH = GetParent (hwnd);
  206669. if (parentH != 0)
  206670. {
  206671. GetWindowRect (parentH, &r);
  206672. bounds.translate (-r.left, -r.top);
  206673. }
  206674. return windowBorder.subtractedFrom (bounds);
  206675. }
  206676. const Point<int> getScreenPosition() const
  206677. {
  206678. RECT r;
  206679. GetWindowRect (hwnd, &r);
  206680. return Point<int> (r.left + windowBorder.getLeft(),
  206681. r.top + windowBorder.getTop());
  206682. }
  206683. const Point<int> localToGlobal (const Point<int>& relativePosition)
  206684. {
  206685. return relativePosition + getScreenPosition();
  206686. }
  206687. const Point<int> globalToLocal (const Point<int>& screenPosition)
  206688. {
  206689. return screenPosition - getScreenPosition();
  206690. }
  206691. void setAlpha (float newAlpha)
  206692. {
  206693. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  206694. if (component->isOpaque())
  206695. {
  206696. if (newAlpha < 1.0f)
  206697. {
  206698. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  206699. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  206700. }
  206701. else
  206702. {
  206703. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  206704. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  206705. }
  206706. }
  206707. else
  206708. {
  206709. updateLayeredWindowAlpha = intAlpha;
  206710. component->repaint();
  206711. }
  206712. }
  206713. void setMinimised (bool shouldBeMinimised)
  206714. {
  206715. if (shouldBeMinimised != isMinimised())
  206716. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206717. }
  206718. bool isMinimised() const
  206719. {
  206720. WINDOWPLACEMENT wp;
  206721. wp.length = sizeof (WINDOWPLACEMENT);
  206722. GetWindowPlacement (hwnd, &wp);
  206723. return wp.showCmd == SW_SHOWMINIMIZED;
  206724. }
  206725. void setFullScreen (bool shouldBeFullScreen)
  206726. {
  206727. setMinimised (false);
  206728. if (fullScreen != shouldBeFullScreen)
  206729. {
  206730. fullScreen = shouldBeFullScreen;
  206731. const WeakReference<Component> deletionChecker (component);
  206732. if (! fullScreen)
  206733. {
  206734. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206735. if (hasTitleBar())
  206736. ShowWindow (hwnd, SW_SHOWNORMAL);
  206737. if (! boundsCopy.isEmpty())
  206738. {
  206739. setBounds (boundsCopy.getX(),
  206740. boundsCopy.getY(),
  206741. boundsCopy.getWidth(),
  206742. boundsCopy.getHeight(),
  206743. false);
  206744. }
  206745. }
  206746. else
  206747. {
  206748. if (hasTitleBar())
  206749. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206750. else
  206751. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206752. }
  206753. if (deletionChecker != 0)
  206754. handleMovedOrResized();
  206755. }
  206756. }
  206757. bool isFullScreen() const
  206758. {
  206759. if (! hasTitleBar())
  206760. return fullScreen;
  206761. WINDOWPLACEMENT wp;
  206762. wp.length = sizeof (wp);
  206763. GetWindowPlacement (hwnd, &wp);
  206764. return wp.showCmd == SW_SHOWMAXIMIZED;
  206765. }
  206766. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206767. {
  206768. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  206769. && isPositiveAndBelow (position.getY(), component->getHeight())))
  206770. return false;
  206771. RECT r;
  206772. GetWindowRect (hwnd, &r);
  206773. POINT p;
  206774. p.x = position.getX() + r.left + windowBorder.getLeft();
  206775. p.y = position.getY() + r.top + windowBorder.getTop();
  206776. HWND w = WindowFromPoint (p);
  206777. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206778. }
  206779. const BorderSize<int> getFrameSize() const
  206780. {
  206781. return windowBorder;
  206782. }
  206783. bool setAlwaysOnTop (bool alwaysOnTop)
  206784. {
  206785. const bool oldDeactivate = shouldDeactivateTitleBar;
  206786. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206787. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206788. 0, 0, 0, 0,
  206789. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206790. shouldDeactivateTitleBar = oldDeactivate;
  206791. if (shadower != 0)
  206792. shadower->componentBroughtToFront (*component);
  206793. return true;
  206794. }
  206795. void toFront (bool makeActive)
  206796. {
  206797. setMinimised (false);
  206798. const bool oldDeactivate = shouldDeactivateTitleBar;
  206799. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206800. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  206801. shouldDeactivateTitleBar = oldDeactivate;
  206802. if (! makeActive)
  206803. {
  206804. // in this case a broughttofront call won't have occured, so do it now..
  206805. handleBroughtToFront();
  206806. }
  206807. }
  206808. void toBehind (ComponentPeer* other)
  206809. {
  206810. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206811. jassert (otherPeer != 0); // wrong type of window?
  206812. if (otherPeer != 0)
  206813. {
  206814. setMinimised (false);
  206815. // must be careful not to try to put a topmost window behind a normal one, or win32
  206816. // promotes the normal one to be topmost!
  206817. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  206818. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206819. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206820. else if (otherPeer->getComponent()->isAlwaysOnTop())
  206821. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  206822. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206823. }
  206824. }
  206825. bool isFocused() const
  206826. {
  206827. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  206828. }
  206829. void grabFocus()
  206830. {
  206831. const bool oldDeactivate = shouldDeactivateTitleBar;
  206832. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206833. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  206834. shouldDeactivateTitleBar = oldDeactivate;
  206835. }
  206836. void textInputRequired (const Point<int>&)
  206837. {
  206838. if (! hasCreatedCaret)
  206839. {
  206840. hasCreatedCaret = true;
  206841. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206842. }
  206843. ShowCaret (hwnd);
  206844. SetCaretPos (0, 0);
  206845. }
  206846. void repaint (const Rectangle<int>& area)
  206847. {
  206848. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  206849. InvalidateRect (hwnd, &r, FALSE);
  206850. }
  206851. void performAnyPendingRepaintsNow()
  206852. {
  206853. MSG m;
  206854. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206855. DispatchMessage (&m);
  206856. }
  206857. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206858. {
  206859. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206860. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  206861. return 0;
  206862. }
  206863. void setTaskBarIcon (const Image& image)
  206864. {
  206865. if (image.isValid())
  206866. {
  206867. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  206868. if (taskBarIcon == 0)
  206869. {
  206870. taskBarIcon = new NOTIFYICONDATA();
  206871. zeromem (taskBarIcon, sizeof (NOTIFYICONDATA));
  206872. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206873. taskBarIcon->hWnd = (HWND) hwnd;
  206874. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206875. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206876. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206877. taskBarIcon->hIcon = hicon;
  206878. taskBarIcon->szTip[0] = 0;
  206879. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206880. }
  206881. else
  206882. {
  206883. HICON oldIcon = taskBarIcon->hIcon;
  206884. taskBarIcon->hIcon = hicon;
  206885. taskBarIcon->uFlags = NIF_ICON;
  206886. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206887. DestroyIcon (oldIcon);
  206888. }
  206889. }
  206890. else if (taskBarIcon != 0)
  206891. {
  206892. taskBarIcon->uFlags = 0;
  206893. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206894. DestroyIcon (taskBarIcon->hIcon);
  206895. taskBarIcon = 0;
  206896. }
  206897. }
  206898. void setTaskBarIconToolTip (const String& toolTip) const
  206899. {
  206900. if (taskBarIcon != 0)
  206901. {
  206902. taskBarIcon->uFlags = NIF_TIP;
  206903. toolTip.copyToUTF16 (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206904. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206905. }
  206906. }
  206907. void handleTaskBarEvent (const LPARAM lParam)
  206908. {
  206909. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206910. {
  206911. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206912. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206913. {
  206914. Component* const current = Component::getCurrentlyModalComponent();
  206915. if (current != 0)
  206916. current->inputAttemptWhenModal();
  206917. }
  206918. }
  206919. else
  206920. {
  206921. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  206922. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206923. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  206924. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206925. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  206926. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206927. eventMods = eventMods.withoutMouseButtons();
  206928. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  206929. Point<int>(), eventMods, component, component, Time (getMouseEventTime()),
  206930. Point<int>(), Time (getMouseEventTime()), 1, false);
  206931. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206932. {
  206933. SetFocus (hwnd);
  206934. SetForegroundWindow (hwnd);
  206935. component->mouseDown (e);
  206936. }
  206937. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206938. {
  206939. component->mouseUp (e);
  206940. }
  206941. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206942. {
  206943. component->mouseDoubleClick (e);
  206944. }
  206945. else if (lParam == WM_MOUSEMOVE)
  206946. {
  206947. component->mouseMove (e);
  206948. }
  206949. }
  206950. }
  206951. bool isInside (HWND h) const
  206952. {
  206953. return GetAncestor (hwnd, GA_ROOT) == h;
  206954. }
  206955. static void updateKeyModifiers() throw()
  206956. {
  206957. int keyMods = 0;
  206958. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  206959. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  206960. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  206961. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206962. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  206963. }
  206964. static void updateModifiersFromWParam (const WPARAM wParam)
  206965. {
  206966. int mouseMods = 0;
  206967. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  206968. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  206969. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  206970. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  206971. updateKeyModifiers();
  206972. }
  206973. static int64 getMouseEventTime()
  206974. {
  206975. static int64 eventTimeOffset = 0;
  206976. static DWORD lastMessageTime = 0;
  206977. const DWORD thisMessageTime = GetMessageTime();
  206978. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206979. {
  206980. lastMessageTime = thisMessageTime;
  206981. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206982. }
  206983. return eventTimeOffset + thisMessageTime;
  206984. }
  206985. bool dontRepaint;
  206986. static ModifierKeys currentModifiers;
  206987. static ModifierKeys modifiersAtLastCallback;
  206988. private:
  206989. HWND hwnd, parentToAddTo;
  206990. ScopedPointer<DropShadower> shadower;
  206991. RenderingEngineType currentRenderingEngine;
  206992. #if JUCE_DIRECT2D
  206993. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  206994. #endif
  206995. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret, constrainerIsResizing;
  206996. BorderSize<int> windowBorder;
  206997. HICON currentWindowIcon;
  206998. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  206999. IDropTarget* dropTarget;
  207000. uint8 updateLayeredWindowAlpha;
  207001. class TemporaryImage : public Timer
  207002. {
  207003. public:
  207004. TemporaryImage() {}
  207005. ~TemporaryImage() {}
  207006. const Image& getImage (const bool transparent, const int w, const int h)
  207007. {
  207008. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207009. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207010. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207011. startTimer (3000);
  207012. return image;
  207013. }
  207014. void timerCallback()
  207015. {
  207016. stopTimer();
  207017. image = Image::null;
  207018. }
  207019. private:
  207020. Image image;
  207021. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TemporaryImage);
  207022. };
  207023. TemporaryImage offscreenImageGenerator;
  207024. class WindowClassHolder : public DeletedAtShutdown
  207025. {
  207026. public:
  207027. WindowClassHolder()
  207028. : windowClassName ("JUCE_")
  207029. {
  207030. // this name has to be different for each app/dll instance because otherwise
  207031. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207032. // window class).
  207033. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207034. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207035. TCHAR moduleFile [1024];
  207036. moduleFile[0] = 0;
  207037. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207038. WORD iconNum = 0;
  207039. WNDCLASSEX wcex;
  207040. wcex.cbSize = sizeof (wcex);
  207041. wcex.style = CS_OWNDC;
  207042. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207043. wcex.lpszClassName = windowClassName.toUTF16();
  207044. wcex.cbClsExtra = 0;
  207045. wcex.cbWndExtra = 32;
  207046. wcex.hInstance = moduleHandle;
  207047. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207048. iconNum = 1;
  207049. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207050. wcex.hCursor = 0;
  207051. wcex.hbrBackground = 0;
  207052. wcex.lpszMenuName = 0;
  207053. RegisterClassEx (&wcex);
  207054. }
  207055. ~WindowClassHolder()
  207056. {
  207057. if (ComponentPeer::getNumPeers() == 0)
  207058. UnregisterClass (windowClassName.toUTF16(), (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207059. clearSingletonInstance();
  207060. }
  207061. String windowClassName;
  207062. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207063. };
  207064. static void* createWindowCallback (void* userData)
  207065. {
  207066. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207067. return 0;
  207068. }
  207069. void createWindow()
  207070. {
  207071. DWORD exstyle = WS_EX_ACCEPTFILES;
  207072. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207073. if (hasTitleBar())
  207074. {
  207075. type |= WS_OVERLAPPED;
  207076. if ((styleFlags & windowHasCloseButton) != 0)
  207077. {
  207078. type |= WS_SYSMENU;
  207079. }
  207080. else
  207081. {
  207082. // annoyingly, windows won't let you have a min/max button without a close button
  207083. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207084. }
  207085. if ((styleFlags & windowIsResizable) != 0)
  207086. type |= WS_THICKFRAME;
  207087. }
  207088. else if (parentToAddTo != 0)
  207089. {
  207090. type |= WS_CHILD;
  207091. }
  207092. else
  207093. {
  207094. type |= WS_POPUP | WS_SYSMENU;
  207095. }
  207096. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207097. exstyle |= WS_EX_TOOLWINDOW;
  207098. else
  207099. exstyle |= WS_EX_APPWINDOW;
  207100. if ((styleFlags & windowHasMinimiseButton) != 0)
  207101. type |= WS_MINIMIZEBOX;
  207102. if ((styleFlags & windowHasMaximiseButton) != 0)
  207103. type |= WS_MAXIMIZEBOX;
  207104. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207105. exstyle |= WS_EX_TRANSPARENT;
  207106. if ((styleFlags & windowIsSemiTransparent) != 0
  207107. && Desktop::canUseSemiTransparentWindows())
  207108. exstyle |= WS_EX_LAYERED;
  207109. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName.toUTF16(), L"", type, 0, 0, 0, 0,
  207110. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207111. #if JUCE_DIRECT2D
  207112. updateDirect2DContext();
  207113. #endif
  207114. if (hwnd != 0)
  207115. {
  207116. SetWindowLongPtr (hwnd, 0, 0);
  207117. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207118. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207119. if (dropTarget == 0)
  207120. dropTarget = new JuceDropTarget (this);
  207121. RegisterDragDrop (hwnd, dropTarget);
  207122. updateBorderSize();
  207123. // Calling this function here is (for some reason) necessary to make Windows
  207124. // correctly enable the menu items that we specify in the wm_initmenu message.
  207125. GetSystemMenu (hwnd, false);
  207126. const float alpha = component->getAlpha();
  207127. if (alpha < 1.0f)
  207128. setAlpha (alpha);
  207129. }
  207130. else
  207131. {
  207132. jassertfalse;
  207133. }
  207134. }
  207135. static void* destroyWindowCallback (void* handle)
  207136. {
  207137. RevokeDragDrop ((HWND) handle);
  207138. DestroyWindow ((HWND) handle);
  207139. return 0;
  207140. }
  207141. static void* toFrontCallback1 (void* h)
  207142. {
  207143. SetForegroundWindow ((HWND) h);
  207144. return 0;
  207145. }
  207146. static void* toFrontCallback2 (void* h)
  207147. {
  207148. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207149. return 0;
  207150. }
  207151. static void* setFocusCallback (void* h)
  207152. {
  207153. SetFocus ((HWND) h);
  207154. return 0;
  207155. }
  207156. static void* getFocusCallback (void*)
  207157. {
  207158. return GetFocus();
  207159. }
  207160. void offsetWithinParent (int& x, int& y) const
  207161. {
  207162. if (isUsingUpdateLayeredWindow())
  207163. {
  207164. HWND parentHwnd = GetParent (hwnd);
  207165. if (parentHwnd != 0)
  207166. {
  207167. RECT parentRect;
  207168. GetWindowRect (parentHwnd, &parentRect);
  207169. x += parentRect.left;
  207170. y += parentRect.top;
  207171. }
  207172. }
  207173. }
  207174. bool isUsingUpdateLayeredWindow() const
  207175. {
  207176. return ! component->isOpaque();
  207177. }
  207178. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207179. void setIcon (const Image& newIcon)
  207180. {
  207181. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207182. if (hicon != 0)
  207183. {
  207184. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207185. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207186. if (currentWindowIcon != 0)
  207187. DestroyIcon (currentWindowIcon);
  207188. currentWindowIcon = hicon;
  207189. }
  207190. }
  207191. void handlePaintMessage()
  207192. {
  207193. #if JUCE_DIRECT2D
  207194. if (direct2DContext != 0)
  207195. {
  207196. RECT r;
  207197. if (GetUpdateRect (hwnd, &r, false))
  207198. {
  207199. direct2DContext->start();
  207200. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207201. handlePaint (*direct2DContext);
  207202. direct2DContext->end();
  207203. }
  207204. }
  207205. else
  207206. #endif
  207207. {
  207208. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207209. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207210. PAINTSTRUCT paintStruct;
  207211. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207212. // message and become re-entrant, but that's OK
  207213. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207214. // corrupt the image it's using to paint into, so do a check here.
  207215. static bool reentrant = false;
  207216. if (reentrant)
  207217. {
  207218. DeleteObject (rgn);
  207219. EndPaint (hwnd, &paintStruct);
  207220. return;
  207221. }
  207222. const ScopedValueSetter<bool> setter (reentrant, true, false);
  207223. // this is the rectangle to update..
  207224. int x = paintStruct.rcPaint.left;
  207225. int y = paintStruct.rcPaint.top;
  207226. int w = paintStruct.rcPaint.right - x;
  207227. int h = paintStruct.rcPaint.bottom - y;
  207228. const bool transparent = isUsingUpdateLayeredWindow();
  207229. if (transparent)
  207230. {
  207231. // it's not possible to have a transparent window with a title bar at the moment!
  207232. jassert (! hasTitleBar());
  207233. RECT r;
  207234. GetWindowRect (hwnd, &r);
  207235. x = y = 0;
  207236. w = r.right - r.left;
  207237. h = r.bottom - r.top;
  207238. }
  207239. if (w > 0 && h > 0)
  207240. {
  207241. clearMaskedRegion();
  207242. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207243. RectangleList contextClip;
  207244. const Rectangle<int> clipBounds (0, 0, w, h);
  207245. bool needToPaintAll = true;
  207246. if (regionType == COMPLEXREGION && ! transparent)
  207247. {
  207248. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207249. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207250. DeleteObject (clipRgn);
  207251. char rgnData [8192];
  207252. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207253. if (res > 0 && res <= sizeof (rgnData))
  207254. {
  207255. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207256. if (hdr->iType == RDH_RECTANGLES
  207257. && hdr->rcBound.right - hdr->rcBound.left >= w
  207258. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207259. {
  207260. needToPaintAll = false;
  207261. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207262. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207263. while (--num >= 0)
  207264. {
  207265. if (rects->right <= x + w && rects->bottom <= y + h)
  207266. {
  207267. const int cx = jmax (x, (int) rects->left);
  207268. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207269. .getIntersection (clipBounds));
  207270. }
  207271. else
  207272. {
  207273. needToPaintAll = true;
  207274. break;
  207275. }
  207276. ++rects;
  207277. }
  207278. }
  207279. }
  207280. }
  207281. if (needToPaintAll)
  207282. {
  207283. contextClip.clear();
  207284. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207285. }
  207286. if (transparent)
  207287. {
  207288. RectangleList::Iterator i (contextClip);
  207289. while (i.next())
  207290. offscreenImage.clear (*i.getRectangle());
  207291. }
  207292. // if the component's not opaque, this won't draw properly unless the platform can support this
  207293. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207294. updateCurrentModifiers();
  207295. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207296. handlePaint (context);
  207297. if (! dontRepaint)
  207298. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207299. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207300. }
  207301. DeleteObject (rgn);
  207302. EndPaint (hwnd, &paintStruct);
  207303. }
  207304. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207305. _fpreset(); // because some graphics cards can unmask FP exceptions
  207306. #endif
  207307. lastPaintTime = Time::getMillisecondCounter();
  207308. }
  207309. void doMouseEvent (const Point<int>& position)
  207310. {
  207311. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207312. }
  207313. const StringArray getAvailableRenderingEngines()
  207314. {
  207315. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207316. #if JUCE_DIRECT2D
  207317. // xxx is this correct? Seems to enable it on Vista too??
  207318. OSVERSIONINFO info;
  207319. zerostruct (info);
  207320. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207321. GetVersionEx (&info);
  207322. if (info.dwMajorVersion >= 6)
  207323. s.add ("Direct2D");
  207324. #endif
  207325. return s;
  207326. }
  207327. int getCurrentRenderingEngine() throw()
  207328. {
  207329. return currentRenderingEngine;
  207330. }
  207331. #if JUCE_DIRECT2D
  207332. void updateDirect2DContext()
  207333. {
  207334. if (currentRenderingEngine != direct2DRenderingEngine)
  207335. direct2DContext = 0;
  207336. else if (direct2DContext == 0)
  207337. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207338. }
  207339. #endif
  207340. void setCurrentRenderingEngine (int index)
  207341. {
  207342. (void) index;
  207343. #if JUCE_DIRECT2D
  207344. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207345. updateDirect2DContext();
  207346. repaint (component->getLocalBounds());
  207347. #endif
  207348. }
  207349. void doMouseMove (const Point<int>& position)
  207350. {
  207351. if (! isMouseOver)
  207352. {
  207353. isMouseOver = true;
  207354. updateKeyModifiers();
  207355. TRACKMOUSEEVENT tme;
  207356. tme.cbSize = sizeof (tme);
  207357. tme.dwFlags = TME_LEAVE;
  207358. tme.hwndTrack = hwnd;
  207359. tme.dwHoverTime = 0;
  207360. if (! TrackMouseEvent (&tme))
  207361. jassertfalse;
  207362. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207363. }
  207364. else if (! isDragging)
  207365. {
  207366. if (! contains (position, false))
  207367. return;
  207368. }
  207369. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207370. static uint32 lastMouseTime = 0;
  207371. const uint32 now = Time::getMillisecondCounter();
  207372. const int maxMouseMovesPerSecond = 60;
  207373. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207374. {
  207375. lastMouseTime = now;
  207376. doMouseEvent (position);
  207377. }
  207378. }
  207379. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207380. {
  207381. if (GetCapture() != hwnd)
  207382. SetCapture (hwnd);
  207383. doMouseMove (position);
  207384. updateModifiersFromWParam (wParam);
  207385. isDragging = true;
  207386. doMouseEvent (position);
  207387. }
  207388. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207389. {
  207390. updateModifiersFromWParam (wParam);
  207391. isDragging = false;
  207392. // release the mouse capture if the user has released all buttons
  207393. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207394. ReleaseCapture();
  207395. doMouseEvent (position);
  207396. }
  207397. void doCaptureChanged()
  207398. {
  207399. if (constrainerIsResizing)
  207400. {
  207401. if (constrainer != 0)
  207402. constrainer->resizeEnd();
  207403. constrainerIsResizing = false;
  207404. }
  207405. if (isDragging)
  207406. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207407. }
  207408. void doMouseExit()
  207409. {
  207410. isMouseOver = false;
  207411. doMouseEvent (getCurrentMousePos());
  207412. }
  207413. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207414. {
  207415. updateKeyModifiers();
  207416. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207417. handleMouseWheel (0, position, getMouseEventTime(),
  207418. isVertical ? 0.0f : amount,
  207419. isVertical ? amount : 0.0f);
  207420. }
  207421. void sendModifierKeyChangeIfNeeded()
  207422. {
  207423. if (modifiersAtLastCallback != currentModifiers)
  207424. {
  207425. modifiersAtLastCallback = currentModifiers;
  207426. handleModifierKeysChange();
  207427. }
  207428. }
  207429. bool doKeyUp (const WPARAM key)
  207430. {
  207431. updateKeyModifiers();
  207432. switch (key)
  207433. {
  207434. case VK_SHIFT:
  207435. case VK_CONTROL:
  207436. case VK_MENU:
  207437. case VK_CAPITAL:
  207438. case VK_LWIN:
  207439. case VK_RWIN:
  207440. case VK_APPS:
  207441. case VK_NUMLOCK:
  207442. case VK_SCROLL:
  207443. case VK_LSHIFT:
  207444. case VK_RSHIFT:
  207445. case VK_LCONTROL:
  207446. case VK_LMENU:
  207447. case VK_RCONTROL:
  207448. case VK_RMENU:
  207449. sendModifierKeyChangeIfNeeded();
  207450. }
  207451. return handleKeyUpOrDown (false)
  207452. || Component::getCurrentlyModalComponent() != 0;
  207453. }
  207454. bool doKeyDown (const WPARAM key)
  207455. {
  207456. updateKeyModifiers();
  207457. bool used = false;
  207458. switch (key)
  207459. {
  207460. case VK_SHIFT:
  207461. case VK_LSHIFT:
  207462. case VK_RSHIFT:
  207463. case VK_CONTROL:
  207464. case VK_LCONTROL:
  207465. case VK_RCONTROL:
  207466. case VK_MENU:
  207467. case VK_LMENU:
  207468. case VK_RMENU:
  207469. case VK_LWIN:
  207470. case VK_RWIN:
  207471. case VK_CAPITAL:
  207472. case VK_NUMLOCK:
  207473. case VK_SCROLL:
  207474. case VK_APPS:
  207475. sendModifierKeyChangeIfNeeded();
  207476. break;
  207477. case VK_LEFT:
  207478. case VK_RIGHT:
  207479. case VK_UP:
  207480. case VK_DOWN:
  207481. case VK_PRIOR:
  207482. case VK_NEXT:
  207483. case VK_HOME:
  207484. case VK_END:
  207485. case VK_DELETE:
  207486. case VK_INSERT:
  207487. case VK_F1:
  207488. case VK_F2:
  207489. case VK_F3:
  207490. case VK_F4:
  207491. case VK_F5:
  207492. case VK_F6:
  207493. case VK_F7:
  207494. case VK_F8:
  207495. case VK_F9:
  207496. case VK_F10:
  207497. case VK_F11:
  207498. case VK_F12:
  207499. case VK_F13:
  207500. case VK_F14:
  207501. case VK_F15:
  207502. case VK_F16:
  207503. used = handleKeyUpOrDown (true);
  207504. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207505. break;
  207506. case VK_ADD:
  207507. case VK_SUBTRACT:
  207508. case VK_MULTIPLY:
  207509. case VK_DIVIDE:
  207510. case VK_SEPARATOR:
  207511. case VK_DECIMAL:
  207512. used = handleKeyUpOrDown (true);
  207513. break;
  207514. default:
  207515. used = handleKeyUpOrDown (true);
  207516. {
  207517. MSG msg;
  207518. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207519. {
  207520. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207521. // manually generate the key-press event that matches this key-down.
  207522. const UINT keyChar = MapVirtualKey (key, 2);
  207523. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207524. }
  207525. }
  207526. break;
  207527. }
  207528. if (Component::getCurrentlyModalComponent() != 0)
  207529. used = true;
  207530. return used;
  207531. }
  207532. bool doKeyChar (int key, const LPARAM flags)
  207533. {
  207534. updateKeyModifiers();
  207535. juce_wchar textChar = (juce_wchar) key;
  207536. const int virtualScanCode = (flags >> 16) & 0xff;
  207537. if (key >= '0' && key <= '9')
  207538. {
  207539. switch (virtualScanCode) // check for a numeric keypad scan-code
  207540. {
  207541. case 0x52:
  207542. case 0x4f:
  207543. case 0x50:
  207544. case 0x51:
  207545. case 0x4b:
  207546. case 0x4c:
  207547. case 0x4d:
  207548. case 0x47:
  207549. case 0x48:
  207550. case 0x49:
  207551. key = (key - '0') + KeyPress::numberPad0;
  207552. break;
  207553. default:
  207554. break;
  207555. }
  207556. }
  207557. else
  207558. {
  207559. // convert the scan code to an unmodified character code..
  207560. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207561. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207562. keyChar = LOWORD (keyChar);
  207563. if (keyChar != 0)
  207564. key = (int) keyChar;
  207565. // avoid sending junk text characters for some control-key combinations
  207566. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207567. textChar = 0;
  207568. }
  207569. return handleKeyPress (key, textChar);
  207570. }
  207571. bool doAppCommand (const LPARAM lParam)
  207572. {
  207573. int key = 0;
  207574. switch (GET_APPCOMMAND_LPARAM (lParam))
  207575. {
  207576. case APPCOMMAND_MEDIA_PLAY_PAUSE: key = KeyPress::playKey; break;
  207577. case APPCOMMAND_MEDIA_STOP: key = KeyPress::stopKey; break;
  207578. case APPCOMMAND_MEDIA_NEXTTRACK: key = KeyPress::fastForwardKey; break;
  207579. case APPCOMMAND_MEDIA_PREVIOUSTRACK: key = KeyPress::rewindKey; break;
  207580. default: break;
  207581. }
  207582. if (key != 0)
  207583. {
  207584. updateKeyModifiers();
  207585. if (hwnd == GetActiveWindow())
  207586. {
  207587. handleKeyPress (key, 0);
  207588. return true;
  207589. }
  207590. }
  207591. return false;
  207592. }
  207593. bool isConstrainedNativeWindow() const
  207594. {
  207595. return constrainer != 0
  207596. && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable);
  207597. }
  207598. LRESULT handleSizeConstraining (RECT* const r, const WPARAM wParam)
  207599. {
  207600. if (isConstrainedNativeWindow())
  207601. {
  207602. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  207603. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  207604. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207605. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  207606. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  207607. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  207608. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  207609. r->left = pos.getX();
  207610. r->top = pos.getY();
  207611. r->right = pos.getRight();
  207612. r->bottom = pos.getBottom();
  207613. }
  207614. return TRUE;
  207615. }
  207616. LRESULT handlePositionChanging (WINDOWPOS* const wp)
  207617. {
  207618. if (isConstrainedNativeWindow())
  207619. {
  207620. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  207621. && ! Component::isMouseButtonDownAnywhere())
  207622. {
  207623. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207624. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  207625. constrainer->checkBounds (pos, current,
  207626. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207627. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207628. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207629. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207630. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207631. wp->x = pos.getX();
  207632. wp->y = pos.getY();
  207633. wp->cx = pos.getWidth();
  207634. wp->cy = pos.getHeight();
  207635. }
  207636. }
  207637. return 0;
  207638. }
  207639. void handleAppActivation (const WPARAM wParam)
  207640. {
  207641. modifiersAtLastCallback = -1;
  207642. updateKeyModifiers();
  207643. if (isMinimised())
  207644. {
  207645. component->repaint();
  207646. handleMovedOrResized();
  207647. if (! ComponentPeer::isValidPeer (this))
  207648. return;
  207649. }
  207650. if (LOWORD (wParam) == WA_CLICKACTIVE && component->isCurrentlyBlockedByAnotherModalComponent())
  207651. {
  207652. Component* const underMouse = component->getComponentAt (component->getMouseXYRelative());
  207653. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207654. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207655. }
  207656. else
  207657. {
  207658. handleBroughtToFront();
  207659. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207660. Component::getCurrentlyModalComponent()->toFront (true);
  207661. }
  207662. }
  207663. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207664. {
  207665. public:
  207666. JuceDropTarget (Win32ComponentPeer* const owner_)
  207667. : owner (owner_)
  207668. {
  207669. }
  207670. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207671. {
  207672. updateFileList (pDataObject);
  207673. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207674. *pdwEffect = DROPEFFECT_COPY;
  207675. return S_OK;
  207676. }
  207677. HRESULT __stdcall DragLeave()
  207678. {
  207679. owner->handleFileDragExit (files);
  207680. return S_OK;
  207681. }
  207682. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207683. {
  207684. owner->handleFileDragMove (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207685. *pdwEffect = DROPEFFECT_COPY;
  207686. return S_OK;
  207687. }
  207688. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207689. {
  207690. updateFileList (pDataObject);
  207691. owner->handleFileDragDrop (files, owner->globalToLocal (Point<int> (mousePos.x, mousePos.y)));
  207692. *pdwEffect = DROPEFFECT_COPY;
  207693. return S_OK;
  207694. }
  207695. private:
  207696. Win32ComponentPeer* const owner;
  207697. StringArray files;
  207698. void updateFileList (IDataObject* const pDataObject)
  207699. {
  207700. files.clear();
  207701. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207702. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207703. if (pDataObject->GetData (&format, &medium) == S_OK)
  207704. {
  207705. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207706. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207707. unsigned int i = 0;
  207708. if (pDropFiles->fWide)
  207709. {
  207710. const WCHAR* const fname = (WCHAR*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207711. for (;;)
  207712. {
  207713. unsigned int len = 0;
  207714. while (i + len < totalLen && fname [i + len] != 0)
  207715. ++len;
  207716. if (len == 0)
  207717. break;
  207718. files.add (String (fname + i, len));
  207719. i += len + 1;
  207720. }
  207721. }
  207722. else
  207723. {
  207724. const char* const fname = (const char*) addBytesToPointer (pDropFiles, sizeof (DROPFILES));
  207725. for (;;)
  207726. {
  207727. unsigned int len = 0;
  207728. while (i + len < totalLen && fname [i + len] != 0)
  207729. ++len;
  207730. if (len == 0)
  207731. break;
  207732. files.add (String (fname + i, len));
  207733. i += len + 1;
  207734. }
  207735. }
  207736. GlobalUnlock (medium.hGlobal);
  207737. }
  207738. }
  207739. JUCE_DECLARE_NON_COPYABLE (JuceDropTarget);
  207740. };
  207741. void doSettingChange()
  207742. {
  207743. Desktop::getInstance().refreshMonitorSizes();
  207744. if (fullScreen && ! isMinimised())
  207745. {
  207746. const Rectangle<int> r (component->getParentMonitorArea());
  207747. SetWindowPos (hwnd, 0, r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207748. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207749. }
  207750. }
  207751. public:
  207752. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207753. {
  207754. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207755. if (peer != 0)
  207756. {
  207757. jassert (isValidPeer (peer));
  207758. return peer->peerWindowProc (h, message, wParam, lParam);
  207759. }
  207760. return DefWindowProcW (h, message, wParam, lParam);
  207761. }
  207762. private:
  207763. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  207764. {
  207765. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  207766. return callback (userData);
  207767. else
  207768. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  207769. }
  207770. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207771. {
  207772. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207773. }
  207774. const Point<int> getCurrentMousePos() throw()
  207775. {
  207776. RECT wr;
  207777. GetWindowRect (hwnd, &wr);
  207778. const DWORD mp = GetMessagePos();
  207779. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207780. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207781. }
  207782. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207783. {
  207784. switch (message)
  207785. {
  207786. case WM_NCHITTEST:
  207787. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207788. return HTTRANSPARENT;
  207789. else if (! hasTitleBar())
  207790. return HTCLIENT;
  207791. break;
  207792. case WM_PAINT:
  207793. handlePaintMessage();
  207794. return 0;
  207795. case WM_NCPAINT:
  207796. if (hasTitleBar())
  207797. break;
  207798. else if (wParam != 1)
  207799. handlePaintMessage();
  207800. return 0;
  207801. case WM_ERASEBKGND:
  207802. case WM_NCCALCSIZE:
  207803. if (hasTitleBar())
  207804. break;
  207805. return 1;
  207806. case WM_MOUSEMOVE:
  207807. doMouseMove (getPointFromLParam (lParam));
  207808. return 0;
  207809. case WM_MOUSELEAVE:
  207810. doMouseExit();
  207811. return 0;
  207812. case WM_LBUTTONDOWN:
  207813. case WM_MBUTTONDOWN:
  207814. case WM_RBUTTONDOWN:
  207815. doMouseDown (getPointFromLParam (lParam), wParam);
  207816. return 0;
  207817. case WM_LBUTTONUP:
  207818. case WM_MBUTTONUP:
  207819. case WM_RBUTTONUP:
  207820. doMouseUp (getPointFromLParam (lParam), wParam);
  207821. return 0;
  207822. case WM_CAPTURECHANGED:
  207823. doCaptureChanged();
  207824. return 0;
  207825. case WM_NCMOUSEMOVE:
  207826. if (hasTitleBar())
  207827. break;
  207828. return 0;
  207829. case 0x020A: /* WM_MOUSEWHEEL */
  207830. case 0x020E: /* WM_MOUSEHWHEEL */
  207831. doMouseWheel (getCurrentMousePos(), wParam, message == 0x020A);
  207832. return 0;
  207833. case WM_SIZING:
  207834. return handleSizeConstraining ((RECT*) lParam, wParam);
  207835. case WM_WINDOWPOSCHANGING:
  207836. return handlePositionChanging ((WINDOWPOS*) lParam);
  207837. case WM_WINDOWPOSCHANGED:
  207838. {
  207839. const Point<int> pos (getCurrentMousePos());
  207840. if (contains (pos, false))
  207841. doMouseEvent (pos);
  207842. }
  207843. handleMovedOrResized();
  207844. if (dontRepaint)
  207845. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207846. return 0;
  207847. case WM_KEYDOWN:
  207848. case WM_SYSKEYDOWN:
  207849. if (doKeyDown (wParam))
  207850. return 0;
  207851. break;
  207852. case WM_KEYUP:
  207853. case WM_SYSKEYUP:
  207854. if (doKeyUp (wParam))
  207855. return 0;
  207856. break;
  207857. case WM_CHAR:
  207858. if (doKeyChar ((int) wParam, lParam))
  207859. return 0;
  207860. break;
  207861. case WM_APPCOMMAND:
  207862. if (doAppCommand (lParam))
  207863. return TRUE;
  207864. break;
  207865. case WM_SETFOCUS:
  207866. updateKeyModifiers();
  207867. handleFocusGain();
  207868. break;
  207869. case WM_KILLFOCUS:
  207870. if (hasCreatedCaret)
  207871. {
  207872. hasCreatedCaret = false;
  207873. DestroyCaret();
  207874. }
  207875. handleFocusLoss();
  207876. break;
  207877. case WM_ACTIVATEAPP:
  207878. // Windows does weird things to process priority when you swap apps,
  207879. // so this forces an update when the app is brought to the front
  207880. if (wParam != FALSE)
  207881. juce_repeatLastProcessPriority();
  207882. else
  207883. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207884. juce_CheckCurrentlyFocusedTopLevelWindow();
  207885. modifiersAtLastCallback = -1;
  207886. return 0;
  207887. case WM_ACTIVATE:
  207888. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207889. {
  207890. handleAppActivation (wParam);
  207891. return 0;
  207892. }
  207893. break;
  207894. case WM_NCACTIVATE:
  207895. // while a temporary window is being shown, prevent Windows from deactivating the
  207896. // title bars of our main windows.
  207897. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207898. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207899. break;
  207900. case WM_MOUSEACTIVATE:
  207901. if (! component->getMouseClickGrabsKeyboardFocus())
  207902. return MA_NOACTIVATE;
  207903. break;
  207904. case WM_SHOWWINDOW:
  207905. if (wParam != 0)
  207906. handleBroughtToFront();
  207907. break;
  207908. case WM_CLOSE:
  207909. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  207910. handleUserClosingWindow();
  207911. return 0;
  207912. case WM_QUERYENDSESSION:
  207913. if (JUCEApplication::getInstance() != 0)
  207914. {
  207915. JUCEApplication::getInstance()->systemRequestedQuit();
  207916. return MessageManager::getInstance()->hasStopMessageBeenSent();
  207917. }
  207918. return TRUE;
  207919. case WM_TRAYNOTIFY:
  207920. handleTaskBarEvent (lParam);
  207921. break;
  207922. case WM_SYNCPAINT:
  207923. return 0;
  207924. case WM_DISPLAYCHANGE:
  207925. InvalidateRect (h, 0, 0);
  207926. // intentional fall-through...
  207927. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207928. doSettingChange();
  207929. break;
  207930. case WM_INITMENU:
  207931. if (! hasTitleBar())
  207932. {
  207933. if (isFullScreen())
  207934. {
  207935. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207936. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207937. }
  207938. else if (! isMinimised())
  207939. {
  207940. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207941. }
  207942. }
  207943. break;
  207944. case WM_SYSCOMMAND:
  207945. switch (wParam & 0xfff0)
  207946. {
  207947. case SC_CLOSE:
  207948. if (sendInputAttemptWhenModalMessage())
  207949. return 0;
  207950. if (hasTitleBar())
  207951. {
  207952. PostMessage (h, WM_CLOSE, 0, 0);
  207953. return 0;
  207954. }
  207955. break;
  207956. case SC_KEYMENU:
  207957. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very obscure
  207958. // situations that can arise if a modal loop is started from an alt-key keypress).
  207959. if (hasTitleBar() && h == GetCapture())
  207960. ReleaseCapture();
  207961. break;
  207962. case SC_MAXIMIZE:
  207963. if (! sendInputAttemptWhenModalMessage())
  207964. setFullScreen (true);
  207965. return 0;
  207966. case SC_MINIMIZE:
  207967. if (sendInputAttemptWhenModalMessage())
  207968. return 0;
  207969. if (! hasTitleBar())
  207970. {
  207971. setMinimised (true);
  207972. return 0;
  207973. }
  207974. break;
  207975. case SC_RESTORE:
  207976. if (sendInputAttemptWhenModalMessage())
  207977. return 0;
  207978. if (hasTitleBar())
  207979. {
  207980. if (isFullScreen())
  207981. {
  207982. setFullScreen (false);
  207983. return 0;
  207984. }
  207985. }
  207986. else
  207987. {
  207988. if (isMinimised())
  207989. setMinimised (false);
  207990. else if (isFullScreen())
  207991. setFullScreen (false);
  207992. return 0;
  207993. }
  207994. break;
  207995. }
  207996. break;
  207997. case WM_NCLBUTTONDOWN:
  207998. if (! sendInputAttemptWhenModalMessage())
  207999. {
  208000. switch (wParam)
  208001. {
  208002. case HTBOTTOM:
  208003. case HTBOTTOMLEFT:
  208004. case HTBOTTOMRIGHT:
  208005. case HTGROWBOX:
  208006. case HTLEFT:
  208007. case HTRIGHT:
  208008. case HTTOP:
  208009. case HTTOPLEFT:
  208010. case HTTOPRIGHT:
  208011. if (isConstrainedNativeWindow())
  208012. {
  208013. constrainerIsResizing = true;
  208014. constrainer->resizeStart();
  208015. }
  208016. break;
  208017. default:
  208018. break;
  208019. };
  208020. }
  208021. break;
  208022. case WM_NCRBUTTONDOWN:
  208023. case WM_NCMBUTTONDOWN:
  208024. sendInputAttemptWhenModalMessage();
  208025. break;
  208026. //case WM_IME_STARTCOMPOSITION;
  208027. // return 0;
  208028. case WM_GETDLGCODE:
  208029. return DLGC_WANTALLKEYS;
  208030. default:
  208031. if (taskBarIcon != 0)
  208032. {
  208033. static const DWORD taskbarCreatedMessage = RegisterWindowMessage (TEXT("TaskbarCreated"));
  208034. if (message == taskbarCreatedMessage)
  208035. {
  208036. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  208037. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  208038. }
  208039. }
  208040. break;
  208041. }
  208042. return DefWindowProcW (h, message, wParam, lParam);
  208043. }
  208044. bool sendInputAttemptWhenModalMessage()
  208045. {
  208046. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208047. {
  208048. Component* const current = Component::getCurrentlyModalComponent();
  208049. if (current != 0)
  208050. current->inputAttemptWhenModal();
  208051. return true;
  208052. }
  208053. return false;
  208054. }
  208055. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32ComponentPeer);
  208056. };
  208057. ModifierKeys Win32ComponentPeer::currentModifiers;
  208058. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208059. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208060. {
  208061. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208062. }
  208063. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208064. void ModifierKeys::updateCurrentModifiers() throw()
  208065. {
  208066. currentModifiers = Win32ComponentPeer::currentModifiers;
  208067. }
  208068. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208069. {
  208070. Win32ComponentPeer::updateKeyModifiers();
  208071. int mouseMods = 0;
  208072. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208073. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208074. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208075. Win32ComponentPeer::currentModifiers
  208076. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208077. return Win32ComponentPeer::currentModifiers;
  208078. }
  208079. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208080. {
  208081. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208082. if (wp != 0)
  208083. wp->setTaskBarIcon (newImage);
  208084. }
  208085. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208086. {
  208087. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208088. if (wp != 0)
  208089. wp->setTaskBarIconToolTip (tooltip);
  208090. }
  208091. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208092. {
  208093. DWORD val = GetWindowLong (h, styleType);
  208094. if (bitIsSet)
  208095. val |= feature;
  208096. else
  208097. val &= ~feature;
  208098. SetWindowLongPtr (h, styleType, val);
  208099. SetWindowPos (h, 0, 0, 0, 0, 0,
  208100. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208101. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208102. }
  208103. bool Process::isForegroundProcess()
  208104. {
  208105. HWND fg = GetForegroundWindow();
  208106. if (fg == 0)
  208107. return true;
  208108. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208109. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208110. // have to see if any of our windows are children of the foreground window
  208111. fg = GetAncestor (fg, GA_ROOT);
  208112. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208113. {
  208114. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208115. if (wp != 0 && wp->isInside (fg))
  208116. return true;
  208117. }
  208118. return false;
  208119. }
  208120. bool AlertWindow::showNativeDialogBox (const String& title,
  208121. const String& bodyText,
  208122. bool isOkCancel)
  208123. {
  208124. return MessageBox (0, bodyText.toUTF16(), title.toUTF16(),
  208125. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208126. : MB_OK)) == IDOK;
  208127. }
  208128. void Desktop::createMouseInputSources()
  208129. {
  208130. mouseSources.add (new MouseInputSource (0, true));
  208131. }
  208132. const Point<int> MouseInputSource::getCurrentMousePosition()
  208133. {
  208134. POINT mousePos;
  208135. GetCursorPos (&mousePos);
  208136. return Point<int> (mousePos.x, mousePos.y);
  208137. }
  208138. void Desktop::setMousePosition (const Point<int>& newPosition)
  208139. {
  208140. SetCursorPos (newPosition.getX(), newPosition.getY());
  208141. }
  208142. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208143. {
  208144. return createSoftwareImage (format, width, height, clearImage);
  208145. }
  208146. class ScreenSaverDefeater : public Timer,
  208147. public DeletedAtShutdown
  208148. {
  208149. public:
  208150. ScreenSaverDefeater()
  208151. {
  208152. startTimer (10000);
  208153. timerCallback();
  208154. }
  208155. ~ScreenSaverDefeater() {}
  208156. void timerCallback()
  208157. {
  208158. if (Process::isForegroundProcess())
  208159. {
  208160. // simulate a shift key getting pressed..
  208161. INPUT input[2];
  208162. input[0].type = INPUT_KEYBOARD;
  208163. input[0].ki.wVk = VK_SHIFT;
  208164. input[0].ki.dwFlags = 0;
  208165. input[0].ki.dwExtraInfo = 0;
  208166. input[1].type = INPUT_KEYBOARD;
  208167. input[1].ki.wVk = VK_SHIFT;
  208168. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208169. input[1].ki.dwExtraInfo = 0;
  208170. SendInput (2, input, sizeof (INPUT));
  208171. }
  208172. }
  208173. };
  208174. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208175. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208176. {
  208177. if (isEnabled)
  208178. deleteAndZero (screenSaverDefeater);
  208179. else if (screenSaverDefeater == 0)
  208180. screenSaverDefeater = new ScreenSaverDefeater();
  208181. }
  208182. bool Desktop::isScreenSaverEnabled()
  208183. {
  208184. return screenSaverDefeater == 0;
  208185. }
  208186. /* (The code below is the "correct" way to disable the screen saver, but it
  208187. completely fails on winXP when the saver is password-protected...)
  208188. static bool juce_screenSaverEnabled = true;
  208189. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208190. {
  208191. juce_screenSaverEnabled = isEnabled;
  208192. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208193. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208194. }
  208195. bool Desktop::isScreenSaverEnabled() throw()
  208196. {
  208197. return juce_screenSaverEnabled;
  208198. }
  208199. */
  208200. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208201. {
  208202. if (enableOrDisable)
  208203. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208204. }
  208205. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208206. {
  208207. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208208. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208209. return TRUE;
  208210. }
  208211. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208212. {
  208213. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208214. // make sure the first in the list is the main monitor
  208215. for (int i = 1; i < monitorCoords.size(); ++i)
  208216. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208217. monitorCoords.swap (i, 0);
  208218. if (monitorCoords.size() == 0)
  208219. {
  208220. RECT r;
  208221. GetWindowRect (GetDesktopWindow(), &r);
  208222. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208223. }
  208224. if (clipToWorkArea)
  208225. {
  208226. // clip the main monitor to the active non-taskbar area
  208227. RECT r;
  208228. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208229. Rectangle<int>& screen = monitorCoords.getReference (0);
  208230. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208231. jmax (screen.getY(), (int) r.top));
  208232. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208233. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208234. }
  208235. }
  208236. const Image juce_createIconForFile (const File& file)
  208237. {
  208238. Image image;
  208239. WORD iconNum = 0;
  208240. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208241. const_cast <WCHAR*> (file.getFullPathName().toUTF16().getAddress()), &iconNum);
  208242. if (icon != 0)
  208243. {
  208244. image = IconConverters::createImageFromHICON (icon);
  208245. DestroyIcon (icon);
  208246. }
  208247. return image;
  208248. }
  208249. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208250. {
  208251. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208252. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208253. Image im (image);
  208254. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208255. {
  208256. im = im.rescaled (maxW, maxH);
  208257. hotspotX = (hotspotX * maxW) / image.getWidth();
  208258. hotspotY = (hotspotY * maxH) / image.getHeight();
  208259. }
  208260. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208261. }
  208262. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208263. {
  208264. if (cursorHandle != 0 && ! isStandard)
  208265. DestroyCursor ((HCURSOR) cursorHandle);
  208266. }
  208267. enum
  208268. {
  208269. hiddenMouseCursorHandle = 32500 // (arbitrary non-zero value to mark this type of cursor)
  208270. };
  208271. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208272. {
  208273. LPCTSTR cursorName = IDC_ARROW;
  208274. switch (type)
  208275. {
  208276. case NormalCursor: break;
  208277. case NoCursor: return (void*) hiddenMouseCursorHandle;
  208278. case WaitCursor: cursorName = IDC_WAIT; break;
  208279. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208280. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208281. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208282. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208283. case LeftRightResizeCursor:
  208284. case LeftEdgeResizeCursor:
  208285. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208286. case UpDownResizeCursor:
  208287. case TopEdgeResizeCursor:
  208288. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208289. case TopLeftCornerResizeCursor:
  208290. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208291. case TopRightCornerResizeCursor:
  208292. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208293. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208294. case DraggingHandCursor:
  208295. {
  208296. static void* dragHandCursor = 0;
  208297. if (dragHandCursor == 0)
  208298. {
  208299. static const unsigned char dragHandData[] =
  208300. { 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,
  208301. 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,
  208302. 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 };
  208303. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208304. }
  208305. return dragHandCursor;
  208306. }
  208307. default:
  208308. jassertfalse; break;
  208309. }
  208310. HCURSOR cursorH = LoadCursor (0, cursorName);
  208311. if (cursorH == 0)
  208312. cursorH = LoadCursor (0, IDC_ARROW);
  208313. return cursorH;
  208314. }
  208315. void MouseCursor::showInWindow (ComponentPeer*) const
  208316. {
  208317. HCURSOR c = (HCURSOR) getHandle();
  208318. if (c == 0)
  208319. c = LoadCursor (0, IDC_ARROW);
  208320. else if (c == (HCURSOR) hiddenMouseCursorHandle)
  208321. c = 0;
  208322. SetCursor (c);
  208323. }
  208324. void MouseCursor::showInAllWindows() const
  208325. {
  208326. showInWindow (0);
  208327. }
  208328. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208329. {
  208330. public:
  208331. JuceDropSource() {}
  208332. ~JuceDropSource() {}
  208333. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208334. {
  208335. if (escapePressed)
  208336. return DRAGDROP_S_CANCEL;
  208337. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208338. return DRAGDROP_S_DROP;
  208339. return S_OK;
  208340. }
  208341. HRESULT __stdcall GiveFeedback (DWORD)
  208342. {
  208343. return DRAGDROP_S_USEDEFAULTCURSORS;
  208344. }
  208345. };
  208346. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208347. {
  208348. public:
  208349. JuceEnumFormatEtc (const FORMATETC* const format_)
  208350. : format (format_),
  208351. index (0)
  208352. {
  208353. }
  208354. ~JuceEnumFormatEtc() {}
  208355. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208356. {
  208357. if (result == 0)
  208358. return E_POINTER;
  208359. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208360. newOne->index = index;
  208361. *result = newOne;
  208362. return S_OK;
  208363. }
  208364. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208365. {
  208366. if (pceltFetched != 0)
  208367. *pceltFetched = 0;
  208368. else if (celt != 1)
  208369. return S_FALSE;
  208370. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208371. {
  208372. copyFormatEtc (lpFormatEtc [0], *format);
  208373. ++index;
  208374. if (pceltFetched != 0)
  208375. *pceltFetched = 1;
  208376. return S_OK;
  208377. }
  208378. return S_FALSE;
  208379. }
  208380. HRESULT __stdcall Skip (ULONG celt)
  208381. {
  208382. if (index + (int) celt >= 1)
  208383. return S_FALSE;
  208384. index += celt;
  208385. return S_OK;
  208386. }
  208387. HRESULT __stdcall Reset()
  208388. {
  208389. index = 0;
  208390. return S_OK;
  208391. }
  208392. private:
  208393. const FORMATETC* const format;
  208394. int index;
  208395. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208396. {
  208397. dest = source;
  208398. if (source.ptd != 0)
  208399. {
  208400. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208401. *(dest.ptd) = *(source.ptd);
  208402. }
  208403. }
  208404. JUCE_DECLARE_NON_COPYABLE (JuceEnumFormatEtc);
  208405. };
  208406. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208407. {
  208408. public:
  208409. JuceDataObject (JuceDropSource* const dropSource_,
  208410. const FORMATETC* const format_,
  208411. const STGMEDIUM* const medium_)
  208412. : dropSource (dropSource_),
  208413. format (format_),
  208414. medium (medium_)
  208415. {
  208416. }
  208417. ~JuceDataObject()
  208418. {
  208419. jassert (refCount == 0);
  208420. }
  208421. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208422. {
  208423. if ((pFormatEtc->tymed & format->tymed) != 0
  208424. && pFormatEtc->cfFormat == format->cfFormat
  208425. && pFormatEtc->dwAspect == format->dwAspect)
  208426. {
  208427. pMedium->tymed = format->tymed;
  208428. pMedium->pUnkForRelease = 0;
  208429. if (format->tymed == TYMED_HGLOBAL)
  208430. {
  208431. const SIZE_T len = GlobalSize (medium->hGlobal);
  208432. void* const src = GlobalLock (medium->hGlobal);
  208433. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208434. memcpy (dst, src, len);
  208435. GlobalUnlock (medium->hGlobal);
  208436. pMedium->hGlobal = dst;
  208437. return S_OK;
  208438. }
  208439. }
  208440. return DV_E_FORMATETC;
  208441. }
  208442. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208443. {
  208444. if (f == 0)
  208445. return E_INVALIDARG;
  208446. if (f->tymed == format->tymed
  208447. && f->cfFormat == format->cfFormat
  208448. && f->dwAspect == format->dwAspect)
  208449. return S_OK;
  208450. return DV_E_FORMATETC;
  208451. }
  208452. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208453. {
  208454. pFormatEtcOut->ptd = 0;
  208455. return E_NOTIMPL;
  208456. }
  208457. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208458. {
  208459. if (result == 0)
  208460. return E_POINTER;
  208461. if (direction == DATADIR_GET)
  208462. {
  208463. *result = new JuceEnumFormatEtc (format);
  208464. return S_OK;
  208465. }
  208466. *result = 0;
  208467. return E_NOTIMPL;
  208468. }
  208469. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208470. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208471. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208472. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208473. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208474. private:
  208475. JuceDropSource* const dropSource;
  208476. const FORMATETC* const format;
  208477. const STGMEDIUM* const medium;
  208478. JUCE_DECLARE_NON_COPYABLE (JuceDataObject);
  208479. };
  208480. static HDROP createHDrop (const StringArray& fileNames)
  208481. {
  208482. int totalBytes = 0;
  208483. for (int i = fileNames.size(); --i >= 0;)
  208484. totalBytes += CharPointer_UTF16::getBytesRequiredFor (fileNames[i].getCharPointer()) + sizeof (WCHAR);
  208485. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof (DROPFILES) + totalBytes + 4);
  208486. if (hDrop != 0)
  208487. {
  208488. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208489. pDropFiles->pFiles = sizeof (DROPFILES);
  208490. pDropFiles->fWide = true;
  208491. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208492. for (int i = 0; i < fileNames.size(); ++i)
  208493. {
  208494. const int bytesWritten = fileNames[i].copyToUTF16 (fname, 2048);
  208495. fname = reinterpret_cast<WCHAR*> (addBytesToPointer (fname, bytesWritten));
  208496. }
  208497. *fname = 0;
  208498. GlobalUnlock (hDrop);
  208499. }
  208500. return hDrop;
  208501. }
  208502. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208503. {
  208504. JuceDropSource* const source = new JuceDropSource();
  208505. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208506. DWORD effect;
  208507. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208508. data->Release();
  208509. source->Release();
  208510. return res == DRAGDROP_S_DROP;
  208511. }
  208512. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208513. {
  208514. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208515. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208516. medium.hGlobal = createHDrop (files);
  208517. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208518. : DROPEFFECT_COPY);
  208519. }
  208520. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208521. {
  208522. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208523. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208524. const int numBytes = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer());
  208525. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, numBytes + 2);
  208526. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208527. text.copyToUTF16 (data, numBytes);
  208528. format.cfFormat = CF_UNICODETEXT;
  208529. GlobalUnlock (medium.hGlobal);
  208530. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208531. }
  208532. #endif
  208533. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208534. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208535. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208536. // compiled on its own).
  208537. #if JUCE_INCLUDED_FILE
  208538. namespace FileChooserHelpers
  208539. {
  208540. static bool areThereAnyAlwaysOnTopWindows()
  208541. {
  208542. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208543. {
  208544. Component* c = Desktop::getInstance().getComponent (i);
  208545. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208546. return true;
  208547. }
  208548. return false;
  208549. }
  208550. struct FileChooserCallbackInfo
  208551. {
  208552. String initialPath;
  208553. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208554. ScopedPointer<Component> customComponent;
  208555. };
  208556. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208557. {
  208558. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208559. if (msg == BFFM_INITIALIZED)
  208560. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) info->initialPath.toUTF16().getAddress());
  208561. else if (msg == BFFM_VALIDATEFAILEDW)
  208562. info->returnedString = (LPCWSTR) lParam;
  208563. else if (msg == BFFM_VALIDATEFAILEDA)
  208564. info->returnedString = (const char*) lParam;
  208565. return 0;
  208566. }
  208567. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208568. {
  208569. if (uiMsg == WM_INITDIALOG)
  208570. {
  208571. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208572. HWND dialogH = GetParent (hdlg);
  208573. jassert (dialogH != 0);
  208574. if (dialogH == 0)
  208575. dialogH = hdlg;
  208576. RECT r, cr;
  208577. GetWindowRect (dialogH, &r);
  208578. GetClientRect (dialogH, &cr);
  208579. SetWindowPos (dialogH, 0,
  208580. r.left, r.top,
  208581. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208582. jmax (150, (int) (r.bottom - r.top)),
  208583. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208584. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208585. customComp->addToDesktop (0, dialogH);
  208586. }
  208587. else if (uiMsg == WM_NOTIFY)
  208588. {
  208589. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208590. if (ofn->hdr.code == CDN_SELCHANGE)
  208591. {
  208592. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208593. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208594. if (comp != 0)
  208595. {
  208596. WCHAR path [MAX_PATH * 2];
  208597. zerostruct (path);
  208598. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208599. comp->selectedFileChanged (File (path));
  208600. }
  208601. }
  208602. }
  208603. return 0;
  208604. }
  208605. class CustomComponentHolder : public Component
  208606. {
  208607. public:
  208608. CustomComponentHolder (Component* customComp)
  208609. {
  208610. setVisible (true);
  208611. setOpaque (true);
  208612. addAndMakeVisible (customComp);
  208613. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208614. }
  208615. void paint (Graphics& g)
  208616. {
  208617. g.fillAll (Colours::lightgrey);
  208618. }
  208619. void resized()
  208620. {
  208621. if (getNumChildComponents() > 0)
  208622. getChildComponent(0)->setBounds (getLocalBounds());
  208623. }
  208624. private:
  208625. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CustomComponentHolder);
  208626. };
  208627. }
  208628. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208629. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208630. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208631. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208632. {
  208633. using namespace FileChooserHelpers;
  208634. HeapBlock<WCHAR> files;
  208635. const int charsAvailableForResult = 32768;
  208636. files.calloc (charsAvailableForResult + 1);
  208637. int filenameOffset = 0;
  208638. FileChooserCallbackInfo info;
  208639. // use a modal window as the parent for this dialog box
  208640. // to block input from other app windows
  208641. Component parentWindow (String::empty);
  208642. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208643. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208644. mainMon.getY() + mainMon.getHeight() / 4,
  208645. 0, 0);
  208646. parentWindow.setOpaque (true);
  208647. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208648. parentWindow.addToDesktop (0);
  208649. if (extraInfoComponent == 0)
  208650. parentWindow.enterModalState();
  208651. if (currentFileOrDirectory.isDirectory())
  208652. {
  208653. info.initialPath = currentFileOrDirectory.getFullPathName();
  208654. }
  208655. else
  208656. {
  208657. currentFileOrDirectory.getFileName().copyToUTF16 (files, charsAvailableForResult * sizeof (WCHAR));
  208658. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208659. }
  208660. if (selectsDirectory)
  208661. {
  208662. BROWSEINFO bi;
  208663. zerostruct (bi);
  208664. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208665. bi.pszDisplayName = files;
  208666. bi.lpszTitle = title.toUTF16();
  208667. bi.lParam = (LPARAM) &info;
  208668. bi.lpfn = browseCallbackProc;
  208669. #ifdef BIF_USENEWUI
  208670. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208671. #else
  208672. bi.ulFlags = 0x50;
  208673. #endif
  208674. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208675. if (! SHGetPathFromIDListW (list, files))
  208676. {
  208677. files[0] = 0;
  208678. info.returnedString = String::empty;
  208679. }
  208680. LPMALLOC al;
  208681. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208682. al->Free (list);
  208683. if (info.returnedString.isNotEmpty())
  208684. {
  208685. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208686. return;
  208687. }
  208688. }
  208689. else
  208690. {
  208691. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208692. if (warnAboutOverwritingExistingFiles)
  208693. flags |= OFN_OVERWRITEPROMPT;
  208694. if (selectMultipleFiles)
  208695. flags |= OFN_ALLOWMULTISELECT;
  208696. if (extraInfoComponent != 0)
  208697. {
  208698. flags |= OFN_ENABLEHOOK;
  208699. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208700. info.customComponent->enterModalState();
  208701. }
  208702. const int filterSpace = 2048;
  208703. HeapBlock<char> filters;
  208704. filters.calloc (filterSpace * 2);
  208705. const int bytesWritten = filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters.getData()), filterSpace);
  208706. filter.copyToUTF16 (reinterpret_cast <WCHAR*> (filters + bytesWritten), filterSpace);
  208707. OPENFILENAMEW of;
  208708. zerostruct (of);
  208709. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208710. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208711. #else
  208712. of.lStructSize = sizeof (of);
  208713. #endif
  208714. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208715. of.lpstrFilter = reinterpret_cast <WCHAR*> (filters.getData());
  208716. of.nFilterIndex = 1;
  208717. of.lpstrFile = files;
  208718. of.nMaxFile = charsAvailableForResult;
  208719. of.lpstrInitialDir = info.initialPath.toUTF16();
  208720. of.lpstrTitle = title.toUTF16();
  208721. of.Flags = flags;
  208722. of.lCustData = (LPARAM) &info;
  208723. if (extraInfoComponent != 0)
  208724. of.lpfnHook = &openCallback;
  208725. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208726. : GetOpenFileName (&of)))
  208727. return;
  208728. filenameOffset = of.nFileOffset;
  208729. }
  208730. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208731. {
  208732. const WCHAR* filename = files + filenameOffset;
  208733. while (*filename != 0)
  208734. {
  208735. results.add (File (String (files) + "\\" + String (filename)));
  208736. filename += wcslen (filename) + 1;
  208737. }
  208738. }
  208739. else if (files[0] != 0)
  208740. {
  208741. results.add (File (String (files)));
  208742. }
  208743. }
  208744. #endif
  208745. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208746. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208747. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208748. // compiled on its own).
  208749. #if JUCE_INCLUDED_FILE
  208750. void SystemClipboard::copyTextToClipboard (const String& text)
  208751. {
  208752. if (OpenClipboard (0) != 0)
  208753. {
  208754. if (EmptyClipboard() != 0)
  208755. {
  208756. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (text.getCharPointer()) + 4;
  208757. if (bytesNeeded > 0)
  208758. {
  208759. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT, bytesNeeded + sizeof (WCHAR));
  208760. if (bufH != 0)
  208761. {
  208762. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208763. text.copyToUTF16 (data, bytesNeeded);
  208764. GlobalUnlock (bufH);
  208765. SetClipboardData (CF_UNICODETEXT, bufH);
  208766. }
  208767. }
  208768. }
  208769. CloseClipboard();
  208770. }
  208771. }
  208772. const String SystemClipboard::getTextFromClipboard()
  208773. {
  208774. String result;
  208775. if (OpenClipboard (0) != 0)
  208776. {
  208777. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208778. if (bufH != 0)
  208779. {
  208780. const WCHAR* const data = (const WCHAR*) GlobalLock (bufH);
  208781. if (data != 0)
  208782. {
  208783. result = String (data, (int) (GlobalSize (bufH) / sizeof (WCHAR)));
  208784. GlobalUnlock (bufH);
  208785. }
  208786. }
  208787. CloseClipboard();
  208788. }
  208789. return result;
  208790. }
  208791. #endif
  208792. /*** End of inlined file: juce_win32_Misc.cpp ***/
  208793. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  208794. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208795. // compiled on its own).
  208796. #if JUCE_INCLUDED_FILE
  208797. namespace ActiveXHelpers
  208798. {
  208799. class JuceIStorage : public ComBaseClassHelper <IStorage>
  208800. {
  208801. public:
  208802. JuceIStorage() {}
  208803. ~JuceIStorage() {}
  208804. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208805. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  208806. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  208807. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  208808. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  208809. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  208810. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  208811. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  208812. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  208813. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  208814. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  208815. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  208816. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  208817. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  208818. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  208819. };
  208820. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  208821. {
  208822. HWND window;
  208823. public:
  208824. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  208825. ~JuceOleInPlaceFrame() {}
  208826. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208827. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208828. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  208829. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208830. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  208831. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  208832. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  208833. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  208834. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  208835. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  208836. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  208837. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  208838. };
  208839. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  208840. {
  208841. HWND window;
  208842. JuceOleInPlaceFrame* frame;
  208843. public:
  208844. JuceIOleInPlaceSite (HWND window_)
  208845. : window (window_),
  208846. frame (new JuceOleInPlaceFrame (window))
  208847. {}
  208848. ~JuceIOleInPlaceSite()
  208849. {
  208850. frame->Release();
  208851. }
  208852. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  208853. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  208854. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  208855. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  208856. HRESULT __stdcall OnUIActivate() { return S_OK; }
  208857. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  208858. {
  208859. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  208860. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  208861. */
  208862. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  208863. if (lplpDoc != 0) *lplpDoc = 0;
  208864. lpFrameInfo->fMDIApp = FALSE;
  208865. lpFrameInfo->hwndFrame = window;
  208866. lpFrameInfo->haccel = 0;
  208867. lpFrameInfo->cAccelEntries = 0;
  208868. return S_OK;
  208869. }
  208870. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  208871. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  208872. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  208873. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  208874. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  208875. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  208876. };
  208877. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  208878. {
  208879. JuceIOleInPlaceSite* inplaceSite;
  208880. public:
  208881. JuceIOleClientSite (HWND window)
  208882. : inplaceSite (new JuceIOleInPlaceSite (window))
  208883. {}
  208884. ~JuceIOleClientSite()
  208885. {
  208886. inplaceSite->Release();
  208887. }
  208888. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  208889. {
  208890. if (type == IID_IOleInPlaceSite)
  208891. {
  208892. inplaceSite->AddRef();
  208893. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  208894. return S_OK;
  208895. }
  208896. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  208897. }
  208898. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  208899. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  208900. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  208901. HRESULT __stdcall ShowObject() { return S_OK; }
  208902. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  208903. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  208904. };
  208905. static Array<ActiveXControlComponent*> activeXComps;
  208906. static HWND getHWND (const ActiveXControlComponent* const component)
  208907. {
  208908. HWND hwnd = 0;
  208909. const IID iid = IID_IOleWindow;
  208910. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  208911. if (window != 0)
  208912. {
  208913. window->GetWindow (&hwnd);
  208914. window->Release();
  208915. }
  208916. return hwnd;
  208917. }
  208918. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  208919. {
  208920. RECT activeXRect, peerRect;
  208921. GetWindowRect (hwnd, &activeXRect);
  208922. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  208923. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  208924. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  208925. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  208926. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  208927. switch (message)
  208928. {
  208929. case WM_MOUSEMOVE:
  208930. case WM_LBUTTONDOWN:
  208931. case WM_MBUTTONDOWN:
  208932. case WM_RBUTTONDOWN:
  208933. case WM_LBUTTONUP:
  208934. case WM_MBUTTONUP:
  208935. case WM_RBUTTONUP:
  208936. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  208937. break;
  208938. default:
  208939. break;
  208940. }
  208941. }
  208942. }
  208943. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  208944. {
  208945. public:
  208946. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  208947. : ComponentMovementWatcher (&owner_),
  208948. owner (owner_),
  208949. controlHWND (0),
  208950. storage (new ActiveXHelpers::JuceIStorage()),
  208951. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  208952. control (0)
  208953. {
  208954. }
  208955. ~Pimpl()
  208956. {
  208957. if (control != 0)
  208958. {
  208959. control->Close (OLECLOSE_NOSAVE);
  208960. control->Release();
  208961. }
  208962. clientSite->Release();
  208963. storage->Release();
  208964. }
  208965. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  208966. {
  208967. Component* const topComp = owner.getTopLevelComponent();
  208968. if (topComp->getPeer() != 0)
  208969. {
  208970. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  208971. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  208972. }
  208973. }
  208974. void componentPeerChanged()
  208975. {
  208976. componentMovedOrResized (true, true);
  208977. }
  208978. void componentVisibilityChanged()
  208979. {
  208980. owner.setControlVisible (owner.isShowing());
  208981. componentPeerChanged();
  208982. }
  208983. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  208984. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  208985. {
  208986. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  208987. {
  208988. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  208989. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  208990. {
  208991. switch (message)
  208992. {
  208993. case WM_MOUSEMOVE:
  208994. case WM_LBUTTONDOWN:
  208995. case WM_MBUTTONDOWN:
  208996. case WM_RBUTTONDOWN:
  208997. case WM_LBUTTONUP:
  208998. case WM_MBUTTONUP:
  208999. case WM_RBUTTONUP:
  209000. case WM_LBUTTONDBLCLK:
  209001. case WM_MBUTTONDBLCLK:
  209002. case WM_RBUTTONDBLCLK:
  209003. if (ax->isShowing())
  209004. {
  209005. ComponentPeer* const peer = ax->getPeer();
  209006. if (peer != 0)
  209007. {
  209008. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209009. if (! ax->areMouseEventsAllowed())
  209010. return 0;
  209011. }
  209012. }
  209013. break;
  209014. default:
  209015. break;
  209016. }
  209017. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209018. }
  209019. }
  209020. return DefWindowProc (hwnd, message, wParam, lParam);
  209021. }
  209022. private:
  209023. ActiveXControlComponent& owner;
  209024. public:
  209025. HWND controlHWND;
  209026. IStorage* storage;
  209027. IOleClientSite* clientSite;
  209028. IOleObject* control;
  209029. };
  209030. ActiveXControlComponent::ActiveXControlComponent()
  209031. : originalWndProc (0),
  209032. mouseEventsAllowed (true)
  209033. {
  209034. ActiveXHelpers::activeXComps.add (this);
  209035. }
  209036. ActiveXControlComponent::~ActiveXControlComponent()
  209037. {
  209038. deleteControl();
  209039. ActiveXHelpers::activeXComps.removeValue (this);
  209040. }
  209041. void ActiveXControlComponent::paint (Graphics& g)
  209042. {
  209043. if (control == 0)
  209044. g.fillAll (Colours::lightgrey);
  209045. }
  209046. bool ActiveXControlComponent::createControl (const void* controlIID)
  209047. {
  209048. deleteControl();
  209049. ComponentPeer* const peer = getPeer();
  209050. // the component must have already been added to a real window when you call this!
  209051. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209052. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209053. {
  209054. const Point<int> pos (getTopLevelComponent()->getLocalPoint (this, Point<int>()));
  209055. HWND hwnd = (HWND) peer->getNativeHandle();
  209056. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209057. HRESULT hr;
  209058. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209059. newControl->clientSite, newControl->storage,
  209060. (void**) &(newControl->control))) == S_OK)
  209061. {
  209062. newControl->control->SetHostNames (L"Juce", 0);
  209063. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209064. {
  209065. RECT rect;
  209066. rect.left = pos.getX();
  209067. rect.top = pos.getY();
  209068. rect.right = pos.getX() + getWidth();
  209069. rect.bottom = pos.getY() + getHeight();
  209070. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209071. {
  209072. control = newControl;
  209073. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209074. control->controlHWND = ActiveXHelpers::getHWND (this);
  209075. if (control->controlHWND != 0)
  209076. {
  209077. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209078. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209079. }
  209080. return true;
  209081. }
  209082. }
  209083. }
  209084. }
  209085. return false;
  209086. }
  209087. void ActiveXControlComponent::deleteControl()
  209088. {
  209089. control = 0;
  209090. originalWndProc = 0;
  209091. }
  209092. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209093. {
  209094. void* result = 0;
  209095. if (control != 0 && control->control != 0
  209096. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209097. return result;
  209098. return 0;
  209099. }
  209100. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209101. {
  209102. if (control->controlHWND != 0)
  209103. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209104. }
  209105. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209106. {
  209107. if (control->controlHWND != 0)
  209108. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209109. }
  209110. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209111. {
  209112. mouseEventsAllowed = eventsCanReachControl;
  209113. }
  209114. #endif
  209115. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209116. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209117. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209118. // compiled on its own).
  209119. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209120. using namespace QTOLibrary;
  209121. using namespace QTOControlLib;
  209122. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209123. static bool isQTAvailable = false;
  209124. class QuickTimeMovieComponent::Pimpl
  209125. {
  209126. public:
  209127. Pimpl() : dataHandle (0)
  209128. {
  209129. }
  209130. ~Pimpl()
  209131. {
  209132. clearHandle();
  209133. }
  209134. void clearHandle()
  209135. {
  209136. if (dataHandle != 0)
  209137. {
  209138. DisposeHandle (dataHandle);
  209139. dataHandle = 0;
  209140. }
  209141. }
  209142. IQTControlPtr qtControl;
  209143. IQTMoviePtr qtMovie;
  209144. Handle dataHandle;
  209145. };
  209146. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209147. : movieLoaded (false),
  209148. controllerVisible (true)
  209149. {
  209150. pimpl = new Pimpl();
  209151. setMouseEventsAllowed (false);
  209152. }
  209153. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209154. {
  209155. closeMovie();
  209156. pimpl->qtControl = 0;
  209157. deleteControl();
  209158. pimpl = 0;
  209159. }
  209160. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209161. {
  209162. if (! isQTAvailable)
  209163. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209164. return isQTAvailable;
  209165. }
  209166. void QuickTimeMovieComponent::createControlIfNeeded()
  209167. {
  209168. if (isShowing() && ! isControlCreated())
  209169. {
  209170. const IID qtIID = __uuidof (QTControl);
  209171. if (createControl (&qtIID))
  209172. {
  209173. const IID qtInterfaceIID = __uuidof (IQTControl);
  209174. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209175. if (pimpl->qtControl != 0)
  209176. {
  209177. pimpl->qtControl->Release(); // it has one ref too many at this point
  209178. pimpl->qtControl->QuickTimeInitialize();
  209179. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209180. if (movieFile != File::nonexistent)
  209181. loadMovie (movieFile, controllerVisible);
  209182. }
  209183. }
  209184. }
  209185. }
  209186. bool QuickTimeMovieComponent::isControlCreated() const
  209187. {
  209188. return isControlOpen();
  209189. }
  209190. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209191. const bool isControllerVisible)
  209192. {
  209193. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209194. movieFile = File::nonexistent;
  209195. movieLoaded = false;
  209196. pimpl->qtMovie = 0;
  209197. controllerVisible = isControllerVisible;
  209198. createControlIfNeeded();
  209199. if (isControlCreated())
  209200. {
  209201. if (pimpl->qtControl != 0)
  209202. {
  209203. pimpl->qtControl->Put_MovieHandle (0);
  209204. pimpl->clearHandle();
  209205. Movie movie;
  209206. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209207. {
  209208. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209209. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209210. if (pimpl->qtMovie != 0)
  209211. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209212. : qtMovieControllerTypeNone);
  209213. }
  209214. if (movie == 0)
  209215. pimpl->clearHandle();
  209216. }
  209217. movieLoaded = (pimpl->qtMovie != 0);
  209218. }
  209219. else
  209220. {
  209221. // You're trying to open a movie when the control hasn't yet been created, probably because
  209222. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209223. jassertfalse;
  209224. }
  209225. return movieLoaded;
  209226. }
  209227. void QuickTimeMovieComponent::closeMovie()
  209228. {
  209229. stop();
  209230. movieFile = File::nonexistent;
  209231. movieLoaded = false;
  209232. pimpl->qtMovie = 0;
  209233. if (pimpl->qtControl != 0)
  209234. pimpl->qtControl->Put_MovieHandle (0);
  209235. pimpl->clearHandle();
  209236. }
  209237. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209238. {
  209239. return movieFile;
  209240. }
  209241. bool QuickTimeMovieComponent::isMovieOpen() const
  209242. {
  209243. return movieLoaded;
  209244. }
  209245. double QuickTimeMovieComponent::getMovieDuration() const
  209246. {
  209247. if (pimpl->qtMovie != 0)
  209248. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209249. return 0.0;
  209250. }
  209251. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209252. {
  209253. if (pimpl->qtMovie != 0)
  209254. {
  209255. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209256. width = r.right - r.left;
  209257. height = r.bottom - r.top;
  209258. }
  209259. else
  209260. {
  209261. width = height = 0;
  209262. }
  209263. }
  209264. void QuickTimeMovieComponent::play()
  209265. {
  209266. if (pimpl->qtMovie != 0)
  209267. pimpl->qtMovie->Play();
  209268. }
  209269. void QuickTimeMovieComponent::stop()
  209270. {
  209271. if (pimpl->qtMovie != 0)
  209272. pimpl->qtMovie->Stop();
  209273. }
  209274. bool QuickTimeMovieComponent::isPlaying() const
  209275. {
  209276. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209277. }
  209278. void QuickTimeMovieComponent::setPosition (const double seconds)
  209279. {
  209280. if (pimpl->qtMovie != 0)
  209281. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209282. }
  209283. double QuickTimeMovieComponent::getPosition() const
  209284. {
  209285. if (pimpl->qtMovie != 0)
  209286. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209287. return 0.0;
  209288. }
  209289. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209290. {
  209291. if (pimpl->qtMovie != 0)
  209292. pimpl->qtMovie->PutRate (newSpeed);
  209293. }
  209294. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209295. {
  209296. if (pimpl->qtMovie != 0)
  209297. {
  209298. pimpl->qtMovie->PutAudioVolume (newVolume);
  209299. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209300. }
  209301. }
  209302. float QuickTimeMovieComponent::getMovieVolume() const
  209303. {
  209304. if (pimpl->qtMovie != 0)
  209305. return pimpl->qtMovie->GetAudioVolume();
  209306. return 0.0f;
  209307. }
  209308. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209309. {
  209310. if (pimpl->qtMovie != 0)
  209311. pimpl->qtMovie->PutLoop (shouldLoop);
  209312. }
  209313. bool QuickTimeMovieComponent::isLooping() const
  209314. {
  209315. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209316. }
  209317. bool QuickTimeMovieComponent::isControllerVisible() const
  209318. {
  209319. return controllerVisible;
  209320. }
  209321. void QuickTimeMovieComponent::parentHierarchyChanged()
  209322. {
  209323. createControlIfNeeded();
  209324. QTCompBaseClass::parentHierarchyChanged();
  209325. }
  209326. void QuickTimeMovieComponent::visibilityChanged()
  209327. {
  209328. createControlIfNeeded();
  209329. QTCompBaseClass::visibilityChanged();
  209330. }
  209331. void QuickTimeMovieComponent::paint (Graphics& g)
  209332. {
  209333. if (! isControlCreated())
  209334. g.fillAll (Colours::black);
  209335. }
  209336. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209337. {
  209338. Handle dataRef = 0;
  209339. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209340. if (err == noErr)
  209341. {
  209342. Str255 suffix;
  209343. strncpy ((char*) suffix, fileName, 128);
  209344. StringPtr name = suffix;
  209345. err = PtrAndHand (name, dataRef, name[0] + 1);
  209346. if (err == noErr)
  209347. {
  209348. long atoms[3];
  209349. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209350. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209351. atoms[2] = EndianU32_NtoB (MovieFileType);
  209352. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209353. if (err == noErr)
  209354. return dataRef;
  209355. }
  209356. DisposeHandle (dataRef);
  209357. }
  209358. return 0;
  209359. }
  209360. static CFStringRef juceStringToCFString (const String& s)
  209361. {
  209362. return CFStringCreateWithCString (kCFAllocatorDefault, s.toUTF8(), kCFStringEncodingUTF8);
  209363. }
  209364. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209365. {
  209366. Boolean trueBool = true;
  209367. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209368. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209369. props[prop].propValueSize = sizeof (trueBool);
  209370. props[prop].propValueAddress = &trueBool;
  209371. ++prop;
  209372. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209373. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209374. props[prop].propValueSize = sizeof (trueBool);
  209375. props[prop].propValueAddress = &trueBool;
  209376. ++prop;
  209377. Boolean isActive = true;
  209378. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209379. props[prop].propID = kQTNewMoviePropertyID_Active;
  209380. props[prop].propValueSize = sizeof (isActive);
  209381. props[prop].propValueAddress = &isActive;
  209382. ++prop;
  209383. MacSetPort (0);
  209384. jassert (prop <= 5);
  209385. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209386. return err == noErr;
  209387. }
  209388. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209389. {
  209390. if (input == 0)
  209391. return false;
  209392. dataHandle = 0;
  209393. bool ok = false;
  209394. QTNewMoviePropertyElement props[5];
  209395. zeromem (props, sizeof (props));
  209396. int prop = 0;
  209397. DataReferenceRecord dr;
  209398. props[prop].propClass = kQTPropertyClass_DataLocation;
  209399. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209400. props[prop].propValueSize = sizeof (dr);
  209401. props[prop].propValueAddress = &dr;
  209402. ++prop;
  209403. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209404. if (fin != 0)
  209405. {
  209406. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209407. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209408. &dr.dataRef, &dr.dataRefType);
  209409. ok = openMovie (props, prop, movie);
  209410. DisposeHandle (dr.dataRef);
  209411. CFRelease (filePath);
  209412. }
  209413. else
  209414. {
  209415. // sanity-check because this currently needs to load the whole stream into memory..
  209416. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209417. dataHandle = NewHandle ((Size) input->getTotalLength());
  209418. HLock (dataHandle);
  209419. // read the entire stream into memory - this is a pain, but can't get it to work
  209420. // properly using a custom callback to supply the data.
  209421. input->read (*dataHandle, (int) input->getTotalLength());
  209422. HUnlock (dataHandle);
  209423. // different types to get QT to try. (We should really be a bit smarter here by
  209424. // working out in advance which one the stream contains, rather than just trying
  209425. // each one)
  209426. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209427. "\04.avi", "\04.m4a" };
  209428. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209429. {
  209430. /* // this fails for some bizarre reason - it can be bodged to work with
  209431. // movies, but can't seem to do it for other file types..
  209432. QTNewMovieUserProcRecord procInfo;
  209433. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209434. procInfo.getMovieUserProcRefcon = this;
  209435. procInfo.defaultDataRef.dataRef = dataRef;
  209436. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209437. props[prop].propClass = kQTPropertyClass_DataLocation;
  209438. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209439. props[prop].propValueSize = sizeof (procInfo);
  209440. props[prop].propValueAddress = (void*) &procInfo;
  209441. ++prop; */
  209442. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209443. dr.dataRefType = HandleDataHandlerSubType;
  209444. ok = openMovie (props, prop, movie);
  209445. DisposeHandle (dr.dataRef);
  209446. }
  209447. }
  209448. return ok;
  209449. }
  209450. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209451. const bool isControllerVisible)
  209452. {
  209453. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209454. movieFile = movieFile_;
  209455. return ok;
  209456. }
  209457. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209458. const bool isControllerVisible)
  209459. {
  209460. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209461. }
  209462. void QuickTimeMovieComponent::goToStart()
  209463. {
  209464. setPosition (0.0);
  209465. }
  209466. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209467. const RectanglePlacement& placement)
  209468. {
  209469. int normalWidth, normalHeight;
  209470. getMovieNormalSize (normalWidth, normalHeight);
  209471. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  209472. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  209473. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  209474. else
  209475. setBounds (spaceToFitWithin);
  209476. }
  209477. #endif
  209478. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209479. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209480. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209481. // compiled on its own).
  209482. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209483. class WebBrowserComponentInternal : public ActiveXControlComponent
  209484. {
  209485. public:
  209486. WebBrowserComponentInternal()
  209487. : browser (0),
  209488. connectionPoint (0),
  209489. adviseCookie (0)
  209490. {
  209491. }
  209492. ~WebBrowserComponentInternal()
  209493. {
  209494. if (connectionPoint != 0)
  209495. connectionPoint->Unadvise (adviseCookie);
  209496. if (browser != 0)
  209497. browser->Release();
  209498. }
  209499. void createBrowser()
  209500. {
  209501. createControl (&CLSID_WebBrowser);
  209502. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209503. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209504. if (connectionPointContainer != 0)
  209505. {
  209506. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209507. &connectionPoint);
  209508. if (connectionPoint != 0)
  209509. {
  209510. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209511. jassert (owner != 0);
  209512. EventHandler* handler = new EventHandler (*owner);
  209513. connectionPoint->Advise (handler, &adviseCookie);
  209514. handler->Release();
  209515. }
  209516. }
  209517. }
  209518. void goToURL (const String& url,
  209519. const StringArray* headers,
  209520. const MemoryBlock* postData)
  209521. {
  209522. if (browser != 0)
  209523. {
  209524. LPSAFEARRAY sa = 0;
  209525. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209526. VariantInit (&flags);
  209527. VariantInit (&frame);
  209528. VariantInit (&postDataVar);
  209529. VariantInit (&headersVar);
  209530. if (headers != 0)
  209531. {
  209532. V_VT (&headersVar) = VT_BSTR;
  209533. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n").toUTF16().getAddress());
  209534. }
  209535. if (postData != 0 && postData->getSize() > 0)
  209536. {
  209537. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209538. if (sa != 0)
  209539. {
  209540. void* data = 0;
  209541. SafeArrayAccessData (sa, &data);
  209542. jassert (data != 0);
  209543. if (data != 0)
  209544. {
  209545. postData->copyTo (data, 0, postData->getSize());
  209546. SafeArrayUnaccessData (sa);
  209547. VARIANT postDataVar2;
  209548. VariantInit (&postDataVar2);
  209549. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209550. V_ARRAY (&postDataVar2) = sa;
  209551. postDataVar = postDataVar2;
  209552. }
  209553. }
  209554. }
  209555. browser->Navigate ((BSTR) (const OLECHAR*) url.toUTF16().getAddress(),
  209556. &flags, &frame,
  209557. &postDataVar, &headersVar);
  209558. if (sa != 0)
  209559. SafeArrayDestroy (sa);
  209560. VariantClear (&flags);
  209561. VariantClear (&frame);
  209562. VariantClear (&postDataVar);
  209563. VariantClear (&headersVar);
  209564. }
  209565. }
  209566. IWebBrowser2* browser;
  209567. private:
  209568. IConnectionPoint* connectionPoint;
  209569. DWORD adviseCookie;
  209570. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209571. public ComponentMovementWatcher
  209572. {
  209573. public:
  209574. EventHandler (WebBrowserComponent& owner_)
  209575. : ComponentMovementWatcher (&owner_),
  209576. owner (owner_)
  209577. {
  209578. }
  209579. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  209580. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  209581. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  209582. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/, WORD /*wFlags*/, DISPPARAMS* pDispParams,
  209583. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/, UINT* /*puArgErr*/)
  209584. {
  209585. if (dispIdMember == DISPID_BEFORENAVIGATE2)
  209586. {
  209587. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209588. String url;
  209589. if ((vurl->vt & VT_BYREF) != 0)
  209590. url = *vurl->pbstrVal;
  209591. else
  209592. url = vurl->bstrVal;
  209593. *pDispParams->rgvarg->pboolVal
  209594. = owner.pageAboutToLoad (url) ? VARIANT_FALSE
  209595. : VARIANT_TRUE;
  209596. return S_OK;
  209597. }
  209598. return E_NOTIMPL;
  209599. }
  209600. void componentMovedOrResized (bool, bool ) {}
  209601. void componentPeerChanged() {}
  209602. void componentVisibilityChanged() { owner.visibilityChanged(); }
  209603. private:
  209604. WebBrowserComponent& owner;
  209605. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (EventHandler);
  209606. };
  209607. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebBrowserComponentInternal);
  209608. };
  209609. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209610. : browser (0),
  209611. blankPageShown (false),
  209612. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209613. {
  209614. setOpaque (true);
  209615. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209616. }
  209617. WebBrowserComponent::~WebBrowserComponent()
  209618. {
  209619. delete browser;
  209620. }
  209621. void WebBrowserComponent::goToURL (const String& url,
  209622. const StringArray* headers,
  209623. const MemoryBlock* postData)
  209624. {
  209625. lastURL = url;
  209626. lastHeaders.clear();
  209627. if (headers != 0)
  209628. lastHeaders = *headers;
  209629. lastPostData.setSize (0);
  209630. if (postData != 0)
  209631. lastPostData = *postData;
  209632. blankPageShown = false;
  209633. browser->goToURL (url, headers, postData);
  209634. }
  209635. void WebBrowserComponent::stop()
  209636. {
  209637. if (browser->browser != 0)
  209638. browser->browser->Stop();
  209639. }
  209640. void WebBrowserComponent::goBack()
  209641. {
  209642. lastURL = String::empty;
  209643. blankPageShown = false;
  209644. if (browser->browser != 0)
  209645. browser->browser->GoBack();
  209646. }
  209647. void WebBrowserComponent::goForward()
  209648. {
  209649. lastURL = String::empty;
  209650. if (browser->browser != 0)
  209651. browser->browser->GoForward();
  209652. }
  209653. void WebBrowserComponent::refresh()
  209654. {
  209655. if (browser->browser != 0)
  209656. browser->browser->Refresh();
  209657. }
  209658. void WebBrowserComponent::paint (Graphics& g)
  209659. {
  209660. if (browser->browser == 0)
  209661. g.fillAll (Colours::white);
  209662. }
  209663. void WebBrowserComponent::checkWindowAssociation()
  209664. {
  209665. if (isShowing())
  209666. {
  209667. if (browser->browser == 0 && getPeer() != 0)
  209668. {
  209669. browser->createBrowser();
  209670. reloadLastURL();
  209671. }
  209672. else
  209673. {
  209674. if (blankPageShown)
  209675. goBack();
  209676. }
  209677. }
  209678. else
  209679. {
  209680. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209681. {
  209682. // when the component becomes invisible, some stuff like flash
  209683. // carries on playing audio, so we need to force it onto a blank
  209684. // page to avoid this..
  209685. blankPageShown = true;
  209686. browser->goToURL ("about:blank", 0, 0);
  209687. }
  209688. }
  209689. }
  209690. void WebBrowserComponent::reloadLastURL()
  209691. {
  209692. if (lastURL.isNotEmpty())
  209693. {
  209694. goToURL (lastURL, &lastHeaders, &lastPostData);
  209695. lastURL = String::empty;
  209696. }
  209697. }
  209698. void WebBrowserComponent::parentHierarchyChanged()
  209699. {
  209700. checkWindowAssociation();
  209701. }
  209702. void WebBrowserComponent::resized()
  209703. {
  209704. browser->setSize (getWidth(), getHeight());
  209705. }
  209706. void WebBrowserComponent::visibilityChanged()
  209707. {
  209708. checkWindowAssociation();
  209709. }
  209710. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209711. {
  209712. return true;
  209713. }
  209714. #endif
  209715. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209716. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209717. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209718. // compiled on its own).
  209719. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209720. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209721. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209722. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209723. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209724. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209725. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209726. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209727. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209728. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209729. #define WGL_ACCELERATION_ARB 0x2003
  209730. #define WGL_SWAP_METHOD_ARB 0x2007
  209731. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209732. #define WGL_PIXEL_TYPE_ARB 0x2013
  209733. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209734. #define WGL_COLOR_BITS_ARB 0x2014
  209735. #define WGL_RED_BITS_ARB 0x2015
  209736. #define WGL_GREEN_BITS_ARB 0x2017
  209737. #define WGL_BLUE_BITS_ARB 0x2019
  209738. #define WGL_ALPHA_BITS_ARB 0x201B
  209739. #define WGL_DEPTH_BITS_ARB 0x2022
  209740. #define WGL_STENCIL_BITS_ARB 0x2023
  209741. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209742. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209743. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209744. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209745. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209746. #define WGL_STEREO_ARB 0x2012
  209747. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  209748. #define WGL_SAMPLES_ARB 0x2042
  209749. #define WGL_TYPE_RGBA_ARB 0x202B
  209750. static void getWglExtensions (HDC dc, StringArray& result) throw()
  209751. {
  209752. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  209753. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  209754. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  209755. else
  209756. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  209757. }
  209758. class WindowedGLContext : public OpenGLContext
  209759. {
  209760. public:
  209761. WindowedGLContext (Component* const component_,
  209762. HGLRC contextToShareWith,
  209763. const OpenGLPixelFormat& pixelFormat)
  209764. : renderContext (0),
  209765. component (component_),
  209766. dc (0)
  209767. {
  209768. jassert (component != 0);
  209769. createNativeWindow();
  209770. // Use a default pixel format that should be supported everywhere
  209771. PIXELFORMATDESCRIPTOR pfd;
  209772. zerostruct (pfd);
  209773. pfd.nSize = sizeof (pfd);
  209774. pfd.nVersion = 1;
  209775. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  209776. pfd.iPixelType = PFD_TYPE_RGBA;
  209777. pfd.cColorBits = 24;
  209778. pfd.cDepthBits = 16;
  209779. const int format = ChoosePixelFormat (dc, &pfd);
  209780. if (format != 0)
  209781. SetPixelFormat (dc, format, &pfd);
  209782. renderContext = wglCreateContext (dc);
  209783. makeActive();
  209784. setPixelFormat (pixelFormat);
  209785. if (contextToShareWith != 0 && renderContext != 0)
  209786. wglShareLists (contextToShareWith, renderContext);
  209787. }
  209788. ~WindowedGLContext()
  209789. {
  209790. deleteContext();
  209791. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209792. nativeWindow = 0;
  209793. }
  209794. void deleteContext()
  209795. {
  209796. makeInactive();
  209797. if (renderContext != 0)
  209798. {
  209799. wglDeleteContext (renderContext);
  209800. renderContext = 0;
  209801. }
  209802. }
  209803. bool makeActive() const throw()
  209804. {
  209805. jassert (renderContext != 0);
  209806. return wglMakeCurrent (dc, renderContext) != 0;
  209807. }
  209808. bool makeInactive() const throw()
  209809. {
  209810. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  209811. }
  209812. bool isActive() const throw()
  209813. {
  209814. return wglGetCurrentContext() == renderContext;
  209815. }
  209816. const OpenGLPixelFormat getPixelFormat() const
  209817. {
  209818. OpenGLPixelFormat pf;
  209819. makeActive();
  209820. StringArray availableExtensions;
  209821. getWglExtensions (dc, availableExtensions);
  209822. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  209823. return pf;
  209824. }
  209825. void* getRawContext() const throw()
  209826. {
  209827. return renderContext;
  209828. }
  209829. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  209830. {
  209831. makeActive();
  209832. PIXELFORMATDESCRIPTOR pfd;
  209833. zerostruct (pfd);
  209834. pfd.nSize = sizeof (pfd);
  209835. pfd.nVersion = 1;
  209836. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  209837. pfd.iPixelType = PFD_TYPE_RGBA;
  209838. pfd.iLayerType = PFD_MAIN_PLANE;
  209839. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  209840. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  209841. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  209842. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  209843. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  209844. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  209845. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  209846. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  209847. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  209848. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  209849. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  209850. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  209851. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  209852. int format = 0;
  209853. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  209854. StringArray availableExtensions;
  209855. getWglExtensions (dc, availableExtensions);
  209856. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  209857. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  209858. {
  209859. int attributes[64];
  209860. int n = 0;
  209861. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  209862. attributes[n++] = GL_TRUE;
  209863. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  209864. attributes[n++] = GL_TRUE;
  209865. attributes[n++] = WGL_ACCELERATION_ARB;
  209866. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  209867. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  209868. attributes[n++] = GL_TRUE;
  209869. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  209870. attributes[n++] = WGL_TYPE_RGBA_ARB;
  209871. attributes[n++] = WGL_COLOR_BITS_ARB;
  209872. attributes[n++] = pfd.cColorBits;
  209873. attributes[n++] = WGL_RED_BITS_ARB;
  209874. attributes[n++] = pixelFormat.redBits;
  209875. attributes[n++] = WGL_GREEN_BITS_ARB;
  209876. attributes[n++] = pixelFormat.greenBits;
  209877. attributes[n++] = WGL_BLUE_BITS_ARB;
  209878. attributes[n++] = pixelFormat.blueBits;
  209879. attributes[n++] = WGL_ALPHA_BITS_ARB;
  209880. attributes[n++] = pixelFormat.alphaBits;
  209881. attributes[n++] = WGL_DEPTH_BITS_ARB;
  209882. attributes[n++] = pixelFormat.depthBufferBits;
  209883. if (pixelFormat.stencilBufferBits > 0)
  209884. {
  209885. attributes[n++] = WGL_STENCIL_BITS_ARB;
  209886. attributes[n++] = pixelFormat.stencilBufferBits;
  209887. }
  209888. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  209889. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  209890. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  209891. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  209892. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  209893. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  209894. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  209895. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  209896. if (availableExtensions.contains ("WGL_ARB_multisample")
  209897. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  209898. {
  209899. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  209900. attributes[n++] = 1;
  209901. attributes[n++] = WGL_SAMPLES_ARB;
  209902. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  209903. }
  209904. attributes[n++] = 0;
  209905. UINT formatsCount;
  209906. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  209907. (void) ok;
  209908. jassert (ok);
  209909. }
  209910. else
  209911. {
  209912. format = ChoosePixelFormat (dc, &pfd);
  209913. }
  209914. if (format != 0)
  209915. {
  209916. makeInactive();
  209917. // win32 can't change the pixel format of a window, so need to delete the
  209918. // old one and create a new one..
  209919. jassert (nativeWindow != 0);
  209920. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  209921. nativeWindow = 0;
  209922. createNativeWindow();
  209923. if (SetPixelFormat (dc, format, &pfd))
  209924. {
  209925. wglDeleteContext (renderContext);
  209926. renderContext = wglCreateContext (dc);
  209927. jassert (renderContext != 0);
  209928. return renderContext != 0;
  209929. }
  209930. }
  209931. return false;
  209932. }
  209933. void updateWindowPosition (int x, int y, int w, int h, int)
  209934. {
  209935. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  209936. x, y, w, h,
  209937. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  209938. }
  209939. void repaint()
  209940. {
  209941. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  209942. }
  209943. void swapBuffers()
  209944. {
  209945. SwapBuffers (dc);
  209946. }
  209947. bool setSwapInterval (int numFramesPerSwap)
  209948. {
  209949. makeActive();
  209950. StringArray availableExtensions;
  209951. getWglExtensions (dc, availableExtensions);
  209952. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  209953. return availableExtensions.contains ("WGL_EXT_swap_control")
  209954. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  209955. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  209956. }
  209957. int getSwapInterval() const
  209958. {
  209959. makeActive();
  209960. StringArray availableExtensions;
  209961. getWglExtensions (dc, availableExtensions);
  209962. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  209963. if (availableExtensions.contains ("WGL_EXT_swap_control")
  209964. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  209965. return wglGetSwapIntervalEXT();
  209966. return 0;
  209967. }
  209968. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  209969. {
  209970. jassert (isActive());
  209971. StringArray availableExtensions;
  209972. getWglExtensions (dc, availableExtensions);
  209973. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  209974. int numTypes = 0;
  209975. if (availableExtensions.contains("WGL_ARB_pixel_format")
  209976. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  209977. {
  209978. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  209979. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  209980. jassertfalse;
  209981. }
  209982. else
  209983. {
  209984. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  209985. }
  209986. OpenGLPixelFormat pf;
  209987. for (int i = 0; i < numTypes; ++i)
  209988. {
  209989. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  209990. {
  209991. bool alreadyListed = false;
  209992. for (int j = results.size(); --j >= 0;)
  209993. if (pf == *results.getUnchecked(j))
  209994. alreadyListed = true;
  209995. if (! alreadyListed)
  209996. results.add (new OpenGLPixelFormat (pf));
  209997. }
  209998. }
  209999. }
  210000. void* getNativeWindowHandle() const
  210001. {
  210002. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210003. }
  210004. HGLRC renderContext;
  210005. private:
  210006. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210007. Component* const component;
  210008. HDC dc;
  210009. void createNativeWindow()
  210010. {
  210011. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210012. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210013. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210014. nativeWindow->dontRepaint = true;
  210015. nativeWindow->setVisible (true);
  210016. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210017. }
  210018. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210019. OpenGLPixelFormat& result,
  210020. const StringArray& availableExtensions) const throw()
  210021. {
  210022. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210023. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210024. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210025. {
  210026. int attributes[32];
  210027. int numAttributes = 0;
  210028. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210029. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210030. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210031. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210032. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210033. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210034. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210035. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210036. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210037. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210038. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210039. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210040. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210041. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210042. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210043. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210044. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210045. int values[32];
  210046. zeromem (values, sizeof (values));
  210047. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210048. {
  210049. int n = 0;
  210050. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210051. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210052. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210053. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210054. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210055. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210056. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210057. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210058. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210059. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210060. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210061. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210062. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210063. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210064. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210065. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210066. return isValidFormat;
  210067. }
  210068. else
  210069. {
  210070. jassertfalse;
  210071. }
  210072. }
  210073. else
  210074. {
  210075. PIXELFORMATDESCRIPTOR pfd;
  210076. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210077. {
  210078. result.redBits = pfd.cRedBits;
  210079. result.greenBits = pfd.cGreenBits;
  210080. result.blueBits = pfd.cBlueBits;
  210081. result.alphaBits = pfd.cAlphaBits;
  210082. result.depthBufferBits = pfd.cDepthBits;
  210083. result.stencilBufferBits = pfd.cStencilBits;
  210084. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210085. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210086. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210087. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210088. result.fullSceneAntiAliasingNumSamples = 0;
  210089. return true;
  210090. }
  210091. else
  210092. {
  210093. jassertfalse;
  210094. }
  210095. }
  210096. return false;
  210097. }
  210098. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  210099. };
  210100. OpenGLContext* OpenGLComponent::createContext()
  210101. {
  210102. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210103. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210104. preferredPixelFormat));
  210105. return (c->renderContext != 0) ? c.release() : 0;
  210106. }
  210107. void* OpenGLComponent::getNativeWindowHandle() const
  210108. {
  210109. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210110. }
  210111. void juce_glViewport (const int w, const int h)
  210112. {
  210113. glViewport (0, 0, w, h);
  210114. }
  210115. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210116. OwnedArray <OpenGLPixelFormat>& results)
  210117. {
  210118. Component tempComp;
  210119. {
  210120. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210121. wc.makeActive();
  210122. wc.findAlternativeOpenGLPixelFormats (results);
  210123. }
  210124. }
  210125. #endif
  210126. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210127. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210128. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210129. // compiled on its own).
  210130. #if JUCE_INCLUDED_FILE
  210131. #if JUCE_USE_CDREADER
  210132. namespace CDReaderHelpers
  210133. {
  210134. #define FILE_ANY_ACCESS 0
  210135. #ifndef FILE_READ_ACCESS
  210136. #define FILE_READ_ACCESS 1
  210137. #endif
  210138. #ifndef FILE_WRITE_ACCESS
  210139. #define FILE_WRITE_ACCESS 2
  210140. #endif
  210141. #define METHOD_BUFFERED 0
  210142. #define IOCTL_SCSI_BASE 4
  210143. #define SCSI_IOCTL_DATA_OUT 0
  210144. #define SCSI_IOCTL_DATA_IN 1
  210145. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210146. #define CTL_CODE2(DevType, Function, Method, Access) (((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method))
  210147. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210148. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210149. #define SENSE_LEN 14
  210150. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210151. #define SRB_DIR_IN 0x08
  210152. #define SRB_DIR_OUT 0x10
  210153. #define SRB_EVENT_NOTIFY 0x40
  210154. #define SC_HA_INQUIRY 0x00
  210155. #define SC_GET_DEV_TYPE 0x01
  210156. #define SC_EXEC_SCSI_CMD 0x02
  210157. #define SS_PENDING 0x00
  210158. #define SS_COMP 0x01
  210159. #define SS_ERR 0x04
  210160. enum
  210161. {
  210162. READTYPE_ANY = 0,
  210163. READTYPE_ATAPI1 = 1,
  210164. READTYPE_ATAPI2 = 2,
  210165. READTYPE_READ6 = 3,
  210166. READTYPE_READ10 = 4,
  210167. READTYPE_READ_D8 = 5,
  210168. READTYPE_READ_D4 = 6,
  210169. READTYPE_READ_D4_1 = 7,
  210170. READTYPE_READ10_2 = 8
  210171. };
  210172. struct SCSI_PASS_THROUGH
  210173. {
  210174. USHORT Length;
  210175. UCHAR ScsiStatus;
  210176. UCHAR PathId;
  210177. UCHAR TargetId;
  210178. UCHAR Lun;
  210179. UCHAR CdbLength;
  210180. UCHAR SenseInfoLength;
  210181. UCHAR DataIn;
  210182. ULONG DataTransferLength;
  210183. ULONG TimeOutValue;
  210184. ULONG DataBufferOffset;
  210185. ULONG SenseInfoOffset;
  210186. UCHAR Cdb[16];
  210187. };
  210188. struct SCSI_PASS_THROUGH_DIRECT
  210189. {
  210190. USHORT Length;
  210191. UCHAR ScsiStatus;
  210192. UCHAR PathId;
  210193. UCHAR TargetId;
  210194. UCHAR Lun;
  210195. UCHAR CdbLength;
  210196. UCHAR SenseInfoLength;
  210197. UCHAR DataIn;
  210198. ULONG DataTransferLength;
  210199. ULONG TimeOutValue;
  210200. PVOID DataBuffer;
  210201. ULONG SenseInfoOffset;
  210202. UCHAR Cdb[16];
  210203. };
  210204. struct SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER
  210205. {
  210206. SCSI_PASS_THROUGH_DIRECT spt;
  210207. ULONG Filler;
  210208. UCHAR ucSenseBuf[32];
  210209. };
  210210. struct SCSI_ADDRESS
  210211. {
  210212. ULONG Length;
  210213. UCHAR PortNumber;
  210214. UCHAR PathId;
  210215. UCHAR TargetId;
  210216. UCHAR Lun;
  210217. };
  210218. #pragma pack(1)
  210219. struct SRB_GDEVBlock
  210220. {
  210221. BYTE SRB_Cmd;
  210222. BYTE SRB_Status;
  210223. BYTE SRB_HaID;
  210224. BYTE SRB_Flags;
  210225. DWORD SRB_Hdr_Rsvd;
  210226. BYTE SRB_Target;
  210227. BYTE SRB_Lun;
  210228. BYTE SRB_DeviceType;
  210229. BYTE SRB_Rsvd1;
  210230. BYTE pad[68];
  210231. };
  210232. struct SRB_ExecSCSICmd
  210233. {
  210234. BYTE SRB_Cmd;
  210235. BYTE SRB_Status;
  210236. BYTE SRB_HaID;
  210237. BYTE SRB_Flags;
  210238. DWORD SRB_Hdr_Rsvd;
  210239. BYTE SRB_Target;
  210240. BYTE SRB_Lun;
  210241. WORD SRB_Rsvd1;
  210242. DWORD SRB_BufLen;
  210243. BYTE *SRB_BufPointer;
  210244. BYTE SRB_SenseLen;
  210245. BYTE SRB_CDBLen;
  210246. BYTE SRB_HaStat;
  210247. BYTE SRB_TargStat;
  210248. VOID *SRB_PostProc;
  210249. BYTE SRB_Rsvd2[20];
  210250. BYTE CDBByte[16];
  210251. BYTE SenseArea[SENSE_LEN + 2];
  210252. };
  210253. struct SRB
  210254. {
  210255. BYTE SRB_Cmd;
  210256. BYTE SRB_Status;
  210257. BYTE SRB_HaId;
  210258. BYTE SRB_Flags;
  210259. DWORD SRB_Hdr_Rsvd;
  210260. };
  210261. struct TOCTRACK
  210262. {
  210263. BYTE rsvd;
  210264. BYTE ADR;
  210265. BYTE trackNumber;
  210266. BYTE rsvd2;
  210267. BYTE addr[4];
  210268. };
  210269. struct TOC
  210270. {
  210271. WORD tocLen;
  210272. BYTE firstTrack;
  210273. BYTE lastTrack;
  210274. TOCTRACK tracks[100];
  210275. };
  210276. #pragma pack()
  210277. struct CDDeviceDescription
  210278. {
  210279. CDDeviceDescription() : ha (0), tgt (0), lun (0), scsiDriveLetter (0)
  210280. {
  210281. }
  210282. void createDescription (const char* data)
  210283. {
  210284. description << String (data + 8, 8).trim() // vendor
  210285. << ' ' << String (data + 16, 16).trim() // product id
  210286. << ' ' << String (data + 32, 4).trim(); // rev
  210287. }
  210288. String description;
  210289. BYTE ha, tgt, lun;
  210290. char scsiDriveLetter; // will be 0 if not using scsi
  210291. };
  210292. class CDReadBuffer
  210293. {
  210294. public:
  210295. CDReadBuffer (const int numberOfFrames)
  210296. : startFrame (0), numFrames (0), dataStartOffset (0),
  210297. dataLength (0), bufferSize (2352 * numberOfFrames), index (0),
  210298. buffer (bufferSize), wantsIndex (false)
  210299. {
  210300. }
  210301. bool isZero() const throw()
  210302. {
  210303. for (int i = 0; i < dataLength; ++i)
  210304. if (buffer [dataStartOffset + i] != 0)
  210305. return false;
  210306. return true;
  210307. }
  210308. int startFrame, numFrames, dataStartOffset;
  210309. int dataLength, bufferSize, index;
  210310. HeapBlock<BYTE> buffer;
  210311. bool wantsIndex;
  210312. };
  210313. class CDDeviceHandle;
  210314. class CDController
  210315. {
  210316. public:
  210317. CDController() : initialised (false) {}
  210318. virtual ~CDController() {}
  210319. virtual bool read (CDReadBuffer&) = 0;
  210320. virtual void shutDown() {}
  210321. bool readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer = 0);
  210322. int getLastIndex();
  210323. public:
  210324. CDDeviceHandle* deviceInfo;
  210325. int framesToCheck, framesOverlap;
  210326. bool initialised;
  210327. void prepare (SRB_ExecSCSICmd& s);
  210328. void perform (SRB_ExecSCSICmd& s);
  210329. void setPaused (bool paused);
  210330. };
  210331. class CDDeviceHandle
  210332. {
  210333. public:
  210334. CDDeviceHandle (const CDDeviceDescription& device, HANDLE scsiHandle_)
  210335. : info (device), scsiHandle (scsiHandle_), readType (READTYPE_ANY)
  210336. {
  210337. }
  210338. ~CDDeviceHandle()
  210339. {
  210340. if (controller != 0)
  210341. {
  210342. controller->shutDown();
  210343. controller = 0;
  210344. }
  210345. if (scsiHandle != 0)
  210346. CloseHandle (scsiHandle);
  210347. }
  210348. bool readTOC (TOC* lpToc);
  210349. bool readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer = 0);
  210350. void openDrawer (bool shouldBeOpen);
  210351. void performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s);
  210352. CDDeviceDescription info;
  210353. HANDLE scsiHandle;
  210354. BYTE readType;
  210355. private:
  210356. ScopedPointer<CDController> controller;
  210357. bool testController (int readType, CDController* newController, CDReadBuffer& bufferToUse);
  210358. };
  210359. HANDLE createSCSIDeviceHandle (const char driveLetter)
  210360. {
  210361. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210362. DWORD flags = GENERIC_READ | GENERIC_WRITE;
  210363. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210364. if (h == INVALID_HANDLE_VALUE)
  210365. {
  210366. flags ^= GENERIC_WRITE;
  210367. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210368. }
  210369. return h;
  210370. }
  210371. void findCDDevices (Array<CDDeviceDescription>& list)
  210372. {
  210373. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  210374. {
  210375. TCHAR drivePath[] = { driveLetter, ':', '\\', 0, 0 };
  210376. if (GetDriveType (drivePath) == DRIVE_CDROM)
  210377. {
  210378. HANDLE h = createSCSIDeviceHandle (driveLetter);
  210379. if (h != INVALID_HANDLE_VALUE)
  210380. {
  210381. char buffer[100];
  210382. zeromem (buffer, sizeof (buffer));
  210383. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p;
  210384. zerostruct (p);
  210385. p.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210386. p.spt.CdbLength = 6;
  210387. p.spt.SenseInfoLength = 24;
  210388. p.spt.DataIn = SCSI_IOCTL_DATA_IN;
  210389. p.spt.DataTransferLength = sizeof (buffer);
  210390. p.spt.TimeOutValue = 2;
  210391. p.spt.DataBuffer = buffer;
  210392. p.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210393. p.spt.Cdb[0] = 0x12;
  210394. p.spt.Cdb[4] = 100;
  210395. DWORD bytesReturned = 0;
  210396. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210397. &p, sizeof (p), &p, sizeof (p),
  210398. &bytesReturned, 0) != 0)
  210399. {
  210400. CDDeviceDescription dev;
  210401. dev.scsiDriveLetter = driveLetter;
  210402. dev.createDescription (buffer);
  210403. SCSI_ADDRESS scsiAddr;
  210404. zerostruct (scsiAddr);
  210405. scsiAddr.Length = sizeof (scsiAddr);
  210406. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  210407. 0, 0, &scsiAddr, sizeof (scsiAddr),
  210408. &bytesReturned, 0) != 0)
  210409. {
  210410. dev.ha = scsiAddr.PortNumber;
  210411. dev.tgt = scsiAddr.TargetId;
  210412. dev.lun = scsiAddr.Lun;
  210413. list.add (dev);
  210414. }
  210415. }
  210416. CloseHandle (h);
  210417. }
  210418. }
  210419. }
  210420. }
  210421. DWORD performScsiPassThroughCommand (SRB_ExecSCSICmd* const srb, const char driveLetter,
  210422. HANDLE& deviceHandle, const bool retryOnFailure)
  210423. {
  210424. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210425. zerostruct (s);
  210426. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210427. s.spt.CdbLength = srb->SRB_CDBLen;
  210428. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210429. ? SCSI_IOCTL_DATA_IN
  210430. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210431. ? SCSI_IOCTL_DATA_OUT
  210432. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210433. s.spt.DataTransferLength = srb->SRB_BufLen;
  210434. s.spt.TimeOutValue = 5;
  210435. s.spt.DataBuffer = srb->SRB_BufPointer;
  210436. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  210437. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  210438. srb->SRB_Status = SS_ERR;
  210439. srb->SRB_TargStat = 0x0004;
  210440. DWORD bytesReturned = 0;
  210441. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  210442. &s, sizeof (s), &s, sizeof (s), &bytesReturned, 0) != 0)
  210443. {
  210444. srb->SRB_Status = SS_COMP;
  210445. }
  210446. else if (retryOnFailure)
  210447. {
  210448. const DWORD error = GetLastError();
  210449. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  210450. {
  210451. if (error != ERROR_INVALID_HANDLE)
  210452. CloseHandle (deviceHandle);
  210453. deviceHandle = createSCSIDeviceHandle (driveLetter);
  210454. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  210455. }
  210456. }
  210457. return srb->SRB_Status;
  210458. }
  210459. // Controller types..
  210460. class ControllerType1 : public CDController
  210461. {
  210462. public:
  210463. ControllerType1() {}
  210464. bool read (CDReadBuffer& rb)
  210465. {
  210466. if (rb.numFrames * 2352 > rb.bufferSize)
  210467. return false;
  210468. SRB_ExecSCSICmd s;
  210469. prepare (s);
  210470. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210471. s.SRB_BufLen = rb.bufferSize;
  210472. s.SRB_BufPointer = rb.buffer;
  210473. s.SRB_CDBLen = 12;
  210474. s.CDBByte[0] = 0xBE;
  210475. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210476. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210477. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210478. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210479. s.CDBByte[9] = (BYTE) (deviceInfo->readType == READTYPE_ATAPI1 ? 0x10 : 0xF0);
  210480. perform (s);
  210481. if (s.SRB_Status != SS_COMP)
  210482. return false;
  210483. rb.dataLength = rb.numFrames * 2352;
  210484. rb.dataStartOffset = 0;
  210485. return true;
  210486. }
  210487. };
  210488. class ControllerType2 : public CDController
  210489. {
  210490. public:
  210491. ControllerType2() {}
  210492. void shutDown()
  210493. {
  210494. if (initialised)
  210495. {
  210496. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  210497. SRB_ExecSCSICmd s;
  210498. prepare (s);
  210499. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  210500. s.SRB_BufLen = 0x0C;
  210501. s.SRB_BufPointer = bufPointer;
  210502. s.SRB_CDBLen = 6;
  210503. s.CDBByte[0] = 0x15;
  210504. s.CDBByte[4] = 0x0C;
  210505. perform (s);
  210506. }
  210507. }
  210508. bool init()
  210509. {
  210510. SRB_ExecSCSICmd s;
  210511. s.SRB_Status = SS_ERR;
  210512. if (deviceInfo->readType == READTYPE_READ10_2)
  210513. {
  210514. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  210515. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  210516. for (int i = 0; i < 2; ++i)
  210517. {
  210518. prepare (s);
  210519. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210520. s.SRB_BufLen = 0x14;
  210521. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  210522. s.SRB_CDBLen = 6;
  210523. s.CDBByte[0] = 0x15;
  210524. s.CDBByte[1] = 0x10;
  210525. s.CDBByte[4] = 0x14;
  210526. perform (s);
  210527. if (s.SRB_Status != SS_COMP)
  210528. return false;
  210529. }
  210530. }
  210531. else
  210532. {
  210533. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  210534. prepare (s);
  210535. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210536. s.SRB_BufLen = 0x0C;
  210537. s.SRB_BufPointer = bufPointer;
  210538. s.SRB_CDBLen = 6;
  210539. s.CDBByte[0] = 0x15;
  210540. s.CDBByte[4] = 0x0C;
  210541. perform (s);
  210542. }
  210543. return s.SRB_Status == SS_COMP;
  210544. }
  210545. bool read (CDReadBuffer& rb)
  210546. {
  210547. if (rb.numFrames * 2352 > rb.bufferSize)
  210548. return false;
  210549. if (! initialised)
  210550. {
  210551. initialised = init();
  210552. if (! initialised)
  210553. return false;
  210554. }
  210555. SRB_ExecSCSICmd s;
  210556. prepare (s);
  210557. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210558. s.SRB_BufLen = rb.bufferSize;
  210559. s.SRB_BufPointer = rb.buffer;
  210560. s.SRB_CDBLen = 10;
  210561. s.CDBByte[0] = 0x28;
  210562. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210563. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210564. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210565. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210566. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210567. perform (s);
  210568. if (s.SRB_Status != SS_COMP)
  210569. return false;
  210570. rb.dataLength = rb.numFrames * 2352;
  210571. rb.dataStartOffset = 0;
  210572. return true;
  210573. }
  210574. };
  210575. class ControllerType3 : public CDController
  210576. {
  210577. public:
  210578. ControllerType3() {}
  210579. bool read (CDReadBuffer& rb)
  210580. {
  210581. if (rb.numFrames * 2352 > rb.bufferSize)
  210582. return false;
  210583. if (! initialised)
  210584. {
  210585. setPaused (false);
  210586. initialised = true;
  210587. }
  210588. SRB_ExecSCSICmd s;
  210589. prepare (s);
  210590. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210591. s.SRB_BufLen = rb.numFrames * 2352;
  210592. s.SRB_BufPointer = rb.buffer;
  210593. s.SRB_CDBLen = 12;
  210594. s.CDBByte[0] = 0xD8;
  210595. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210596. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210597. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210598. s.CDBByte[9] = (BYTE) (rb.numFrames & 0xFF);
  210599. perform (s);
  210600. if (s.SRB_Status != SS_COMP)
  210601. return false;
  210602. rb.dataLength = rb.numFrames * 2352;
  210603. rb.dataStartOffset = 0;
  210604. return true;
  210605. }
  210606. };
  210607. class ControllerType4 : public CDController
  210608. {
  210609. public:
  210610. ControllerType4() {}
  210611. bool selectD4Mode()
  210612. {
  210613. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  210614. SRB_ExecSCSICmd s;
  210615. prepare (s);
  210616. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210617. s.SRB_CDBLen = 6;
  210618. s.SRB_BufLen = 12;
  210619. s.SRB_BufPointer = bufPointer;
  210620. s.CDBByte[0] = 0x15;
  210621. s.CDBByte[1] = 0x10;
  210622. s.CDBByte[4] = 0x08;
  210623. perform (s);
  210624. return s.SRB_Status == SS_COMP;
  210625. }
  210626. bool read (CDReadBuffer& rb)
  210627. {
  210628. if (rb.numFrames * 2352 > rb.bufferSize)
  210629. return false;
  210630. if (! initialised)
  210631. {
  210632. setPaused (true);
  210633. if (deviceInfo->readType == READTYPE_READ_D4_1)
  210634. selectD4Mode();
  210635. initialised = true;
  210636. }
  210637. SRB_ExecSCSICmd s;
  210638. prepare (s);
  210639. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210640. s.SRB_BufLen = rb.bufferSize;
  210641. s.SRB_BufPointer = rb.buffer;
  210642. s.SRB_CDBLen = 10;
  210643. s.CDBByte[0] = 0xD4;
  210644. s.CDBByte[3] = (BYTE) ((rb.startFrame >> 16) & 0xFF);
  210645. s.CDBByte[4] = (BYTE) ((rb.startFrame >> 8) & 0xFF);
  210646. s.CDBByte[5] = (BYTE) (rb.startFrame & 0xFF);
  210647. s.CDBByte[8] = (BYTE) (rb.numFrames & 0xFF);
  210648. perform (s);
  210649. if (s.SRB_Status != SS_COMP)
  210650. return false;
  210651. rb.dataLength = rb.numFrames * 2352;
  210652. rb.dataStartOffset = 0;
  210653. return true;
  210654. }
  210655. };
  210656. void CDController::prepare (SRB_ExecSCSICmd& s)
  210657. {
  210658. zerostruct (s);
  210659. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210660. s.SRB_HaID = deviceInfo->info.ha;
  210661. s.SRB_Target = deviceInfo->info.tgt;
  210662. s.SRB_Lun = deviceInfo->info.lun;
  210663. s.SRB_SenseLen = SENSE_LEN;
  210664. }
  210665. void CDController::perform (SRB_ExecSCSICmd& s)
  210666. {
  210667. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210668. deviceInfo->performScsiCommand (s.SRB_PostProc, s);
  210669. }
  210670. void CDController::setPaused (bool paused)
  210671. {
  210672. SRB_ExecSCSICmd s;
  210673. prepare (s);
  210674. s.SRB_Flags = SRB_EVENT_NOTIFY;
  210675. s.SRB_CDBLen = 10;
  210676. s.CDBByte[0] = 0x4B;
  210677. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  210678. perform (s);
  210679. }
  210680. bool CDController::readAudio (CDReadBuffer& rb, CDReadBuffer* overlapBuffer)
  210681. {
  210682. if (overlapBuffer != 0)
  210683. {
  210684. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  210685. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  210686. if (doJitter
  210687. && overlapBuffer->startFrame > 0
  210688. && overlapBuffer->numFrames > 0
  210689. && overlapBuffer->dataLength > 0)
  210690. {
  210691. const int numFrames = rb.numFrames;
  210692. if (overlapBuffer->startFrame == (rb.startFrame - framesToCheck))
  210693. {
  210694. rb.startFrame -= framesOverlap;
  210695. if (framesToCheck < framesOverlap
  210696. && numFrames + framesOverlap <= rb.bufferSize / 2352)
  210697. rb.numFrames += framesOverlap;
  210698. }
  210699. else
  210700. {
  210701. overlapBuffer->dataLength = 0;
  210702. overlapBuffer->startFrame = 0;
  210703. overlapBuffer->numFrames = 0;
  210704. }
  210705. }
  210706. if (! read (rb))
  210707. return false;
  210708. if (doJitter)
  210709. {
  210710. const int checkLen = framesToCheck * 2352;
  210711. const int maxToCheck = rb.dataLength - checkLen;
  210712. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  210713. return true;
  210714. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  210715. bool found = false;
  210716. for (int i = 0; i < maxToCheck; ++i)
  210717. {
  210718. if (memcmp (p, rb.buffer + i, checkLen) == 0)
  210719. {
  210720. i += checkLen;
  210721. rb.dataStartOffset = i;
  210722. rb.dataLength -= i;
  210723. rb.startFrame = overlapBuffer->startFrame + framesToCheck;
  210724. found = true;
  210725. break;
  210726. }
  210727. }
  210728. rb.numFrames = rb.dataLength / 2352;
  210729. rb.dataLength = 2352 * rb.numFrames;
  210730. if (! found)
  210731. return false;
  210732. }
  210733. if (canDoJitter)
  210734. {
  210735. memcpy (overlapBuffer->buffer,
  210736. rb.buffer + rb.dataStartOffset + 2352 * (rb.numFrames - framesToCheck),
  210737. 2352 * framesToCheck);
  210738. overlapBuffer->startFrame = rb.startFrame + rb.numFrames - framesToCheck;
  210739. overlapBuffer->numFrames = framesToCheck;
  210740. overlapBuffer->dataLength = 2352 * framesToCheck;
  210741. overlapBuffer->dataStartOffset = 0;
  210742. }
  210743. else
  210744. {
  210745. overlapBuffer->startFrame = 0;
  210746. overlapBuffer->numFrames = 0;
  210747. overlapBuffer->dataLength = 0;
  210748. }
  210749. return true;
  210750. }
  210751. return read (rb);
  210752. }
  210753. int CDController::getLastIndex()
  210754. {
  210755. char qdata[100];
  210756. SRB_ExecSCSICmd s;
  210757. prepare (s);
  210758. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210759. s.SRB_BufLen = sizeof (qdata);
  210760. s.SRB_BufPointer = (BYTE*) qdata;
  210761. s.SRB_CDBLen = 12;
  210762. s.CDBByte[0] = 0x42;
  210763. s.CDBByte[1] = (BYTE) (deviceInfo->info.lun << 5);
  210764. s.CDBByte[2] = 64;
  210765. s.CDBByte[3] = 1; // get current position
  210766. s.CDBByte[7] = 0;
  210767. s.CDBByte[8] = (BYTE) sizeof (qdata);
  210768. perform (s);
  210769. return s.SRB_Status == SS_COMP ? qdata[7] : 0;
  210770. }
  210771. bool CDDeviceHandle::readTOC (TOC* lpToc)
  210772. {
  210773. SRB_ExecSCSICmd s;
  210774. zerostruct (s);
  210775. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210776. s.SRB_HaID = info.ha;
  210777. s.SRB_Target = info.tgt;
  210778. s.SRB_Lun = info.lun;
  210779. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210780. s.SRB_BufLen = 0x324;
  210781. s.SRB_BufPointer = (BYTE*) lpToc;
  210782. s.SRB_SenseLen = 0x0E;
  210783. s.SRB_CDBLen = 0x0A;
  210784. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210785. s.CDBByte[0] = 0x43;
  210786. s.CDBByte[1] = 0x00;
  210787. s.CDBByte[7] = 0x03;
  210788. s.CDBByte[8] = 0x24;
  210789. performScsiCommand (s.SRB_PostProc, s);
  210790. return (s.SRB_Status == SS_COMP);
  210791. }
  210792. void CDDeviceHandle::performScsiCommand (HANDLE event, SRB_ExecSCSICmd& s)
  210793. {
  210794. ResetEvent (event);
  210795. DWORD status = performScsiPassThroughCommand ((SRB_ExecSCSICmd*) &s, info.scsiDriveLetter, scsiHandle, true);
  210796. if (status == SS_PENDING)
  210797. WaitForSingleObject (event, 4000);
  210798. CloseHandle (event);
  210799. }
  210800. bool CDDeviceHandle::readAudio (CDReadBuffer& buffer, CDReadBuffer* overlapBuffer)
  210801. {
  210802. if (controller == 0)
  210803. {
  210804. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  210805. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  210806. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  210807. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  210808. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  210809. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  210810. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  210811. }
  210812. buffer.index = 0;
  210813. if (controller != 0 && controller->readAudio (buffer, overlapBuffer))
  210814. {
  210815. if (buffer.wantsIndex)
  210816. buffer.index = controller->getLastIndex();
  210817. return true;
  210818. }
  210819. return false;
  210820. }
  210821. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  210822. {
  210823. if (shouldBeOpen)
  210824. {
  210825. if (controller != 0)
  210826. {
  210827. controller->shutDown();
  210828. controller = 0;
  210829. }
  210830. if (scsiHandle != 0)
  210831. {
  210832. CloseHandle (scsiHandle);
  210833. scsiHandle = 0;
  210834. }
  210835. }
  210836. SRB_ExecSCSICmd s;
  210837. zerostruct (s);
  210838. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  210839. s.SRB_HaID = info.ha;
  210840. s.SRB_Target = info.tgt;
  210841. s.SRB_Lun = info.lun;
  210842. s.SRB_SenseLen = SENSE_LEN;
  210843. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  210844. s.SRB_BufLen = 0;
  210845. s.SRB_BufPointer = 0;
  210846. s.SRB_CDBLen = 12;
  210847. s.CDBByte[0] = 0x1b;
  210848. s.CDBByte[1] = (BYTE) (info.lun << 5);
  210849. s.CDBByte[4] = (BYTE) (shouldBeOpen ? 2 : 3);
  210850. s.SRB_PostProc = CreateEvent (0, TRUE, FALSE, 0);
  210851. performScsiCommand (s.SRB_PostProc, s);
  210852. }
  210853. bool CDDeviceHandle::testController (const int type, CDController* const newController, CDReadBuffer& rb)
  210854. {
  210855. controller = newController;
  210856. readType = (BYTE) type;
  210857. controller->deviceInfo = this;
  210858. controller->framesToCheck = 1;
  210859. controller->framesOverlap = 3;
  210860. bool passed = false;
  210861. memset (rb.buffer, 0xcd, rb.bufferSize);
  210862. if (controller->read (rb))
  210863. {
  210864. passed = true;
  210865. int* p = (int*) (rb.buffer + rb.dataStartOffset);
  210866. int wrong = 0;
  210867. for (int i = rb.dataLength / 4; --i >= 0;)
  210868. {
  210869. if (*p++ == (int) 0xcdcdcdcd)
  210870. {
  210871. if (++wrong == 4)
  210872. {
  210873. passed = false;
  210874. break;
  210875. }
  210876. }
  210877. else
  210878. {
  210879. wrong = 0;
  210880. }
  210881. }
  210882. }
  210883. if (! passed)
  210884. {
  210885. controller->shutDown();
  210886. controller = 0;
  210887. }
  210888. return passed;
  210889. }
  210890. struct CDDeviceWrapper
  210891. {
  210892. CDDeviceWrapper (const CDDeviceDescription& device, HANDLE scsiHandle)
  210893. : deviceHandle (device, scsiHandle), overlapBuffer (3), jitter (false)
  210894. {
  210895. // xxx jitter never seemed to actually be enabled (??)
  210896. }
  210897. CDDeviceHandle deviceHandle;
  210898. CDReadBuffer overlapBuffer;
  210899. bool jitter;
  210900. };
  210901. int getAddressOfTrack (const TOCTRACK& t) throw()
  210902. {
  210903. return (((DWORD) t.addr[0]) << 24) + (((DWORD) t.addr[1]) << 16)
  210904. + (((DWORD) t.addr[2]) << 8) + ((DWORD) t.addr[3]);
  210905. }
  210906. const int samplesPerFrame = 44100 / 75;
  210907. const int bytesPerFrame = samplesPerFrame * 4;
  210908. const int framesPerIndexRead = 4;
  210909. }
  210910. const StringArray AudioCDReader::getAvailableCDNames()
  210911. {
  210912. using namespace CDReaderHelpers;
  210913. StringArray results;
  210914. Array<CDDeviceDescription> list;
  210915. findCDDevices (list);
  210916. for (int i = 0; i < list.size(); ++i)
  210917. {
  210918. String s;
  210919. if (list[i].scsiDriveLetter > 0)
  210920. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  210921. s << list[i].description;
  210922. results.add (s);
  210923. }
  210924. return results;
  210925. }
  210926. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  210927. {
  210928. using namespace CDReaderHelpers;
  210929. Array<CDDeviceDescription> list;
  210930. findCDDevices (list);
  210931. if (isPositiveAndBelow (deviceIndex, list.size()))
  210932. {
  210933. HANDLE h = createSCSIDeviceHandle (list [deviceIndex].scsiDriveLetter);
  210934. if (h != INVALID_HANDLE_VALUE)
  210935. return new AudioCDReader (new CDDeviceWrapper (list [deviceIndex], h));
  210936. }
  210937. return 0;
  210938. }
  210939. AudioCDReader::AudioCDReader (void* handle_)
  210940. : AudioFormatReader (0, "CD Audio"),
  210941. handle (handle_),
  210942. indexingEnabled (false),
  210943. lastIndex (0),
  210944. firstFrameInBuffer (0),
  210945. samplesInBuffer (0)
  210946. {
  210947. using namespace CDReaderHelpers;
  210948. jassert (handle_ != 0);
  210949. refreshTrackLengths();
  210950. sampleRate = 44100.0;
  210951. bitsPerSample = 16;
  210952. numChannels = 2;
  210953. usesFloatingPointData = false;
  210954. buffer.setSize (4 * bytesPerFrame, true);
  210955. }
  210956. AudioCDReader::~AudioCDReader()
  210957. {
  210958. using namespace CDReaderHelpers;
  210959. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210960. delete device;
  210961. }
  210962. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  210963. int64 startSampleInFile, int numSamples)
  210964. {
  210965. using namespace CDReaderHelpers;
  210966. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  210967. bool ok = true;
  210968. while (numSamples > 0)
  210969. {
  210970. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  210971. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  210972. if (startSampleInFile >= bufferStartSample
  210973. && startSampleInFile < bufferEndSample)
  210974. {
  210975. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  210976. int* const l = destSamples[0] + startOffsetInDestBuffer;
  210977. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  210978. const short* src = (const short*) buffer.getData();
  210979. src += 2 * (startSampleInFile - bufferStartSample);
  210980. for (int i = 0; i < toDo; ++i)
  210981. {
  210982. l[i] = src [i << 1] << 16;
  210983. if (r != 0)
  210984. r[i] = src [(i << 1) + 1] << 16;
  210985. }
  210986. startOffsetInDestBuffer += toDo;
  210987. startSampleInFile += toDo;
  210988. numSamples -= toDo;
  210989. }
  210990. else
  210991. {
  210992. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  210993. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  210994. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  210995. {
  210996. device->overlapBuffer.dataLength = 0;
  210997. device->overlapBuffer.startFrame = 0;
  210998. device->overlapBuffer.numFrames = 0;
  210999. device->jitter = false;
  211000. }
  211001. firstFrameInBuffer = frameNeeded;
  211002. lastIndex = 0;
  211003. CDReadBuffer readBuffer (framesInBuffer + 4);
  211004. readBuffer.wantsIndex = indexingEnabled;
  211005. int i;
  211006. for (i = 5; --i >= 0;)
  211007. {
  211008. readBuffer.startFrame = frameNeeded;
  211009. readBuffer.numFrames = framesInBuffer;
  211010. if (device->deviceHandle.readAudio (readBuffer, device->jitter ? &device->overlapBuffer : 0))
  211011. break;
  211012. else
  211013. device->overlapBuffer.dataLength = 0;
  211014. }
  211015. if (i >= 0)
  211016. {
  211017. buffer.copyFrom (readBuffer.buffer + readBuffer.dataStartOffset, 0, readBuffer.dataLength);
  211018. samplesInBuffer = readBuffer.dataLength >> 2;
  211019. lastIndex = readBuffer.index;
  211020. }
  211021. else
  211022. {
  211023. int* l = destSamples[0] + startOffsetInDestBuffer;
  211024. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211025. while (--numSamples >= 0)
  211026. {
  211027. *l++ = 0;
  211028. if (r != 0)
  211029. *r++ = 0;
  211030. }
  211031. // sometimes the read fails for just the very last couple of blocks, so
  211032. // we'll ignore and errors in the last half-second of the disk..
  211033. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211034. break;
  211035. }
  211036. }
  211037. }
  211038. return ok;
  211039. }
  211040. bool AudioCDReader::isCDStillPresent() const
  211041. {
  211042. using namespace CDReaderHelpers;
  211043. TOC toc;
  211044. zerostruct (toc);
  211045. return static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc);
  211046. }
  211047. void AudioCDReader::refreshTrackLengths()
  211048. {
  211049. using namespace CDReaderHelpers;
  211050. trackStartSamples.clear();
  211051. zeromem (audioTracks, sizeof (audioTracks));
  211052. TOC toc;
  211053. zerostruct (toc);
  211054. if (static_cast <CDDeviceWrapper*> (handle)->deviceHandle.readTOC (&toc))
  211055. {
  211056. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211057. for (int i = 0; i <= numTracks; ++i)
  211058. {
  211059. trackStartSamples.add (samplesPerFrame * getAddressOfTrack (toc.tracks [i]));
  211060. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211061. }
  211062. }
  211063. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211064. }
  211065. bool AudioCDReader::isTrackAudio (int trackNum) const
  211066. {
  211067. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211068. }
  211069. void AudioCDReader::enableIndexScanning (bool b)
  211070. {
  211071. indexingEnabled = b;
  211072. }
  211073. int AudioCDReader::getLastIndex() const
  211074. {
  211075. return lastIndex;
  211076. }
  211077. int AudioCDReader::getIndexAt (int samplePos)
  211078. {
  211079. using namespace CDReaderHelpers;
  211080. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211081. const int frameNeeded = samplePos / samplesPerFrame;
  211082. device->overlapBuffer.dataLength = 0;
  211083. device->overlapBuffer.startFrame = 0;
  211084. device->overlapBuffer.numFrames = 0;
  211085. device->jitter = false;
  211086. firstFrameInBuffer = 0;
  211087. lastIndex = 0;
  211088. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211089. readBuffer.wantsIndex = true;
  211090. int i;
  211091. for (i = 5; --i >= 0;)
  211092. {
  211093. readBuffer.startFrame = frameNeeded;
  211094. readBuffer.numFrames = framesPerIndexRead;
  211095. if (device->deviceHandle.readAudio (readBuffer))
  211096. break;
  211097. }
  211098. if (i >= 0)
  211099. return readBuffer.index;
  211100. return -1;
  211101. }
  211102. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211103. {
  211104. using namespace CDReaderHelpers;
  211105. Array <int> indexes;
  211106. const int trackStart = getPositionOfTrackStart (trackNumber);
  211107. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211108. bool needToScan = true;
  211109. if (trackEnd - trackStart > 20 * 44100)
  211110. {
  211111. // check the end of the track for indexes before scanning the whole thing
  211112. needToScan = false;
  211113. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211114. bool seenAnIndex = false;
  211115. while (pos <= trackEnd - samplesPerFrame)
  211116. {
  211117. const int index = getIndexAt (pos);
  211118. if (index == 0)
  211119. {
  211120. // lead-out, so skip back a bit if we've not found any indexes yet..
  211121. if (seenAnIndex)
  211122. break;
  211123. pos -= 44100 * 5;
  211124. if (pos < trackStart)
  211125. break;
  211126. }
  211127. else
  211128. {
  211129. if (index > 0)
  211130. seenAnIndex = true;
  211131. if (index > 1)
  211132. {
  211133. needToScan = true;
  211134. break;
  211135. }
  211136. pos += samplesPerFrame * framesPerIndexRead;
  211137. }
  211138. }
  211139. }
  211140. if (needToScan)
  211141. {
  211142. CDDeviceWrapper* const device = static_cast <CDDeviceWrapper*> (handle);
  211143. int pos = trackStart;
  211144. int last = -1;
  211145. while (pos < trackEnd - samplesPerFrame * 10)
  211146. {
  211147. const int frameNeeded = pos / samplesPerFrame;
  211148. device->overlapBuffer.dataLength = 0;
  211149. device->overlapBuffer.startFrame = 0;
  211150. device->overlapBuffer.numFrames = 0;
  211151. device->jitter = false;
  211152. firstFrameInBuffer = 0;
  211153. CDReadBuffer readBuffer (4);
  211154. readBuffer.wantsIndex = true;
  211155. int i;
  211156. for (i = 5; --i >= 0;)
  211157. {
  211158. readBuffer.startFrame = frameNeeded;
  211159. readBuffer.numFrames = framesPerIndexRead;
  211160. if (device->deviceHandle.readAudio (readBuffer))
  211161. break;
  211162. }
  211163. if (i < 0)
  211164. break;
  211165. if (readBuffer.index > last && readBuffer.index > 1)
  211166. {
  211167. last = readBuffer.index;
  211168. indexes.add (pos);
  211169. }
  211170. pos += samplesPerFrame * framesPerIndexRead;
  211171. }
  211172. indexes.removeValue (trackStart);
  211173. }
  211174. return indexes;
  211175. }
  211176. void AudioCDReader::ejectDisk()
  211177. {
  211178. using namespace CDReaderHelpers;
  211179. static_cast <CDDeviceWrapper*> (handle)->deviceHandle.openDrawer (true);
  211180. }
  211181. #endif
  211182. #if JUCE_USE_CDBURNER
  211183. namespace CDBurnerHelpers
  211184. {
  211185. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  211186. {
  211187. CoInitialize (0);
  211188. IDiscMaster* dm;
  211189. IDiscRecorder* result = 0;
  211190. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  211191. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  211192. IID_IDiscMaster,
  211193. (void**) &dm)))
  211194. {
  211195. if (SUCCEEDED (dm->Open()))
  211196. {
  211197. IEnumDiscRecorders* drEnum = 0;
  211198. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  211199. {
  211200. IDiscRecorder* dr = 0;
  211201. DWORD dummy;
  211202. int index = 0;
  211203. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  211204. {
  211205. if (indexToOpen == index)
  211206. {
  211207. result = dr;
  211208. break;
  211209. }
  211210. else if (list != 0)
  211211. {
  211212. BSTR path;
  211213. if (SUCCEEDED (dr->GetPath (&path)))
  211214. list->add ((const WCHAR*) path);
  211215. }
  211216. ++index;
  211217. dr->Release();
  211218. }
  211219. drEnum->Release();
  211220. }
  211221. if (master == 0)
  211222. dm->Close();
  211223. }
  211224. if (master != 0)
  211225. *master = dm;
  211226. else
  211227. dm->Release();
  211228. }
  211229. return result;
  211230. }
  211231. }
  211232. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  211233. public Timer
  211234. {
  211235. public:
  211236. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  211237. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  211238. listener (0), progress (0), shouldCancel (false)
  211239. {
  211240. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  211241. jassert (SUCCEEDED (hr));
  211242. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  211243. //jassert (SUCCEEDED (hr));
  211244. lastState = getDiskState();
  211245. startTimer (2000);
  211246. }
  211247. ~Pimpl() {}
  211248. void releaseObjects()
  211249. {
  211250. discRecorder->Close();
  211251. if (redbook != 0)
  211252. redbook->Release();
  211253. discRecorder->Release();
  211254. discMaster->Release();
  211255. Release();
  211256. }
  211257. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  211258. {
  211259. if (listener != 0 && ! shouldCancel)
  211260. shouldCancel = listener->audioCDBurnProgress (progress);
  211261. *pbCancel = shouldCancel;
  211262. return S_OK;
  211263. }
  211264. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  211265. {
  211266. progress = nCompleted / (float) nTotal;
  211267. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  211268. return E_NOTIMPL;
  211269. }
  211270. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  211271. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  211272. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  211273. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211274. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  211275. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211276. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  211277. class ScopedDiscOpener
  211278. {
  211279. public:
  211280. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  211281. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  211282. private:
  211283. Pimpl& pimpl;
  211284. JUCE_DECLARE_NON_COPYABLE (ScopedDiscOpener);
  211285. };
  211286. DiskState getDiskState()
  211287. {
  211288. const ScopedDiscOpener opener (*this);
  211289. long type, flags;
  211290. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  211291. if (FAILED (hr))
  211292. return unknown;
  211293. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  211294. return writableDiskPresent;
  211295. if (type == 0)
  211296. return noDisc;
  211297. else
  211298. return readOnlyDiskPresent;
  211299. }
  211300. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  211301. {
  211302. ComSmartPtr<IPropertyStorage> prop;
  211303. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211304. return defaultReturn;
  211305. PROPSPEC iPropSpec;
  211306. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211307. iPropSpec.lpwstr = name;
  211308. PROPVARIANT iPropVariant;
  211309. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  211310. ? defaultReturn : (int) iPropVariant.lVal;
  211311. }
  211312. bool setIntProperty (const LPOLESTR name, const int value) const
  211313. {
  211314. ComSmartPtr<IPropertyStorage> prop;
  211315. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  211316. return false;
  211317. PROPSPEC iPropSpec;
  211318. iPropSpec.ulKind = PRSPEC_LPWSTR;
  211319. iPropSpec.lpwstr = name;
  211320. PROPVARIANT iPropVariant;
  211321. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  211322. return false;
  211323. iPropVariant.lVal = (long) value;
  211324. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  211325. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  211326. }
  211327. void timerCallback()
  211328. {
  211329. const DiskState state = getDiskState();
  211330. if (state != lastState)
  211331. {
  211332. lastState = state;
  211333. owner.sendChangeMessage();
  211334. }
  211335. }
  211336. AudioCDBurner& owner;
  211337. DiskState lastState;
  211338. IDiscMaster* discMaster;
  211339. IDiscRecorder* discRecorder;
  211340. IRedbookDiscMaster* redbook;
  211341. AudioCDBurner::BurnProgressListener* listener;
  211342. float progress;
  211343. bool shouldCancel;
  211344. };
  211345. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  211346. {
  211347. IDiscMaster* discMaster = 0;
  211348. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  211349. if (discRecorder != 0)
  211350. pimpl = new Pimpl (*this, discMaster, discRecorder);
  211351. }
  211352. AudioCDBurner::~AudioCDBurner()
  211353. {
  211354. if (pimpl != 0)
  211355. pimpl.release()->releaseObjects();
  211356. }
  211357. const StringArray AudioCDBurner::findAvailableDevices()
  211358. {
  211359. StringArray devs;
  211360. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  211361. return devs;
  211362. }
  211363. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  211364. {
  211365. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  211366. if (b->pimpl == 0)
  211367. b = 0;
  211368. return b.release();
  211369. }
  211370. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  211371. {
  211372. return pimpl->getDiskState();
  211373. }
  211374. bool AudioCDBurner::isDiskPresent() const
  211375. {
  211376. return getDiskState() == writableDiskPresent;
  211377. }
  211378. bool AudioCDBurner::openTray()
  211379. {
  211380. const Pimpl::ScopedDiscOpener opener (*pimpl);
  211381. return SUCCEEDED (pimpl->discRecorder->Eject());
  211382. }
  211383. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  211384. {
  211385. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  211386. DiskState oldState = getDiskState();
  211387. DiskState newState = oldState;
  211388. while (newState == oldState && Time::currentTimeMillis() < timeout)
  211389. {
  211390. newState = getDiskState();
  211391. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  211392. }
  211393. return newState;
  211394. }
  211395. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  211396. {
  211397. Array<int> results;
  211398. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  211399. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  211400. for (int i = 0; i < numElementsInArray (speeds); ++i)
  211401. if (speeds[i] <= maxSpeed)
  211402. results.add (speeds[i]);
  211403. results.addIfNotAlreadyThere (maxSpeed);
  211404. return results;
  211405. }
  211406. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  211407. {
  211408. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  211409. return false;
  211410. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  211411. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  211412. }
  211413. int AudioCDBurner::getNumAvailableAudioBlocks() const
  211414. {
  211415. long blocksFree = 0;
  211416. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  211417. return blocksFree;
  211418. }
  211419. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  211420. bool performFakeBurnForTesting, int writeSpeed)
  211421. {
  211422. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  211423. pimpl->listener = listener;
  211424. pimpl->progress = 0;
  211425. pimpl->shouldCancel = false;
  211426. UINT_PTR cookie;
  211427. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  211428. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  211429. ejectDiscAfterwards);
  211430. String error;
  211431. if (hr != S_OK)
  211432. {
  211433. const char* e = "Couldn't open or write to the CD device";
  211434. if (hr == IMAPI_E_USERABORT)
  211435. e = "User cancelled the write operation";
  211436. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  211437. e = "No Disk present";
  211438. error = e;
  211439. }
  211440. pimpl->discMaster->ProgressUnadvise (cookie);
  211441. pimpl->listener = 0;
  211442. return error;
  211443. }
  211444. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  211445. {
  211446. if (audioSource == 0)
  211447. return false;
  211448. ScopedPointer<AudioSource> source (audioSource);
  211449. long bytesPerBlock;
  211450. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  211451. const int samplesPerBlock = bytesPerBlock / 4;
  211452. bool ok = true;
  211453. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  211454. HeapBlock <byte> buffer (bytesPerBlock);
  211455. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  211456. int samplesDone = 0;
  211457. source->prepareToPlay (samplesPerBlock, 44100.0);
  211458. while (ok)
  211459. {
  211460. {
  211461. AudioSourceChannelInfo info;
  211462. info.buffer = &sourceBuffer;
  211463. info.numSamples = samplesPerBlock;
  211464. info.startSample = 0;
  211465. sourceBuffer.clear();
  211466. source->getNextAudioBlock (info);
  211467. }
  211468. zeromem (buffer, bytesPerBlock);
  211469. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  211470. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  211471. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  211472. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  211473. CDSampleFormat left (buffer, 2);
  211474. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  211475. CDSampleFormat right (buffer + 2, 2);
  211476. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  211477. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  211478. if (FAILED (hr))
  211479. ok = false;
  211480. samplesDone += samplesPerBlock;
  211481. if (samplesDone >= numSamples)
  211482. break;
  211483. }
  211484. hr = pimpl->redbook->CloseAudioTrack();
  211485. return ok && hr == S_OK;
  211486. }
  211487. #endif
  211488. #endif
  211489. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  211490. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  211491. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211492. // compiled on its own).
  211493. #if JUCE_INCLUDED_FILE
  211494. class MidiInCollector
  211495. {
  211496. public:
  211497. MidiInCollector (MidiInput* const input_,
  211498. MidiInputCallback& callback_)
  211499. : deviceHandle (0),
  211500. input (input_),
  211501. callback (callback_),
  211502. concatenator (4096),
  211503. isStarted (false),
  211504. startTime (0)
  211505. {
  211506. }
  211507. ~MidiInCollector()
  211508. {
  211509. stop();
  211510. if (deviceHandle != 0)
  211511. {
  211512. int count = 5;
  211513. while (--count >= 0)
  211514. {
  211515. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  211516. break;
  211517. Sleep (20);
  211518. }
  211519. }
  211520. }
  211521. void handleMessage (const uint32 message, const uint32 timeStamp)
  211522. {
  211523. if ((message & 0xff) >= 0x80 && isStarted)
  211524. {
  211525. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  211526. writeFinishedBlocks();
  211527. }
  211528. }
  211529. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  211530. {
  211531. if (isStarted)
  211532. {
  211533. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  211534. writeFinishedBlocks();
  211535. }
  211536. }
  211537. void start()
  211538. {
  211539. jassert (deviceHandle != 0);
  211540. if (deviceHandle != 0 && ! isStarted)
  211541. {
  211542. activeMidiCollectors.addIfNotAlreadyThere (this);
  211543. for (int i = 0; i < (int) numHeaders; ++i)
  211544. headers[i].write (deviceHandle);
  211545. startTime = Time::getMillisecondCounter();
  211546. MMRESULT res = midiInStart (deviceHandle);
  211547. if (res == MMSYSERR_NOERROR)
  211548. {
  211549. concatenator.reset();
  211550. isStarted = true;
  211551. }
  211552. else
  211553. {
  211554. unprepareAllHeaders();
  211555. }
  211556. }
  211557. }
  211558. void stop()
  211559. {
  211560. if (isStarted)
  211561. {
  211562. isStarted = false;
  211563. midiInReset (deviceHandle);
  211564. midiInStop (deviceHandle);
  211565. activeMidiCollectors.removeValue (this);
  211566. unprepareAllHeaders();
  211567. concatenator.reset();
  211568. }
  211569. }
  211570. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  211571. {
  211572. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  211573. if (activeMidiCollectors.contains (collector))
  211574. {
  211575. if (uMsg == MIM_DATA)
  211576. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  211577. else if (uMsg == MIM_LONGDATA)
  211578. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  211579. }
  211580. }
  211581. HMIDIIN deviceHandle;
  211582. private:
  211583. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  211584. MidiInput* input;
  211585. MidiInputCallback& callback;
  211586. MidiDataConcatenator concatenator;
  211587. bool volatile isStarted;
  211588. uint32 startTime;
  211589. class MidiHeader
  211590. {
  211591. public:
  211592. MidiHeader()
  211593. {
  211594. zerostruct (hdr);
  211595. hdr.lpData = data;
  211596. hdr.dwBufferLength = numElementsInArray (data);
  211597. }
  211598. void write (HMIDIIN deviceHandle)
  211599. {
  211600. hdr.dwBytesRecorded = 0;
  211601. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211602. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  211603. }
  211604. void writeIfFinished (HMIDIIN deviceHandle)
  211605. {
  211606. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211607. {
  211608. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  211609. (void) res;
  211610. write (deviceHandle);
  211611. }
  211612. }
  211613. void unprepare (HMIDIIN deviceHandle)
  211614. {
  211615. if ((hdr.dwFlags & WHDR_DONE) != 0)
  211616. {
  211617. int c = 10;
  211618. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  211619. Thread::sleep (20);
  211620. jassert (c >= 0);
  211621. }
  211622. }
  211623. private:
  211624. MIDIHDR hdr;
  211625. char data [256];
  211626. JUCE_DECLARE_NON_COPYABLE (MidiHeader);
  211627. };
  211628. enum { numHeaders = 32 };
  211629. MidiHeader headers [numHeaders];
  211630. void writeFinishedBlocks()
  211631. {
  211632. for (int i = 0; i < (int) numHeaders; ++i)
  211633. headers[i].writeIfFinished (deviceHandle);
  211634. }
  211635. void unprepareAllHeaders()
  211636. {
  211637. for (int i = 0; i < (int) numHeaders; ++i)
  211638. headers[i].unprepare (deviceHandle);
  211639. }
  211640. double convertTimeStamp (uint32 timeStamp)
  211641. {
  211642. timeStamp += startTime;
  211643. const uint32 now = Time::getMillisecondCounter();
  211644. if (timeStamp > now)
  211645. {
  211646. if (timeStamp > now + 2)
  211647. --startTime;
  211648. timeStamp = now;
  211649. }
  211650. return timeStamp * 0.001;
  211651. }
  211652. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector);
  211653. };
  211654. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  211655. const StringArray MidiInput::getDevices()
  211656. {
  211657. StringArray s;
  211658. const int num = midiInGetNumDevs();
  211659. for (int i = 0; i < num; ++i)
  211660. {
  211661. MIDIINCAPS mc;
  211662. zerostruct (mc);
  211663. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211664. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211665. }
  211666. return s;
  211667. }
  211668. int MidiInput::getDefaultDeviceIndex()
  211669. {
  211670. return 0;
  211671. }
  211672. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  211673. {
  211674. if (callback == 0)
  211675. return 0;
  211676. UINT deviceId = MIDI_MAPPER;
  211677. int n = 0;
  211678. String name;
  211679. const int num = midiInGetNumDevs();
  211680. for (int i = 0; i < num; ++i)
  211681. {
  211682. MIDIINCAPS mc;
  211683. zerostruct (mc);
  211684. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211685. {
  211686. if (index == n)
  211687. {
  211688. deviceId = i;
  211689. name = String (mc.szPname, numElementsInArray (mc.szPname));
  211690. break;
  211691. }
  211692. ++n;
  211693. }
  211694. }
  211695. ScopedPointer <MidiInput> in (new MidiInput (name));
  211696. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  211697. HMIDIIN h;
  211698. HRESULT err = midiInOpen (&h, deviceId,
  211699. (DWORD_PTR) &MidiInCollector::midiInCallback,
  211700. (DWORD_PTR) (MidiInCollector*) collector,
  211701. CALLBACK_FUNCTION);
  211702. if (err == MMSYSERR_NOERROR)
  211703. {
  211704. collector->deviceHandle = h;
  211705. in->internal = collector.release();
  211706. return in.release();
  211707. }
  211708. return 0;
  211709. }
  211710. MidiInput::MidiInput (const String& name_)
  211711. : name (name_),
  211712. internal (0)
  211713. {
  211714. }
  211715. MidiInput::~MidiInput()
  211716. {
  211717. delete static_cast <MidiInCollector*> (internal);
  211718. }
  211719. void MidiInput::start()
  211720. {
  211721. static_cast <MidiInCollector*> (internal)->start();
  211722. }
  211723. void MidiInput::stop()
  211724. {
  211725. static_cast <MidiInCollector*> (internal)->stop();
  211726. }
  211727. struct MidiOutHandle
  211728. {
  211729. int refCount;
  211730. UINT deviceId;
  211731. HMIDIOUT handle;
  211732. static Array<MidiOutHandle*> activeHandles;
  211733. private:
  211734. JUCE_LEAK_DETECTOR (MidiOutHandle);
  211735. };
  211736. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  211737. const StringArray MidiOutput::getDevices()
  211738. {
  211739. StringArray s;
  211740. const int num = midiOutGetNumDevs();
  211741. for (int i = 0; i < num; ++i)
  211742. {
  211743. MIDIOUTCAPS mc;
  211744. zerostruct (mc);
  211745. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211746. s.add (String (mc.szPname, sizeof (mc.szPname)));
  211747. }
  211748. return s;
  211749. }
  211750. int MidiOutput::getDefaultDeviceIndex()
  211751. {
  211752. const int num = midiOutGetNumDevs();
  211753. int n = 0;
  211754. for (int i = 0; i < num; ++i)
  211755. {
  211756. MIDIOUTCAPS mc;
  211757. zerostruct (mc);
  211758. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211759. {
  211760. if ((mc.wTechnology & MOD_MAPPER) != 0)
  211761. return n;
  211762. ++n;
  211763. }
  211764. }
  211765. return 0;
  211766. }
  211767. MidiOutput* MidiOutput::openDevice (int index)
  211768. {
  211769. UINT deviceId = MIDI_MAPPER;
  211770. const int num = midiOutGetNumDevs();
  211771. int i, n = 0;
  211772. for (i = 0; i < num; ++i)
  211773. {
  211774. MIDIOUTCAPS mc;
  211775. zerostruct (mc);
  211776. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  211777. {
  211778. // use the microsoft sw synth as a default - best not to allow deviceId
  211779. // to be MIDI_MAPPER, or else device sharing breaks
  211780. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  211781. deviceId = i;
  211782. if (index == n)
  211783. {
  211784. deviceId = i;
  211785. break;
  211786. }
  211787. ++n;
  211788. }
  211789. }
  211790. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  211791. {
  211792. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  211793. if (han != 0 && han->deviceId == deviceId)
  211794. {
  211795. han->refCount++;
  211796. MidiOutput* const out = new MidiOutput();
  211797. out->internal = han;
  211798. return out;
  211799. }
  211800. }
  211801. for (i = 4; --i >= 0;)
  211802. {
  211803. HMIDIOUT h = 0;
  211804. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  211805. if (res == MMSYSERR_NOERROR)
  211806. {
  211807. MidiOutHandle* const han = new MidiOutHandle();
  211808. han->deviceId = deviceId;
  211809. han->refCount = 1;
  211810. han->handle = h;
  211811. MidiOutHandle::activeHandles.add (han);
  211812. MidiOutput* const out = new MidiOutput();
  211813. out->internal = han;
  211814. return out;
  211815. }
  211816. else if (res == MMSYSERR_ALLOCATED)
  211817. {
  211818. Sleep (100);
  211819. }
  211820. else
  211821. {
  211822. break;
  211823. }
  211824. }
  211825. return 0;
  211826. }
  211827. MidiOutput::~MidiOutput()
  211828. {
  211829. stopBackgroundThread();
  211830. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  211831. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  211832. {
  211833. midiOutClose (h->handle);
  211834. MidiOutHandle::activeHandles.removeValue (h);
  211835. delete h;
  211836. }
  211837. }
  211838. void MidiOutput::reset()
  211839. {
  211840. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  211841. midiOutReset (h->handle);
  211842. }
  211843. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211844. {
  211845. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211846. DWORD n;
  211847. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  211848. {
  211849. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  211850. rightVol = nn[0] / (float) 0xffff;
  211851. leftVol = nn[1] / (float) 0xffff;
  211852. return true;
  211853. }
  211854. else
  211855. {
  211856. rightVol = leftVol = 1.0f;
  211857. return false;
  211858. }
  211859. }
  211860. void MidiOutput::setVolume (float leftVol, float rightVol)
  211861. {
  211862. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  211863. DWORD n;
  211864. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  211865. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  211866. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  211867. midiOutSetVolume (handle->handle, n);
  211868. }
  211869. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211870. {
  211871. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  211872. if (message.getRawDataSize() > 3
  211873. || message.isSysEx())
  211874. {
  211875. MIDIHDR h;
  211876. zerostruct (h);
  211877. h.lpData = (char*) message.getRawData();
  211878. h.dwBufferLength = message.getRawDataSize();
  211879. h.dwBytesRecorded = message.getRawDataSize();
  211880. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  211881. {
  211882. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  211883. if (res == MMSYSERR_NOERROR)
  211884. {
  211885. while ((h.dwFlags & MHDR_DONE) == 0)
  211886. Sleep (1);
  211887. int count = 500; // 1 sec timeout
  211888. while (--count >= 0)
  211889. {
  211890. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  211891. if (res == MIDIERR_STILLPLAYING)
  211892. Sleep (2);
  211893. else
  211894. break;
  211895. }
  211896. }
  211897. }
  211898. }
  211899. else
  211900. {
  211901. midiOutShortMsg (handle->handle,
  211902. *(unsigned int*) message.getRawData());
  211903. }
  211904. }
  211905. #endif
  211906. /*** End of inlined file: juce_win32_Midi.cpp ***/
  211907. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  211908. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211909. // compiled on its own).
  211910. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  211911. #undef WINDOWS
  211912. // #define ASIO_DEBUGGING 1
  211913. #undef log
  211914. #if ASIO_DEBUGGING
  211915. #define log(a) { Logger::writeToLog (a); DBG (a) }
  211916. #else
  211917. #define log(a) {}
  211918. #endif
  211919. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  211920. to be pretty random about whether or not they do this. If you hit an error using these functions
  211921. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  211922. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  211923. */
  211924. #define JUCE_ASIOCALLBACK __cdecl
  211925. namespace ASIODebugging
  211926. {
  211927. #if ASIO_DEBUGGING
  211928. static void log (const String& context, long error)
  211929. {
  211930. String err ("unknown error");
  211931. if (error == ASE_NotPresent) err = "Not Present";
  211932. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  211933. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  211934. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  211935. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  211936. else if (error == ASE_NoClock) err = "No Clock";
  211937. else if (error == ASE_NoMemory) err = "Out of memory";
  211938. log ("!!error: " + context + " - " + err);
  211939. }
  211940. #define logError(a, b) ASIODebugging::log ((a), (b))
  211941. #else
  211942. #define logError(a, b) {}
  211943. #endif
  211944. }
  211945. class ASIOAudioIODevice;
  211946. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  211947. static const int maxASIOChannels = 160;
  211948. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  211949. private Timer
  211950. {
  211951. public:
  211952. Component ourWindow;
  211953. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  211954. const String& optionalDllForDirectLoading_)
  211955. : AudioIODevice (name_, "ASIO"),
  211956. asioObject (0),
  211957. classId (classId_),
  211958. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  211959. currentBitDepth (16),
  211960. currentSampleRate (0),
  211961. isOpen_ (false),
  211962. isStarted (false),
  211963. postOutput (true),
  211964. insideControlPanelModalLoop (false),
  211965. shouldUsePreferredSize (false)
  211966. {
  211967. name = name_;
  211968. ourWindow.addToDesktop (0);
  211969. windowHandle = ourWindow.getWindowHandle();
  211970. jassert (currentASIODev [slotNumber] == 0);
  211971. currentASIODev [slotNumber] = this;
  211972. openDevice();
  211973. }
  211974. ~ASIOAudioIODevice()
  211975. {
  211976. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  211977. if (currentASIODev[i] == this)
  211978. currentASIODev[i] = 0;
  211979. close();
  211980. log ("ASIO - exiting");
  211981. removeCurrentDriver();
  211982. }
  211983. void updateSampleRates()
  211984. {
  211985. // find a list of sample rates..
  211986. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  211987. sampleRates.clear();
  211988. if (asioObject != 0)
  211989. {
  211990. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  211991. {
  211992. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  211993. if (err == 0)
  211994. {
  211995. sampleRates.add ((int) possibleSampleRates[index]);
  211996. log ("rate: " + String ((int) possibleSampleRates[index]));
  211997. }
  211998. else if (err != ASE_NoClock)
  211999. {
  212000. logError ("CanSampleRate", err);
  212001. }
  212002. }
  212003. if (sampleRates.size() == 0)
  212004. {
  212005. double cr = 0;
  212006. const long err = asioObject->getSampleRate (&cr);
  212007. log ("No sample rates supported - current rate: " + String ((int) cr));
  212008. if (err == 0)
  212009. sampleRates.add ((int) cr);
  212010. }
  212011. }
  212012. }
  212013. const StringArray getOutputChannelNames() { return outputChannelNames; }
  212014. const StringArray getInputChannelNames() { return inputChannelNames; }
  212015. int getNumSampleRates() { return sampleRates.size(); }
  212016. double getSampleRate (int index) { return sampleRates [index]; }
  212017. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  212018. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  212019. int getDefaultBufferSize() { return preferredSize; }
  212020. const String open (const BigInteger& inputChannels,
  212021. const BigInteger& outputChannels,
  212022. double sr,
  212023. int bufferSizeSamples)
  212024. {
  212025. close();
  212026. currentCallback = 0;
  212027. if (bufferSizeSamples <= 0)
  212028. shouldUsePreferredSize = true;
  212029. if (asioObject == 0 || ! isASIOOpen)
  212030. {
  212031. log ("Warning: device not open");
  212032. const String err (openDevice());
  212033. if (asioObject == 0 || ! isASIOOpen)
  212034. return err;
  212035. }
  212036. isStarted = false;
  212037. bufferIndex = -1;
  212038. long err = 0;
  212039. long newPreferredSize = 0;
  212040. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212041. minSize = 0;
  212042. maxSize = 0;
  212043. newPreferredSize = 0;
  212044. granularity = 0;
  212045. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212046. {
  212047. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212048. shouldUsePreferredSize = true;
  212049. preferredSize = newPreferredSize;
  212050. }
  212051. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212052. // dynamic changes to the buffer size...
  212053. shouldUsePreferredSize = shouldUsePreferredSize
  212054. || getName().containsIgnoreCase ("Digidesign");
  212055. if (shouldUsePreferredSize)
  212056. {
  212057. log ("Using preferred size for buffer..");
  212058. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212059. {
  212060. bufferSizeSamples = preferredSize;
  212061. }
  212062. else
  212063. {
  212064. bufferSizeSamples = 1024;
  212065. logError ("GetBufferSize1", err);
  212066. }
  212067. shouldUsePreferredSize = false;
  212068. }
  212069. int sampleRate = roundDoubleToInt (sr);
  212070. currentSampleRate = sampleRate;
  212071. currentBlockSizeSamples = bufferSizeSamples;
  212072. currentChansOut.clear();
  212073. currentChansIn.clear();
  212074. zeromem (inBuffers, sizeof (inBuffers));
  212075. zeromem (outBuffers, sizeof (outBuffers));
  212076. updateSampleRates();
  212077. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212078. sampleRate = sampleRates[0];
  212079. jassert (sampleRate != 0);
  212080. if (sampleRate == 0)
  212081. sampleRate = 44100;
  212082. long numSources = 32;
  212083. ASIOClockSource clocks[32];
  212084. zeromem (clocks, sizeof (clocks));
  212085. asioObject->getClockSources (clocks, &numSources);
  212086. bool isSourceSet = false;
  212087. // careful not to remove this loop because it does more than just logging!
  212088. int i;
  212089. for (i = 0; i < numSources; ++i)
  212090. {
  212091. String s ("clock: ");
  212092. s += clocks[i].name;
  212093. if (clocks[i].isCurrentSource)
  212094. {
  212095. isSourceSet = true;
  212096. s << " (cur)";
  212097. }
  212098. log (s);
  212099. }
  212100. if (numSources > 1 && ! isSourceSet)
  212101. {
  212102. log ("setting clock source");
  212103. asioObject->setClockSource (clocks[0].index);
  212104. Thread::sleep (20);
  212105. }
  212106. else
  212107. {
  212108. if (numSources == 0)
  212109. {
  212110. log ("ASIO - no clock sources!");
  212111. }
  212112. }
  212113. double cr = 0;
  212114. err = asioObject->getSampleRate (&cr);
  212115. if (err == 0)
  212116. {
  212117. currentSampleRate = cr;
  212118. }
  212119. else
  212120. {
  212121. logError ("GetSampleRate", err);
  212122. currentSampleRate = 0;
  212123. }
  212124. error = String::empty;
  212125. needToReset = false;
  212126. isReSync = false;
  212127. err = 0;
  212128. bool buffersCreated = false;
  212129. if (currentSampleRate != sampleRate)
  212130. {
  212131. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212132. err = asioObject->setSampleRate (sampleRate);
  212133. if (err == ASE_NoClock && numSources > 0)
  212134. {
  212135. log ("trying to set a clock source..");
  212136. Thread::sleep (10);
  212137. err = asioObject->setClockSource (clocks[0].index);
  212138. if (err != 0)
  212139. {
  212140. logError ("SetClock", err);
  212141. }
  212142. Thread::sleep (10);
  212143. err = asioObject->setSampleRate (sampleRate);
  212144. }
  212145. }
  212146. if (err == 0)
  212147. {
  212148. currentSampleRate = sampleRate;
  212149. if (needToReset)
  212150. {
  212151. if (isReSync)
  212152. {
  212153. log ("Resync request");
  212154. }
  212155. log ("! Resetting ASIO after sample rate change");
  212156. removeCurrentDriver();
  212157. loadDriver();
  212158. const String error (initDriver());
  212159. if (error.isNotEmpty())
  212160. {
  212161. log ("ASIOInit: " + error);
  212162. }
  212163. needToReset = false;
  212164. isReSync = false;
  212165. }
  212166. numActiveInputChans = 0;
  212167. numActiveOutputChans = 0;
  212168. ASIOBufferInfo* info = bufferInfos;
  212169. int i;
  212170. for (i = 0; i < totalNumInputChans; ++i)
  212171. {
  212172. if (inputChannels[i])
  212173. {
  212174. currentChansIn.setBit (i);
  212175. info->isInput = 1;
  212176. info->channelNum = i;
  212177. info->buffers[0] = info->buffers[1] = 0;
  212178. ++info;
  212179. ++numActiveInputChans;
  212180. }
  212181. }
  212182. for (i = 0; i < totalNumOutputChans; ++i)
  212183. {
  212184. if (outputChannels[i])
  212185. {
  212186. currentChansOut.setBit (i);
  212187. info->isInput = 0;
  212188. info->channelNum = i;
  212189. info->buffers[0] = info->buffers[1] = 0;
  212190. ++info;
  212191. ++numActiveOutputChans;
  212192. }
  212193. }
  212194. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  212195. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212196. if (currentASIODev[0] == this)
  212197. {
  212198. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212199. callbacks.asioMessage = &asioMessagesCallback0;
  212200. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212201. }
  212202. else if (currentASIODev[1] == this)
  212203. {
  212204. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212205. callbacks.asioMessage = &asioMessagesCallback1;
  212206. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212207. }
  212208. else if (currentASIODev[2] == this)
  212209. {
  212210. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212211. callbacks.asioMessage = &asioMessagesCallback2;
  212212. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212213. }
  212214. else
  212215. {
  212216. jassertfalse;
  212217. }
  212218. log ("disposing buffers");
  212219. err = asioObject->disposeBuffers();
  212220. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  212221. err = asioObject->createBuffers (bufferInfos,
  212222. totalBuffers,
  212223. currentBlockSizeSamples,
  212224. &callbacks);
  212225. if (err != 0)
  212226. {
  212227. currentBlockSizeSamples = preferredSize;
  212228. logError ("create buffers 2", err);
  212229. asioObject->disposeBuffers();
  212230. err = asioObject->createBuffers (bufferInfos,
  212231. totalBuffers,
  212232. currentBlockSizeSamples,
  212233. &callbacks);
  212234. }
  212235. if (err == 0)
  212236. {
  212237. buffersCreated = true;
  212238. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  212239. int n = 0;
  212240. Array <int> types;
  212241. currentBitDepth = 16;
  212242. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  212243. {
  212244. if (inputChannels[i])
  212245. {
  212246. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  212247. ASIOChannelInfo channelInfo;
  212248. zerostruct (channelInfo);
  212249. channelInfo.channel = i;
  212250. channelInfo.isInput = 1;
  212251. asioObject->getChannelInfo (&channelInfo);
  212252. types.addIfNotAlreadyThere (channelInfo.type);
  212253. typeToFormatParameters (channelInfo.type,
  212254. inputChannelBitDepths[n],
  212255. inputChannelBytesPerSample[n],
  212256. inputChannelIsFloat[n],
  212257. inputChannelLittleEndian[n]);
  212258. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  212259. ++n;
  212260. }
  212261. }
  212262. jassert (numActiveInputChans == n);
  212263. n = 0;
  212264. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  212265. {
  212266. if (outputChannels[i])
  212267. {
  212268. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  212269. ASIOChannelInfo channelInfo;
  212270. zerostruct (channelInfo);
  212271. channelInfo.channel = i;
  212272. channelInfo.isInput = 0;
  212273. asioObject->getChannelInfo (&channelInfo);
  212274. types.addIfNotAlreadyThere (channelInfo.type);
  212275. typeToFormatParameters (channelInfo.type,
  212276. outputChannelBitDepths[n],
  212277. outputChannelBytesPerSample[n],
  212278. outputChannelIsFloat[n],
  212279. outputChannelLittleEndian[n]);
  212280. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  212281. ++n;
  212282. }
  212283. }
  212284. jassert (numActiveOutputChans == n);
  212285. for (i = types.size(); --i >= 0;)
  212286. {
  212287. log ("channel format: " + String (types[i]));
  212288. }
  212289. jassert (n <= totalBuffers);
  212290. for (i = 0; i < numActiveOutputChans; ++i)
  212291. {
  212292. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  212293. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  212294. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  212295. {
  212296. log ("!! Null buffers");
  212297. }
  212298. else
  212299. {
  212300. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  212301. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  212302. }
  212303. }
  212304. inputLatency = outputLatency = 0;
  212305. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212306. {
  212307. log ("ASIO - no latencies");
  212308. }
  212309. else
  212310. {
  212311. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  212312. }
  212313. isOpen_ = true;
  212314. log ("starting ASIO");
  212315. calledback = false;
  212316. err = asioObject->start();
  212317. if (err != 0)
  212318. {
  212319. isOpen_ = false;
  212320. log ("ASIO - stop on failure");
  212321. Thread::sleep (10);
  212322. asioObject->stop();
  212323. error = "Can't start device";
  212324. Thread::sleep (10);
  212325. }
  212326. else
  212327. {
  212328. int count = 300;
  212329. while (--count > 0 && ! calledback)
  212330. Thread::sleep (10);
  212331. isStarted = true;
  212332. if (! calledback)
  212333. {
  212334. error = "Device didn't start correctly";
  212335. log ("ASIO didn't callback - stopping..");
  212336. asioObject->stop();
  212337. }
  212338. }
  212339. }
  212340. else
  212341. {
  212342. error = "Can't create i/o buffers";
  212343. }
  212344. }
  212345. else
  212346. {
  212347. error = "Can't set sample rate: ";
  212348. error << sampleRate;
  212349. }
  212350. if (error.isNotEmpty())
  212351. {
  212352. logError (error, err);
  212353. if (asioObject != 0 && buffersCreated)
  212354. asioObject->disposeBuffers();
  212355. Thread::sleep (20);
  212356. isStarted = false;
  212357. isOpen_ = false;
  212358. const String errorCopy (error);
  212359. close(); // (this resets the error string)
  212360. error = errorCopy;
  212361. }
  212362. needToReset = false;
  212363. isReSync = false;
  212364. return error;
  212365. }
  212366. void close()
  212367. {
  212368. error = String::empty;
  212369. stopTimer();
  212370. stop();
  212371. if (isASIOOpen && isOpen_)
  212372. {
  212373. const ScopedLock sl (callbackLock);
  212374. isOpen_ = false;
  212375. isStarted = false;
  212376. needToReset = false;
  212377. isReSync = false;
  212378. log ("ASIO - stopping");
  212379. if (asioObject != 0)
  212380. {
  212381. Thread::sleep (20);
  212382. asioObject->stop();
  212383. Thread::sleep (10);
  212384. asioObject->disposeBuffers();
  212385. }
  212386. Thread::sleep (10);
  212387. }
  212388. }
  212389. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  212390. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  212391. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  212392. double getCurrentSampleRate() { return currentSampleRate; }
  212393. int getCurrentBitDepth() { return currentBitDepth; }
  212394. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  212395. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  212396. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  212397. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  212398. void start (AudioIODeviceCallback* callback)
  212399. {
  212400. if (callback != 0)
  212401. {
  212402. callback->audioDeviceAboutToStart (this);
  212403. const ScopedLock sl (callbackLock);
  212404. currentCallback = callback;
  212405. }
  212406. }
  212407. void stop()
  212408. {
  212409. AudioIODeviceCallback* const lastCallback = currentCallback;
  212410. {
  212411. const ScopedLock sl (callbackLock);
  212412. currentCallback = 0;
  212413. }
  212414. if (lastCallback != 0)
  212415. lastCallback->audioDeviceStopped();
  212416. }
  212417. const String getLastError() { return error; }
  212418. bool hasControlPanel() const { return true; }
  212419. bool showControlPanel()
  212420. {
  212421. log ("ASIO - showing control panel");
  212422. Component modalWindow (String::empty);
  212423. modalWindow.setOpaque (true);
  212424. modalWindow.addToDesktop (0);
  212425. modalWindow.enterModalState();
  212426. bool done = false;
  212427. JUCE_TRY
  212428. {
  212429. // are there are devices that need to be closed before showing their control panel?
  212430. // close();
  212431. insideControlPanelModalLoop = true;
  212432. const uint32 started = Time::getMillisecondCounter();
  212433. if (asioObject != 0)
  212434. {
  212435. asioObject->controlPanel();
  212436. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  212437. log ("spent: " + String (spent));
  212438. if (spent > 300)
  212439. {
  212440. shouldUsePreferredSize = true;
  212441. done = true;
  212442. }
  212443. }
  212444. }
  212445. JUCE_CATCH_ALL
  212446. insideControlPanelModalLoop = false;
  212447. return done;
  212448. }
  212449. void resetRequest() throw()
  212450. {
  212451. needToReset = true;
  212452. }
  212453. void resyncRequest() throw()
  212454. {
  212455. needToReset = true;
  212456. isReSync = true;
  212457. }
  212458. void timerCallback()
  212459. {
  212460. if (! insideControlPanelModalLoop)
  212461. {
  212462. stopTimer();
  212463. // used to cause a reset
  212464. log ("! ASIO restart request!");
  212465. if (isOpen_)
  212466. {
  212467. AudioIODeviceCallback* const oldCallback = currentCallback;
  212468. close();
  212469. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  212470. currentSampleRate, currentBlockSizeSamples);
  212471. if (oldCallback != 0)
  212472. start (oldCallback);
  212473. }
  212474. }
  212475. else
  212476. {
  212477. startTimer (100);
  212478. }
  212479. }
  212480. private:
  212481. IASIO* volatile asioObject;
  212482. ASIOCallbacks callbacks;
  212483. void* windowHandle;
  212484. CLSID classId;
  212485. const String optionalDllForDirectLoading;
  212486. String error;
  212487. long totalNumInputChans, totalNumOutputChans;
  212488. StringArray inputChannelNames, outputChannelNames;
  212489. Array<int> sampleRates, bufferSizes;
  212490. long inputLatency, outputLatency;
  212491. long minSize, maxSize, preferredSize, granularity;
  212492. int volatile currentBlockSizeSamples;
  212493. int volatile currentBitDepth;
  212494. double volatile currentSampleRate;
  212495. BigInteger currentChansOut, currentChansIn;
  212496. AudioIODeviceCallback* volatile currentCallback;
  212497. CriticalSection callbackLock;
  212498. ASIOBufferInfo bufferInfos [maxASIOChannels];
  212499. float* inBuffers [maxASIOChannels];
  212500. float* outBuffers [maxASIOChannels];
  212501. int inputChannelBitDepths [maxASIOChannels];
  212502. int outputChannelBitDepths [maxASIOChannels];
  212503. int inputChannelBytesPerSample [maxASIOChannels];
  212504. int outputChannelBytesPerSample [maxASIOChannels];
  212505. bool inputChannelIsFloat [maxASIOChannels];
  212506. bool outputChannelIsFloat [maxASIOChannels];
  212507. bool inputChannelLittleEndian [maxASIOChannels];
  212508. bool outputChannelLittleEndian [maxASIOChannels];
  212509. WaitableEvent event1;
  212510. HeapBlock <float> tempBuffer;
  212511. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  212512. bool isOpen_, isStarted;
  212513. bool volatile isASIOOpen;
  212514. bool volatile calledback;
  212515. bool volatile littleEndian, postOutput, needToReset, isReSync;
  212516. bool volatile insideControlPanelModalLoop;
  212517. bool volatile shouldUsePreferredSize;
  212518. void removeCurrentDriver()
  212519. {
  212520. if (asioObject != 0)
  212521. {
  212522. asioObject->Release();
  212523. asioObject = 0;
  212524. }
  212525. }
  212526. bool loadDriver()
  212527. {
  212528. removeCurrentDriver();
  212529. JUCE_TRY
  212530. {
  212531. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  212532. classId, (void**) &asioObject) == S_OK)
  212533. {
  212534. return true;
  212535. }
  212536. // If a class isn't registered but we have a path for it, we can fallback to
  212537. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  212538. if (optionalDllForDirectLoading.isNotEmpty())
  212539. {
  212540. HMODULE h = LoadLibrary (optionalDllForDirectLoading.toUTF16());
  212541. if (h != 0)
  212542. {
  212543. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  212544. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  212545. if (dllGetClassObject != 0)
  212546. {
  212547. IClassFactory* classFactory = 0;
  212548. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  212549. if (classFactory != 0)
  212550. {
  212551. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  212552. classFactory->Release();
  212553. }
  212554. return asioObject != 0;
  212555. }
  212556. }
  212557. }
  212558. }
  212559. JUCE_CATCH_ALL
  212560. asioObject = 0;
  212561. return false;
  212562. }
  212563. const String initDriver()
  212564. {
  212565. if (asioObject != 0)
  212566. {
  212567. char buffer [256];
  212568. zeromem (buffer, sizeof (buffer));
  212569. if (! asioObject->init (windowHandle))
  212570. {
  212571. asioObject->getErrorMessage (buffer);
  212572. return String (buffer, sizeof (buffer) - 1);
  212573. }
  212574. // just in case any daft drivers expect this to be called..
  212575. asioObject->getDriverName (buffer);
  212576. return String::empty;
  212577. }
  212578. return "No Driver";
  212579. }
  212580. const String openDevice()
  212581. {
  212582. // use this in case the driver starts opening dialog boxes..
  212583. Component modalWindow (String::empty);
  212584. modalWindow.setOpaque (true);
  212585. modalWindow.addToDesktop (0);
  212586. modalWindow.enterModalState();
  212587. // open the device and get its info..
  212588. log ("opening ASIO device: " + getName());
  212589. needToReset = false;
  212590. isReSync = false;
  212591. outputChannelNames.clear();
  212592. inputChannelNames.clear();
  212593. bufferSizes.clear();
  212594. sampleRates.clear();
  212595. isASIOOpen = false;
  212596. isOpen_ = false;
  212597. totalNumInputChans = 0;
  212598. totalNumOutputChans = 0;
  212599. numActiveInputChans = 0;
  212600. numActiveOutputChans = 0;
  212601. currentCallback = 0;
  212602. error = String::empty;
  212603. if (getName().isEmpty())
  212604. return error;
  212605. long err = 0;
  212606. if (loadDriver())
  212607. {
  212608. if ((error = initDriver()).isEmpty())
  212609. {
  212610. numActiveInputChans = 0;
  212611. numActiveOutputChans = 0;
  212612. totalNumInputChans = 0;
  212613. totalNumOutputChans = 0;
  212614. if (asioObject != 0
  212615. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  212616. {
  212617. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  212618. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212619. {
  212620. // find a list of buffer sizes..
  212621. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  212622. if (granularity >= 0)
  212623. {
  212624. granularity = jmax (1, (int) granularity);
  212625. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  212626. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  212627. }
  212628. else if (granularity < 0)
  212629. {
  212630. for (int i = 0; i < 18; ++i)
  212631. {
  212632. const int s = (1 << i);
  212633. if (s >= minSize && s <= maxSize)
  212634. bufferSizes.add (s);
  212635. }
  212636. }
  212637. if (! bufferSizes.contains (preferredSize))
  212638. bufferSizes.insert (0, preferredSize);
  212639. double currentRate = 0;
  212640. asioObject->getSampleRate (&currentRate);
  212641. if (currentRate <= 0.0 || currentRate > 192001.0)
  212642. {
  212643. log ("setting sample rate");
  212644. err = asioObject->setSampleRate (44100.0);
  212645. if (err != 0)
  212646. {
  212647. logError ("setting sample rate", err);
  212648. }
  212649. asioObject->getSampleRate (&currentRate);
  212650. }
  212651. currentSampleRate = currentRate;
  212652. postOutput = (asioObject->outputReady() == 0);
  212653. if (postOutput)
  212654. {
  212655. log ("ASIO outputReady = ok");
  212656. }
  212657. updateSampleRates();
  212658. // ..because cubase does it at this point
  212659. inputLatency = outputLatency = 0;
  212660. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  212661. {
  212662. log ("ASIO - no latencies");
  212663. }
  212664. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  212665. // create some dummy buffers now.. because cubase does..
  212666. numActiveInputChans = 0;
  212667. numActiveOutputChans = 0;
  212668. ASIOBufferInfo* info = bufferInfos;
  212669. int i, numChans = 0;
  212670. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  212671. {
  212672. info->isInput = 1;
  212673. info->channelNum = i;
  212674. info->buffers[0] = info->buffers[1] = 0;
  212675. ++info;
  212676. ++numChans;
  212677. }
  212678. const int outputBufferIndex = numChans;
  212679. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  212680. {
  212681. info->isInput = 0;
  212682. info->channelNum = i;
  212683. info->buffers[0] = info->buffers[1] = 0;
  212684. ++info;
  212685. ++numChans;
  212686. }
  212687. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  212688. if (currentASIODev[0] == this)
  212689. {
  212690. callbacks.bufferSwitch = &bufferSwitchCallback0;
  212691. callbacks.asioMessage = &asioMessagesCallback0;
  212692. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  212693. }
  212694. else if (currentASIODev[1] == this)
  212695. {
  212696. callbacks.bufferSwitch = &bufferSwitchCallback1;
  212697. callbacks.asioMessage = &asioMessagesCallback1;
  212698. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  212699. }
  212700. else if (currentASIODev[2] == this)
  212701. {
  212702. callbacks.bufferSwitch = &bufferSwitchCallback2;
  212703. callbacks.asioMessage = &asioMessagesCallback2;
  212704. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  212705. }
  212706. else
  212707. {
  212708. jassertfalse;
  212709. }
  212710. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  212711. if (preferredSize > 0)
  212712. {
  212713. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  212714. if (err != 0)
  212715. {
  212716. logError ("dummy buffers", err);
  212717. }
  212718. }
  212719. long newInps = 0, newOuts = 0;
  212720. asioObject->getChannels (&newInps, &newOuts);
  212721. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  212722. {
  212723. totalNumInputChans = newInps;
  212724. totalNumOutputChans = newOuts;
  212725. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  212726. }
  212727. updateSampleRates();
  212728. ASIOChannelInfo channelInfo;
  212729. channelInfo.type = 0;
  212730. for (i = 0; i < totalNumInputChans; ++i)
  212731. {
  212732. zerostruct (channelInfo);
  212733. channelInfo.channel = i;
  212734. channelInfo.isInput = 1;
  212735. asioObject->getChannelInfo (&channelInfo);
  212736. inputChannelNames.add (String (channelInfo.name));
  212737. }
  212738. for (i = 0; i < totalNumOutputChans; ++i)
  212739. {
  212740. zerostruct (channelInfo);
  212741. channelInfo.channel = i;
  212742. channelInfo.isInput = 0;
  212743. asioObject->getChannelInfo (&channelInfo);
  212744. outputChannelNames.add (String (channelInfo.name));
  212745. typeToFormatParameters (channelInfo.type,
  212746. outputChannelBitDepths[i],
  212747. outputChannelBytesPerSample[i],
  212748. outputChannelIsFloat[i],
  212749. outputChannelLittleEndian[i]);
  212750. if (i < 2)
  212751. {
  212752. // clear the channels that are used with the dummy stuff
  212753. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  212754. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  212755. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  212756. }
  212757. }
  212758. outputChannelNames.trim();
  212759. inputChannelNames.trim();
  212760. outputChannelNames.appendNumbersToDuplicates (false, true);
  212761. inputChannelNames.appendNumbersToDuplicates (false, true);
  212762. // start and stop because cubase does it..
  212763. asioObject->getLatencies (&inputLatency, &outputLatency);
  212764. if ((err = asioObject->start()) != 0)
  212765. {
  212766. // ignore an error here, as it might start later after setting other stuff up
  212767. logError ("ASIO start", err);
  212768. }
  212769. Thread::sleep (100);
  212770. asioObject->stop();
  212771. }
  212772. else
  212773. {
  212774. error = "Can't detect buffer sizes";
  212775. }
  212776. }
  212777. else
  212778. {
  212779. error = "Can't detect asio channels";
  212780. }
  212781. }
  212782. }
  212783. else
  212784. {
  212785. error = "No such device";
  212786. }
  212787. if (error.isNotEmpty())
  212788. {
  212789. logError (error, err);
  212790. if (asioObject != 0)
  212791. asioObject->disposeBuffers();
  212792. removeCurrentDriver();
  212793. isASIOOpen = false;
  212794. }
  212795. else
  212796. {
  212797. isASIOOpen = true;
  212798. log ("ASIO device open");
  212799. }
  212800. isOpen_ = false;
  212801. needToReset = false;
  212802. isReSync = false;
  212803. return error;
  212804. }
  212805. void JUCE_ASIOCALLBACK callback (const long index)
  212806. {
  212807. if (isStarted)
  212808. {
  212809. bufferIndex = index;
  212810. processBuffer();
  212811. }
  212812. else
  212813. {
  212814. if (postOutput && (asioObject != 0))
  212815. asioObject->outputReady();
  212816. }
  212817. calledback = true;
  212818. }
  212819. void processBuffer()
  212820. {
  212821. const ASIOBufferInfo* const infos = bufferInfos;
  212822. const int bi = bufferIndex;
  212823. const ScopedLock sl (callbackLock);
  212824. if (needToReset)
  212825. {
  212826. needToReset = false;
  212827. if (isReSync)
  212828. {
  212829. log ("! ASIO resync");
  212830. isReSync = false;
  212831. }
  212832. else
  212833. {
  212834. startTimer (20);
  212835. }
  212836. }
  212837. if (bi >= 0)
  212838. {
  212839. const int samps = currentBlockSizeSamples;
  212840. if (currentCallback != 0)
  212841. {
  212842. int i;
  212843. for (i = 0; i < numActiveInputChans; ++i)
  212844. {
  212845. float* const dst = inBuffers[i];
  212846. jassert (dst != 0);
  212847. const char* const src = (const char*) (infos[i].buffers[bi]);
  212848. if (inputChannelIsFloat[i])
  212849. {
  212850. memcpy (dst, src, samps * sizeof (float));
  212851. }
  212852. else
  212853. {
  212854. jassert (dst == tempBuffer + (samps * i));
  212855. switch (inputChannelBitDepths[i])
  212856. {
  212857. case 16:
  212858. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  212859. samps, inputChannelLittleEndian[i]);
  212860. break;
  212861. case 24:
  212862. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  212863. samps, inputChannelLittleEndian[i]);
  212864. break;
  212865. case 32:
  212866. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  212867. samps, inputChannelLittleEndian[i]);
  212868. break;
  212869. case 64:
  212870. jassertfalse;
  212871. break;
  212872. }
  212873. }
  212874. }
  212875. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  212876. outBuffers, numActiveOutputChans, samps);
  212877. for (i = 0; i < numActiveOutputChans; ++i)
  212878. {
  212879. float* const src = outBuffers[i];
  212880. jassert (src != 0);
  212881. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  212882. if (outputChannelIsFloat[i])
  212883. {
  212884. memcpy (dst, src, samps * sizeof (float));
  212885. }
  212886. else
  212887. {
  212888. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  212889. switch (outputChannelBitDepths[i])
  212890. {
  212891. case 16:
  212892. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  212893. samps, outputChannelLittleEndian[i]);
  212894. break;
  212895. case 24:
  212896. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  212897. samps, outputChannelLittleEndian[i]);
  212898. break;
  212899. case 32:
  212900. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  212901. samps, outputChannelLittleEndian[i]);
  212902. break;
  212903. case 64:
  212904. jassertfalse;
  212905. break;
  212906. }
  212907. }
  212908. }
  212909. }
  212910. else
  212911. {
  212912. for (int i = 0; i < numActiveOutputChans; ++i)
  212913. {
  212914. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  212915. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  212916. }
  212917. }
  212918. }
  212919. if (postOutput)
  212920. asioObject->outputReady();
  212921. }
  212922. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  212923. {
  212924. if (currentASIODev[0] != 0)
  212925. currentASIODev[0]->callback (index);
  212926. return 0;
  212927. }
  212928. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  212929. {
  212930. if (currentASIODev[1] != 0)
  212931. currentASIODev[1]->callback (index);
  212932. return 0;
  212933. }
  212934. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  212935. {
  212936. if (currentASIODev[2] != 0)
  212937. currentASIODev[2]->callback (index);
  212938. return 0;
  212939. }
  212940. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  212941. {
  212942. if (currentASIODev[0] != 0)
  212943. currentASIODev[0]->callback (index);
  212944. }
  212945. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  212946. {
  212947. if (currentASIODev[1] != 0)
  212948. currentASIODev[1]->callback (index);
  212949. }
  212950. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  212951. {
  212952. if (currentASIODev[2] != 0)
  212953. currentASIODev[2]->callback (index);
  212954. }
  212955. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  212956. {
  212957. return asioMessagesCallback (selector, value, 0);
  212958. }
  212959. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  212960. {
  212961. return asioMessagesCallback (selector, value, 1);
  212962. }
  212963. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  212964. {
  212965. return asioMessagesCallback (selector, value, 2);
  212966. }
  212967. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  212968. {
  212969. switch (selector)
  212970. {
  212971. case kAsioSelectorSupported:
  212972. if (value == kAsioResetRequest
  212973. || value == kAsioEngineVersion
  212974. || value == kAsioResyncRequest
  212975. || value == kAsioLatenciesChanged
  212976. || value == kAsioSupportsInputMonitor)
  212977. return 1;
  212978. break;
  212979. case kAsioBufferSizeChange:
  212980. break;
  212981. case kAsioResetRequest:
  212982. if (currentASIODev[deviceIndex] != 0)
  212983. currentASIODev[deviceIndex]->resetRequest();
  212984. return 1;
  212985. case kAsioResyncRequest:
  212986. if (currentASIODev[deviceIndex] != 0)
  212987. currentASIODev[deviceIndex]->resyncRequest();
  212988. return 1;
  212989. case kAsioLatenciesChanged:
  212990. return 1;
  212991. case kAsioEngineVersion:
  212992. return 2;
  212993. case kAsioSupportsTimeInfo:
  212994. case kAsioSupportsTimeCode:
  212995. return 0;
  212996. }
  212997. return 0;
  212998. }
  212999. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  213000. {
  213001. }
  213002. static void convertInt16ToFloat (const char* src,
  213003. float* dest,
  213004. const int srcStrideBytes,
  213005. int numSamples,
  213006. const bool littleEndian) throw()
  213007. {
  213008. const double g = 1.0 / 32768.0;
  213009. if (littleEndian)
  213010. {
  213011. while (--numSamples >= 0)
  213012. {
  213013. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213014. src += srcStrideBytes;
  213015. }
  213016. }
  213017. else
  213018. {
  213019. while (--numSamples >= 0)
  213020. {
  213021. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213022. src += srcStrideBytes;
  213023. }
  213024. }
  213025. }
  213026. static void convertFloatToInt16 (const float* src,
  213027. char* dest,
  213028. const int dstStrideBytes,
  213029. int numSamples,
  213030. const bool littleEndian) throw()
  213031. {
  213032. const double maxVal = (double) 0x7fff;
  213033. if (littleEndian)
  213034. {
  213035. while (--numSamples >= 0)
  213036. {
  213037. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213038. dest += dstStrideBytes;
  213039. }
  213040. }
  213041. else
  213042. {
  213043. while (--numSamples >= 0)
  213044. {
  213045. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213046. dest += dstStrideBytes;
  213047. }
  213048. }
  213049. }
  213050. static void convertInt24ToFloat (const char* src,
  213051. float* dest,
  213052. const int srcStrideBytes,
  213053. int numSamples,
  213054. const bool littleEndian) throw()
  213055. {
  213056. const double g = 1.0 / 0x7fffff;
  213057. if (littleEndian)
  213058. {
  213059. while (--numSamples >= 0)
  213060. {
  213061. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213062. src += srcStrideBytes;
  213063. }
  213064. }
  213065. else
  213066. {
  213067. while (--numSamples >= 0)
  213068. {
  213069. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213070. src += srcStrideBytes;
  213071. }
  213072. }
  213073. }
  213074. static void convertFloatToInt24 (const float* src,
  213075. char* dest,
  213076. const int dstStrideBytes,
  213077. int numSamples,
  213078. const bool littleEndian) throw()
  213079. {
  213080. const double maxVal = (double) 0x7fffff;
  213081. if (littleEndian)
  213082. {
  213083. while (--numSamples >= 0)
  213084. {
  213085. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213086. dest += dstStrideBytes;
  213087. }
  213088. }
  213089. else
  213090. {
  213091. while (--numSamples >= 0)
  213092. {
  213093. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213094. dest += dstStrideBytes;
  213095. }
  213096. }
  213097. }
  213098. static void convertInt32ToFloat (const char* src,
  213099. float* dest,
  213100. const int srcStrideBytes,
  213101. int numSamples,
  213102. const bool littleEndian) throw()
  213103. {
  213104. const double g = 1.0 / 0x7fffffff;
  213105. if (littleEndian)
  213106. {
  213107. while (--numSamples >= 0)
  213108. {
  213109. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213110. src += srcStrideBytes;
  213111. }
  213112. }
  213113. else
  213114. {
  213115. while (--numSamples >= 0)
  213116. {
  213117. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213118. src += srcStrideBytes;
  213119. }
  213120. }
  213121. }
  213122. static void convertFloatToInt32 (const float* src,
  213123. char* dest,
  213124. const int dstStrideBytes,
  213125. int numSamples,
  213126. const bool littleEndian) throw()
  213127. {
  213128. const double maxVal = (double) 0x7fffffff;
  213129. if (littleEndian)
  213130. {
  213131. while (--numSamples >= 0)
  213132. {
  213133. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213134. dest += dstStrideBytes;
  213135. }
  213136. }
  213137. else
  213138. {
  213139. while (--numSamples >= 0)
  213140. {
  213141. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213142. dest += dstStrideBytes;
  213143. }
  213144. }
  213145. }
  213146. static void typeToFormatParameters (const long type,
  213147. int& bitDepth,
  213148. int& byteStride,
  213149. bool& formatIsFloat,
  213150. bool& littleEndian) throw()
  213151. {
  213152. bitDepth = 0;
  213153. littleEndian = false;
  213154. formatIsFloat = false;
  213155. switch (type)
  213156. {
  213157. case ASIOSTInt16MSB:
  213158. case ASIOSTInt16LSB:
  213159. case ASIOSTInt32MSB16:
  213160. case ASIOSTInt32LSB16:
  213161. bitDepth = 16; break;
  213162. case ASIOSTFloat32MSB:
  213163. case ASIOSTFloat32LSB:
  213164. formatIsFloat = true;
  213165. bitDepth = 32; break;
  213166. case ASIOSTInt32MSB:
  213167. case ASIOSTInt32LSB:
  213168. bitDepth = 32; break;
  213169. case ASIOSTInt24MSB:
  213170. case ASIOSTInt24LSB:
  213171. case ASIOSTInt32MSB24:
  213172. case ASIOSTInt32LSB24:
  213173. case ASIOSTInt32MSB18:
  213174. case ASIOSTInt32MSB20:
  213175. case ASIOSTInt32LSB18:
  213176. case ASIOSTInt32LSB20:
  213177. bitDepth = 24; break;
  213178. case ASIOSTFloat64MSB:
  213179. case ASIOSTFloat64LSB:
  213180. default:
  213181. bitDepth = 64;
  213182. break;
  213183. }
  213184. switch (type)
  213185. {
  213186. case ASIOSTInt16MSB:
  213187. case ASIOSTInt32MSB16:
  213188. case ASIOSTFloat32MSB:
  213189. case ASIOSTFloat64MSB:
  213190. case ASIOSTInt32MSB:
  213191. case ASIOSTInt32MSB18:
  213192. case ASIOSTInt32MSB20:
  213193. case ASIOSTInt32MSB24:
  213194. case ASIOSTInt24MSB:
  213195. littleEndian = false; break;
  213196. case ASIOSTInt16LSB:
  213197. case ASIOSTInt32LSB16:
  213198. case ASIOSTFloat32LSB:
  213199. case ASIOSTFloat64LSB:
  213200. case ASIOSTInt32LSB:
  213201. case ASIOSTInt32LSB18:
  213202. case ASIOSTInt32LSB20:
  213203. case ASIOSTInt32LSB24:
  213204. case ASIOSTInt24LSB:
  213205. littleEndian = true; break;
  213206. default:
  213207. break;
  213208. }
  213209. switch (type)
  213210. {
  213211. case ASIOSTInt16LSB:
  213212. case ASIOSTInt16MSB:
  213213. byteStride = 2; break;
  213214. case ASIOSTInt24LSB:
  213215. case ASIOSTInt24MSB:
  213216. byteStride = 3; break;
  213217. case ASIOSTInt32MSB16:
  213218. case ASIOSTInt32LSB16:
  213219. case ASIOSTInt32MSB:
  213220. case ASIOSTInt32MSB18:
  213221. case ASIOSTInt32MSB20:
  213222. case ASIOSTInt32MSB24:
  213223. case ASIOSTInt32LSB:
  213224. case ASIOSTInt32LSB18:
  213225. case ASIOSTInt32LSB20:
  213226. case ASIOSTInt32LSB24:
  213227. case ASIOSTFloat32LSB:
  213228. case ASIOSTFloat32MSB:
  213229. byteStride = 4; break;
  213230. case ASIOSTFloat64MSB:
  213231. case ASIOSTFloat64LSB:
  213232. byteStride = 8; break;
  213233. default:
  213234. break;
  213235. }
  213236. }
  213237. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODevice);
  213238. };
  213239. class ASIOAudioIODeviceType : public AudioIODeviceType
  213240. {
  213241. public:
  213242. ASIOAudioIODeviceType()
  213243. : AudioIODeviceType ("ASIO"),
  213244. hasScanned (false)
  213245. {
  213246. CoInitialize (0);
  213247. }
  213248. ~ASIOAudioIODeviceType()
  213249. {
  213250. }
  213251. void scanForDevices()
  213252. {
  213253. hasScanned = true;
  213254. deviceNames.clear();
  213255. classIds.clear();
  213256. HKEY hk = 0;
  213257. int index = 0;
  213258. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  213259. {
  213260. for (;;)
  213261. {
  213262. char name [256];
  213263. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  213264. {
  213265. addDriverInfo (name, hk);
  213266. }
  213267. else
  213268. {
  213269. break;
  213270. }
  213271. }
  213272. RegCloseKey (hk);
  213273. }
  213274. }
  213275. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  213276. {
  213277. jassert (hasScanned); // need to call scanForDevices() before doing this
  213278. return deviceNames;
  213279. }
  213280. int getDefaultDeviceIndex (bool) const
  213281. {
  213282. jassert (hasScanned); // need to call scanForDevices() before doing this
  213283. for (int i = deviceNames.size(); --i >= 0;)
  213284. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  213285. return i; // asio4all is a safe choice for a default..
  213286. #if JUCE_DEBUG
  213287. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  213288. return 1; // (the digi m-box driver crashes the app when you run
  213289. // it in the debugger, which can be a bit annoying)
  213290. #endif
  213291. return 0;
  213292. }
  213293. static int findFreeSlot()
  213294. {
  213295. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213296. if (currentASIODev[i] == 0)
  213297. return i;
  213298. jassertfalse; // unfortunately you can only have a finite number
  213299. // of ASIO devices open at the same time..
  213300. return -1;
  213301. }
  213302. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  213303. {
  213304. jassert (hasScanned); // need to call scanForDevices() before doing this
  213305. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  213306. }
  213307. bool hasSeparateInputsAndOutputs() const { return false; }
  213308. AudioIODevice* createDevice (const String& outputDeviceName,
  213309. const String& inputDeviceName)
  213310. {
  213311. // ASIO can't open two different devices for input and output - they must be the same one.
  213312. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  213313. jassert (hasScanned); // need to call scanForDevices() before doing this
  213314. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  213315. : inputDeviceName);
  213316. if (index >= 0)
  213317. {
  213318. const int freeSlot = findFreeSlot();
  213319. if (freeSlot >= 0)
  213320. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  213321. }
  213322. return 0;
  213323. }
  213324. private:
  213325. StringArray deviceNames;
  213326. OwnedArray <CLSID> classIds;
  213327. bool hasScanned;
  213328. static bool checkClassIsOk (const String& classId)
  213329. {
  213330. HKEY hk = 0;
  213331. bool ok = false;
  213332. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  213333. {
  213334. int index = 0;
  213335. for (;;)
  213336. {
  213337. WCHAR buf [512];
  213338. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  213339. {
  213340. if (classId.equalsIgnoreCase (buf))
  213341. {
  213342. HKEY subKey, pathKey;
  213343. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213344. {
  213345. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  213346. {
  213347. WCHAR pathName [1024];
  213348. DWORD dtype = REG_SZ;
  213349. DWORD dsize = sizeof (pathName);
  213350. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  213351. ok = File (pathName).exists();
  213352. RegCloseKey (pathKey);
  213353. }
  213354. RegCloseKey (subKey);
  213355. }
  213356. break;
  213357. }
  213358. }
  213359. else
  213360. {
  213361. break;
  213362. }
  213363. }
  213364. RegCloseKey (hk);
  213365. }
  213366. return ok;
  213367. }
  213368. void addDriverInfo (const String& keyName, HKEY hk)
  213369. {
  213370. HKEY subKey;
  213371. if (RegOpenKeyEx (hk, keyName.toUTF16(), 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  213372. {
  213373. WCHAR buf [256];
  213374. zerostruct (buf);
  213375. DWORD dtype = REG_SZ;
  213376. DWORD dsize = sizeof (buf);
  213377. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213378. {
  213379. if (dsize > 0 && checkClassIsOk (buf))
  213380. {
  213381. CLSID classId;
  213382. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  213383. {
  213384. dtype = REG_SZ;
  213385. dsize = sizeof (buf);
  213386. String deviceName;
  213387. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  213388. deviceName = buf;
  213389. else
  213390. deviceName = keyName;
  213391. log ("found " + deviceName);
  213392. deviceNames.add (deviceName);
  213393. classIds.add (new CLSID (classId));
  213394. }
  213395. }
  213396. RegCloseKey (subKey);
  213397. }
  213398. }
  213399. }
  213400. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ASIOAudioIODeviceType);
  213401. };
  213402. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  213403. {
  213404. return new ASIOAudioIODeviceType();
  213405. }
  213406. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  213407. void* guid,
  213408. const String& optionalDllForDirectLoading)
  213409. {
  213410. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  213411. if (freeSlot < 0)
  213412. return 0;
  213413. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  213414. }
  213415. #undef logError
  213416. #undef log
  213417. #endif
  213418. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  213419. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  213420. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213421. // compiled on its own).
  213422. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  213423. END_JUCE_NAMESPACE
  213424. extern "C"
  213425. {
  213426. // Declare just the minimum number of interfaces for the DSound objects that we need..
  213427. typedef struct typeDSBUFFERDESC
  213428. {
  213429. DWORD dwSize;
  213430. DWORD dwFlags;
  213431. DWORD dwBufferBytes;
  213432. DWORD dwReserved;
  213433. LPWAVEFORMATEX lpwfxFormat;
  213434. GUID guid3DAlgorithm;
  213435. } DSBUFFERDESC;
  213436. struct IDirectSoundBuffer;
  213437. #undef INTERFACE
  213438. #define INTERFACE IDirectSound
  213439. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  213440. {
  213441. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213442. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213443. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213444. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  213445. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213446. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  213447. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  213448. STDMETHOD(Compact) (THIS) PURE;
  213449. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  213450. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  213451. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213452. };
  213453. #undef INTERFACE
  213454. #define INTERFACE IDirectSoundBuffer
  213455. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  213456. {
  213457. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213458. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213459. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213460. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213461. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213462. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213463. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  213464. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  213465. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  213466. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213467. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  213468. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213469. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  213470. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  213471. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  213472. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  213473. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  213474. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  213475. STDMETHOD(Stop) (THIS) PURE;
  213476. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213477. STDMETHOD(Restore) (THIS) PURE;
  213478. };
  213479. typedef struct typeDSCBUFFERDESC
  213480. {
  213481. DWORD dwSize;
  213482. DWORD dwFlags;
  213483. DWORD dwBufferBytes;
  213484. DWORD dwReserved;
  213485. LPWAVEFORMATEX lpwfxFormat;
  213486. } DSCBUFFERDESC;
  213487. struct IDirectSoundCaptureBuffer;
  213488. #undef INTERFACE
  213489. #define INTERFACE IDirectSoundCapture
  213490. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  213491. {
  213492. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213493. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213494. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213495. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  213496. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213497. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  213498. };
  213499. #undef INTERFACE
  213500. #define INTERFACE IDirectSoundCaptureBuffer
  213501. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  213502. {
  213503. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  213504. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  213505. STDMETHOD_(ULONG,Release) (THIS) PURE;
  213506. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  213507. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  213508. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  213509. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  213510. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  213511. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  213512. STDMETHOD(Start) (THIS_ DWORD) PURE;
  213513. STDMETHOD(Stop) (THIS) PURE;
  213514. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  213515. };
  213516. };
  213517. BEGIN_JUCE_NAMESPACE
  213518. namespace
  213519. {
  213520. const String getDSErrorMessage (HRESULT hr)
  213521. {
  213522. const char* result = 0;
  213523. switch (hr)
  213524. {
  213525. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  213526. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  213527. case E_INVALIDARG: result = "Invalid parameter"; break;
  213528. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  213529. case E_FAIL: result = "Generic error"; break;
  213530. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  213531. case E_OUTOFMEMORY: result = "Out of memory"; break;
  213532. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  213533. case E_NOTIMPL: result = "Unsupported function"; break;
  213534. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  213535. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  213536. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  213537. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  213538. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  213539. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  213540. case E_NOINTERFACE: result = "No interface"; break;
  213541. case S_OK: result = "No error"; break;
  213542. default: return "Unknown error: " + String ((int) hr);
  213543. }
  213544. return result;
  213545. }
  213546. #define DS_DEBUGGING 1
  213547. #ifdef DS_DEBUGGING
  213548. #define CATCH JUCE_CATCH_EXCEPTION
  213549. #undef log
  213550. #define log(a) Logger::writeToLog(a);
  213551. #undef logError
  213552. #define logError(a) logDSError(a, __LINE__);
  213553. static void logDSError (HRESULT hr, int lineNum)
  213554. {
  213555. if (hr != S_OK)
  213556. {
  213557. String error ("DS error at line ");
  213558. error << lineNum << " - " << getDSErrorMessage (hr);
  213559. log (error);
  213560. }
  213561. }
  213562. #else
  213563. #define CATCH JUCE_CATCH_ALL
  213564. #define log(a)
  213565. #define logError(a)
  213566. #endif
  213567. #define DSOUND_FUNCTION(functionName, params) \
  213568. typedef HRESULT (WINAPI *type##functionName) params; \
  213569. static type##functionName ds##functionName = 0;
  213570. #define DSOUND_FUNCTION_LOAD(functionName) \
  213571. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  213572. jassert (ds##functionName != 0);
  213573. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  213574. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  213575. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  213576. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  213577. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213578. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  213579. void initialiseDSoundFunctions()
  213580. {
  213581. if (dsDirectSoundCreate == 0)
  213582. {
  213583. HMODULE h = LoadLibraryA ("dsound.dll");
  213584. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  213585. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  213586. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  213587. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  213588. }
  213589. }
  213590. }
  213591. class DSoundInternalOutChannel
  213592. {
  213593. public:
  213594. DSoundInternalOutChannel (const String& name_, LPGUID guid_, int rate,
  213595. int bufferSize, float* left, float* right)
  213596. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213597. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213598. pDirectSound (0), pOutputBuffer (0)
  213599. {
  213600. }
  213601. ~DSoundInternalOutChannel()
  213602. {
  213603. close();
  213604. }
  213605. void close()
  213606. {
  213607. HRESULT hr;
  213608. if (pOutputBuffer != 0)
  213609. {
  213610. log ("closing dsound out: " + name);
  213611. hr = pOutputBuffer->Stop();
  213612. logError (hr);
  213613. hr = pOutputBuffer->Release();
  213614. pOutputBuffer = 0;
  213615. logError (hr);
  213616. }
  213617. if (pDirectSound != 0)
  213618. {
  213619. hr = pDirectSound->Release();
  213620. pDirectSound = 0;
  213621. logError (hr);
  213622. }
  213623. }
  213624. const String open()
  213625. {
  213626. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  213627. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213628. pDirectSound = 0;
  213629. pOutputBuffer = 0;
  213630. writeOffset = 0;
  213631. String error;
  213632. HRESULT hr = E_NOINTERFACE;
  213633. if (dsDirectSoundCreate != 0)
  213634. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  213635. if (hr == S_OK)
  213636. {
  213637. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213638. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213639. const int numChannels = 2;
  213640. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  213641. logError (hr);
  213642. if (hr == S_OK)
  213643. {
  213644. IDirectSoundBuffer* pPrimaryBuffer;
  213645. DSBUFFERDESC primaryDesc;
  213646. zerostruct (primaryDesc);
  213647. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213648. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  213649. primaryDesc.dwBufferBytes = 0;
  213650. primaryDesc.lpwfxFormat = 0;
  213651. log ("opening dsound out step 2");
  213652. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  213653. logError (hr);
  213654. if (hr == S_OK)
  213655. {
  213656. WAVEFORMATEX wfFormat;
  213657. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213658. wfFormat.nChannels = (unsigned short) numChannels;
  213659. wfFormat.nSamplesPerSec = sampleRate;
  213660. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  213661. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  213662. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213663. wfFormat.cbSize = 0;
  213664. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  213665. logError (hr);
  213666. if (hr == S_OK)
  213667. {
  213668. DSBUFFERDESC secondaryDesc;
  213669. zerostruct (secondaryDesc);
  213670. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  213671. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  213672. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  213673. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  213674. secondaryDesc.lpwfxFormat = &wfFormat;
  213675. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  213676. logError (hr);
  213677. if (hr == S_OK)
  213678. {
  213679. log ("opening dsound out step 3");
  213680. DWORD dwDataLen;
  213681. unsigned char* pDSBuffData;
  213682. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  213683. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  213684. logError (hr);
  213685. if (hr == S_OK)
  213686. {
  213687. zeromem (pDSBuffData, dwDataLen);
  213688. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  213689. if (hr == S_OK)
  213690. {
  213691. hr = pOutputBuffer->SetCurrentPosition (0);
  213692. if (hr == S_OK)
  213693. {
  213694. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  213695. if (hr == S_OK)
  213696. return String::empty;
  213697. }
  213698. }
  213699. }
  213700. }
  213701. }
  213702. }
  213703. }
  213704. }
  213705. error = getDSErrorMessage (hr);
  213706. close();
  213707. return error;
  213708. }
  213709. void synchronisePosition()
  213710. {
  213711. if (pOutputBuffer != 0)
  213712. {
  213713. DWORD playCursor;
  213714. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  213715. }
  213716. }
  213717. bool service()
  213718. {
  213719. if (pOutputBuffer == 0)
  213720. return true;
  213721. DWORD playCursor, writeCursor;
  213722. for (;;)
  213723. {
  213724. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  213725. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213726. {
  213727. pOutputBuffer->Restore();
  213728. continue;
  213729. }
  213730. if (hr == S_OK)
  213731. break;
  213732. logError (hr);
  213733. jassertfalse;
  213734. return true;
  213735. }
  213736. int playWriteGap = writeCursor - playCursor;
  213737. if (playWriteGap < 0)
  213738. playWriteGap += totalBytesPerBuffer;
  213739. int bytesEmpty = playCursor - writeOffset;
  213740. if (bytesEmpty < 0)
  213741. bytesEmpty += totalBytesPerBuffer;
  213742. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  213743. {
  213744. writeOffset = writeCursor;
  213745. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  213746. }
  213747. if (bytesEmpty >= bytesPerBuffer)
  213748. {
  213749. void* lpbuf1 = 0;
  213750. void* lpbuf2 = 0;
  213751. DWORD dwSize1 = 0;
  213752. DWORD dwSize2 = 0;
  213753. HRESULT hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213754. &lpbuf1, &dwSize1,
  213755. &lpbuf2, &dwSize2, 0);
  213756. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  213757. {
  213758. pOutputBuffer->Restore();
  213759. hr = pOutputBuffer->Lock (writeOffset, bytesPerBuffer,
  213760. &lpbuf1, &dwSize1,
  213761. &lpbuf2, &dwSize2, 0);
  213762. }
  213763. if (hr == S_OK)
  213764. {
  213765. if (bitDepth == 16)
  213766. {
  213767. int* dest = static_cast<int*> (lpbuf1);
  213768. const float* left = leftBuffer;
  213769. const float* right = rightBuffer;
  213770. int samples1 = dwSize1 >> 2;
  213771. int samples2 = dwSize2 >> 2;
  213772. if (left == 0)
  213773. {
  213774. while (--samples1 >= 0)
  213775. *dest++ = (convertInputValue (*right++) << 16);
  213776. dest = static_cast<int*> (lpbuf2);
  213777. while (--samples2 >= 0)
  213778. *dest++ = (convertInputValue (*right++) << 16);
  213779. }
  213780. else if (right == 0)
  213781. {
  213782. while (--samples1 >= 0)
  213783. *dest++ = (0xffff & convertInputValue (*left++));
  213784. dest = static_cast<int*> (lpbuf2);
  213785. while (--samples2 >= 0)
  213786. *dest++ = (0xffff & convertInputValue (*left++));
  213787. }
  213788. else
  213789. {
  213790. while (--samples1 >= 0)
  213791. {
  213792. const int l = convertInputValue (*left++);
  213793. const int r = convertInputValue (*right++);
  213794. *dest++ = (r << 16) | (0xffff & l);
  213795. }
  213796. dest = static_cast<int*> (lpbuf2);
  213797. while (--samples2 >= 0)
  213798. {
  213799. const int l = convertInputValue (*left++);
  213800. const int r = convertInputValue (*right++);
  213801. *dest++ = (r << 16) | (0xffff & l);
  213802. }
  213803. }
  213804. }
  213805. else
  213806. {
  213807. jassertfalse;
  213808. }
  213809. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  213810. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  213811. }
  213812. else
  213813. {
  213814. jassertfalse;
  213815. logError (hr);
  213816. }
  213817. bytesEmpty -= bytesPerBuffer;
  213818. return true;
  213819. }
  213820. else
  213821. {
  213822. return false;
  213823. }
  213824. }
  213825. int bitDepth;
  213826. bool doneFlag;
  213827. private:
  213828. String name;
  213829. LPGUID guid;
  213830. int sampleRate, bufferSizeSamples;
  213831. float* leftBuffer;
  213832. float* rightBuffer;
  213833. IDirectSound* pDirectSound;
  213834. IDirectSoundBuffer* pOutputBuffer;
  213835. DWORD writeOffset;
  213836. int totalBytesPerBuffer, bytesPerBuffer;
  213837. unsigned int lastPlayCursor;
  213838. static inline int convertInputValue (const float v) throw()
  213839. {
  213840. return jlimit (-32768, 32767, roundToInt (32767.0f * v));
  213841. }
  213842. JUCE_DECLARE_NON_COPYABLE (DSoundInternalOutChannel);
  213843. };
  213844. struct DSoundInternalInChannel
  213845. {
  213846. public:
  213847. DSoundInternalInChannel (const String& name_, LPGUID guid_, int rate,
  213848. int bufferSize, float* left, float* right)
  213849. : bitDepth (16), name (name_), guid (guid_), sampleRate (rate),
  213850. bufferSizeSamples (bufferSize), leftBuffer (left), rightBuffer (right),
  213851. pDirectSound (0), pDirectSoundCapture (0), pInputBuffer (0)
  213852. {
  213853. }
  213854. ~DSoundInternalInChannel()
  213855. {
  213856. close();
  213857. }
  213858. void close()
  213859. {
  213860. HRESULT hr;
  213861. if (pInputBuffer != 0)
  213862. {
  213863. log ("closing dsound in: " + name);
  213864. hr = pInputBuffer->Stop();
  213865. logError (hr);
  213866. hr = pInputBuffer->Release();
  213867. pInputBuffer = 0;
  213868. logError (hr);
  213869. }
  213870. if (pDirectSoundCapture != 0)
  213871. {
  213872. hr = pDirectSoundCapture->Release();
  213873. pDirectSoundCapture = 0;
  213874. logError (hr);
  213875. }
  213876. if (pDirectSound != 0)
  213877. {
  213878. hr = pDirectSound->Release();
  213879. pDirectSound = 0;
  213880. logError (hr);
  213881. }
  213882. }
  213883. const String open()
  213884. {
  213885. log ("opening dsound in device: " + name
  213886. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  213887. pDirectSound = 0;
  213888. pDirectSoundCapture = 0;
  213889. pInputBuffer = 0;
  213890. readOffset = 0;
  213891. totalBytesPerBuffer = 0;
  213892. String error;
  213893. HRESULT hr = E_NOINTERFACE;
  213894. if (dsDirectSoundCaptureCreate != 0)
  213895. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  213896. logError (hr);
  213897. if (hr == S_OK)
  213898. {
  213899. const int numChannels = 2;
  213900. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  213901. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  213902. WAVEFORMATEX wfFormat;
  213903. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  213904. wfFormat.nChannels = (unsigned short)numChannels;
  213905. wfFormat.nSamplesPerSec = sampleRate;
  213906. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  213907. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  213908. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  213909. wfFormat.cbSize = 0;
  213910. DSCBUFFERDESC captureDesc;
  213911. zerostruct (captureDesc);
  213912. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  213913. captureDesc.dwFlags = 0;
  213914. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  213915. captureDesc.lpwfxFormat = &wfFormat;
  213916. log ("opening dsound in step 2");
  213917. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  213918. logError (hr);
  213919. if (hr == S_OK)
  213920. {
  213921. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  213922. logError (hr);
  213923. if (hr == S_OK)
  213924. return String::empty;
  213925. }
  213926. }
  213927. error = getDSErrorMessage (hr);
  213928. close();
  213929. return error;
  213930. }
  213931. void synchronisePosition()
  213932. {
  213933. if (pInputBuffer != 0)
  213934. {
  213935. DWORD capturePos;
  213936. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  213937. }
  213938. }
  213939. bool service()
  213940. {
  213941. if (pInputBuffer == 0)
  213942. return true;
  213943. DWORD capturePos, readPos;
  213944. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  213945. logError (hr);
  213946. if (hr != S_OK)
  213947. return true;
  213948. int bytesFilled = readPos - readOffset;
  213949. if (bytesFilled < 0)
  213950. bytesFilled += totalBytesPerBuffer;
  213951. if (bytesFilled >= bytesPerBuffer)
  213952. {
  213953. LPBYTE lpbuf1 = 0;
  213954. LPBYTE lpbuf2 = 0;
  213955. DWORD dwsize1 = 0;
  213956. DWORD dwsize2 = 0;
  213957. HRESULT hr = pInputBuffer->Lock (readOffset, bytesPerBuffer,
  213958. (void**) &lpbuf1, &dwsize1,
  213959. (void**) &lpbuf2, &dwsize2, 0);
  213960. if (hr == S_OK)
  213961. {
  213962. if (bitDepth == 16)
  213963. {
  213964. const float g = 1.0f / 32768.0f;
  213965. float* destL = leftBuffer;
  213966. float* destR = rightBuffer;
  213967. int samples1 = dwsize1 >> 2;
  213968. int samples2 = dwsize2 >> 2;
  213969. const short* src = (const short*)lpbuf1;
  213970. if (destL == 0)
  213971. {
  213972. while (--samples1 >= 0)
  213973. {
  213974. ++src;
  213975. *destR++ = *src++ * g;
  213976. }
  213977. src = (const short*)lpbuf2;
  213978. while (--samples2 >= 0)
  213979. {
  213980. ++src;
  213981. *destR++ = *src++ * g;
  213982. }
  213983. }
  213984. else if (destR == 0)
  213985. {
  213986. while (--samples1 >= 0)
  213987. {
  213988. *destL++ = *src++ * g;
  213989. ++src;
  213990. }
  213991. src = (const short*)lpbuf2;
  213992. while (--samples2 >= 0)
  213993. {
  213994. *destL++ = *src++ * g;
  213995. ++src;
  213996. }
  213997. }
  213998. else
  213999. {
  214000. while (--samples1 >= 0)
  214001. {
  214002. *destL++ = *src++ * g;
  214003. *destR++ = *src++ * g;
  214004. }
  214005. src = (const short*)lpbuf2;
  214006. while (--samples2 >= 0)
  214007. {
  214008. *destL++ = *src++ * g;
  214009. *destR++ = *src++ * g;
  214010. }
  214011. }
  214012. }
  214013. else
  214014. {
  214015. jassertfalse;
  214016. }
  214017. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214018. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214019. }
  214020. else
  214021. {
  214022. logError (hr);
  214023. jassertfalse;
  214024. }
  214025. bytesFilled -= bytesPerBuffer;
  214026. return true;
  214027. }
  214028. else
  214029. {
  214030. return false;
  214031. }
  214032. }
  214033. unsigned int readOffset;
  214034. int bytesPerBuffer, totalBytesPerBuffer;
  214035. int bitDepth;
  214036. bool doneFlag;
  214037. private:
  214038. String name;
  214039. LPGUID guid;
  214040. int sampleRate, bufferSizeSamples;
  214041. float* leftBuffer;
  214042. float* rightBuffer;
  214043. IDirectSound* pDirectSound;
  214044. IDirectSoundCapture* pDirectSoundCapture;
  214045. IDirectSoundCaptureBuffer* pInputBuffer;
  214046. JUCE_DECLARE_NON_COPYABLE (DSoundInternalInChannel);
  214047. };
  214048. class DSoundAudioIODevice : public AudioIODevice,
  214049. public Thread
  214050. {
  214051. public:
  214052. DSoundAudioIODevice (const String& deviceName,
  214053. const int outputDeviceIndex_,
  214054. const int inputDeviceIndex_)
  214055. : AudioIODevice (deviceName, "DirectSound"),
  214056. Thread ("Juce DSound"),
  214057. outputDeviceIndex (outputDeviceIndex_),
  214058. inputDeviceIndex (inputDeviceIndex_),
  214059. isOpen_ (false),
  214060. isStarted (false),
  214061. bufferSizeSamples (0),
  214062. totalSamplesOut (0),
  214063. sampleRate (0.0),
  214064. inputBuffers (1, 1),
  214065. outputBuffers (1, 1),
  214066. callback (0)
  214067. {
  214068. if (outputDeviceIndex_ >= 0)
  214069. {
  214070. outChannels.add (TRANS("Left"));
  214071. outChannels.add (TRANS("Right"));
  214072. }
  214073. if (inputDeviceIndex_ >= 0)
  214074. {
  214075. inChannels.add (TRANS("Left"));
  214076. inChannels.add (TRANS("Right"));
  214077. }
  214078. }
  214079. ~DSoundAudioIODevice()
  214080. {
  214081. close();
  214082. }
  214083. const String open (const BigInteger& inputChannels,
  214084. const BigInteger& outputChannels,
  214085. double sampleRate, int bufferSizeSamples)
  214086. {
  214087. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  214088. isOpen_ = lastError.isEmpty();
  214089. return lastError;
  214090. }
  214091. void close()
  214092. {
  214093. stop();
  214094. if (isOpen_)
  214095. {
  214096. closeDevice();
  214097. isOpen_ = false;
  214098. }
  214099. }
  214100. bool isOpen() { return isOpen_ && isThreadRunning(); }
  214101. int getCurrentBufferSizeSamples() { return bufferSizeSamples; }
  214102. double getCurrentSampleRate() { return sampleRate; }
  214103. const BigInteger getActiveOutputChannels() const { return enabledOutputs; }
  214104. const BigInteger getActiveInputChannels() const { return enabledInputs; }
  214105. int getOutputLatencyInSamples() { return (int) (getCurrentBufferSizeSamples() * 1.5); }
  214106. int getInputLatencyInSamples() { return getOutputLatencyInSamples(); }
  214107. const StringArray getOutputChannelNames() { return outChannels; }
  214108. const StringArray getInputChannelNames() { return inChannels; }
  214109. int getNumSampleRates() { return 4; }
  214110. int getDefaultBufferSize() { return 2560; }
  214111. int getNumBufferSizesAvailable() { return 50; }
  214112. double getSampleRate (int index)
  214113. {
  214114. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214115. return samps [jlimit (0, 3, index)];
  214116. }
  214117. int getBufferSizeSamples (int index)
  214118. {
  214119. int n = 64;
  214120. for (int i = 0; i < index; ++i)
  214121. n += (n < 512) ? 32
  214122. : ((n < 1024) ? 64
  214123. : ((n < 2048) ? 128 : 256));
  214124. return n;
  214125. }
  214126. int getCurrentBitDepth()
  214127. {
  214128. int i, bits = 256;
  214129. for (i = inChans.size(); --i >= 0;)
  214130. bits = jmin (bits, inChans[i]->bitDepth);
  214131. for (i = outChans.size(); --i >= 0;)
  214132. bits = jmin (bits, outChans[i]->bitDepth);
  214133. if (bits > 32)
  214134. bits = 16;
  214135. return bits;
  214136. }
  214137. void start (AudioIODeviceCallback* call)
  214138. {
  214139. if (isOpen_ && call != 0 && ! isStarted)
  214140. {
  214141. if (! isThreadRunning())
  214142. {
  214143. // something gone wrong and the thread's stopped..
  214144. isOpen_ = false;
  214145. return;
  214146. }
  214147. call->audioDeviceAboutToStart (this);
  214148. const ScopedLock sl (startStopLock);
  214149. callback = call;
  214150. isStarted = true;
  214151. }
  214152. }
  214153. void stop()
  214154. {
  214155. if (isStarted)
  214156. {
  214157. AudioIODeviceCallback* const callbackLocal = callback;
  214158. {
  214159. const ScopedLock sl (startStopLock);
  214160. isStarted = false;
  214161. }
  214162. if (callbackLocal != 0)
  214163. callbackLocal->audioDeviceStopped();
  214164. }
  214165. }
  214166. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  214167. const String getLastError() { return lastError; }
  214168. StringArray inChannels, outChannels;
  214169. int outputDeviceIndex, inputDeviceIndex;
  214170. private:
  214171. bool isOpen_;
  214172. bool isStarted;
  214173. String lastError;
  214174. OwnedArray <DSoundInternalInChannel> inChans;
  214175. OwnedArray <DSoundInternalOutChannel> outChans;
  214176. WaitableEvent startEvent;
  214177. int bufferSizeSamples;
  214178. int volatile totalSamplesOut;
  214179. int64 volatile lastBlockTime;
  214180. double sampleRate;
  214181. BigInteger enabledInputs, enabledOutputs;
  214182. AudioSampleBuffer inputBuffers, outputBuffers;
  214183. AudioIODeviceCallback* callback;
  214184. CriticalSection startStopLock;
  214185. const String openDevice (const BigInteger& inputChannels,
  214186. const BigInteger& outputChannels,
  214187. double sampleRate_, int bufferSizeSamples_);
  214188. void closeDevice()
  214189. {
  214190. isStarted = false;
  214191. stopThread (5000);
  214192. inChans.clear();
  214193. outChans.clear();
  214194. inputBuffers.setSize (1, 1);
  214195. outputBuffers.setSize (1, 1);
  214196. }
  214197. void resync()
  214198. {
  214199. if (! threadShouldExit())
  214200. {
  214201. sleep (5);
  214202. int i;
  214203. for (i = 0; i < outChans.size(); ++i)
  214204. outChans.getUnchecked(i)->synchronisePosition();
  214205. for (i = 0; i < inChans.size(); ++i)
  214206. inChans.getUnchecked(i)->synchronisePosition();
  214207. }
  214208. }
  214209. public:
  214210. void run()
  214211. {
  214212. while (! threadShouldExit())
  214213. {
  214214. if (wait (100))
  214215. break;
  214216. }
  214217. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  214218. const int maxTimeMS = jmax (5, 3 * latencyMs);
  214219. while (! threadShouldExit())
  214220. {
  214221. int numToDo = 0;
  214222. uint32 startTime = Time::getMillisecondCounter();
  214223. int i;
  214224. for (i = inChans.size(); --i >= 0;)
  214225. {
  214226. inChans.getUnchecked(i)->doneFlag = false;
  214227. ++numToDo;
  214228. }
  214229. for (i = outChans.size(); --i >= 0;)
  214230. {
  214231. outChans.getUnchecked(i)->doneFlag = false;
  214232. ++numToDo;
  214233. }
  214234. if (numToDo > 0)
  214235. {
  214236. const int maxCount = 3;
  214237. int count = maxCount;
  214238. for (;;)
  214239. {
  214240. for (i = inChans.size(); --i >= 0;)
  214241. {
  214242. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  214243. if ((! in->doneFlag) && in->service())
  214244. {
  214245. in->doneFlag = true;
  214246. --numToDo;
  214247. }
  214248. }
  214249. for (i = outChans.size(); --i >= 0;)
  214250. {
  214251. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  214252. if ((! out->doneFlag) && out->service())
  214253. {
  214254. out->doneFlag = true;
  214255. --numToDo;
  214256. }
  214257. }
  214258. if (numToDo <= 0)
  214259. break;
  214260. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  214261. {
  214262. resync();
  214263. break;
  214264. }
  214265. if (--count <= 0)
  214266. {
  214267. Sleep (1);
  214268. count = maxCount;
  214269. }
  214270. if (threadShouldExit())
  214271. return;
  214272. }
  214273. }
  214274. else
  214275. {
  214276. sleep (1);
  214277. }
  214278. const ScopedLock sl (startStopLock);
  214279. if (isStarted)
  214280. {
  214281. JUCE_TRY
  214282. {
  214283. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  214284. inputBuffers.getNumChannels(),
  214285. outputBuffers.getArrayOfChannels(),
  214286. outputBuffers.getNumChannels(),
  214287. bufferSizeSamples);
  214288. }
  214289. JUCE_CATCH_EXCEPTION
  214290. totalSamplesOut += bufferSizeSamples;
  214291. }
  214292. else
  214293. {
  214294. outputBuffers.clear();
  214295. totalSamplesOut = 0;
  214296. sleep (1);
  214297. }
  214298. }
  214299. }
  214300. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODevice);
  214301. };
  214302. class DSoundAudioIODeviceType : public AudioIODeviceType
  214303. {
  214304. public:
  214305. DSoundAudioIODeviceType()
  214306. : AudioIODeviceType ("DirectSound"),
  214307. hasScanned (false)
  214308. {
  214309. initialiseDSoundFunctions();
  214310. }
  214311. void scanForDevices()
  214312. {
  214313. hasScanned = true;
  214314. outputDeviceNames.clear();
  214315. outputGuids.clear();
  214316. inputDeviceNames.clear();
  214317. inputGuids.clear();
  214318. if (dsDirectSoundEnumerateW != 0)
  214319. {
  214320. dsDirectSoundEnumerateW (outputEnumProcW, this);
  214321. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  214322. }
  214323. }
  214324. const StringArray getDeviceNames (bool wantInputNames) const
  214325. {
  214326. jassert (hasScanned); // need to call scanForDevices() before doing this
  214327. return wantInputNames ? inputDeviceNames
  214328. : outputDeviceNames;
  214329. }
  214330. int getDefaultDeviceIndex (bool /*forInput*/) const
  214331. {
  214332. jassert (hasScanned); // need to call scanForDevices() before doing this
  214333. return 0;
  214334. }
  214335. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  214336. {
  214337. jassert (hasScanned); // need to call scanForDevices() before doing this
  214338. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  214339. if (d == 0)
  214340. return -1;
  214341. return asInput ? d->inputDeviceIndex
  214342. : d->outputDeviceIndex;
  214343. }
  214344. bool hasSeparateInputsAndOutputs() const { return true; }
  214345. AudioIODevice* createDevice (const String& outputDeviceName,
  214346. const String& inputDeviceName)
  214347. {
  214348. jassert (hasScanned); // need to call scanForDevices() before doing this
  214349. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  214350. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  214351. if (outputIndex >= 0 || inputIndex >= 0)
  214352. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  214353. : inputDeviceName,
  214354. outputIndex, inputIndex);
  214355. return 0;
  214356. }
  214357. StringArray outputDeviceNames, inputDeviceNames;
  214358. OwnedArray <GUID> outputGuids, inputGuids;
  214359. private:
  214360. bool hasScanned;
  214361. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  214362. {
  214363. desc = desc.trim();
  214364. if (desc.isNotEmpty())
  214365. {
  214366. const String origDesc (desc);
  214367. int n = 2;
  214368. while (outputDeviceNames.contains (desc))
  214369. desc = origDesc + " (" + String (n++) + ")";
  214370. outputDeviceNames.add (desc);
  214371. if (lpGUID != 0)
  214372. outputGuids.add (new GUID (*lpGUID));
  214373. else
  214374. outputGuids.add (0);
  214375. }
  214376. return TRUE;
  214377. }
  214378. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214379. {
  214380. return ((DSoundAudioIODeviceType*) object)
  214381. ->outputEnumProc (lpGUID, String (description));
  214382. }
  214383. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214384. {
  214385. return ((DSoundAudioIODeviceType*) object)
  214386. ->outputEnumProc (lpGUID, String (description));
  214387. }
  214388. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  214389. {
  214390. desc = desc.trim();
  214391. if (desc.isNotEmpty())
  214392. {
  214393. const String origDesc (desc);
  214394. int n = 2;
  214395. while (inputDeviceNames.contains (desc))
  214396. desc = origDesc + " (" + String (n++) + ")";
  214397. inputDeviceNames.add (desc);
  214398. if (lpGUID != 0)
  214399. inputGuids.add (new GUID (*lpGUID));
  214400. else
  214401. inputGuids.add (0);
  214402. }
  214403. return TRUE;
  214404. }
  214405. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  214406. {
  214407. return ((DSoundAudioIODeviceType*) object)
  214408. ->inputEnumProc (lpGUID, String (description));
  214409. }
  214410. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  214411. {
  214412. return ((DSoundAudioIODeviceType*) object)
  214413. ->inputEnumProc (lpGUID, String (description));
  214414. }
  214415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DSoundAudioIODeviceType);
  214416. };
  214417. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  214418. const BigInteger& outputChannels,
  214419. double sampleRate_, int bufferSizeSamples_)
  214420. {
  214421. closeDevice();
  214422. totalSamplesOut = 0;
  214423. sampleRate = sampleRate_;
  214424. if (bufferSizeSamples_ <= 0)
  214425. bufferSizeSamples_ = 960; // use as a default size if none is set.
  214426. bufferSizeSamples = bufferSizeSamples_ & ~7;
  214427. DSoundAudioIODeviceType dlh;
  214428. dlh.scanForDevices();
  214429. enabledInputs = inputChannels;
  214430. enabledInputs.setRange (inChannels.size(),
  214431. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  214432. false);
  214433. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  214434. inputBuffers.clear();
  214435. int i, numIns = 0;
  214436. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  214437. {
  214438. float* left = 0;
  214439. if (enabledInputs[i])
  214440. left = inputBuffers.getSampleData (numIns++);
  214441. float* right = 0;
  214442. if (enabledInputs[i + 1])
  214443. right = inputBuffers.getSampleData (numIns++);
  214444. if (left != 0 || right != 0)
  214445. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  214446. dlh.inputGuids [inputDeviceIndex],
  214447. (int) sampleRate, bufferSizeSamples,
  214448. left, right));
  214449. }
  214450. enabledOutputs = outputChannels;
  214451. enabledOutputs.setRange (outChannels.size(),
  214452. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  214453. false);
  214454. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  214455. outputBuffers.clear();
  214456. int numOuts = 0;
  214457. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  214458. {
  214459. float* left = 0;
  214460. if (enabledOutputs[i])
  214461. left = outputBuffers.getSampleData (numOuts++);
  214462. float* right = 0;
  214463. if (enabledOutputs[i + 1])
  214464. right = outputBuffers.getSampleData (numOuts++);
  214465. if (left != 0 || right != 0)
  214466. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  214467. dlh.outputGuids [outputDeviceIndex],
  214468. (int) sampleRate, bufferSizeSamples,
  214469. left, right));
  214470. }
  214471. String error;
  214472. // boost our priority while opening the devices to try to get better sync between them
  214473. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  214474. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  214475. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  214476. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  214477. for (i = 0; i < outChans.size(); ++i)
  214478. {
  214479. error = outChans[i]->open();
  214480. if (error.isNotEmpty())
  214481. {
  214482. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  214483. break;
  214484. }
  214485. }
  214486. if (error.isEmpty())
  214487. {
  214488. for (i = 0; i < inChans.size(); ++i)
  214489. {
  214490. error = inChans[i]->open();
  214491. if (error.isNotEmpty())
  214492. {
  214493. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  214494. break;
  214495. }
  214496. }
  214497. }
  214498. if (error.isEmpty())
  214499. {
  214500. totalSamplesOut = 0;
  214501. for (i = 0; i < outChans.size(); ++i)
  214502. outChans.getUnchecked(i)->synchronisePosition();
  214503. for (i = 0; i < inChans.size(); ++i)
  214504. inChans.getUnchecked(i)->synchronisePosition();
  214505. startThread (9);
  214506. sleep (10);
  214507. notify();
  214508. }
  214509. else
  214510. {
  214511. log (error);
  214512. }
  214513. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  214514. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  214515. return error;
  214516. }
  214517. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  214518. {
  214519. return new DSoundAudioIODeviceType();
  214520. }
  214521. #undef log
  214522. #endif
  214523. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  214524. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  214525. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214526. // compiled on its own).
  214527. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  214528. #ifndef WASAPI_ENABLE_LOGGING
  214529. #define WASAPI_ENABLE_LOGGING 0
  214530. #endif
  214531. namespace WasapiClasses
  214532. {
  214533. void logFailure (HRESULT hr)
  214534. {
  214535. (void) hr;
  214536. #if WASAPI_ENABLE_LOGGING
  214537. if (FAILED (hr))
  214538. {
  214539. String e;
  214540. e << Time::getCurrentTime().toString (true, true, true, true)
  214541. << " -- WASAPI error: ";
  214542. switch (hr)
  214543. {
  214544. case E_POINTER: e << "E_POINTER"; break;
  214545. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  214546. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  214547. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  214548. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  214549. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  214550. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  214551. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  214552. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  214553. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  214554. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  214555. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  214556. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  214557. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  214558. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  214559. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  214560. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  214561. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  214562. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  214563. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  214564. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  214565. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  214566. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  214567. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  214568. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  214569. default: e << String::toHexString ((int) hr); break;
  214570. }
  214571. DBG (e);
  214572. jassertfalse;
  214573. }
  214574. #endif
  214575. }
  214576. #undef check
  214577. bool check (HRESULT hr)
  214578. {
  214579. logFailure (hr);
  214580. return SUCCEEDED (hr);
  214581. }
  214582. const String getDeviceID (IMMDevice* const device)
  214583. {
  214584. String s;
  214585. WCHAR* deviceId = 0;
  214586. if (check (device->GetId (&deviceId)))
  214587. {
  214588. s = String (deviceId);
  214589. CoTaskMemFree (deviceId);
  214590. }
  214591. return s;
  214592. }
  214593. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  214594. {
  214595. EDataFlow flow = eRender;
  214596. ComSmartPtr <IMMEndpoint> endPoint;
  214597. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  214598. (void) check (endPoint->GetDataFlow (&flow));
  214599. return flow;
  214600. }
  214601. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  214602. {
  214603. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  214604. }
  214605. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  214606. {
  214607. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  214608. : sizeof (WAVEFORMATEX));
  214609. }
  214610. class WASAPIDeviceBase
  214611. {
  214612. public:
  214613. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214614. : device (device_),
  214615. sampleRate (0),
  214616. defaultSampleRate (0),
  214617. numChannels (0),
  214618. actualNumChannels (0),
  214619. minBufferSize (0),
  214620. defaultBufferSize (0),
  214621. latencySamples (0),
  214622. useExclusiveMode (useExclusiveMode_)
  214623. {
  214624. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  214625. ComSmartPtr <IAudioClient> tempClient (createClient());
  214626. if (tempClient == 0)
  214627. return;
  214628. REFERENCE_TIME defaultPeriod, minPeriod;
  214629. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  214630. return;
  214631. WAVEFORMATEX* mixFormat = 0;
  214632. if (! check (tempClient->GetMixFormat (&mixFormat)))
  214633. return;
  214634. WAVEFORMATEXTENSIBLE format;
  214635. copyWavFormat (format, mixFormat);
  214636. CoTaskMemFree (mixFormat);
  214637. actualNumChannels = numChannels = format.Format.nChannels;
  214638. defaultSampleRate = format.Format.nSamplesPerSec;
  214639. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  214640. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  214641. rates.addUsingDefaultSort (defaultSampleRate);
  214642. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  214643. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  214644. {
  214645. if (ratesToTest[i] == defaultSampleRate)
  214646. continue;
  214647. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  214648. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214649. (WAVEFORMATEX*) &format, 0)))
  214650. if (! rates.contains (ratesToTest[i]))
  214651. rates.addUsingDefaultSort (ratesToTest[i]);
  214652. }
  214653. }
  214654. ~WASAPIDeviceBase()
  214655. {
  214656. device = 0;
  214657. CloseHandle (clientEvent);
  214658. }
  214659. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  214660. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  214661. {
  214662. sampleRate = newSampleRate;
  214663. channels = newChannels;
  214664. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  214665. numChannels = channels.getHighestBit() + 1;
  214666. if (numChannels == 0)
  214667. return true;
  214668. client = createClient();
  214669. if (client != 0
  214670. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  214671. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  214672. {
  214673. channelMaps.clear();
  214674. for (int i = 0; i <= channels.getHighestBit(); ++i)
  214675. if (channels[i])
  214676. channelMaps.add (i);
  214677. REFERENCE_TIME latency;
  214678. if (check (client->GetStreamLatency (&latency)))
  214679. latencySamples = refTimeToSamples (latency, sampleRate);
  214680. (void) check (client->GetBufferSize (&actualBufferSize));
  214681. return check (client->SetEventHandle (clientEvent));
  214682. }
  214683. return false;
  214684. }
  214685. void closeClient()
  214686. {
  214687. if (client != 0)
  214688. client->Stop();
  214689. client = 0;
  214690. ResetEvent (clientEvent);
  214691. }
  214692. ComSmartPtr <IMMDevice> device;
  214693. ComSmartPtr <IAudioClient> client;
  214694. double sampleRate, defaultSampleRate;
  214695. int numChannels, actualNumChannels;
  214696. int minBufferSize, defaultBufferSize, latencySamples;
  214697. const bool useExclusiveMode;
  214698. Array <double> rates;
  214699. HANDLE clientEvent;
  214700. BigInteger channels;
  214701. Array <int> channelMaps;
  214702. UINT32 actualBufferSize;
  214703. int bytesPerSample;
  214704. virtual void updateFormat (bool isFloat) = 0;
  214705. private:
  214706. const ComSmartPtr <IAudioClient> createClient()
  214707. {
  214708. ComSmartPtr <IAudioClient> client;
  214709. if (device != 0)
  214710. {
  214711. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  214712. logFailure (hr);
  214713. }
  214714. return client;
  214715. }
  214716. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  214717. {
  214718. WAVEFORMATEXTENSIBLE format;
  214719. zerostruct (format);
  214720. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  214721. {
  214722. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  214723. }
  214724. else
  214725. {
  214726. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  214727. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  214728. }
  214729. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  214730. format.Format.nChannels = (WORD) numChannels;
  214731. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  214732. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  214733. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  214734. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  214735. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  214736. switch (numChannels)
  214737. {
  214738. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  214739. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  214740. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214741. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  214742. 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;
  214743. default: break;
  214744. }
  214745. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  214746. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214747. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  214748. logFailure (hr);
  214749. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  214750. {
  214751. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  214752. hr = S_OK;
  214753. }
  214754. CoTaskMemFree (nearestFormat);
  214755. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  214756. if (useExclusiveMode)
  214757. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  214758. GUID session;
  214759. if (hr == S_OK
  214760. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  214761. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  214762. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  214763. {
  214764. actualNumChannels = format.Format.nChannels;
  214765. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  214766. bytesPerSample = format.Format.wBitsPerSample / 8;
  214767. updateFormat (isFloat);
  214768. return true;
  214769. }
  214770. return false;
  214771. }
  214772. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIDeviceBase);
  214773. };
  214774. class WASAPIInputDevice : public WASAPIDeviceBase
  214775. {
  214776. public:
  214777. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214778. : WASAPIDeviceBase (device_, useExclusiveMode_),
  214779. reservoir (1, 1)
  214780. {
  214781. }
  214782. ~WASAPIInputDevice()
  214783. {
  214784. close();
  214785. }
  214786. bool open (const double newSampleRate, const BigInteger& newChannels)
  214787. {
  214788. reservoirSize = 0;
  214789. reservoirCapacity = 16384;
  214790. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  214791. return openClient (newSampleRate, newChannels)
  214792. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient),
  214793. (void**) captureClient.resetAndGetPointerAddress())));
  214794. }
  214795. void close()
  214796. {
  214797. closeClient();
  214798. captureClient = 0;
  214799. reservoir.setSize (0);
  214800. }
  214801. template <class SourceType>
  214802. void updateFormatWithType (SourceType*)
  214803. {
  214804. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  214805. converter = new AudioData::ConverterInstance <AudioData::Pointer <SourceType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  214806. }
  214807. void updateFormat (bool isFloat)
  214808. {
  214809. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214810. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214811. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214812. else updateFormatWithType ((AudioData::Int16*) 0);
  214813. }
  214814. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  214815. {
  214816. if (numChannels <= 0)
  214817. return;
  214818. int offset = 0;
  214819. while (bufferSize > 0)
  214820. {
  214821. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  214822. {
  214823. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  214824. for (int i = 0; i < numDestBuffers; ++i)
  214825. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  214826. bufferSize -= samplesToDo;
  214827. offset += samplesToDo;
  214828. reservoirSize = 0;
  214829. }
  214830. else
  214831. {
  214832. UINT32 packetLength = 0;
  214833. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  214834. break;
  214835. if (packetLength == 0)
  214836. {
  214837. if (thread.threadShouldExit()
  214838. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214839. break;
  214840. continue;
  214841. }
  214842. uint8* inputData;
  214843. UINT32 numSamplesAvailable;
  214844. DWORD flags;
  214845. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  214846. {
  214847. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  214848. for (int i = 0; i < numDestBuffers; ++i)
  214849. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  214850. bufferSize -= samplesToDo;
  214851. offset += samplesToDo;
  214852. if (samplesToDo < (int) numSamplesAvailable)
  214853. {
  214854. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  214855. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  214856. bytesPerSample * actualNumChannels * reservoirSize);
  214857. }
  214858. captureClient->ReleaseBuffer (numSamplesAvailable);
  214859. }
  214860. }
  214861. }
  214862. }
  214863. ComSmartPtr <IAudioCaptureClient> captureClient;
  214864. MemoryBlock reservoir;
  214865. int reservoirSize, reservoirCapacity;
  214866. ScopedPointer <AudioData::Converter> converter;
  214867. private:
  214868. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIInputDevice);
  214869. };
  214870. class WASAPIOutputDevice : public WASAPIDeviceBase
  214871. {
  214872. public:
  214873. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  214874. : WASAPIDeviceBase (device_, useExclusiveMode_)
  214875. {
  214876. }
  214877. ~WASAPIOutputDevice()
  214878. {
  214879. close();
  214880. }
  214881. bool open (const double newSampleRate, const BigInteger& newChannels)
  214882. {
  214883. return openClient (newSampleRate, newChannels)
  214884. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  214885. }
  214886. void close()
  214887. {
  214888. closeClient();
  214889. renderClient = 0;
  214890. }
  214891. template <class DestType>
  214892. void updateFormatWithType (DestType*)
  214893. {
  214894. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  214895. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <DestType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  214896. }
  214897. void updateFormat (bool isFloat)
  214898. {
  214899. if (isFloat) updateFormatWithType ((AudioData::Float32*) 0);
  214900. else if (bytesPerSample == 4) updateFormatWithType ((AudioData::Int32*) 0);
  214901. else if (bytesPerSample == 3) updateFormatWithType ((AudioData::Int24*) 0);
  214902. else updateFormatWithType ((AudioData::Int16*) 0);
  214903. }
  214904. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  214905. {
  214906. if (numChannels <= 0)
  214907. return;
  214908. int offset = 0;
  214909. while (bufferSize > 0)
  214910. {
  214911. UINT32 padding = 0;
  214912. if (! check (client->GetCurrentPadding (&padding)))
  214913. return;
  214914. int samplesToDo = useExclusiveMode ? bufferSize
  214915. : jmin ((int) (actualBufferSize - padding), bufferSize);
  214916. if (samplesToDo <= 0)
  214917. {
  214918. if (thread.threadShouldExit()
  214919. || WaitForSingleObject (clientEvent, 1000) == WAIT_TIMEOUT)
  214920. break;
  214921. continue;
  214922. }
  214923. uint8* outputData = 0;
  214924. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  214925. {
  214926. for (int i = 0; i < numSrcBuffers; ++i)
  214927. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  214928. renderClient->ReleaseBuffer (samplesToDo, 0);
  214929. offset += samplesToDo;
  214930. bufferSize -= samplesToDo;
  214931. }
  214932. }
  214933. }
  214934. ComSmartPtr <IAudioRenderClient> renderClient;
  214935. ScopedPointer <AudioData::Converter> converter;
  214936. private:
  214937. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIOutputDevice);
  214938. };
  214939. class WASAPIAudioIODevice : public AudioIODevice,
  214940. public Thread
  214941. {
  214942. public:
  214943. WASAPIAudioIODevice (const String& deviceName,
  214944. const String& outputDeviceId_,
  214945. const String& inputDeviceId_,
  214946. const bool useExclusiveMode_)
  214947. : AudioIODevice (deviceName, "Windows Audio"),
  214948. Thread ("Juce WASAPI"),
  214949. outputDeviceId (outputDeviceId_),
  214950. inputDeviceId (inputDeviceId_),
  214951. useExclusiveMode (useExclusiveMode_),
  214952. isOpen_ (false),
  214953. isStarted (false),
  214954. currentBufferSizeSamples (0),
  214955. currentSampleRate (0),
  214956. callback (0)
  214957. {
  214958. }
  214959. ~WASAPIAudioIODevice()
  214960. {
  214961. close();
  214962. }
  214963. bool initialise()
  214964. {
  214965. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  214966. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  214967. latencyIn = latencyOut = 0;
  214968. Array <double> ratesIn, ratesOut;
  214969. if (createDevices())
  214970. {
  214971. jassert (inputDevice != 0 || outputDevice != 0);
  214972. if (inputDevice != 0 && outputDevice != 0)
  214973. {
  214974. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  214975. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  214976. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  214977. sampleRates = inputDevice->rates;
  214978. sampleRates.removeValuesNotIn (outputDevice->rates);
  214979. }
  214980. else
  214981. {
  214982. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  214983. : static_cast<WASAPIDeviceBase*> (outputDevice);
  214984. defaultSampleRate = d->defaultSampleRate;
  214985. minBufferSize = d->minBufferSize;
  214986. defaultBufferSize = d->defaultBufferSize;
  214987. sampleRates = d->rates;
  214988. }
  214989. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  214990. if (minBufferSize != defaultBufferSize)
  214991. bufferSizes.addUsingDefaultSort (minBufferSize);
  214992. int n = 64;
  214993. for (int i = 0; i < 40; ++i)
  214994. {
  214995. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  214996. bufferSizes.addUsingDefaultSort (n);
  214997. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  214998. }
  214999. return true;
  215000. }
  215001. return false;
  215002. }
  215003. const StringArray getOutputChannelNames()
  215004. {
  215005. StringArray outChannels;
  215006. if (outputDevice != 0)
  215007. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  215008. outChannels.add ("Output channel " + String (i));
  215009. return outChannels;
  215010. }
  215011. const StringArray getInputChannelNames()
  215012. {
  215013. StringArray inChannels;
  215014. if (inputDevice != 0)
  215015. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  215016. inChannels.add ("Input channel " + String (i));
  215017. return inChannels;
  215018. }
  215019. int getNumSampleRates() { return sampleRates.size(); }
  215020. double getSampleRate (int index) { return sampleRates [index]; }
  215021. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  215022. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  215023. int getDefaultBufferSize() { return defaultBufferSize; }
  215024. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  215025. double getCurrentSampleRate() { return currentSampleRate; }
  215026. int getCurrentBitDepth() { return 32; }
  215027. int getOutputLatencyInSamples() { return latencyOut; }
  215028. int getInputLatencyInSamples() { return latencyIn; }
  215029. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  215030. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  215031. const String getLastError() { return lastError; }
  215032. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  215033. double sampleRate, int bufferSizeSamples)
  215034. {
  215035. close();
  215036. lastError = String::empty;
  215037. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  215038. {
  215039. lastError = "The input and output devices don't share a common sample rate!";
  215040. return lastError;
  215041. }
  215042. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  215043. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  215044. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  215045. {
  215046. lastError = "Couldn't open the input device!";
  215047. return lastError;
  215048. }
  215049. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  215050. {
  215051. close();
  215052. lastError = "Couldn't open the output device!";
  215053. return lastError;
  215054. }
  215055. if (inputDevice != 0) ResetEvent (inputDevice->clientEvent);
  215056. if (outputDevice != 0) ResetEvent (outputDevice->clientEvent);
  215057. startThread (8);
  215058. Thread::sleep (5);
  215059. if (inputDevice != 0 && inputDevice->client != 0)
  215060. {
  215061. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  215062. HRESULT hr = inputDevice->client->Start();
  215063. logFailure (hr); //xxx handle this
  215064. }
  215065. if (outputDevice != 0 && outputDevice->client != 0)
  215066. {
  215067. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  215068. HRESULT hr = outputDevice->client->Start();
  215069. logFailure (hr); //xxx handle this
  215070. }
  215071. isOpen_ = true;
  215072. return lastError;
  215073. }
  215074. void close()
  215075. {
  215076. stop();
  215077. signalThreadShouldExit();
  215078. if (inputDevice != 0) SetEvent (inputDevice->clientEvent);
  215079. if (outputDevice != 0) SetEvent (outputDevice->clientEvent);
  215080. stopThread (5000);
  215081. if (inputDevice != 0) inputDevice->close();
  215082. if (outputDevice != 0) outputDevice->close();
  215083. isOpen_ = false;
  215084. }
  215085. bool isOpen() { return isOpen_ && isThreadRunning(); }
  215086. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  215087. void start (AudioIODeviceCallback* call)
  215088. {
  215089. if (isOpen_ && call != 0 && ! isStarted)
  215090. {
  215091. if (! isThreadRunning())
  215092. {
  215093. // something's gone wrong and the thread's stopped..
  215094. isOpen_ = false;
  215095. return;
  215096. }
  215097. call->audioDeviceAboutToStart (this);
  215098. const ScopedLock sl (startStopLock);
  215099. callback = call;
  215100. isStarted = true;
  215101. }
  215102. }
  215103. void stop()
  215104. {
  215105. if (isStarted)
  215106. {
  215107. AudioIODeviceCallback* const callbackLocal = callback;
  215108. {
  215109. const ScopedLock sl (startStopLock);
  215110. isStarted = false;
  215111. }
  215112. if (callbackLocal != 0)
  215113. callbackLocal->audioDeviceStopped();
  215114. }
  215115. }
  215116. void setMMThreadPriority()
  215117. {
  215118. DynamicLibraryLoader dll ("avrt.dll");
  215119. DynamicLibraryImport (AvSetMmThreadCharacteristicsW, avSetMmThreadCharacteristics, HANDLE, dll, (LPCWSTR, LPDWORD))
  215120. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  215121. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  215122. {
  215123. DWORD dummy = 0;
  215124. HANDLE h = avSetMmThreadCharacteristics (L"Pro Audio", &dummy);
  215125. if (h != 0)
  215126. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  215127. }
  215128. }
  215129. void run()
  215130. {
  215131. setMMThreadPriority();
  215132. const int bufferSize = currentBufferSizeSamples;
  215133. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  215134. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  215135. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  215136. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  215137. float** const inputBuffers = ins.getArrayOfChannels();
  215138. float** const outputBuffers = outs.getArrayOfChannels();
  215139. ins.clear();
  215140. while (! threadShouldExit())
  215141. {
  215142. if (inputDevice != 0)
  215143. {
  215144. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  215145. if (threadShouldExit())
  215146. break;
  215147. }
  215148. JUCE_TRY
  215149. {
  215150. const ScopedLock sl (startStopLock);
  215151. if (isStarted)
  215152. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers), numInputBuffers,
  215153. outputBuffers, numOutputBuffers, bufferSize);
  215154. else
  215155. outs.clear();
  215156. }
  215157. JUCE_CATCH_EXCEPTION
  215158. if (outputDevice != 0)
  215159. outputDevice->copyBuffers (const_cast <const float**> (outputBuffers), numOutputBuffers, bufferSize, *this);
  215160. }
  215161. }
  215162. String outputDeviceId, inputDeviceId;
  215163. String lastError;
  215164. private:
  215165. // Device stats...
  215166. ScopedPointer<WASAPIInputDevice> inputDevice;
  215167. ScopedPointer<WASAPIOutputDevice> outputDevice;
  215168. const bool useExclusiveMode;
  215169. double defaultSampleRate;
  215170. int minBufferSize, defaultBufferSize;
  215171. int latencyIn, latencyOut;
  215172. Array <double> sampleRates;
  215173. Array <int> bufferSizes;
  215174. // Active state...
  215175. bool isOpen_, isStarted;
  215176. int currentBufferSizeSamples;
  215177. double currentSampleRate;
  215178. AudioIODeviceCallback* callback;
  215179. CriticalSection startStopLock;
  215180. bool createDevices()
  215181. {
  215182. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215183. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215184. return false;
  215185. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215186. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  215187. return false;
  215188. UINT32 numDevices = 0;
  215189. if (! check (deviceCollection->GetCount (&numDevices)))
  215190. return false;
  215191. for (UINT32 i = 0; i < numDevices; ++i)
  215192. {
  215193. ComSmartPtr <IMMDevice> device;
  215194. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215195. continue;
  215196. const String deviceId (getDeviceID (device));
  215197. if (deviceId.isEmpty())
  215198. continue;
  215199. const EDataFlow flow = getDataFlow (device);
  215200. if (deviceId == inputDeviceId && flow == eCapture)
  215201. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  215202. else if (deviceId == outputDeviceId && flow == eRender)
  215203. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  215204. }
  215205. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  215206. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  215207. }
  215208. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODevice);
  215209. };
  215210. class WASAPIAudioIODeviceType : public AudioIODeviceType
  215211. {
  215212. public:
  215213. WASAPIAudioIODeviceType()
  215214. : AudioIODeviceType ("Windows Audio"),
  215215. hasScanned (false)
  215216. {
  215217. }
  215218. ~WASAPIAudioIODeviceType()
  215219. {
  215220. }
  215221. void scanForDevices()
  215222. {
  215223. hasScanned = true;
  215224. outputDeviceNames.clear();
  215225. inputDeviceNames.clear();
  215226. outputDeviceIds.clear();
  215227. inputDeviceIds.clear();
  215228. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  215229. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  215230. return;
  215231. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  215232. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  215233. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  215234. UINT32 numDevices = 0;
  215235. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  215236. && check (deviceCollection->GetCount (&numDevices))))
  215237. return;
  215238. for (UINT32 i = 0; i < numDevices; ++i)
  215239. {
  215240. ComSmartPtr <IMMDevice> device;
  215241. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  215242. continue;
  215243. const String deviceId (getDeviceID (device));
  215244. DWORD state = 0;
  215245. if (! check (device->GetState (&state)))
  215246. continue;
  215247. if (state != DEVICE_STATE_ACTIVE)
  215248. continue;
  215249. String name;
  215250. {
  215251. ComSmartPtr <IPropertyStore> properties;
  215252. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  215253. continue;
  215254. PROPVARIANT value;
  215255. PropVariantInit (&value);
  215256. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  215257. name = value.pwszVal;
  215258. PropVariantClear (&value);
  215259. }
  215260. const EDataFlow flow = getDataFlow (device);
  215261. if (flow == eRender)
  215262. {
  215263. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  215264. outputDeviceIds.insert (index, deviceId);
  215265. outputDeviceNames.insert (index, name);
  215266. }
  215267. else if (flow == eCapture)
  215268. {
  215269. const int index = (deviceId == defaultCapture) ? 0 : -1;
  215270. inputDeviceIds.insert (index, deviceId);
  215271. inputDeviceNames.insert (index, name);
  215272. }
  215273. }
  215274. inputDeviceNames.appendNumbersToDuplicates (false, false);
  215275. outputDeviceNames.appendNumbersToDuplicates (false, false);
  215276. }
  215277. const StringArray getDeviceNames (bool wantInputNames) const
  215278. {
  215279. jassert (hasScanned); // need to call scanForDevices() before doing this
  215280. return wantInputNames ? inputDeviceNames
  215281. : outputDeviceNames;
  215282. }
  215283. int getDefaultDeviceIndex (bool /*forInput*/) const
  215284. {
  215285. jassert (hasScanned); // need to call scanForDevices() before doing this
  215286. return 0;
  215287. }
  215288. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215289. {
  215290. jassert (hasScanned); // need to call scanForDevices() before doing this
  215291. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  215292. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  215293. : outputDeviceIds.indexOf (d->outputDeviceId));
  215294. }
  215295. bool hasSeparateInputsAndOutputs() const { return true; }
  215296. AudioIODevice* createDevice (const String& outputDeviceName,
  215297. const String& inputDeviceName)
  215298. {
  215299. jassert (hasScanned); // need to call scanForDevices() before doing this
  215300. const bool useExclusiveMode = false;
  215301. ScopedPointer<WASAPIAudioIODevice> device;
  215302. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215303. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215304. if (outputIndex >= 0 || inputIndex >= 0)
  215305. {
  215306. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215307. : inputDeviceName,
  215308. outputDeviceIds [outputIndex],
  215309. inputDeviceIds [inputIndex],
  215310. useExclusiveMode);
  215311. if (! device->initialise())
  215312. device = 0;
  215313. }
  215314. return device.release();
  215315. }
  215316. StringArray outputDeviceNames, outputDeviceIds;
  215317. StringArray inputDeviceNames, inputDeviceIds;
  215318. private:
  215319. bool hasScanned;
  215320. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  215321. {
  215322. String s;
  215323. IMMDevice* dev = 0;
  215324. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  215325. eMultimedia, &dev)))
  215326. {
  215327. WCHAR* deviceId = 0;
  215328. if (check (dev->GetId (&deviceId)))
  215329. {
  215330. s = String (deviceId);
  215331. CoTaskMemFree (deviceId);
  215332. }
  215333. dev->Release();
  215334. }
  215335. return s;
  215336. }
  215337. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WASAPIAudioIODeviceType);
  215338. };
  215339. }
  215340. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  215341. {
  215342. return new WasapiClasses::WASAPIAudioIODeviceType();
  215343. }
  215344. #endif
  215345. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  215346. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  215347. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215348. // compiled on its own).
  215349. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  215350. class DShowCameraDeviceInteral : public ChangeBroadcaster
  215351. {
  215352. public:
  215353. DShowCameraDeviceInteral (CameraDevice* const owner_,
  215354. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  215355. const ComSmartPtr <IBaseFilter>& filter_,
  215356. int minWidth, int minHeight,
  215357. int maxWidth, int maxHeight)
  215358. : owner (owner_),
  215359. captureGraphBuilder (captureGraphBuilder_),
  215360. filter (filter_),
  215361. ok (false),
  215362. imageNeedsFlipping (false),
  215363. width (0),
  215364. height (0),
  215365. activeUsers (0),
  215366. recordNextFrameTime (false),
  215367. previewMaxFPS (60)
  215368. {
  215369. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  215370. if (FAILED (hr))
  215371. return;
  215372. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  215373. if (FAILED (hr))
  215374. return;
  215375. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  215376. if (FAILED (hr))
  215377. return;
  215378. {
  215379. ComSmartPtr <IAMStreamConfig> streamConfig;
  215380. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  215381. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  215382. if (streamConfig != 0)
  215383. {
  215384. getVideoSizes (streamConfig);
  215385. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  215386. return;
  215387. }
  215388. }
  215389. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  215390. if (FAILED (hr))
  215391. return;
  215392. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  215393. if (FAILED (hr))
  215394. return;
  215395. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  215396. if (FAILED (hr))
  215397. return;
  215398. if (! connectFilters (filter, smartTee))
  215399. return;
  215400. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  215401. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  215402. if (FAILED (hr))
  215403. return;
  215404. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  215405. if (FAILED (hr))
  215406. return;
  215407. AM_MEDIA_TYPE mt;
  215408. zerostruct (mt);
  215409. mt.majortype = MEDIATYPE_Video;
  215410. mt.subtype = MEDIASUBTYPE_RGB24;
  215411. mt.formattype = FORMAT_VideoInfo;
  215412. sampleGrabber->SetMediaType (&mt);
  215413. callback = new GrabberCallback (*this);
  215414. hr = sampleGrabber->SetCallback (callback, 1);
  215415. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  215416. if (FAILED (hr))
  215417. return;
  215418. ComSmartPtr <IPin> grabberInputPin;
  215419. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  215420. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  215421. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  215422. return;
  215423. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  215424. if (FAILED (hr))
  215425. return;
  215426. zerostruct (mt);
  215427. hr = sampleGrabber->GetConnectedMediaType (&mt);
  215428. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  215429. width = pVih->bmiHeader.biWidth;
  215430. height = pVih->bmiHeader.biHeight;
  215431. ComSmartPtr <IBaseFilter> nullFilter;
  215432. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  215433. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  215434. if (connectFilters (sampleGrabberBase, nullFilter)
  215435. && addGraphToRot())
  215436. {
  215437. activeImage = Image (Image::RGB, width, height, true);
  215438. loadingImage = Image (Image::RGB, width, height, true);
  215439. ok = true;
  215440. }
  215441. }
  215442. ~DShowCameraDeviceInteral()
  215443. {
  215444. if (mediaControl != 0)
  215445. mediaControl->Stop();
  215446. removeGraphFromRot();
  215447. for (int i = viewerComps.size(); --i >= 0;)
  215448. viewerComps.getUnchecked(i)->ownerDeleted();
  215449. callback = 0;
  215450. graphBuilder = 0;
  215451. sampleGrabber = 0;
  215452. mediaControl = 0;
  215453. filter = 0;
  215454. captureGraphBuilder = 0;
  215455. smartTee = 0;
  215456. smartTeePreviewOutputPin = 0;
  215457. smartTeeCaptureOutputPin = 0;
  215458. asfWriter = 0;
  215459. }
  215460. void addUser()
  215461. {
  215462. if (ok && activeUsers++ == 0)
  215463. mediaControl->Run();
  215464. }
  215465. void removeUser()
  215466. {
  215467. if (ok && --activeUsers == 0)
  215468. mediaControl->Stop();
  215469. }
  215470. int getPreviewMaxFPS() const
  215471. {
  215472. return previewMaxFPS;
  215473. }
  215474. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  215475. {
  215476. if (recordNextFrameTime)
  215477. {
  215478. const double defaultCameraLatency = 0.1;
  215479. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  215480. recordNextFrameTime = false;
  215481. ComSmartPtr <IPin> pin;
  215482. if (getPin (filter, PINDIR_OUTPUT, pin))
  215483. {
  215484. ComSmartPtr <IAMPushSource> pushSource;
  215485. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  215486. if (pushSource != 0)
  215487. {
  215488. REFERENCE_TIME latency = 0;
  215489. hr = pushSource->GetLatency (&latency);
  215490. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  215491. }
  215492. }
  215493. }
  215494. {
  215495. const int lineStride = width * 3;
  215496. const ScopedLock sl (imageSwapLock);
  215497. {
  215498. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  215499. for (int i = 0; i < height; ++i)
  215500. memcpy (destData.getLinePointer ((height - 1) - i),
  215501. buffer + lineStride * i,
  215502. lineStride);
  215503. }
  215504. imageNeedsFlipping = true;
  215505. }
  215506. if (listeners.size() > 0)
  215507. callListeners (loadingImage);
  215508. sendChangeMessage();
  215509. }
  215510. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  215511. {
  215512. if (imageNeedsFlipping)
  215513. {
  215514. const ScopedLock sl (imageSwapLock);
  215515. swapVariables (loadingImage, activeImage);
  215516. imageNeedsFlipping = false;
  215517. }
  215518. RectanglePlacement rp (RectanglePlacement::centred);
  215519. double dx = 0, dy = 0, dw = width, dh = height;
  215520. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  215521. const int rx = roundToInt (dx), ry = roundToInt (dy);
  215522. const int rw = roundToInt (dw), rh = roundToInt (dh);
  215523. {
  215524. Graphics::ScopedSaveState ss (g);
  215525. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  215526. g.fillAll (Colours::black);
  215527. }
  215528. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  215529. }
  215530. bool createFileCaptureFilter (const File& file, int quality)
  215531. {
  215532. removeFileCaptureFilter();
  215533. file.deleteFile();
  215534. mediaControl->Stop();
  215535. firstRecordedTime = Time();
  215536. recordNextFrameTime = true;
  215537. previewMaxFPS = 60;
  215538. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  215539. if (SUCCEEDED (hr))
  215540. {
  215541. ComSmartPtr <IFileSinkFilter> fileSink;
  215542. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  215543. if (SUCCEEDED (hr))
  215544. {
  215545. hr = fileSink->SetFileName (file.getFullPathName().toUTF16(), 0);
  215546. if (SUCCEEDED (hr))
  215547. {
  215548. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  215549. if (SUCCEEDED (hr))
  215550. {
  215551. ComSmartPtr <IConfigAsfWriter> asfConfig;
  215552. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  215553. asfConfig->SetIndexMode (true);
  215554. ComSmartPtr <IWMProfileManager> profileManager;
  215555. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  215556. // This gibberish is the DirectShow profile for a video-only wmv file.
  215557. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  215558. "<streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" "
  215559. "streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  215560. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  215561. "<videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  215562. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" "
  215563. "btemporalcompression=\"1\" lsamplesize=\"0\">"
  215564. "<videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  215565. "<rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215566. "<rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  215567. "<bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  215568. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" "
  215569. "biclrused=\"0\" biclrimportant=\"0\"/>"
  215570. "</videoinfoheader>"
  215571. "</wmmediatype>"
  215572. "</streamconfig>"
  215573. "</profile>");
  215574. const int fps[] = { 10, 15, 30 };
  215575. int maxFramesPerSecond = fps [jlimit (0, numElementsInArray (fps) - 1, quality & 0xff)];
  215576. if ((quality & 0xff000000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215577. maxFramesPerSecond = (quality >> 24) & 0xff;
  215578. prof = prof.replace ("$WIDTH", String (width))
  215579. .replace ("$HEIGHT", String (height))
  215580. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  215581. ComSmartPtr <IWMProfile> currentProfile;
  215582. hr = profileManager->LoadProfileByData (prof.toUTF16(), currentProfile.resetAndGetPointerAddress());
  215583. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  215584. if (SUCCEEDED (hr))
  215585. {
  215586. ComSmartPtr <IPin> asfWriterInputPin;
  215587. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  215588. {
  215589. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  215590. if (SUCCEEDED (hr) && ok && activeUsers > 0
  215591. && SUCCEEDED (mediaControl->Run()))
  215592. {
  215593. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  215594. if ((quality & 0x00ff0000) != 0) // (internal hacky way to pass explicit frame rates for testing)
  215595. previewMaxFPS = (quality >> 16) & 0xff;
  215596. return true;
  215597. }
  215598. }
  215599. }
  215600. }
  215601. }
  215602. }
  215603. }
  215604. removeFileCaptureFilter();
  215605. if (ok && activeUsers > 0)
  215606. mediaControl->Run();
  215607. return false;
  215608. }
  215609. void removeFileCaptureFilter()
  215610. {
  215611. mediaControl->Stop();
  215612. if (asfWriter != 0)
  215613. {
  215614. graphBuilder->RemoveFilter (asfWriter);
  215615. asfWriter = 0;
  215616. }
  215617. if (ok && activeUsers > 0)
  215618. mediaControl->Run();
  215619. previewMaxFPS = 60;
  215620. }
  215621. void addListener (CameraDevice::Listener* listenerToAdd)
  215622. {
  215623. const ScopedLock sl (listenerLock);
  215624. if (listeners.size() == 0)
  215625. addUser();
  215626. listeners.addIfNotAlreadyThere (listenerToAdd);
  215627. }
  215628. void removeListener (CameraDevice::Listener* listenerToRemove)
  215629. {
  215630. const ScopedLock sl (listenerLock);
  215631. listeners.removeValue (listenerToRemove);
  215632. if (listeners.size() == 0)
  215633. removeUser();
  215634. }
  215635. void callListeners (const Image& image)
  215636. {
  215637. const ScopedLock sl (listenerLock);
  215638. for (int i = listeners.size(); --i >= 0;)
  215639. {
  215640. CameraDevice::Listener* const l = listeners[i];
  215641. if (l != 0)
  215642. l->imageReceived (image);
  215643. }
  215644. }
  215645. class DShowCaptureViewerComp : public Component,
  215646. public ChangeListener
  215647. {
  215648. public:
  215649. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  215650. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  215651. {
  215652. setOpaque (true);
  215653. owner->addChangeListener (this);
  215654. owner->addUser();
  215655. owner->viewerComps.add (this);
  215656. setSize (owner->width, owner->height);
  215657. }
  215658. ~DShowCaptureViewerComp()
  215659. {
  215660. if (owner != 0)
  215661. {
  215662. owner->viewerComps.removeValue (this);
  215663. owner->removeUser();
  215664. owner->removeChangeListener (this);
  215665. }
  215666. }
  215667. void ownerDeleted()
  215668. {
  215669. owner = 0;
  215670. }
  215671. void paint (Graphics& g)
  215672. {
  215673. g.setColour (Colours::black);
  215674. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  215675. if (owner != 0)
  215676. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  215677. else
  215678. g.fillAll (Colours::black);
  215679. }
  215680. void changeListenerCallback (ChangeBroadcaster*)
  215681. {
  215682. const int64 now = Time::currentTimeMillis();
  215683. if (now >= lastRepaintTime + (1000 / maxFPS))
  215684. {
  215685. lastRepaintTime = now;
  215686. repaint();
  215687. if (owner != 0)
  215688. maxFPS = owner->getPreviewMaxFPS();
  215689. }
  215690. }
  215691. private:
  215692. DShowCameraDeviceInteral* owner;
  215693. int maxFPS;
  215694. int64 lastRepaintTime;
  215695. };
  215696. bool ok;
  215697. int width, height;
  215698. Time firstRecordedTime;
  215699. Array <DShowCaptureViewerComp*> viewerComps;
  215700. private:
  215701. CameraDevice* const owner;
  215702. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215703. ComSmartPtr <IBaseFilter> filter;
  215704. ComSmartPtr <IBaseFilter> smartTee;
  215705. ComSmartPtr <IGraphBuilder> graphBuilder;
  215706. ComSmartPtr <ISampleGrabber> sampleGrabber;
  215707. ComSmartPtr <IMediaControl> mediaControl;
  215708. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  215709. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  215710. ComSmartPtr <IBaseFilter> asfWriter;
  215711. int activeUsers;
  215712. Array <int> widths, heights;
  215713. DWORD graphRegistrationID;
  215714. CriticalSection imageSwapLock;
  215715. bool imageNeedsFlipping;
  215716. Image loadingImage;
  215717. Image activeImage;
  215718. bool recordNextFrameTime;
  215719. int previewMaxFPS;
  215720. void getVideoSizes (IAMStreamConfig* const streamConfig)
  215721. {
  215722. widths.clear();
  215723. heights.clear();
  215724. int count = 0, size = 0;
  215725. streamConfig->GetNumberOfCapabilities (&count, &size);
  215726. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215727. {
  215728. for (int i = 0; i < count; ++i)
  215729. {
  215730. VIDEO_STREAM_CONFIG_CAPS scc;
  215731. AM_MEDIA_TYPE* config;
  215732. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215733. if (SUCCEEDED (hr))
  215734. {
  215735. const int w = scc.InputSize.cx;
  215736. const int h = scc.InputSize.cy;
  215737. bool duplicate = false;
  215738. for (int j = widths.size(); --j >= 0;)
  215739. {
  215740. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  215741. {
  215742. duplicate = true;
  215743. break;
  215744. }
  215745. }
  215746. if (! duplicate)
  215747. {
  215748. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  215749. widths.add (w);
  215750. heights.add (h);
  215751. }
  215752. deleteMediaType (config);
  215753. }
  215754. }
  215755. }
  215756. }
  215757. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  215758. const int minWidth, const int minHeight,
  215759. const int maxWidth, const int maxHeight)
  215760. {
  215761. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  215762. streamConfig->GetNumberOfCapabilities (&count, &size);
  215763. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  215764. {
  215765. AM_MEDIA_TYPE* config;
  215766. VIDEO_STREAM_CONFIG_CAPS scc;
  215767. for (int i = 0; i < count; ++i)
  215768. {
  215769. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  215770. if (SUCCEEDED (hr))
  215771. {
  215772. if (scc.InputSize.cx >= minWidth
  215773. && scc.InputSize.cy >= minHeight
  215774. && scc.InputSize.cx <= maxWidth
  215775. && scc.InputSize.cy <= maxHeight)
  215776. {
  215777. int area = scc.InputSize.cx * scc.InputSize.cy;
  215778. if (area > bestArea)
  215779. {
  215780. bestIndex = i;
  215781. bestArea = area;
  215782. }
  215783. }
  215784. deleteMediaType (config);
  215785. }
  215786. }
  215787. if (bestIndex >= 0)
  215788. {
  215789. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  215790. hr = streamConfig->SetFormat (config);
  215791. deleteMediaType (config);
  215792. return SUCCEEDED (hr);
  215793. }
  215794. }
  215795. return false;
  215796. }
  215797. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  215798. {
  215799. ComSmartPtr <IEnumPins> enumerator;
  215800. ComSmartPtr <IPin> pin;
  215801. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  215802. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  215803. {
  215804. PIN_DIRECTION dir;
  215805. pin->QueryDirection (&dir);
  215806. if (wantedDirection == dir)
  215807. {
  215808. PIN_INFO info;
  215809. zerostruct (info);
  215810. pin->QueryPinInfo (&info);
  215811. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  215812. {
  215813. result = pin;
  215814. return true;
  215815. }
  215816. }
  215817. }
  215818. return false;
  215819. }
  215820. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  215821. {
  215822. ComSmartPtr <IPin> in, out;
  215823. return getPin (first, PINDIR_OUTPUT, out)
  215824. && getPin (second, PINDIR_INPUT, in)
  215825. && SUCCEEDED (graphBuilder->Connect (out, in));
  215826. }
  215827. bool addGraphToRot()
  215828. {
  215829. ComSmartPtr <IRunningObjectTable> rot;
  215830. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215831. return false;
  215832. ComSmartPtr <IMoniker> moniker;
  215833. WCHAR buffer[128];
  215834. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  215835. if (FAILED (hr))
  215836. return false;
  215837. graphRegistrationID = 0;
  215838. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  215839. }
  215840. void removeGraphFromRot()
  215841. {
  215842. ComSmartPtr <IRunningObjectTable> rot;
  215843. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  215844. rot->Revoke (graphRegistrationID);
  215845. }
  215846. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  215847. {
  215848. if (pmt->cbFormat != 0)
  215849. CoTaskMemFree ((PVOID) pmt->pbFormat);
  215850. if (pmt->pUnk != 0)
  215851. pmt->pUnk->Release();
  215852. CoTaskMemFree (pmt);
  215853. }
  215854. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  215855. {
  215856. public:
  215857. GrabberCallback (DShowCameraDeviceInteral& owner_)
  215858. : owner (owner_)
  215859. {
  215860. }
  215861. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  215862. {
  215863. return E_FAIL;
  215864. }
  215865. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  215866. {
  215867. owner.handleFrame (time, buffer, bufferSize);
  215868. return S_OK;
  215869. }
  215870. private:
  215871. DShowCameraDeviceInteral& owner;
  215872. GrabberCallback (const GrabberCallback&);
  215873. GrabberCallback& operator= (const GrabberCallback&);
  215874. };
  215875. ComSmartPtr <GrabberCallback> callback;
  215876. Array <CameraDevice::Listener*> listeners;
  215877. CriticalSection listenerLock;
  215878. JUCE_DECLARE_NON_COPYABLE (DShowCameraDeviceInteral);
  215879. };
  215880. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  215881. : name (name_)
  215882. {
  215883. isRecording = false;
  215884. }
  215885. CameraDevice::~CameraDevice()
  215886. {
  215887. stopRecording();
  215888. delete static_cast <DShowCameraDeviceInteral*> (internal);
  215889. internal = 0;
  215890. }
  215891. Component* CameraDevice::createViewerComponent()
  215892. {
  215893. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  215894. }
  215895. const String CameraDevice::getFileExtension()
  215896. {
  215897. return ".wmv";
  215898. }
  215899. void CameraDevice::startRecordingToFile (const File& file, int quality)
  215900. {
  215901. stopRecording();
  215902. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215903. d->addUser();
  215904. isRecording = d->createFileCaptureFilter (file, quality);
  215905. }
  215906. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  215907. {
  215908. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215909. return d->firstRecordedTime;
  215910. }
  215911. void CameraDevice::stopRecording()
  215912. {
  215913. if (isRecording)
  215914. {
  215915. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215916. d->removeFileCaptureFilter();
  215917. d->removeUser();
  215918. isRecording = false;
  215919. }
  215920. }
  215921. void CameraDevice::addListener (Listener* listenerToAdd)
  215922. {
  215923. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215924. if (listenerToAdd != 0)
  215925. d->addListener (listenerToAdd);
  215926. }
  215927. void CameraDevice::removeListener (Listener* listenerToRemove)
  215928. {
  215929. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  215930. if (listenerToRemove != 0)
  215931. d->removeListener (listenerToRemove);
  215932. }
  215933. namespace
  215934. {
  215935. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  215936. const int deviceIndexToOpen,
  215937. String& name)
  215938. {
  215939. int index = 0;
  215940. ComSmartPtr <IBaseFilter> result;
  215941. ComSmartPtr <ICreateDevEnum> pDevEnum;
  215942. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  215943. if (SUCCEEDED (hr))
  215944. {
  215945. ComSmartPtr <IEnumMoniker> enumerator;
  215946. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  215947. if (SUCCEEDED (hr) && enumerator != 0)
  215948. {
  215949. ComSmartPtr <IMoniker> moniker;
  215950. ULONG fetched;
  215951. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  215952. {
  215953. ComSmartPtr <IBaseFilter> captureFilter;
  215954. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  215955. if (SUCCEEDED (hr))
  215956. {
  215957. ComSmartPtr <IPropertyBag> propertyBag;
  215958. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  215959. if (SUCCEEDED (hr))
  215960. {
  215961. VARIANT var;
  215962. var.vt = VT_BSTR;
  215963. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  215964. propertyBag = 0;
  215965. if (SUCCEEDED (hr))
  215966. {
  215967. if (names != 0)
  215968. names->add (var.bstrVal);
  215969. if (index == deviceIndexToOpen)
  215970. {
  215971. name = var.bstrVal;
  215972. result = captureFilter;
  215973. break;
  215974. }
  215975. ++index;
  215976. }
  215977. }
  215978. }
  215979. }
  215980. }
  215981. }
  215982. return result;
  215983. }
  215984. }
  215985. const StringArray CameraDevice::getAvailableDevices()
  215986. {
  215987. StringArray devs;
  215988. String dummy;
  215989. enumerateCameras (&devs, -1, dummy);
  215990. return devs;
  215991. }
  215992. CameraDevice* CameraDevice::openDevice (int index,
  215993. int minWidth, int minHeight,
  215994. int maxWidth, int maxHeight)
  215995. {
  215996. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  215997. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  215998. if (SUCCEEDED (hr))
  215999. {
  216000. String name;
  216001. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  216002. if (filter != 0)
  216003. {
  216004. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  216005. DShowCameraDeviceInteral* const intern
  216006. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  216007. minWidth, minHeight, maxWidth, maxHeight);
  216008. cam->internal = intern;
  216009. if (intern->ok)
  216010. return cam.release();
  216011. }
  216012. }
  216013. return 0;
  216014. }
  216015. #endif
  216016. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  216017. #endif
  216018. // Auto-link the other win32 libs that are needed by library calls..
  216019. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  216020. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216021. // Auto-links to various win32 libs that are needed by library calls..
  216022. #pragma comment(lib, "kernel32.lib")
  216023. #pragma comment(lib, "user32.lib")
  216024. #pragma comment(lib, "shell32.lib")
  216025. #pragma comment(lib, "gdi32.lib")
  216026. #pragma comment(lib, "vfw32.lib")
  216027. #pragma comment(lib, "comdlg32.lib")
  216028. #pragma comment(lib, "winmm.lib")
  216029. #pragma comment(lib, "wininet.lib")
  216030. #pragma comment(lib, "ole32.lib")
  216031. #pragma comment(lib, "oleaut32.lib")
  216032. #pragma comment(lib, "advapi32.lib")
  216033. #pragma comment(lib, "ws2_32.lib")
  216034. #pragma comment(lib, "version.lib")
  216035. #pragma comment(lib, "shlwapi.lib")
  216036. #ifdef _NATIVE_WCHAR_T_DEFINED
  216037. #ifdef _DEBUG
  216038. #pragma comment(lib, "comsuppwd.lib")
  216039. #else
  216040. #pragma comment(lib, "comsuppw.lib")
  216041. #endif
  216042. #else
  216043. #ifdef _DEBUG
  216044. #pragma comment(lib, "comsuppd.lib")
  216045. #else
  216046. #pragma comment(lib, "comsupp.lib")
  216047. #endif
  216048. #endif
  216049. #if JUCE_OPENGL
  216050. #pragma comment(lib, "OpenGL32.Lib")
  216051. #pragma comment(lib, "GlU32.Lib")
  216052. #endif
  216053. #if JUCE_QUICKTIME
  216054. #pragma comment (lib, "QTMLClient.lib")
  216055. #endif
  216056. #if JUCE_USE_CAMERA
  216057. #pragma comment (lib, "Strmiids.lib")
  216058. #pragma comment (lib, "wmvcore.lib")
  216059. #endif
  216060. #if JUCE_DIRECT2D
  216061. #pragma comment (lib, "Dwrite.lib")
  216062. #pragma comment (lib, "D2d1.lib")
  216063. #endif
  216064. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  216065. #endif
  216066. END_JUCE_NAMESPACE
  216067. #endif
  216068. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  216069. #elif JUCE_LINUX
  216070. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  216071. /*
  216072. This file wraps together all the mac-specific code, so that
  216073. we can include all the native headers just once, and compile all our
  216074. platform-specific stuff in one big lump, keeping it out of the way of
  216075. the rest of the codebase.
  216076. */
  216077. #if JUCE_LINUX
  216078. #undef JUCE_BUILD_NATIVE
  216079. #define JUCE_BUILD_NATIVE 1
  216080. BEGIN_JUCE_NAMESPACE
  216081. #define JUCE_INCLUDED_FILE 1
  216082. // Now include the actual code files..
  216083. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  216084. /*
  216085. This file contains posix routines that are common to both the Linux and Mac builds.
  216086. It gets included directly in the cpp files for these platforms.
  216087. */
  216088. CriticalSection::CriticalSection() throw()
  216089. {
  216090. pthread_mutexattr_t atts;
  216091. pthread_mutexattr_init (&atts);
  216092. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216093. #if ! JUCE_ANDROID
  216094. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216095. #endif
  216096. pthread_mutex_init (&internal, &atts);
  216097. }
  216098. CriticalSection::~CriticalSection() throw()
  216099. {
  216100. pthread_mutex_destroy (&internal);
  216101. }
  216102. void CriticalSection::enter() const throw()
  216103. {
  216104. pthread_mutex_lock (&internal);
  216105. }
  216106. bool CriticalSection::tryEnter() const throw()
  216107. {
  216108. return pthread_mutex_trylock (&internal) == 0;
  216109. }
  216110. void CriticalSection::exit() const throw()
  216111. {
  216112. pthread_mutex_unlock (&internal);
  216113. }
  216114. class WaitableEventImpl
  216115. {
  216116. public:
  216117. WaitableEventImpl (const bool manualReset_)
  216118. : triggered (false),
  216119. manualReset (manualReset_)
  216120. {
  216121. pthread_cond_init (&condition, 0);
  216122. pthread_mutexattr_t atts;
  216123. pthread_mutexattr_init (&atts);
  216124. #if ! JUCE_ANDROID
  216125. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  216126. #endif
  216127. pthread_mutex_init (&mutex, &atts);
  216128. }
  216129. ~WaitableEventImpl()
  216130. {
  216131. pthread_cond_destroy (&condition);
  216132. pthread_mutex_destroy (&mutex);
  216133. }
  216134. bool wait (const int timeOutMillisecs) throw()
  216135. {
  216136. pthread_mutex_lock (&mutex);
  216137. if (! triggered)
  216138. {
  216139. if (timeOutMillisecs < 0)
  216140. {
  216141. do
  216142. {
  216143. pthread_cond_wait (&condition, &mutex);
  216144. }
  216145. while (! triggered);
  216146. }
  216147. else
  216148. {
  216149. struct timeval now;
  216150. gettimeofday (&now, 0);
  216151. struct timespec time;
  216152. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  216153. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216154. if (time.tv_nsec >= 1000000000)
  216155. {
  216156. time.tv_nsec -= 1000000000;
  216157. time.tv_sec++;
  216158. }
  216159. do
  216160. {
  216161. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  216162. {
  216163. pthread_mutex_unlock (&mutex);
  216164. return false;
  216165. }
  216166. }
  216167. while (! triggered);
  216168. }
  216169. }
  216170. if (! manualReset)
  216171. triggered = false;
  216172. pthread_mutex_unlock (&mutex);
  216173. return true;
  216174. }
  216175. void signal() throw()
  216176. {
  216177. pthread_mutex_lock (&mutex);
  216178. triggered = true;
  216179. pthread_cond_broadcast (&condition);
  216180. pthread_mutex_unlock (&mutex);
  216181. }
  216182. void reset() throw()
  216183. {
  216184. pthread_mutex_lock (&mutex);
  216185. triggered = false;
  216186. pthread_mutex_unlock (&mutex);
  216187. }
  216188. private:
  216189. pthread_cond_t condition;
  216190. pthread_mutex_t mutex;
  216191. bool triggered;
  216192. const bool manualReset;
  216193. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  216194. };
  216195. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  216196. : internal (new WaitableEventImpl (manualReset))
  216197. {
  216198. }
  216199. WaitableEvent::~WaitableEvent() throw()
  216200. {
  216201. delete static_cast <WaitableEventImpl*> (internal);
  216202. }
  216203. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216204. {
  216205. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  216206. }
  216207. void WaitableEvent::signal() const throw()
  216208. {
  216209. static_cast <WaitableEventImpl*> (internal)->signal();
  216210. }
  216211. void WaitableEvent::reset() const throw()
  216212. {
  216213. static_cast <WaitableEventImpl*> (internal)->reset();
  216214. }
  216215. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  216216. {
  216217. struct timespec time;
  216218. time.tv_sec = millisecs / 1000;
  216219. time.tv_nsec = (millisecs % 1000) * 1000000;
  216220. nanosleep (&time, 0);
  216221. }
  216222. const juce_wchar File::separator = '/';
  216223. const String File::separatorString ("/");
  216224. const File File::getCurrentWorkingDirectory()
  216225. {
  216226. HeapBlock<char> heapBuffer;
  216227. char localBuffer [1024];
  216228. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  216229. int bufferSize = 4096;
  216230. while (cwd == 0 && errno == ERANGE)
  216231. {
  216232. heapBuffer.malloc (bufferSize);
  216233. cwd = getcwd (heapBuffer, bufferSize - 1);
  216234. bufferSize += 1024;
  216235. }
  216236. return File (String::fromUTF8 (cwd));
  216237. }
  216238. bool File::setAsCurrentWorkingDirectory() const
  216239. {
  216240. return chdir (getFullPathName().toUTF8()) == 0;
  216241. }
  216242. namespace
  216243. {
  216244. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216245. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  216246. #else
  216247. typedef struct stat juce_statStruct;
  216248. #endif
  216249. bool juce_stat (const String& fileName, juce_statStruct& info)
  216250. {
  216251. return fileName.isNotEmpty()
  216252. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216253. && (stat64 (fileName.toUTF8(), &info) == 0);
  216254. #else
  216255. && (stat (fileName.toUTF8(), &info) == 0);
  216256. #endif
  216257. }
  216258. // if this file doesn't exist, find a parent of it that does..
  216259. bool juce_doStatFS (File f, struct statfs& result)
  216260. {
  216261. for (int i = 5; --i >= 0;)
  216262. {
  216263. if (f.exists())
  216264. break;
  216265. f = f.getParentDirectory();
  216266. }
  216267. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216268. }
  216269. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  216270. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216271. {
  216272. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  216273. {
  216274. juce_statStruct info;
  216275. const bool statOk = juce_stat (path, info);
  216276. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  216277. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  216278. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  216279. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  216280. }
  216281. if (isReadOnly != 0)
  216282. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  216283. }
  216284. }
  216285. bool File::isDirectory() const
  216286. {
  216287. juce_statStruct info;
  216288. return fullPath.isEmpty()
  216289. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  216290. }
  216291. bool File::exists() const
  216292. {
  216293. juce_statStruct info;
  216294. return fullPath.isNotEmpty()
  216295. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  216296. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  216297. #else
  216298. && (lstat (fullPath.toUTF8(), &info) == 0);
  216299. #endif
  216300. }
  216301. bool File::existsAsFile() const
  216302. {
  216303. return exists() && ! isDirectory();
  216304. }
  216305. int64 File::getSize() const
  216306. {
  216307. juce_statStruct info;
  216308. return juce_stat (fullPath, info) ? info.st_size : 0;
  216309. }
  216310. bool File::hasWriteAccess() const
  216311. {
  216312. if (exists())
  216313. return access (fullPath.toUTF8(), W_OK) == 0;
  216314. if ((! isDirectory()) && fullPath.containsChar (separator))
  216315. return getParentDirectory().hasWriteAccess();
  216316. return false;
  216317. }
  216318. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  216319. {
  216320. juce_statStruct info;
  216321. if (! juce_stat (fullPath, info))
  216322. return false;
  216323. info.st_mode &= 0777; // Just permissions
  216324. if (shouldBeReadOnly)
  216325. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216326. else
  216327. // Give everybody write permission?
  216328. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216329. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  216330. }
  216331. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  216332. {
  216333. modificationTime = 0;
  216334. accessTime = 0;
  216335. creationTime = 0;
  216336. juce_statStruct info;
  216337. if (juce_stat (fullPath, info))
  216338. {
  216339. modificationTime = (int64) info.st_mtime * 1000;
  216340. accessTime = (int64) info.st_atime * 1000;
  216341. creationTime = (int64) info.st_ctime * 1000;
  216342. }
  216343. }
  216344. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  216345. {
  216346. juce_statStruct info;
  216347. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  216348. {
  216349. struct utimbuf times;
  216350. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  216351. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  216352. return utime (fullPath.toUTF8(), &times) == 0;
  216353. }
  216354. return false;
  216355. }
  216356. bool File::deleteFile() const
  216357. {
  216358. if (! exists())
  216359. return true;
  216360. if (isDirectory())
  216361. return rmdir (fullPath.toUTF8()) == 0;
  216362. return remove (fullPath.toUTF8()) == 0;
  216363. }
  216364. bool File::moveInternal (const File& dest) const
  216365. {
  216366. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  216367. return true;
  216368. if (hasWriteAccess() && copyInternal (dest))
  216369. {
  216370. if (deleteFile())
  216371. return true;
  216372. dest.deleteFile();
  216373. }
  216374. return false;
  216375. }
  216376. void File::createDirectoryInternal (const String& fileName) const
  216377. {
  216378. mkdir (fileName.toUTF8(), 0777);
  216379. }
  216380. int64 juce_fileSetPosition (void* handle, int64 pos)
  216381. {
  216382. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216383. return pos;
  216384. return -1;
  216385. }
  216386. void FileInputStream::openHandle()
  216387. {
  216388. totalSize = file.getSize();
  216389. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  216390. if (f != -1)
  216391. fileHandle = (void*) f;
  216392. }
  216393. void FileInputStream::closeHandle()
  216394. {
  216395. if (fileHandle != 0)
  216396. {
  216397. close ((int) (pointer_sized_int) fileHandle);
  216398. fileHandle = 0;
  216399. }
  216400. }
  216401. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  216402. {
  216403. if (fileHandle != 0)
  216404. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  216405. return 0;
  216406. }
  216407. void FileOutputStream::openHandle()
  216408. {
  216409. if (file.exists())
  216410. {
  216411. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  216412. if (f != -1)
  216413. {
  216414. currentPosition = lseek (f, 0, SEEK_END);
  216415. if (currentPosition >= 0)
  216416. fileHandle = (void*) f;
  216417. else
  216418. close (f);
  216419. }
  216420. }
  216421. else
  216422. {
  216423. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  216424. if (f != -1)
  216425. fileHandle = (void*) f;
  216426. }
  216427. }
  216428. void FileOutputStream::closeHandle()
  216429. {
  216430. if (fileHandle != 0)
  216431. {
  216432. close ((int) (pointer_sized_int) fileHandle);
  216433. fileHandle = 0;
  216434. }
  216435. }
  216436. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  216437. {
  216438. if (fileHandle != 0)
  216439. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  216440. return 0;
  216441. }
  216442. void FileOutputStream::flushInternal()
  216443. {
  216444. if (fileHandle != 0)
  216445. fsync ((int) (pointer_sized_int) fileHandle);
  216446. }
  216447. const File juce_getExecutableFile()
  216448. {
  216449. #if JUCE_ANDROID
  216450. // TODO
  216451. return File::nonexistent;
  216452. #else
  216453. Dl_info exeInfo;
  216454. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  216455. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  216456. #endif
  216457. }
  216458. int64 File::getBytesFreeOnVolume() const
  216459. {
  216460. struct statfs buf;
  216461. if (juce_doStatFS (*this, buf))
  216462. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  216463. return 0;
  216464. }
  216465. int64 File::getVolumeTotalSize() const
  216466. {
  216467. struct statfs buf;
  216468. if (juce_doStatFS (*this, buf))
  216469. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  216470. return 0;
  216471. }
  216472. const String File::getVolumeLabel() const
  216473. {
  216474. #if JUCE_MAC
  216475. struct VolAttrBuf
  216476. {
  216477. u_int32_t length;
  216478. attrreference_t mountPointRef;
  216479. char mountPointSpace [MAXPATHLEN];
  216480. } attrBuf;
  216481. struct attrlist attrList;
  216482. zerostruct (attrList);
  216483. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  216484. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  216485. File f (*this);
  216486. for (;;)
  216487. {
  216488. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  216489. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  216490. (int) attrBuf.mountPointRef.attr_length);
  216491. const File parent (f.getParentDirectory());
  216492. if (f == parent)
  216493. break;
  216494. f = parent;
  216495. }
  216496. #endif
  216497. return String::empty;
  216498. }
  216499. int File::getVolumeSerialNumber() const
  216500. {
  216501. int result = 0;
  216502. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  216503. char info [512];
  216504. #ifndef HDIO_GET_IDENTITY
  216505. #define HDIO_GET_IDENTITY 0x030d
  216506. #endif
  216507. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  216508. {
  216509. DBG (String (info + 20, 20));
  216510. result = String (info + 20, 20).trim().getIntValue();
  216511. }
  216512. close (fd);*/
  216513. return result;
  216514. }
  216515. void juce_runSystemCommand (const String& command)
  216516. {
  216517. int result = system (command.toUTF8());
  216518. (void) result;
  216519. }
  216520. const String juce_getOutputFromCommand (const String& command)
  216521. {
  216522. // slight bodge here, as we just pipe the output into a temp file and read it...
  216523. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  216524. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  216525. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  216526. String result (tempFile.loadFileAsString());
  216527. tempFile.deleteFile();
  216528. return result;
  216529. }
  216530. class InterProcessLock::Pimpl
  216531. {
  216532. public:
  216533. Pimpl (const String& name, const int timeOutMillisecs)
  216534. : handle (0), refCount (1)
  216535. {
  216536. #if JUCE_MAC
  216537. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216538. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  216539. #else
  216540. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216541. #endif
  216542. temp.create();
  216543. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  216544. if (handle != 0)
  216545. {
  216546. struct flock fl;
  216547. zerostruct (fl);
  216548. fl.l_whence = SEEK_SET;
  216549. fl.l_type = F_WRLCK;
  216550. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216551. for (;;)
  216552. {
  216553. const int result = fcntl (handle, F_SETLK, &fl);
  216554. if (result >= 0)
  216555. return;
  216556. if (errno != EINTR)
  216557. {
  216558. if (timeOutMillisecs == 0
  216559. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216560. break;
  216561. Thread::sleep (10);
  216562. }
  216563. }
  216564. }
  216565. closeFile();
  216566. }
  216567. ~Pimpl()
  216568. {
  216569. closeFile();
  216570. }
  216571. void closeFile()
  216572. {
  216573. if (handle != 0)
  216574. {
  216575. struct flock fl;
  216576. zerostruct (fl);
  216577. fl.l_whence = SEEK_SET;
  216578. fl.l_type = F_UNLCK;
  216579. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  216580. {}
  216581. close (handle);
  216582. handle = 0;
  216583. }
  216584. }
  216585. int handle, refCount;
  216586. };
  216587. InterProcessLock::InterProcessLock (const String& name_)
  216588. : name (name_)
  216589. {
  216590. }
  216591. InterProcessLock::~InterProcessLock()
  216592. {
  216593. }
  216594. bool InterProcessLock::enter (const int timeOutMillisecs)
  216595. {
  216596. const ScopedLock sl (lock);
  216597. if (pimpl == 0)
  216598. {
  216599. pimpl = new Pimpl (name, timeOutMillisecs);
  216600. if (pimpl->handle == 0)
  216601. pimpl = 0;
  216602. }
  216603. else
  216604. {
  216605. pimpl->refCount++;
  216606. }
  216607. return pimpl != 0;
  216608. }
  216609. void InterProcessLock::exit()
  216610. {
  216611. const ScopedLock sl (lock);
  216612. // Trying to release the lock too many times!
  216613. jassert (pimpl != 0);
  216614. if (pimpl != 0 && --(pimpl->refCount) == 0)
  216615. pimpl = 0;
  216616. }
  216617. void JUCE_API juce_threadEntryPoint (void*);
  216618. void* threadEntryProc (void* userData)
  216619. {
  216620. JUCE_AUTORELEASEPOOL
  216621. juce_threadEntryPoint (userData);
  216622. return 0;
  216623. }
  216624. void Thread::launchThread()
  216625. {
  216626. threadHandle_ = 0;
  216627. pthread_t handle = 0;
  216628. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  216629. {
  216630. pthread_detach (handle);
  216631. threadHandle_ = (void*) handle;
  216632. threadId_ = (ThreadID) threadHandle_;
  216633. }
  216634. }
  216635. void Thread::closeThreadHandle()
  216636. {
  216637. threadId_ = 0;
  216638. threadHandle_ = 0;
  216639. }
  216640. void Thread::killThread()
  216641. {
  216642. if (threadHandle_ != 0)
  216643. {
  216644. #if JUCE_ANDROID
  216645. jassertfalse; // pthread_cancel not available!
  216646. #else
  216647. pthread_cancel ((pthread_t) threadHandle_);
  216648. #endif
  216649. }
  216650. }
  216651. void Thread::setCurrentThreadName (const String& /*name*/)
  216652. {
  216653. }
  216654. bool Thread::setThreadPriority (void* handle, int priority)
  216655. {
  216656. struct sched_param param;
  216657. int policy;
  216658. priority = jlimit (0, 10, priority);
  216659. if (handle == 0)
  216660. handle = (void*) pthread_self();
  216661. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  216662. return false;
  216663. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  216664. const int minPriority = sched_get_priority_min (policy);
  216665. const int maxPriority = sched_get_priority_max (policy);
  216666. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  216667. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  216668. }
  216669. Thread::ThreadID Thread::getCurrentThreadId()
  216670. {
  216671. return (ThreadID) pthread_self();
  216672. }
  216673. void Thread::yield()
  216674. {
  216675. sched_yield();
  216676. }
  216677. /* Remove this macro if you're having problems compiling the cpu affinity
  216678. calls (the API for these has changed about quite a bit in various Linux
  216679. versions, and a lot of distros seem to ship with obsolete versions)
  216680. */
  216681. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  216682. #define SUPPORT_AFFINITIES 1
  216683. #endif
  216684. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  216685. {
  216686. #if SUPPORT_AFFINITIES
  216687. cpu_set_t affinity;
  216688. CPU_ZERO (&affinity);
  216689. for (int i = 0; i < 32; ++i)
  216690. if ((affinityMask & (1 << i)) != 0)
  216691. CPU_SET (i, &affinity);
  216692. /*
  216693. N.B. If this line causes a compile error, then you've probably not got the latest
  216694. version of glibc installed.
  216695. If you don't want to update your copy of glibc and don't care about cpu affinities,
  216696. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  216697. */
  216698. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  216699. sched_yield();
  216700. #else
  216701. /* affinities aren't supported because either the appropriate header files weren't found,
  216702. or the SUPPORT_AFFINITIES macro was turned off
  216703. */
  216704. jassertfalse;
  216705. (void) affinityMask;
  216706. #endif
  216707. }
  216708. /*** End of inlined file: juce_posix_SharedCode.h ***/
  216709. /*** Start of inlined file: juce_linux_Files.cpp ***/
  216710. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  216711. // compiled on its own).
  216712. #if JUCE_INCLUDED_FILE
  216713. enum
  216714. {
  216715. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  216716. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  216717. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  216718. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  216719. };
  216720. bool File::copyInternal (const File& dest) const
  216721. {
  216722. FileInputStream in (*this);
  216723. if (dest.deleteFile())
  216724. {
  216725. {
  216726. FileOutputStream out (dest);
  216727. if (out.failedToOpen())
  216728. return false;
  216729. if (out.writeFromInputStream (in, -1) == getSize())
  216730. return true;
  216731. }
  216732. dest.deleteFile();
  216733. }
  216734. return false;
  216735. }
  216736. void File::findFileSystemRoots (Array<File>& destArray)
  216737. {
  216738. destArray.add (File ("/"));
  216739. }
  216740. bool File::isOnCDRomDrive() const
  216741. {
  216742. struct statfs buf;
  216743. return statfs (getFullPathName().toUTF8(), &buf) == 0
  216744. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  216745. }
  216746. bool File::isOnHardDisk() const
  216747. {
  216748. struct statfs buf;
  216749. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216750. {
  216751. switch (buf.f_type)
  216752. {
  216753. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216754. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216755. case U_NFS_SUPER_MAGIC: // Network NFS
  216756. case U_SMB_SUPER_MAGIC: // Network Samba
  216757. return false;
  216758. default:
  216759. // Assume anything else is a hard-disk (but note it could
  216760. // be a RAM disk. There isn't a good way of determining
  216761. // this for sure)
  216762. return true;
  216763. }
  216764. }
  216765. // Assume so if this fails for some reason
  216766. return true;
  216767. }
  216768. bool File::isOnRemovableDrive() const
  216769. {
  216770. jassertfalse; // xxx not implemented for linux!
  216771. return false;
  216772. }
  216773. bool File::isHidden() const
  216774. {
  216775. return getFileName().startsWithChar ('.');
  216776. }
  216777. namespace
  216778. {
  216779. const File juce_readlink (const String& file, const File& defaultFile)
  216780. {
  216781. const int size = 8192;
  216782. HeapBlock<char> buffer;
  216783. buffer.malloc (size + 4);
  216784. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  216785. if (numBytes > 0 && numBytes <= size)
  216786. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  216787. return defaultFile;
  216788. }
  216789. }
  216790. const File File::getLinkedTarget() const
  216791. {
  216792. return juce_readlink (getFullPathName().toUTF8(), *this);
  216793. }
  216794. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  216795. const File File::getSpecialLocation (const SpecialLocationType type)
  216796. {
  216797. switch (type)
  216798. {
  216799. case userHomeDirectory:
  216800. {
  216801. const char* homeDir = getenv ("HOME");
  216802. if (homeDir == 0)
  216803. {
  216804. struct passwd* const pw = getpwuid (getuid());
  216805. if (pw != 0)
  216806. homeDir = pw->pw_dir;
  216807. }
  216808. return File (String::fromUTF8 (homeDir));
  216809. }
  216810. case userDocumentsDirectory:
  216811. case userMusicDirectory:
  216812. case userMoviesDirectory:
  216813. case userApplicationDataDirectory:
  216814. return File ("~");
  216815. case userDesktopDirectory:
  216816. return File ("~/Desktop");
  216817. case commonApplicationDataDirectory:
  216818. return File ("/var");
  216819. case globalApplicationsDirectory:
  216820. return File ("/usr");
  216821. case tempDirectory:
  216822. {
  216823. File tmp ("/var/tmp");
  216824. if (! tmp.isDirectory())
  216825. {
  216826. tmp = "/tmp";
  216827. if (! tmp.isDirectory())
  216828. tmp = File::getCurrentWorkingDirectory();
  216829. }
  216830. return tmp;
  216831. }
  216832. case invokedExecutableFile:
  216833. if (juce_Argv0 != 0)
  216834. return File (String::fromUTF8 (juce_Argv0));
  216835. // deliberate fall-through...
  216836. case currentExecutableFile:
  216837. case currentApplicationFile:
  216838. return juce_getExecutableFile();
  216839. case hostApplicationPath:
  216840. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  216841. default:
  216842. jassertfalse; // unknown type?
  216843. break;
  216844. }
  216845. return File::nonexistent;
  216846. }
  216847. const String File::getVersion() const
  216848. {
  216849. return String::empty; // xxx not yet implemented
  216850. }
  216851. bool File::moveToTrash() const
  216852. {
  216853. if (! exists())
  216854. return true;
  216855. File trashCan ("~/.Trash");
  216856. if (! trashCan.isDirectory())
  216857. trashCan = "~/.local/share/Trash/files";
  216858. if (! trashCan.isDirectory())
  216859. return false;
  216860. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  216861. getFileExtension()));
  216862. }
  216863. class DirectoryIterator::NativeIterator::Pimpl
  216864. {
  216865. public:
  216866. Pimpl (const File& directory, const String& wildCard_)
  216867. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  216868. wildCard (wildCard_),
  216869. dir (opendir (directory.getFullPathName().toUTF8()))
  216870. {
  216871. wildcardUTF8 = wildCard.toUTF8();
  216872. }
  216873. ~Pimpl()
  216874. {
  216875. if (dir != 0)
  216876. closedir (dir);
  216877. }
  216878. bool next (String& filenameFound,
  216879. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216880. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216881. {
  216882. if (dir != 0)
  216883. {
  216884. for (;;)
  216885. {
  216886. struct dirent* const de = readdir (dir);
  216887. if (de == 0)
  216888. break;
  216889. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216890. {
  216891. filenameFound = String::fromUTF8 (de->d_name);
  216892. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  216893. if (isHidden != 0)
  216894. *isHidden = filenameFound.startsWithChar ('.');
  216895. return true;
  216896. }
  216897. }
  216898. }
  216899. return false;
  216900. }
  216901. private:
  216902. String parentDir, wildCard;
  216903. const char* wildcardUTF8;
  216904. DIR* dir;
  216905. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  216906. };
  216907. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  216908. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  216909. {
  216910. }
  216911. DirectoryIterator::NativeIterator::~NativeIterator()
  216912. {
  216913. }
  216914. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  216915. bool* const isDir, bool* const isHidden, int64* const fileSize,
  216916. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  216917. {
  216918. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216919. }
  216920. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  216921. {
  216922. String cmdString (fileName.replace (" ", "\\ ",false));
  216923. cmdString << " " << parameters;
  216924. if (URL::isProbablyAWebsiteURL (fileName)
  216925. || cmdString.startsWithIgnoreCase ("file:")
  216926. || URL::isProbablyAnEmailAddress (fileName))
  216927. {
  216928. // create a command that tries to launch a bunch of likely browsers
  216929. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216930. StringArray cmdLines;
  216931. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216932. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  216933. cmdString = cmdLines.joinIntoString (" || ");
  216934. }
  216935. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  216936. const int cpid = fork();
  216937. if (cpid == 0)
  216938. {
  216939. setsid();
  216940. // Child process
  216941. execve (argv[0], (char**) argv, environ);
  216942. exit (0);
  216943. }
  216944. return cpid >= 0;
  216945. }
  216946. void File::revealToUser() const
  216947. {
  216948. if (isDirectory())
  216949. startAsProcess();
  216950. else if (getParentDirectory().exists())
  216951. getParentDirectory().startAsProcess();
  216952. }
  216953. #endif
  216954. /*** End of inlined file: juce_linux_Files.cpp ***/
  216955. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  216956. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  216957. // compiled on its own).
  216958. #if JUCE_INCLUDED_FILE
  216959. struct NamedPipeInternal
  216960. {
  216961. String pipeInName, pipeOutName;
  216962. int pipeIn, pipeOut;
  216963. bool volatile createdPipe, blocked, stopReadOperation;
  216964. static void signalHandler (int) {}
  216965. };
  216966. void NamedPipe::cancelPendingReads()
  216967. {
  216968. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  216969. {
  216970. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216971. intern->stopReadOperation = true;
  216972. char buffer [1] = { 0 };
  216973. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  216974. (void) bytesWritten;
  216975. int timeout = 2000;
  216976. while (intern->blocked && --timeout >= 0)
  216977. Thread::sleep (2);
  216978. intern->stopReadOperation = false;
  216979. }
  216980. }
  216981. void NamedPipe::close()
  216982. {
  216983. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  216984. if (intern != 0)
  216985. {
  216986. internal = 0;
  216987. if (intern->pipeIn != -1)
  216988. ::close (intern->pipeIn);
  216989. if (intern->pipeOut != -1)
  216990. ::close (intern->pipeOut);
  216991. if (intern->createdPipe)
  216992. {
  216993. unlink (intern->pipeInName.toUTF8());
  216994. unlink (intern->pipeOutName.toUTF8());
  216995. }
  216996. delete intern;
  216997. }
  216998. }
  216999. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217000. {
  217001. close();
  217002. NamedPipeInternal* const intern = new NamedPipeInternal();
  217003. internal = intern;
  217004. intern->createdPipe = createPipe;
  217005. intern->blocked = false;
  217006. intern->stopReadOperation = false;
  217007. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217008. siginterrupt (SIGPIPE, 1);
  217009. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217010. intern->pipeInName = pipePath + "_in";
  217011. intern->pipeOutName = pipePath + "_out";
  217012. intern->pipeIn = -1;
  217013. intern->pipeOut = -1;
  217014. if (createPipe)
  217015. {
  217016. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217017. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217018. {
  217019. delete intern;
  217020. internal = 0;
  217021. return false;
  217022. }
  217023. }
  217024. return true;
  217025. }
  217026. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217027. {
  217028. int bytesRead = -1;
  217029. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217030. if (intern != 0)
  217031. {
  217032. intern->blocked = true;
  217033. if (intern->pipeIn == -1)
  217034. {
  217035. if (intern->createdPipe)
  217036. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217037. else
  217038. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217039. if (intern->pipeIn == -1)
  217040. {
  217041. intern->blocked = false;
  217042. return -1;
  217043. }
  217044. }
  217045. bytesRead = 0;
  217046. char* p = static_cast<char*> (destBuffer);
  217047. while (bytesRead < maxBytesToRead)
  217048. {
  217049. const int bytesThisTime = maxBytesToRead - bytesRead;
  217050. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  217051. if (numRead <= 0 || intern->stopReadOperation)
  217052. {
  217053. bytesRead = -1;
  217054. break;
  217055. }
  217056. bytesRead += numRead;
  217057. p += bytesRead;
  217058. }
  217059. intern->blocked = false;
  217060. }
  217061. return bytesRead;
  217062. }
  217063. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  217064. {
  217065. int bytesWritten = -1;
  217066. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217067. if (intern != 0)
  217068. {
  217069. if (intern->pipeOut == -1)
  217070. {
  217071. if (intern->createdPipe)
  217072. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  217073. else
  217074. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  217075. if (intern->pipeOut == -1)
  217076. {
  217077. return -1;
  217078. }
  217079. }
  217080. const char* p = static_cast<const char*> (sourceBuffer);
  217081. bytesWritten = 0;
  217082. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  217083. while (bytesWritten < numBytesToWrite
  217084. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  217085. {
  217086. const int bytesThisTime = numBytesToWrite - bytesWritten;
  217087. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  217088. if (numWritten <= 0)
  217089. {
  217090. bytesWritten = -1;
  217091. break;
  217092. }
  217093. bytesWritten += numWritten;
  217094. p += bytesWritten;
  217095. }
  217096. }
  217097. return bytesWritten;
  217098. }
  217099. #endif
  217100. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  217101. /*** Start of inlined file: juce_linux_Network.cpp ***/
  217102. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217103. // compiled on its own).
  217104. #if JUCE_INCLUDED_FILE
  217105. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  217106. {
  217107. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  217108. if (s != -1)
  217109. {
  217110. char buf [1024];
  217111. struct ifconf ifc;
  217112. ifc.ifc_len = sizeof (buf);
  217113. ifc.ifc_buf = buf;
  217114. ioctl (s, SIOCGIFCONF, &ifc);
  217115. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  217116. {
  217117. struct ifreq ifr;
  217118. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  217119. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  217120. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  217121. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0)
  217122. {
  217123. result.addIfNotAlreadyThere (MACAddress ((const uint8*) ifr.ifr_hwaddr.sa_data));
  217124. }
  217125. }
  217126. close (s);
  217127. }
  217128. }
  217129. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  217130. const String& emailSubject,
  217131. const String& bodyText,
  217132. const StringArray& filesToAttach)
  217133. {
  217134. jassertfalse; // xxx todo
  217135. return false;
  217136. }
  217137. class WebInputStream : public InputStream
  217138. {
  217139. public:
  217140. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  217141. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217142. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  217143. : socketHandle (-1), levelsOfRedirection (0),
  217144. address (address_), headers (headers_), postData (postData_), position (0),
  217145. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  217146. {
  217147. createConnection (progressCallback, progressCallbackContext);
  217148. if (responseHeaders != 0 && ! isError())
  217149. {
  217150. for (int i = 0; i < headerLines.size(); ++i)
  217151. {
  217152. const String& headersEntry = headerLines[i];
  217153. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  217154. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  217155. const String previousValue ((*responseHeaders) [key]);
  217156. responseHeaders->set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  217157. }
  217158. }
  217159. }
  217160. ~WebInputStream()
  217161. {
  217162. closeSocket();
  217163. }
  217164. bool isError() const { return socketHandle < 0; }
  217165. bool isExhausted() { return finished; }
  217166. int64 getPosition() { return position; }
  217167. int64 getTotalLength()
  217168. {
  217169. jassertfalse; //xxx to do
  217170. return -1;
  217171. }
  217172. int read (void* buffer, int bytesToRead)
  217173. {
  217174. if (finished || isError())
  217175. return 0;
  217176. fd_set readbits;
  217177. FD_ZERO (&readbits);
  217178. FD_SET (socketHandle, &readbits);
  217179. struct timeval tv;
  217180. tv.tv_sec = jmax (1, timeOutMs / 1000);
  217181. tv.tv_usec = 0;
  217182. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217183. return 0; // (timeout)
  217184. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217185. if (bytesRead == 0)
  217186. finished = true;
  217187. position += bytesRead;
  217188. return bytesRead;
  217189. }
  217190. bool setPosition (int64 wantedPos)
  217191. {
  217192. if (isError())
  217193. return false;
  217194. if (wantedPos != position)
  217195. {
  217196. finished = false;
  217197. if (wantedPos < position)
  217198. {
  217199. closeSocket();
  217200. position = 0;
  217201. createConnection (0, 0);
  217202. }
  217203. skipNextBytes (wantedPos - position);
  217204. }
  217205. return true;
  217206. }
  217207. private:
  217208. int socketHandle, levelsOfRedirection;
  217209. StringArray headerLines;
  217210. String address, headers;
  217211. MemoryBlock postData;
  217212. int64 position;
  217213. bool finished;
  217214. const bool isPost;
  217215. const int timeOutMs;
  217216. void closeSocket()
  217217. {
  217218. if (socketHandle >= 0)
  217219. close (socketHandle);
  217220. socketHandle = -1;
  217221. levelsOfRedirection = 0;
  217222. }
  217223. void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217224. {
  217225. closeSocket();
  217226. uint32 timeOutTime = Time::getMillisecondCounter();
  217227. if (timeOutMs == 0)
  217228. timeOutTime += 60000;
  217229. else if (timeOutMs < 0)
  217230. timeOutTime = 0xffffffff;
  217231. else
  217232. timeOutTime += timeOutMs;
  217233. String hostName, hostPath;
  217234. int hostPort;
  217235. if (! decomposeURL (address, hostName, hostPath, hostPort))
  217236. return;
  217237. const struct hostent* host = 0;
  217238. int port = 0;
  217239. String proxyName, proxyPath;
  217240. int proxyPort = 0;
  217241. String proxyURL (getenv ("http_proxy"));
  217242. if (proxyURL.startsWithIgnoreCase ("http://"))
  217243. {
  217244. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217245. return;
  217246. host = gethostbyname (proxyName.toUTF8());
  217247. port = proxyPort;
  217248. }
  217249. else
  217250. {
  217251. host = gethostbyname (hostName.toUTF8());
  217252. port = hostPort;
  217253. }
  217254. if (host == 0)
  217255. return;
  217256. {
  217257. struct sockaddr_in socketAddress;
  217258. zerostruct (socketAddress);
  217259. memcpy (&socketAddress.sin_addr, host->h_addr, host->h_length);
  217260. socketAddress.sin_family = host->h_addrtype;
  217261. socketAddress.sin_port = htons (port);
  217262. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217263. if (socketHandle == -1)
  217264. return;
  217265. int receiveBufferSize = 16384;
  217266. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217267. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217268. #if JUCE_MAC
  217269. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217270. #endif
  217271. if (connect (socketHandle, (struct sockaddr*) &socketAddress, sizeof (socketAddress)) == -1)
  217272. {
  217273. closeSocket();
  217274. return;
  217275. }
  217276. }
  217277. {
  217278. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
  217279. hostPath, address, headers, postData, isPost));
  217280. if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
  217281. {
  217282. closeSocket();
  217283. return;
  217284. }
  217285. }
  217286. const String responseHeader (readResponse (socketHandle, timeOutTime));
  217287. if (responseHeader.isNotEmpty())
  217288. {
  217289. headerLines.clear();
  217290. headerLines.addLines (responseHeader);
  217291. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  217292. .substring (0, 3).getIntValue();
  217293. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  217294. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  217295. String location (findHeaderItem (headerLines, "Location:"));
  217296. if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
  217297. {
  217298. if (! location.startsWithIgnoreCase ("http://"))
  217299. location = "http://" + location;
  217300. if (++levelsOfRedirection <= 3)
  217301. {
  217302. address = location;
  217303. createConnection (progressCallback, progressCallbackContext);
  217304. return;
  217305. }
  217306. }
  217307. else
  217308. {
  217309. levelsOfRedirection = 0;
  217310. return;
  217311. }
  217312. }
  217313. closeSocket();
  217314. }
  217315. static const String readResponse (const int socketHandle, const uint32 timeOutTime)
  217316. {
  217317. int bytesRead = 0, numConsecutiveLFs = 0;
  217318. MemoryBlock buffer (1024, true);
  217319. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217320. && Time::getMillisecondCounter() <= timeOutTime)
  217321. {
  217322. fd_set readbits;
  217323. FD_ZERO (&readbits);
  217324. FD_SET (socketHandle, &readbits);
  217325. struct timeval tv;
  217326. tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
  217327. tv.tv_usec = 0;
  217328. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217329. return String::empty; // (timeout)
  217330. buffer.ensureSize (bytesRead + 8, true);
  217331. char* const dest = (char*) buffer.getData() + bytesRead;
  217332. if (recv (socketHandle, dest, 1, 0) == -1)
  217333. return String::empty;
  217334. const char lastByte = *dest;
  217335. ++bytesRead;
  217336. if (lastByte == '\n')
  217337. ++numConsecutiveLFs;
  217338. else if (lastByte != '\r')
  217339. numConsecutiveLFs = 0;
  217340. }
  217341. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  217342. if (header.startsWithIgnoreCase ("HTTP/"))
  217343. return header.trimEnd();
  217344. return String::empty;
  217345. }
  217346. static const MemoryBlock createRequestHeader (const String& hostName, const int hostPort,
  217347. const String& proxyName, const int proxyPort,
  217348. const String& hostPath, const String& originalURL,
  217349. const String& headers, const MemoryBlock& postData,
  217350. const bool isPost)
  217351. {
  217352. String header (isPost ? "POST " : "GET ");
  217353. if (proxyName.isEmpty())
  217354. {
  217355. header << hostPath << " HTTP/1.0\r\nHost: "
  217356. << hostName << ':' << hostPort;
  217357. }
  217358. else
  217359. {
  217360. header << originalURL << " HTTP/1.0\r\nHost: "
  217361. << proxyName << ':' << proxyPort;
  217362. }
  217363. header << "\r\nUser-Agent: JUCE/" << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217364. << "\r\nConnection: Close\r\nContent-Length: "
  217365. << (int) postData.getSize() << "\r\n"
  217366. << headers << "\r\n";
  217367. MemoryBlock mb;
  217368. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217369. mb.append (postData.getData(), postData.getSize());
  217370. return mb;
  217371. }
  217372. static bool sendHeader (int socketHandle, const MemoryBlock& requestHeader, const uint32 timeOutTime,
  217373. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
  217374. {
  217375. size_t totalHeaderSent = 0;
  217376. while (totalHeaderSent < requestHeader.getSize())
  217377. {
  217378. if (Time::getMillisecondCounter() > timeOutTime)
  217379. return false;
  217380. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  217381. if (send (socketHandle, static_cast <const char*> (requestHeader.getData()) + totalHeaderSent, numToSend, 0) != numToSend)
  217382. return false;
  217383. totalHeaderSent += numToSend;
  217384. if (progressCallback != 0 && ! progressCallback (progressCallbackContext, totalHeaderSent, requestHeader.getSize()))
  217385. return false;
  217386. }
  217387. return true;
  217388. }
  217389. static bool decomposeURL (const String& url, String& host, String& path, int& port)
  217390. {
  217391. if (! url.startsWithIgnoreCase ("http://"))
  217392. return false;
  217393. const int nextSlash = url.indexOfChar (7, '/');
  217394. int nextColon = url.indexOfChar (7, ':');
  217395. if (nextColon > nextSlash && nextSlash > 0)
  217396. nextColon = -1;
  217397. if (nextColon >= 0)
  217398. {
  217399. host = url.substring (7, nextColon);
  217400. if (nextSlash >= 0)
  217401. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217402. else
  217403. port = url.substring (nextColon + 1).getIntValue();
  217404. }
  217405. else
  217406. {
  217407. port = 80;
  217408. if (nextSlash >= 0)
  217409. host = url.substring (7, nextSlash);
  217410. else
  217411. host = url.substring (7);
  217412. }
  217413. if (nextSlash >= 0)
  217414. path = url.substring (nextSlash);
  217415. else
  217416. path = "/";
  217417. return true;
  217418. }
  217419. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217420. {
  217421. for (int i = 0; i < lines.size(); ++i)
  217422. if (lines[i].startsWithIgnoreCase (itemName))
  217423. return lines[i].substring (itemName.length()).trim();
  217424. return String::empty;
  217425. }
  217426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  217427. };
  217428. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  217429. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  217430. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  217431. {
  217432. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  217433. progressCallback, progressCallbackContext,
  217434. headers, timeOutMs, responseHeaders));
  217435. return wi->isError() ? 0 : wi.release();
  217436. }
  217437. #endif
  217438. /*** End of inlined file: juce_linux_Network.cpp ***/
  217439. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  217440. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217441. // compiled on its own).
  217442. #if JUCE_INCLUDED_FILE
  217443. void Logger::outputDebugString (const String& text)
  217444. {
  217445. std::cerr << text << std::endl;
  217446. }
  217447. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  217448. {
  217449. return Linux;
  217450. }
  217451. const String SystemStats::getOperatingSystemName()
  217452. {
  217453. return "Linux";
  217454. }
  217455. bool SystemStats::isOperatingSystem64Bit()
  217456. {
  217457. #if JUCE_64BIT
  217458. return true;
  217459. #else
  217460. //xxx not sure how to find this out?..
  217461. return false;
  217462. #endif
  217463. }
  217464. namespace LinuxStatsHelpers
  217465. {
  217466. const String getCpuInfo (const char* const key)
  217467. {
  217468. StringArray lines;
  217469. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  217470. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  217471. if (lines[i].startsWithIgnoreCase (key))
  217472. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  217473. return String::empty;
  217474. }
  217475. }
  217476. const String SystemStats::getCpuVendor()
  217477. {
  217478. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  217479. }
  217480. int SystemStats::getCpuSpeedInMegaherz()
  217481. {
  217482. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  217483. }
  217484. int SystemStats::getMemorySizeInMegabytes()
  217485. {
  217486. struct sysinfo sysi;
  217487. if (sysinfo (&sysi) == 0)
  217488. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217489. return 0;
  217490. }
  217491. int SystemStats::getPageSize()
  217492. {
  217493. return sysconf (_SC_PAGESIZE);
  217494. }
  217495. const String SystemStats::getLogonName()
  217496. {
  217497. const char* user = getenv ("USER");
  217498. if (user == 0)
  217499. {
  217500. struct passwd* const pw = getpwuid (getuid());
  217501. if (pw != 0)
  217502. user = pw->pw_name;
  217503. }
  217504. return String::fromUTF8 (user);
  217505. }
  217506. const String SystemStats::getFullUserName()
  217507. {
  217508. return getLogonName();
  217509. }
  217510. void SystemStats::initialiseStats()
  217511. {
  217512. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  217513. cpuFlags.hasMMX = flags.contains ("mmx");
  217514. cpuFlags.hasSSE = flags.contains ("sse");
  217515. cpuFlags.hasSSE2 = flags.contains ("sse2");
  217516. cpuFlags.has3DNow = flags.contains ("3dnow");
  217517. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  217518. }
  217519. void PlatformUtilities::fpuReset()
  217520. {
  217521. }
  217522. uint32 juce_millisecondsSinceStartup() throw()
  217523. {
  217524. timespec t;
  217525. clock_gettime (CLOCK_MONOTONIC, &t);
  217526. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  217527. }
  217528. int64 Time::getHighResolutionTicks() throw()
  217529. {
  217530. timespec t;
  217531. clock_gettime (CLOCK_MONOTONIC, &t);
  217532. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  217533. }
  217534. int64 Time::getHighResolutionTicksPerSecond() throw()
  217535. {
  217536. return 1000000; // (microseconds)
  217537. }
  217538. double Time::getMillisecondCounterHiRes() throw()
  217539. {
  217540. return getHighResolutionTicks() * 0.001;
  217541. }
  217542. bool Time::setSystemTimeToThisTime() const
  217543. {
  217544. timeval t;
  217545. t.tv_sec = millisSinceEpoch / 1000;
  217546. t.tv_usec = (millisSinceEpoch - t.tv_sec * 1000) * 1000;
  217547. return settimeofday (&t, 0) == 0;
  217548. }
  217549. #endif
  217550. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  217551. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  217552. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217553. // compiled on its own).
  217554. #if JUCE_INCLUDED_FILE
  217555. /*
  217556. Note that a lot of methods that you'd expect to find in this file actually
  217557. live in juce_posix_SharedCode.h!
  217558. */
  217559. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217560. void Process::setPriority (ProcessPriority prior)
  217561. {
  217562. struct sched_param param;
  217563. int policy, maxp, minp;
  217564. const int p = (int) prior;
  217565. if (p <= 1)
  217566. policy = SCHED_OTHER;
  217567. else
  217568. policy = SCHED_RR;
  217569. minp = sched_get_priority_min (policy);
  217570. maxp = sched_get_priority_max (policy);
  217571. if (p < 2)
  217572. param.sched_priority = 0;
  217573. else if (p == 2 )
  217574. // Set to middle of lower realtime priority range
  217575. param.sched_priority = minp + (maxp - minp) / 4;
  217576. else
  217577. // Set to middle of higher realtime priority range
  217578. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  217579. pthread_setschedparam (pthread_self(), policy, &param);
  217580. }
  217581. void Process::terminate()
  217582. {
  217583. exit (0);
  217584. }
  217585. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  217586. {
  217587. static char testResult = 0;
  217588. if (testResult == 0)
  217589. {
  217590. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217591. if (testResult >= 0)
  217592. {
  217593. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217594. testResult = 1;
  217595. }
  217596. }
  217597. return testResult < 0;
  217598. }
  217599. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  217600. {
  217601. return juce_isRunningUnderDebugger();
  217602. }
  217603. void Process::raisePrivilege()
  217604. {
  217605. // If running suid root, change effective user
  217606. // to root
  217607. if (geteuid() != 0 && getuid() == 0)
  217608. {
  217609. setreuid (geteuid(), getuid());
  217610. setregid (getegid(), getgid());
  217611. }
  217612. }
  217613. void Process::lowerPrivilege()
  217614. {
  217615. // If runing suid root, change effective user
  217616. // back to real user
  217617. if (geteuid() == 0 && getuid() != 0)
  217618. {
  217619. setreuid (geteuid(), getuid());
  217620. setregid (getegid(), getgid());
  217621. }
  217622. }
  217623. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217624. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217625. {
  217626. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217627. }
  217628. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217629. {
  217630. dlclose(handle);
  217631. }
  217632. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217633. {
  217634. return dlsym (libraryHandle, procedureName.toCString());
  217635. }
  217636. #endif
  217637. #endif
  217638. /*** End of inlined file: juce_linux_Threads.cpp ***/
  217639. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217640. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  217641. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217642. // compiled on its own).
  217643. #if JUCE_INCLUDED_FILE
  217644. extern Display* display;
  217645. extern Window juce_messageWindowHandle;
  217646. namespace ClipboardHelpers
  217647. {
  217648. static String localClipboardContent;
  217649. static Atom atom_UTF8_STRING;
  217650. static Atom atom_CLIPBOARD;
  217651. static Atom atom_TARGETS;
  217652. static void initSelectionAtoms()
  217653. {
  217654. static bool isInitialised = false;
  217655. if (! isInitialised)
  217656. {
  217657. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  217658. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  217659. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  217660. }
  217661. }
  217662. // Read the content of a window property as either a locale-dependent string or an utf8 string
  217663. // works only for strings shorter than 1000000 bytes
  217664. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  217665. {
  217666. String returnData;
  217667. char* clipData;
  217668. Atom actualType;
  217669. int actualFormat;
  217670. unsigned long numItems, bytesLeft;
  217671. if (XGetWindowProperty (display, window, prop,
  217672. 0L /* offset */, 1000000 /* length (max) */, False,
  217673. AnyPropertyType /* format */,
  217674. &actualType, &actualFormat, &numItems, &bytesLeft,
  217675. (unsigned char**) &clipData) == Success)
  217676. {
  217677. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  217678. returnData = String::fromUTF8 (clipData, numItems);
  217679. else if (actualType == XA_STRING && actualFormat == 8)
  217680. returnData = String (clipData, numItems);
  217681. if (clipData != 0)
  217682. XFree (clipData);
  217683. jassert (bytesLeft == 0 || numItems == 1000000);
  217684. }
  217685. XDeleteProperty (display, window, prop);
  217686. return returnData;
  217687. }
  217688. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  217689. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  217690. {
  217691. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  217692. // The selection owner will be asked to set the JUCE_SEL property on the
  217693. // juce_messageWindowHandle with the selection content
  217694. XConvertSelection (display, selection, requestedFormat, property_name,
  217695. juce_messageWindowHandle, CurrentTime);
  217696. int count = 50; // will wait at most for 200 ms
  217697. while (--count >= 0)
  217698. {
  217699. XEvent event;
  217700. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  217701. {
  217702. if (event.xselection.property == property_name)
  217703. {
  217704. jassert (event.xselection.requestor == juce_messageWindowHandle);
  217705. selectionContent = readWindowProperty (event.xselection.requestor,
  217706. event.xselection.property,
  217707. requestedFormat);
  217708. return true;
  217709. }
  217710. else
  217711. {
  217712. return false; // the format we asked for was denied.. (event.xselection.property == None)
  217713. }
  217714. }
  217715. // not very elegant.. we could do a select() or something like that...
  217716. // however clipboard content requesting is inherently slow on x11, it
  217717. // often takes 50ms or more so...
  217718. Thread::sleep (4);
  217719. }
  217720. return false;
  217721. }
  217722. }
  217723. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  217724. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  217725. {
  217726. ClipboardHelpers::initSelectionAtoms();
  217727. // the selection content is sent to the target window as a window property
  217728. XSelectionEvent reply;
  217729. reply.type = SelectionNotify;
  217730. reply.display = evt.display;
  217731. reply.requestor = evt.requestor;
  217732. reply.selection = evt.selection;
  217733. reply.target = evt.target;
  217734. reply.property = None; // == "fail"
  217735. reply.time = evt.time;
  217736. HeapBlock <char> data;
  217737. int propertyFormat = 0, numDataItems = 0;
  217738. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  217739. {
  217740. if (evt.target == XA_STRING)
  217741. {
  217742. // format data according to system locale
  217743. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  217744. data.calloc (numDataItems + 1);
  217745. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  217746. propertyFormat = 8; // bits/item
  217747. }
  217748. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  217749. {
  217750. // translate to utf8
  217751. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  217752. data.calloc (numDataItems + 1);
  217753. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  217754. propertyFormat = 8; // bits/item
  217755. }
  217756. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  217757. {
  217758. // another application wants to know what we are able to send
  217759. numDataItems = 2;
  217760. propertyFormat = 32; // atoms are 32-bit
  217761. data.calloc (numDataItems * 4);
  217762. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  217763. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  217764. atoms[1] = XA_STRING;
  217765. }
  217766. }
  217767. else
  217768. {
  217769. DBG ("requested unsupported clipboard");
  217770. }
  217771. if (data != 0)
  217772. {
  217773. const int maxReasonableSelectionSize = 1000000;
  217774. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  217775. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  217776. {
  217777. XChangeProperty (evt.display, evt.requestor,
  217778. evt.property, evt.target,
  217779. propertyFormat /* 8 or 32 */, PropModeReplace,
  217780. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  217781. reply.property = evt.property; // " == success"
  217782. }
  217783. }
  217784. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  217785. }
  217786. void SystemClipboard::copyTextToClipboard (const String& clipText)
  217787. {
  217788. ClipboardHelpers::initSelectionAtoms();
  217789. ClipboardHelpers::localClipboardContent = clipText;
  217790. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  217791. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  217792. }
  217793. const String SystemClipboard::getTextFromClipboard()
  217794. {
  217795. ClipboardHelpers::initSelectionAtoms();
  217796. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  217797. level" clipboard that is supposed to be filled by ctrl-C
  217798. etc). When a clipboard manager is running, the content of this
  217799. selection is preserved even when the original selection owner
  217800. exits.
  217801. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  217802. filled by good old x11 apps such as xterm)
  217803. */
  217804. String content;
  217805. Atom selection = XA_PRIMARY;
  217806. Window selectionOwner = None;
  217807. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  217808. {
  217809. selection = ClipboardHelpers::atom_CLIPBOARD;
  217810. selectionOwner = XGetSelectionOwner (display, selection);
  217811. }
  217812. if (selectionOwner != None)
  217813. {
  217814. if (selectionOwner == juce_messageWindowHandle)
  217815. {
  217816. content = ClipboardHelpers::localClipboardContent;
  217817. }
  217818. else
  217819. {
  217820. // first try: we want an utf8 string
  217821. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  217822. if (! ok)
  217823. {
  217824. // second chance, ask for a good old locale-dependent string ..
  217825. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  217826. }
  217827. }
  217828. }
  217829. return content;
  217830. }
  217831. #endif
  217832. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  217833. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  217834. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217835. // compiled on its own).
  217836. #if JUCE_INCLUDED_FILE
  217837. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  217838. #define JUCE_DEBUG_XERRORS 1
  217839. #endif
  217840. Display* display = 0;
  217841. Window juce_messageWindowHandle = None;
  217842. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  217843. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  217844. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  217845. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  217846. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  217847. class InternalMessageQueue
  217848. {
  217849. public:
  217850. InternalMessageQueue()
  217851. : bytesInSocket (0),
  217852. totalEventCount (0)
  217853. {
  217854. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  217855. (void) ret; jassert (ret == 0);
  217856. //setNonBlocking (fd[0]);
  217857. //setNonBlocking (fd[1]);
  217858. }
  217859. ~InternalMessageQueue()
  217860. {
  217861. close (fd[0]);
  217862. close (fd[1]);
  217863. clearSingletonInstance();
  217864. }
  217865. void postMessage (Message* msg)
  217866. {
  217867. const int maxBytesInSocketQueue = 128;
  217868. ScopedLock sl (lock);
  217869. queue.add (msg);
  217870. if (bytesInSocket < maxBytesInSocketQueue)
  217871. {
  217872. ++bytesInSocket;
  217873. ScopedUnlock ul (lock);
  217874. const unsigned char x = 0xff;
  217875. size_t bytesWritten = write (fd[0], &x, 1);
  217876. (void) bytesWritten;
  217877. }
  217878. }
  217879. bool isEmpty() const
  217880. {
  217881. ScopedLock sl (lock);
  217882. return queue.size() == 0;
  217883. }
  217884. bool dispatchNextEvent()
  217885. {
  217886. // This alternates between giving priority to XEvents or internal messages,
  217887. // to keep everything running smoothly..
  217888. if ((++totalEventCount & 1) != 0)
  217889. return dispatchNextXEvent() || dispatchNextInternalMessage();
  217890. else
  217891. return dispatchNextInternalMessage() || dispatchNextXEvent();
  217892. }
  217893. // Wait for an event (either XEvent, or an internal Message)
  217894. bool sleepUntilEvent (const int timeoutMs)
  217895. {
  217896. if (! isEmpty())
  217897. return true;
  217898. if (display != 0)
  217899. {
  217900. ScopedXLock xlock;
  217901. if (XPending (display))
  217902. return true;
  217903. }
  217904. struct timeval tv;
  217905. tv.tv_sec = 0;
  217906. tv.tv_usec = timeoutMs * 1000;
  217907. int fd0 = getWaitHandle();
  217908. int fdmax = fd0;
  217909. fd_set readset;
  217910. FD_ZERO (&readset);
  217911. FD_SET (fd0, &readset);
  217912. if (display != 0)
  217913. {
  217914. ScopedXLock xlock;
  217915. int fd1 = XConnectionNumber (display);
  217916. FD_SET (fd1, &readset);
  217917. fdmax = jmax (fd0, fd1);
  217918. }
  217919. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  217920. return (ret > 0); // ret <= 0 if error or timeout
  217921. }
  217922. struct MessageThreadFuncCall
  217923. {
  217924. enum { uniqueID = 0x73774623 };
  217925. MessageCallbackFunction* func;
  217926. void* parameter;
  217927. void* result;
  217928. CriticalSection lock;
  217929. WaitableEvent event;
  217930. };
  217931. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  217932. private:
  217933. CriticalSection lock;
  217934. ReferenceCountedArray <Message> queue;
  217935. int fd[2];
  217936. int bytesInSocket;
  217937. int totalEventCount;
  217938. int getWaitHandle() const throw() { return fd[1]; }
  217939. static bool setNonBlocking (int handle)
  217940. {
  217941. int socketFlags = fcntl (handle, F_GETFL, 0);
  217942. if (socketFlags == -1)
  217943. return false;
  217944. socketFlags |= O_NONBLOCK;
  217945. return fcntl (handle, F_SETFL, socketFlags) == 0;
  217946. }
  217947. static bool dispatchNextXEvent()
  217948. {
  217949. if (display == 0)
  217950. return false;
  217951. XEvent evt;
  217952. {
  217953. ScopedXLock xlock;
  217954. if (! XPending (display))
  217955. return false;
  217956. XNextEvent (display, &evt);
  217957. }
  217958. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  217959. juce_handleSelectionRequest (evt.xselectionrequest);
  217960. else if (evt.xany.window != juce_messageWindowHandle)
  217961. juce_windowMessageReceive (&evt);
  217962. return true;
  217963. }
  217964. const Message::Ptr popNextMessage()
  217965. {
  217966. const ScopedLock sl (lock);
  217967. if (bytesInSocket > 0)
  217968. {
  217969. --bytesInSocket;
  217970. const ScopedUnlock ul (lock);
  217971. unsigned char x;
  217972. size_t numBytes = read (fd[1], &x, 1);
  217973. (void) numBytes;
  217974. }
  217975. return queue.removeAndReturn (0);
  217976. }
  217977. bool dispatchNextInternalMessage()
  217978. {
  217979. const Message::Ptr msg (popNextMessage());
  217980. if (msg == 0)
  217981. return false;
  217982. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  217983. {
  217984. // Handle callback message
  217985. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  217986. call->result = (*(call->func)) (call->parameter);
  217987. call->event.signal();
  217988. }
  217989. else
  217990. {
  217991. // Handle "normal" messages
  217992. MessageManager::getInstance()->deliverMessage (msg);
  217993. }
  217994. return true;
  217995. }
  217996. };
  217997. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  217998. namespace LinuxErrorHandling
  217999. {
  218000. static bool errorOccurred = false;
  218001. static bool keyboardBreakOccurred = false;
  218002. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218003. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218004. // Usually happens when client-server connection is broken
  218005. static int ioErrorHandler (Display* display)
  218006. {
  218007. DBG ("ERROR: connection to X server broken.. terminating.");
  218008. if (JUCEApplication::isStandaloneApp())
  218009. MessageManager::getInstance()->stopDispatchLoop();
  218010. errorOccurred = true;
  218011. return 0;
  218012. }
  218013. // A protocol error has occurred
  218014. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218015. {
  218016. #if JUCE_DEBUG_XERRORS
  218017. char errorStr[64] = { 0 };
  218018. char requestStr[64] = { 0 };
  218019. XGetErrorText (display, event->error_code, errorStr, 64);
  218020. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  218021. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  218022. #endif
  218023. return 0;
  218024. }
  218025. static void installXErrorHandlers()
  218026. {
  218027. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  218028. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  218029. }
  218030. static void removeXErrorHandlers()
  218031. {
  218032. if (JUCEApplication::isStandaloneApp())
  218033. {
  218034. XSetIOErrorHandler (oldIOErrorHandler);
  218035. oldIOErrorHandler = 0;
  218036. XSetErrorHandler (oldErrorHandler);
  218037. oldErrorHandler = 0;
  218038. }
  218039. }
  218040. static void keyboardBreakSignalHandler (int sig)
  218041. {
  218042. if (sig == SIGINT)
  218043. keyboardBreakOccurred = true;
  218044. }
  218045. static void installKeyboardBreakHandler()
  218046. {
  218047. struct sigaction saction;
  218048. sigset_t maskSet;
  218049. sigemptyset (&maskSet);
  218050. saction.sa_handler = keyboardBreakSignalHandler;
  218051. saction.sa_mask = maskSet;
  218052. saction.sa_flags = 0;
  218053. sigaction (SIGINT, &saction, 0);
  218054. }
  218055. }
  218056. void MessageManager::doPlatformSpecificInitialisation()
  218057. {
  218058. if (JUCEApplication::isStandaloneApp())
  218059. {
  218060. // Initialise xlib for multiple thread support
  218061. static bool initThreadCalled = false;
  218062. if (! initThreadCalled)
  218063. {
  218064. if (! XInitThreads())
  218065. {
  218066. // This is fatal! Print error and closedown
  218067. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  218068. Process::terminate();
  218069. return;
  218070. }
  218071. initThreadCalled = true;
  218072. }
  218073. LinuxErrorHandling::installXErrorHandlers();
  218074. LinuxErrorHandling::installKeyboardBreakHandler();
  218075. }
  218076. // Create the internal message queue
  218077. InternalMessageQueue::getInstance();
  218078. // Try to connect to a display
  218079. String displayName (getenv ("DISPLAY"));
  218080. if (displayName.isEmpty())
  218081. displayName = ":0.0";
  218082. display = XOpenDisplay (displayName.toCString());
  218083. if (display != 0) // This is not fatal! we can run headless.
  218084. {
  218085. // Create a context to store user data associated with Windows we create in WindowDriver
  218086. windowHandleXContext = XUniqueContext();
  218087. // We're only interested in client messages for this window, which are always sent
  218088. XSetWindowAttributes swa;
  218089. swa.event_mask = NoEventMask;
  218090. // Create our message window (this will never be mapped)
  218091. const int screen = DefaultScreen (display);
  218092. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  218093. 0, 0, 1, 1, 0, 0, InputOnly,
  218094. DefaultVisual (display, screen),
  218095. CWEventMask, &swa);
  218096. }
  218097. }
  218098. void MessageManager::doPlatformSpecificShutdown()
  218099. {
  218100. InternalMessageQueue::deleteInstance();
  218101. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  218102. {
  218103. XDestroyWindow (display, juce_messageWindowHandle);
  218104. XCloseDisplay (display);
  218105. juce_messageWindowHandle = 0;
  218106. display = 0;
  218107. LinuxErrorHandling::removeXErrorHandlers();
  218108. }
  218109. }
  218110. bool juce_postMessageToSystemQueue (Message* message)
  218111. {
  218112. if (LinuxErrorHandling::errorOccurred)
  218113. return false;
  218114. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  218115. return true;
  218116. }
  218117. void MessageManager::broadcastMessage (const String& value)
  218118. {
  218119. /* TODO */
  218120. }
  218121. class AsyncFunctionCaller : public AsyncUpdater
  218122. {
  218123. public:
  218124. static void* call (MessageCallbackFunction* func_, void* parameter_)
  218125. {
  218126. if (MessageManager::getInstance()->isThisTheMessageThread())
  218127. return func_ (parameter_);
  218128. AsyncFunctionCaller caller (func_, parameter_);
  218129. caller.triggerAsyncUpdate();
  218130. caller.finished.wait();
  218131. return caller.result;
  218132. }
  218133. void handleAsyncUpdate()
  218134. {
  218135. result = (*func) (parameter);
  218136. finished.signal();
  218137. }
  218138. private:
  218139. WaitableEvent finished;
  218140. MessageCallbackFunction* func;
  218141. void* parameter;
  218142. void* volatile result;
  218143. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  218144. : result (0), func (func_), parameter (parameter_)
  218145. {}
  218146. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  218147. };
  218148. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  218149. {
  218150. if (LinuxErrorHandling::errorOccurred)
  218151. return 0;
  218152. return AsyncFunctionCaller::call (func, parameter);
  218153. }
  218154. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  218155. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  218156. {
  218157. while (! LinuxErrorHandling::errorOccurred)
  218158. {
  218159. if (LinuxErrorHandling::keyboardBreakOccurred)
  218160. {
  218161. LinuxErrorHandling::errorOccurred = true;
  218162. if (JUCEApplication::isStandaloneApp())
  218163. Process::terminate();
  218164. break;
  218165. }
  218166. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  218167. return true;
  218168. if (returnIfNoPendingMessages)
  218169. break;
  218170. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  218171. }
  218172. return false;
  218173. }
  218174. #endif
  218175. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  218176. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  218177. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218178. // compiled on its own).
  218179. #if JUCE_INCLUDED_FILE
  218180. class FreeTypeFontFace
  218181. {
  218182. public:
  218183. enum FontStyle
  218184. {
  218185. Plain = 0,
  218186. Bold = 1,
  218187. Italic = 2
  218188. };
  218189. FreeTypeFontFace (const String& familyName)
  218190. : hasSerif (false),
  218191. monospaced (false)
  218192. {
  218193. family = familyName;
  218194. }
  218195. void setFileName (const String& name, const int faceIndex, FontStyle style)
  218196. {
  218197. if (names [(int) style].fileName.isEmpty())
  218198. {
  218199. names [(int) style].fileName = name;
  218200. names [(int) style].faceIndex = faceIndex;
  218201. }
  218202. }
  218203. const String& getFamilyName() const throw() { return family; }
  218204. const String& getFileName (const int style, int& faceIndex) const throw()
  218205. {
  218206. faceIndex = names[style].faceIndex;
  218207. return names[style].fileName;
  218208. }
  218209. void setMonospaced (bool mono) throw() { monospaced = mono; }
  218210. bool getMonospaced() const throw() { return monospaced; }
  218211. void setSerif (const bool serif) throw() { hasSerif = serif; }
  218212. bool getSerif() const throw() { return hasSerif; }
  218213. private:
  218214. String family;
  218215. struct FontNameIndex
  218216. {
  218217. String fileName;
  218218. int faceIndex;
  218219. };
  218220. FontNameIndex names[4];
  218221. bool hasSerif, monospaced;
  218222. };
  218223. class FreeTypeInterface : public DeletedAtShutdown
  218224. {
  218225. public:
  218226. FreeTypeInterface()
  218227. : ftLib (0),
  218228. lastFace (0),
  218229. lastBold (false),
  218230. lastItalic (false)
  218231. {
  218232. if (FT_Init_FreeType (&ftLib) != 0)
  218233. {
  218234. ftLib = 0;
  218235. DBG ("Failed to initialize FreeType");
  218236. }
  218237. StringArray fontDirs;
  218238. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  218239. fontDirs.removeEmptyStrings (true);
  218240. if (fontDirs.size() == 0)
  218241. {
  218242. const ScopedPointer<XmlElement> fontsInfo (XmlDocument::parse (File ("/etc/fonts/fonts.conf")));
  218243. if (fontsInfo != 0)
  218244. {
  218245. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  218246. {
  218247. fontDirs.add (e->getAllSubText().trim());
  218248. }
  218249. }
  218250. }
  218251. if (fontDirs.size() == 0)
  218252. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  218253. for (int i = 0; i < fontDirs.size(); ++i)
  218254. enumerateFaces (fontDirs[i]);
  218255. }
  218256. ~FreeTypeInterface()
  218257. {
  218258. if (lastFace != 0)
  218259. FT_Done_Face (lastFace);
  218260. if (ftLib != 0)
  218261. FT_Done_FreeType (ftLib);
  218262. clearSingletonInstance();
  218263. }
  218264. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  218265. {
  218266. for (int i = 0; i < faces.size(); i++)
  218267. if (faces[i]->getFamilyName() == familyName)
  218268. return faces[i];
  218269. if (! create)
  218270. return 0;
  218271. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  218272. faces.add (newFace);
  218273. return newFace;
  218274. }
  218275. // Enumerate all font faces available in a given directory
  218276. void enumerateFaces (const String& path)
  218277. {
  218278. File dirPath (path);
  218279. if (path.isEmpty() || ! dirPath.isDirectory())
  218280. return;
  218281. DirectoryIterator di (dirPath, true);
  218282. while (di.next())
  218283. {
  218284. File possible (di.getFile());
  218285. if (possible.hasFileExtension ("ttf")
  218286. || possible.hasFileExtension ("pfb")
  218287. || possible.hasFileExtension ("pcf"))
  218288. {
  218289. FT_Face face;
  218290. int faceIndex = 0;
  218291. int numFaces = 0;
  218292. do
  218293. {
  218294. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  218295. faceIndex, &face) == 0)
  218296. {
  218297. if (faceIndex == 0)
  218298. numFaces = face->num_faces;
  218299. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  218300. {
  218301. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  218302. int style = (int) FreeTypeFontFace::Plain;
  218303. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  218304. style |= (int) FreeTypeFontFace::Bold;
  218305. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  218306. style |= (int) FreeTypeFontFace::Italic;
  218307. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  218308. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  218309. // Surely there must be a better way to do this?
  218310. const String name (face->family_name);
  218311. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  218312. || name.containsIgnoreCase ("Verdana")
  218313. || name.containsIgnoreCase ("Arial")));
  218314. }
  218315. FT_Done_Face (face);
  218316. }
  218317. ++faceIndex;
  218318. }
  218319. while (faceIndex < numFaces);
  218320. }
  218321. }
  218322. }
  218323. // Create a FreeType face object for a given font
  218324. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  218325. {
  218326. FT_Face face = 0;
  218327. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  218328. {
  218329. face = lastFace;
  218330. }
  218331. else
  218332. {
  218333. if (lastFace != 0)
  218334. {
  218335. FT_Done_Face (lastFace);
  218336. lastFace = 0;
  218337. }
  218338. lastFontName = fontName;
  218339. lastBold = bold;
  218340. lastItalic = italic;
  218341. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  218342. if (ftFace != 0)
  218343. {
  218344. int style = (int) FreeTypeFontFace::Plain;
  218345. if (bold)
  218346. style |= (int) FreeTypeFontFace::Bold;
  218347. if (italic)
  218348. style |= (int) FreeTypeFontFace::Italic;
  218349. int faceIndex;
  218350. String fileName (ftFace->getFileName (style, faceIndex));
  218351. if (fileName.isEmpty())
  218352. {
  218353. style ^= (int) FreeTypeFontFace::Bold;
  218354. fileName = ftFace->getFileName (style, faceIndex);
  218355. if (fileName.isEmpty())
  218356. {
  218357. style ^= (int) FreeTypeFontFace::Bold;
  218358. style ^= (int) FreeTypeFontFace::Italic;
  218359. fileName = ftFace->getFileName (style, faceIndex);
  218360. if (! fileName.length())
  218361. {
  218362. style ^= (int) FreeTypeFontFace::Bold;
  218363. fileName = ftFace->getFileName (style, faceIndex);
  218364. }
  218365. }
  218366. }
  218367. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  218368. {
  218369. face = lastFace;
  218370. // If there isn't a unicode charmap then select the first one.
  218371. if (FT_Select_Charmap (face, ft_encoding_unicode))
  218372. FT_Set_Charmap (face, face->charmaps[0]);
  218373. }
  218374. }
  218375. }
  218376. return face;
  218377. }
  218378. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  218379. {
  218380. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  218381. const float height = (float) (face->ascender - face->descender);
  218382. const float scaleX = 1.0f / height;
  218383. const float scaleY = -1.0f / height;
  218384. Path destShape;
  218385. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  218386. || face->glyph->format != ft_glyph_format_outline)
  218387. {
  218388. return false;
  218389. }
  218390. const FT_Outline* const outline = &face->glyph->outline;
  218391. const short* const contours = outline->contours;
  218392. const char* const tags = outline->tags;
  218393. FT_Vector* const points = outline->points;
  218394. for (int c = 0; c < outline->n_contours; c++)
  218395. {
  218396. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  218397. const int endPoint = contours[c];
  218398. for (int p = startPoint; p <= endPoint; p++)
  218399. {
  218400. const float x = scaleX * points[p].x;
  218401. const float y = scaleY * points[p].y;
  218402. if (p == startPoint)
  218403. {
  218404. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218405. {
  218406. float x2 = scaleX * points [endPoint].x;
  218407. float y2 = scaleY * points [endPoint].y;
  218408. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  218409. {
  218410. x2 = (x + x2) * 0.5f;
  218411. y2 = (y + y2) * 0.5f;
  218412. }
  218413. destShape.startNewSubPath (x2, y2);
  218414. }
  218415. else
  218416. {
  218417. destShape.startNewSubPath (x, y);
  218418. }
  218419. }
  218420. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  218421. {
  218422. if (p != startPoint)
  218423. destShape.lineTo (x, y);
  218424. }
  218425. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  218426. {
  218427. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  218428. float x2 = scaleX * points [nextIndex].x;
  218429. float y2 = scaleY * points [nextIndex].y;
  218430. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  218431. {
  218432. x2 = (x + x2) * 0.5f;
  218433. y2 = (y + y2) * 0.5f;
  218434. }
  218435. else
  218436. {
  218437. ++p;
  218438. }
  218439. destShape.quadraticTo (x, y, x2, y2);
  218440. }
  218441. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  218442. {
  218443. if (p >= endPoint)
  218444. return false;
  218445. const int next1 = p + 1;
  218446. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  218447. const float x2 = scaleX * points [next1].x;
  218448. const float y2 = scaleY * points [next1].y;
  218449. const float x3 = scaleX * points [next2].x;
  218450. const float y3 = scaleY * points [next2].y;
  218451. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  218452. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  218453. return false;
  218454. destShape.cubicTo (x, y, x2, y2, x3, y3);
  218455. p += 2;
  218456. }
  218457. }
  218458. destShape.closeSubPath();
  218459. }
  218460. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  218461. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  218462. addKerning (face, dest, character, glyphIndex);
  218463. return true;
  218464. }
  218465. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  218466. {
  218467. const float height = (float) (face->ascender - face->descender);
  218468. uint32 rightGlyphIndex;
  218469. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  218470. while (rightGlyphIndex != 0)
  218471. {
  218472. FT_Vector kerning;
  218473. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  218474. {
  218475. if (kerning.x != 0)
  218476. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  218477. }
  218478. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  218479. }
  218480. }
  218481. // Add a glyph to a font
  218482. bool addGlyphToFont (const uint32 character, const String& fontName,
  218483. bool bold, bool italic, CustomTypeface& dest)
  218484. {
  218485. FT_Face face = createFT_Face (fontName, bold, italic);
  218486. return face != 0 && addGlyph (face, dest, character);
  218487. }
  218488. void getFamilyNames (StringArray& familyNames) const
  218489. {
  218490. for (int i = 0; i < faces.size(); i++)
  218491. familyNames.add (faces[i]->getFamilyName());
  218492. }
  218493. void getMonospacedNames (StringArray& monoSpaced) const
  218494. {
  218495. for (int i = 0; i < faces.size(); i++)
  218496. if (faces[i]->getMonospaced())
  218497. monoSpaced.add (faces[i]->getFamilyName());
  218498. }
  218499. void getSerifNames (StringArray& serif) const
  218500. {
  218501. for (int i = 0; i < faces.size(); i++)
  218502. if (faces[i]->getSerif())
  218503. serif.add (faces[i]->getFamilyName());
  218504. }
  218505. void getSansSerifNames (StringArray& sansSerif) const
  218506. {
  218507. for (int i = 0; i < faces.size(); i++)
  218508. if (! faces[i]->getSerif())
  218509. sansSerif.add (faces[i]->getFamilyName());
  218510. }
  218511. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  218512. private:
  218513. FT_Library ftLib;
  218514. FT_Face lastFace;
  218515. String lastFontName;
  218516. bool lastBold, lastItalic;
  218517. OwnedArray<FreeTypeFontFace> faces;
  218518. };
  218519. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  218520. class FreetypeTypeface : public CustomTypeface
  218521. {
  218522. public:
  218523. FreetypeTypeface (const Font& font)
  218524. {
  218525. FT_Face face = FreeTypeInterface::getInstance()
  218526. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  218527. if (face == 0)
  218528. {
  218529. #if JUCE_DEBUG
  218530. String msg ("Failed to create typeface: ");
  218531. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  218532. DBG (msg);
  218533. #endif
  218534. }
  218535. else
  218536. {
  218537. setCharacteristics (font.getTypefaceName(),
  218538. face->ascender / (float) (face->ascender - face->descender),
  218539. font.isBold(), font.isItalic(),
  218540. L' ');
  218541. }
  218542. }
  218543. bool loadGlyphIfPossible (juce_wchar character)
  218544. {
  218545. return FreeTypeInterface::getInstance()
  218546. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  218547. }
  218548. };
  218549. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  218550. {
  218551. return new FreetypeTypeface (font);
  218552. }
  218553. const StringArray Font::findAllTypefaceNames()
  218554. {
  218555. StringArray s;
  218556. FreeTypeInterface::getInstance()->getFamilyNames (s);
  218557. s.sort (true);
  218558. return s;
  218559. }
  218560. namespace
  218561. {
  218562. const String pickBestFont (const StringArray& names,
  218563. const char* const choicesString)
  218564. {
  218565. StringArray choices;
  218566. choices.addTokens (String (choicesString), ",", String::empty);
  218567. choices.trim();
  218568. choices.removeEmptyStrings();
  218569. int i, j;
  218570. for (j = 0; j < choices.size(); ++j)
  218571. if (names.contains (choices[j], true))
  218572. return choices[j];
  218573. for (j = 0; j < choices.size(); ++j)
  218574. for (i = 0; i < names.size(); i++)
  218575. if (names[i].startsWithIgnoreCase (choices[j]))
  218576. return names[i];
  218577. for (j = 0; j < choices.size(); ++j)
  218578. for (i = 0; i < names.size(); i++)
  218579. if (names[i].containsIgnoreCase (choices[j]))
  218580. return names[i];
  218581. return names[0];
  218582. }
  218583. const String linux_getDefaultSansSerifFontName()
  218584. {
  218585. StringArray allFonts;
  218586. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  218587. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  218588. }
  218589. const String linux_getDefaultSerifFontName()
  218590. {
  218591. StringArray allFonts;
  218592. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  218593. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  218594. }
  218595. const String linux_getDefaultMonospacedFontName()
  218596. {
  218597. StringArray allFonts;
  218598. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  218599. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  218600. }
  218601. }
  218602. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& /*defaultFallback*/)
  218603. {
  218604. defaultSans = linux_getDefaultSansSerifFontName();
  218605. defaultSerif = linux_getDefaultSerifFontName();
  218606. defaultFixed = linux_getDefaultMonospacedFontName();
  218607. }
  218608. #endif
  218609. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  218610. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  218611. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218612. // compiled on its own).
  218613. #if JUCE_INCLUDED_FILE
  218614. // These are defined in juce_linux_Messaging.cpp
  218615. extern Display* display;
  218616. extern XContext windowHandleXContext;
  218617. namespace Atoms
  218618. {
  218619. enum ProtocolItems
  218620. {
  218621. TAKE_FOCUS = 0,
  218622. DELETE_WINDOW = 1,
  218623. PING = 2
  218624. };
  218625. static Atom Protocols, ProtocolList[3], ChangeState, State,
  218626. ActiveWin, Pid, WindowType, WindowState,
  218627. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  218628. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  218629. XdndActionDescription, XdndActionCopy,
  218630. allowedActions[5],
  218631. allowedMimeTypes[2];
  218632. const unsigned long DndVersion = 3;
  218633. static void initialiseAtoms()
  218634. {
  218635. static bool atomsInitialised = false;
  218636. if (! atomsInitialised)
  218637. {
  218638. atomsInitialised = true;
  218639. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  218640. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  218641. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  218642. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  218643. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  218644. State = XInternAtom (display, "WM_STATE", True);
  218645. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  218646. Pid = XInternAtom (display, "_NET_WM_PID", False);
  218647. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  218648. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  218649. XdndAware = XInternAtom (display, "XdndAware", False);
  218650. XdndEnter = XInternAtom (display, "XdndEnter", False);
  218651. XdndLeave = XInternAtom (display, "XdndLeave", False);
  218652. XdndPosition = XInternAtom (display, "XdndPosition", False);
  218653. XdndStatus = XInternAtom (display, "XdndStatus", False);
  218654. XdndDrop = XInternAtom (display, "XdndDrop", False);
  218655. XdndFinished = XInternAtom (display, "XdndFinished", False);
  218656. XdndSelection = XInternAtom (display, "XdndSelection", False);
  218657. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  218658. XdndActionList = XInternAtom (display, "XdndActionList", False);
  218659. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  218660. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  218661. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  218662. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  218663. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  218664. allowedActions[1] = XdndActionCopy;
  218665. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  218666. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  218667. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  218668. }
  218669. }
  218670. }
  218671. namespace Keys
  218672. {
  218673. enum MouseButtons
  218674. {
  218675. NoButton = 0,
  218676. LeftButton = 1,
  218677. MiddleButton = 2,
  218678. RightButton = 3,
  218679. WheelUp = 4,
  218680. WheelDown = 5
  218681. };
  218682. static int AltMask = 0;
  218683. static int NumLockMask = 0;
  218684. static bool numLock = false;
  218685. static bool capsLock = false;
  218686. static char keyStates [32];
  218687. static const int extendedKeyModifier = 0x10000000;
  218688. }
  218689. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  218690. {
  218691. int keysym;
  218692. if (keyCode & Keys::extendedKeyModifier)
  218693. {
  218694. keysym = 0xff00 | (keyCode & 0xff);
  218695. }
  218696. else
  218697. {
  218698. keysym = keyCode;
  218699. if (keysym == (XK_Tab & 0xff)
  218700. || keysym == (XK_Return & 0xff)
  218701. || keysym == (XK_Escape & 0xff)
  218702. || keysym == (XK_BackSpace & 0xff))
  218703. {
  218704. keysym |= 0xff00;
  218705. }
  218706. }
  218707. ScopedXLock xlock;
  218708. const int keycode = XKeysymToKeycode (display, keysym);
  218709. const int keybyte = keycode >> 3;
  218710. const int keybit = (1 << (keycode & 7));
  218711. return (Keys::keyStates [keybyte] & keybit) != 0;
  218712. }
  218713. #if JUCE_USE_XSHM
  218714. namespace XSHMHelpers
  218715. {
  218716. static int trappedErrorCode = 0;
  218717. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  218718. {
  218719. trappedErrorCode = err->error_code;
  218720. return 0;
  218721. }
  218722. static bool isShmAvailable() throw()
  218723. {
  218724. static bool isChecked = false;
  218725. static bool isAvailable = false;
  218726. if (! isChecked)
  218727. {
  218728. isChecked = true;
  218729. int major, minor;
  218730. Bool pixmaps;
  218731. ScopedXLock xlock;
  218732. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  218733. {
  218734. trappedErrorCode = 0;
  218735. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  218736. XShmSegmentInfo segmentInfo;
  218737. zerostruct (segmentInfo);
  218738. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  218739. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  218740. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218741. xImage->bytes_per_line * xImage->height,
  218742. IPC_CREAT | 0777)) >= 0)
  218743. {
  218744. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218745. if (segmentInfo.shmaddr != (void*) -1)
  218746. {
  218747. segmentInfo.readOnly = False;
  218748. xImage->data = segmentInfo.shmaddr;
  218749. XSync (display, False);
  218750. if (XShmAttach (display, &segmentInfo) != 0)
  218751. {
  218752. XSync (display, False);
  218753. XShmDetach (display, &segmentInfo);
  218754. isAvailable = true;
  218755. }
  218756. }
  218757. XFlush (display);
  218758. XDestroyImage (xImage);
  218759. shmdt (segmentInfo.shmaddr);
  218760. }
  218761. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218762. XSetErrorHandler (oldHandler);
  218763. if (trappedErrorCode != 0)
  218764. isAvailable = false;
  218765. }
  218766. }
  218767. return isAvailable;
  218768. }
  218769. }
  218770. #endif
  218771. #if JUCE_USE_XRENDER
  218772. namespace XRender
  218773. {
  218774. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  218775. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  218776. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  218777. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  218778. static tXRenderQueryVersion xRenderQueryVersion = 0;
  218779. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  218780. static tXRenderFindFormat xRenderFindFormat = 0;
  218781. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  218782. static bool isAvailable()
  218783. {
  218784. static bool hasLoaded = false;
  218785. if (! hasLoaded)
  218786. {
  218787. ScopedXLock xlock;
  218788. hasLoaded = true;
  218789. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  218790. if (h != 0)
  218791. {
  218792. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  218793. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  218794. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  218795. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  218796. }
  218797. if (xRenderQueryVersion != 0
  218798. && xRenderFindStandardFormat != 0
  218799. && xRenderFindFormat != 0
  218800. && xRenderFindVisualFormat != 0)
  218801. {
  218802. int major, minor;
  218803. if (xRenderQueryVersion (display, &major, &minor))
  218804. return true;
  218805. }
  218806. xRenderQueryVersion = 0;
  218807. }
  218808. return xRenderQueryVersion != 0;
  218809. }
  218810. static XRenderPictFormat* findPictureFormat()
  218811. {
  218812. ScopedXLock xlock;
  218813. XRenderPictFormat* pictFormat = 0;
  218814. if (isAvailable())
  218815. {
  218816. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  218817. if (pictFormat == 0)
  218818. {
  218819. XRenderPictFormat desiredFormat;
  218820. desiredFormat.type = PictTypeDirect;
  218821. desiredFormat.depth = 32;
  218822. desiredFormat.direct.alphaMask = 0xff;
  218823. desiredFormat.direct.redMask = 0xff;
  218824. desiredFormat.direct.greenMask = 0xff;
  218825. desiredFormat.direct.blueMask = 0xff;
  218826. desiredFormat.direct.alpha = 24;
  218827. desiredFormat.direct.red = 16;
  218828. desiredFormat.direct.green = 8;
  218829. desiredFormat.direct.blue = 0;
  218830. pictFormat = xRenderFindFormat (display,
  218831. PictFormatType | PictFormatDepth
  218832. | PictFormatRedMask | PictFormatRed
  218833. | PictFormatGreenMask | PictFormatGreen
  218834. | PictFormatBlueMask | PictFormatBlue
  218835. | PictFormatAlphaMask | PictFormatAlpha,
  218836. &desiredFormat,
  218837. 0);
  218838. }
  218839. }
  218840. return pictFormat;
  218841. }
  218842. }
  218843. #endif
  218844. namespace Visuals
  218845. {
  218846. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  218847. {
  218848. ScopedXLock xlock;
  218849. Visual* visual = 0;
  218850. int numVisuals = 0;
  218851. long desiredMask = VisualNoMask;
  218852. XVisualInfo desiredVisual;
  218853. desiredVisual.screen = DefaultScreen (display);
  218854. desiredVisual.depth = desiredDepth;
  218855. desiredMask = VisualScreenMask | VisualDepthMask;
  218856. if (desiredDepth == 32)
  218857. {
  218858. desiredVisual.c_class = TrueColor;
  218859. desiredVisual.red_mask = 0x00FF0000;
  218860. desiredVisual.green_mask = 0x0000FF00;
  218861. desiredVisual.blue_mask = 0x000000FF;
  218862. desiredVisual.bits_per_rgb = 8;
  218863. desiredMask |= VisualClassMask;
  218864. desiredMask |= VisualRedMaskMask;
  218865. desiredMask |= VisualGreenMaskMask;
  218866. desiredMask |= VisualBlueMaskMask;
  218867. desiredMask |= VisualBitsPerRGBMask;
  218868. }
  218869. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218870. desiredMask,
  218871. &desiredVisual,
  218872. &numVisuals);
  218873. if (xvinfos != 0)
  218874. {
  218875. for (int i = 0; i < numVisuals; i++)
  218876. {
  218877. if (xvinfos[i].depth == desiredDepth)
  218878. {
  218879. visual = xvinfos[i].visual;
  218880. break;
  218881. }
  218882. }
  218883. XFree (xvinfos);
  218884. }
  218885. return visual;
  218886. }
  218887. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  218888. {
  218889. Visual* visual = 0;
  218890. if (desiredDepth == 32)
  218891. {
  218892. #if JUCE_USE_XSHM
  218893. if (XSHMHelpers::isShmAvailable())
  218894. {
  218895. #if JUCE_USE_XRENDER
  218896. if (XRender::isAvailable())
  218897. {
  218898. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  218899. if (pictFormat != 0)
  218900. {
  218901. int numVisuals = 0;
  218902. XVisualInfo desiredVisual;
  218903. desiredVisual.screen = DefaultScreen (display);
  218904. desiredVisual.depth = 32;
  218905. desiredVisual.bits_per_rgb = 8;
  218906. XVisualInfo* xvinfos = XGetVisualInfo (display,
  218907. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  218908. &desiredVisual, &numVisuals);
  218909. if (xvinfos != 0)
  218910. {
  218911. for (int i = 0; i < numVisuals; ++i)
  218912. {
  218913. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  218914. if (pictVisualFormat != 0
  218915. && pictVisualFormat->type == PictTypeDirect
  218916. && pictVisualFormat->direct.alphaMask)
  218917. {
  218918. visual = xvinfos[i].visual;
  218919. matchedDepth = 32;
  218920. break;
  218921. }
  218922. }
  218923. XFree (xvinfos);
  218924. }
  218925. }
  218926. }
  218927. #endif
  218928. if (visual == 0)
  218929. {
  218930. visual = findVisualWithDepth (32);
  218931. if (visual != 0)
  218932. matchedDepth = 32;
  218933. }
  218934. }
  218935. #endif
  218936. }
  218937. if (visual == 0 && desiredDepth >= 24)
  218938. {
  218939. visual = findVisualWithDepth (24);
  218940. if (visual != 0)
  218941. matchedDepth = 24;
  218942. }
  218943. if (visual == 0 && desiredDepth >= 16)
  218944. {
  218945. visual = findVisualWithDepth (16);
  218946. if (visual != 0)
  218947. matchedDepth = 16;
  218948. }
  218949. return visual;
  218950. }
  218951. }
  218952. class XBitmapImage : public Image::SharedImage
  218953. {
  218954. public:
  218955. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  218956. const bool clearImage, const int imageDepth_, Visual* visual)
  218957. : Image::SharedImage (format_, w, h),
  218958. imageDepth (imageDepth_),
  218959. gc (None)
  218960. {
  218961. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  218962. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  218963. lineStride = ((w * pixelStride + 3) & ~3);
  218964. ScopedXLock xlock;
  218965. #if JUCE_USE_XSHM
  218966. usingXShm = false;
  218967. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  218968. {
  218969. zerostruct (segmentInfo);
  218970. segmentInfo.shmid = -1;
  218971. segmentInfo.shmaddr = (char *) -1;
  218972. segmentInfo.readOnly = False;
  218973. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  218974. if (xImage != 0)
  218975. {
  218976. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  218977. xImage->bytes_per_line * xImage->height,
  218978. IPC_CREAT | 0777)) >= 0)
  218979. {
  218980. if (segmentInfo.shmid != -1)
  218981. {
  218982. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  218983. if (segmentInfo.shmaddr != (void*) -1)
  218984. {
  218985. segmentInfo.readOnly = False;
  218986. xImage->data = segmentInfo.shmaddr;
  218987. imageData = (uint8*) segmentInfo.shmaddr;
  218988. if (XShmAttach (display, &segmentInfo) != 0)
  218989. usingXShm = true;
  218990. else
  218991. jassertfalse;
  218992. }
  218993. else
  218994. {
  218995. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  218996. }
  218997. }
  218998. }
  218999. }
  219000. }
  219001. if (! usingXShm)
  219002. #endif
  219003. {
  219004. imageDataAllocated.malloc (lineStride * h);
  219005. imageData = imageDataAllocated;
  219006. if (format_ == Image::ARGB && clearImage)
  219007. zeromem (imageData, h * lineStride);
  219008. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219009. xImage->width = w;
  219010. xImage->height = h;
  219011. xImage->xoffset = 0;
  219012. xImage->format = ZPixmap;
  219013. xImage->data = (char*) imageData;
  219014. xImage->byte_order = ImageByteOrder (display);
  219015. xImage->bitmap_unit = BitmapUnit (display);
  219016. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219017. xImage->bitmap_pad = 32;
  219018. xImage->depth = pixelStride * 8;
  219019. xImage->bytes_per_line = lineStride;
  219020. xImage->bits_per_pixel = pixelStride * 8;
  219021. xImage->red_mask = 0x00FF0000;
  219022. xImage->green_mask = 0x0000FF00;
  219023. xImage->blue_mask = 0x000000FF;
  219024. if (imageDepth == 16)
  219025. {
  219026. const int pixelStride = 2;
  219027. const int lineStride = ((w * pixelStride + 3) & ~3);
  219028. imageData16Bit.malloc (lineStride * h);
  219029. xImage->data = imageData16Bit;
  219030. xImage->bitmap_pad = 16;
  219031. xImage->depth = pixelStride * 8;
  219032. xImage->bytes_per_line = lineStride;
  219033. xImage->bits_per_pixel = pixelStride * 8;
  219034. xImage->red_mask = visual->red_mask;
  219035. xImage->green_mask = visual->green_mask;
  219036. xImage->blue_mask = visual->blue_mask;
  219037. }
  219038. if (! XInitImage (xImage))
  219039. jassertfalse;
  219040. }
  219041. }
  219042. ~XBitmapImage()
  219043. {
  219044. ScopedXLock xlock;
  219045. if (gc != None)
  219046. XFreeGC (display, gc);
  219047. #if JUCE_USE_XSHM
  219048. if (usingXShm)
  219049. {
  219050. XShmDetach (display, &segmentInfo);
  219051. XFlush (display);
  219052. XDestroyImage (xImage);
  219053. shmdt (segmentInfo.shmaddr);
  219054. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219055. }
  219056. else
  219057. #endif
  219058. {
  219059. xImage->data = 0;
  219060. XDestroyImage (xImage);
  219061. }
  219062. }
  219063. Image::ImageType getType() const { return Image::NativeImage; }
  219064. LowLevelGraphicsContext* createLowLevelContext()
  219065. {
  219066. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  219067. }
  219068. SharedImage* clone()
  219069. {
  219070. jassertfalse;
  219071. return 0;
  219072. }
  219073. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  219074. {
  219075. ScopedXLock xlock;
  219076. if (gc == None)
  219077. {
  219078. XGCValues gcvalues;
  219079. gcvalues.foreground = None;
  219080. gcvalues.background = None;
  219081. gcvalues.function = GXcopy;
  219082. gcvalues.plane_mask = AllPlanes;
  219083. gcvalues.clip_mask = None;
  219084. gcvalues.graphics_exposures = False;
  219085. gc = XCreateGC (display, window,
  219086. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  219087. &gcvalues);
  219088. }
  219089. if (imageDepth == 16)
  219090. {
  219091. const uint32 rMask = xImage->red_mask;
  219092. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  219093. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  219094. const uint32 gMask = xImage->green_mask;
  219095. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  219096. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  219097. const uint32 bMask = xImage->blue_mask;
  219098. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  219099. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  219100. const Image::BitmapData srcData (Image (this), false);
  219101. for (int y = sy; y < sy + dh; ++y)
  219102. {
  219103. const uint8* p = srcData.getPixelPointer (sx, y);
  219104. for (int x = sx; x < sx + dw; ++x)
  219105. {
  219106. const PixelRGB* const pixel = (const PixelRGB*) p;
  219107. p += srcData.pixelStride;
  219108. XPutPixel (xImage, x, y,
  219109. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  219110. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  219111. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  219112. }
  219113. }
  219114. }
  219115. // blit results to screen.
  219116. #if JUCE_USE_XSHM
  219117. if (usingXShm)
  219118. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  219119. else
  219120. #endif
  219121. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  219122. }
  219123. private:
  219124. XImage* xImage;
  219125. const int imageDepth;
  219126. HeapBlock <uint8> imageDataAllocated;
  219127. HeapBlock <char> imageData16Bit;
  219128. GC gc;
  219129. #if JUCE_USE_XSHM
  219130. XShmSegmentInfo segmentInfo;
  219131. bool usingXShm;
  219132. #endif
  219133. static int getShiftNeeded (const uint32 mask) throw()
  219134. {
  219135. for (int i = 32; --i >= 0;)
  219136. if (((mask >> i) & 1) != 0)
  219137. return i - 7;
  219138. jassertfalse;
  219139. return 0;
  219140. }
  219141. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (XBitmapImage);
  219142. };
  219143. namespace PixmapHelpers
  219144. {
  219145. Pixmap createColourPixmapFromImage (Display* display, const Image& image)
  219146. {
  219147. ScopedXLock xlock;
  219148. const int width = image.getWidth();
  219149. const int height = image.getHeight();
  219150. HeapBlock <uint32> colour (width * height);
  219151. int index = 0;
  219152. for (int y = 0; y < height; ++y)
  219153. for (int x = 0; x < width; ++x)
  219154. colour[index++] = image.getPixelAt (x, y).getARGB();
  219155. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  219156. 0, reinterpret_cast<char*> (colour.getData()),
  219157. width, height, 32, 0);
  219158. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  219159. width, height, 24);
  219160. GC gc = XCreateGC (display, pixmap, 0, 0);
  219161. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  219162. XFreeGC (display, gc);
  219163. return pixmap;
  219164. }
  219165. Pixmap createMaskPixmapFromImage (Display* display, const Image& image)
  219166. {
  219167. ScopedXLock xlock;
  219168. const int width = image.getWidth();
  219169. const int height = image.getHeight();
  219170. const int stride = (width + 7) >> 3;
  219171. HeapBlock <char> mask;
  219172. mask.calloc (stride * height);
  219173. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  219174. for (int y = 0; y < height; ++y)
  219175. {
  219176. for (int x = 0; x < width; ++x)
  219177. {
  219178. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  219179. const int offset = y * stride + (x >> 3);
  219180. if (image.getPixelAt (x, y).getAlpha() >= 128)
  219181. mask[offset] |= bit;
  219182. }
  219183. }
  219184. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  219185. mask.getData(), width, height, 1, 0, 1);
  219186. }
  219187. }
  219188. class LinuxComponentPeer : public ComponentPeer
  219189. {
  219190. public:
  219191. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  219192. : ComponentPeer (component, windowStyleFlags),
  219193. windowH (0),
  219194. parentWindow (0),
  219195. wx (0),
  219196. wy (0),
  219197. ww (0),
  219198. wh (0),
  219199. fullScreen (false),
  219200. mapped (false),
  219201. visual (0),
  219202. depth (0)
  219203. {
  219204. // it's dangerous to create a window on a thread other than the message thread..
  219205. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219206. repainter = new LinuxRepaintManager (this);
  219207. createWindow();
  219208. setTitle (component->getName());
  219209. }
  219210. ~LinuxComponentPeer()
  219211. {
  219212. // it's dangerous to delete a window on a thread other than the message thread..
  219213. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  219214. deleteIconPixmaps();
  219215. destroyWindow();
  219216. windowH = 0;
  219217. }
  219218. void* getNativeHandle() const
  219219. {
  219220. return (void*) windowH;
  219221. }
  219222. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  219223. {
  219224. XPointer peer = 0;
  219225. ScopedXLock xlock;
  219226. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  219227. {
  219228. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  219229. peer = 0;
  219230. }
  219231. return (LinuxComponentPeer*) peer;
  219232. }
  219233. void setVisible (bool shouldBeVisible)
  219234. {
  219235. ScopedXLock xlock;
  219236. if (shouldBeVisible)
  219237. XMapWindow (display, windowH);
  219238. else
  219239. XUnmapWindow (display, windowH);
  219240. }
  219241. void setTitle (const String& title)
  219242. {
  219243. XTextProperty nameProperty;
  219244. char* strings[] = { const_cast <char*> (title.toUTF8().getAddress()) };
  219245. ScopedXLock xlock;
  219246. if (XStringListToTextProperty (strings, 1, &nameProperty))
  219247. {
  219248. XSetWMName (display, windowH, &nameProperty);
  219249. XSetWMIconName (display, windowH, &nameProperty);
  219250. XFree (nameProperty.value);
  219251. }
  219252. }
  219253. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  219254. {
  219255. fullScreen = isNowFullScreen;
  219256. if (windowH != 0)
  219257. {
  219258. WeakReference<Component> deletionChecker (component);
  219259. wx = x;
  219260. wy = y;
  219261. ww = jmax (1, w);
  219262. wh = jmax (1, h);
  219263. ScopedXLock xlock;
  219264. // Make sure the Window manager does what we want
  219265. XSizeHints* hints = XAllocSizeHints();
  219266. hints->flags = USSize | USPosition;
  219267. hints->width = ww;
  219268. hints->height = wh;
  219269. hints->x = wx;
  219270. hints->y = wy;
  219271. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  219272. {
  219273. hints->min_width = hints->max_width = hints->width;
  219274. hints->min_height = hints->max_height = hints->height;
  219275. hints->flags |= PMinSize | PMaxSize;
  219276. }
  219277. XSetWMNormalHints (display, windowH, hints);
  219278. XFree (hints);
  219279. XMoveResizeWindow (display, windowH,
  219280. wx - windowBorder.getLeft(),
  219281. wy - windowBorder.getTop(), ww, wh);
  219282. if (deletionChecker != 0)
  219283. {
  219284. updateBorderSize();
  219285. handleMovedOrResized();
  219286. }
  219287. }
  219288. }
  219289. void setPosition (int x, int y) { setBounds (x, y, ww, wh, false); }
  219290. void setSize (int w, int h) { setBounds (wx, wy, w, h, false); }
  219291. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  219292. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  219293. const Point<int> localToGlobal (const Point<int>& relativePosition)
  219294. {
  219295. return relativePosition + getScreenPosition();
  219296. }
  219297. const Point<int> globalToLocal (const Point<int>& screenPosition)
  219298. {
  219299. return screenPosition - getScreenPosition();
  219300. }
  219301. void setAlpha (float newAlpha)
  219302. {
  219303. //xxx todo!
  219304. }
  219305. void setMinimised (bool shouldBeMinimised)
  219306. {
  219307. if (shouldBeMinimised)
  219308. {
  219309. Window root = RootWindow (display, DefaultScreen (display));
  219310. XClientMessageEvent clientMsg;
  219311. clientMsg.display = display;
  219312. clientMsg.window = windowH;
  219313. clientMsg.type = ClientMessage;
  219314. clientMsg.format = 32;
  219315. clientMsg.message_type = Atoms::ChangeState;
  219316. clientMsg.data.l[0] = IconicState;
  219317. ScopedXLock xlock;
  219318. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  219319. }
  219320. else
  219321. {
  219322. setVisible (true);
  219323. }
  219324. }
  219325. bool isMinimised() const
  219326. {
  219327. bool minimised = false;
  219328. unsigned char* stateProp;
  219329. unsigned long nitems, bytesLeft;
  219330. Atom actualType;
  219331. int actualFormat;
  219332. ScopedXLock xlock;
  219333. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  219334. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  219335. &stateProp) == Success
  219336. && actualType == Atoms::State
  219337. && actualFormat == 32
  219338. && nitems > 0)
  219339. {
  219340. if (((unsigned long*) stateProp)[0] == IconicState)
  219341. minimised = true;
  219342. XFree (stateProp);
  219343. }
  219344. return minimised;
  219345. }
  219346. void setFullScreen (const bool shouldBeFullScreen)
  219347. {
  219348. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  219349. setMinimised (false);
  219350. if (fullScreen != shouldBeFullScreen)
  219351. {
  219352. if (shouldBeFullScreen)
  219353. r = Desktop::getInstance().getMainMonitorArea();
  219354. if (! r.isEmpty())
  219355. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219356. getComponent()->repaint();
  219357. }
  219358. }
  219359. bool isFullScreen() const
  219360. {
  219361. return fullScreen;
  219362. }
  219363. bool isChildWindowOf (Window possibleParent) const
  219364. {
  219365. Window* windowList = 0;
  219366. uint32 windowListSize = 0;
  219367. Window parent, root;
  219368. ScopedXLock xlock;
  219369. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  219370. {
  219371. if (windowList != 0)
  219372. XFree (windowList);
  219373. return parent == possibleParent;
  219374. }
  219375. return false;
  219376. }
  219377. bool isFrontWindow() const
  219378. {
  219379. Window* windowList = 0;
  219380. uint32 windowListSize = 0;
  219381. bool result = false;
  219382. ScopedXLock xlock;
  219383. Window parent, root = RootWindow (display, DefaultScreen (display));
  219384. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  219385. {
  219386. for (int i = windowListSize; --i >= 0;)
  219387. {
  219388. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  219389. if (peer != 0)
  219390. {
  219391. result = (peer == this);
  219392. break;
  219393. }
  219394. }
  219395. }
  219396. if (windowList != 0)
  219397. XFree (windowList);
  219398. return result;
  219399. }
  219400. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  219401. {
  219402. if (! (isPositiveAndBelow (position.getX(), ww) && isPositiveAndBelow (position.getY(), wh)))
  219403. return false;
  219404. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  219405. {
  219406. Component* const c = Desktop::getInstance().getComponent (i);
  219407. if (c == getComponent())
  219408. break;
  219409. if (c->contains (position + Point<int> (wx, wy) - c->getScreenPosition()))
  219410. return false;
  219411. }
  219412. if (trueIfInAChildWindow)
  219413. return true;
  219414. ::Window root, child;
  219415. unsigned int bw, depth;
  219416. int wx, wy, w, h;
  219417. ScopedXLock xlock;
  219418. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  219419. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  219420. &bw, &depth))
  219421. {
  219422. return false;
  219423. }
  219424. if (! XTranslateCoordinates (display, windowH, windowH, position.getX(), position.getY(), &wx, &wy, &child))
  219425. return false;
  219426. return child == None;
  219427. }
  219428. const BorderSize<int> getFrameSize() const
  219429. {
  219430. return BorderSize<int>();
  219431. }
  219432. bool setAlwaysOnTop (bool alwaysOnTop)
  219433. {
  219434. return false;
  219435. }
  219436. void toFront (bool makeActive)
  219437. {
  219438. if (makeActive)
  219439. {
  219440. setVisible (true);
  219441. grabFocus();
  219442. }
  219443. XEvent ev;
  219444. ev.xclient.type = ClientMessage;
  219445. ev.xclient.serial = 0;
  219446. ev.xclient.send_event = True;
  219447. ev.xclient.message_type = Atoms::ActiveWin;
  219448. ev.xclient.window = windowH;
  219449. ev.xclient.format = 32;
  219450. ev.xclient.data.l[0] = 2;
  219451. ev.xclient.data.l[1] = CurrentTime;
  219452. ev.xclient.data.l[2] = 0;
  219453. ev.xclient.data.l[3] = 0;
  219454. ev.xclient.data.l[4] = 0;
  219455. {
  219456. ScopedXLock xlock;
  219457. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  219458. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  219459. XWindowAttributes attr;
  219460. XGetWindowAttributes (display, windowH, &attr);
  219461. if (component->isAlwaysOnTop())
  219462. XRaiseWindow (display, windowH);
  219463. XSync (display, False);
  219464. }
  219465. handleBroughtToFront();
  219466. }
  219467. void toBehind (ComponentPeer* other)
  219468. {
  219469. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  219470. jassert (otherPeer != 0); // wrong type of window?
  219471. if (otherPeer != 0)
  219472. {
  219473. setMinimised (false);
  219474. Window newStack[] = { otherPeer->windowH, windowH };
  219475. ScopedXLock xlock;
  219476. XRestackWindows (display, newStack, 2);
  219477. }
  219478. }
  219479. bool isFocused() const
  219480. {
  219481. int revert = 0;
  219482. Window focusedWindow = 0;
  219483. ScopedXLock xlock;
  219484. XGetInputFocus (display, &focusedWindow, &revert);
  219485. return focusedWindow == windowH;
  219486. }
  219487. void grabFocus()
  219488. {
  219489. XWindowAttributes atts;
  219490. ScopedXLock xlock;
  219491. if (windowH != 0
  219492. && XGetWindowAttributes (display, windowH, &atts)
  219493. && atts.map_state == IsViewable
  219494. && ! isFocused())
  219495. {
  219496. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  219497. isActiveApplication = true;
  219498. }
  219499. }
  219500. void textInputRequired (const Point<int>&)
  219501. {
  219502. }
  219503. void repaint (const Rectangle<int>& area)
  219504. {
  219505. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  219506. }
  219507. void performAnyPendingRepaintsNow()
  219508. {
  219509. repainter->performAnyPendingRepaintsNow();
  219510. }
  219511. void setIcon (const Image& newIcon)
  219512. {
  219513. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  219514. HeapBlock <unsigned long> data (dataSize);
  219515. int index = 0;
  219516. data[index++] = newIcon.getWidth();
  219517. data[index++] = newIcon.getHeight();
  219518. for (int y = 0; y < newIcon.getHeight(); ++y)
  219519. for (int x = 0; x < newIcon.getWidth(); ++x)
  219520. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  219521. ScopedXLock xlock;
  219522. XChangeProperty (display, windowH,
  219523. XInternAtom (display, "_NET_WM_ICON", False),
  219524. XA_CARDINAL, 32, PropModeReplace,
  219525. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  219526. deleteIconPixmaps();
  219527. XWMHints* wmHints = XGetWMHints (display, windowH);
  219528. if (wmHints == 0)
  219529. wmHints = XAllocWMHints();
  219530. wmHints->flags |= IconPixmapHint | IconMaskHint;
  219531. wmHints->icon_pixmap = PixmapHelpers::createColourPixmapFromImage (display, newIcon);
  219532. wmHints->icon_mask = PixmapHelpers::createMaskPixmapFromImage (display, newIcon);
  219533. XSetWMHints (display, windowH, wmHints);
  219534. XFree (wmHints);
  219535. XSync (display, False);
  219536. }
  219537. void deleteIconPixmaps()
  219538. {
  219539. ScopedXLock xlock;
  219540. XWMHints* wmHints = XGetWMHints (display, windowH);
  219541. if (wmHints != 0)
  219542. {
  219543. if ((wmHints->flags & IconPixmapHint) != 0)
  219544. {
  219545. wmHints->flags &= ~IconPixmapHint;
  219546. XFreePixmap (display, wmHints->icon_pixmap);
  219547. }
  219548. if ((wmHints->flags & IconMaskHint) != 0)
  219549. {
  219550. wmHints->flags &= ~IconMaskHint;
  219551. XFreePixmap (display, wmHints->icon_mask);
  219552. }
  219553. XSetWMHints (display, windowH, wmHints);
  219554. XFree (wmHints);
  219555. }
  219556. }
  219557. void handleWindowMessage (XEvent* event)
  219558. {
  219559. switch (event->xany.type)
  219560. {
  219561. case 2: /* KeyPress */ handleKeyPressEvent ((XKeyEvent*) &event->xkey); break;
  219562. case KeyRelease: handleKeyReleaseEvent ((const XKeyEvent*) &event->xkey); break;
  219563. case ButtonPress: handleButtonPressEvent ((const XButtonPressedEvent*) &event->xbutton); break;
  219564. case ButtonRelease: handleButtonReleaseEvent ((const XButtonReleasedEvent*) &event->xbutton); break;
  219565. case MotionNotify: handleMotionNotifyEvent ((const XPointerMovedEvent*) &event->xmotion); break;
  219566. case EnterNotify: handleEnterNotifyEvent ((const XEnterWindowEvent*) &event->xcrossing); break;
  219567. case LeaveNotify: handleLeaveNotifyEvent ((const XLeaveWindowEvent*) &event->xcrossing); break;
  219568. case FocusIn: handleFocusInEvent(); break;
  219569. case FocusOut: handleFocusOutEvent(); break;
  219570. case Expose: handleExposeEvent ((XExposeEvent*) &event->xexpose); break;
  219571. case MappingNotify: handleMappingNotify ((XMappingEvent*) &event->xmapping); break;
  219572. case ClientMessage: handleClientMessageEvent ((XClientMessageEvent*) &event->xclient, event); break;
  219573. case SelectionNotify: handleDragAndDropSelection (event); break;
  219574. case ConfigureNotify: handleConfigureNotifyEvent ((XConfigureEvent*) &event->xconfigure); break;
  219575. case ReparentNotify: handleReparentNotifyEvent(); break;
  219576. case GravityNotify: handleGravityNotify(); break;
  219577. case CirculateNotify:
  219578. case CreateNotify:
  219579. case DestroyNotify:
  219580. // Think we can ignore these
  219581. break;
  219582. case MapNotify:
  219583. mapped = true;
  219584. handleBroughtToFront();
  219585. break;
  219586. case UnmapNotify:
  219587. mapped = false;
  219588. break;
  219589. case SelectionClear:
  219590. case SelectionRequest:
  219591. break;
  219592. default:
  219593. #if JUCE_USE_XSHM
  219594. {
  219595. ScopedXLock xlock;
  219596. if (event->xany.type == XShmGetEventBase (display))
  219597. repainter->notifyPaintCompleted();
  219598. }
  219599. #endif
  219600. break;
  219601. }
  219602. }
  219603. void handleKeyPressEvent (XKeyEvent* const keyEvent)
  219604. {
  219605. char utf8 [64] = { 0 };
  219606. juce_wchar unicodeChar = 0;
  219607. int keyCode = 0;
  219608. bool keyDownChange = false;
  219609. KeySym sym;
  219610. {
  219611. ScopedXLock xlock;
  219612. updateKeyStates (keyEvent->keycode, true);
  219613. const char* oldLocale = ::setlocale (LC_ALL, 0);
  219614. ::setlocale (LC_ALL, "");
  219615. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  219616. ::setlocale (LC_ALL, oldLocale);
  219617. unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  219618. keyCode = (int) unicodeChar;
  219619. if (keyCode < 0x20)
  219620. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  219621. keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  219622. }
  219623. const ModifierKeys oldMods (currentModifiers);
  219624. bool keyPressed = false;
  219625. if ((sym & 0xff00) == 0xff00)
  219626. {
  219627. switch (sym) // Translate keypad
  219628. {
  219629. case XK_KP_Divide: keyCode = XK_slash; break;
  219630. case XK_KP_Multiply: keyCode = XK_asterisk; break;
  219631. case XK_KP_Subtract: keyCode = XK_hyphen; break;
  219632. case XK_KP_Add: keyCode = XK_plus; break;
  219633. case XK_KP_Enter: keyCode = XK_Return; break;
  219634. case XK_KP_Decimal: keyCode = Keys::numLock ? XK_period : XK_Delete; break;
  219635. case XK_KP_0: keyCode = Keys::numLock ? XK_0 : XK_Insert; break;
  219636. case XK_KP_1: keyCode = Keys::numLock ? XK_1 : XK_End; break;
  219637. case XK_KP_2: keyCode = Keys::numLock ? XK_2 : XK_Down; break;
  219638. case XK_KP_3: keyCode = Keys::numLock ? XK_3 : XK_Page_Down; break;
  219639. case XK_KP_4: keyCode = Keys::numLock ? XK_4 : XK_Left; break;
  219640. case XK_KP_5: keyCode = XK_5; break;
  219641. case XK_KP_6: keyCode = Keys::numLock ? XK_6 : XK_Right; break;
  219642. case XK_KP_7: keyCode = Keys::numLock ? XK_7 : XK_Home; break;
  219643. case XK_KP_8: keyCode = Keys::numLock ? XK_8 : XK_Up; break;
  219644. case XK_KP_9: keyCode = Keys::numLock ? XK_9 : XK_Page_Up; break;
  219645. default: break;
  219646. }
  219647. switch (sym)
  219648. {
  219649. case XK_Left:
  219650. case XK_Right:
  219651. case XK_Up:
  219652. case XK_Down:
  219653. case XK_Page_Up:
  219654. case XK_Page_Down:
  219655. case XK_End:
  219656. case XK_Home:
  219657. case XK_Delete:
  219658. case XK_Insert:
  219659. keyPressed = true;
  219660. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219661. break;
  219662. case XK_Tab:
  219663. case XK_Return:
  219664. case XK_Escape:
  219665. case XK_BackSpace:
  219666. keyPressed = true;
  219667. keyCode &= 0xff;
  219668. break;
  219669. default:
  219670. if (sym >= XK_F1 && sym <= XK_F16)
  219671. {
  219672. keyPressed = true;
  219673. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  219674. }
  219675. break;
  219676. }
  219677. }
  219678. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  219679. keyPressed = true;
  219680. if (oldMods != currentModifiers)
  219681. handleModifierKeysChange();
  219682. if (keyDownChange)
  219683. handleKeyUpOrDown (true);
  219684. if (keyPressed)
  219685. handleKeyPress (keyCode, unicodeChar);
  219686. }
  219687. void handleKeyReleaseEvent (const XKeyEvent* const keyEvent)
  219688. {
  219689. updateKeyStates (keyEvent->keycode, false);
  219690. KeySym sym;
  219691. {
  219692. ScopedXLock xlock;
  219693. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  219694. }
  219695. const ModifierKeys oldMods (currentModifiers);
  219696. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  219697. if (oldMods != currentModifiers)
  219698. handleModifierKeysChange();
  219699. if (keyDownChange)
  219700. handleKeyUpOrDown (false);
  219701. }
  219702. void handleButtonPressEvent (const XButtonPressedEvent* const buttonPressEvent)
  219703. {
  219704. updateKeyModifiers (buttonPressEvent->state);
  219705. bool buttonMsg = false;
  219706. const int map = pointerMap [buttonPressEvent->button - Button1];
  219707. if (map == Keys::WheelUp || map == Keys::WheelDown)
  219708. {
  219709. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  219710. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  219711. }
  219712. if (map == Keys::LeftButton)
  219713. {
  219714. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  219715. buttonMsg = true;
  219716. }
  219717. else if (map == Keys::RightButton)
  219718. {
  219719. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  219720. buttonMsg = true;
  219721. }
  219722. else if (map == Keys::MiddleButton)
  219723. {
  219724. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  219725. buttonMsg = true;
  219726. }
  219727. if (buttonMsg)
  219728. {
  219729. toFront (true);
  219730. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  219731. getEventTime (buttonPressEvent->time));
  219732. }
  219733. clearLastMousePos();
  219734. }
  219735. void handleButtonReleaseEvent (const XButtonReleasedEvent* const buttonRelEvent)
  219736. {
  219737. updateKeyModifiers (buttonRelEvent->state);
  219738. const int map = pointerMap [buttonRelEvent->button - Button1];
  219739. if (map == Keys::LeftButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  219740. else if (map == Keys::RightButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  219741. else if (map == Keys::MiddleButton) currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  219742. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  219743. getEventTime (buttonRelEvent->time));
  219744. clearLastMousePos();
  219745. }
  219746. void handleMotionNotifyEvent (const XPointerMovedEvent* const movedEvent)
  219747. {
  219748. updateKeyModifiers (movedEvent->state);
  219749. const Point<int> mousePos (movedEvent->x_root, movedEvent->y_root);
  219750. if (lastMousePos != mousePos)
  219751. {
  219752. lastMousePos = mousePos;
  219753. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  219754. {
  219755. Window wRoot = 0, wParent = 0;
  219756. {
  219757. ScopedXLock xlock;
  219758. unsigned int numChildren;
  219759. Window* wChild = 0;
  219760. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  219761. }
  219762. if (wParent != 0
  219763. && wParent != windowH
  219764. && wParent != wRoot)
  219765. {
  219766. parentWindow = wParent;
  219767. updateBounds();
  219768. }
  219769. else
  219770. {
  219771. parentWindow = 0;
  219772. }
  219773. }
  219774. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  219775. }
  219776. }
  219777. void handleEnterNotifyEvent (const XEnterWindowEvent* const enterEvent)
  219778. {
  219779. clearLastMousePos();
  219780. if (! currentModifiers.isAnyMouseButtonDown())
  219781. {
  219782. updateKeyModifiers (enterEvent->state);
  219783. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  219784. }
  219785. }
  219786. void handleLeaveNotifyEvent (const XLeaveWindowEvent* const leaveEvent)
  219787. {
  219788. // Suppress the normal leave if we've got a pointer grab, or if
  219789. // it's a bogus one caused by clicking a mouse button when running
  219790. // in a Window manager
  219791. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  219792. || leaveEvent->mode == NotifyUngrab)
  219793. {
  219794. updateKeyModifiers (leaveEvent->state);
  219795. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  219796. }
  219797. }
  219798. void handleFocusInEvent()
  219799. {
  219800. isActiveApplication = true;
  219801. if (isFocused())
  219802. handleFocusGain();
  219803. }
  219804. void handleFocusOutEvent()
  219805. {
  219806. isActiveApplication = false;
  219807. if (! isFocused())
  219808. handleFocusLoss();
  219809. }
  219810. void handleExposeEvent (XExposeEvent* exposeEvent)
  219811. {
  219812. // Batch together all pending expose events
  219813. XEvent nextEvent;
  219814. ScopedXLock xlock;
  219815. if (exposeEvent->window != windowH)
  219816. {
  219817. Window child;
  219818. XTranslateCoordinates (display, exposeEvent->window, windowH,
  219819. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  219820. &child);
  219821. }
  219822. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  219823. exposeEvent->width, exposeEvent->height));
  219824. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  219825. {
  219826. XPeekEvent (display, (XEvent*) &nextEvent);
  219827. if (nextEvent.type != Expose || nextEvent.xany.window != exposeEvent->window)
  219828. break;
  219829. XNextEvent (display, (XEvent*) &nextEvent);
  219830. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  219831. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  219832. nextExposeEvent->width, nextExposeEvent->height));
  219833. }
  219834. }
  219835. void handleConfigureNotifyEvent (XConfigureEvent* const confEvent)
  219836. {
  219837. updateBounds();
  219838. updateBorderSize();
  219839. handleMovedOrResized();
  219840. // if the native title bar is dragged, need to tell any active menus, etc.
  219841. if ((styleFlags & windowHasTitleBar) != 0
  219842. && component->isCurrentlyBlockedByAnotherModalComponent())
  219843. {
  219844. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  219845. if (currentModalComp != 0)
  219846. currentModalComp->inputAttemptWhenModal();
  219847. }
  219848. if (confEvent->window == windowH
  219849. && confEvent->above != 0
  219850. && isFrontWindow())
  219851. {
  219852. handleBroughtToFront();
  219853. }
  219854. }
  219855. void handleReparentNotifyEvent()
  219856. {
  219857. parentWindow = 0;
  219858. Window wRoot = 0;
  219859. Window* wChild = 0;
  219860. unsigned int numChildren;
  219861. {
  219862. ScopedXLock xlock;
  219863. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  219864. }
  219865. if (parentWindow == windowH || parentWindow == wRoot)
  219866. parentWindow = 0;
  219867. handleGravityNotify();
  219868. }
  219869. void handleGravityNotify()
  219870. {
  219871. updateBounds();
  219872. updateBorderSize();
  219873. handleMovedOrResized();
  219874. }
  219875. void handleMappingNotify (XMappingEvent* const mappingEvent)
  219876. {
  219877. if (mappingEvent->request != MappingPointer)
  219878. {
  219879. // Deal with modifier/keyboard mapping
  219880. ScopedXLock xlock;
  219881. XRefreshKeyboardMapping (mappingEvent);
  219882. updateModifierMappings();
  219883. }
  219884. }
  219885. void handleClientMessageEvent (XClientMessageEvent* const clientMsg, XEvent* event)
  219886. {
  219887. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  219888. {
  219889. const Atom atom = (Atom) clientMsg->data.l[0];
  219890. if (atom == Atoms::ProtocolList [Atoms::PING])
  219891. {
  219892. Window root = RootWindow (display, DefaultScreen (display));
  219893. clientMsg->window = root;
  219894. XSendEvent (display, root, False, NoEventMask, event);
  219895. XFlush (display);
  219896. }
  219897. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  219898. {
  219899. XWindowAttributes atts;
  219900. ScopedXLock xlock;
  219901. if (clientMsg->window != 0
  219902. && XGetWindowAttributes (display, clientMsg->window, &atts))
  219903. {
  219904. if (atts.map_state == IsViewable)
  219905. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  219906. }
  219907. }
  219908. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  219909. {
  219910. handleUserClosingWindow();
  219911. }
  219912. }
  219913. else if (clientMsg->message_type == Atoms::XdndEnter)
  219914. {
  219915. handleDragAndDropEnter (clientMsg);
  219916. }
  219917. else if (clientMsg->message_type == Atoms::XdndLeave)
  219918. {
  219919. resetDragAndDrop();
  219920. }
  219921. else if (clientMsg->message_type == Atoms::XdndPosition)
  219922. {
  219923. handleDragAndDropPosition (clientMsg);
  219924. }
  219925. else if (clientMsg->message_type == Atoms::XdndDrop)
  219926. {
  219927. handleDragAndDropDrop (clientMsg);
  219928. }
  219929. else if (clientMsg->message_type == Atoms::XdndStatus)
  219930. {
  219931. handleDragAndDropStatus (clientMsg);
  219932. }
  219933. else if (clientMsg->message_type == Atoms::XdndFinished)
  219934. {
  219935. resetDragAndDrop();
  219936. }
  219937. }
  219938. void showMouseCursor (Cursor cursor) throw()
  219939. {
  219940. ScopedXLock xlock;
  219941. XDefineCursor (display, windowH, cursor);
  219942. }
  219943. void setTaskBarIcon (const Image& image)
  219944. {
  219945. ScopedXLock xlock;
  219946. taskbarImage = image;
  219947. Screen* const screen = XDefaultScreenOfDisplay (display);
  219948. const int screenNumber = XScreenNumberOfScreen (screen);
  219949. String screenAtom ("_NET_SYSTEM_TRAY_S");
  219950. screenAtom << screenNumber;
  219951. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  219952. XGrabServer (display);
  219953. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  219954. if (managerWin != None)
  219955. XSelectInput (display, managerWin, StructureNotifyMask);
  219956. XUngrabServer (display);
  219957. XFlush (display);
  219958. if (managerWin != None)
  219959. {
  219960. XEvent ev;
  219961. zerostruct (ev);
  219962. ev.xclient.type = ClientMessage;
  219963. ev.xclient.window = managerWin;
  219964. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  219965. ev.xclient.format = 32;
  219966. ev.xclient.data.l[0] = CurrentTime;
  219967. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  219968. ev.xclient.data.l[2] = windowH;
  219969. ev.xclient.data.l[3] = 0;
  219970. ev.xclient.data.l[4] = 0;
  219971. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  219972. XSync (display, False);
  219973. }
  219974. // For older KDE's ...
  219975. long atomData = 1;
  219976. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  219977. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  219978. // For more recent KDE's...
  219979. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  219980. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  219981. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  219982. XSizeHints* hints = XAllocSizeHints();
  219983. hints->flags = PMinSize;
  219984. hints->min_width = 22;
  219985. hints->min_height = 22;
  219986. XSetWMNormalHints (display, windowH, hints);
  219987. XFree (hints);
  219988. }
  219989. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  219990. bool dontRepaint;
  219991. static ModifierKeys currentModifiers;
  219992. static bool isActiveApplication;
  219993. private:
  219994. class LinuxRepaintManager : public Timer
  219995. {
  219996. public:
  219997. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  219998. : peer (peer_),
  219999. lastTimeImageUsed (0)
  220000. {
  220001. #if JUCE_USE_XSHM
  220002. shmCompletedDrawing = true;
  220003. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220004. if (useARGBImagesForRendering)
  220005. {
  220006. ScopedXLock xlock;
  220007. XShmSegmentInfo segmentinfo;
  220008. XImage* const testImage
  220009. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220010. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  220011. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  220012. XDestroyImage (testImage);
  220013. }
  220014. #endif
  220015. }
  220016. void timerCallback()
  220017. {
  220018. #if JUCE_USE_XSHM
  220019. if (! shmCompletedDrawing)
  220020. return;
  220021. #endif
  220022. if (! regionsNeedingRepaint.isEmpty())
  220023. {
  220024. stopTimer();
  220025. performAnyPendingRepaintsNow();
  220026. }
  220027. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  220028. {
  220029. stopTimer();
  220030. image = Image::null;
  220031. }
  220032. }
  220033. void repaint (const Rectangle<int>& area)
  220034. {
  220035. if (! isTimerRunning())
  220036. startTimer (repaintTimerPeriod);
  220037. regionsNeedingRepaint.add (area);
  220038. }
  220039. void performAnyPendingRepaintsNow()
  220040. {
  220041. #if JUCE_USE_XSHM
  220042. if (! shmCompletedDrawing)
  220043. {
  220044. startTimer (repaintTimerPeriod);
  220045. return;
  220046. }
  220047. #endif
  220048. peer->clearMaskedRegion();
  220049. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  220050. regionsNeedingRepaint.clear();
  220051. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  220052. if (! totalArea.isEmpty())
  220053. {
  220054. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  220055. || image.getHeight() < totalArea.getHeight())
  220056. {
  220057. #if JUCE_USE_XSHM
  220058. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  220059. : Image::RGB,
  220060. #else
  220061. image = Image (new XBitmapImage (Image::RGB,
  220062. #endif
  220063. (totalArea.getWidth() + 31) & ~31,
  220064. (totalArea.getHeight() + 31) & ~31,
  220065. false, peer->depth, peer->visual));
  220066. }
  220067. startTimer (repaintTimerPeriod);
  220068. RectangleList adjustedList (originalRepaintRegion);
  220069. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  220070. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  220071. if (peer->depth == 32)
  220072. {
  220073. RectangleList::Iterator i (originalRepaintRegion);
  220074. while (i.next())
  220075. image.clear (*i.getRectangle() - totalArea.getPosition());
  220076. }
  220077. peer->handlePaint (context);
  220078. if (! peer->maskedRegion.isEmpty())
  220079. originalRepaintRegion.subtract (peer->maskedRegion);
  220080. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  220081. {
  220082. #if JUCE_USE_XSHM
  220083. shmCompletedDrawing = false;
  220084. #endif
  220085. const Rectangle<int>& r = *i.getRectangle();
  220086. static_cast<XBitmapImage*> (image.getSharedImage())
  220087. ->blitToWindow (peer->windowH,
  220088. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  220089. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  220090. }
  220091. }
  220092. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  220093. startTimer (repaintTimerPeriod);
  220094. }
  220095. #if JUCE_USE_XSHM
  220096. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  220097. #endif
  220098. private:
  220099. enum { repaintTimerPeriod = 1000 / 100 };
  220100. LinuxComponentPeer* const peer;
  220101. Image image;
  220102. uint32 lastTimeImageUsed;
  220103. RectangleList regionsNeedingRepaint;
  220104. #if JUCE_USE_XSHM
  220105. bool useARGBImagesForRendering, shmCompletedDrawing;
  220106. #endif
  220107. JUCE_DECLARE_NON_COPYABLE (LinuxRepaintManager);
  220108. };
  220109. ScopedPointer <LinuxRepaintManager> repainter;
  220110. friend class LinuxRepaintManager;
  220111. Window windowH, parentWindow;
  220112. int wx, wy, ww, wh;
  220113. Image taskbarImage;
  220114. bool fullScreen, mapped;
  220115. Visual* visual;
  220116. int depth;
  220117. BorderSize<int> windowBorder;
  220118. struct MotifWmHints
  220119. {
  220120. unsigned long flags;
  220121. unsigned long functions;
  220122. unsigned long decorations;
  220123. long input_mode;
  220124. unsigned long status;
  220125. };
  220126. static void updateKeyStates (const int keycode, const bool press) throw()
  220127. {
  220128. const int keybyte = keycode >> 3;
  220129. const int keybit = (1 << (keycode & 7));
  220130. if (press)
  220131. Keys::keyStates [keybyte] |= keybit;
  220132. else
  220133. Keys::keyStates [keybyte] &= ~keybit;
  220134. }
  220135. static void updateKeyModifiers (const int status) throw()
  220136. {
  220137. int keyMods = 0;
  220138. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  220139. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  220140. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  220141. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  220142. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  220143. Keys::capsLock = ((status & LockMask) != 0);
  220144. }
  220145. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220146. {
  220147. int modifier = 0;
  220148. bool isModifier = true;
  220149. switch (sym)
  220150. {
  220151. case XK_Shift_L:
  220152. case XK_Shift_R:
  220153. modifier = ModifierKeys::shiftModifier;
  220154. break;
  220155. case XK_Control_L:
  220156. case XK_Control_R:
  220157. modifier = ModifierKeys::ctrlModifier;
  220158. break;
  220159. case XK_Alt_L:
  220160. case XK_Alt_R:
  220161. modifier = ModifierKeys::altModifier;
  220162. break;
  220163. case XK_Num_Lock:
  220164. if (press)
  220165. Keys::numLock = ! Keys::numLock;
  220166. break;
  220167. case XK_Caps_Lock:
  220168. if (press)
  220169. Keys::capsLock = ! Keys::capsLock;
  220170. break;
  220171. case XK_Scroll_Lock:
  220172. break;
  220173. default:
  220174. isModifier = false;
  220175. break;
  220176. }
  220177. if (modifier != 0)
  220178. {
  220179. if (press)
  220180. currentModifiers = currentModifiers.withFlags (modifier);
  220181. else
  220182. currentModifiers = currentModifiers.withoutFlags (modifier);
  220183. }
  220184. return isModifier;
  220185. }
  220186. // Alt and Num lock are not defined by standard X
  220187. // modifier constants: check what they're mapped to
  220188. static void updateModifierMappings() throw()
  220189. {
  220190. ScopedXLock xlock;
  220191. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220192. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220193. Keys::AltMask = 0;
  220194. Keys::NumLockMask = 0;
  220195. XModifierKeymap* mapping = XGetModifierMapping (display);
  220196. if (mapping)
  220197. {
  220198. for (int i = 0; i < 8; i++)
  220199. {
  220200. if (mapping->modifiermap [i << 1] == altLeftCode)
  220201. Keys::AltMask = 1 << i;
  220202. else if (mapping->modifiermap [i << 1] == numLockCode)
  220203. Keys::NumLockMask = 1 << i;
  220204. }
  220205. XFreeModifiermap (mapping);
  220206. }
  220207. }
  220208. void removeWindowDecorations (Window wndH)
  220209. {
  220210. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220211. if (hints != None)
  220212. {
  220213. MotifWmHints motifHints;
  220214. zerostruct (motifHints);
  220215. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  220216. motifHints.decorations = 0;
  220217. ScopedXLock xlock;
  220218. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220219. (unsigned char*) &motifHints, 4);
  220220. }
  220221. hints = XInternAtom (display, "_WIN_HINTS", True);
  220222. if (hints != None)
  220223. {
  220224. long gnomeHints = 0;
  220225. ScopedXLock xlock;
  220226. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220227. (unsigned char*) &gnomeHints, 1);
  220228. }
  220229. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  220230. if (hints != None)
  220231. {
  220232. long kwmHints = 2; /*KDE_tinyDecoration*/
  220233. ScopedXLock xlock;
  220234. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  220235. (unsigned char*) &kwmHints, 1);
  220236. }
  220237. }
  220238. void addWindowButtons (Window wndH)
  220239. {
  220240. ScopedXLock xlock;
  220241. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  220242. if (hints != None)
  220243. {
  220244. MotifWmHints motifHints;
  220245. zerostruct (motifHints);
  220246. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  220247. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  220248. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  220249. if ((styleFlags & windowHasCloseButton) != 0)
  220250. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  220251. if ((styleFlags & windowHasMinimiseButton) != 0)
  220252. {
  220253. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  220254. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  220255. }
  220256. if ((styleFlags & windowHasMaximiseButton) != 0)
  220257. {
  220258. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  220259. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  220260. }
  220261. if ((styleFlags & windowIsResizable) != 0)
  220262. {
  220263. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  220264. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  220265. }
  220266. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  220267. }
  220268. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  220269. if (hints != None)
  220270. {
  220271. int netHints [6];
  220272. int num = 0;
  220273. if ((styleFlags & windowIsResizable) != 0)
  220274. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  220275. if ((styleFlags & windowHasMaximiseButton) != 0)
  220276. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  220277. if ((styleFlags & windowHasMinimiseButton) != 0)
  220278. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  220279. if ((styleFlags & windowHasCloseButton) != 0)
  220280. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  220281. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  220282. }
  220283. }
  220284. void setWindowType()
  220285. {
  220286. int netHints [2];
  220287. int numHints = 0;
  220288. if ((styleFlags & windowIsTemporary) != 0
  220289. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  220290. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  220291. else
  220292. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  220293. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  220294. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  220295. (unsigned char*) &netHints, numHints);
  220296. numHints = 0;
  220297. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  220298. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  220299. if (component->isAlwaysOnTop())
  220300. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  220301. if (numHints > 0)
  220302. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  220303. (unsigned char*) &netHints, numHints);
  220304. }
  220305. void createWindow()
  220306. {
  220307. ScopedXLock xlock;
  220308. Atoms::initialiseAtoms();
  220309. resetDragAndDrop();
  220310. // Get defaults for various properties
  220311. const int screen = DefaultScreen (display);
  220312. Window root = RootWindow (display, screen);
  220313. // Try to obtain a 32-bit visual or fallback to 24 or 16
  220314. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  220315. if (visual == 0)
  220316. {
  220317. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  220318. Process::terminate();
  220319. }
  220320. // Create and install a colormap suitable fr our visual
  220321. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  220322. XInstallColormap (display, colormap);
  220323. // Set up the window attributes
  220324. XSetWindowAttributes swa;
  220325. swa.border_pixel = 0;
  220326. swa.background_pixmap = None;
  220327. swa.colormap = colormap;
  220328. swa.event_mask = getAllEventsMask();
  220329. windowH = XCreateWindow (display, root,
  220330. 0, 0, 1, 1,
  220331. 0, depth, InputOutput, visual,
  220332. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  220333. &swa);
  220334. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  220335. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  220336. GrabModeAsync, GrabModeAsync, None, None);
  220337. // Set the window context to identify the window handle object
  220338. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  220339. {
  220340. // Failed
  220341. jassertfalse;
  220342. Logger::outputDebugString ("Failed to create context information for window.\n");
  220343. XDestroyWindow (display, windowH);
  220344. windowH = 0;
  220345. return;
  220346. }
  220347. // Set window manager hints
  220348. XWMHints* wmHints = XAllocWMHints();
  220349. wmHints->flags = InputHint | StateHint;
  220350. wmHints->input = True; // Locally active input model
  220351. wmHints->initial_state = NormalState;
  220352. XSetWMHints (display, windowH, wmHints);
  220353. XFree (wmHints);
  220354. // Set the window type
  220355. setWindowType();
  220356. // Define decoration
  220357. if ((styleFlags & windowHasTitleBar) == 0)
  220358. removeWindowDecorations (windowH);
  220359. else
  220360. addWindowButtons (windowH);
  220361. setTitle (getComponent()->getName());
  220362. // Associate the PID, allowing to be shut down when something goes wrong
  220363. unsigned long pid = getpid();
  220364. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  220365. (unsigned char*) &pid, 1);
  220366. // Set window manager protocols
  220367. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  220368. (unsigned char*) Atoms::ProtocolList, 2);
  220369. // Set drag and drop flags
  220370. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  220371. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  220372. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  220373. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  220374. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  220375. (const unsigned char*) "", 0);
  220376. unsigned long dndVersion = Atoms::DndVersion;
  220377. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  220378. (const unsigned char*) &dndVersion, 1);
  220379. // Initialise the pointer and keyboard mapping
  220380. // This is not the same as the logical pointer mapping the X server uses:
  220381. // we don't mess with this.
  220382. static bool mappingInitialised = false;
  220383. if (! mappingInitialised)
  220384. {
  220385. mappingInitialised = true;
  220386. const int numButtons = XGetPointerMapping (display, 0, 0);
  220387. if (numButtons == 2)
  220388. {
  220389. pointerMap[0] = Keys::LeftButton;
  220390. pointerMap[1] = Keys::RightButton;
  220391. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  220392. }
  220393. else if (numButtons >= 3)
  220394. {
  220395. pointerMap[0] = Keys::LeftButton;
  220396. pointerMap[1] = Keys::MiddleButton;
  220397. pointerMap[2] = Keys::RightButton;
  220398. if (numButtons >= 5)
  220399. {
  220400. pointerMap[3] = Keys::WheelUp;
  220401. pointerMap[4] = Keys::WheelDown;
  220402. }
  220403. }
  220404. updateModifierMappings();
  220405. }
  220406. }
  220407. void destroyWindow()
  220408. {
  220409. ScopedXLock xlock;
  220410. XPointer handlePointer;
  220411. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  220412. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  220413. XDestroyWindow (display, windowH);
  220414. // Wait for it to complete and then remove any events for this
  220415. // window from the event queue.
  220416. XSync (display, false);
  220417. XEvent event;
  220418. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  220419. {}
  220420. }
  220421. static int getAllEventsMask() throw()
  220422. {
  220423. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220424. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220425. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220426. }
  220427. static int64 getEventTime (::Time t)
  220428. {
  220429. static int64 eventTimeOffset = 0x12345678;
  220430. const int64 thisMessageTime = t;
  220431. if (eventTimeOffset == 0x12345678)
  220432. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  220433. return eventTimeOffset + thisMessageTime;
  220434. }
  220435. void updateBorderSize()
  220436. {
  220437. if ((styleFlags & windowHasTitleBar) == 0)
  220438. {
  220439. windowBorder = BorderSize<int> (0);
  220440. }
  220441. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  220442. {
  220443. ScopedXLock xlock;
  220444. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  220445. if (hints != None)
  220446. {
  220447. unsigned char* data = 0;
  220448. unsigned long nitems, bytesLeft;
  220449. Atom actualType;
  220450. int actualFormat;
  220451. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  220452. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220453. &data) == Success)
  220454. {
  220455. const unsigned long* const sizes = (const unsigned long*) data;
  220456. if (actualFormat == 32)
  220457. windowBorder = BorderSize<int> ((int) sizes[2], (int) sizes[0],
  220458. (int) sizes[3], (int) sizes[1]);
  220459. XFree (data);
  220460. }
  220461. }
  220462. }
  220463. }
  220464. void updateBounds()
  220465. {
  220466. jassert (windowH != 0);
  220467. if (windowH != 0)
  220468. {
  220469. Window root, child;
  220470. unsigned int bw, depth;
  220471. ScopedXLock xlock;
  220472. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220473. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  220474. &bw, &depth))
  220475. {
  220476. wx = wy = ww = wh = 0;
  220477. }
  220478. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  220479. {
  220480. wx = wy = 0;
  220481. }
  220482. }
  220483. }
  220484. void resetDragAndDrop()
  220485. {
  220486. dragAndDropFiles.clear();
  220487. lastDropPos = Point<int> (-1, -1);
  220488. dragAndDropCurrentMimeType = 0;
  220489. dragAndDropSourceWindow = 0;
  220490. srcMimeTypeAtomList.clear();
  220491. }
  220492. void sendDragAndDropMessage (XClientMessageEvent& msg)
  220493. {
  220494. msg.type = ClientMessage;
  220495. msg.display = display;
  220496. msg.window = dragAndDropSourceWindow;
  220497. msg.format = 32;
  220498. msg.data.l[0] = windowH;
  220499. ScopedXLock xlock;
  220500. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  220501. }
  220502. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  220503. {
  220504. XClientMessageEvent msg;
  220505. zerostruct (msg);
  220506. msg.message_type = Atoms::XdndStatus;
  220507. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  220508. msg.data.l[4] = dropAction;
  220509. sendDragAndDropMessage (msg);
  220510. }
  220511. void sendDragAndDropLeave()
  220512. {
  220513. XClientMessageEvent msg;
  220514. zerostruct (msg);
  220515. msg.message_type = Atoms::XdndLeave;
  220516. sendDragAndDropMessage (msg);
  220517. }
  220518. void sendDragAndDropFinish()
  220519. {
  220520. XClientMessageEvent msg;
  220521. zerostruct (msg);
  220522. msg.message_type = Atoms::XdndFinished;
  220523. sendDragAndDropMessage (msg);
  220524. }
  220525. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  220526. {
  220527. if ((clientMsg->data.l[1] & 1) == 0)
  220528. {
  220529. sendDragAndDropLeave();
  220530. if (dragAndDropFiles.size() > 0)
  220531. handleFileDragExit (dragAndDropFiles);
  220532. dragAndDropFiles.clear();
  220533. }
  220534. }
  220535. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  220536. {
  220537. if (dragAndDropSourceWindow == 0)
  220538. return;
  220539. dragAndDropSourceWindow = clientMsg->data.l[0];
  220540. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  220541. (int) clientMsg->data.l[2] & 0xffff);
  220542. dropPos -= getScreenPosition();
  220543. if (lastDropPos != dropPos)
  220544. {
  220545. lastDropPos = dropPos;
  220546. dragAndDropTimestamp = clientMsg->data.l[3];
  220547. Atom targetAction = Atoms::XdndActionCopy;
  220548. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  220549. {
  220550. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  220551. {
  220552. targetAction = Atoms::allowedActions[i];
  220553. break;
  220554. }
  220555. }
  220556. sendDragAndDropStatus (true, targetAction);
  220557. if (dragAndDropFiles.size() == 0)
  220558. updateDraggedFileList (clientMsg);
  220559. if (dragAndDropFiles.size() > 0)
  220560. handleFileDragMove (dragAndDropFiles, dropPos);
  220561. }
  220562. }
  220563. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  220564. {
  220565. if (dragAndDropFiles.size() == 0)
  220566. updateDraggedFileList (clientMsg);
  220567. const StringArray files (dragAndDropFiles);
  220568. const Point<int> lastPos (lastDropPos);
  220569. sendDragAndDropFinish();
  220570. resetDragAndDrop();
  220571. if (files.size() > 0)
  220572. handleFileDragDrop (files, lastPos);
  220573. }
  220574. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  220575. {
  220576. dragAndDropFiles.clear();
  220577. srcMimeTypeAtomList.clear();
  220578. dragAndDropCurrentMimeType = 0;
  220579. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  220580. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  220581. {
  220582. dragAndDropSourceWindow = 0;
  220583. return;
  220584. }
  220585. dragAndDropSourceWindow = clientMsg->data.l[0];
  220586. if ((clientMsg->data.l[1] & 1) != 0)
  220587. {
  220588. Atom actual;
  220589. int format;
  220590. unsigned long count = 0, remaining = 0;
  220591. unsigned char* data = 0;
  220592. ScopedXLock xlock;
  220593. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  220594. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  220595. &count, &remaining, &data);
  220596. if (data != 0)
  220597. {
  220598. if (actual == XA_ATOM && format == 32 && count != 0)
  220599. {
  220600. const unsigned long* const types = (const unsigned long*) data;
  220601. for (unsigned int i = 0; i < count; ++i)
  220602. if (types[i] != None)
  220603. srcMimeTypeAtomList.add (types[i]);
  220604. }
  220605. XFree (data);
  220606. }
  220607. }
  220608. if (srcMimeTypeAtomList.size() == 0)
  220609. {
  220610. for (int i = 2; i < 5; ++i)
  220611. if (clientMsg->data.l[i] != None)
  220612. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  220613. if (srcMimeTypeAtomList.size() == 0)
  220614. {
  220615. dragAndDropSourceWindow = 0;
  220616. return;
  220617. }
  220618. }
  220619. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  220620. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  220621. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  220622. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  220623. handleDragAndDropPosition (clientMsg);
  220624. }
  220625. void handleDragAndDropSelection (const XEvent* const evt)
  220626. {
  220627. dragAndDropFiles.clear();
  220628. if (evt->xselection.property != 0)
  220629. {
  220630. StringArray lines;
  220631. {
  220632. MemoryBlock dropData;
  220633. for (;;)
  220634. {
  220635. Atom actual;
  220636. uint8* data = 0;
  220637. unsigned long count = 0, remaining = 0;
  220638. int format = 0;
  220639. ScopedXLock xlock;
  220640. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  220641. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  220642. &format, &count, &remaining, &data) == Success)
  220643. {
  220644. dropData.append (data, count * format / 8);
  220645. XFree (data);
  220646. if (remaining == 0)
  220647. break;
  220648. }
  220649. else
  220650. {
  220651. XFree (data);
  220652. break;
  220653. }
  220654. }
  220655. lines.addLines (dropData.toString());
  220656. }
  220657. for (int i = 0; i < lines.size(); ++i)
  220658. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  220659. dragAndDropFiles.trim();
  220660. dragAndDropFiles.removeEmptyStrings();
  220661. }
  220662. }
  220663. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  220664. {
  220665. dragAndDropFiles.clear();
  220666. if (dragAndDropSourceWindow != None
  220667. && dragAndDropCurrentMimeType != 0)
  220668. {
  220669. dragAndDropTimestamp = clientMsg->data.l[2];
  220670. ScopedXLock xlock;
  220671. XConvertSelection (display,
  220672. Atoms::XdndSelection,
  220673. dragAndDropCurrentMimeType,
  220674. XInternAtom (display, "JXSelectionWindowProperty", 0),
  220675. windowH,
  220676. dragAndDropTimestamp);
  220677. }
  220678. }
  220679. StringArray dragAndDropFiles;
  220680. int dragAndDropTimestamp;
  220681. Point<int> lastDropPos;
  220682. Atom dragAndDropCurrentMimeType;
  220683. Window dragAndDropSourceWindow;
  220684. Array <Atom> srcMimeTypeAtomList;
  220685. static int pointerMap[5];
  220686. static Point<int> lastMousePos;
  220687. static void clearLastMousePos() throw()
  220688. {
  220689. lastMousePos = Point<int> (0x100000, 0x100000);
  220690. }
  220691. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LinuxComponentPeer);
  220692. };
  220693. ModifierKeys LinuxComponentPeer::currentModifiers;
  220694. bool LinuxComponentPeer::isActiveApplication = false;
  220695. int LinuxComponentPeer::pointerMap[5];
  220696. Point<int> LinuxComponentPeer::lastMousePos;
  220697. bool Process::isForegroundProcess()
  220698. {
  220699. return LinuxComponentPeer::isActiveApplication;
  220700. }
  220701. void ModifierKeys::updateCurrentModifiers() throw()
  220702. {
  220703. currentModifiers = LinuxComponentPeer::currentModifiers;
  220704. }
  220705. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220706. {
  220707. Window root, child;
  220708. int x, y, winx, winy;
  220709. unsigned int mask;
  220710. int mouseMods = 0;
  220711. ScopedXLock xlock;
  220712. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  220713. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  220714. {
  220715. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  220716. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  220717. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  220718. }
  220719. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  220720. return LinuxComponentPeer::currentModifiers;
  220721. }
  220722. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  220723. {
  220724. if (enableOrDisable)
  220725. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  220726. }
  220727. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  220728. {
  220729. return new LinuxComponentPeer (this, styleFlags);
  220730. }
  220731. // (this callback is hooked up in the messaging code)
  220732. void juce_windowMessageReceive (XEvent* event)
  220733. {
  220734. if (event->xany.window != None)
  220735. {
  220736. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  220737. if (ComponentPeer::isValidPeer (peer))
  220738. peer->handleWindowMessage (event);
  220739. }
  220740. else
  220741. {
  220742. switch (event->xany.type)
  220743. {
  220744. case KeymapNotify:
  220745. {
  220746. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  220747. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  220748. break;
  220749. }
  220750. default:
  220751. break;
  220752. }
  220753. }
  220754. }
  220755. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  220756. {
  220757. if (display == 0)
  220758. return;
  220759. #if JUCE_USE_XINERAMA
  220760. int major_opcode, first_event, first_error;
  220761. ScopedXLock xlock;
  220762. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  220763. {
  220764. typedef Bool (*tXineramaIsActive) (Display*);
  220765. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  220766. static tXineramaIsActive xXineramaIsActive = 0;
  220767. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  220768. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  220769. {
  220770. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  220771. if (h == 0)
  220772. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  220773. if (h != 0)
  220774. {
  220775. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  220776. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  220777. }
  220778. }
  220779. if (xXineramaIsActive != 0
  220780. && xXineramaQueryScreens != 0
  220781. && xXineramaIsActive (display))
  220782. {
  220783. int numMonitors = 0;
  220784. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  220785. if (screens != 0)
  220786. {
  220787. for (int i = numMonitors; --i >= 0;)
  220788. {
  220789. int index = screens[i].screen_number;
  220790. if (index >= 0)
  220791. {
  220792. while (monitorCoords.size() < index)
  220793. monitorCoords.add (Rectangle<int>());
  220794. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  220795. screens[i].y_org,
  220796. screens[i].width,
  220797. screens[i].height));
  220798. }
  220799. }
  220800. XFree (screens);
  220801. }
  220802. }
  220803. }
  220804. if (monitorCoords.size() == 0)
  220805. #endif
  220806. {
  220807. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  220808. if (hints != None)
  220809. {
  220810. const int numMonitors = ScreenCount (display);
  220811. for (int i = 0; i < numMonitors; ++i)
  220812. {
  220813. Window root = RootWindow (display, i);
  220814. unsigned long nitems, bytesLeft;
  220815. Atom actualType;
  220816. int actualFormat;
  220817. unsigned char* data = 0;
  220818. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  220819. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  220820. &data) == Success)
  220821. {
  220822. const long* const position = (const long*) data;
  220823. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  220824. monitorCoords.add (Rectangle<int> (position[0], position[1],
  220825. position[2], position[3]));
  220826. XFree (data);
  220827. }
  220828. }
  220829. }
  220830. if (monitorCoords.size() == 0)
  220831. {
  220832. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  220833. DisplayHeight (display, DefaultScreen (display))));
  220834. }
  220835. }
  220836. }
  220837. void Desktop::createMouseInputSources()
  220838. {
  220839. mouseSources.add (new MouseInputSource (0, true));
  220840. }
  220841. bool Desktop::canUseSemiTransparentWindows() throw()
  220842. {
  220843. int matchedDepth = 0;
  220844. const int desiredDepth = 32;
  220845. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  220846. && (matchedDepth == desiredDepth);
  220847. }
  220848. const Point<int> MouseInputSource::getCurrentMousePosition()
  220849. {
  220850. Window root, child;
  220851. int x, y, winx, winy;
  220852. unsigned int mask;
  220853. ScopedXLock xlock;
  220854. if (XQueryPointer (display,
  220855. RootWindow (display, DefaultScreen (display)),
  220856. &root, &child,
  220857. &x, &y, &winx, &winy, &mask) == False)
  220858. {
  220859. // Pointer not on the default screen
  220860. x = y = -1;
  220861. }
  220862. return Point<int> (x, y);
  220863. }
  220864. void Desktop::setMousePosition (const Point<int>& newPosition)
  220865. {
  220866. ScopedXLock xlock;
  220867. Window root = RootWindow (display, DefaultScreen (display));
  220868. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  220869. }
  220870. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  220871. {
  220872. return upright;
  220873. }
  220874. static bool screenSaverAllowed = true;
  220875. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  220876. {
  220877. if (screenSaverAllowed != isEnabled)
  220878. {
  220879. screenSaverAllowed = isEnabled;
  220880. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  220881. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  220882. if (xScreenSaverSuspend == 0)
  220883. {
  220884. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  220885. if (h != 0)
  220886. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  220887. }
  220888. ScopedXLock xlock;
  220889. if (xScreenSaverSuspend != 0)
  220890. xScreenSaverSuspend (display, ! isEnabled);
  220891. }
  220892. }
  220893. bool Desktop::isScreenSaverEnabled()
  220894. {
  220895. return screenSaverAllowed;
  220896. }
  220897. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  220898. {
  220899. ScopedXLock xlock;
  220900. const unsigned int imageW = image.getWidth();
  220901. const unsigned int imageH = image.getHeight();
  220902. #if JUCE_USE_XCURSOR
  220903. {
  220904. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  220905. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  220906. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  220907. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  220908. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  220909. static tXcursorImageCreate xXcursorImageCreate = 0;
  220910. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  220911. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  220912. static bool hasBeenLoaded = false;
  220913. if (! hasBeenLoaded)
  220914. {
  220915. hasBeenLoaded = true;
  220916. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  220917. if (h != 0)
  220918. {
  220919. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  220920. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  220921. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  220922. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  220923. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  220924. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  220925. || ! xXcursorSupportsARGB (display))
  220926. xXcursorSupportsARGB = 0;
  220927. }
  220928. }
  220929. if (xXcursorSupportsARGB != 0)
  220930. {
  220931. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  220932. if (xcImage != 0)
  220933. {
  220934. xcImage->xhot = hotspotX;
  220935. xcImage->yhot = hotspotY;
  220936. XcursorPixel* dest = xcImage->pixels;
  220937. for (int y = 0; y < (int) imageH; ++y)
  220938. for (int x = 0; x < (int) imageW; ++x)
  220939. *dest++ = image.getPixelAt (x, y).getARGB();
  220940. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  220941. xXcursorImageDestroy (xcImage);
  220942. if (result != 0)
  220943. return result;
  220944. }
  220945. }
  220946. }
  220947. #endif
  220948. Window root = RootWindow (display, DefaultScreen (display));
  220949. unsigned int cursorW, cursorH;
  220950. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  220951. return 0;
  220952. Image im (Image::ARGB, cursorW, cursorH, true);
  220953. {
  220954. Graphics g (im);
  220955. if (imageW > cursorW || imageH > cursorH)
  220956. {
  220957. hotspotX = (hotspotX * cursorW) / imageW;
  220958. hotspotY = (hotspotY * cursorH) / imageH;
  220959. g.drawImageWithin (image, 0, 0, imageW, imageH,
  220960. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  220961. false);
  220962. }
  220963. else
  220964. {
  220965. g.drawImageAt (image, 0, 0);
  220966. }
  220967. }
  220968. const int stride = (cursorW + 7) >> 3;
  220969. HeapBlock <char> maskPlane, sourcePlane;
  220970. maskPlane.calloc (stride * cursorH);
  220971. sourcePlane.calloc (stride * cursorH);
  220972. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220973. for (int y = cursorH; --y >= 0;)
  220974. {
  220975. for (int x = cursorW; --x >= 0;)
  220976. {
  220977. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220978. const int offset = y * stride + (x >> 3);
  220979. const Colour c (im.getPixelAt (x, y));
  220980. if (c.getAlpha() >= 128)
  220981. maskPlane[offset] |= mask;
  220982. if (c.getBrightness() >= 0.5f)
  220983. sourcePlane[offset] |= mask;
  220984. }
  220985. }
  220986. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220987. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  220988. XColor white, black;
  220989. black.red = black.green = black.blue = 0;
  220990. white.red = white.green = white.blue = 0xffff;
  220991. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  220992. XFreePixmap (display, sourcePixmap);
  220993. XFreePixmap (display, maskPixmap);
  220994. return result;
  220995. }
  220996. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  220997. {
  220998. ScopedXLock xlock;
  220999. if (cursorHandle != 0)
  221000. XFreeCursor (display, (Cursor) cursorHandle);
  221001. }
  221002. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  221003. {
  221004. unsigned int shape;
  221005. switch (type)
  221006. {
  221007. case NormalCursor: return None; // Use parent cursor
  221008. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  221009. case WaitCursor: shape = XC_watch; break;
  221010. case IBeamCursor: shape = XC_xterm; break;
  221011. case PointingHandCursor: shape = XC_hand2; break;
  221012. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  221013. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  221014. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  221015. case TopEdgeResizeCursor: shape = XC_top_side; break;
  221016. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  221017. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  221018. case RightEdgeResizeCursor: shape = XC_right_side; break;
  221019. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  221020. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  221021. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  221022. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  221023. case CrosshairCursor: shape = XC_crosshair; break;
  221024. case DraggingHandCursor:
  221025. {
  221026. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  221027. 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,
  221028. 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 };
  221029. const int dragHandDataSize = 99;
  221030. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  221031. }
  221032. case CopyingCursor:
  221033. {
  221034. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  221035. 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,
  221036. 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,
  221037. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  221038. const int copyCursorSize = 119;
  221039. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  221040. }
  221041. default:
  221042. jassertfalse;
  221043. return None;
  221044. }
  221045. ScopedXLock xlock;
  221046. return (void*) XCreateFontCursor (display, shape);
  221047. }
  221048. void MouseCursor::showInWindow (ComponentPeer* peer) const
  221049. {
  221050. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  221051. if (lp != 0)
  221052. lp->showMouseCursor ((Cursor) getHandle());
  221053. }
  221054. void MouseCursor::showInAllWindows() const
  221055. {
  221056. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  221057. showInWindow (ComponentPeer::getPeer (i));
  221058. }
  221059. const Image juce_createIconForFile (const File& file)
  221060. {
  221061. return Image::null;
  221062. }
  221063. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  221064. {
  221065. return createSoftwareImage (format, width, height, clearImage);
  221066. }
  221067. #if JUCE_OPENGL
  221068. class WindowedGLContext : public OpenGLContext
  221069. {
  221070. public:
  221071. WindowedGLContext (Component* const component,
  221072. const OpenGLPixelFormat& pixelFormat_,
  221073. GLXContext sharedContext)
  221074. : renderContext (0),
  221075. embeddedWindow (0),
  221076. pixelFormat (pixelFormat_),
  221077. swapInterval (0)
  221078. {
  221079. jassert (component != 0);
  221080. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221081. if (peer == 0)
  221082. return;
  221083. ScopedXLock xlock;
  221084. XSync (display, False);
  221085. GLint attribs [64];
  221086. int n = 0;
  221087. attribs[n++] = GLX_RGBA;
  221088. attribs[n++] = GLX_DOUBLEBUFFER;
  221089. attribs[n++] = GLX_RED_SIZE;
  221090. attribs[n++] = pixelFormat.redBits;
  221091. attribs[n++] = GLX_GREEN_SIZE;
  221092. attribs[n++] = pixelFormat.greenBits;
  221093. attribs[n++] = GLX_BLUE_SIZE;
  221094. attribs[n++] = pixelFormat.blueBits;
  221095. attribs[n++] = GLX_ALPHA_SIZE;
  221096. attribs[n++] = pixelFormat.alphaBits;
  221097. attribs[n++] = GLX_DEPTH_SIZE;
  221098. attribs[n++] = pixelFormat.depthBufferBits;
  221099. attribs[n++] = GLX_STENCIL_SIZE;
  221100. attribs[n++] = pixelFormat.stencilBufferBits;
  221101. attribs[n++] = GLX_ACCUM_RED_SIZE;
  221102. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221103. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  221104. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221105. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  221106. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221107. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  221108. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221109. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  221110. attribs[n++] = None;
  221111. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  221112. if (bestVisual == 0)
  221113. return;
  221114. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  221115. Window windowH = (Window) peer->getNativeHandle();
  221116. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  221117. XSetWindowAttributes swa;
  221118. swa.colormap = colourMap;
  221119. swa.border_pixel = 0;
  221120. swa.event_mask = ExposureMask | StructureNotifyMask;
  221121. embeddedWindow = XCreateWindow (display, windowH,
  221122. 0, 0, 1, 1, 0,
  221123. bestVisual->depth,
  221124. InputOutput,
  221125. bestVisual->visual,
  221126. CWBorderPixel | CWColormap | CWEventMask,
  221127. &swa);
  221128. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  221129. XMapWindow (display, embeddedWindow);
  221130. XFreeColormap (display, colourMap);
  221131. XFree (bestVisual);
  221132. XSync (display, False);
  221133. }
  221134. ~WindowedGLContext()
  221135. {
  221136. ScopedXLock xlock;
  221137. deleteContext();
  221138. XUnmapWindow (display, embeddedWindow);
  221139. XDestroyWindow (display, embeddedWindow);
  221140. }
  221141. void deleteContext()
  221142. {
  221143. makeInactive();
  221144. if (renderContext != 0)
  221145. {
  221146. ScopedXLock xlock;
  221147. glXDestroyContext (display, renderContext);
  221148. renderContext = 0;
  221149. }
  221150. }
  221151. bool makeActive() const throw()
  221152. {
  221153. jassert (renderContext != 0);
  221154. ScopedXLock xlock;
  221155. return glXMakeCurrent (display, embeddedWindow, renderContext)
  221156. && XSync (display, False);
  221157. }
  221158. bool makeInactive() const throw()
  221159. {
  221160. ScopedXLock xlock;
  221161. return (! isActive()) || glXMakeCurrent (display, None, 0);
  221162. }
  221163. bool isActive() const throw()
  221164. {
  221165. ScopedXLock xlock;
  221166. return glXGetCurrentContext() == renderContext;
  221167. }
  221168. const OpenGLPixelFormat getPixelFormat() const
  221169. {
  221170. return pixelFormat;
  221171. }
  221172. void* getRawContext() const throw()
  221173. {
  221174. return renderContext;
  221175. }
  221176. void updateWindowPosition (int x, int y, int w, int h, int)
  221177. {
  221178. ScopedXLock xlock;
  221179. XMoveResizeWindow (display, embeddedWindow,
  221180. x, y, jmax (1, w), jmax (1, h));
  221181. }
  221182. void swapBuffers()
  221183. {
  221184. ScopedXLock xlock;
  221185. glXSwapBuffers (display, embeddedWindow);
  221186. }
  221187. bool setSwapInterval (const int numFramesPerSwap)
  221188. {
  221189. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  221190. if (GLXSwapIntervalSGI != 0)
  221191. {
  221192. swapInterval = numFramesPerSwap;
  221193. GLXSwapIntervalSGI (numFramesPerSwap);
  221194. return true;
  221195. }
  221196. return false;
  221197. }
  221198. int getSwapInterval() const
  221199. {
  221200. return swapInterval;
  221201. }
  221202. void repaint()
  221203. {
  221204. }
  221205. GLXContext renderContext;
  221206. private:
  221207. Window embeddedWindow;
  221208. OpenGLPixelFormat pixelFormat;
  221209. int swapInterval;
  221210. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  221211. };
  221212. OpenGLContext* OpenGLComponent::createContext()
  221213. {
  221214. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  221215. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  221216. return (c->renderContext != 0) ? c.release() : 0;
  221217. }
  221218. void juce_glViewport (const int w, const int h)
  221219. {
  221220. glViewport (0, 0, w, h);
  221221. }
  221222. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  221223. OwnedArray <OpenGLPixelFormat>& results)
  221224. {
  221225. results.add (new OpenGLPixelFormat()); // xxx
  221226. }
  221227. #endif
  221228. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  221229. {
  221230. jassertfalse; // not implemented!
  221231. return false;
  221232. }
  221233. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  221234. {
  221235. jassertfalse; // not implemented!
  221236. return false;
  221237. }
  221238. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  221239. {
  221240. if (! isOnDesktop ())
  221241. addToDesktop (0);
  221242. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221243. if (wp != 0)
  221244. {
  221245. wp->setTaskBarIcon (newImage);
  221246. setVisible (true);
  221247. toFront (false);
  221248. repaint();
  221249. }
  221250. }
  221251. void SystemTrayIconComponent::paint (Graphics& g)
  221252. {
  221253. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  221254. if (wp != 0)
  221255. {
  221256. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  221257. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221258. false);
  221259. }
  221260. }
  221261. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  221262. {
  221263. // xxx not yet implemented!
  221264. }
  221265. void PlatformUtilities::beep()
  221266. {
  221267. std::cout << "\a" << std::flush;
  221268. }
  221269. bool AlertWindow::showNativeDialogBox (const String& title,
  221270. const String& bodyText,
  221271. bool isOkCancel)
  221272. {
  221273. // use a non-native one for the time being..
  221274. if (isOkCancel)
  221275. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  221276. else
  221277. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  221278. return true;
  221279. }
  221280. const int KeyPress::spaceKey = XK_space & 0xff;
  221281. const int KeyPress::returnKey = XK_Return & 0xff;
  221282. const int KeyPress::escapeKey = XK_Escape & 0xff;
  221283. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  221284. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  221285. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  221286. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  221287. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  221288. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  221289. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  221290. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  221291. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  221292. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  221293. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  221294. const int KeyPress::tabKey = XK_Tab & 0xff;
  221295. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  221296. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  221297. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  221298. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  221299. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  221300. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  221301. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  221302. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  221303. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  221304. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  221305. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  221306. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  221307. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  221308. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  221309. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  221310. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  221311. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  221312. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  221313. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  221314. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  221315. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  221316. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  221317. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  221318. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  221319. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  221320. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  221321. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  221322. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  221323. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  221324. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  221325. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  221326. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  221327. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  221328. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  221329. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  221330. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  221331. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  221332. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  221333. #endif
  221334. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  221335. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  221336. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  221337. // compiled on its own).
  221338. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  221339. namespace
  221340. {
  221341. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  221342. {
  221343. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  221344. snd_pcm_hw_params_t* hwParams;
  221345. snd_pcm_hw_params_alloca (&hwParams);
  221346. for (int i = 0; ratesToTry[i] != 0; ++i)
  221347. {
  221348. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  221349. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  221350. {
  221351. rates.addIfNotAlreadyThere (ratesToTry[i]);
  221352. }
  221353. }
  221354. }
  221355. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  221356. {
  221357. snd_pcm_hw_params_t *params;
  221358. snd_pcm_hw_params_alloca (&params);
  221359. if (snd_pcm_hw_params_any (handle, params) >= 0)
  221360. {
  221361. snd_pcm_hw_params_get_channels_min (params, minChans);
  221362. snd_pcm_hw_params_get_channels_max (params, maxChans);
  221363. }
  221364. }
  221365. void getDeviceProperties (const String& deviceID,
  221366. unsigned int& minChansOut,
  221367. unsigned int& maxChansOut,
  221368. unsigned int& minChansIn,
  221369. unsigned int& maxChansIn,
  221370. Array <int>& rates)
  221371. {
  221372. if (deviceID.isEmpty())
  221373. return;
  221374. snd_ctl_t* handle;
  221375. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  221376. {
  221377. snd_pcm_info_t* info;
  221378. snd_pcm_info_alloca (&info);
  221379. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  221380. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  221381. snd_pcm_info_set_subdevice (info, 0);
  221382. if (snd_ctl_pcm_info (handle, info) >= 0)
  221383. {
  221384. snd_pcm_t* pcmHandle;
  221385. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221386. {
  221387. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  221388. getDeviceSampleRates (pcmHandle, rates);
  221389. snd_pcm_close (pcmHandle);
  221390. }
  221391. }
  221392. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  221393. if (snd_ctl_pcm_info (handle, info) >= 0)
  221394. {
  221395. snd_pcm_t* pcmHandle;
  221396. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  221397. {
  221398. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  221399. if (rates.size() == 0)
  221400. getDeviceSampleRates (pcmHandle, rates);
  221401. snd_pcm_close (pcmHandle);
  221402. }
  221403. }
  221404. snd_ctl_close (handle);
  221405. }
  221406. }
  221407. }
  221408. class ALSADevice
  221409. {
  221410. public:
  221411. ALSADevice (const String& deviceID, bool forInput)
  221412. : handle (0),
  221413. bitDepth (16),
  221414. numChannelsRunning (0),
  221415. latency (0),
  221416. isInput (forInput),
  221417. isInterleaved (true)
  221418. {
  221419. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  221420. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  221421. SND_PCM_ASYNC));
  221422. }
  221423. ~ALSADevice()
  221424. {
  221425. if (handle != 0)
  221426. snd_pcm_close (handle);
  221427. }
  221428. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  221429. {
  221430. if (handle == 0)
  221431. return false;
  221432. snd_pcm_hw_params_t* hwParams;
  221433. snd_pcm_hw_params_alloca (&hwParams);
  221434. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  221435. return false;
  221436. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  221437. isInterleaved = false;
  221438. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  221439. isInterleaved = true;
  221440. else
  221441. {
  221442. jassertfalse;
  221443. return false;
  221444. }
  221445. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  221446. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  221447. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  221448. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  221449. SND_PCM_FORMAT_S32_BE, 32,
  221450. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  221451. SND_PCM_FORMAT_S24_3BE, 24,
  221452. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  221453. SND_PCM_FORMAT_S16_BE, 16 };
  221454. bitDepth = 0;
  221455. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  221456. {
  221457. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  221458. {
  221459. bitDepth = formatsToTry [i + 1] & 255;
  221460. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  221461. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  221462. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  221463. break;
  221464. }
  221465. }
  221466. if (bitDepth == 0)
  221467. {
  221468. error = "device doesn't support a compatible PCM format";
  221469. DBG ("ALSA error: " + error + "\n");
  221470. return false;
  221471. }
  221472. int dir = 0;
  221473. unsigned int periods = 4;
  221474. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  221475. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  221476. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  221477. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  221478. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  221479. || failed (snd_pcm_hw_params (handle, hwParams)))
  221480. {
  221481. return false;
  221482. }
  221483. snd_pcm_uframes_t frames = 0;
  221484. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  221485. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  221486. latency = 0;
  221487. else
  221488. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  221489. snd_pcm_sw_params_t* swParams;
  221490. snd_pcm_sw_params_alloca (&swParams);
  221491. snd_pcm_uframes_t boundary;
  221492. if (failed (snd_pcm_sw_params_current (handle, swParams))
  221493. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  221494. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  221495. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  221496. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  221497. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  221498. || failed (snd_pcm_sw_params (handle, swParams)))
  221499. {
  221500. return false;
  221501. }
  221502. #if 0
  221503. // enable this to dump the config of the devices that get opened
  221504. snd_output_t* out;
  221505. snd_output_stdio_attach (&out, stderr, 0);
  221506. snd_pcm_hw_params_dump (hwParams, out);
  221507. snd_pcm_sw_params_dump (swParams, out);
  221508. #endif
  221509. numChannelsRunning = numChannels;
  221510. return true;
  221511. }
  221512. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  221513. {
  221514. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  221515. float** const data = outputChannelBuffer.getArrayOfChannels();
  221516. snd_pcm_sframes_t numDone = 0;
  221517. if (isInterleaved)
  221518. {
  221519. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221520. for (int i = 0; i < numChannelsRunning; ++i)
  221521. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  221522. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  221523. }
  221524. else
  221525. {
  221526. for (int i = 0; i < numChannelsRunning; ++i)
  221527. converter->convertSamples (data[i], data[i], numSamples);
  221528. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  221529. }
  221530. if (failed (numDone))
  221531. {
  221532. if (numDone == -EPIPE)
  221533. {
  221534. if (failed (snd_pcm_prepare (handle)))
  221535. return false;
  221536. }
  221537. else if (numDone != -ESTRPIPE)
  221538. return false;
  221539. }
  221540. return true;
  221541. }
  221542. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  221543. {
  221544. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  221545. float** const data = inputChannelBuffer.getArrayOfChannels();
  221546. if (isInterleaved)
  221547. {
  221548. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  221549. scratch.fillWith (0); // (not clearing this data causes warnings in valgrind)
  221550. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  221551. if (failed (num))
  221552. {
  221553. if (num == -EPIPE)
  221554. {
  221555. if (failed (snd_pcm_prepare (handle)))
  221556. return false;
  221557. }
  221558. else if (num != -ESTRPIPE)
  221559. return false;
  221560. }
  221561. for (int i = 0; i < numChannelsRunning; ++i)
  221562. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  221563. }
  221564. else
  221565. {
  221566. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  221567. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  221568. return false;
  221569. for (int i = 0; i < numChannelsRunning; ++i)
  221570. converter->convertSamples (data[i], data[i], numSamples);
  221571. }
  221572. return true;
  221573. }
  221574. snd_pcm_t* handle;
  221575. String error;
  221576. int bitDepth, numChannelsRunning, latency;
  221577. private:
  221578. const bool isInput;
  221579. bool isInterleaved;
  221580. MemoryBlock scratch;
  221581. ScopedPointer<AudioData::Converter> converter;
  221582. template <class SampleType>
  221583. struct ConverterHelper
  221584. {
  221585. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  221586. {
  221587. if (forInput)
  221588. {
  221589. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  221590. if (isLittleEndian)
  221591. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221592. else
  221593. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  221594. }
  221595. else
  221596. {
  221597. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  221598. if (isLittleEndian)
  221599. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221600. else
  221601. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  221602. }
  221603. }
  221604. };
  221605. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  221606. {
  221607. switch (bitDepth)
  221608. {
  221609. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221610. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221611. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  221612. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  221613. default: jassertfalse; break; // unsupported format!
  221614. }
  221615. return 0;
  221616. }
  221617. bool failed (const int errorNum)
  221618. {
  221619. if (errorNum >= 0)
  221620. return false;
  221621. error = snd_strerror (errorNum);
  221622. DBG ("ALSA error: " + error + "\n");
  221623. return true;
  221624. }
  221625. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSADevice);
  221626. };
  221627. class ALSAThread : public Thread
  221628. {
  221629. public:
  221630. ALSAThread (const String& inputId_,
  221631. const String& outputId_)
  221632. : Thread ("Juce ALSA"),
  221633. sampleRate (0),
  221634. bufferSize (0),
  221635. outputLatency (0),
  221636. inputLatency (0),
  221637. callback (0),
  221638. inputId (inputId_),
  221639. outputId (outputId_),
  221640. numCallbacks (0),
  221641. inputChannelBuffer (1, 1),
  221642. outputChannelBuffer (1, 1)
  221643. {
  221644. initialiseRatesAndChannels();
  221645. }
  221646. ~ALSAThread()
  221647. {
  221648. close();
  221649. }
  221650. void open (BigInteger inputChannels,
  221651. BigInteger outputChannels,
  221652. const double sampleRate_,
  221653. const int bufferSize_)
  221654. {
  221655. close();
  221656. error = String::empty;
  221657. sampleRate = sampleRate_;
  221658. bufferSize = bufferSize_;
  221659. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  221660. inputChannelBuffer.clear();
  221661. inputChannelDataForCallback.clear();
  221662. currentInputChans.clear();
  221663. if (inputChannels.getHighestBit() >= 0)
  221664. {
  221665. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  221666. {
  221667. if (inputChannels[i])
  221668. {
  221669. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  221670. currentInputChans.setBit (i);
  221671. }
  221672. }
  221673. }
  221674. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  221675. outputChannelBuffer.clear();
  221676. outputChannelDataForCallback.clear();
  221677. currentOutputChans.clear();
  221678. if (outputChannels.getHighestBit() >= 0)
  221679. {
  221680. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  221681. {
  221682. if (outputChannels[i])
  221683. {
  221684. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  221685. currentOutputChans.setBit (i);
  221686. }
  221687. }
  221688. }
  221689. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  221690. {
  221691. outputDevice = new ALSADevice (outputId, false);
  221692. if (outputDevice->error.isNotEmpty())
  221693. {
  221694. error = outputDevice->error;
  221695. outputDevice = 0;
  221696. return;
  221697. }
  221698. currentOutputChans.setRange (0, minChansOut, true);
  221699. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  221700. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  221701. bufferSize))
  221702. {
  221703. error = outputDevice->error;
  221704. outputDevice = 0;
  221705. return;
  221706. }
  221707. outputLatency = outputDevice->latency;
  221708. }
  221709. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  221710. {
  221711. inputDevice = new ALSADevice (inputId, true);
  221712. if (inputDevice->error.isNotEmpty())
  221713. {
  221714. error = inputDevice->error;
  221715. inputDevice = 0;
  221716. return;
  221717. }
  221718. currentInputChans.setRange (0, minChansIn, true);
  221719. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  221720. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  221721. bufferSize))
  221722. {
  221723. error = inputDevice->error;
  221724. inputDevice = 0;
  221725. return;
  221726. }
  221727. inputLatency = inputDevice->latency;
  221728. }
  221729. if (outputDevice == 0 && inputDevice == 0)
  221730. {
  221731. error = "no channels";
  221732. return;
  221733. }
  221734. if (outputDevice != 0 && inputDevice != 0)
  221735. {
  221736. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  221737. }
  221738. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  221739. return;
  221740. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  221741. return;
  221742. startThread (9);
  221743. int count = 1000;
  221744. while (numCallbacks == 0)
  221745. {
  221746. sleep (5);
  221747. if (--count < 0 || ! isThreadRunning())
  221748. {
  221749. error = "device didn't start";
  221750. break;
  221751. }
  221752. }
  221753. }
  221754. void close()
  221755. {
  221756. stopThread (6000);
  221757. inputDevice = 0;
  221758. outputDevice = 0;
  221759. inputChannelBuffer.setSize (1, 1);
  221760. outputChannelBuffer.setSize (1, 1);
  221761. numCallbacks = 0;
  221762. }
  221763. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  221764. {
  221765. const ScopedLock sl (callbackLock);
  221766. callback = newCallback;
  221767. }
  221768. void run()
  221769. {
  221770. while (! threadShouldExit())
  221771. {
  221772. if (inputDevice != 0)
  221773. {
  221774. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  221775. {
  221776. DBG ("ALSA: read failure");
  221777. break;
  221778. }
  221779. }
  221780. if (threadShouldExit())
  221781. break;
  221782. {
  221783. const ScopedLock sl (callbackLock);
  221784. ++numCallbacks;
  221785. if (callback != 0)
  221786. {
  221787. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  221788. inputChannelDataForCallback.size(),
  221789. outputChannelDataForCallback.getRawDataPointer(),
  221790. outputChannelDataForCallback.size(),
  221791. bufferSize);
  221792. }
  221793. else
  221794. {
  221795. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  221796. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  221797. }
  221798. }
  221799. if (outputDevice != 0)
  221800. {
  221801. failed (snd_pcm_wait (outputDevice->handle, 2000));
  221802. if (threadShouldExit())
  221803. break;
  221804. failed (snd_pcm_avail_update (outputDevice->handle));
  221805. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  221806. {
  221807. DBG ("ALSA: write failure");
  221808. break;
  221809. }
  221810. }
  221811. }
  221812. }
  221813. int getBitDepth() const throw()
  221814. {
  221815. if (outputDevice != 0)
  221816. return outputDevice->bitDepth;
  221817. if (inputDevice != 0)
  221818. return inputDevice->bitDepth;
  221819. return 16;
  221820. }
  221821. String error;
  221822. double sampleRate;
  221823. int bufferSize, outputLatency, inputLatency;
  221824. BigInteger currentInputChans, currentOutputChans;
  221825. Array <int> sampleRates;
  221826. StringArray channelNamesOut, channelNamesIn;
  221827. AudioIODeviceCallback* callback;
  221828. private:
  221829. const String inputId, outputId;
  221830. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  221831. int numCallbacks;
  221832. CriticalSection callbackLock;
  221833. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  221834. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  221835. unsigned int minChansOut, maxChansOut;
  221836. unsigned int minChansIn, maxChansIn;
  221837. bool failed (const int errorNum)
  221838. {
  221839. if (errorNum >= 0)
  221840. return false;
  221841. error = snd_strerror (errorNum);
  221842. DBG ("ALSA error: " + error + "\n");
  221843. return true;
  221844. }
  221845. void initialiseRatesAndChannels()
  221846. {
  221847. sampleRates.clear();
  221848. channelNamesOut.clear();
  221849. channelNamesIn.clear();
  221850. minChansOut = 0;
  221851. maxChansOut = 0;
  221852. minChansIn = 0;
  221853. maxChansIn = 0;
  221854. unsigned int dummy = 0;
  221855. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  221856. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  221857. unsigned int i;
  221858. for (i = 0; i < maxChansOut; ++i)
  221859. channelNamesOut.add ("channel " + String ((int) i + 1));
  221860. for (i = 0; i < maxChansIn; ++i)
  221861. channelNamesIn.add ("channel " + String ((int) i + 1));
  221862. }
  221863. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAThread);
  221864. };
  221865. class ALSAAudioIODevice : public AudioIODevice
  221866. {
  221867. public:
  221868. ALSAAudioIODevice (const String& deviceName,
  221869. const String& inputId_,
  221870. const String& outputId_)
  221871. : AudioIODevice (deviceName, "ALSA"),
  221872. inputId (inputId_),
  221873. outputId (outputId_),
  221874. isOpen_ (false),
  221875. isStarted (false),
  221876. internal (inputId_, outputId_)
  221877. {
  221878. }
  221879. ~ALSAAudioIODevice()
  221880. {
  221881. }
  221882. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  221883. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  221884. int getNumSampleRates() { return internal.sampleRates.size(); }
  221885. double getSampleRate (int index) { return internal.sampleRates [index]; }
  221886. int getDefaultBufferSize() { return 512; }
  221887. int getNumBufferSizesAvailable() { return 50; }
  221888. int getBufferSizeSamples (int index)
  221889. {
  221890. int n = 16;
  221891. for (int i = 0; i < index; ++i)
  221892. n += n < 64 ? 16
  221893. : (n < 512 ? 32
  221894. : (n < 1024 ? 64
  221895. : (n < 2048 ? 128 : 256)));
  221896. return n;
  221897. }
  221898. const String open (const BigInteger& inputChannels,
  221899. const BigInteger& outputChannels,
  221900. double sampleRate,
  221901. int bufferSizeSamples)
  221902. {
  221903. close();
  221904. if (bufferSizeSamples <= 0)
  221905. bufferSizeSamples = getDefaultBufferSize();
  221906. if (sampleRate <= 0)
  221907. {
  221908. for (int i = 0; i < getNumSampleRates(); ++i)
  221909. {
  221910. if (getSampleRate (i) >= 44100)
  221911. {
  221912. sampleRate = getSampleRate (i);
  221913. break;
  221914. }
  221915. }
  221916. }
  221917. internal.open (inputChannels, outputChannels,
  221918. sampleRate, bufferSizeSamples);
  221919. isOpen_ = internal.error.isEmpty();
  221920. return internal.error;
  221921. }
  221922. void close()
  221923. {
  221924. stop();
  221925. internal.close();
  221926. isOpen_ = false;
  221927. }
  221928. bool isOpen() { return isOpen_; }
  221929. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  221930. const String getLastError() { return internal.error; }
  221931. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  221932. double getCurrentSampleRate() { return internal.sampleRate; }
  221933. int getCurrentBitDepth() { return internal.getBitDepth(); }
  221934. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  221935. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  221936. int getOutputLatencyInSamples() { return internal.outputLatency; }
  221937. int getInputLatencyInSamples() { return internal.inputLatency; }
  221938. void start (AudioIODeviceCallback* callback)
  221939. {
  221940. if (! isOpen_)
  221941. callback = 0;
  221942. if (callback != 0)
  221943. callback->audioDeviceAboutToStart (this);
  221944. internal.setCallback (callback);
  221945. isStarted = (callback != 0);
  221946. }
  221947. void stop()
  221948. {
  221949. AudioIODeviceCallback* const oldCallback = internal.callback;
  221950. start (0);
  221951. if (oldCallback != 0)
  221952. oldCallback->audioDeviceStopped();
  221953. }
  221954. String inputId, outputId;
  221955. private:
  221956. bool isOpen_, isStarted;
  221957. ALSAThread internal;
  221958. };
  221959. class ALSAAudioIODeviceType : public AudioIODeviceType
  221960. {
  221961. public:
  221962. ALSAAudioIODeviceType()
  221963. : AudioIODeviceType ("ALSA"),
  221964. hasScanned (false)
  221965. {
  221966. }
  221967. ~ALSAAudioIODeviceType()
  221968. {
  221969. }
  221970. void scanForDevices()
  221971. {
  221972. if (hasScanned)
  221973. return;
  221974. hasScanned = true;
  221975. inputNames.clear();
  221976. inputIds.clear();
  221977. outputNames.clear();
  221978. outputIds.clear();
  221979. /* void** hints = 0;
  221980. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  221981. {
  221982. for (void** hint = hints; *hint != 0; ++hint)
  221983. {
  221984. const String name (getHint (*hint, "NAME"));
  221985. if (name.isNotEmpty())
  221986. {
  221987. const String ioid (getHint (*hint, "IOID"));
  221988. String desc (getHint (*hint, "DESC"));
  221989. if (desc.isEmpty())
  221990. desc = name;
  221991. desc = desc.replaceCharacters ("\n\r", " ");
  221992. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  221993. if (ioid.isEmpty() || ioid == "Input")
  221994. {
  221995. inputNames.add (desc);
  221996. inputIds.add (name);
  221997. }
  221998. if (ioid.isEmpty() || ioid == "Output")
  221999. {
  222000. outputNames.add (desc);
  222001. outputIds.add (name);
  222002. }
  222003. }
  222004. }
  222005. snd_device_name_free_hint (hints);
  222006. }
  222007. */
  222008. snd_ctl_t* handle = 0;
  222009. snd_ctl_card_info_t* info = 0;
  222010. snd_ctl_card_info_alloca (&info);
  222011. int cardNum = -1;
  222012. while (outputIds.size() + inputIds.size() <= 32)
  222013. {
  222014. snd_card_next (&cardNum);
  222015. if (cardNum < 0)
  222016. break;
  222017. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222018. {
  222019. if (snd_ctl_card_info (handle, info) >= 0)
  222020. {
  222021. String cardId (snd_ctl_card_info_get_id (info));
  222022. if (cardId.removeCharacters ("0123456789").isEmpty())
  222023. cardId = String (cardNum);
  222024. int device = -1;
  222025. for (;;)
  222026. {
  222027. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  222028. break;
  222029. String id, name;
  222030. id << "hw:" << cardId << ',' << device;
  222031. bool isInput, isOutput;
  222032. if (testDevice (id, isInput, isOutput))
  222033. {
  222034. name << snd_ctl_card_info_get_name (info);
  222035. if (name.isEmpty())
  222036. name = id;
  222037. if (isInput)
  222038. {
  222039. inputNames.add (name);
  222040. inputIds.add (id);
  222041. }
  222042. if (isOutput)
  222043. {
  222044. outputNames.add (name);
  222045. outputIds.add (id);
  222046. }
  222047. }
  222048. }
  222049. }
  222050. snd_ctl_close (handle);
  222051. }
  222052. }
  222053. inputNames.appendNumbersToDuplicates (false, true);
  222054. outputNames.appendNumbersToDuplicates (false, true);
  222055. }
  222056. const StringArray getDeviceNames (bool wantInputNames) const
  222057. {
  222058. jassert (hasScanned); // need to call scanForDevices() before doing this
  222059. return wantInputNames ? inputNames : outputNames;
  222060. }
  222061. int getDefaultDeviceIndex (bool forInput) const
  222062. {
  222063. jassert (hasScanned); // need to call scanForDevices() before doing this
  222064. return 0;
  222065. }
  222066. bool hasSeparateInputsAndOutputs() const { return true; }
  222067. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222068. {
  222069. jassert (hasScanned); // need to call scanForDevices() before doing this
  222070. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  222071. if (d == 0)
  222072. return -1;
  222073. return asInput ? inputIds.indexOf (d->inputId)
  222074. : outputIds.indexOf (d->outputId);
  222075. }
  222076. AudioIODevice* createDevice (const String& outputDeviceName,
  222077. const String& inputDeviceName)
  222078. {
  222079. jassert (hasScanned); // need to call scanForDevices() before doing this
  222080. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222081. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222082. String deviceName (outputIndex >= 0 ? outputDeviceName
  222083. : inputDeviceName);
  222084. if (inputIndex >= 0 || outputIndex >= 0)
  222085. return new ALSAAudioIODevice (deviceName,
  222086. inputIds [inputIndex],
  222087. outputIds [outputIndex]);
  222088. return 0;
  222089. }
  222090. private:
  222091. StringArray inputNames, outputNames, inputIds, outputIds;
  222092. bool hasScanned;
  222093. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  222094. {
  222095. unsigned int minChansOut = 0, maxChansOut = 0;
  222096. unsigned int minChansIn = 0, maxChansIn = 0;
  222097. Array <int> rates;
  222098. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  222099. DBG ("ALSA device: " + id
  222100. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  222101. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  222102. + " rates=" + String (rates.size()));
  222103. isInput = maxChansIn > 0;
  222104. isOutput = maxChansOut > 0;
  222105. return (isInput || isOutput) && rates.size() > 0;
  222106. }
  222107. /*static const String getHint (void* hint, const char* type)
  222108. {
  222109. char* const n = snd_device_name_get_hint (hint, type);
  222110. const String s ((const char*) n);
  222111. free (n);
  222112. return s;
  222113. }*/
  222114. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ALSAAudioIODeviceType);
  222115. };
  222116. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  222117. {
  222118. return new ALSAAudioIODeviceType();
  222119. }
  222120. #endif
  222121. /*** End of inlined file: juce_linux_Audio.cpp ***/
  222122. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  222123. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222124. // compiled on its own).
  222125. #ifdef JUCE_INCLUDED_FILE
  222126. #if JUCE_JACK
  222127. static void* juce_libjack_handle = 0;
  222128. void* juce_load_jack_function (const char* const name)
  222129. {
  222130. if (juce_libjack_handle == 0)
  222131. return 0;
  222132. return dlsym (juce_libjack_handle, name);
  222133. }
  222134. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  222135. typedef return_type (*fn_name##_ptr_t)argument_types; \
  222136. return_type fn_name argument_types { \
  222137. static fn_name##_ptr_t fn = 0; \
  222138. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222139. if (fn) return (*fn)arguments; \
  222140. else return 0; \
  222141. }
  222142. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  222143. typedef void (*fn_name##_ptr_t)argument_types; \
  222144. void fn_name argument_types { \
  222145. static fn_name##_ptr_t fn = 0; \
  222146. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  222147. if (fn) (*fn)arguments; \
  222148. }
  222149. 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));
  222150. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  222151. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  222152. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  222153. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  222154. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  222155. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  222156. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  222157. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  222158. 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));
  222159. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  222160. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  222161. 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));
  222162. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  222163. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  222164. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  222165. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  222166. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  222167. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  222168. #if JUCE_DEBUG
  222169. #define JACK_LOGGING_ENABLED 1
  222170. #endif
  222171. #if JACK_LOGGING_ENABLED
  222172. namespace
  222173. {
  222174. void jack_Log (const String& s)
  222175. {
  222176. std::cerr << s << std::endl;
  222177. }
  222178. void dumpJackErrorMessage (const jack_status_t status)
  222179. {
  222180. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  222181. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  222182. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  222183. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  222184. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  222185. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  222186. }
  222187. }
  222188. #else
  222189. #define dumpJackErrorMessage(a) {}
  222190. #define jack_Log(...) {}
  222191. #endif
  222192. #ifndef JUCE_JACK_CLIENT_NAME
  222193. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  222194. #endif
  222195. class JackAudioIODevice : public AudioIODevice
  222196. {
  222197. public:
  222198. JackAudioIODevice (const String& deviceName,
  222199. const String& inputId_,
  222200. const String& outputId_)
  222201. : AudioIODevice (deviceName, "JACK"),
  222202. inputId (inputId_),
  222203. outputId (outputId_),
  222204. isOpen_ (false),
  222205. callback (0),
  222206. totalNumberOfInputChannels (0),
  222207. totalNumberOfOutputChannels (0)
  222208. {
  222209. jassert (deviceName.isNotEmpty());
  222210. jack_status_t status;
  222211. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  222212. if (client == 0)
  222213. {
  222214. dumpJackErrorMessage (status);
  222215. }
  222216. else
  222217. {
  222218. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  222219. // open input ports
  222220. const StringArray inputChannels (getInputChannelNames());
  222221. for (int i = 0; i < inputChannels.size(); i++)
  222222. {
  222223. String inputName;
  222224. inputName << "in_" << ++totalNumberOfInputChannels;
  222225. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  222226. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  222227. }
  222228. // open output ports
  222229. const StringArray outputChannels (getOutputChannelNames());
  222230. for (int i = 0; i < outputChannels.size (); i++)
  222231. {
  222232. String outputName;
  222233. outputName << "out_" << ++totalNumberOfOutputChannels;
  222234. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  222235. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  222236. }
  222237. inChans.calloc (totalNumberOfInputChannels + 2);
  222238. outChans.calloc (totalNumberOfOutputChannels + 2);
  222239. }
  222240. }
  222241. ~JackAudioIODevice()
  222242. {
  222243. close();
  222244. if (client != 0)
  222245. {
  222246. JUCE_NAMESPACE::jack_client_close (client);
  222247. client = 0;
  222248. }
  222249. }
  222250. const StringArray getChannelNames (bool forInput) const
  222251. {
  222252. StringArray names;
  222253. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  222254. forInput ? JackPortIsInput : JackPortIsOutput);
  222255. if (ports != 0)
  222256. {
  222257. int j = 0;
  222258. while (ports[j] != 0)
  222259. {
  222260. const String portName (ports [j++]);
  222261. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222262. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  222263. }
  222264. free (ports);
  222265. }
  222266. return names;
  222267. }
  222268. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  222269. const StringArray getInputChannelNames() { return getChannelNames (true); }
  222270. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  222271. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  222272. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  222273. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  222274. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  222275. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  222276. double sampleRate, int bufferSizeSamples)
  222277. {
  222278. if (client == 0)
  222279. {
  222280. lastError = "No JACK client running";
  222281. return lastError;
  222282. }
  222283. lastError = String::empty;
  222284. close();
  222285. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  222286. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  222287. JUCE_NAMESPACE::jack_activate (client);
  222288. isOpen_ = true;
  222289. if (! inputChannels.isZero())
  222290. {
  222291. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222292. if (ports != 0)
  222293. {
  222294. const int numInputChannels = inputChannels.getHighestBit() + 1;
  222295. for (int i = 0; i < numInputChannels; ++i)
  222296. {
  222297. const String portName (ports[i]);
  222298. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222299. {
  222300. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  222301. if (error != 0)
  222302. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222303. }
  222304. }
  222305. free (ports);
  222306. }
  222307. }
  222308. if (! outputChannels.isZero())
  222309. {
  222310. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222311. if (ports != 0)
  222312. {
  222313. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  222314. for (int i = 0; i < numOutputChannels; ++i)
  222315. {
  222316. const String portName (ports[i]);
  222317. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  222318. {
  222319. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  222320. if (error != 0)
  222321. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  222322. }
  222323. }
  222324. free (ports);
  222325. }
  222326. }
  222327. return lastError;
  222328. }
  222329. void close()
  222330. {
  222331. stop();
  222332. if (client != 0)
  222333. {
  222334. JUCE_NAMESPACE::jack_deactivate (client);
  222335. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  222336. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  222337. }
  222338. isOpen_ = false;
  222339. }
  222340. void start (AudioIODeviceCallback* newCallback)
  222341. {
  222342. if (isOpen_ && newCallback != callback)
  222343. {
  222344. if (newCallback != 0)
  222345. newCallback->audioDeviceAboutToStart (this);
  222346. AudioIODeviceCallback* const oldCallback = callback;
  222347. {
  222348. const ScopedLock sl (callbackLock);
  222349. callback = newCallback;
  222350. }
  222351. if (oldCallback != 0)
  222352. oldCallback->audioDeviceStopped();
  222353. }
  222354. }
  222355. void stop()
  222356. {
  222357. start (0);
  222358. }
  222359. bool isOpen() { return isOpen_; }
  222360. bool isPlaying() { return callback != 0; }
  222361. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  222362. double getCurrentSampleRate() { return getSampleRate (0); }
  222363. int getCurrentBitDepth() { return 32; }
  222364. const String getLastError() { return lastError; }
  222365. const BigInteger getActiveOutputChannels() const
  222366. {
  222367. BigInteger outputBits;
  222368. for (int i = 0; i < outputPorts.size(); i++)
  222369. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  222370. outputBits.setBit (i);
  222371. return outputBits;
  222372. }
  222373. const BigInteger getActiveInputChannels() const
  222374. {
  222375. BigInteger inputBits;
  222376. for (int i = 0; i < inputPorts.size(); i++)
  222377. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  222378. inputBits.setBit (i);
  222379. return inputBits;
  222380. }
  222381. int getOutputLatencyInSamples()
  222382. {
  222383. int latency = 0;
  222384. for (int i = 0; i < outputPorts.size(); i++)
  222385. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  222386. return latency;
  222387. }
  222388. int getInputLatencyInSamples()
  222389. {
  222390. int latency = 0;
  222391. for (int i = 0; i < inputPorts.size(); i++)
  222392. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  222393. return latency;
  222394. }
  222395. String inputId, outputId;
  222396. private:
  222397. void process (const int numSamples)
  222398. {
  222399. int i, numActiveInChans = 0, numActiveOutChans = 0;
  222400. for (i = 0; i < totalNumberOfInputChannels; ++i)
  222401. {
  222402. jack_default_audio_sample_t* in
  222403. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  222404. if (in != 0)
  222405. inChans [numActiveInChans++] = (float*) in;
  222406. }
  222407. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  222408. {
  222409. jack_default_audio_sample_t* out
  222410. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  222411. if (out != 0)
  222412. outChans [numActiveOutChans++] = (float*) out;
  222413. }
  222414. const ScopedLock sl (callbackLock);
  222415. if (callback != 0)
  222416. {
  222417. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  222418. outChans, numActiveOutChans, numSamples);
  222419. }
  222420. else
  222421. {
  222422. for (i = 0; i < numActiveOutChans; ++i)
  222423. zeromem (outChans[i], sizeof (float) * numSamples);
  222424. }
  222425. }
  222426. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  222427. {
  222428. if (callbackArgument != 0)
  222429. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  222430. return 0;
  222431. }
  222432. static void threadInitCallback (void* callbackArgument)
  222433. {
  222434. jack_Log ("JackAudioIODevice::initialise");
  222435. }
  222436. static void shutdownCallback (void* callbackArgument)
  222437. {
  222438. jack_Log ("JackAudioIODevice::shutdown");
  222439. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  222440. if (device != 0)
  222441. {
  222442. device->client = 0;
  222443. device->close();
  222444. }
  222445. }
  222446. static void errorCallback (const char* msg)
  222447. {
  222448. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  222449. }
  222450. bool isOpen_;
  222451. jack_client_t* client;
  222452. String lastError;
  222453. AudioIODeviceCallback* callback;
  222454. CriticalSection callbackLock;
  222455. HeapBlock <float*> inChans, outChans;
  222456. int totalNumberOfInputChannels;
  222457. int totalNumberOfOutputChannels;
  222458. Array<void*> inputPorts, outputPorts;
  222459. };
  222460. class JackAudioIODeviceType : public AudioIODeviceType
  222461. {
  222462. public:
  222463. JackAudioIODeviceType()
  222464. : AudioIODeviceType ("JACK"),
  222465. hasScanned (false)
  222466. {
  222467. }
  222468. ~JackAudioIODeviceType()
  222469. {
  222470. }
  222471. void scanForDevices()
  222472. {
  222473. hasScanned = true;
  222474. inputNames.clear();
  222475. inputIds.clear();
  222476. outputNames.clear();
  222477. outputIds.clear();
  222478. if (juce_libjack_handle == 0)
  222479. {
  222480. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  222481. if (juce_libjack_handle == 0)
  222482. return;
  222483. }
  222484. // open a dummy client
  222485. jack_status_t status;
  222486. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  222487. if (client == 0)
  222488. {
  222489. dumpJackErrorMessage (status);
  222490. }
  222491. else
  222492. {
  222493. // scan for output devices
  222494. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  222495. if (ports != 0)
  222496. {
  222497. int j = 0;
  222498. while (ports[j] != 0)
  222499. {
  222500. String clientName (ports[j]);
  222501. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222502. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222503. && ! inputNames.contains (clientName))
  222504. {
  222505. inputNames.add (clientName);
  222506. inputIds.add (ports [j]);
  222507. }
  222508. ++j;
  222509. }
  222510. free (ports);
  222511. }
  222512. // scan for input devices
  222513. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  222514. if (ports != 0)
  222515. {
  222516. int j = 0;
  222517. while (ports[j] != 0)
  222518. {
  222519. String clientName (ports[j]);
  222520. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  222521. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  222522. && ! outputNames.contains (clientName))
  222523. {
  222524. outputNames.add (clientName);
  222525. outputIds.add (ports [j]);
  222526. }
  222527. ++j;
  222528. }
  222529. free (ports);
  222530. }
  222531. JUCE_NAMESPACE::jack_client_close (client);
  222532. }
  222533. }
  222534. const StringArray getDeviceNames (bool wantInputNames) const
  222535. {
  222536. jassert (hasScanned); // need to call scanForDevices() before doing this
  222537. return wantInputNames ? inputNames : outputNames;
  222538. }
  222539. int getDefaultDeviceIndex (bool forInput) const
  222540. {
  222541. jassert (hasScanned); // need to call scanForDevices() before doing this
  222542. return 0;
  222543. }
  222544. bool hasSeparateInputsAndOutputs() const { return true; }
  222545. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  222546. {
  222547. jassert (hasScanned); // need to call scanForDevices() before doing this
  222548. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  222549. if (d == 0)
  222550. return -1;
  222551. return asInput ? inputIds.indexOf (d->inputId)
  222552. : outputIds.indexOf (d->outputId);
  222553. }
  222554. AudioIODevice* createDevice (const String& outputDeviceName,
  222555. const String& inputDeviceName)
  222556. {
  222557. jassert (hasScanned); // need to call scanForDevices() before doing this
  222558. const int inputIndex = inputNames.indexOf (inputDeviceName);
  222559. const int outputIndex = outputNames.indexOf (outputDeviceName);
  222560. if (inputIndex >= 0 || outputIndex >= 0)
  222561. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  222562. : inputDeviceName,
  222563. inputIds [inputIndex],
  222564. outputIds [outputIndex]);
  222565. return 0;
  222566. }
  222567. private:
  222568. StringArray inputNames, outputNames, inputIds, outputIds;
  222569. bool hasScanned;
  222570. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JackAudioIODeviceType);
  222571. };
  222572. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  222573. {
  222574. return new JackAudioIODeviceType();
  222575. }
  222576. #else // if JACK is turned off..
  222577. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  222578. #endif
  222579. #endif
  222580. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  222581. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  222582. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222583. // compiled on its own).
  222584. #if JUCE_INCLUDED_FILE
  222585. #if JUCE_ALSA
  222586. namespace
  222587. {
  222588. snd_seq_t* iterateMidiDevices (const bool forInput,
  222589. StringArray& deviceNamesFound,
  222590. const int deviceIndexToOpen)
  222591. {
  222592. snd_seq_t* returnedHandle = 0;
  222593. snd_seq_t* seqHandle;
  222594. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222595. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222596. {
  222597. snd_seq_system_info_t* systemInfo;
  222598. snd_seq_client_info_t* clientInfo;
  222599. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  222600. {
  222601. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  222602. && snd_seq_client_info_malloc (&clientInfo) == 0)
  222603. {
  222604. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  222605. while (--numClients >= 0 && returnedHandle == 0)
  222606. {
  222607. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  222608. {
  222609. snd_seq_port_info_t* portInfo;
  222610. if (snd_seq_port_info_malloc (&portInfo) == 0)
  222611. {
  222612. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  222613. const int client = snd_seq_client_info_get_client (clientInfo);
  222614. snd_seq_port_info_set_client (portInfo, client);
  222615. snd_seq_port_info_set_port (portInfo, -1);
  222616. while (--numPorts >= 0)
  222617. {
  222618. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  222619. && (snd_seq_port_info_get_capability (portInfo)
  222620. & (forInput ? SND_SEQ_PORT_CAP_READ
  222621. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  222622. {
  222623. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  222624. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  222625. {
  222626. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  222627. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  222628. if (sourcePort != -1)
  222629. {
  222630. snd_seq_set_client_name (seqHandle,
  222631. forInput ? "Juce Midi Input"
  222632. : "Juce Midi Output");
  222633. const int portId
  222634. = snd_seq_create_simple_port (seqHandle,
  222635. forInput ? "Juce Midi In Port"
  222636. : "Juce Midi Out Port",
  222637. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222638. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222639. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222640. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  222641. returnedHandle = seqHandle;
  222642. }
  222643. }
  222644. }
  222645. }
  222646. snd_seq_port_info_free (portInfo);
  222647. }
  222648. }
  222649. }
  222650. snd_seq_client_info_free (clientInfo);
  222651. }
  222652. snd_seq_system_info_free (systemInfo);
  222653. }
  222654. if (returnedHandle == 0)
  222655. snd_seq_close (seqHandle);
  222656. }
  222657. deviceNamesFound.appendNumbersToDuplicates (true, true);
  222658. return returnedHandle;
  222659. }
  222660. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  222661. {
  222662. snd_seq_t* seqHandle = 0;
  222663. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  222664. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  222665. {
  222666. snd_seq_set_client_name (seqHandle,
  222667. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  222668. const int portId
  222669. = snd_seq_create_simple_port (seqHandle,
  222670. forInput ? "in"
  222671. : "out",
  222672. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  222673. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  222674. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  222675. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  222676. if (portId < 0)
  222677. {
  222678. snd_seq_close (seqHandle);
  222679. seqHandle = 0;
  222680. }
  222681. }
  222682. return seqHandle;
  222683. }
  222684. }
  222685. class MidiOutputDevice
  222686. {
  222687. public:
  222688. MidiOutputDevice (MidiOutput* const midiOutput_,
  222689. snd_seq_t* const seqHandle_)
  222690. :
  222691. midiOutput (midiOutput_),
  222692. seqHandle (seqHandle_),
  222693. maxEventSize (16 * 1024)
  222694. {
  222695. jassert (seqHandle != 0 && midiOutput != 0);
  222696. snd_midi_event_new (maxEventSize, &midiParser);
  222697. }
  222698. ~MidiOutputDevice()
  222699. {
  222700. snd_midi_event_free (midiParser);
  222701. snd_seq_close (seqHandle);
  222702. }
  222703. void sendMessageNow (const MidiMessage& message)
  222704. {
  222705. if (message.getRawDataSize() > maxEventSize)
  222706. {
  222707. maxEventSize = message.getRawDataSize();
  222708. snd_midi_event_free (midiParser);
  222709. snd_midi_event_new (maxEventSize, &midiParser);
  222710. }
  222711. snd_seq_event_t event;
  222712. snd_seq_ev_clear (&event);
  222713. snd_midi_event_encode (midiParser,
  222714. message.getRawData(),
  222715. message.getRawDataSize(),
  222716. &event);
  222717. snd_midi_event_reset_encode (midiParser);
  222718. snd_seq_ev_set_source (&event, 0);
  222719. snd_seq_ev_set_subs (&event);
  222720. snd_seq_ev_set_direct (&event);
  222721. snd_seq_event_output (seqHandle, &event);
  222722. snd_seq_drain_output (seqHandle);
  222723. }
  222724. private:
  222725. MidiOutput* const midiOutput;
  222726. snd_seq_t* const seqHandle;
  222727. snd_midi_event_t* midiParser;
  222728. int maxEventSize;
  222729. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutputDevice);
  222730. };
  222731. const StringArray MidiOutput::getDevices()
  222732. {
  222733. StringArray devices;
  222734. iterateMidiDevices (false, devices, -1);
  222735. return devices;
  222736. }
  222737. int MidiOutput::getDefaultDeviceIndex()
  222738. {
  222739. return 0;
  222740. }
  222741. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  222742. {
  222743. MidiOutput* newDevice = 0;
  222744. StringArray devices;
  222745. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  222746. if (handle != 0)
  222747. {
  222748. newDevice = new MidiOutput();
  222749. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222750. }
  222751. return newDevice;
  222752. }
  222753. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  222754. {
  222755. MidiOutput* newDevice = 0;
  222756. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  222757. if (handle != 0)
  222758. {
  222759. newDevice = new MidiOutput();
  222760. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  222761. }
  222762. return newDevice;
  222763. }
  222764. MidiOutput::~MidiOutput()
  222765. {
  222766. delete static_cast <MidiOutputDevice*> (internal);
  222767. }
  222768. void MidiOutput::reset()
  222769. {
  222770. }
  222771. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  222772. {
  222773. return false;
  222774. }
  222775. void MidiOutput::setVolume (float leftVol, float rightVol)
  222776. {
  222777. }
  222778. void MidiOutput::sendMessageNow (const MidiMessage& message)
  222779. {
  222780. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  222781. }
  222782. class MidiInputThread : public Thread
  222783. {
  222784. public:
  222785. MidiInputThread (MidiInput* const midiInput_,
  222786. snd_seq_t* const seqHandle_,
  222787. MidiInputCallback* const callback_)
  222788. : Thread ("Juce MIDI Input"),
  222789. midiInput (midiInput_),
  222790. seqHandle (seqHandle_),
  222791. callback (callback_)
  222792. {
  222793. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  222794. }
  222795. ~MidiInputThread()
  222796. {
  222797. snd_seq_close (seqHandle);
  222798. }
  222799. void run()
  222800. {
  222801. const int maxEventSize = 16 * 1024;
  222802. snd_midi_event_t* midiParser;
  222803. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  222804. {
  222805. HeapBlock <uint8> buffer (maxEventSize);
  222806. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  222807. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  222808. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  222809. while (! threadShouldExit())
  222810. {
  222811. if (poll (pfd, numPfds, 500) > 0)
  222812. {
  222813. snd_seq_event_t* inputEvent = 0;
  222814. snd_seq_nonblock (seqHandle, 1);
  222815. do
  222816. {
  222817. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  222818. {
  222819. // xxx what about SYSEXes that are too big for the buffer?
  222820. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  222821. snd_midi_event_reset_decode (midiParser);
  222822. if (numBytes > 0)
  222823. {
  222824. const MidiMessage message ((const uint8*) buffer,
  222825. numBytes,
  222826. Time::getMillisecondCounter() * 0.001);
  222827. callback->handleIncomingMidiMessage (midiInput, message);
  222828. }
  222829. snd_seq_free_event (inputEvent);
  222830. }
  222831. }
  222832. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  222833. snd_seq_free_event (inputEvent);
  222834. }
  222835. }
  222836. snd_midi_event_free (midiParser);
  222837. }
  222838. };
  222839. private:
  222840. MidiInput* const midiInput;
  222841. snd_seq_t* const seqHandle;
  222842. MidiInputCallback* const callback;
  222843. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputThread);
  222844. };
  222845. MidiInput::MidiInput (const String& name_)
  222846. : name (name_),
  222847. internal (0)
  222848. {
  222849. }
  222850. MidiInput::~MidiInput()
  222851. {
  222852. stop();
  222853. delete static_cast <MidiInputThread*> (internal);
  222854. }
  222855. void MidiInput::start()
  222856. {
  222857. static_cast <MidiInputThread*> (internal)->startThread();
  222858. }
  222859. void MidiInput::stop()
  222860. {
  222861. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  222862. }
  222863. int MidiInput::getDefaultDeviceIndex()
  222864. {
  222865. return 0;
  222866. }
  222867. const StringArray MidiInput::getDevices()
  222868. {
  222869. StringArray devices;
  222870. iterateMidiDevices (true, devices, -1);
  222871. return devices;
  222872. }
  222873. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  222874. {
  222875. MidiInput* newDevice = 0;
  222876. StringArray devices;
  222877. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  222878. if (handle != 0)
  222879. {
  222880. newDevice = new MidiInput (devices [deviceIndex]);
  222881. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222882. }
  222883. return newDevice;
  222884. }
  222885. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  222886. {
  222887. MidiInput* newDevice = 0;
  222888. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  222889. if (handle != 0)
  222890. {
  222891. newDevice = new MidiInput (deviceName);
  222892. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  222893. }
  222894. return newDevice;
  222895. }
  222896. #else
  222897. // (These are just stub functions if ALSA is unavailable...)
  222898. const StringArray MidiOutput::getDevices() { return StringArray(); }
  222899. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  222900. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  222901. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  222902. MidiOutput::~MidiOutput() {}
  222903. void MidiOutput::reset() {}
  222904. bool MidiOutput::getVolume (float&, float&) { return false; }
  222905. void MidiOutput::setVolume (float, float) {}
  222906. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  222907. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  222908. MidiInput::~MidiInput() {}
  222909. void MidiInput::start() {}
  222910. void MidiInput::stop() {}
  222911. int MidiInput::getDefaultDeviceIndex() { return 0; }
  222912. const StringArray MidiInput::getDevices() { return StringArray(); }
  222913. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  222914. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  222915. #endif
  222916. #endif
  222917. /*** End of inlined file: juce_linux_Midi.cpp ***/
  222918. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  222919. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222920. // compiled on its own).
  222921. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  222922. AudioCDReader::AudioCDReader()
  222923. : AudioFormatReader (0, "CD Audio")
  222924. {
  222925. }
  222926. const StringArray AudioCDReader::getAvailableCDNames()
  222927. {
  222928. StringArray names;
  222929. return names;
  222930. }
  222931. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  222932. {
  222933. return 0;
  222934. }
  222935. AudioCDReader::~AudioCDReader()
  222936. {
  222937. }
  222938. void AudioCDReader::refreshTrackLengths()
  222939. {
  222940. }
  222941. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  222942. int64 startSampleInFile, int numSamples)
  222943. {
  222944. return false;
  222945. }
  222946. bool AudioCDReader::isCDStillPresent() const
  222947. {
  222948. return false;
  222949. }
  222950. bool AudioCDReader::isTrackAudio (int trackNum) const
  222951. {
  222952. return false;
  222953. }
  222954. void AudioCDReader::enableIndexScanning (bool b)
  222955. {
  222956. }
  222957. int AudioCDReader::getLastIndex() const
  222958. {
  222959. return 0;
  222960. }
  222961. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  222962. {
  222963. return Array<int>();
  222964. }
  222965. #endif
  222966. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  222967. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  222968. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222969. // compiled on its own).
  222970. #if JUCE_INCLUDED_FILE
  222971. void FileChooser::showPlatformDialog (Array<File>& results,
  222972. const String& title,
  222973. const File& file,
  222974. const String& filters,
  222975. bool isDirectory,
  222976. bool selectsFiles,
  222977. bool isSave,
  222978. bool warnAboutOverwritingExistingFiles,
  222979. bool selectMultipleFiles,
  222980. FilePreviewComponent* previewComponent)
  222981. {
  222982. const String separator (":");
  222983. String command ("zenity --file-selection");
  222984. if (title.isNotEmpty())
  222985. command << " --title=\"" << title << "\"";
  222986. if (file != File::nonexistent)
  222987. command << " --filename=\"" << file.getFullPathName () << "\"";
  222988. if (isDirectory)
  222989. command << " --directory";
  222990. if (isSave)
  222991. command << " --save";
  222992. if (selectMultipleFiles)
  222993. command << " --multiple --separator=\"" << separator << "\"";
  222994. command << " 2>&1";
  222995. MemoryOutputStream result;
  222996. int status = -1;
  222997. FILE* stream = popen (command.toUTF8(), "r");
  222998. if (stream != 0)
  222999. {
  223000. for (;;)
  223001. {
  223002. char buffer [1024];
  223003. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  223004. if (bytesRead <= 0)
  223005. break;
  223006. result.write (buffer, bytesRead);
  223007. }
  223008. status = pclose (stream);
  223009. }
  223010. if (status == 0)
  223011. {
  223012. StringArray tokens;
  223013. if (selectMultipleFiles)
  223014. tokens.addTokens (result.toUTF8(), separator, String::empty);
  223015. else
  223016. tokens.add (result.toUTF8());
  223017. for (int i = 0; i < tokens.size(); i++)
  223018. results.add (File (tokens[i]));
  223019. return;
  223020. }
  223021. //xxx ain't got one!
  223022. jassertfalse;
  223023. }
  223024. #endif
  223025. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  223026. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223027. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223028. // compiled on its own).
  223029. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223030. /*
  223031. Sorry.. This class isn't implemented on Linux!
  223032. */
  223033. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  223034. : browser (0),
  223035. blankPageShown (false),
  223036. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  223037. {
  223038. setOpaque (true);
  223039. }
  223040. WebBrowserComponent::~WebBrowserComponent()
  223041. {
  223042. }
  223043. void WebBrowserComponent::goToURL (const String& url,
  223044. const StringArray* headers,
  223045. const MemoryBlock* postData)
  223046. {
  223047. lastURL = url;
  223048. lastHeaders.clear();
  223049. if (headers != 0)
  223050. lastHeaders = *headers;
  223051. lastPostData.setSize (0);
  223052. if (postData != 0)
  223053. lastPostData = *postData;
  223054. blankPageShown = false;
  223055. }
  223056. void WebBrowserComponent::stop()
  223057. {
  223058. }
  223059. void WebBrowserComponent::goBack()
  223060. {
  223061. lastURL = String::empty;
  223062. blankPageShown = false;
  223063. }
  223064. void WebBrowserComponent::goForward()
  223065. {
  223066. lastURL = String::empty;
  223067. }
  223068. void WebBrowserComponent::refresh()
  223069. {
  223070. }
  223071. void WebBrowserComponent::paint (Graphics& g)
  223072. {
  223073. g.fillAll (Colours::white);
  223074. }
  223075. void WebBrowserComponent::checkWindowAssociation()
  223076. {
  223077. }
  223078. void WebBrowserComponent::reloadLastURL()
  223079. {
  223080. if (lastURL.isNotEmpty())
  223081. {
  223082. goToURL (lastURL, &lastHeaders, &lastPostData);
  223083. lastURL = String::empty;
  223084. }
  223085. }
  223086. void WebBrowserComponent::parentHierarchyChanged()
  223087. {
  223088. checkWindowAssociation();
  223089. }
  223090. void WebBrowserComponent::resized()
  223091. {
  223092. }
  223093. void WebBrowserComponent::visibilityChanged()
  223094. {
  223095. checkWindowAssociation();
  223096. }
  223097. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  223098. {
  223099. return true;
  223100. }
  223101. #endif
  223102. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  223103. #endif
  223104. END_JUCE_NAMESPACE
  223105. #endif
  223106. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  223107. #elif JUCE_MAC || JUCE_IOS
  223108. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  223109. /*
  223110. This file wraps together all the mac-specific code, so that
  223111. we can include all the native headers just once, and compile all our
  223112. platform-specific stuff in one big lump, keeping it out of the way of
  223113. the rest of the codebase.
  223114. */
  223115. #if JUCE_MAC || JUCE_IOS
  223116. #undef JUCE_BUILD_NATIVE
  223117. #define JUCE_BUILD_NATIVE 1
  223118. BEGIN_JUCE_NAMESPACE
  223119. #undef Point
  223120. namespace
  223121. {
  223122. template <class RectType>
  223123. const Rectangle<int> convertToRectInt (const RectType& r)
  223124. {
  223125. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  223126. }
  223127. template <class RectType>
  223128. const Rectangle<float> convertToRectFloat (const RectType& r)
  223129. {
  223130. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  223131. }
  223132. template <class RectType>
  223133. CGRect convertToCGRect (const RectType& r)
  223134. {
  223135. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  223136. }
  223137. }
  223138. class MessageQueue
  223139. {
  223140. public:
  223141. MessageQueue()
  223142. {
  223143. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4 && ! JUCE_IOS
  223144. runLoop = CFRunLoopGetMain();
  223145. #else
  223146. runLoop = CFRunLoopGetCurrent();
  223147. #endif
  223148. CFRunLoopSourceContext sourceContext;
  223149. zerostruct (sourceContext);
  223150. sourceContext.info = this;
  223151. sourceContext.perform = runLoopSourceCallback;
  223152. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  223153. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223154. }
  223155. ~MessageQueue()
  223156. {
  223157. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  223158. CFRunLoopSourceInvalidate (runLoopSource);
  223159. CFRelease (runLoopSource);
  223160. }
  223161. void post (Message* const message)
  223162. {
  223163. messages.add (message);
  223164. CFRunLoopSourceSignal (runLoopSource);
  223165. CFRunLoopWakeUp (runLoop);
  223166. }
  223167. private:
  223168. ReferenceCountedArray <Message, CriticalSection> messages;
  223169. CriticalSection lock;
  223170. CFRunLoopRef runLoop;
  223171. CFRunLoopSourceRef runLoopSource;
  223172. bool deliverNextMessage()
  223173. {
  223174. const Message::Ptr nextMessage (messages.removeAndReturn (0));
  223175. if (nextMessage == 0)
  223176. return false;
  223177. const ScopedAutoReleasePool pool;
  223178. MessageManager::getInstance()->deliverMessage (nextMessage);
  223179. return true;
  223180. }
  223181. void runLoopCallback()
  223182. {
  223183. for (int i = 4; --i >= 0;)
  223184. if (! deliverNextMessage())
  223185. return;
  223186. CFRunLoopSourceSignal (runLoopSource);
  223187. CFRunLoopWakeUp (runLoop);
  223188. }
  223189. static void runLoopSourceCallback (void* info)
  223190. {
  223191. static_cast <MessageQueue*> (info)->runLoopCallback();
  223192. }
  223193. };
  223194. #define JUCE_INCLUDED_FILE 1
  223195. // Now include the actual code files..
  223196. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  223197. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  223198. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  223199. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  223200. cross-linked so that when you make a call to a class that you thought was private, it ends up
  223201. actually calling into a similarly named class in the other module's address space.
  223202. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  223203. have unique names, and should avoid this problem.
  223204. If you're using the amalgamated version, you can just set this macro to something unique before
  223205. you include juce_amalgamated.cpp.
  223206. */
  223207. #ifndef JUCE_ObjCExtraSuffix
  223208. #define JUCE_ObjCExtraSuffix 3
  223209. #endif
  223210. #ifndef DOXYGEN
  223211. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  223212. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  223213. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  223214. #endif
  223215. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  223216. /*** Start of inlined file: juce_mac_Strings.mm ***/
  223217. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223218. // compiled on its own).
  223219. #if JUCE_INCLUDED_FILE
  223220. namespace
  223221. {
  223222. const String nsStringToJuce (NSString* s)
  223223. {
  223224. return String::fromUTF8 ([s UTF8String]);
  223225. }
  223226. NSString* juceStringToNS (const String& s)
  223227. {
  223228. return [NSString stringWithUTF8String: s.toUTF8()];
  223229. }
  223230. const String convertUTF16ToString (const UniChar* utf16)
  223231. {
  223232. String s;
  223233. while (*utf16 != 0)
  223234. s += (juce_wchar) *utf16++;
  223235. return s;
  223236. }
  223237. }
  223238. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223239. {
  223240. String result;
  223241. if (cfString != 0)
  223242. {
  223243. CFRange range = { 0, CFStringGetLength (cfString) };
  223244. HeapBlock <UniChar> u (range.length + 1);
  223245. CFStringGetCharacters (cfString, range, u);
  223246. u[range.length] = 0;
  223247. result = convertUTF16ToString (u);
  223248. }
  223249. return result;
  223250. }
  223251. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223252. {
  223253. const int len = s.length();
  223254. HeapBlock <UniChar> temp (len + 2);
  223255. for (int i = 0; i <= len; ++i)
  223256. temp[i] = s[i];
  223257. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223258. }
  223259. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223260. {
  223261. #if JUCE_IOS
  223262. const ScopedAutoReleasePool pool;
  223263. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  223264. #else
  223265. UnicodeMapping map;
  223266. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223267. kUnicodeNoSubset,
  223268. kTextEncodingDefaultFormat);
  223269. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223270. kUnicodeCanonicalCompVariant,
  223271. kTextEncodingDefaultFormat);
  223272. map.mappingVersion = kUnicodeUseLatestMapping;
  223273. UnicodeToTextInfo conversionInfo = 0;
  223274. String result;
  223275. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223276. {
  223277. const int bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (s.getCharPointer());
  223278. HeapBlock <char> tempOut;
  223279. tempOut.calloc (bytesNeeded + 4);
  223280. ByteCount bytesRead = 0;
  223281. ByteCount outputBufferSize = 0;
  223282. if (ConvertFromUnicodeToText (conversionInfo,
  223283. bytesNeeded, (ConstUniCharArrayPtr) s.toUTF16().getAddress(),
  223284. kUnicodeDefaultDirectionMask,
  223285. 0, 0, 0, 0,
  223286. bytesNeeded, &bytesRead,
  223287. &outputBufferSize, tempOut) == noErr)
  223288. {
  223289. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223290. CharPointer_UTF32 dest (result.getCharPointer());
  223291. dest.writeAll (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  223292. }
  223293. DisposeUnicodeToTextInfo (&conversionInfo);
  223294. }
  223295. return result;
  223296. #endif
  223297. }
  223298. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  223299. void SystemClipboard::copyTextToClipboard (const String& text)
  223300. {
  223301. #if JUCE_IOS
  223302. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  223303. forPasteboardType: @"public.text"];
  223304. #else
  223305. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223306. owner: nil];
  223307. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223308. forType: NSStringPboardType];
  223309. #endif
  223310. }
  223311. const String SystemClipboard::getTextFromClipboard()
  223312. {
  223313. #if JUCE_IOS
  223314. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  223315. #else
  223316. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223317. #endif
  223318. return text == 0 ? String::empty
  223319. : nsStringToJuce (text);
  223320. }
  223321. #endif
  223322. #endif
  223323. /*** End of inlined file: juce_mac_Strings.mm ***/
  223324. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  223325. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223326. // compiled on its own).
  223327. #if JUCE_INCLUDED_FILE
  223328. namespace SystemStatsHelpers
  223329. {
  223330. static int64 highResTimerFrequency = 0;
  223331. static double highResTimerToMillisecRatio = 0;
  223332. #if JUCE_INTEL
  223333. void doCPUID (uint32& a, uint32& b, uint32& c, uint32& d, uint32 type)
  223334. {
  223335. uint32 la = a, lb = b, lc = c, ld = d;
  223336. asm ("mov %%ebx, %%esi \n\t"
  223337. "cpuid \n\t"
  223338. "xchg %%esi, %%ebx"
  223339. : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
  223340. #if JUCE_64BIT
  223341. , "b" (lb), "c" (lc), "d" (ld)
  223342. #endif
  223343. );
  223344. a = la; b = lb; c = lc; d = ld;
  223345. }
  223346. #endif
  223347. }
  223348. void SystemStats::initialiseStats()
  223349. {
  223350. using namespace SystemStatsHelpers;
  223351. static bool initialised = false;
  223352. if (! initialised)
  223353. {
  223354. initialised = true;
  223355. #if JUCE_MAC
  223356. [NSApplication sharedApplication];
  223357. #endif
  223358. #if JUCE_INTEL
  223359. uint32 familyModel = 0, extFeatures = 0, features = 0, dummy = 0;
  223360. doCPUID (familyModel, extFeatures, dummy, features, 1);
  223361. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223362. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223363. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223364. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223365. #else
  223366. cpuFlags.hasMMX = false;
  223367. cpuFlags.hasSSE = false;
  223368. cpuFlags.hasSSE2 = false;
  223369. cpuFlags.has3DNow = false;
  223370. #endif
  223371. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  223372. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  223373. #else
  223374. cpuFlags.numCpus = (int) MPProcessors();
  223375. #endif
  223376. mach_timebase_info_data_t timebase;
  223377. (void) mach_timebase_info (&timebase);
  223378. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  223379. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  223380. String s (SystemStats::getJUCEVersion());
  223381. rlimit lim;
  223382. getrlimit (RLIMIT_NOFILE, &lim);
  223383. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223384. setrlimit (RLIMIT_NOFILE, &lim);
  223385. }
  223386. }
  223387. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  223388. {
  223389. return MacOSX;
  223390. }
  223391. const String SystemStats::getOperatingSystemName()
  223392. {
  223393. return "Mac OS X";
  223394. }
  223395. #if ! JUCE_IOS
  223396. int PlatformUtilities::getOSXMinorVersionNumber()
  223397. {
  223398. SInt32 versionMinor = 0;
  223399. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  223400. (void) err;
  223401. jassert (err == noErr);
  223402. return (int) versionMinor;
  223403. }
  223404. #endif
  223405. bool SystemStats::isOperatingSystem64Bit()
  223406. {
  223407. #if JUCE_IOS
  223408. return false;
  223409. #elif JUCE_64BIT
  223410. return true;
  223411. #else
  223412. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  223413. #endif
  223414. }
  223415. int SystemStats::getMemorySizeInMegabytes()
  223416. {
  223417. uint64 mem = 0;
  223418. size_t memSize = sizeof (mem);
  223419. int mib[] = { CTL_HW, HW_MEMSIZE };
  223420. sysctl (mib, 2, &mem, &memSize, 0, 0);
  223421. return (int) (mem / (1024 * 1024));
  223422. }
  223423. const String SystemStats::getCpuVendor()
  223424. {
  223425. #if JUCE_INTEL
  223426. uint32 dummy = 0;
  223427. uint32 vendor[4];
  223428. zerostruct (vendor);
  223429. SystemStatsHelpers::doCPUID (dummy, vendor[0], vendor[2], vendor[1], 0);
  223430. return String (reinterpret_cast <const char*> (vendor), 12);
  223431. #else
  223432. return String::empty;
  223433. #endif
  223434. }
  223435. int SystemStats::getCpuSpeedInMegaherz()
  223436. {
  223437. uint64 speedHz = 0;
  223438. size_t speedSize = sizeof (speedHz);
  223439. int mib[] = { CTL_HW, HW_CPU_FREQ };
  223440. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  223441. #if JUCE_BIG_ENDIAN
  223442. if (speedSize == 4)
  223443. speedHz >>= 32;
  223444. #endif
  223445. return (int) (speedHz / 1000000);
  223446. }
  223447. const String SystemStats::getLogonName()
  223448. {
  223449. return nsStringToJuce (NSUserName());
  223450. }
  223451. const String SystemStats::getFullUserName()
  223452. {
  223453. return nsStringToJuce (NSFullUserName());
  223454. }
  223455. uint32 juce_millisecondsSinceStartup() throw()
  223456. {
  223457. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  223458. }
  223459. double Time::getMillisecondCounterHiRes() throw()
  223460. {
  223461. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  223462. }
  223463. int64 Time::getHighResolutionTicks() throw()
  223464. {
  223465. return (int64) mach_absolute_time();
  223466. }
  223467. int64 Time::getHighResolutionTicksPerSecond() throw()
  223468. {
  223469. return SystemStatsHelpers::highResTimerFrequency;
  223470. }
  223471. bool Time::setSystemTimeToThisTime() const
  223472. {
  223473. jassertfalse;
  223474. return false;
  223475. }
  223476. int SystemStats::getPageSize()
  223477. {
  223478. return (int) NSPageSize();
  223479. }
  223480. void PlatformUtilities::fpuReset()
  223481. {
  223482. }
  223483. #endif
  223484. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  223485. /*** Start of inlined file: juce_mac_Network.mm ***/
  223486. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223487. // compiled on its own).
  223488. #if JUCE_INCLUDED_FILE
  223489. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  223490. {
  223491. ifaddrs* addrs = 0;
  223492. if (getifaddrs (&addrs) == 0)
  223493. {
  223494. for (const ifaddrs* cursor = addrs; cursor != 0; cursor = cursor->ifa_next)
  223495. {
  223496. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  223497. if (sto->ss_family == AF_LINK)
  223498. {
  223499. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  223500. #ifndef IFT_ETHER
  223501. #define IFT_ETHER 6
  223502. #endif
  223503. if (sadd->sdl_type == IFT_ETHER)
  223504. result.addIfNotAlreadyThere (MACAddress (((const uint8*) sadd->sdl_data) + sadd->sdl_nlen));
  223505. }
  223506. }
  223507. freeifaddrs (addrs);
  223508. }
  223509. }
  223510. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223511. const String& emailSubject,
  223512. const String& bodyText,
  223513. const StringArray& filesToAttach)
  223514. {
  223515. #if JUCE_IOS
  223516. //xxx probably need to use MFMailComposeViewController
  223517. jassertfalse;
  223518. return false;
  223519. #else
  223520. const ScopedAutoReleasePool pool;
  223521. String script;
  223522. script << "tell application \"Mail\"\r\n"
  223523. "set newMessage to make new outgoing message with properties {subject:\""
  223524. << emailSubject.replace ("\"", "\\\"")
  223525. << "\", content:\""
  223526. << bodyText.replace ("\"", "\\\"")
  223527. << "\" & return & return}\r\n"
  223528. "tell newMessage\r\n"
  223529. "set visible to true\r\n"
  223530. "set sender to \"sdfsdfsdfewf\"\r\n"
  223531. "make new to recipient at end of to recipients with properties {address:\""
  223532. << targetEmailAddress
  223533. << "\"}\r\n";
  223534. for (int i = 0; i < filesToAttach.size(); ++i)
  223535. {
  223536. script << "tell content\r\n"
  223537. "make new attachment with properties {file name:\""
  223538. << filesToAttach[i].replace ("\"", "\\\"")
  223539. << "\"} at after the last paragraph\r\n"
  223540. "end tell\r\n";
  223541. }
  223542. script << "end tell\r\n"
  223543. "end tell\r\n";
  223544. NSAppleScript* s = [[NSAppleScript alloc]
  223545. initWithSource: juceStringToNS (script)];
  223546. NSDictionary* error = 0;
  223547. const bool ok = [s executeAndReturnError: &error] != nil;
  223548. [s release];
  223549. return ok;
  223550. #endif
  223551. }
  223552. END_JUCE_NAMESPACE
  223553. using namespace JUCE_NAMESPACE;
  223554. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  223555. @interface JuceURLConnection : NSObject
  223556. {
  223557. @public
  223558. NSURLRequest* request;
  223559. NSURLConnection* connection;
  223560. NSMutableData* data;
  223561. Thread* runLoopThread;
  223562. bool initialised, hasFailed, hasFinished;
  223563. int position;
  223564. int64 contentLength;
  223565. NSDictionary* headers;
  223566. NSLock* dataLock;
  223567. }
  223568. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223569. - (void) dealloc;
  223570. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223571. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223572. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223573. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223574. - (BOOL) isOpen;
  223575. - (int) read: (char*) dest numBytes: (int) num;
  223576. - (int) readPosition;
  223577. - (void) stop;
  223578. - (void) createConnection;
  223579. @end
  223580. class JuceURLConnectionMessageThread : public Thread
  223581. {
  223582. public:
  223583. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223584. : Thread ("http connection"),
  223585. owner (owner_)
  223586. {
  223587. }
  223588. ~JuceURLConnectionMessageThread()
  223589. {
  223590. stopThread (10000);
  223591. }
  223592. void run()
  223593. {
  223594. [owner createConnection];
  223595. while (! threadShouldExit())
  223596. {
  223597. const ScopedAutoReleasePool pool;
  223598. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223599. }
  223600. }
  223601. private:
  223602. JuceURLConnection* owner;
  223603. };
  223604. @implementation JuceURLConnection
  223605. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223606. withCallback: (URL::OpenStreamProgressCallback*) callback
  223607. withContext: (void*) context;
  223608. {
  223609. [super init];
  223610. request = req;
  223611. [request retain];
  223612. data = [[NSMutableData data] retain];
  223613. dataLock = [[NSLock alloc] init];
  223614. connection = 0;
  223615. initialised = false;
  223616. hasFailed = false;
  223617. hasFinished = false;
  223618. contentLength = -1;
  223619. headers = 0;
  223620. runLoopThread = new JuceURLConnectionMessageThread (self);
  223621. runLoopThread->startThread();
  223622. while (runLoopThread->isThreadRunning() && ! initialised)
  223623. {
  223624. if (callback != 0)
  223625. callback (context, -1, (int) [[request HTTPBody] length]);
  223626. Thread::sleep (1);
  223627. }
  223628. return self;
  223629. }
  223630. - (void) dealloc
  223631. {
  223632. [self stop];
  223633. deleteAndZero (runLoopThread);
  223634. [connection release];
  223635. [data release];
  223636. [dataLock release];
  223637. [request release];
  223638. [headers release];
  223639. [super dealloc];
  223640. }
  223641. - (void) createConnection
  223642. {
  223643. NSUInteger oldRetainCount = [self retainCount];
  223644. connection = [[NSURLConnection alloc] initWithRequest: request
  223645. delegate: self];
  223646. if (oldRetainCount == [self retainCount])
  223647. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  223648. if (connection == nil)
  223649. runLoopThread->signalThreadShouldExit();
  223650. }
  223651. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  223652. {
  223653. (void) conn;
  223654. [dataLock lock];
  223655. [data setLength: 0];
  223656. [dataLock unlock];
  223657. initialised = true;
  223658. contentLength = [response expectedContentLength];
  223659. [headers release];
  223660. headers = 0;
  223661. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  223662. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  223663. }
  223664. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  223665. {
  223666. (void) conn;
  223667. DBG (nsStringToJuce ([error description]));
  223668. hasFailed = true;
  223669. initialised = true;
  223670. if (runLoopThread != 0)
  223671. runLoopThread->signalThreadShouldExit();
  223672. }
  223673. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  223674. {
  223675. (void) conn;
  223676. [dataLock lock];
  223677. [data appendData: newData];
  223678. [dataLock unlock];
  223679. initialised = true;
  223680. }
  223681. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  223682. {
  223683. (void) conn;
  223684. hasFinished = true;
  223685. initialised = true;
  223686. if (runLoopThread != 0)
  223687. runLoopThread->signalThreadShouldExit();
  223688. }
  223689. - (BOOL) isOpen
  223690. {
  223691. return connection != 0 && ! hasFailed;
  223692. }
  223693. - (int) readPosition
  223694. {
  223695. return position;
  223696. }
  223697. - (int) read: (char*) dest numBytes: (int) numNeeded
  223698. {
  223699. int numDone = 0;
  223700. while (numNeeded > 0)
  223701. {
  223702. int available = jmin (numNeeded, (int) [data length]);
  223703. if (available > 0)
  223704. {
  223705. [dataLock lock];
  223706. [data getBytes: dest length: available];
  223707. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223708. [dataLock unlock];
  223709. numDone += available;
  223710. numNeeded -= available;
  223711. dest += available;
  223712. }
  223713. else
  223714. {
  223715. if (hasFailed || hasFinished)
  223716. break;
  223717. Thread::sleep (1);
  223718. }
  223719. }
  223720. position += numDone;
  223721. return numDone;
  223722. }
  223723. - (void) stop
  223724. {
  223725. [connection cancel];
  223726. if (runLoopThread != 0)
  223727. runLoopThread->stopThread (10000);
  223728. }
  223729. @end
  223730. BEGIN_JUCE_NAMESPACE
  223731. class WebInputStream : public InputStream
  223732. {
  223733. public:
  223734. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  223735. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223736. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  223737. : connection (nil),
  223738. address (address_), headers (headers_), postData (postData_), position (0),
  223739. finished (false), isPost (isPost_), timeOutMs (timeOutMs_)
  223740. {
  223741. JUCE_AUTORELEASEPOOL
  223742. connection = createConnection (progressCallback, progressCallbackContext);
  223743. if (responseHeaders != 0 && connection != 0 && connection->headers != 0)
  223744. {
  223745. NSEnumerator* enumerator = [connection->headers keyEnumerator];
  223746. NSString* key;
  223747. while ((key = [enumerator nextObject]) != nil)
  223748. responseHeaders->set (nsStringToJuce (key),
  223749. nsStringToJuce ((NSString*) [connection->headers objectForKey: key]));
  223750. }
  223751. }
  223752. ~WebInputStream()
  223753. {
  223754. close();
  223755. }
  223756. bool isError() const { return connection == nil; }
  223757. int64 getTotalLength() { return connection == nil ? -1 : connection->contentLength; }
  223758. bool isExhausted() { return finished; }
  223759. int64 getPosition() { return position; }
  223760. int read (void* buffer, int bytesToRead)
  223761. {
  223762. if (finished || isError())
  223763. {
  223764. return 0;
  223765. }
  223766. else
  223767. {
  223768. JUCE_AUTORELEASEPOOL
  223769. const int bytesRead = [connection read: static_cast <char*> (buffer) numBytes: bytesToRead];
  223770. position += bytesRead;
  223771. if (bytesRead == 0)
  223772. finished = true;
  223773. return bytesRead;
  223774. }
  223775. }
  223776. bool setPosition (int64 wantedPos)
  223777. {
  223778. if (wantedPos != position)
  223779. {
  223780. finished = false;
  223781. if (wantedPos < position)
  223782. {
  223783. close();
  223784. position = 0;
  223785. connection = createConnection (0, 0);
  223786. }
  223787. skipNextBytes (wantedPos - position);
  223788. }
  223789. return true;
  223790. }
  223791. private:
  223792. JuceURLConnection* connection;
  223793. String address, headers;
  223794. MemoryBlock postData;
  223795. int64 position;
  223796. bool finished;
  223797. const bool isPost;
  223798. const int timeOutMs;
  223799. void close()
  223800. {
  223801. [connection stop];
  223802. [connection release];
  223803. connection = nil;
  223804. }
  223805. JuceURLConnection* createConnection (URL::OpenStreamProgressCallback* progressCallback,
  223806. void* progressCallbackContext)
  223807. {
  223808. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (address)]
  223809. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223810. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223811. if (req == nil)
  223812. return 0;
  223813. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223814. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223815. StringArray headerLines;
  223816. headerLines.addLines (headers);
  223817. headerLines.removeEmptyStrings (true);
  223818. for (int i = 0; i < headerLines.size(); ++i)
  223819. {
  223820. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  223821. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  223822. if (key.isNotEmpty() && value.isNotEmpty())
  223823. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223824. }
  223825. if (isPost && postData.getSize() > 0)
  223826. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223827. length: postData.getSize()]];
  223828. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223829. withCallback: progressCallback
  223830. withContext: progressCallbackContext];
  223831. if ([s isOpen])
  223832. return s;
  223833. [s release];
  223834. return 0;
  223835. }
  223836. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  223837. };
  223838. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  223839. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  223840. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  223841. {
  223842. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  223843. progressCallback, progressCallbackContext,
  223844. headers, timeOutMs, responseHeaders));
  223845. return wi->isError() ? 0 : wi.release();
  223846. }
  223847. #endif
  223848. /*** End of inlined file: juce_mac_Network.mm ***/
  223849. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  223850. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223851. // compiled on its own).
  223852. #if JUCE_INCLUDED_FILE
  223853. struct NamedPipeInternal
  223854. {
  223855. String pipeInName, pipeOutName;
  223856. int pipeIn, pipeOut;
  223857. bool volatile createdPipe, blocked, stopReadOperation;
  223858. static void signalHandler (int) {}
  223859. };
  223860. void NamedPipe::cancelPendingReads()
  223861. {
  223862. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  223863. {
  223864. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223865. intern->stopReadOperation = true;
  223866. char buffer [1] = { 0 };
  223867. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  223868. (void) bytesWritten;
  223869. int timeout = 2000;
  223870. while (intern->blocked && --timeout >= 0)
  223871. Thread::sleep (2);
  223872. intern->stopReadOperation = false;
  223873. }
  223874. }
  223875. void NamedPipe::close()
  223876. {
  223877. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223878. if (intern != 0)
  223879. {
  223880. internal = 0;
  223881. if (intern->pipeIn != -1)
  223882. ::close (intern->pipeIn);
  223883. if (intern->pipeOut != -1)
  223884. ::close (intern->pipeOut);
  223885. if (intern->createdPipe)
  223886. {
  223887. unlink (intern->pipeInName.toUTF8());
  223888. unlink (intern->pipeOutName.toUTF8());
  223889. }
  223890. delete intern;
  223891. }
  223892. }
  223893. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  223894. {
  223895. close();
  223896. NamedPipeInternal* const intern = new NamedPipeInternal();
  223897. internal = intern;
  223898. intern->createdPipe = createPipe;
  223899. intern->blocked = false;
  223900. intern->stopReadOperation = false;
  223901. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  223902. siginterrupt (SIGPIPE, 1);
  223903. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  223904. intern->pipeInName = pipePath + "_in";
  223905. intern->pipeOutName = pipePath + "_out";
  223906. intern->pipeIn = -1;
  223907. intern->pipeOut = -1;
  223908. if (createPipe)
  223909. {
  223910. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  223911. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  223912. {
  223913. delete intern;
  223914. internal = 0;
  223915. return false;
  223916. }
  223917. }
  223918. return true;
  223919. }
  223920. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  223921. {
  223922. int bytesRead = -1;
  223923. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223924. if (intern != 0)
  223925. {
  223926. intern->blocked = true;
  223927. if (intern->pipeIn == -1)
  223928. {
  223929. if (intern->createdPipe)
  223930. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  223931. else
  223932. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  223933. if (intern->pipeIn == -1)
  223934. {
  223935. intern->blocked = false;
  223936. return -1;
  223937. }
  223938. }
  223939. bytesRead = 0;
  223940. char* p = static_cast<char*> (destBuffer);
  223941. while (bytesRead < maxBytesToRead)
  223942. {
  223943. const int bytesThisTime = maxBytesToRead - bytesRead;
  223944. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  223945. if (numRead <= 0 || intern->stopReadOperation)
  223946. {
  223947. bytesRead = -1;
  223948. break;
  223949. }
  223950. bytesRead += numRead;
  223951. p += bytesRead;
  223952. }
  223953. intern->blocked = false;
  223954. }
  223955. return bytesRead;
  223956. }
  223957. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  223958. {
  223959. int bytesWritten = -1;
  223960. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  223961. if (intern != 0)
  223962. {
  223963. if (intern->pipeOut == -1)
  223964. {
  223965. if (intern->createdPipe)
  223966. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  223967. else
  223968. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  223969. if (intern->pipeOut == -1)
  223970. {
  223971. return -1;
  223972. }
  223973. }
  223974. const char* p = static_cast<const char*> (sourceBuffer);
  223975. bytesWritten = 0;
  223976. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  223977. while (bytesWritten < numBytesToWrite
  223978. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  223979. {
  223980. const int bytesThisTime = numBytesToWrite - bytesWritten;
  223981. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  223982. if (numWritten <= 0)
  223983. {
  223984. bytesWritten = -1;
  223985. break;
  223986. }
  223987. bytesWritten += numWritten;
  223988. p += bytesWritten;
  223989. }
  223990. }
  223991. return bytesWritten;
  223992. }
  223993. #endif
  223994. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  223995. /*** Start of inlined file: juce_mac_Threads.mm ***/
  223996. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223997. // compiled on its own).
  223998. #if JUCE_INCLUDED_FILE
  223999. /*
  224000. Note that a lot of methods that you'd expect to find in this file actually
  224001. live in juce_posix_SharedCode.h!
  224002. */
  224003. bool Process::isForegroundProcess()
  224004. {
  224005. #if JUCE_MAC
  224006. return [NSApp isActive];
  224007. #else
  224008. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224009. #endif
  224010. }
  224011. void Process::raisePrivilege()
  224012. {
  224013. jassertfalse;
  224014. }
  224015. void Process::lowerPrivilege()
  224016. {
  224017. jassertfalse;
  224018. }
  224019. void Process::terminate()
  224020. {
  224021. exit (0);
  224022. }
  224023. void Process::setPriority (ProcessPriority)
  224024. {
  224025. // xxx
  224026. }
  224027. #endif
  224028. /*** End of inlined file: juce_mac_Threads.mm ***/
  224029. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224030. /*
  224031. This file contains posix routines that are common to both the Linux and Mac builds.
  224032. It gets included directly in the cpp files for these platforms.
  224033. */
  224034. CriticalSection::CriticalSection() throw()
  224035. {
  224036. pthread_mutexattr_t atts;
  224037. pthread_mutexattr_init (&atts);
  224038. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224039. #if ! JUCE_ANDROID
  224040. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224041. #endif
  224042. pthread_mutex_init (&internal, &atts);
  224043. }
  224044. CriticalSection::~CriticalSection() throw()
  224045. {
  224046. pthread_mutex_destroy (&internal);
  224047. }
  224048. void CriticalSection::enter() const throw()
  224049. {
  224050. pthread_mutex_lock (&internal);
  224051. }
  224052. bool CriticalSection::tryEnter() const throw()
  224053. {
  224054. return pthread_mutex_trylock (&internal) == 0;
  224055. }
  224056. void CriticalSection::exit() const throw()
  224057. {
  224058. pthread_mutex_unlock (&internal);
  224059. }
  224060. class WaitableEventImpl
  224061. {
  224062. public:
  224063. WaitableEventImpl (const bool manualReset_)
  224064. : triggered (false),
  224065. manualReset (manualReset_)
  224066. {
  224067. pthread_cond_init (&condition, 0);
  224068. pthread_mutexattr_t atts;
  224069. pthread_mutexattr_init (&atts);
  224070. #if ! JUCE_ANDROID
  224071. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224072. #endif
  224073. pthread_mutex_init (&mutex, &atts);
  224074. }
  224075. ~WaitableEventImpl()
  224076. {
  224077. pthread_cond_destroy (&condition);
  224078. pthread_mutex_destroy (&mutex);
  224079. }
  224080. bool wait (const int timeOutMillisecs) throw()
  224081. {
  224082. pthread_mutex_lock (&mutex);
  224083. if (! triggered)
  224084. {
  224085. if (timeOutMillisecs < 0)
  224086. {
  224087. do
  224088. {
  224089. pthread_cond_wait (&condition, &mutex);
  224090. }
  224091. while (! triggered);
  224092. }
  224093. else
  224094. {
  224095. struct timeval now;
  224096. gettimeofday (&now, 0);
  224097. struct timespec time;
  224098. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  224099. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224100. if (time.tv_nsec >= 1000000000)
  224101. {
  224102. time.tv_nsec -= 1000000000;
  224103. time.tv_sec++;
  224104. }
  224105. do
  224106. {
  224107. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  224108. {
  224109. pthread_mutex_unlock (&mutex);
  224110. return false;
  224111. }
  224112. }
  224113. while (! triggered);
  224114. }
  224115. }
  224116. if (! manualReset)
  224117. triggered = false;
  224118. pthread_mutex_unlock (&mutex);
  224119. return true;
  224120. }
  224121. void signal() throw()
  224122. {
  224123. pthread_mutex_lock (&mutex);
  224124. triggered = true;
  224125. pthread_cond_broadcast (&condition);
  224126. pthread_mutex_unlock (&mutex);
  224127. }
  224128. void reset() throw()
  224129. {
  224130. pthread_mutex_lock (&mutex);
  224131. triggered = false;
  224132. pthread_mutex_unlock (&mutex);
  224133. }
  224134. private:
  224135. pthread_cond_t condition;
  224136. pthread_mutex_t mutex;
  224137. bool triggered;
  224138. const bool manualReset;
  224139. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  224140. };
  224141. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  224142. : internal (new WaitableEventImpl (manualReset))
  224143. {
  224144. }
  224145. WaitableEvent::~WaitableEvent() throw()
  224146. {
  224147. delete static_cast <WaitableEventImpl*> (internal);
  224148. }
  224149. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224150. {
  224151. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  224152. }
  224153. void WaitableEvent::signal() const throw()
  224154. {
  224155. static_cast <WaitableEventImpl*> (internal)->signal();
  224156. }
  224157. void WaitableEvent::reset() const throw()
  224158. {
  224159. static_cast <WaitableEventImpl*> (internal)->reset();
  224160. }
  224161. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  224162. {
  224163. struct timespec time;
  224164. time.tv_sec = millisecs / 1000;
  224165. time.tv_nsec = (millisecs % 1000) * 1000000;
  224166. nanosleep (&time, 0);
  224167. }
  224168. const juce_wchar File::separator = '/';
  224169. const String File::separatorString ("/");
  224170. const File File::getCurrentWorkingDirectory()
  224171. {
  224172. HeapBlock<char> heapBuffer;
  224173. char localBuffer [1024];
  224174. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  224175. int bufferSize = 4096;
  224176. while (cwd == 0 && errno == ERANGE)
  224177. {
  224178. heapBuffer.malloc (bufferSize);
  224179. cwd = getcwd (heapBuffer, bufferSize - 1);
  224180. bufferSize += 1024;
  224181. }
  224182. return File (String::fromUTF8 (cwd));
  224183. }
  224184. bool File::setAsCurrentWorkingDirectory() const
  224185. {
  224186. return chdir (getFullPathName().toUTF8()) == 0;
  224187. }
  224188. namespace
  224189. {
  224190. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224191. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  224192. #else
  224193. typedef struct stat juce_statStruct;
  224194. #endif
  224195. bool juce_stat (const String& fileName, juce_statStruct& info)
  224196. {
  224197. return fileName.isNotEmpty()
  224198. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224199. && (stat64 (fileName.toUTF8(), &info) == 0);
  224200. #else
  224201. && (stat (fileName.toUTF8(), &info) == 0);
  224202. #endif
  224203. }
  224204. // if this file doesn't exist, find a parent of it that does..
  224205. bool juce_doStatFS (File f, struct statfs& result)
  224206. {
  224207. for (int i = 5; --i >= 0;)
  224208. {
  224209. if (f.exists())
  224210. break;
  224211. f = f.getParentDirectory();
  224212. }
  224213. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224214. }
  224215. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  224216. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224217. {
  224218. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  224219. {
  224220. juce_statStruct info;
  224221. const bool statOk = juce_stat (path, info);
  224222. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  224223. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  224224. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  224225. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  224226. }
  224227. if (isReadOnly != 0)
  224228. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  224229. }
  224230. }
  224231. bool File::isDirectory() const
  224232. {
  224233. juce_statStruct info;
  224234. return fullPath.isEmpty()
  224235. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  224236. }
  224237. bool File::exists() const
  224238. {
  224239. juce_statStruct info;
  224240. return fullPath.isNotEmpty()
  224241. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  224242. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  224243. #else
  224244. && (lstat (fullPath.toUTF8(), &info) == 0);
  224245. #endif
  224246. }
  224247. bool File::existsAsFile() const
  224248. {
  224249. return exists() && ! isDirectory();
  224250. }
  224251. int64 File::getSize() const
  224252. {
  224253. juce_statStruct info;
  224254. return juce_stat (fullPath, info) ? info.st_size : 0;
  224255. }
  224256. bool File::hasWriteAccess() const
  224257. {
  224258. if (exists())
  224259. return access (fullPath.toUTF8(), W_OK) == 0;
  224260. if ((! isDirectory()) && fullPath.containsChar (separator))
  224261. return getParentDirectory().hasWriteAccess();
  224262. return false;
  224263. }
  224264. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  224265. {
  224266. juce_statStruct info;
  224267. if (! juce_stat (fullPath, info))
  224268. return false;
  224269. info.st_mode &= 0777; // Just permissions
  224270. if (shouldBeReadOnly)
  224271. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224272. else
  224273. // Give everybody write permission?
  224274. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224275. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  224276. }
  224277. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  224278. {
  224279. modificationTime = 0;
  224280. accessTime = 0;
  224281. creationTime = 0;
  224282. juce_statStruct info;
  224283. if (juce_stat (fullPath, info))
  224284. {
  224285. modificationTime = (int64) info.st_mtime * 1000;
  224286. accessTime = (int64) info.st_atime * 1000;
  224287. creationTime = (int64) info.st_ctime * 1000;
  224288. }
  224289. }
  224290. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  224291. {
  224292. juce_statStruct info;
  224293. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  224294. {
  224295. struct utimbuf times;
  224296. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  224297. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  224298. return utime (fullPath.toUTF8(), &times) == 0;
  224299. }
  224300. return false;
  224301. }
  224302. bool File::deleteFile() const
  224303. {
  224304. if (! exists())
  224305. return true;
  224306. if (isDirectory())
  224307. return rmdir (fullPath.toUTF8()) == 0;
  224308. return remove (fullPath.toUTF8()) == 0;
  224309. }
  224310. bool File::moveInternal (const File& dest) const
  224311. {
  224312. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  224313. return true;
  224314. if (hasWriteAccess() && copyInternal (dest))
  224315. {
  224316. if (deleteFile())
  224317. return true;
  224318. dest.deleteFile();
  224319. }
  224320. return false;
  224321. }
  224322. void File::createDirectoryInternal (const String& fileName) const
  224323. {
  224324. mkdir (fileName.toUTF8(), 0777);
  224325. }
  224326. int64 juce_fileSetPosition (void* handle, int64 pos)
  224327. {
  224328. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224329. return pos;
  224330. return -1;
  224331. }
  224332. void FileInputStream::openHandle()
  224333. {
  224334. totalSize = file.getSize();
  224335. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  224336. if (f != -1)
  224337. fileHandle = (void*) f;
  224338. }
  224339. void FileInputStream::closeHandle()
  224340. {
  224341. if (fileHandle != 0)
  224342. {
  224343. close ((int) (pointer_sized_int) fileHandle);
  224344. fileHandle = 0;
  224345. }
  224346. }
  224347. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  224348. {
  224349. if (fileHandle != 0)
  224350. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  224351. return 0;
  224352. }
  224353. void FileOutputStream::openHandle()
  224354. {
  224355. if (file.exists())
  224356. {
  224357. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  224358. if (f != -1)
  224359. {
  224360. currentPosition = lseek (f, 0, SEEK_END);
  224361. if (currentPosition >= 0)
  224362. fileHandle = (void*) f;
  224363. else
  224364. close (f);
  224365. }
  224366. }
  224367. else
  224368. {
  224369. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  224370. if (f != -1)
  224371. fileHandle = (void*) f;
  224372. }
  224373. }
  224374. void FileOutputStream::closeHandle()
  224375. {
  224376. if (fileHandle != 0)
  224377. {
  224378. close ((int) (pointer_sized_int) fileHandle);
  224379. fileHandle = 0;
  224380. }
  224381. }
  224382. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  224383. {
  224384. if (fileHandle != 0)
  224385. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  224386. return 0;
  224387. }
  224388. void FileOutputStream::flushInternal()
  224389. {
  224390. if (fileHandle != 0)
  224391. fsync ((int) (pointer_sized_int) fileHandle);
  224392. }
  224393. const File juce_getExecutableFile()
  224394. {
  224395. #if JUCE_ANDROID
  224396. // TODO
  224397. return File::nonexistent;
  224398. #else
  224399. Dl_info exeInfo;
  224400. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  224401. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  224402. #endif
  224403. }
  224404. int64 File::getBytesFreeOnVolume() const
  224405. {
  224406. struct statfs buf;
  224407. if (juce_doStatFS (*this, buf))
  224408. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  224409. return 0;
  224410. }
  224411. int64 File::getVolumeTotalSize() const
  224412. {
  224413. struct statfs buf;
  224414. if (juce_doStatFS (*this, buf))
  224415. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  224416. return 0;
  224417. }
  224418. const String File::getVolumeLabel() const
  224419. {
  224420. #if JUCE_MAC
  224421. struct VolAttrBuf
  224422. {
  224423. u_int32_t length;
  224424. attrreference_t mountPointRef;
  224425. char mountPointSpace [MAXPATHLEN];
  224426. } attrBuf;
  224427. struct attrlist attrList;
  224428. zerostruct (attrList);
  224429. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  224430. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  224431. File f (*this);
  224432. for (;;)
  224433. {
  224434. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  224435. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  224436. (int) attrBuf.mountPointRef.attr_length);
  224437. const File parent (f.getParentDirectory());
  224438. if (f == parent)
  224439. break;
  224440. f = parent;
  224441. }
  224442. #endif
  224443. return String::empty;
  224444. }
  224445. int File::getVolumeSerialNumber() const
  224446. {
  224447. int result = 0;
  224448. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  224449. char info [512];
  224450. #ifndef HDIO_GET_IDENTITY
  224451. #define HDIO_GET_IDENTITY 0x030d
  224452. #endif
  224453. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  224454. {
  224455. DBG (String (info + 20, 20));
  224456. result = String (info + 20, 20).trim().getIntValue();
  224457. }
  224458. close (fd);*/
  224459. return result;
  224460. }
  224461. void juce_runSystemCommand (const String& command)
  224462. {
  224463. int result = system (command.toUTF8());
  224464. (void) result;
  224465. }
  224466. const String juce_getOutputFromCommand (const String& command)
  224467. {
  224468. // slight bodge here, as we just pipe the output into a temp file and read it...
  224469. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  224470. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  224471. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  224472. String result (tempFile.loadFileAsString());
  224473. tempFile.deleteFile();
  224474. return result;
  224475. }
  224476. class InterProcessLock::Pimpl
  224477. {
  224478. public:
  224479. Pimpl (const String& name, const int timeOutMillisecs)
  224480. : handle (0), refCount (1)
  224481. {
  224482. #if JUCE_MAC
  224483. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224484. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  224485. #else
  224486. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224487. #endif
  224488. temp.create();
  224489. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  224490. if (handle != 0)
  224491. {
  224492. struct flock fl;
  224493. zerostruct (fl);
  224494. fl.l_whence = SEEK_SET;
  224495. fl.l_type = F_WRLCK;
  224496. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224497. for (;;)
  224498. {
  224499. const int result = fcntl (handle, F_SETLK, &fl);
  224500. if (result >= 0)
  224501. return;
  224502. if (errno != EINTR)
  224503. {
  224504. if (timeOutMillisecs == 0
  224505. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224506. break;
  224507. Thread::sleep (10);
  224508. }
  224509. }
  224510. }
  224511. closeFile();
  224512. }
  224513. ~Pimpl()
  224514. {
  224515. closeFile();
  224516. }
  224517. void closeFile()
  224518. {
  224519. if (handle != 0)
  224520. {
  224521. struct flock fl;
  224522. zerostruct (fl);
  224523. fl.l_whence = SEEK_SET;
  224524. fl.l_type = F_UNLCK;
  224525. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  224526. {}
  224527. close (handle);
  224528. handle = 0;
  224529. }
  224530. }
  224531. int handle, refCount;
  224532. };
  224533. InterProcessLock::InterProcessLock (const String& name_)
  224534. : name (name_)
  224535. {
  224536. }
  224537. InterProcessLock::~InterProcessLock()
  224538. {
  224539. }
  224540. bool InterProcessLock::enter (const int timeOutMillisecs)
  224541. {
  224542. const ScopedLock sl (lock);
  224543. if (pimpl == 0)
  224544. {
  224545. pimpl = new Pimpl (name, timeOutMillisecs);
  224546. if (pimpl->handle == 0)
  224547. pimpl = 0;
  224548. }
  224549. else
  224550. {
  224551. pimpl->refCount++;
  224552. }
  224553. return pimpl != 0;
  224554. }
  224555. void InterProcessLock::exit()
  224556. {
  224557. const ScopedLock sl (lock);
  224558. // Trying to release the lock too many times!
  224559. jassert (pimpl != 0);
  224560. if (pimpl != 0 && --(pimpl->refCount) == 0)
  224561. pimpl = 0;
  224562. }
  224563. void JUCE_API juce_threadEntryPoint (void*);
  224564. void* threadEntryProc (void* userData)
  224565. {
  224566. JUCE_AUTORELEASEPOOL
  224567. juce_threadEntryPoint (userData);
  224568. return 0;
  224569. }
  224570. void Thread::launchThread()
  224571. {
  224572. threadHandle_ = 0;
  224573. pthread_t handle = 0;
  224574. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  224575. {
  224576. pthread_detach (handle);
  224577. threadHandle_ = (void*) handle;
  224578. threadId_ = (ThreadID) threadHandle_;
  224579. }
  224580. }
  224581. void Thread::closeThreadHandle()
  224582. {
  224583. threadId_ = 0;
  224584. threadHandle_ = 0;
  224585. }
  224586. void Thread::killThread()
  224587. {
  224588. if (threadHandle_ != 0)
  224589. {
  224590. #if JUCE_ANDROID
  224591. jassertfalse; // pthread_cancel not available!
  224592. #else
  224593. pthread_cancel ((pthread_t) threadHandle_);
  224594. #endif
  224595. }
  224596. }
  224597. void Thread::setCurrentThreadName (const String& /*name*/)
  224598. {
  224599. }
  224600. bool Thread::setThreadPriority (void* handle, int priority)
  224601. {
  224602. struct sched_param param;
  224603. int policy;
  224604. priority = jlimit (0, 10, priority);
  224605. if (handle == 0)
  224606. handle = (void*) pthread_self();
  224607. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  224608. return false;
  224609. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  224610. const int minPriority = sched_get_priority_min (policy);
  224611. const int maxPriority = sched_get_priority_max (policy);
  224612. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  224613. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  224614. }
  224615. Thread::ThreadID Thread::getCurrentThreadId()
  224616. {
  224617. return (ThreadID) pthread_self();
  224618. }
  224619. void Thread::yield()
  224620. {
  224621. sched_yield();
  224622. }
  224623. /* Remove this macro if you're having problems compiling the cpu affinity
  224624. calls (the API for these has changed about quite a bit in various Linux
  224625. versions, and a lot of distros seem to ship with obsolete versions)
  224626. */
  224627. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  224628. #define SUPPORT_AFFINITIES 1
  224629. #endif
  224630. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  224631. {
  224632. #if SUPPORT_AFFINITIES
  224633. cpu_set_t affinity;
  224634. CPU_ZERO (&affinity);
  224635. for (int i = 0; i < 32; ++i)
  224636. if ((affinityMask & (1 << i)) != 0)
  224637. CPU_SET (i, &affinity);
  224638. /*
  224639. N.B. If this line causes a compile error, then you've probably not got the latest
  224640. version of glibc installed.
  224641. If you don't want to update your copy of glibc and don't care about cpu affinities,
  224642. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  224643. */
  224644. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  224645. sched_yield();
  224646. #else
  224647. /* affinities aren't supported because either the appropriate header files weren't found,
  224648. or the SUPPORT_AFFINITIES macro was turned off
  224649. */
  224650. jassertfalse;
  224651. (void) affinityMask;
  224652. #endif
  224653. }
  224654. /*** End of inlined file: juce_posix_SharedCode.h ***/
  224655. /*** Start of inlined file: juce_mac_Files.mm ***/
  224656. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224657. // compiled on its own).
  224658. #if JUCE_INCLUDED_FILE
  224659. /*
  224660. Note that a lot of methods that you'd expect to find in this file actually
  224661. live in juce_posix_SharedCode.h!
  224662. */
  224663. bool File::copyInternal (const File& dest) const
  224664. {
  224665. const ScopedAutoReleasePool pool;
  224666. NSFileManager* fm = [NSFileManager defaultManager];
  224667. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  224668. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  224669. && [fm copyItemAtPath: juceStringToNS (fullPath)
  224670. toPath: juceStringToNS (dest.getFullPathName())
  224671. error: nil];
  224672. #else
  224673. && [fm copyPath: juceStringToNS (fullPath)
  224674. toPath: juceStringToNS (dest.getFullPathName())
  224675. handler: nil];
  224676. #endif
  224677. }
  224678. void File::findFileSystemRoots (Array<File>& destArray)
  224679. {
  224680. destArray.add (File ("/"));
  224681. }
  224682. namespace FileHelpers
  224683. {
  224684. bool isFileOnDriveType (const File& f, const char* const* types)
  224685. {
  224686. struct statfs buf;
  224687. if (juce_doStatFS (f, buf))
  224688. {
  224689. const String type (buf.f_fstypename);
  224690. while (*types != 0)
  224691. if (type.equalsIgnoreCase (*types++))
  224692. return true;
  224693. }
  224694. return false;
  224695. }
  224696. bool isHiddenFile (const String& path)
  224697. {
  224698. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  224699. const ScopedAutoReleasePool pool;
  224700. NSNumber* hidden = nil;
  224701. NSError* err = nil;
  224702. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  224703. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  224704. && [hidden boolValue];
  224705. #else
  224706. #if JUCE_IOS
  224707. return File (path).getFileName().startsWithChar ('.');
  224708. #else
  224709. FSRef ref;
  224710. LSItemInfoRecord info;
  224711. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8().getAddress(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  224712. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  224713. && (info.flags & kLSItemInfoIsInvisible) != 0;
  224714. #endif
  224715. #endif
  224716. }
  224717. #if JUCE_IOS
  224718. const String getIOSSystemLocation (NSSearchPathDirectory type)
  224719. {
  224720. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  224721. objectAtIndex: 0]);
  224722. }
  224723. #endif
  224724. bool launchExecutable (const String& pathAndArguments)
  224725. {
  224726. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  224727. const int cpid = fork();
  224728. if (cpid == 0)
  224729. {
  224730. // Child process
  224731. if (execve (argv[0], (char**) argv, 0) < 0)
  224732. exit (0);
  224733. }
  224734. else
  224735. {
  224736. if (cpid < 0)
  224737. return false;
  224738. }
  224739. return true;
  224740. }
  224741. }
  224742. bool File::isOnCDRomDrive() const
  224743. {
  224744. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224745. return FileHelpers::isFileOnDriveType (*this, cdTypes);
  224746. }
  224747. bool File::isOnHardDisk() const
  224748. {
  224749. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224750. return ! (isOnCDRomDrive() || FileHelpers::isFileOnDriveType (*this, nonHDTypes));
  224751. }
  224752. bool File::isOnRemovableDrive() const
  224753. {
  224754. #if JUCE_IOS
  224755. return false; // xxx is this possible?
  224756. #else
  224757. const ScopedAutoReleasePool pool;
  224758. BOOL removable = false;
  224759. [[NSWorkspace sharedWorkspace]
  224760. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  224761. isRemovable: &removable
  224762. isWritable: nil
  224763. isUnmountable: nil
  224764. description: nil
  224765. type: nil];
  224766. return removable;
  224767. #endif
  224768. }
  224769. bool File::isHidden() const
  224770. {
  224771. return FileHelpers::isHiddenFile (getFullPathName());
  224772. }
  224773. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  224774. const File File::getSpecialLocation (const SpecialLocationType type)
  224775. {
  224776. const ScopedAutoReleasePool pool;
  224777. String resultPath;
  224778. switch (type)
  224779. {
  224780. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  224781. #if JUCE_IOS
  224782. case userDocumentsDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDocumentDirectory); break;
  224783. case userDesktopDirectory: resultPath = FileHelpers::getIOSSystemLocation (NSDesktopDirectory); break;
  224784. case tempDirectory:
  224785. {
  224786. File tmp (FileHelpers::getIOSSystemLocation (NSCachesDirectory));
  224787. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  224788. tmp.createDirectory();
  224789. return tmp.getFullPathName();
  224790. }
  224791. #else
  224792. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  224793. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  224794. case tempDirectory:
  224795. {
  224796. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  224797. tmp.createDirectory();
  224798. return tmp.getFullPathName();
  224799. }
  224800. #endif
  224801. case userMusicDirectory: resultPath = "~/Music"; break;
  224802. case userMoviesDirectory: resultPath = "~/Movies"; break;
  224803. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  224804. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  224805. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  224806. case invokedExecutableFile:
  224807. if (juce_Argv0 != 0)
  224808. return File (String::fromUTF8 (juce_Argv0));
  224809. // deliberate fall-through...
  224810. case currentExecutableFile:
  224811. return juce_getExecutableFile();
  224812. case currentApplicationFile:
  224813. {
  224814. const File exe (juce_getExecutableFile());
  224815. const File parent (exe.getParentDirectory());
  224816. #if JUCE_IOS
  224817. return parent;
  224818. #else
  224819. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  224820. ? parent.getParentDirectory().getParentDirectory()
  224821. : exe;
  224822. #endif
  224823. }
  224824. case hostApplicationPath:
  224825. {
  224826. unsigned int size = 8192;
  224827. HeapBlock<char> buffer;
  224828. buffer.calloc (size + 8);
  224829. _NSGetExecutablePath (buffer.getData(), &size);
  224830. return String::fromUTF8 (buffer, size);
  224831. }
  224832. default:
  224833. jassertfalse; // unknown type?
  224834. break;
  224835. }
  224836. if (resultPath.isNotEmpty())
  224837. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224838. return File::nonexistent;
  224839. }
  224840. const String File::getVersion() const
  224841. {
  224842. const ScopedAutoReleasePool pool;
  224843. String result;
  224844. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  224845. if (bundle != 0)
  224846. {
  224847. NSDictionary* info = [bundle infoDictionary];
  224848. if (info != 0)
  224849. {
  224850. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  224851. if (name != nil)
  224852. result = nsStringToJuce (name);
  224853. }
  224854. }
  224855. return result;
  224856. }
  224857. const File File::getLinkedTarget() const
  224858. {
  224859. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  224860. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  224861. #else
  224862. // (the cast here avoids a deprecation warning)
  224863. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  224864. #endif
  224865. if (dest != nil)
  224866. return File (nsStringToJuce (dest));
  224867. return *this;
  224868. }
  224869. bool File::moveToTrash() const
  224870. {
  224871. if (! exists())
  224872. return true;
  224873. #if JUCE_IOS
  224874. return deleteFile(); //xxx is there a trashcan on the iPhone?
  224875. #else
  224876. const ScopedAutoReleasePool pool;
  224877. NSString* p = juceStringToNS (getFullPathName());
  224878. return [[NSWorkspace sharedWorkspace]
  224879. performFileOperation: NSWorkspaceRecycleOperation
  224880. source: [p stringByDeletingLastPathComponent]
  224881. destination: @""
  224882. files: [NSArray arrayWithObject: [p lastPathComponent]]
  224883. tag: nil ];
  224884. #endif
  224885. }
  224886. class DirectoryIterator::NativeIterator::Pimpl
  224887. {
  224888. public:
  224889. Pimpl (const File& directory, const String& wildCard_)
  224890. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  224891. wildCard (wildCard_),
  224892. enumerator (0)
  224893. {
  224894. const ScopedAutoReleasePool pool;
  224895. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  224896. wildcardUTF8 = wildCard.toUTF8();
  224897. }
  224898. ~Pimpl()
  224899. {
  224900. [enumerator release];
  224901. }
  224902. bool next (String& filenameFound,
  224903. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224904. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224905. {
  224906. const ScopedAutoReleasePool pool;
  224907. for (;;)
  224908. {
  224909. NSString* file;
  224910. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  224911. return false;
  224912. [enumerator skipDescendents];
  224913. filenameFound = nsStringToJuce (file);
  224914. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  224915. continue;
  224916. const String path (parentDir + filenameFound);
  224917. updateStatInfoForFile (path, isDir, fileSize, modTime, creationTime, isReadOnly);
  224918. if (isHidden != 0)
  224919. *isHidden = FileHelpers::isHiddenFile (path);
  224920. return true;
  224921. }
  224922. }
  224923. private:
  224924. String parentDir, wildCard;
  224925. const char* wildcardUTF8;
  224926. NSDirectoryEnumerator* enumerator;
  224927. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  224928. };
  224929. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  224930. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  224931. {
  224932. }
  224933. DirectoryIterator::NativeIterator::~NativeIterator()
  224934. {
  224935. }
  224936. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  224937. bool* const isDir, bool* const isHidden, int64* const fileSize,
  224938. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  224939. {
  224940. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224941. }
  224942. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  224943. {
  224944. #if JUCE_IOS
  224945. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  224946. #else
  224947. const ScopedAutoReleasePool pool;
  224948. if (parameters.isEmpty())
  224949. {
  224950. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  224951. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  224952. }
  224953. bool ok = false;
  224954. if (PlatformUtilities::isBundle (fileName))
  224955. {
  224956. NSMutableArray* urls = [NSMutableArray array];
  224957. StringArray docs;
  224958. docs.addTokens (parameters, true);
  224959. for (int i = 0; i < docs.size(); ++i)
  224960. [urls addObject: juceStringToNS (docs[i])];
  224961. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224962. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224963. options: 0
  224964. additionalEventParamDescriptor: nil
  224965. launchIdentifiers: nil];
  224966. }
  224967. else if (File (fileName).exists())
  224968. {
  224969. ok = FileHelpers::launchExecutable ("\"" + fileName + "\" " + parameters);
  224970. }
  224971. return ok;
  224972. #endif
  224973. }
  224974. void File::revealToUser() const
  224975. {
  224976. #if ! JUCE_IOS
  224977. if (exists())
  224978. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  224979. else if (getParentDirectory().exists())
  224980. getParentDirectory().revealToUser();
  224981. #endif
  224982. }
  224983. #if ! JUCE_IOS
  224984. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224985. {
  224986. return FSPathMakeRef (reinterpret_cast <const UInt8*> (path.toUTF8().getAddress()), destFSRef, 0) == noErr;
  224987. }
  224988. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224989. {
  224990. char path [2048];
  224991. zerostruct (path);
  224992. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224993. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  224994. return String::empty;
  224995. }
  224996. #endif
  224997. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224998. {
  224999. const ScopedAutoReleasePool pool;
  225000. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225001. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225002. #else
  225003. // (the cast here avoids a deprecation warning)
  225004. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225005. #endif
  225006. return [fileDict fileHFSTypeCode];
  225007. }
  225008. bool PlatformUtilities::isBundle (const String& filename)
  225009. {
  225010. #if JUCE_IOS
  225011. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225012. #else
  225013. const ScopedAutoReleasePool pool;
  225014. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225015. #endif
  225016. }
  225017. #endif
  225018. /*** End of inlined file: juce_mac_Files.mm ***/
  225019. #if JUCE_IOS
  225020. /*** Start of inlined file: juce_ios_MiscUtilities.mm ***/
  225021. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225022. // compiled on its own).
  225023. #if JUCE_INCLUDED_FILE
  225024. END_JUCE_NAMESPACE
  225025. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225026. {
  225027. }
  225028. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225029. - (void) applicationWillTerminate: (UIApplication*) application;
  225030. @end
  225031. @implementation JuceAppStartupDelegate
  225032. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225033. {
  225034. initialiseJuce_GUI();
  225035. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225036. exit (0);
  225037. }
  225038. - (void) applicationWillTerminate: (UIApplication*) application
  225039. {
  225040. JUCEApplication::appWillTerminateByForce();
  225041. }
  225042. @end
  225043. BEGIN_JUCE_NAMESPACE
  225044. int juce_iOSMain (int argc, const char* argv[])
  225045. {
  225046. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225047. }
  225048. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225049. {
  225050. pool = [[NSAutoreleasePool alloc] init];
  225051. }
  225052. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225053. {
  225054. [((NSAutoreleasePool*) pool) release];
  225055. }
  225056. void PlatformUtilities::beep()
  225057. {
  225058. //xxx
  225059. //AudioServicesPlaySystemSound ();
  225060. }
  225061. void PlatformUtilities::addItemToDock (const File& file)
  225062. {
  225063. }
  225064. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225065. END_JUCE_NAMESPACE
  225066. @interface JuceAlertBoxDelegate : NSObject
  225067. {
  225068. @public
  225069. bool clickedOk;
  225070. }
  225071. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225072. @end
  225073. @implementation JuceAlertBoxDelegate
  225074. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225075. {
  225076. clickedOk = (buttonIndex == 0);
  225077. alertView.hidden = true;
  225078. }
  225079. @end
  225080. BEGIN_JUCE_NAMESPACE
  225081. // (This function is used directly by other bits of code)
  225082. bool juce_iPhoneShowModalAlert (const String& title,
  225083. const String& bodyText,
  225084. NSString* okButtonText,
  225085. NSString* cancelButtonText)
  225086. {
  225087. const ScopedAutoReleasePool pool;
  225088. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225089. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225090. message: juceStringToNS (bodyText)
  225091. delegate: callback
  225092. cancelButtonTitle: okButtonText
  225093. otherButtonTitles: cancelButtonText, nil];
  225094. [alert retain];
  225095. [alert show];
  225096. while (! alert.hidden && alert.superview != nil)
  225097. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225098. const bool result = callback->clickedOk;
  225099. [alert release];
  225100. [callback release];
  225101. return result;
  225102. }
  225103. bool AlertWindow::showNativeDialogBox (const String& title,
  225104. const String& bodyText,
  225105. bool isOkCancel)
  225106. {
  225107. return juce_iPhoneShowModalAlert (title, bodyText,
  225108. @"OK",
  225109. isOkCancel ? @"Cancel" : nil);
  225110. }
  225111. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225112. {
  225113. jassertfalse; // no such thing on the iphone!
  225114. return false;
  225115. }
  225116. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225117. {
  225118. jassertfalse; // no such thing on the iphone!
  225119. return false;
  225120. }
  225121. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225122. {
  225123. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225124. }
  225125. bool Desktop::isScreenSaverEnabled()
  225126. {
  225127. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225128. }
  225129. #endif
  225130. #endif
  225131. /*** End of inlined file: juce_ios_MiscUtilities.mm ***/
  225132. #else
  225133. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225134. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225135. // compiled on its own).
  225136. #if JUCE_INCLUDED_FILE
  225137. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225138. {
  225139. pool = [[NSAutoreleasePool alloc] init];
  225140. }
  225141. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225142. {
  225143. [((NSAutoreleasePool*) pool) release];
  225144. }
  225145. void PlatformUtilities::beep()
  225146. {
  225147. NSBeep();
  225148. }
  225149. void PlatformUtilities::addItemToDock (const File& file)
  225150. {
  225151. // check that it's not already there...
  225152. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  225153. .containsIgnoreCase (file.getFullPathName()))
  225154. {
  225155. 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>"
  225156. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  225157. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  225158. }
  225159. }
  225160. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225161. bool AlertWindow::showNativeDialogBox (const String& title,
  225162. const String& bodyText,
  225163. bool isOkCancel)
  225164. {
  225165. const ScopedAutoReleasePool pool;
  225166. return NSRunAlertPanel (juceStringToNS (title),
  225167. juceStringToNS (bodyText),
  225168. @"Ok",
  225169. isOkCancel ? @"Cancel" : nil,
  225170. nil) == NSAlertDefaultReturn;
  225171. }
  225172. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  225173. {
  225174. if (files.size() == 0)
  225175. return false;
  225176. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  225177. if (draggingSource == 0)
  225178. {
  225179. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225180. return false;
  225181. }
  225182. Component* sourceComp = draggingSource->getComponentUnderMouse();
  225183. if (sourceComp == 0)
  225184. {
  225185. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  225186. return false;
  225187. }
  225188. const ScopedAutoReleasePool pool;
  225189. NSView* view = (NSView*) sourceComp->getWindowHandle();
  225190. if (view == 0)
  225191. return false;
  225192. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  225193. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  225194. owner: nil];
  225195. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  225196. for (int i = 0; i < files.size(); ++i)
  225197. [filesArray addObject: juceStringToNS (files[i])];
  225198. [pboard setPropertyList: filesArray
  225199. forType: NSFilenamesPboardType];
  225200. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  225201. fromView: nil];
  225202. dragPosition.x -= 16;
  225203. dragPosition.y -= 16;
  225204. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  225205. at: dragPosition
  225206. offset: NSMakeSize (0, 0)
  225207. event: [[view window] currentEvent]
  225208. pasteboard: pboard
  225209. source: view
  225210. slideBack: YES];
  225211. return true;
  225212. }
  225213. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  225214. {
  225215. jassertfalse; // not implemented!
  225216. return false;
  225217. }
  225218. bool Desktop::canUseSemiTransparentWindows() throw()
  225219. {
  225220. return true;
  225221. }
  225222. const Point<int> MouseInputSource::getCurrentMousePosition()
  225223. {
  225224. const ScopedAutoReleasePool pool;
  225225. const NSPoint p ([NSEvent mouseLocation]);
  225226. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  225227. }
  225228. void Desktop::setMousePosition (const Point<int>& newPosition)
  225229. {
  225230. // this rubbish needs to be done around the warp call, to avoid causing a
  225231. // bizarre glitch..
  225232. CGAssociateMouseAndMouseCursorPosition (false);
  225233. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  225234. CGAssociateMouseAndMouseCursorPosition (true);
  225235. }
  225236. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  225237. {
  225238. return upright;
  225239. }
  225240. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225241. class ScreenSaverDefeater : public Timer,
  225242. public DeletedAtShutdown
  225243. {
  225244. public:
  225245. ScreenSaverDefeater()
  225246. {
  225247. startTimer (10000);
  225248. timerCallback();
  225249. }
  225250. ~ScreenSaverDefeater() {}
  225251. void timerCallback()
  225252. {
  225253. if (Process::isForegroundProcess())
  225254. UpdateSystemActivity (UsrActivity);
  225255. }
  225256. };
  225257. static ScreenSaverDefeater* screenSaverDefeater = 0;
  225258. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225259. {
  225260. if (isEnabled)
  225261. deleteAndZero (screenSaverDefeater);
  225262. else if (screenSaverDefeater == 0)
  225263. screenSaverDefeater = new ScreenSaverDefeater();
  225264. }
  225265. bool Desktop::isScreenSaverEnabled()
  225266. {
  225267. return screenSaverDefeater == 0;
  225268. }
  225269. #else
  225270. static IOPMAssertionID screenSaverDisablerID = 0;
  225271. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225272. {
  225273. if (isEnabled)
  225274. {
  225275. if (screenSaverDisablerID != 0)
  225276. {
  225277. IOPMAssertionRelease (screenSaverDisablerID);
  225278. screenSaverDisablerID = 0;
  225279. }
  225280. }
  225281. else
  225282. {
  225283. if (screenSaverDisablerID == 0)
  225284. {
  225285. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225286. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225287. CFSTR ("Juce"), &screenSaverDisablerID);
  225288. #else
  225289. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  225290. &screenSaverDisablerID);
  225291. #endif
  225292. }
  225293. }
  225294. }
  225295. bool Desktop::isScreenSaverEnabled()
  225296. {
  225297. return screenSaverDisablerID == 0;
  225298. }
  225299. #endif
  225300. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  225301. {
  225302. const ScopedAutoReleasePool pool;
  225303. monitorCoords.clear();
  225304. NSArray* screens = [NSScreen screens];
  225305. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  225306. for (unsigned int i = 0; i < [screens count]; ++i)
  225307. {
  225308. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  225309. NSRect r = clipToWorkArea ? [s visibleFrame]
  225310. : [s frame];
  225311. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  225312. monitorCoords.add (convertToRectInt (r));
  225313. }
  225314. jassert (monitorCoords.size() > 0);
  225315. }
  225316. #endif
  225317. #endif
  225318. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  225319. #endif
  225320. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  225321. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225322. // compiled on its own).
  225323. #if JUCE_INCLUDED_FILE
  225324. void Logger::outputDebugString (const String& text)
  225325. {
  225326. std::cerr << text << std::endl;
  225327. }
  225328. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  225329. {
  225330. static char testResult = 0;
  225331. if (testResult == 0)
  225332. {
  225333. struct kinfo_proc info;
  225334. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  225335. size_t sz = sizeof (info);
  225336. sysctl (m, 4, &info, &sz, 0, 0);
  225337. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  225338. }
  225339. return testResult > 0;
  225340. }
  225341. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  225342. {
  225343. return juce_isRunningUnderDebugger();
  225344. }
  225345. #endif
  225346. /*** End of inlined file: juce_mac_Debugging.mm ***/
  225347. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225348. #if JUCE_IOS
  225349. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  225350. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225351. // compiled on its own).
  225352. #if JUCE_INCLUDED_FILE
  225353. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  225354. #define SUPPORT_10_4_FONTS 1
  225355. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  225356. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  225357. #define SUPPORT_ONLY_10_4_FONTS 1
  225358. #endif
  225359. END_JUCE_NAMESPACE
  225360. @interface NSFont (PrivateHack)
  225361. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  225362. @end
  225363. BEGIN_JUCE_NAMESPACE
  225364. #endif
  225365. class MacTypeface : public Typeface
  225366. {
  225367. public:
  225368. MacTypeface (const Font& font)
  225369. : Typeface (font.getTypefaceName())
  225370. {
  225371. const ScopedAutoReleasePool pool;
  225372. renderingTransform = CGAffineTransformIdentity;
  225373. bool needsItalicTransform = false;
  225374. #if JUCE_IOS
  225375. NSString* fontName = juceStringToNS (font.getTypefaceName());
  225376. if (font.isItalic() || font.isBold())
  225377. {
  225378. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  225379. for (NSString* i in familyFonts)
  225380. {
  225381. const String fn (nsStringToJuce (i));
  225382. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  225383. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  225384. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  225385. || afterDash.containsIgnoreCase ("italic")
  225386. || fn.endsWithIgnoreCase ("oblique")
  225387. || fn.endsWithIgnoreCase ("italic");
  225388. if (probablyBold == font.isBold()
  225389. && probablyItalic == font.isItalic())
  225390. {
  225391. fontName = i;
  225392. needsItalicTransform = false;
  225393. break;
  225394. }
  225395. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  225396. {
  225397. fontName = i;
  225398. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  225399. }
  225400. }
  225401. if (needsItalicTransform)
  225402. renderingTransform.c = 0.15f;
  225403. }
  225404. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  225405. const int ascender = abs (CGFontGetAscent (fontRef));
  225406. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  225407. ascent = ascender / totalHeight;
  225408. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225409. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  225410. #else
  225411. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  225412. if (font.isItalic())
  225413. {
  225414. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  225415. toHaveTrait: NSItalicFontMask];
  225416. if (newFont == nsFont)
  225417. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  225418. nsFont = newFont;
  225419. }
  225420. if (font.isBold())
  225421. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  225422. [nsFont retain];
  225423. ascent = std::abs ((float) [nsFont ascender]);
  225424. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  225425. ascent /= totalSize;
  225426. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  225427. if (needsItalicTransform)
  225428. {
  225429. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  225430. renderingTransform.c = 0.15f;
  225431. }
  225432. #if SUPPORT_ONLY_10_4_FONTS
  225433. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225434. if (atsFont == 0)
  225435. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225436. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225437. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225438. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225439. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225440. #else
  225441. #if SUPPORT_10_4_FONTS
  225442. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225443. {
  225444. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225445. if (atsFont == 0)
  225446. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  225447. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  225448. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  225449. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225450. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  225451. }
  225452. else
  225453. #endif
  225454. {
  225455. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  225456. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  225457. unitsToHeightScaleFactor = 1.0f / totalHeight;
  225458. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  225459. }
  225460. #endif
  225461. #endif
  225462. }
  225463. ~MacTypeface()
  225464. {
  225465. #if ! JUCE_IOS
  225466. [nsFont release];
  225467. #endif
  225468. if (fontRef != 0)
  225469. CGFontRelease (fontRef);
  225470. }
  225471. float getAscent() const
  225472. {
  225473. return ascent;
  225474. }
  225475. float getDescent() const
  225476. {
  225477. return 1.0f - ascent;
  225478. }
  225479. float getStringWidth (const String& text)
  225480. {
  225481. if (fontRef == 0 || text.isEmpty())
  225482. return 0;
  225483. const int length = text.length();
  225484. HeapBlock <CGGlyph> glyphs;
  225485. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225486. float x = 0;
  225487. #if SUPPORT_ONLY_10_4_FONTS
  225488. HeapBlock <NSSize> advances (length);
  225489. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225490. for (int i = 0; i < length; ++i)
  225491. x += advances[i].width;
  225492. #else
  225493. #if SUPPORT_10_4_FONTS
  225494. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225495. {
  225496. HeapBlock <NSSize> advances (length);
  225497. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  225498. for (int i = 0; i < length; ++i)
  225499. x += advances[i].width;
  225500. }
  225501. else
  225502. #endif
  225503. {
  225504. HeapBlock <int> advances (length);
  225505. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225506. for (int i = 0; i < length; ++i)
  225507. x += advances[i];
  225508. }
  225509. #endif
  225510. return x * unitsToHeightScaleFactor;
  225511. }
  225512. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  225513. {
  225514. xOffsets.add (0);
  225515. if (fontRef == 0 || text.isEmpty())
  225516. return;
  225517. const int length = text.length();
  225518. HeapBlock <CGGlyph> glyphs;
  225519. createGlyphsForString (text.getCharPointer(), length, glyphs);
  225520. #if SUPPORT_ONLY_10_4_FONTS
  225521. HeapBlock <NSSize> advances (length);
  225522. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  225523. int x = 0;
  225524. for (int i = 0; i < length; ++i)
  225525. {
  225526. x += advances[i].width;
  225527. xOffsets.add (x * unitsToHeightScaleFactor);
  225528. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  225529. }
  225530. #else
  225531. #if SUPPORT_10_4_FONTS
  225532. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225533. {
  225534. HeapBlock <NSSize> advances (length);
  225535. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225536. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  225537. float x = 0;
  225538. for (int i = 0; i < length; ++i)
  225539. {
  225540. x += advances[i].width;
  225541. xOffsets.add (x * unitsToHeightScaleFactor);
  225542. resultGlyphs.add (nsGlyphs[i]);
  225543. }
  225544. }
  225545. else
  225546. #endif
  225547. {
  225548. HeapBlock <int> advances (length);
  225549. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  225550. {
  225551. int x = 0;
  225552. for (int i = 0; i < length; ++i)
  225553. {
  225554. x += advances [i];
  225555. xOffsets.add (x * unitsToHeightScaleFactor);
  225556. resultGlyphs.add (glyphs[i]);
  225557. }
  225558. }
  225559. }
  225560. #endif
  225561. }
  225562. bool getOutlineForGlyph (int glyphNumber, Path& path)
  225563. {
  225564. #if JUCE_IOS
  225565. return false;
  225566. #else
  225567. if (nsFont == 0)
  225568. return false;
  225569. // we might need to apply a transform to the path, so it mustn't have anything else in it
  225570. jassert (path.isEmpty());
  225571. const ScopedAutoReleasePool pool;
  225572. NSBezierPath* bez = [NSBezierPath bezierPath];
  225573. [bez moveToPoint: NSMakePoint (0, 0)];
  225574. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  225575. inFont: nsFont];
  225576. for (int i = 0; i < [bez elementCount]; ++i)
  225577. {
  225578. NSPoint p[3];
  225579. switch ([bez elementAtIndex: i associatedPoints: p])
  225580. {
  225581. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  225582. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  225583. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  225584. (float) p[1].x, (float) -p[1].y,
  225585. (float) p[2].x, (float) -p[2].y); break;
  225586. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  225587. default: jassertfalse; break;
  225588. }
  225589. }
  225590. path.applyTransform (pathTransform);
  225591. return true;
  225592. #endif
  225593. }
  225594. CGFontRef fontRef;
  225595. float fontHeightToCGSizeFactor;
  225596. CGAffineTransform renderingTransform;
  225597. private:
  225598. float ascent, unitsToHeightScaleFactor;
  225599. #if JUCE_IOS
  225600. #else
  225601. NSFont* nsFont;
  225602. AffineTransform pathTransform;
  225603. #endif
  225604. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  225605. {
  225606. #if SUPPORT_10_4_FONTS
  225607. #if ! SUPPORT_ONLY_10_4_FONTS
  225608. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  225609. #endif
  225610. {
  225611. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  225612. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  225613. for (int i = 0; i < length; ++i)
  225614. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  225615. return;
  225616. }
  225617. #endif
  225618. #if ! SUPPORT_ONLY_10_4_FONTS
  225619. if (charToGlyphMapper == 0)
  225620. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  225621. glyphs.malloc (length);
  225622. for (int i = 0; i < length; ++i)
  225623. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  225624. #endif
  225625. }
  225626. #if ! SUPPORT_ONLY_10_4_FONTS
  225627. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  225628. class CharToGlyphMapper
  225629. {
  225630. public:
  225631. CharToGlyphMapper (CGFontRef fontRef)
  225632. : segCount (0), endCode (0), startCode (0), idDelta (0),
  225633. idRangeOffset (0), glyphIndexes (0)
  225634. {
  225635. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  225636. if (cmapTable != 0)
  225637. {
  225638. const int numSubtables = getValue16 (cmapTable, 2);
  225639. for (int i = 0; i < numSubtables; ++i)
  225640. {
  225641. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  225642. {
  225643. const int offset = getValue32 (cmapTable, i * 8 + 8);
  225644. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  225645. {
  225646. const int length = getValue16 (cmapTable, offset + 2);
  225647. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  225648. segCount = segCountX2 / 2;
  225649. const int endCodeOffset = offset + 14;
  225650. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  225651. const int idDeltaOffset = startCodeOffset + segCountX2;
  225652. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  225653. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  225654. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  225655. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  225656. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  225657. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  225658. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  225659. }
  225660. break;
  225661. }
  225662. }
  225663. CFRelease (cmapTable);
  225664. }
  225665. }
  225666. ~CharToGlyphMapper()
  225667. {
  225668. if (endCode != 0)
  225669. {
  225670. CFRelease (endCode);
  225671. CFRelease (startCode);
  225672. CFRelease (idDelta);
  225673. CFRelease (idRangeOffset);
  225674. CFRelease (glyphIndexes);
  225675. }
  225676. }
  225677. int getGlyphForCharacter (const juce_wchar c) const
  225678. {
  225679. for (int i = 0; i < segCount; ++i)
  225680. {
  225681. if (getValue16 (endCode, i * 2) >= c)
  225682. {
  225683. const int start = getValue16 (startCode, i * 2);
  225684. if (start > c)
  225685. break;
  225686. const int delta = getValue16 (idDelta, i * 2);
  225687. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  225688. if (rangeOffset == 0)
  225689. return delta + c;
  225690. else
  225691. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  225692. }
  225693. }
  225694. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  225695. return jmax (-1, (int) c - 29);
  225696. }
  225697. private:
  225698. int segCount;
  225699. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  225700. static uint16 getValue16 (CFDataRef data, const int index)
  225701. {
  225702. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  225703. }
  225704. static uint32 getValue32 (CFDataRef data, const int index)
  225705. {
  225706. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  225707. }
  225708. };
  225709. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  225710. #endif
  225711. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  225712. };
  225713. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  225714. {
  225715. return new MacTypeface (font);
  225716. }
  225717. const StringArray Font::findAllTypefaceNames()
  225718. {
  225719. StringArray names;
  225720. const ScopedAutoReleasePool pool;
  225721. #if JUCE_IOS
  225722. NSArray* fonts = [UIFont familyNames];
  225723. #else
  225724. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  225725. #endif
  225726. for (unsigned int i = 0; i < [fonts count]; ++i)
  225727. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  225728. names.sort (true);
  225729. return names;
  225730. }
  225731. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  225732. {
  225733. #if JUCE_IOS
  225734. defaultSans = "Helvetica";
  225735. defaultSerif = "Times New Roman";
  225736. defaultFixed = "Courier New";
  225737. #else
  225738. defaultSans = "Lucida Grande";
  225739. defaultSerif = "Times New Roman";
  225740. defaultFixed = "Monaco";
  225741. #endif
  225742. defaultFallback = "Arial Unicode MS";
  225743. }
  225744. #endif
  225745. /*** End of inlined file: juce_mac_Fonts.mm ***/
  225746. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  225747. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225748. // compiled on its own).
  225749. #if JUCE_INCLUDED_FILE
  225750. class CoreGraphicsImage : public Image::SharedImage
  225751. {
  225752. public:
  225753. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  225754. : Image::SharedImage (format_, width_, height_)
  225755. {
  225756. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  225757. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  225758. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  225759. imageData = imageDataAllocated;
  225760. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  225761. : CGColorSpaceCreateDeviceRGB();
  225762. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  225763. colourSpace, getCGImageFlags (format_));
  225764. CGColorSpaceRelease (colourSpace);
  225765. }
  225766. ~CoreGraphicsImage()
  225767. {
  225768. CGContextRelease (context);
  225769. }
  225770. Image::ImageType getType() const { return Image::NativeImage; }
  225771. LowLevelGraphicsContext* createLowLevelContext();
  225772. SharedImage* clone()
  225773. {
  225774. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  225775. memcpy (im->imageData, imageData, lineStride * height);
  225776. return im;
  225777. }
  225778. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  225779. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  225780. {
  225781. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  225782. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  225783. {
  225784. return CGBitmapContextCreateImage (nativeImage->context);
  225785. }
  225786. else
  225787. {
  225788. const Image::BitmapData srcData (juceImage, false);
  225789. CGDataProviderRef provider;
  225790. if (mustOutliveSource)
  225791. {
  225792. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  225793. provider = CGDataProviderCreateWithCFData (data);
  225794. CFRelease (data);
  225795. }
  225796. else
  225797. {
  225798. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  225799. }
  225800. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  225801. 8, srcData.pixelStride * 8, srcData.lineStride,
  225802. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  225803. 0, true, kCGRenderingIntentDefault);
  225804. CGDataProviderRelease (provider);
  225805. return imageRef;
  225806. }
  225807. }
  225808. #if JUCE_MAC
  225809. static NSImage* createNSImage (const Image& image)
  225810. {
  225811. const ScopedAutoReleasePool pool;
  225812. NSImage* im = [[NSImage alloc] init];
  225813. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  225814. [im lockFocus];
  225815. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  225816. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  225817. CGColorSpaceRelease (colourSpace);
  225818. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  225819. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  225820. CGImageRelease (imageRef);
  225821. [im unlockFocus];
  225822. return im;
  225823. }
  225824. #endif
  225825. CGContextRef context;
  225826. HeapBlock<uint8> imageDataAllocated;
  225827. private:
  225828. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  225829. {
  225830. #if JUCE_BIG_ENDIAN
  225831. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  225832. #else
  225833. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  225834. #endif
  225835. }
  225836. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  225837. };
  225838. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  225839. {
  225840. #if USE_COREGRAPHICS_RENDERING
  225841. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  225842. #else
  225843. return createSoftwareImage (format, width, height, clearImage);
  225844. #endif
  225845. }
  225846. class CoreGraphicsContext : public LowLevelGraphicsContext
  225847. {
  225848. public:
  225849. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  225850. : context (context_),
  225851. flipHeight (flipHeight_),
  225852. lastClipRectIsValid (false),
  225853. state (new SavedState()),
  225854. numGradientLookupEntries (0)
  225855. {
  225856. CGContextRetain (context);
  225857. CGContextSaveGState(context);
  225858. CGContextSetShouldSmoothFonts (context, true);
  225859. CGContextSetShouldAntialias (context, true);
  225860. CGContextSetBlendMode (context, kCGBlendModeNormal);
  225861. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  225862. greyColourSpace = CGColorSpaceCreateDeviceGray();
  225863. gradientCallbacks.version = 0;
  225864. gradientCallbacks.evaluate = gradientCallback;
  225865. gradientCallbacks.releaseInfo = 0;
  225866. setFont (Font());
  225867. }
  225868. ~CoreGraphicsContext()
  225869. {
  225870. CGContextRestoreGState (context);
  225871. CGContextRelease (context);
  225872. CGColorSpaceRelease (rgbColourSpace);
  225873. CGColorSpaceRelease (greyColourSpace);
  225874. }
  225875. bool isVectorDevice() const { return false; }
  225876. void setOrigin (int x, int y)
  225877. {
  225878. CGContextTranslateCTM (context, x, -y);
  225879. if (lastClipRectIsValid)
  225880. lastClipRect.translate (-x, -y);
  225881. }
  225882. void addTransform (const AffineTransform& transform)
  225883. {
  225884. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  225885. .translated (0, flipHeight)
  225886. .followedBy (transform)
  225887. .translated (0, -flipHeight)
  225888. .scaled (1.0f, -1.0f));
  225889. lastClipRectIsValid = false;
  225890. }
  225891. float getScaleFactor()
  225892. {
  225893. CGAffineTransform t = CGContextGetCTM (context);
  225894. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  225895. }
  225896. bool clipToRectangle (const Rectangle<int>& r)
  225897. {
  225898. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  225899. if (lastClipRectIsValid)
  225900. {
  225901. // This is actually incorrect, because the actual clip region may be complex, and
  225902. // clipping its bounds to a rect may not be right... But, removing this shortcut
  225903. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  225904. // when calculating the resultant clip bounds, and makes the same mistake!
  225905. lastClipRect = lastClipRect.getIntersection (r);
  225906. return ! lastClipRect.isEmpty();
  225907. }
  225908. return ! isClipEmpty();
  225909. }
  225910. bool clipToRectangleList (const RectangleList& clipRegion)
  225911. {
  225912. if (clipRegion.isEmpty())
  225913. {
  225914. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  225915. lastClipRectIsValid = true;
  225916. lastClipRect = Rectangle<int>();
  225917. return false;
  225918. }
  225919. else
  225920. {
  225921. const int numRects = clipRegion.getNumRectangles();
  225922. HeapBlock <CGRect> rects (numRects);
  225923. for (int i = 0; i < numRects; ++i)
  225924. {
  225925. const Rectangle<int>& r = clipRegion.getRectangle(i);
  225926. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  225927. }
  225928. CGContextClipToRects (context, rects, numRects);
  225929. lastClipRectIsValid = false;
  225930. return ! isClipEmpty();
  225931. }
  225932. }
  225933. void excludeClipRectangle (const Rectangle<int>& r)
  225934. {
  225935. RectangleList remaining (getClipBounds());
  225936. remaining.subtract (r);
  225937. clipToRectangleList (remaining);
  225938. lastClipRectIsValid = false;
  225939. }
  225940. void clipToPath (const Path& path, const AffineTransform& transform)
  225941. {
  225942. createPath (path, transform);
  225943. CGContextClip (context);
  225944. lastClipRectIsValid = false;
  225945. }
  225946. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  225947. {
  225948. if (! transform.isSingularity())
  225949. {
  225950. Image singleChannelImage (sourceImage);
  225951. if (sourceImage.getFormat() != Image::SingleChannel)
  225952. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  225953. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  225954. flip();
  225955. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  225956. applyTransform (t);
  225957. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  225958. CGContextClipToMask (context, r, image);
  225959. applyTransform (t.inverted());
  225960. flip();
  225961. CGImageRelease (image);
  225962. lastClipRectIsValid = false;
  225963. }
  225964. }
  225965. bool clipRegionIntersects (const Rectangle<int>& r)
  225966. {
  225967. return getClipBounds().intersects (r);
  225968. }
  225969. const Rectangle<int> getClipBounds() const
  225970. {
  225971. if (! lastClipRectIsValid)
  225972. {
  225973. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  225974. lastClipRectIsValid = true;
  225975. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  225976. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  225977. roundToInt (bounds.size.width),
  225978. roundToInt (bounds.size.height));
  225979. }
  225980. return lastClipRect;
  225981. }
  225982. bool isClipEmpty() const
  225983. {
  225984. return getClipBounds().isEmpty();
  225985. }
  225986. void saveState()
  225987. {
  225988. CGContextSaveGState (context);
  225989. stateStack.add (new SavedState (*state));
  225990. }
  225991. void restoreState()
  225992. {
  225993. CGContextRestoreGState (context);
  225994. SavedState* const top = stateStack.getLast();
  225995. if (top != 0)
  225996. {
  225997. state = top;
  225998. stateStack.removeLast (1, false);
  225999. lastClipRectIsValid = false;
  226000. }
  226001. else
  226002. {
  226003. jassertfalse; // trying to pop with an empty stack!
  226004. }
  226005. }
  226006. void beginTransparencyLayer (float opacity)
  226007. {
  226008. saveState();
  226009. CGContextSetAlpha (context, opacity);
  226010. CGContextBeginTransparencyLayer (context, 0);
  226011. }
  226012. void endTransparencyLayer()
  226013. {
  226014. CGContextEndTransparencyLayer (context);
  226015. restoreState();
  226016. }
  226017. void setFill (const FillType& fillType)
  226018. {
  226019. state->fillType = fillType;
  226020. if (fillType.isColour())
  226021. {
  226022. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226023. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226024. CGContextSetAlpha (context, 1.0f);
  226025. }
  226026. }
  226027. void setOpacity (float newOpacity)
  226028. {
  226029. state->fillType.setOpacity (newOpacity);
  226030. setFill (state->fillType);
  226031. }
  226032. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226033. {
  226034. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226035. ? kCGInterpolationLow
  226036. : kCGInterpolationHigh);
  226037. }
  226038. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226039. {
  226040. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226041. }
  226042. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226043. {
  226044. if (replaceExistingContents)
  226045. {
  226046. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226047. CGContextClearRect (context, cgRect);
  226048. #else
  226049. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226050. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226051. CGContextClearRect (context, cgRect);
  226052. else
  226053. #endif
  226054. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226055. #endif
  226056. fillCGRect (cgRect, false);
  226057. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226058. }
  226059. else
  226060. {
  226061. if (state->fillType.isColour())
  226062. {
  226063. CGContextFillRect (context, cgRect);
  226064. }
  226065. else if (state->fillType.isGradient())
  226066. {
  226067. CGContextSaveGState (context);
  226068. CGContextClipToRect (context, cgRect);
  226069. drawGradient();
  226070. CGContextRestoreGState (context);
  226071. }
  226072. else
  226073. {
  226074. CGContextSaveGState (context);
  226075. CGContextClipToRect (context, cgRect);
  226076. drawImage (state->fillType.image, state->fillType.transform, true);
  226077. CGContextRestoreGState (context);
  226078. }
  226079. }
  226080. }
  226081. void fillPath (const Path& path, const AffineTransform& transform)
  226082. {
  226083. CGContextSaveGState (context);
  226084. if (state->fillType.isColour())
  226085. {
  226086. flip();
  226087. applyTransform (transform);
  226088. createPath (path);
  226089. if (path.isUsingNonZeroWinding())
  226090. CGContextFillPath (context);
  226091. else
  226092. CGContextEOFillPath (context);
  226093. }
  226094. else
  226095. {
  226096. createPath (path, transform);
  226097. if (path.isUsingNonZeroWinding())
  226098. CGContextClip (context);
  226099. else
  226100. CGContextEOClip (context);
  226101. if (state->fillType.isGradient())
  226102. drawGradient();
  226103. else
  226104. drawImage (state->fillType.image, state->fillType.transform, true);
  226105. }
  226106. CGContextRestoreGState (context);
  226107. }
  226108. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226109. {
  226110. const int iw = sourceImage.getWidth();
  226111. const int ih = sourceImage.getHeight();
  226112. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  226113. CGContextSaveGState (context);
  226114. CGContextSetAlpha (context, state->fillType.getOpacity());
  226115. flip();
  226116. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226117. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226118. if (fillEntireClipAsTiles)
  226119. {
  226120. #if JUCE_IOS
  226121. CGContextDrawTiledImage (context, imageRect, image);
  226122. #else
  226123. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226124. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226125. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226126. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226127. CGContextDrawTiledImage (context, imageRect, image);
  226128. else
  226129. #endif
  226130. {
  226131. // Fallback to manually doing a tiled fill on 10.4
  226132. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226133. int x = 0, y = 0;
  226134. while (x > clip.origin.x) x -= iw;
  226135. while (y > clip.origin.y) y -= ih;
  226136. const int right = (int) (clip.origin.x + clip.size.width);
  226137. const int bottom = (int) (clip.origin.y + clip.size.height);
  226138. while (y < bottom)
  226139. {
  226140. for (int x2 = x; x2 < right; x2 += iw)
  226141. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226142. y += ih;
  226143. }
  226144. }
  226145. #endif
  226146. }
  226147. else
  226148. {
  226149. CGContextDrawImage (context, imageRect, image);
  226150. }
  226151. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226152. CGContextRestoreGState (context);
  226153. }
  226154. void drawLine (const Line<float>& line)
  226155. {
  226156. if (state->fillType.isColour())
  226157. {
  226158. CGContextSetLineCap (context, kCGLineCapSquare);
  226159. CGContextSetLineWidth (context, 1.0f);
  226160. CGContextSetRGBStrokeColor (context,
  226161. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226162. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226163. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226164. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226165. CGContextStrokeLineSegments (context, cgLine, 1);
  226166. }
  226167. else
  226168. {
  226169. Path p;
  226170. p.addLineSegment (line, 1.0f);
  226171. fillPath (p, AffineTransform::identity);
  226172. }
  226173. }
  226174. void drawVerticalLine (const int x, float top, float bottom)
  226175. {
  226176. if (state->fillType.isColour())
  226177. {
  226178. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226179. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  226180. #else
  226181. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226182. // the x co-ord slightly to trick it..
  226183. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  226184. #endif
  226185. }
  226186. else
  226187. {
  226188. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  226189. }
  226190. }
  226191. void drawHorizontalLine (const int y, float left, float right)
  226192. {
  226193. if (state->fillType.isColour())
  226194. {
  226195. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  226196. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  226197. #else
  226198. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  226199. // the x co-ord slightly to trick it..
  226200. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  226201. #endif
  226202. }
  226203. else
  226204. {
  226205. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  226206. }
  226207. }
  226208. void setFont (const Font& newFont)
  226209. {
  226210. if (state->font != newFont)
  226211. {
  226212. state->fontRef = 0;
  226213. state->font = newFont;
  226214. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  226215. if (mf != 0)
  226216. {
  226217. state->fontRef = mf->fontRef;
  226218. CGContextSetFont (context, state->fontRef);
  226219. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  226220. state->fontTransform = mf->renderingTransform;
  226221. state->fontTransform.a *= state->font.getHorizontalScale();
  226222. CGContextSetTextMatrix (context, state->fontTransform);
  226223. }
  226224. }
  226225. }
  226226. const Font getFont()
  226227. {
  226228. return state->font;
  226229. }
  226230. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  226231. {
  226232. if (state->fontRef != 0 && state->fillType.isColour())
  226233. {
  226234. if (transform.isOnlyTranslation())
  226235. {
  226236. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  226237. CGGlyph g = glyphNumber;
  226238. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  226239. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  226240. }
  226241. else
  226242. {
  226243. CGContextSaveGState (context);
  226244. flip();
  226245. applyTransform (transform);
  226246. CGAffineTransform t = state->fontTransform;
  226247. t.d = -t.d;
  226248. CGContextSetTextMatrix (context, t);
  226249. CGGlyph g = glyphNumber;
  226250. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  226251. CGContextRestoreGState (context);
  226252. }
  226253. }
  226254. else
  226255. {
  226256. Path p;
  226257. Font& f = state->font;
  226258. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  226259. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  226260. .followedBy (transform));
  226261. }
  226262. }
  226263. private:
  226264. CGContextRef context;
  226265. const CGFloat flipHeight;
  226266. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  226267. CGFunctionCallbacks gradientCallbacks;
  226268. mutable Rectangle<int> lastClipRect;
  226269. mutable bool lastClipRectIsValid;
  226270. struct SavedState
  226271. {
  226272. SavedState()
  226273. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  226274. {
  226275. }
  226276. SavedState (const SavedState& other)
  226277. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  226278. fontTransform (other.fontTransform)
  226279. {
  226280. }
  226281. FillType fillType;
  226282. Font font;
  226283. CGFontRef fontRef;
  226284. CGAffineTransform fontTransform;
  226285. };
  226286. ScopedPointer <SavedState> state;
  226287. OwnedArray <SavedState> stateStack;
  226288. HeapBlock <PixelARGB> gradientLookupTable;
  226289. int numGradientLookupEntries;
  226290. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  226291. {
  226292. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  226293. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  226294. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  226295. colour.unpremultiply();
  226296. outData[0] = colour.getRed() / 255.0f;
  226297. outData[1] = colour.getGreen() / 255.0f;
  226298. outData[2] = colour.getBlue() / 255.0f;
  226299. outData[3] = colour.getAlpha() / 255.0f;
  226300. }
  226301. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  226302. {
  226303. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  226304. CGShadingRef result = 0;
  226305. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  226306. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  226307. if (gradient.isRadial)
  226308. {
  226309. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  226310. p1, gradient.point1.getDistanceFrom (gradient.point2),
  226311. function, true, true);
  226312. }
  226313. else
  226314. {
  226315. result = CGShadingCreateAxial (rgbColourSpace, p1,
  226316. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  226317. function, true, true);
  226318. }
  226319. CGFunctionRelease (function);
  226320. return result;
  226321. }
  226322. void drawGradient()
  226323. {
  226324. flip();
  226325. applyTransform (state->fillType.transform);
  226326. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  226327. // you draw a gradient with high quality interp enabled).
  226328. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  226329. CGContextSetAlpha (context, state->fillType.getOpacity());
  226330. CGContextDrawShading (context, shading);
  226331. CGShadingRelease (shading);
  226332. }
  226333. void createPath (const Path& path) const
  226334. {
  226335. CGContextBeginPath (context);
  226336. Path::Iterator i (path);
  226337. while (i.next())
  226338. {
  226339. switch (i.elementType)
  226340. {
  226341. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  226342. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  226343. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  226344. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  226345. case Path::Iterator::closePath: CGContextClosePath (context); break;
  226346. default: jassertfalse; break;
  226347. }
  226348. }
  226349. }
  226350. void createPath (const Path& path, const AffineTransform& transform) const
  226351. {
  226352. CGContextBeginPath (context);
  226353. Path::Iterator i (path);
  226354. while (i.next())
  226355. {
  226356. switch (i.elementType)
  226357. {
  226358. case Path::Iterator::startNewSubPath:
  226359. transform.transformPoint (i.x1, i.y1);
  226360. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  226361. break;
  226362. case Path::Iterator::lineTo:
  226363. transform.transformPoint (i.x1, i.y1);
  226364. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  226365. break;
  226366. case Path::Iterator::quadraticTo:
  226367. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  226368. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  226369. break;
  226370. case Path::Iterator::cubicTo:
  226371. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  226372. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  226373. break;
  226374. case Path::Iterator::closePath:
  226375. CGContextClosePath (context); break;
  226376. default:
  226377. jassertfalse;
  226378. break;
  226379. }
  226380. }
  226381. }
  226382. void flip() const
  226383. {
  226384. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  226385. }
  226386. void applyTransform (const AffineTransform& transform) const
  226387. {
  226388. CGAffineTransform t;
  226389. t.a = transform.mat00;
  226390. t.b = transform.mat10;
  226391. t.c = transform.mat01;
  226392. t.d = transform.mat11;
  226393. t.tx = transform.mat02;
  226394. t.ty = transform.mat12;
  226395. CGContextConcatCTM (context, t);
  226396. }
  226397. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  226398. };
  226399. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  226400. {
  226401. return new CoreGraphicsContext (context, height);
  226402. }
  226403. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  226404. const Image juce_loadWithCoreImage (InputStream& input)
  226405. {
  226406. MemoryBlock data;
  226407. input.readIntoMemoryBlock (data, -1);
  226408. #if JUCE_IOS
  226409. JUCE_AUTORELEASEPOOL
  226410. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  226411. length: data.getSize()
  226412. freeWhenDone: NO]];
  226413. if (image != nil)
  226414. {
  226415. CGImageRef loadedImage = image.CGImage;
  226416. #else
  226417. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  226418. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  226419. CGDataProviderRelease (provider);
  226420. if (imageSource != 0)
  226421. {
  226422. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  226423. CFRelease (imageSource);
  226424. #endif
  226425. if (loadedImage != 0)
  226426. {
  226427. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  226428. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  226429. && alphaInfo != kCGImageAlphaNoneSkipLast
  226430. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  226431. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  226432. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  226433. hasAlphaChan, Image::NativeImage);
  226434. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  226435. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  226436. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  226437. CGContextFlush (cgImage->context);
  226438. #if ! JUCE_IOS
  226439. CFRelease (loadedImage);
  226440. #endif
  226441. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  226442. // to find out whether the file they just loaded the image from had an alpha channel or not.
  226443. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  226444. return image;
  226445. }
  226446. }
  226447. return Image::null;
  226448. }
  226449. #endif
  226450. #endif
  226451. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226452. /*** Start of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  226453. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226454. // compiled on its own).
  226455. #if JUCE_INCLUDED_FILE
  226456. class UIViewComponentPeer;
  226457. END_JUCE_NAMESPACE
  226458. #define JuceUIView MakeObjCClassName(JuceUIView)
  226459. @interface JuceUIView : UIView <UITextViewDelegate>
  226460. {
  226461. @public
  226462. UIViewComponentPeer* owner;
  226463. UITextView* hiddenTextView;
  226464. }
  226465. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  226466. - (void) dealloc;
  226467. - (void) drawRect: (CGRect) r;
  226468. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  226469. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  226470. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  226471. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  226472. - (BOOL) becomeFirstResponder;
  226473. - (BOOL) resignFirstResponder;
  226474. - (BOOL) canBecomeFirstResponder;
  226475. - (void) asyncRepaint: (id) rect;
  226476. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  226477. @end
  226478. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  226479. @interface JuceUIViewController : UIViewController
  226480. {
  226481. }
  226482. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  226483. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  226484. @end
  226485. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  226486. @interface JuceUIWindow : UIWindow
  226487. {
  226488. @private
  226489. UIViewComponentPeer* owner;
  226490. bool isZooming;
  226491. }
  226492. - (void) setOwner: (UIViewComponentPeer*) owner;
  226493. - (void) becomeKeyWindow;
  226494. @end
  226495. BEGIN_JUCE_NAMESPACE
  226496. class UIViewComponentPeer : public ComponentPeer,
  226497. public FocusChangeListener
  226498. {
  226499. public:
  226500. UIViewComponentPeer (Component* const component,
  226501. const int windowStyleFlags,
  226502. UIView* viewToAttachTo);
  226503. ~UIViewComponentPeer();
  226504. void* getNativeHandle() const;
  226505. void setVisible (bool shouldBeVisible);
  226506. void setTitle (const String& title);
  226507. void setPosition (int x, int y);
  226508. void setSize (int w, int h);
  226509. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  226510. const Rectangle<int> getBounds() const;
  226511. const Rectangle<int> getBounds (const bool global) const;
  226512. const Point<int> getScreenPosition() const;
  226513. const Point<int> localToGlobal (const Point<int>& relativePosition);
  226514. const Point<int> globalToLocal (const Point<int>& screenPosition);
  226515. void setAlpha (float newAlpha);
  226516. void setMinimised (bool shouldBeMinimised);
  226517. bool isMinimised() const;
  226518. void setFullScreen (bool shouldBeFullScreen);
  226519. bool isFullScreen() const;
  226520. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  226521. const BorderSize<int> getFrameSize() const;
  226522. bool setAlwaysOnTop (bool alwaysOnTop);
  226523. void toFront (bool makeActiveWindow);
  226524. void toBehind (ComponentPeer* other);
  226525. void setIcon (const Image& newIcon);
  226526. virtual void drawRect (CGRect r);
  226527. virtual bool canBecomeKeyWindow();
  226528. virtual bool windowShouldClose();
  226529. virtual void redirectMovedOrResized();
  226530. virtual CGRect constrainRect (CGRect r);
  226531. virtual void viewFocusGain();
  226532. virtual void viewFocusLoss();
  226533. bool isFocused() const;
  226534. void grabFocus();
  226535. void textInputRequired (const Point<int>& position);
  226536. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  226537. void updateHiddenTextContent (TextInputTarget* target);
  226538. void globalFocusChanged (Component*);
  226539. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  226540. virtual void displayRotated();
  226541. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  226542. void repaint (const Rectangle<int>& area);
  226543. void performAnyPendingRepaintsNow();
  226544. UIWindow* window;
  226545. JuceUIView* view;
  226546. JuceUIViewController* controller;
  226547. bool isSharedWindow, fullScreen, insideDrawRect;
  226548. static ModifierKeys currentModifiers;
  226549. static int64 getMouseTime (UIEvent* e)
  226550. {
  226551. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  226552. + (int64) ([e timestamp] * 1000.0);
  226553. }
  226554. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  226555. {
  226556. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226557. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226558. {
  226559. case UIInterfaceOrientationPortrait:
  226560. return r;
  226561. case UIInterfaceOrientationPortraitUpsideDown:
  226562. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226563. r.getWidth(), r.getHeight());
  226564. case UIInterfaceOrientationLandscapeLeft:
  226565. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  226566. r.getHeight(), r.getWidth());
  226567. case UIInterfaceOrientationLandscapeRight:
  226568. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  226569. r.getHeight(), r.getWidth());
  226570. default: jassertfalse; // unknown orientation!
  226571. }
  226572. return r;
  226573. }
  226574. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  226575. {
  226576. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  226577. switch ([[UIApplication sharedApplication] statusBarOrientation])
  226578. {
  226579. case UIInterfaceOrientationPortrait:
  226580. return r;
  226581. case UIInterfaceOrientationPortraitUpsideDown:
  226582. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  226583. r.getWidth(), r.getHeight());
  226584. case UIInterfaceOrientationLandscapeLeft:
  226585. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  226586. r.getHeight(), r.getWidth());
  226587. case UIInterfaceOrientationLandscapeRight:
  226588. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  226589. r.getHeight(), r.getWidth());
  226590. default: jassertfalse; // unknown orientation!
  226591. }
  226592. return r;
  226593. }
  226594. Array <UITouch*> currentTouches;
  226595. private:
  226596. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UIViewComponentPeer);
  226597. };
  226598. END_JUCE_NAMESPACE
  226599. @implementation JuceUIViewController
  226600. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  226601. {
  226602. JuceUIView* juceView = (JuceUIView*) [self view];
  226603. jassert (juceView != 0 && juceView->owner != 0);
  226604. return juceView->owner->shouldRotate (interfaceOrientation);
  226605. }
  226606. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  226607. {
  226608. JuceUIView* juceView = (JuceUIView*) [self view];
  226609. jassert (juceView != 0 && juceView->owner != 0);
  226610. juceView->owner->displayRotated();
  226611. }
  226612. @end
  226613. @implementation JuceUIView
  226614. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  226615. withFrame: (CGRect) frame
  226616. {
  226617. [super initWithFrame: frame];
  226618. owner = owner_;
  226619. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  226620. [self addSubview: hiddenTextView];
  226621. hiddenTextView.delegate = self;
  226622. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  226623. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  226624. return self;
  226625. }
  226626. - (void) dealloc
  226627. {
  226628. [hiddenTextView removeFromSuperview];
  226629. [hiddenTextView release];
  226630. [super dealloc];
  226631. }
  226632. - (void) drawRect: (CGRect) r
  226633. {
  226634. if (owner != 0)
  226635. owner->drawRect (r);
  226636. }
  226637. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  226638. {
  226639. return false;
  226640. }
  226641. ModifierKeys UIViewComponentPeer::currentModifiers;
  226642. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  226643. {
  226644. return UIViewComponentPeer::currentModifiers;
  226645. }
  226646. void ModifierKeys::updateCurrentModifiers() throw()
  226647. {
  226648. currentModifiers = UIViewComponentPeer::currentModifiers;
  226649. }
  226650. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  226651. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  226652. {
  226653. if (owner != 0)
  226654. owner->handleTouches (event, true, false, false);
  226655. }
  226656. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  226657. {
  226658. if (owner != 0)
  226659. owner->handleTouches (event, false, false, false);
  226660. }
  226661. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  226662. {
  226663. if (owner != 0)
  226664. owner->handleTouches (event, false, true, false);
  226665. }
  226666. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  226667. {
  226668. if (owner != 0)
  226669. owner->handleTouches (event, false, true, true);
  226670. [self touchesEnded: touches withEvent: event];
  226671. }
  226672. - (BOOL) becomeFirstResponder
  226673. {
  226674. if (owner != 0)
  226675. owner->viewFocusGain();
  226676. return true;
  226677. }
  226678. - (BOOL) resignFirstResponder
  226679. {
  226680. if (owner != 0)
  226681. owner->viewFocusLoss();
  226682. return true;
  226683. }
  226684. - (BOOL) canBecomeFirstResponder
  226685. {
  226686. return owner != 0 && owner->canBecomeKeyWindow();
  226687. }
  226688. - (void) asyncRepaint: (id) rect
  226689. {
  226690. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  226691. [self setNeedsDisplayInRect: *r];
  226692. }
  226693. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  226694. {
  226695. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  226696. nsStringToJuce (text));
  226697. }
  226698. @end
  226699. @implementation JuceUIWindow
  226700. - (void) setOwner: (UIViewComponentPeer*) owner_
  226701. {
  226702. owner = owner_;
  226703. isZooming = false;
  226704. }
  226705. - (void) becomeKeyWindow
  226706. {
  226707. [super becomeKeyWindow];
  226708. if (owner != 0)
  226709. owner->grabFocus();
  226710. }
  226711. @end
  226712. BEGIN_JUCE_NAMESPACE
  226713. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  226714. const int windowStyleFlags,
  226715. UIView* viewToAttachTo)
  226716. : ComponentPeer (component, windowStyleFlags),
  226717. window (0),
  226718. view (0), controller (0),
  226719. isSharedWindow (viewToAttachTo != 0),
  226720. fullScreen (false),
  226721. insideDrawRect (false)
  226722. {
  226723. CGRect r = convertToCGRect (component->getLocalBounds());
  226724. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  226725. if (isSharedWindow)
  226726. {
  226727. window = [viewToAttachTo window];
  226728. [viewToAttachTo addSubview: view];
  226729. setVisible (component->isVisible());
  226730. }
  226731. else
  226732. {
  226733. controller = [[JuceUIViewController alloc] init];
  226734. controller.view = view;
  226735. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  226736. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  226737. window = [[JuceUIWindow alloc] init];
  226738. window.frame = r;
  226739. window.opaque = component->isOpaque();
  226740. view.opaque = component->isOpaque();
  226741. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226742. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  226743. [((JuceUIWindow*) window) setOwner: this];
  226744. if (component->isAlwaysOnTop())
  226745. window.windowLevel = UIWindowLevelAlert;
  226746. [window addSubview: view];
  226747. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  226748. view.hidden = ! component->isVisible();
  226749. window.hidden = ! component->isVisible();
  226750. view.multipleTouchEnabled = YES;
  226751. }
  226752. setTitle (component->getName());
  226753. Desktop::getInstance().addFocusChangeListener (this);
  226754. }
  226755. UIViewComponentPeer::~UIViewComponentPeer()
  226756. {
  226757. Desktop::getInstance().removeFocusChangeListener (this);
  226758. view->owner = 0;
  226759. [view removeFromSuperview];
  226760. [view release];
  226761. [controller release];
  226762. if (! isSharedWindow)
  226763. {
  226764. [((JuceUIWindow*) window) setOwner: 0];
  226765. [window release];
  226766. }
  226767. }
  226768. void* UIViewComponentPeer::getNativeHandle() const
  226769. {
  226770. return view;
  226771. }
  226772. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  226773. {
  226774. view.hidden = ! shouldBeVisible;
  226775. if (! isSharedWindow)
  226776. window.hidden = ! shouldBeVisible;
  226777. }
  226778. void UIViewComponentPeer::setTitle (const String& title)
  226779. {
  226780. // xxx is this possible?
  226781. }
  226782. void UIViewComponentPeer::setPosition (int x, int y)
  226783. {
  226784. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  226785. }
  226786. void UIViewComponentPeer::setSize (int w, int h)
  226787. {
  226788. setBounds (component->getX(), component->getY(), w, h, false);
  226789. }
  226790. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  226791. {
  226792. fullScreen = isNowFullScreen;
  226793. w = jmax (0, w);
  226794. h = jmax (0, h);
  226795. if (isSharedWindow)
  226796. {
  226797. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  226798. if ([view frame].size.width != r.size.width
  226799. || [view frame].size.height != r.size.height)
  226800. [view setNeedsDisplay];
  226801. view.frame = r;
  226802. }
  226803. else
  226804. {
  226805. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  226806. window.frame = convertToCGRect (bounds);
  226807. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  226808. handleMovedOrResized();
  226809. }
  226810. }
  226811. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  226812. {
  226813. CGRect r = [view frame];
  226814. if (global && [view window] != 0)
  226815. {
  226816. r = [view convertRect: r toView: nil];
  226817. CGRect wr = [[view window] frame];
  226818. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  226819. r.origin.x = windowBounds.getX();
  226820. r.origin.y = windowBounds.getY();
  226821. }
  226822. return convertToRectInt (r);
  226823. }
  226824. const Rectangle<int> UIViewComponentPeer::getBounds() const
  226825. {
  226826. return getBounds (! isSharedWindow);
  226827. }
  226828. const Point<int> UIViewComponentPeer::getScreenPosition() const
  226829. {
  226830. return getBounds (true).getPosition();
  226831. }
  226832. const Point<int> UIViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  226833. {
  226834. return relativePosition + getScreenPosition();
  226835. }
  226836. const Point<int> UIViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  226837. {
  226838. return screenPosition - getScreenPosition();
  226839. }
  226840. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  226841. {
  226842. if (constrainer != 0)
  226843. {
  226844. CGRect current = [window frame];
  226845. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  226846. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  226847. Rectangle<int> pos (convertToRectInt (r));
  226848. Rectangle<int> original (convertToRectInt (current));
  226849. constrainer->checkBounds (pos, original,
  226850. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  226851. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  226852. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  226853. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  226854. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  226855. r.origin.x = pos.getX();
  226856. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  226857. r.size.width = pos.getWidth();
  226858. r.size.height = pos.getHeight();
  226859. }
  226860. return r;
  226861. }
  226862. void UIViewComponentPeer::setAlpha (float newAlpha)
  226863. {
  226864. [[view window] setAlpha: (CGFloat) newAlpha];
  226865. }
  226866. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  226867. {
  226868. }
  226869. bool UIViewComponentPeer::isMinimised() const
  226870. {
  226871. return false;
  226872. }
  226873. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  226874. {
  226875. if (! isSharedWindow)
  226876. {
  226877. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  226878. : lastNonFullscreenBounds);
  226879. if ((! shouldBeFullScreen) && r.isEmpty())
  226880. r = getBounds();
  226881. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  226882. if (! r.isEmpty())
  226883. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  226884. component->repaint();
  226885. }
  226886. }
  226887. bool UIViewComponentPeer::isFullScreen() const
  226888. {
  226889. return fullScreen;
  226890. }
  226891. namespace
  226892. {
  226893. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  226894. {
  226895. switch (interfaceOrientation)
  226896. {
  226897. case UIInterfaceOrientationPortrait: return Desktop::upright;
  226898. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  226899. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  226900. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  226901. default: jassertfalse; // unknown orientation!
  226902. }
  226903. return Desktop::upright;
  226904. }
  226905. }
  226906. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  226907. {
  226908. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  226909. }
  226910. void UIViewComponentPeer::displayRotated()
  226911. {
  226912. const Rectangle<int> oldArea (component->getBounds());
  226913. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  226914. Desktop::getInstance().refreshMonitorSizes();
  226915. if (fullScreen)
  226916. {
  226917. fullScreen = false;
  226918. setFullScreen (true);
  226919. }
  226920. else
  226921. {
  226922. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  226923. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  226924. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  226925. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  226926. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  226927. setBounds ((int) (l * newDesktop.getWidth()),
  226928. (int) (t * newDesktop.getHeight()),
  226929. (int) ((r - l) * newDesktop.getWidth()),
  226930. (int) ((b - t) * newDesktop.getHeight()),
  226931. false);
  226932. }
  226933. }
  226934. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  226935. {
  226936. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  226937. && isPositiveAndBelow (position.getY(), component->getHeight())))
  226938. return false;
  226939. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  226940. withEvent: nil];
  226941. if (trueIfInAChildWindow)
  226942. return v != nil;
  226943. return v == view;
  226944. }
  226945. const BorderSize<int> UIViewComponentPeer::getFrameSize() const
  226946. {
  226947. return BorderSize<int>();
  226948. }
  226949. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  226950. {
  226951. if (! isSharedWindow)
  226952. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  226953. return true;
  226954. }
  226955. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  226956. {
  226957. if (isSharedWindow)
  226958. [[view superview] bringSubviewToFront: view];
  226959. if (window != 0 && component->isVisible())
  226960. [window makeKeyAndVisible];
  226961. }
  226962. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  226963. {
  226964. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  226965. jassert (otherPeer != 0); // wrong type of window?
  226966. if (otherPeer != 0)
  226967. {
  226968. if (isSharedWindow)
  226969. {
  226970. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  226971. }
  226972. else
  226973. {
  226974. jassertfalse; // don't know how to do this
  226975. }
  226976. }
  226977. }
  226978. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  226979. {
  226980. // to do..
  226981. }
  226982. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  226983. {
  226984. NSArray* touches = [[event touchesForView: view] allObjects];
  226985. for (unsigned int i = 0; i < [touches count]; ++i)
  226986. {
  226987. UITouch* touch = [touches objectAtIndex: i];
  226988. CGPoint p = [touch locationInView: view];
  226989. const Point<int> pos ((int) p.x, (int) p.y);
  226990. juce_lastMousePos = pos + getScreenPosition();
  226991. const int64 time = getMouseTime (event);
  226992. int touchIndex = currentTouches.indexOf (touch);
  226993. if (touchIndex < 0)
  226994. {
  226995. touchIndex = currentTouches.size();
  226996. currentTouches.add (touch);
  226997. }
  226998. if (isDown)
  226999. {
  227000. currentModifiers = currentModifiers.withoutMouseButtons();
  227001. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227002. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227003. }
  227004. else if (isUp)
  227005. {
  227006. currentModifiers = currentModifiers.withoutMouseButtons();
  227007. currentTouches.remove (touchIndex);
  227008. }
  227009. if (isCancel)
  227010. currentTouches.clear();
  227011. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227012. }
  227013. }
  227014. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227015. void UIViewComponentPeer::viewFocusGain()
  227016. {
  227017. if (currentlyFocusedPeer != this)
  227018. {
  227019. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227020. currentlyFocusedPeer->handleFocusLoss();
  227021. currentlyFocusedPeer = this;
  227022. handleFocusGain();
  227023. }
  227024. }
  227025. void UIViewComponentPeer::viewFocusLoss()
  227026. {
  227027. if (currentlyFocusedPeer == this)
  227028. {
  227029. currentlyFocusedPeer = 0;
  227030. handleFocusLoss();
  227031. }
  227032. }
  227033. void juce_HandleProcessFocusChange()
  227034. {
  227035. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227036. {
  227037. if (Process::isForegroundProcess())
  227038. {
  227039. currentlyFocusedPeer->handleFocusGain();
  227040. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  227041. }
  227042. else
  227043. {
  227044. currentlyFocusedPeer->handleFocusLoss();
  227045. // turn kiosk mode off if we lose focus..
  227046. Desktop::getInstance().setKioskModeComponent (0);
  227047. }
  227048. }
  227049. }
  227050. bool UIViewComponentPeer::isFocused() const
  227051. {
  227052. return isSharedWindow ? this == currentlyFocusedPeer
  227053. : (window != 0 && [window isKeyWindow]);
  227054. }
  227055. void UIViewComponentPeer::grabFocus()
  227056. {
  227057. if (window != 0)
  227058. {
  227059. [window makeKeyWindow];
  227060. viewFocusGain();
  227061. }
  227062. }
  227063. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227064. {
  227065. }
  227066. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227067. {
  227068. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227069. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227070. }
  227071. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227072. {
  227073. TextInputTarget* const target = findCurrentTextInputTarget();
  227074. if (target != 0)
  227075. {
  227076. const Range<int> currentSelection (target->getHighlightedRegion());
  227077. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227078. if (currentSelection.isEmpty())
  227079. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227080. target->insertTextAtCaret (text);
  227081. updateHiddenTextContent (target);
  227082. }
  227083. return NO;
  227084. }
  227085. void UIViewComponentPeer::globalFocusChanged (Component*)
  227086. {
  227087. TextInputTarget* const target = findCurrentTextInputTarget();
  227088. if (target != 0)
  227089. {
  227090. Component* comp = dynamic_cast<Component*> (target);
  227091. Point<int> pos (component->getLocalPoint (comp, Point<int>()));
  227092. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227093. updateHiddenTextContent (target);
  227094. [view->hiddenTextView becomeFirstResponder];
  227095. }
  227096. else
  227097. {
  227098. [view->hiddenTextView resignFirstResponder];
  227099. }
  227100. }
  227101. void UIViewComponentPeer::drawRect (CGRect r)
  227102. {
  227103. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227104. return;
  227105. CGContextRef cg = UIGraphicsGetCurrentContext();
  227106. if (! component->isOpaque())
  227107. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227108. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227109. CoreGraphicsContext g (cg, view.bounds.size.height);
  227110. insideDrawRect = true;
  227111. handlePaint (g);
  227112. insideDrawRect = false;
  227113. }
  227114. bool UIViewComponentPeer::canBecomeKeyWindow()
  227115. {
  227116. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227117. }
  227118. bool UIViewComponentPeer::windowShouldClose()
  227119. {
  227120. if (! isValidPeer (this))
  227121. return YES;
  227122. handleUserClosingWindow();
  227123. return NO;
  227124. }
  227125. void UIViewComponentPeer::redirectMovedOrResized()
  227126. {
  227127. handleMovedOrResized();
  227128. }
  227129. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227130. {
  227131. }
  227132. class AsyncRepaintMessage : public CallbackMessage
  227133. {
  227134. public:
  227135. UIViewComponentPeer* const peer;
  227136. const Rectangle<int> rect;
  227137. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227138. : peer (peer_), rect (rect_)
  227139. {
  227140. }
  227141. void messageCallback()
  227142. {
  227143. if (ComponentPeer::isValidPeer (peer))
  227144. peer->repaint (rect);
  227145. }
  227146. };
  227147. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227148. {
  227149. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227150. {
  227151. (new AsyncRepaintMessage (this, area))->post();
  227152. }
  227153. else
  227154. {
  227155. [view setNeedsDisplayInRect: convertToCGRect (area)];
  227156. }
  227157. }
  227158. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227159. {
  227160. }
  227161. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227162. {
  227163. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227164. }
  227165. const Image juce_createIconForFile (const File& file)
  227166. {
  227167. return Image::null;
  227168. }
  227169. void Desktop::createMouseInputSources()
  227170. {
  227171. for (int i = 0; i < 10; ++i)
  227172. mouseSources.add (new MouseInputSource (i, false));
  227173. }
  227174. bool Desktop::canUseSemiTransparentWindows() throw()
  227175. {
  227176. return true;
  227177. }
  227178. const Point<int> MouseInputSource::getCurrentMousePosition()
  227179. {
  227180. return juce_lastMousePos;
  227181. }
  227182. void Desktop::setMousePosition (const Point<int>&)
  227183. {
  227184. }
  227185. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  227186. {
  227187. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  227188. }
  227189. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  227190. {
  227191. const ScopedAutoReleasePool pool;
  227192. monitorCoords.clear();
  227193. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  227194. : [[UIScreen mainScreen] bounds];
  227195. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  227196. }
  227197. const int KeyPress::spaceKey = ' ';
  227198. const int KeyPress::returnKey = 0x0d;
  227199. const int KeyPress::escapeKey = 0x1b;
  227200. const int KeyPress::backspaceKey = 0x7f;
  227201. const int KeyPress::leftKey = 0x1000;
  227202. const int KeyPress::rightKey = 0x1001;
  227203. const int KeyPress::upKey = 0x1002;
  227204. const int KeyPress::downKey = 0x1003;
  227205. const int KeyPress::pageUpKey = 0x1004;
  227206. const int KeyPress::pageDownKey = 0x1005;
  227207. const int KeyPress::endKey = 0x1006;
  227208. const int KeyPress::homeKey = 0x1007;
  227209. const int KeyPress::deleteKey = 0x1008;
  227210. const int KeyPress::insertKey = -1;
  227211. const int KeyPress::tabKey = 9;
  227212. const int KeyPress::F1Key = 0x2001;
  227213. const int KeyPress::F2Key = 0x2002;
  227214. const int KeyPress::F3Key = 0x2003;
  227215. const int KeyPress::F4Key = 0x2004;
  227216. const int KeyPress::F5Key = 0x2005;
  227217. const int KeyPress::F6Key = 0x2006;
  227218. const int KeyPress::F7Key = 0x2007;
  227219. const int KeyPress::F8Key = 0x2008;
  227220. const int KeyPress::F9Key = 0x2009;
  227221. const int KeyPress::F10Key = 0x200a;
  227222. const int KeyPress::F11Key = 0x200b;
  227223. const int KeyPress::F12Key = 0x200c;
  227224. const int KeyPress::F13Key = 0x200d;
  227225. const int KeyPress::F14Key = 0x200e;
  227226. const int KeyPress::F15Key = 0x200f;
  227227. const int KeyPress::F16Key = 0x2010;
  227228. const int KeyPress::numberPad0 = 0x30020;
  227229. const int KeyPress::numberPad1 = 0x30021;
  227230. const int KeyPress::numberPad2 = 0x30022;
  227231. const int KeyPress::numberPad3 = 0x30023;
  227232. const int KeyPress::numberPad4 = 0x30024;
  227233. const int KeyPress::numberPad5 = 0x30025;
  227234. const int KeyPress::numberPad6 = 0x30026;
  227235. const int KeyPress::numberPad7 = 0x30027;
  227236. const int KeyPress::numberPad8 = 0x30028;
  227237. const int KeyPress::numberPad9 = 0x30029;
  227238. const int KeyPress::numberPadAdd = 0x3002a;
  227239. const int KeyPress::numberPadSubtract = 0x3002b;
  227240. const int KeyPress::numberPadMultiply = 0x3002c;
  227241. const int KeyPress::numberPadDivide = 0x3002d;
  227242. const int KeyPress::numberPadSeparator = 0x3002e;
  227243. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227244. const int KeyPress::numberPadEquals = 0x30030;
  227245. const int KeyPress::numberPadDelete = 0x30031;
  227246. const int KeyPress::playKey = 0x30000;
  227247. const int KeyPress::stopKey = 0x30001;
  227248. const int KeyPress::fastForwardKey = 0x30002;
  227249. const int KeyPress::rewindKey = 0x30003;
  227250. #endif
  227251. /*** End of inlined file: juce_ios_UIViewComponentPeer.mm ***/
  227252. /*** Start of inlined file: juce_ios_MessageManager.mm ***/
  227253. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227254. // compiled on its own).
  227255. #if JUCE_INCLUDED_FILE
  227256. struct CallbackMessagePayload
  227257. {
  227258. MessageCallbackFunction* function;
  227259. void* parameter;
  227260. void* volatile result;
  227261. bool volatile hasBeenExecuted;
  227262. };
  227263. END_JUCE_NAMESPACE
  227264. @interface JuceCustomMessageHandler : NSObject
  227265. {
  227266. }
  227267. - (void) performCallback: (id) info;
  227268. @end
  227269. @implementation JuceCustomMessageHandler
  227270. - (void) performCallback: (id) info
  227271. {
  227272. if ([info isKindOfClass: [NSData class]])
  227273. {
  227274. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227275. if (pl != 0)
  227276. {
  227277. pl->result = (*pl->function) (pl->parameter);
  227278. pl->hasBeenExecuted = true;
  227279. }
  227280. }
  227281. else
  227282. {
  227283. jassertfalse; // should never get here!
  227284. }
  227285. }
  227286. @end
  227287. BEGIN_JUCE_NAMESPACE
  227288. void MessageManager::runDispatchLoop()
  227289. {
  227290. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227291. runDispatchLoopUntil (-1);
  227292. }
  227293. void MessageManager::stopDispatchLoop()
  227294. {
  227295. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  227296. exit (0); // iPhone apps get no mercy..
  227297. }
  227298. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  227299. {
  227300. const ScopedAutoReleasePool pool;
  227301. jassert (isThisTheMessageThread()); // must only be called by the message thread
  227302. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  227303. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  227304. while (! quitMessagePosted)
  227305. {
  227306. const ScopedAutoReleasePool pool;
  227307. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  227308. beforeDate: endDate];
  227309. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  227310. break;
  227311. }
  227312. return ! quitMessagePosted;
  227313. }
  227314. struct MessageDispatchSystem
  227315. {
  227316. MessageDispatchSystem()
  227317. : juceCustomMessageHandler (0)
  227318. {
  227319. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  227320. }
  227321. ~MessageDispatchSystem()
  227322. {
  227323. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  227324. [juceCustomMessageHandler release];
  227325. }
  227326. JuceCustomMessageHandler* juceCustomMessageHandler;
  227327. MessageQueue messageQueue;
  227328. };
  227329. static MessageDispatchSystem* dispatcher = 0;
  227330. void MessageManager::doPlatformSpecificInitialisation()
  227331. {
  227332. if (dispatcher == 0)
  227333. dispatcher = new MessageDispatchSystem();
  227334. }
  227335. void MessageManager::doPlatformSpecificShutdown()
  227336. {
  227337. deleteAndZero (dispatcher);
  227338. }
  227339. bool juce_postMessageToSystemQueue (Message* message)
  227340. {
  227341. if (dispatcher != 0)
  227342. dispatcher->messageQueue.post (message);
  227343. return true;
  227344. }
  227345. void MessageManager::broadcastMessage (const String& value)
  227346. {
  227347. }
  227348. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  227349. {
  227350. if (isThisTheMessageThread())
  227351. {
  227352. return (*callback) (data);
  227353. }
  227354. else
  227355. {
  227356. jassert (dispatcher != 0); // trying to call this when the juce system isn't initialised..
  227357. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  227358. // deadlock because the message manager is blocked from running, so can never
  227359. // call your function..
  227360. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  227361. const ScopedAutoReleasePool pool;
  227362. CallbackMessagePayload cmp;
  227363. cmp.function = callback;
  227364. cmp.parameter = data;
  227365. cmp.result = 0;
  227366. cmp.hasBeenExecuted = false;
  227367. [dispatcher->juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  227368. withObject: [NSData dataWithBytesNoCopy: &cmp
  227369. length: sizeof (cmp)
  227370. freeWhenDone: NO]
  227371. waitUntilDone: YES];
  227372. return cmp.result;
  227373. }
  227374. }
  227375. #endif
  227376. /*** End of inlined file: juce_ios_MessageManager.mm ***/
  227377. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  227378. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227379. // compiled on its own).
  227380. #if JUCE_INCLUDED_FILE
  227381. #if JUCE_MAC
  227382. END_JUCE_NAMESPACE
  227383. using namespace JUCE_NAMESPACE;
  227384. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  227385. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  227386. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  227387. #else
  227388. @interface JuceFileChooserDelegate : NSObject
  227389. #endif
  227390. {
  227391. StringArray* filters;
  227392. }
  227393. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  227394. - (void) dealloc;
  227395. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  227396. @end
  227397. @implementation JuceFileChooserDelegate
  227398. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  227399. {
  227400. [super init];
  227401. filters = filters_;
  227402. return self;
  227403. }
  227404. - (void) dealloc
  227405. {
  227406. delete filters;
  227407. [super dealloc];
  227408. }
  227409. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  227410. {
  227411. (void) sender;
  227412. const File f (nsStringToJuce (filename));
  227413. for (int i = filters->size(); --i >= 0;)
  227414. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  227415. return true;
  227416. return f.isDirectory();
  227417. }
  227418. @end
  227419. BEGIN_JUCE_NAMESPACE
  227420. void FileChooser::showPlatformDialog (Array<File>& results,
  227421. const String& title,
  227422. const File& currentFileOrDirectory,
  227423. const String& filter,
  227424. bool selectsDirectory,
  227425. bool selectsFiles,
  227426. bool isSaveDialogue,
  227427. bool /*warnAboutOverwritingExistingFiles*/,
  227428. bool selectMultipleFiles,
  227429. FilePreviewComponent* /*extraInfoComponent*/)
  227430. {
  227431. const ScopedAutoReleasePool pool;
  227432. StringArray* filters = new StringArray();
  227433. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  227434. filters->trim();
  227435. filters->removeEmptyStrings();
  227436. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  227437. [delegate autorelease];
  227438. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  227439. : [NSOpenPanel openPanel];
  227440. [panel setTitle: juceStringToNS (title)];
  227441. if (! isSaveDialogue)
  227442. {
  227443. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227444. [openPanel setCanChooseDirectories: selectsDirectory];
  227445. [openPanel setCanChooseFiles: selectsFiles];
  227446. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  227447. }
  227448. [panel setDelegate: delegate];
  227449. if (isSaveDialogue || selectsDirectory)
  227450. [panel setCanCreateDirectories: YES];
  227451. String directory, filename;
  227452. if (currentFileOrDirectory.isDirectory())
  227453. {
  227454. directory = currentFileOrDirectory.getFullPathName();
  227455. }
  227456. else
  227457. {
  227458. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  227459. filename = currentFileOrDirectory.getFileName();
  227460. }
  227461. if ([panel runModalForDirectory: juceStringToNS (directory)
  227462. file: juceStringToNS (filename)]
  227463. == NSOKButton)
  227464. {
  227465. if (isSaveDialogue)
  227466. {
  227467. results.add (File (nsStringToJuce ([panel filename])));
  227468. }
  227469. else
  227470. {
  227471. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  227472. NSArray* urls = [openPanel filenames];
  227473. for (unsigned int i = 0; i < [urls count]; ++i)
  227474. {
  227475. NSString* f = [urls objectAtIndex: i];
  227476. results.add (File (nsStringToJuce (f)));
  227477. }
  227478. }
  227479. }
  227480. [panel setDelegate: nil];
  227481. }
  227482. #else
  227483. void FileChooser::showPlatformDialog (Array<File>& results,
  227484. const String& title,
  227485. const File& currentFileOrDirectory,
  227486. const String& filter,
  227487. bool selectsDirectory,
  227488. bool selectsFiles,
  227489. bool isSaveDialogue,
  227490. bool warnAboutOverwritingExistingFiles,
  227491. bool selectMultipleFiles,
  227492. FilePreviewComponent* extraInfoComponent)
  227493. {
  227494. const ScopedAutoReleasePool pool;
  227495. jassertfalse; //xxx to do
  227496. }
  227497. #endif
  227498. #endif
  227499. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  227500. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  227501. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227502. // compiled on its own).
  227503. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  227504. #if JUCE_MAC
  227505. END_JUCE_NAMESPACE
  227506. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  227507. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  227508. {
  227509. CriticalSection* contextLock;
  227510. bool needsUpdate;
  227511. }
  227512. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  227513. - (bool) makeActive;
  227514. - (void) makeInactive;
  227515. - (void) reshape;
  227516. @end
  227517. @implementation ThreadSafeNSOpenGLView
  227518. - (id) initWithFrame: (NSRect) frameRect
  227519. pixelFormat: (NSOpenGLPixelFormat*) format
  227520. {
  227521. contextLock = new CriticalSection();
  227522. self = [super initWithFrame: frameRect pixelFormat: format];
  227523. if (self != nil)
  227524. [[NSNotificationCenter defaultCenter] addObserver: self
  227525. selector: @selector (_surfaceNeedsUpdate:)
  227526. name: NSViewGlobalFrameDidChangeNotification
  227527. object: self];
  227528. return self;
  227529. }
  227530. - (void) dealloc
  227531. {
  227532. [[NSNotificationCenter defaultCenter] removeObserver: self];
  227533. delete contextLock;
  227534. [super dealloc];
  227535. }
  227536. - (bool) makeActive
  227537. {
  227538. const ScopedLock sl (*contextLock);
  227539. if ([self openGLContext] == 0)
  227540. return false;
  227541. [[self openGLContext] makeCurrentContext];
  227542. if (needsUpdate)
  227543. {
  227544. [super update];
  227545. needsUpdate = false;
  227546. }
  227547. return true;
  227548. }
  227549. - (void) makeInactive
  227550. {
  227551. const ScopedLock sl (*contextLock);
  227552. [NSOpenGLContext clearCurrentContext];
  227553. }
  227554. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  227555. {
  227556. (void) notification;
  227557. const ScopedLock sl (*contextLock);
  227558. needsUpdate = true;
  227559. }
  227560. - (void) update
  227561. {
  227562. const ScopedLock sl (*contextLock);
  227563. needsUpdate = true;
  227564. }
  227565. - (void) reshape
  227566. {
  227567. const ScopedLock sl (*contextLock);
  227568. needsUpdate = true;
  227569. }
  227570. @end
  227571. BEGIN_JUCE_NAMESPACE
  227572. class WindowedGLContext : public OpenGLContext
  227573. {
  227574. public:
  227575. WindowedGLContext (Component& component,
  227576. const OpenGLPixelFormat& pixelFormat_,
  227577. NSOpenGLContext* sharedContext)
  227578. : renderContext (0),
  227579. pixelFormat (pixelFormat_)
  227580. {
  227581. NSOpenGLPixelFormatAttribute attribs [64];
  227582. int n = 0;
  227583. attribs[n++] = NSOpenGLPFADoubleBuffer;
  227584. attribs[n++] = NSOpenGLPFAAccelerated;
  227585. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  227586. attribs[n++] = NSOpenGLPFAColorSize;
  227587. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  227588. pixelFormat.greenBits,
  227589. pixelFormat.blueBits);
  227590. attribs[n++] = NSOpenGLPFAAlphaSize;
  227591. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  227592. attribs[n++] = NSOpenGLPFADepthSize;
  227593. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  227594. attribs[n++] = NSOpenGLPFAStencilSize;
  227595. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  227596. attribs[n++] = NSOpenGLPFAAccumSize;
  227597. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  227598. pixelFormat.accumulationBufferGreenBits,
  227599. pixelFormat.accumulationBufferBlueBits,
  227600. pixelFormat.accumulationBufferAlphaBits);
  227601. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  227602. attribs[n++] = NSOpenGLPFASampleBuffers;
  227603. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  227604. attribs[n++] = NSOpenGLPFAClosestPolicy;
  227605. attribs[n++] = NSOpenGLPFANoRecovery;
  227606. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  227607. NSOpenGLPixelFormat* format
  227608. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  227609. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  227610. pixelFormat: format];
  227611. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  227612. shareContext: sharedContext] autorelease];
  227613. const GLint swapInterval = 1;
  227614. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  227615. [view setOpenGLContext: renderContext];
  227616. [format release];
  227617. viewHolder = new NSViewComponentInternal (view, component);
  227618. }
  227619. ~WindowedGLContext()
  227620. {
  227621. deleteContext();
  227622. viewHolder = 0;
  227623. }
  227624. void deleteContext()
  227625. {
  227626. makeInactive();
  227627. [renderContext clearDrawable];
  227628. [renderContext setView: nil];
  227629. [view setOpenGLContext: nil];
  227630. renderContext = nil;
  227631. }
  227632. bool makeActive() const throw()
  227633. {
  227634. jassert (renderContext != 0);
  227635. if ([renderContext view] != view)
  227636. [renderContext setView: view];
  227637. [view makeActive];
  227638. return isActive();
  227639. }
  227640. bool makeInactive() const throw()
  227641. {
  227642. [view makeInactive];
  227643. return true;
  227644. }
  227645. bool isActive() const throw()
  227646. {
  227647. return [NSOpenGLContext currentContext] == renderContext;
  227648. }
  227649. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227650. void* getRawContext() const throw() { return renderContext; }
  227651. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  227652. {
  227653. }
  227654. void swapBuffers()
  227655. {
  227656. [renderContext flushBuffer];
  227657. }
  227658. bool setSwapInterval (const int numFramesPerSwap)
  227659. {
  227660. [renderContext setValues: (const GLint*) &numFramesPerSwap
  227661. forParameter: NSOpenGLCPSwapInterval];
  227662. return true;
  227663. }
  227664. int getSwapInterval() const
  227665. {
  227666. GLint numFrames = 0;
  227667. [renderContext getValues: &numFrames
  227668. forParameter: NSOpenGLCPSwapInterval];
  227669. return numFrames;
  227670. }
  227671. void repaint()
  227672. {
  227673. // we need to invalidate the juce view that holds this gl view, to make it
  227674. // cause a repaint callback
  227675. NSView* v = (NSView*) viewHolder->view;
  227676. NSRect r = [v frame];
  227677. // bit of a bodge here.. if we only invalidate the area of the gl component,
  227678. // it's completely covered by the NSOpenGLView, so the OS throws away the
  227679. // repaint message, thus never causing our paint() callback, and never repainting
  227680. // the comp. So invalidating just a little bit around the edge helps..
  227681. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  227682. }
  227683. void* getNativeWindowHandle() const { return viewHolder->view; }
  227684. NSOpenGLContext* renderContext;
  227685. ThreadSafeNSOpenGLView* view;
  227686. private:
  227687. OpenGLPixelFormat pixelFormat;
  227688. ScopedPointer <NSViewComponentInternal> viewHolder;
  227689. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  227690. };
  227691. OpenGLContext* OpenGLComponent::createContext()
  227692. {
  227693. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  227694. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  227695. return (c->renderContext != 0) ? c.release() : 0;
  227696. }
  227697. void* OpenGLComponent::getNativeWindowHandle() const
  227698. {
  227699. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  227700. : 0;
  227701. }
  227702. void juce_glViewport (const int w, const int h)
  227703. {
  227704. glViewport (0, 0, w, h);
  227705. }
  227706. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227707. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227708. {
  227709. /* GLint attribs [64];
  227710. int n = 0;
  227711. attribs[n++] = AGL_RGBA;
  227712. attribs[n++] = AGL_DOUBLEBUFFER;
  227713. attribs[n++] = AGL_ACCELERATED;
  227714. attribs[n++] = AGL_NO_RECOVERY;
  227715. attribs[n++] = AGL_NONE;
  227716. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  227717. while (p != 0)
  227718. {
  227719. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  227720. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  227721. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  227722. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  227723. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  227724. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  227725. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  227726. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  227727. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  227728. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  227729. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  227730. results.add (pf);
  227731. p = aglNextPixelFormat (p);
  227732. }*/
  227733. //jassertfalse // can't see how you do this in cocoa!
  227734. }
  227735. #else
  227736. END_JUCE_NAMESPACE
  227737. @interface JuceGLView : UIView
  227738. {
  227739. }
  227740. + (Class) layerClass;
  227741. @end
  227742. @implementation JuceGLView
  227743. + (Class) layerClass
  227744. {
  227745. return [CAEAGLLayer class];
  227746. }
  227747. @end
  227748. BEGIN_JUCE_NAMESPACE
  227749. class GLESContext : public OpenGLContext
  227750. {
  227751. public:
  227752. GLESContext (UIViewComponentPeer* peer,
  227753. Component* const component_,
  227754. const OpenGLPixelFormat& pixelFormat_,
  227755. const GLESContext* const sharedContext,
  227756. NSUInteger apiType)
  227757. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  227758. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  227759. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  227760. {
  227761. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  227762. view.opaque = YES;
  227763. view.hidden = NO;
  227764. view.backgroundColor = [UIColor blackColor];
  227765. view.userInteractionEnabled = NO;
  227766. glLayer = (CAEAGLLayer*) [view layer];
  227767. [peer->view addSubview: view];
  227768. if (sharedContext != 0)
  227769. context = [[EAGLContext alloc] initWithAPI: apiType
  227770. sharegroup: [sharedContext->context sharegroup]];
  227771. else
  227772. context = [[EAGLContext alloc] initWithAPI: apiType];
  227773. createGLBuffers();
  227774. }
  227775. ~GLESContext()
  227776. {
  227777. deleteContext();
  227778. [view removeFromSuperview];
  227779. [view release];
  227780. freeGLBuffers();
  227781. }
  227782. void deleteContext()
  227783. {
  227784. makeInactive();
  227785. [context release];
  227786. context = nil;
  227787. }
  227788. bool makeActive() const throw()
  227789. {
  227790. jassert (context != 0);
  227791. [EAGLContext setCurrentContext: context];
  227792. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227793. return true;
  227794. }
  227795. void swapBuffers()
  227796. {
  227797. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227798. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  227799. }
  227800. bool makeInactive() const throw()
  227801. {
  227802. return [EAGLContext setCurrentContext: nil];
  227803. }
  227804. bool isActive() const throw()
  227805. {
  227806. return [EAGLContext currentContext] == context;
  227807. }
  227808. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  227809. void* getRawContext() const throw() { return glLayer; }
  227810. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  227811. {
  227812. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  227813. if (lastWidth != w || lastHeight != h)
  227814. {
  227815. lastWidth = w;
  227816. lastHeight = h;
  227817. freeGLBuffers();
  227818. createGLBuffers();
  227819. }
  227820. }
  227821. bool setSwapInterval (const int numFramesPerSwap)
  227822. {
  227823. numFrames = numFramesPerSwap;
  227824. return true;
  227825. }
  227826. int getSwapInterval() const
  227827. {
  227828. return numFrames;
  227829. }
  227830. void repaint()
  227831. {
  227832. }
  227833. void createGLBuffers()
  227834. {
  227835. makeActive();
  227836. glGenFramebuffersOES (1, &frameBufferHandle);
  227837. glGenRenderbuffersOES (1, &colorBufferHandle);
  227838. glGenRenderbuffersOES (1, &depthBufferHandle);
  227839. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227840. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  227841. GLint width, height;
  227842. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  227843. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  227844. if (useDepthBuffer)
  227845. {
  227846. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  227847. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  227848. }
  227849. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  227850. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  227851. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  227852. if (useDepthBuffer)
  227853. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  227854. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  227855. }
  227856. void freeGLBuffers()
  227857. {
  227858. if (frameBufferHandle != 0)
  227859. {
  227860. glDeleteFramebuffersOES (1, &frameBufferHandle);
  227861. frameBufferHandle = 0;
  227862. }
  227863. if (colorBufferHandle != 0)
  227864. {
  227865. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  227866. colorBufferHandle = 0;
  227867. }
  227868. if (depthBufferHandle != 0)
  227869. {
  227870. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  227871. depthBufferHandle = 0;
  227872. }
  227873. }
  227874. private:
  227875. WeakReference<Component> component;
  227876. OpenGLPixelFormat pixelFormat;
  227877. JuceGLView* view;
  227878. CAEAGLLayer* glLayer;
  227879. EAGLContext* context;
  227880. bool useDepthBuffer;
  227881. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  227882. int numFrames;
  227883. int lastWidth, lastHeight;
  227884. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  227885. };
  227886. OpenGLContext* OpenGLComponent::createContext()
  227887. {
  227888. ScopedAutoReleasePool pool;
  227889. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  227890. if (peer != 0)
  227891. return new GLESContext (peer, this, preferredPixelFormat,
  227892. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  227893. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  227894. return 0;
  227895. }
  227896. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  227897. OwnedArray <OpenGLPixelFormat>& /*results*/)
  227898. {
  227899. }
  227900. void juce_glViewport (const int w, const int h)
  227901. {
  227902. glViewport (0, 0, w, h);
  227903. }
  227904. #endif
  227905. #endif
  227906. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  227907. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  227908. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227909. // compiled on its own).
  227910. #if JUCE_INCLUDED_FILE
  227911. #if JUCE_MAC
  227912. namespace MouseCursorHelpers
  227913. {
  227914. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  227915. {
  227916. NSImage* im = CoreGraphicsImage::createNSImage (image);
  227917. NSCursor* c = [[NSCursor alloc] initWithImage: im
  227918. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  227919. [im release];
  227920. return c;
  227921. }
  227922. static void* fromWebKitFile (const char* filename, float hx, float hy)
  227923. {
  227924. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  227925. BufferedInputStream buf (fileStream, 4096);
  227926. PNGImageFormat pngFormat;
  227927. Image im (pngFormat.decodeImage (buf));
  227928. if (im.isValid())
  227929. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  227930. jassertfalse;
  227931. return 0;
  227932. }
  227933. }
  227934. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  227935. {
  227936. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  227937. }
  227938. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  227939. {
  227940. const ScopedAutoReleasePool pool;
  227941. NSCursor* c = 0;
  227942. switch (type)
  227943. {
  227944. case NormalCursor: c = [NSCursor arrowCursor]; break;
  227945. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  227946. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  227947. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  227948. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  227949. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  227950. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  227951. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  227952. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  227953. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  227954. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  227955. case UpDownResizeCursor:
  227956. case TopEdgeResizeCursor:
  227957. case BottomEdgeResizeCursor:
  227958. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  227959. case TopLeftCornerResizeCursor:
  227960. case BottomRightCornerResizeCursor:
  227961. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  227962. case TopRightCornerResizeCursor:
  227963. case BottomLeftCornerResizeCursor:
  227964. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  227965. case UpDownLeftRightResizeCursor:
  227966. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  227967. default:
  227968. jassertfalse;
  227969. break;
  227970. }
  227971. [c retain];
  227972. return c;
  227973. }
  227974. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  227975. {
  227976. [((NSCursor*) cursorHandle) release];
  227977. }
  227978. void MouseCursor::showInAllWindows() const
  227979. {
  227980. showInWindow (0);
  227981. }
  227982. void MouseCursor::showInWindow (ComponentPeer*) const
  227983. {
  227984. NSCursor* c = (NSCursor*) getHandle();
  227985. if (c == 0)
  227986. c = [NSCursor arrowCursor];
  227987. [c set];
  227988. }
  227989. #else
  227990. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  227991. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  227992. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  227993. void MouseCursor::showInAllWindows() const {}
  227994. void MouseCursor::showInWindow (ComponentPeer*) const {}
  227995. #endif
  227996. #endif
  227997. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  227998. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  227999. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228000. // compiled on its own).
  228001. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228002. #if JUCE_MAC
  228003. END_JUCE_NAMESPACE
  228004. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228005. @interface DownloadClickDetector : NSObject
  228006. {
  228007. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228008. }
  228009. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228010. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228011. request: (NSURLRequest*) request
  228012. frame: (WebFrame*) frame
  228013. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228014. @end
  228015. @implementation DownloadClickDetector
  228016. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228017. {
  228018. [super init];
  228019. ownerComponent = ownerComponent_;
  228020. return self;
  228021. }
  228022. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228023. request: (NSURLRequest*) request
  228024. frame: (WebFrame*) frame
  228025. decisionListener: (id <WebPolicyDecisionListener>) listener
  228026. {
  228027. (void) sender;
  228028. (void) request;
  228029. (void) frame;
  228030. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228031. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228032. [listener use];
  228033. else
  228034. [listener ignore];
  228035. }
  228036. @end
  228037. BEGIN_JUCE_NAMESPACE
  228038. class WebBrowserComponentInternal : public NSViewComponent
  228039. {
  228040. public:
  228041. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228042. {
  228043. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228044. frameName: @""
  228045. groupName: @""];
  228046. setView (webView);
  228047. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228048. [webView setPolicyDelegate: clickListener];
  228049. }
  228050. ~WebBrowserComponentInternal()
  228051. {
  228052. [webView setPolicyDelegate: nil];
  228053. [clickListener release];
  228054. setView (0);
  228055. }
  228056. void goToURL (const String& url,
  228057. const StringArray* headers,
  228058. const MemoryBlock* postData)
  228059. {
  228060. NSMutableURLRequest* r
  228061. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228062. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228063. timeoutInterval: 30.0];
  228064. if (postData != 0 && postData->getSize() > 0)
  228065. {
  228066. [r setHTTPMethod: @"POST"];
  228067. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228068. length: postData->getSize()]];
  228069. }
  228070. if (headers != 0)
  228071. {
  228072. for (int i = 0; i < headers->size(); ++i)
  228073. {
  228074. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228075. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228076. [r setValue: juceStringToNS (headerValue)
  228077. forHTTPHeaderField: juceStringToNS (headerName)];
  228078. }
  228079. }
  228080. stop();
  228081. [[webView mainFrame] loadRequest: r];
  228082. }
  228083. void goBack()
  228084. {
  228085. [webView goBack];
  228086. }
  228087. void goForward()
  228088. {
  228089. [webView goForward];
  228090. }
  228091. void stop()
  228092. {
  228093. [webView stopLoading: nil];
  228094. }
  228095. void refresh()
  228096. {
  228097. [webView reload: nil];
  228098. }
  228099. void mouseMove (const MouseEvent&)
  228100. {
  228101. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  228102. // them work is to push them via this non-public method..
  228103. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  228104. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  228105. }
  228106. private:
  228107. WebView* webView;
  228108. DownloadClickDetector* clickListener;
  228109. };
  228110. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228111. : browser (0),
  228112. blankPageShown (false),
  228113. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228114. {
  228115. setOpaque (true);
  228116. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228117. }
  228118. WebBrowserComponent::~WebBrowserComponent()
  228119. {
  228120. deleteAndZero (browser);
  228121. }
  228122. void WebBrowserComponent::goToURL (const String& url,
  228123. const StringArray* headers,
  228124. const MemoryBlock* postData)
  228125. {
  228126. lastURL = url;
  228127. lastHeaders.clear();
  228128. if (headers != 0)
  228129. lastHeaders = *headers;
  228130. lastPostData.setSize (0);
  228131. if (postData != 0)
  228132. lastPostData = *postData;
  228133. blankPageShown = false;
  228134. browser->goToURL (url, headers, postData);
  228135. }
  228136. void WebBrowserComponent::stop()
  228137. {
  228138. browser->stop();
  228139. }
  228140. void WebBrowserComponent::goBack()
  228141. {
  228142. lastURL = String::empty;
  228143. blankPageShown = false;
  228144. browser->goBack();
  228145. }
  228146. void WebBrowserComponent::goForward()
  228147. {
  228148. lastURL = String::empty;
  228149. browser->goForward();
  228150. }
  228151. void WebBrowserComponent::refresh()
  228152. {
  228153. browser->refresh();
  228154. }
  228155. void WebBrowserComponent::paint (Graphics&)
  228156. {
  228157. }
  228158. void WebBrowserComponent::checkWindowAssociation()
  228159. {
  228160. if (isShowing())
  228161. {
  228162. if (blankPageShown)
  228163. goBack();
  228164. }
  228165. else
  228166. {
  228167. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228168. {
  228169. // when the component becomes invisible, some stuff like flash
  228170. // carries on playing audio, so we need to force it onto a blank
  228171. // page to avoid this, (and send it back when it's made visible again).
  228172. blankPageShown = true;
  228173. browser->goToURL ("about:blank", 0, 0);
  228174. }
  228175. }
  228176. }
  228177. void WebBrowserComponent::reloadLastURL()
  228178. {
  228179. if (lastURL.isNotEmpty())
  228180. {
  228181. goToURL (lastURL, &lastHeaders, &lastPostData);
  228182. lastURL = String::empty;
  228183. }
  228184. }
  228185. void WebBrowserComponent::parentHierarchyChanged()
  228186. {
  228187. checkWindowAssociation();
  228188. }
  228189. void WebBrowserComponent::resized()
  228190. {
  228191. browser->setSize (getWidth(), getHeight());
  228192. }
  228193. void WebBrowserComponent::visibilityChanged()
  228194. {
  228195. checkWindowAssociation();
  228196. }
  228197. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228198. {
  228199. return true;
  228200. }
  228201. #else
  228202. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228203. {
  228204. }
  228205. WebBrowserComponent::~WebBrowserComponent()
  228206. {
  228207. }
  228208. void WebBrowserComponent::goToURL (const String& url,
  228209. const StringArray* headers,
  228210. const MemoryBlock* postData)
  228211. {
  228212. }
  228213. void WebBrowserComponent::stop()
  228214. {
  228215. }
  228216. void WebBrowserComponent::goBack()
  228217. {
  228218. }
  228219. void WebBrowserComponent::goForward()
  228220. {
  228221. }
  228222. void WebBrowserComponent::refresh()
  228223. {
  228224. }
  228225. void WebBrowserComponent::paint (Graphics& g)
  228226. {
  228227. }
  228228. void WebBrowserComponent::checkWindowAssociation()
  228229. {
  228230. }
  228231. void WebBrowserComponent::reloadLastURL()
  228232. {
  228233. }
  228234. void WebBrowserComponent::parentHierarchyChanged()
  228235. {
  228236. }
  228237. void WebBrowserComponent::resized()
  228238. {
  228239. }
  228240. void WebBrowserComponent::visibilityChanged()
  228241. {
  228242. }
  228243. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228244. {
  228245. return true;
  228246. }
  228247. #endif
  228248. #endif
  228249. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228250. /*** Start of inlined file: juce_ios_Audio.cpp ***/
  228251. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228252. // compiled on its own).
  228253. #if JUCE_INCLUDED_FILE
  228254. class IPhoneAudioIODevice : public AudioIODevice
  228255. {
  228256. public:
  228257. IPhoneAudioIODevice (const String& deviceName)
  228258. : AudioIODevice (deviceName, "Audio"),
  228259. actualBufferSize (0),
  228260. isRunning (false),
  228261. audioUnit (0),
  228262. callback (0),
  228263. floatData (1, 2)
  228264. {
  228265. numInputChannels = 2;
  228266. numOutputChannels = 2;
  228267. preferredBufferSize = 0;
  228268. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  228269. updateDeviceInfo();
  228270. }
  228271. ~IPhoneAudioIODevice()
  228272. {
  228273. close();
  228274. }
  228275. const StringArray getOutputChannelNames()
  228276. {
  228277. StringArray s;
  228278. s.add ("Left");
  228279. s.add ("Right");
  228280. return s;
  228281. }
  228282. const StringArray getInputChannelNames()
  228283. {
  228284. StringArray s;
  228285. if (audioInputIsAvailable)
  228286. {
  228287. s.add ("Left");
  228288. s.add ("Right");
  228289. }
  228290. return s;
  228291. }
  228292. int getNumSampleRates()
  228293. {
  228294. return 1;
  228295. }
  228296. double getSampleRate (int index)
  228297. {
  228298. return sampleRate;
  228299. }
  228300. int getNumBufferSizesAvailable()
  228301. {
  228302. return 1;
  228303. }
  228304. int getBufferSizeSamples (int index)
  228305. {
  228306. return getDefaultBufferSize();
  228307. }
  228308. int getDefaultBufferSize()
  228309. {
  228310. return 1024;
  228311. }
  228312. const String open (const BigInteger& inputChannels,
  228313. const BigInteger& outputChannels,
  228314. double sampleRate,
  228315. int bufferSize)
  228316. {
  228317. close();
  228318. lastError = String::empty;
  228319. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  228320. // xxx set up channel mapping
  228321. activeOutputChans = outputChannels;
  228322. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  228323. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  228324. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  228325. activeInputChans = inputChannels;
  228326. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  228327. numInputChannels = activeInputChans.countNumberOfSetBits();
  228328. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  228329. AudioSessionSetActive (true);
  228330. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  228331. : kAudioSessionCategory_MediaPlayback;
  228332. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  228333. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  228334. fixAudioRouteIfSetToReceiver();
  228335. updateDeviceInfo();
  228336. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228337. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  228338. actualBufferSize = preferredBufferSize;
  228339. prepareFloatBuffers();
  228340. isRunning = true;
  228341. propertyChanged (0, 0, 0); // creates and starts the AU
  228342. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  228343. return lastError;
  228344. }
  228345. void close()
  228346. {
  228347. if (isRunning)
  228348. {
  228349. isRunning = false;
  228350. AudioSessionSetActive (false);
  228351. if (audioUnit != 0)
  228352. {
  228353. AudioComponentInstanceDispose (audioUnit);
  228354. audioUnit = 0;
  228355. }
  228356. }
  228357. }
  228358. bool isOpen()
  228359. {
  228360. return isRunning;
  228361. }
  228362. int getCurrentBufferSizeSamples()
  228363. {
  228364. return actualBufferSize;
  228365. }
  228366. double getCurrentSampleRate()
  228367. {
  228368. return sampleRate;
  228369. }
  228370. int getCurrentBitDepth()
  228371. {
  228372. return 16;
  228373. }
  228374. const BigInteger getActiveOutputChannels() const
  228375. {
  228376. return activeOutputChans;
  228377. }
  228378. const BigInteger getActiveInputChannels() const
  228379. {
  228380. return activeInputChans;
  228381. }
  228382. int getOutputLatencyInSamples()
  228383. {
  228384. return 0; //xxx
  228385. }
  228386. int getInputLatencyInSamples()
  228387. {
  228388. return 0; //xxx
  228389. }
  228390. void start (AudioIODeviceCallback* callback_)
  228391. {
  228392. if (isRunning && callback != callback_)
  228393. {
  228394. if (callback_ != 0)
  228395. callback_->audioDeviceAboutToStart (this);
  228396. const ScopedLock sl (callbackLock);
  228397. callback = callback_;
  228398. }
  228399. }
  228400. void stop()
  228401. {
  228402. if (isRunning)
  228403. {
  228404. AudioIODeviceCallback* lastCallback;
  228405. {
  228406. const ScopedLock sl (callbackLock);
  228407. lastCallback = callback;
  228408. callback = 0;
  228409. }
  228410. if (lastCallback != 0)
  228411. lastCallback->audioDeviceStopped();
  228412. }
  228413. }
  228414. bool isPlaying()
  228415. {
  228416. return isRunning && callback != 0;
  228417. }
  228418. const String getLastError()
  228419. {
  228420. return lastError;
  228421. }
  228422. private:
  228423. CriticalSection callbackLock;
  228424. Float64 sampleRate;
  228425. int numInputChannels, numOutputChannels;
  228426. int preferredBufferSize;
  228427. int actualBufferSize;
  228428. bool isRunning;
  228429. String lastError;
  228430. AudioStreamBasicDescription format;
  228431. AudioUnit audioUnit;
  228432. UInt32 audioInputIsAvailable;
  228433. AudioIODeviceCallback* callback;
  228434. BigInteger activeOutputChans, activeInputChans;
  228435. AudioSampleBuffer floatData;
  228436. float* inputChannels[3];
  228437. float* outputChannels[3];
  228438. bool monoInputChannelNumber, monoOutputChannelNumber;
  228439. void prepareFloatBuffers()
  228440. {
  228441. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  228442. zerostruct (inputChannels);
  228443. zerostruct (outputChannels);
  228444. for (int i = 0; i < numInputChannels; ++i)
  228445. inputChannels[i] = floatData.getSampleData (i);
  228446. for (int i = 0; i < numOutputChannels; ++i)
  228447. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  228448. }
  228449. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228450. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228451. {
  228452. OSStatus err = noErr;
  228453. if (audioInputIsAvailable)
  228454. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  228455. const ScopedLock sl (callbackLock);
  228456. if (callback != 0)
  228457. {
  228458. if (audioInputIsAvailable && numInputChannels > 0)
  228459. {
  228460. short* shortData = (short*) ioData->mBuffers[0].mData;
  228461. if (numInputChannels >= 2)
  228462. {
  228463. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228464. {
  228465. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228466. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  228467. }
  228468. }
  228469. else
  228470. {
  228471. if (monoInputChannelNumber > 0)
  228472. ++shortData;
  228473. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228474. {
  228475. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  228476. ++shortData;
  228477. }
  228478. }
  228479. }
  228480. else
  228481. {
  228482. for (int i = numInputChannels; --i >= 0;)
  228483. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  228484. }
  228485. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  228486. outputChannels, numOutputChannels,
  228487. (int) inNumberFrames);
  228488. short* shortData = (short*) ioData->mBuffers[0].mData;
  228489. int n = 0;
  228490. if (numOutputChannels >= 2)
  228491. {
  228492. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228493. {
  228494. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  228495. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  228496. }
  228497. }
  228498. else if (numOutputChannels == 1)
  228499. {
  228500. for (UInt32 i = 0; i < inNumberFrames; ++i)
  228501. {
  228502. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  228503. shortData [n++] = s;
  228504. shortData [n++] = s;
  228505. }
  228506. }
  228507. else
  228508. {
  228509. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228510. }
  228511. }
  228512. else
  228513. {
  228514. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  228515. }
  228516. return err;
  228517. }
  228518. void updateDeviceInfo()
  228519. {
  228520. UInt32 size = sizeof (sampleRate);
  228521. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  228522. size = sizeof (audioInputIsAvailable);
  228523. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  228524. }
  228525. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228526. {
  228527. if (! isRunning)
  228528. return;
  228529. if (inPropertyValue != 0)
  228530. {
  228531. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  228532. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  228533. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  228534. SInt32 routeChangeReason;
  228535. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  228536. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  228537. fixAudioRouteIfSetToReceiver();
  228538. }
  228539. updateDeviceInfo();
  228540. createAudioUnit();
  228541. AudioSessionSetActive (true);
  228542. if (audioUnit != 0)
  228543. {
  228544. UInt32 formatSize = sizeof (format);
  228545. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  228546. Float32 bufferDuration = preferredBufferSize / sampleRate;
  228547. UInt32 bufferDurationSize = sizeof (bufferDuration);
  228548. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  228549. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  228550. AudioOutputUnitStart (audioUnit);
  228551. }
  228552. }
  228553. void interruptionListener (UInt32 inInterruption)
  228554. {
  228555. /*if (inInterruption == kAudioSessionBeginInterruption)
  228556. {
  228557. isRunning = false;
  228558. AudioOutputUnitStop (audioUnit);
  228559. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  228560. "This could have been interrupted by another application or by unplugging a headset",
  228561. @"Resume",
  228562. @"Cancel"))
  228563. {
  228564. isRunning = true;
  228565. propertyChanged (0, 0, 0);
  228566. }
  228567. }*/
  228568. if (inInterruption == kAudioSessionEndInterruption)
  228569. {
  228570. isRunning = true;
  228571. AudioSessionSetActive (true);
  228572. AudioOutputUnitStart (audioUnit);
  228573. }
  228574. }
  228575. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  228576. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  228577. {
  228578. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  228579. }
  228580. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  228581. {
  228582. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  228583. }
  228584. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  228585. {
  228586. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  228587. }
  228588. void resetFormat (const int numChannels)
  228589. {
  228590. memset (&format, 0, sizeof (format));
  228591. format.mFormatID = kAudioFormatLinearPCM;
  228592. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  228593. format.mBitsPerChannel = 8 * sizeof (short);
  228594. format.mChannelsPerFrame = 2;
  228595. format.mFramesPerPacket = 1;
  228596. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  228597. }
  228598. bool createAudioUnit()
  228599. {
  228600. if (audioUnit != 0)
  228601. {
  228602. AudioComponentInstanceDispose (audioUnit);
  228603. audioUnit = 0;
  228604. }
  228605. resetFormat (2);
  228606. AudioComponentDescription desc;
  228607. desc.componentType = kAudioUnitType_Output;
  228608. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  228609. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  228610. desc.componentFlags = 0;
  228611. desc.componentFlagsMask = 0;
  228612. AudioComponent comp = AudioComponentFindNext (0, &desc);
  228613. AudioComponentInstanceNew (comp, &audioUnit);
  228614. if (audioUnit == 0)
  228615. return false;
  228616. const UInt32 one = 1;
  228617. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  228618. AudioChannelLayout layout;
  228619. layout.mChannelBitmap = 0;
  228620. layout.mNumberChannelDescriptions = 0;
  228621. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  228622. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  228623. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  228624. AURenderCallbackStruct inputProc;
  228625. inputProc.inputProc = processStatic;
  228626. inputProc.inputProcRefCon = this;
  228627. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  228628. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  228629. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  228630. AudioUnitInitialize (audioUnit);
  228631. return true;
  228632. }
  228633. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  228634. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  228635. static void fixAudioRouteIfSetToReceiver()
  228636. {
  228637. CFStringRef audioRoute = 0;
  228638. UInt32 propertySize = sizeof (audioRoute);
  228639. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  228640. {
  228641. NSString* route = (NSString*) audioRoute;
  228642. //DBG ("audio route: " + nsStringToJuce (route));
  228643. if ([route hasPrefix: @"Receiver"])
  228644. {
  228645. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  228646. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  228647. }
  228648. CFRelease (audioRoute);
  228649. }
  228650. }
  228651. JUCE_DECLARE_NON_COPYABLE (IPhoneAudioIODevice);
  228652. };
  228653. class IPhoneAudioIODeviceType : public AudioIODeviceType
  228654. {
  228655. public:
  228656. IPhoneAudioIODeviceType()
  228657. : AudioIODeviceType ("iPhone Audio")
  228658. {
  228659. }
  228660. void scanForDevices()
  228661. {
  228662. }
  228663. const StringArray getDeviceNames (bool wantInputNames) const
  228664. {
  228665. StringArray s;
  228666. s.add ("iPhone Audio");
  228667. return s;
  228668. }
  228669. int getDefaultDeviceIndex (bool forInput) const
  228670. {
  228671. return 0;
  228672. }
  228673. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  228674. {
  228675. return device != 0 ? 0 : -1;
  228676. }
  228677. bool hasSeparateInputsAndOutputs() const { return false; }
  228678. AudioIODevice* createDevice (const String& outputDeviceName,
  228679. const String& inputDeviceName)
  228680. {
  228681. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  228682. {
  228683. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  228684. : inputDeviceName);
  228685. }
  228686. return 0;
  228687. }
  228688. private:
  228689. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (IPhoneAudioIODeviceType);
  228690. };
  228691. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  228692. {
  228693. return new IPhoneAudioIODeviceType();
  228694. }
  228695. #endif
  228696. /*** End of inlined file: juce_ios_Audio.cpp ***/
  228697. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  228698. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228699. // compiled on its own).
  228700. #if JUCE_INCLUDED_FILE
  228701. #if JUCE_MAC
  228702. namespace CoreMidiHelpers
  228703. {
  228704. bool logError (const OSStatus err, const int lineNum)
  228705. {
  228706. if (err == noErr)
  228707. return true;
  228708. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  228709. jassertfalse;
  228710. return false;
  228711. }
  228712. #undef CHECK_ERROR
  228713. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  228714. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  228715. {
  228716. String result;
  228717. CFStringRef str = 0;
  228718. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  228719. if (str != 0)
  228720. {
  228721. result = PlatformUtilities::cfStringToJuceString (str);
  228722. CFRelease (str);
  228723. str = 0;
  228724. }
  228725. MIDIEntityRef entity = 0;
  228726. MIDIEndpointGetEntity (endpoint, &entity);
  228727. if (entity == 0)
  228728. return result; // probably virtual
  228729. if (result.isEmpty())
  228730. {
  228731. // endpoint name has zero length - try the entity
  228732. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  228733. if (str != 0)
  228734. {
  228735. result += PlatformUtilities::cfStringToJuceString (str);
  228736. CFRelease (str);
  228737. str = 0;
  228738. }
  228739. }
  228740. // now consider the device's name
  228741. MIDIDeviceRef device = 0;
  228742. MIDIEntityGetDevice (entity, &device);
  228743. if (device == 0)
  228744. return result;
  228745. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  228746. if (str != 0)
  228747. {
  228748. const String s (PlatformUtilities::cfStringToJuceString (str));
  228749. CFRelease (str);
  228750. // if an external device has only one entity, throw away
  228751. // the endpoint name and just use the device name
  228752. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  228753. {
  228754. result = s;
  228755. }
  228756. else if (! result.startsWithIgnoreCase (s))
  228757. {
  228758. // prepend the device name to the entity name
  228759. result = (s + " " + result).trimEnd();
  228760. }
  228761. }
  228762. return result;
  228763. }
  228764. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  228765. {
  228766. String result;
  228767. // Does the endpoint have connections?
  228768. CFDataRef connections = 0;
  228769. int numConnections = 0;
  228770. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  228771. if (connections != 0)
  228772. {
  228773. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  228774. if (numConnections > 0)
  228775. {
  228776. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  228777. for (int i = 0; i < numConnections; ++i, ++pid)
  228778. {
  228779. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  228780. MIDIObjectRef connObject;
  228781. MIDIObjectType connObjectType;
  228782. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  228783. if (err == noErr)
  228784. {
  228785. String s;
  228786. if (connObjectType == kMIDIObjectType_ExternalSource
  228787. || connObjectType == kMIDIObjectType_ExternalDestination)
  228788. {
  228789. // Connected to an external device's endpoint (10.3 and later).
  228790. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  228791. }
  228792. else
  228793. {
  228794. // Connected to an external device (10.2) (or something else, catch-all)
  228795. CFStringRef str = 0;
  228796. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  228797. if (str != 0)
  228798. {
  228799. s = PlatformUtilities::cfStringToJuceString (str);
  228800. CFRelease (str);
  228801. }
  228802. }
  228803. if (s.isNotEmpty())
  228804. {
  228805. if (result.isNotEmpty())
  228806. result += ", ";
  228807. result += s;
  228808. }
  228809. }
  228810. }
  228811. }
  228812. CFRelease (connections);
  228813. }
  228814. if (result.isNotEmpty())
  228815. return result;
  228816. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  228817. return getEndpointName (endpoint, false);
  228818. }
  228819. MIDIClientRef getGlobalMidiClient()
  228820. {
  228821. static MIDIClientRef globalMidiClient = 0;
  228822. if (globalMidiClient == 0)
  228823. {
  228824. String name ("JUCE");
  228825. if (JUCEApplication::getInstance() != 0)
  228826. name = JUCEApplication::getInstance()->getApplicationName();
  228827. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  228828. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  228829. CFRelease (appName);
  228830. }
  228831. return globalMidiClient;
  228832. }
  228833. class MidiPortAndEndpoint
  228834. {
  228835. public:
  228836. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  228837. : port (port_), endPoint (endPoint_)
  228838. {
  228839. }
  228840. ~MidiPortAndEndpoint()
  228841. {
  228842. if (port != 0)
  228843. MIDIPortDispose (port);
  228844. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  228845. MIDIEndpointDispose (endPoint);
  228846. }
  228847. void send (const MIDIPacketList* const packets)
  228848. {
  228849. if (port != 0)
  228850. MIDISend (port, endPoint, packets);
  228851. else
  228852. MIDIReceived (endPoint, packets);
  228853. }
  228854. MIDIPortRef port;
  228855. MIDIEndpointRef endPoint;
  228856. };
  228857. class MidiPortAndCallback;
  228858. CriticalSection callbackLock;
  228859. Array<MidiPortAndCallback*> activeCallbacks;
  228860. class MidiPortAndCallback
  228861. {
  228862. public:
  228863. MidiPortAndCallback (MidiInputCallback& callback_)
  228864. : input (0), active (false), callback (callback_), concatenator (2048)
  228865. {
  228866. }
  228867. ~MidiPortAndCallback()
  228868. {
  228869. active = false;
  228870. {
  228871. const ScopedLock sl (callbackLock);
  228872. activeCallbacks.removeValue (this);
  228873. }
  228874. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  228875. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  228876. }
  228877. void handlePackets (const MIDIPacketList* const pktlist)
  228878. {
  228879. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  228880. const ScopedLock sl (callbackLock);
  228881. if (activeCallbacks.contains (this) && active)
  228882. {
  228883. const MIDIPacket* packet = &pktlist->packet[0];
  228884. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  228885. {
  228886. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  228887. input, callback);
  228888. packet = MIDIPacketNext (packet);
  228889. }
  228890. }
  228891. }
  228892. MidiInput* input;
  228893. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  228894. volatile bool active;
  228895. private:
  228896. MidiInputCallback& callback;
  228897. MidiDataConcatenator concatenator;
  228898. };
  228899. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  228900. {
  228901. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  228902. }
  228903. }
  228904. const StringArray MidiOutput::getDevices()
  228905. {
  228906. StringArray s;
  228907. const ItemCount num = MIDIGetNumberOfDestinations();
  228908. for (ItemCount i = 0; i < num; ++i)
  228909. {
  228910. MIDIEndpointRef dest = MIDIGetDestination (i);
  228911. if (dest != 0)
  228912. {
  228913. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  228914. if (name.isEmpty())
  228915. name = "<error>";
  228916. s.add (name);
  228917. }
  228918. else
  228919. {
  228920. s.add ("<error>");
  228921. }
  228922. }
  228923. return s;
  228924. }
  228925. int MidiOutput::getDefaultDeviceIndex()
  228926. {
  228927. return 0;
  228928. }
  228929. MidiOutput* MidiOutput::openDevice (int index)
  228930. {
  228931. MidiOutput* mo = 0;
  228932. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  228933. {
  228934. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  228935. CFStringRef pname;
  228936. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  228937. {
  228938. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228939. MIDIPortRef port;
  228940. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  228941. {
  228942. mo = new MidiOutput();
  228943. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  228944. }
  228945. CFRelease (pname);
  228946. }
  228947. }
  228948. return mo;
  228949. }
  228950. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  228951. {
  228952. MidiOutput* mo = 0;
  228953. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  228954. MIDIEndpointRef endPoint;
  228955. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  228956. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  228957. {
  228958. mo = new MidiOutput();
  228959. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  228960. }
  228961. CFRelease (name);
  228962. return mo;
  228963. }
  228964. MidiOutput::~MidiOutput()
  228965. {
  228966. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228967. }
  228968. void MidiOutput::reset()
  228969. {
  228970. }
  228971. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  228972. {
  228973. return false;
  228974. }
  228975. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  228976. {
  228977. }
  228978. void MidiOutput::sendMessageNow (const MidiMessage& message)
  228979. {
  228980. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  228981. if (message.isSysEx())
  228982. {
  228983. const int maxPacketSize = 256;
  228984. int pos = 0, bytesLeft = message.getRawDataSize();
  228985. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  228986. HeapBlock <MIDIPacketList> packets;
  228987. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  228988. packets->numPackets = numPackets;
  228989. MIDIPacket* p = packets->packet;
  228990. for (int i = 0; i < numPackets; ++i)
  228991. {
  228992. p->timeStamp = AudioGetCurrentHostTime();
  228993. p->length = jmin (maxPacketSize, bytesLeft);
  228994. memcpy (p->data, message.getRawData() + pos, p->length);
  228995. pos += p->length;
  228996. bytesLeft -= p->length;
  228997. p = MIDIPacketNext (p);
  228998. }
  228999. mpe->send (packets);
  229000. }
  229001. else
  229002. {
  229003. MIDIPacketList packets;
  229004. packets.numPackets = 1;
  229005. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  229006. packets.packet[0].length = message.getRawDataSize();
  229007. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229008. mpe->send (&packets);
  229009. }
  229010. }
  229011. const StringArray MidiInput::getDevices()
  229012. {
  229013. StringArray s;
  229014. const ItemCount num = MIDIGetNumberOfSources();
  229015. for (ItemCount i = 0; i < num; ++i)
  229016. {
  229017. MIDIEndpointRef source = MIDIGetSource (i);
  229018. if (source != 0)
  229019. {
  229020. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229021. if (name.isEmpty())
  229022. name = "<error>";
  229023. s.add (name);
  229024. }
  229025. else
  229026. {
  229027. s.add ("<error>");
  229028. }
  229029. }
  229030. return s;
  229031. }
  229032. int MidiInput::getDefaultDeviceIndex()
  229033. {
  229034. return 0;
  229035. }
  229036. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229037. {
  229038. jassert (callback != 0);
  229039. using namespace CoreMidiHelpers;
  229040. MidiInput* newInput = 0;
  229041. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  229042. {
  229043. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229044. if (endPoint != 0)
  229045. {
  229046. CFStringRef name;
  229047. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229048. {
  229049. MIDIClientRef client = getGlobalMidiClient();
  229050. if (client != 0)
  229051. {
  229052. MIDIPortRef port;
  229053. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229054. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229055. {
  229056. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229057. {
  229058. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229059. newInput = new MidiInput (getDevices() [index]);
  229060. mpc->input = newInput;
  229061. newInput->internal = mpc;
  229062. const ScopedLock sl (callbackLock);
  229063. activeCallbacks.add (mpc.release());
  229064. }
  229065. else
  229066. {
  229067. CHECK_ERROR (MIDIPortDispose (port));
  229068. }
  229069. }
  229070. }
  229071. }
  229072. CFRelease (name);
  229073. }
  229074. }
  229075. return newInput;
  229076. }
  229077. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229078. {
  229079. jassert (callback != 0);
  229080. using namespace CoreMidiHelpers;
  229081. MidiInput* mi = 0;
  229082. MIDIClientRef client = getGlobalMidiClient();
  229083. if (client != 0)
  229084. {
  229085. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229086. mpc->active = false;
  229087. MIDIEndpointRef endPoint;
  229088. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229089. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229090. {
  229091. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229092. mi = new MidiInput (deviceName);
  229093. mpc->input = mi;
  229094. mi->internal = mpc;
  229095. const ScopedLock sl (callbackLock);
  229096. activeCallbacks.add (mpc.release());
  229097. }
  229098. CFRelease (name);
  229099. }
  229100. return mi;
  229101. }
  229102. MidiInput::MidiInput (const String& name_)
  229103. : name (name_)
  229104. {
  229105. }
  229106. MidiInput::~MidiInput()
  229107. {
  229108. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229109. }
  229110. void MidiInput::start()
  229111. {
  229112. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229113. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229114. }
  229115. void MidiInput::stop()
  229116. {
  229117. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229118. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229119. }
  229120. #undef CHECK_ERROR
  229121. #else // Stubs for iOS...
  229122. MidiOutput::~MidiOutput() {}
  229123. void MidiOutput::reset() {}
  229124. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229125. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229126. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229127. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229128. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229129. const StringArray MidiInput::getDevices() { return StringArray(); }
  229130. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229131. #endif
  229132. #endif
  229133. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229134. #else
  229135. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229136. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229137. // compiled on its own).
  229138. #if JUCE_INCLUDED_FILE
  229139. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229140. #define SUPPORT_10_4_FONTS 1
  229141. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229142. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229143. #define SUPPORT_ONLY_10_4_FONTS 1
  229144. #endif
  229145. END_JUCE_NAMESPACE
  229146. @interface NSFont (PrivateHack)
  229147. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229148. @end
  229149. BEGIN_JUCE_NAMESPACE
  229150. #endif
  229151. class MacTypeface : public Typeface
  229152. {
  229153. public:
  229154. MacTypeface (const Font& font)
  229155. : Typeface (font.getTypefaceName())
  229156. {
  229157. const ScopedAutoReleasePool pool;
  229158. renderingTransform = CGAffineTransformIdentity;
  229159. bool needsItalicTransform = false;
  229160. #if JUCE_IOS
  229161. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229162. if (font.isItalic() || font.isBold())
  229163. {
  229164. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229165. for (NSString* i in familyFonts)
  229166. {
  229167. const String fn (nsStringToJuce (i));
  229168. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229169. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229170. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229171. || afterDash.containsIgnoreCase ("italic")
  229172. || fn.endsWithIgnoreCase ("oblique")
  229173. || fn.endsWithIgnoreCase ("italic");
  229174. if (probablyBold == font.isBold()
  229175. && probablyItalic == font.isItalic())
  229176. {
  229177. fontName = i;
  229178. needsItalicTransform = false;
  229179. break;
  229180. }
  229181. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229182. {
  229183. fontName = i;
  229184. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229185. }
  229186. }
  229187. if (needsItalicTransform)
  229188. renderingTransform.c = 0.15f;
  229189. }
  229190. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229191. const int ascender = abs (CGFontGetAscent (fontRef));
  229192. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229193. ascent = ascender / totalHeight;
  229194. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229195. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229196. #else
  229197. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229198. if (font.isItalic())
  229199. {
  229200. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229201. toHaveTrait: NSItalicFontMask];
  229202. if (newFont == nsFont)
  229203. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229204. nsFont = newFont;
  229205. }
  229206. if (font.isBold())
  229207. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229208. [nsFont retain];
  229209. ascent = std::abs ((float) [nsFont ascender]);
  229210. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229211. ascent /= totalSize;
  229212. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229213. if (needsItalicTransform)
  229214. {
  229215. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229216. renderingTransform.c = 0.15f;
  229217. }
  229218. #if SUPPORT_ONLY_10_4_FONTS
  229219. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229220. if (atsFont == 0)
  229221. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229222. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229223. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229224. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229225. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229226. #else
  229227. #if SUPPORT_10_4_FONTS
  229228. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229229. {
  229230. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229231. if (atsFont == 0)
  229232. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229233. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229234. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229235. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229236. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229237. }
  229238. else
  229239. #endif
  229240. {
  229241. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229242. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229243. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229244. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229245. }
  229246. #endif
  229247. #endif
  229248. }
  229249. ~MacTypeface()
  229250. {
  229251. #if ! JUCE_IOS
  229252. [nsFont release];
  229253. #endif
  229254. if (fontRef != 0)
  229255. CGFontRelease (fontRef);
  229256. }
  229257. float getAscent() const
  229258. {
  229259. return ascent;
  229260. }
  229261. float getDescent() const
  229262. {
  229263. return 1.0f - ascent;
  229264. }
  229265. float getStringWidth (const String& text)
  229266. {
  229267. if (fontRef == 0 || text.isEmpty())
  229268. return 0;
  229269. const int length = text.length();
  229270. HeapBlock <CGGlyph> glyphs;
  229271. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229272. float x = 0;
  229273. #if SUPPORT_ONLY_10_4_FONTS
  229274. HeapBlock <NSSize> advances (length);
  229275. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229276. for (int i = 0; i < length; ++i)
  229277. x += advances[i].width;
  229278. #else
  229279. #if SUPPORT_10_4_FONTS
  229280. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229281. {
  229282. HeapBlock <NSSize> advances (length);
  229283. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  229284. for (int i = 0; i < length; ++i)
  229285. x += advances[i].width;
  229286. }
  229287. else
  229288. #endif
  229289. {
  229290. HeapBlock <int> advances (length);
  229291. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229292. for (int i = 0; i < length; ++i)
  229293. x += advances[i];
  229294. }
  229295. #endif
  229296. return x * unitsToHeightScaleFactor;
  229297. }
  229298. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  229299. {
  229300. xOffsets.add (0);
  229301. if (fontRef == 0 || text.isEmpty())
  229302. return;
  229303. const int length = text.length();
  229304. HeapBlock <CGGlyph> glyphs;
  229305. createGlyphsForString (text.getCharPointer(), length, glyphs);
  229306. #if SUPPORT_ONLY_10_4_FONTS
  229307. HeapBlock <NSSize> advances (length);
  229308. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  229309. int x = 0;
  229310. for (int i = 0; i < length; ++i)
  229311. {
  229312. x += advances[i].width;
  229313. xOffsets.add (x * unitsToHeightScaleFactor);
  229314. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  229315. }
  229316. #else
  229317. #if SUPPORT_10_4_FONTS
  229318. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229319. {
  229320. HeapBlock <NSSize> advances (length);
  229321. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229322. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  229323. float x = 0;
  229324. for (int i = 0; i < length; ++i)
  229325. {
  229326. x += advances[i].width;
  229327. xOffsets.add (x * unitsToHeightScaleFactor);
  229328. resultGlyphs.add (nsGlyphs[i]);
  229329. }
  229330. }
  229331. else
  229332. #endif
  229333. {
  229334. HeapBlock <int> advances (length);
  229335. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  229336. {
  229337. int x = 0;
  229338. for (int i = 0; i < length; ++i)
  229339. {
  229340. x += advances [i];
  229341. xOffsets.add (x * unitsToHeightScaleFactor);
  229342. resultGlyphs.add (glyphs[i]);
  229343. }
  229344. }
  229345. }
  229346. #endif
  229347. }
  229348. bool getOutlineForGlyph (int glyphNumber, Path& path)
  229349. {
  229350. #if JUCE_IOS
  229351. return false;
  229352. #else
  229353. if (nsFont == 0)
  229354. return false;
  229355. // we might need to apply a transform to the path, so it mustn't have anything else in it
  229356. jassert (path.isEmpty());
  229357. const ScopedAutoReleasePool pool;
  229358. NSBezierPath* bez = [NSBezierPath bezierPath];
  229359. [bez moveToPoint: NSMakePoint (0, 0)];
  229360. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  229361. inFont: nsFont];
  229362. for (int i = 0; i < [bez elementCount]; ++i)
  229363. {
  229364. NSPoint p[3];
  229365. switch ([bez elementAtIndex: i associatedPoints: p])
  229366. {
  229367. case NSMoveToBezierPathElement: path.startNewSubPath ((float) p[0].x, (float) -p[0].y); break;
  229368. case NSLineToBezierPathElement: path.lineTo ((float) p[0].x, (float) -p[0].y); break;
  229369. case NSCurveToBezierPathElement: path.cubicTo ((float) p[0].x, (float) -p[0].y,
  229370. (float) p[1].x, (float) -p[1].y,
  229371. (float) p[2].x, (float) -p[2].y); break;
  229372. case NSClosePathBezierPathElement: path.closeSubPath(); break;
  229373. default: jassertfalse; break;
  229374. }
  229375. }
  229376. path.applyTransform (pathTransform);
  229377. return true;
  229378. #endif
  229379. }
  229380. CGFontRef fontRef;
  229381. float fontHeightToCGSizeFactor;
  229382. CGAffineTransform renderingTransform;
  229383. private:
  229384. float ascent, unitsToHeightScaleFactor;
  229385. #if JUCE_IOS
  229386. #else
  229387. NSFont* nsFont;
  229388. AffineTransform pathTransform;
  229389. #endif
  229390. void createGlyphsForString (String::CharPointerType text, const int length, HeapBlock <CGGlyph>& glyphs)
  229391. {
  229392. #if SUPPORT_10_4_FONTS
  229393. #if ! SUPPORT_ONLY_10_4_FONTS
  229394. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229395. #endif
  229396. {
  229397. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  229398. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  229399. for (int i = 0; i < length; ++i)
  229400. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text.getAndAdvance()];
  229401. return;
  229402. }
  229403. #endif
  229404. #if ! SUPPORT_ONLY_10_4_FONTS
  229405. if (charToGlyphMapper == 0)
  229406. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  229407. glyphs.malloc (length);
  229408. for (int i = 0; i < length; ++i)
  229409. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text.getAndAdvance());
  229410. #endif
  229411. }
  229412. #if ! SUPPORT_ONLY_10_4_FONTS
  229413. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  229414. class CharToGlyphMapper
  229415. {
  229416. public:
  229417. CharToGlyphMapper (CGFontRef fontRef)
  229418. : segCount (0), endCode (0), startCode (0), idDelta (0),
  229419. idRangeOffset (0), glyphIndexes (0)
  229420. {
  229421. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  229422. if (cmapTable != 0)
  229423. {
  229424. const int numSubtables = getValue16 (cmapTable, 2);
  229425. for (int i = 0; i < numSubtables; ++i)
  229426. {
  229427. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  229428. {
  229429. const int offset = getValue32 (cmapTable, i * 8 + 8);
  229430. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  229431. {
  229432. const int length = getValue16 (cmapTable, offset + 2);
  229433. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  229434. segCount = segCountX2 / 2;
  229435. const int endCodeOffset = offset + 14;
  229436. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  229437. const int idDeltaOffset = startCodeOffset + segCountX2;
  229438. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  229439. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  229440. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  229441. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  229442. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  229443. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  229444. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  229445. }
  229446. break;
  229447. }
  229448. }
  229449. CFRelease (cmapTable);
  229450. }
  229451. }
  229452. ~CharToGlyphMapper()
  229453. {
  229454. if (endCode != 0)
  229455. {
  229456. CFRelease (endCode);
  229457. CFRelease (startCode);
  229458. CFRelease (idDelta);
  229459. CFRelease (idRangeOffset);
  229460. CFRelease (glyphIndexes);
  229461. }
  229462. }
  229463. int getGlyphForCharacter (const juce_wchar c) const
  229464. {
  229465. for (int i = 0; i < segCount; ++i)
  229466. {
  229467. if (getValue16 (endCode, i * 2) >= c)
  229468. {
  229469. const int start = getValue16 (startCode, i * 2);
  229470. if (start > c)
  229471. break;
  229472. const int delta = getValue16 (idDelta, i * 2);
  229473. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  229474. if (rangeOffset == 0)
  229475. return delta + c;
  229476. else
  229477. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  229478. }
  229479. }
  229480. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  229481. return jmax (-1, (int) c - 29);
  229482. }
  229483. private:
  229484. int segCount;
  229485. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  229486. static uint16 getValue16 (CFDataRef data, const int index)
  229487. {
  229488. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  229489. }
  229490. static uint32 getValue32 (CFDataRef data, const int index)
  229491. {
  229492. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  229493. }
  229494. };
  229495. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  229496. #endif
  229497. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MacTypeface);
  229498. };
  229499. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  229500. {
  229501. return new MacTypeface (font);
  229502. }
  229503. const StringArray Font::findAllTypefaceNames()
  229504. {
  229505. StringArray names;
  229506. const ScopedAutoReleasePool pool;
  229507. #if JUCE_IOS
  229508. NSArray* fonts = [UIFont familyNames];
  229509. #else
  229510. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  229511. #endif
  229512. for (unsigned int i = 0; i < [fonts count]; ++i)
  229513. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  229514. names.sort (true);
  229515. return names;
  229516. }
  229517. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  229518. {
  229519. #if JUCE_IOS
  229520. defaultSans = "Helvetica";
  229521. defaultSerif = "Times New Roman";
  229522. defaultFixed = "Courier New";
  229523. #else
  229524. defaultSans = "Lucida Grande";
  229525. defaultSerif = "Times New Roman";
  229526. defaultFixed = "Monaco";
  229527. #endif
  229528. defaultFallback = "Arial Unicode MS";
  229529. }
  229530. #endif
  229531. /*** End of inlined file: juce_mac_Fonts.mm ***/
  229532. // (must go before juce_mac_CoreGraphicsContext.mm)
  229533. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  229534. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229535. // compiled on its own).
  229536. #if JUCE_INCLUDED_FILE
  229537. class CoreGraphicsImage : public Image::SharedImage
  229538. {
  229539. public:
  229540. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  229541. : Image::SharedImage (format_, width_, height_)
  229542. {
  229543. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  229544. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  229545. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  229546. imageData = imageDataAllocated;
  229547. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  229548. : CGColorSpaceCreateDeviceRGB();
  229549. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  229550. colourSpace, getCGImageFlags (format_));
  229551. CGColorSpaceRelease (colourSpace);
  229552. }
  229553. ~CoreGraphicsImage()
  229554. {
  229555. CGContextRelease (context);
  229556. }
  229557. Image::ImageType getType() const { return Image::NativeImage; }
  229558. LowLevelGraphicsContext* createLowLevelContext();
  229559. SharedImage* clone()
  229560. {
  229561. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  229562. memcpy (im->imageData, imageData, lineStride * height);
  229563. return im;
  229564. }
  229565. static CGImageRef createImage (const Image& juceImage, const bool forAlpha,
  229566. CGColorSpaceRef colourSpace, const bool mustOutliveSource)
  229567. {
  229568. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  229569. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  229570. {
  229571. return CGBitmapContextCreateImage (nativeImage->context);
  229572. }
  229573. else
  229574. {
  229575. const Image::BitmapData srcData (juceImage, false);
  229576. CGDataProviderRef provider;
  229577. if (mustOutliveSource)
  229578. {
  229579. CFDataRef data = CFDataCreate (0, (const UInt8*) srcData.data, (CFIndex) (srcData.lineStride * srcData.height));
  229580. provider = CGDataProviderCreateWithCFData (data);
  229581. CFRelease (data);
  229582. }
  229583. else
  229584. {
  229585. provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  229586. }
  229587. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  229588. 8, srcData.pixelStride * 8, srcData.lineStride,
  229589. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  229590. 0, true, kCGRenderingIntentDefault);
  229591. CGDataProviderRelease (provider);
  229592. return imageRef;
  229593. }
  229594. }
  229595. #if JUCE_MAC
  229596. static NSImage* createNSImage (const Image& image)
  229597. {
  229598. const ScopedAutoReleasePool pool;
  229599. NSImage* im = [[NSImage alloc] init];
  229600. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  229601. [im lockFocus];
  229602. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  229603. CGImageRef imageRef = createImage (image, false, colourSpace, false);
  229604. CGColorSpaceRelease (colourSpace);
  229605. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  229606. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  229607. CGImageRelease (imageRef);
  229608. [im unlockFocus];
  229609. return im;
  229610. }
  229611. #endif
  229612. CGContextRef context;
  229613. HeapBlock<uint8> imageDataAllocated;
  229614. private:
  229615. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  229616. {
  229617. #if JUCE_BIG_ENDIAN
  229618. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  229619. #else
  229620. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  229621. #endif
  229622. }
  229623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsImage);
  229624. };
  229625. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  229626. {
  229627. #if USE_COREGRAPHICS_RENDERING
  229628. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  229629. #else
  229630. return createSoftwareImage (format, width, height, clearImage);
  229631. #endif
  229632. }
  229633. class CoreGraphicsContext : public LowLevelGraphicsContext
  229634. {
  229635. public:
  229636. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  229637. : context (context_),
  229638. flipHeight (flipHeight_),
  229639. lastClipRectIsValid (false),
  229640. state (new SavedState()),
  229641. numGradientLookupEntries (0)
  229642. {
  229643. CGContextRetain (context);
  229644. CGContextSaveGState(context);
  229645. CGContextSetShouldSmoothFonts (context, true);
  229646. CGContextSetShouldAntialias (context, true);
  229647. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229648. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  229649. greyColourSpace = CGColorSpaceCreateDeviceGray();
  229650. gradientCallbacks.version = 0;
  229651. gradientCallbacks.evaluate = gradientCallback;
  229652. gradientCallbacks.releaseInfo = 0;
  229653. setFont (Font());
  229654. }
  229655. ~CoreGraphicsContext()
  229656. {
  229657. CGContextRestoreGState (context);
  229658. CGContextRelease (context);
  229659. CGColorSpaceRelease (rgbColourSpace);
  229660. CGColorSpaceRelease (greyColourSpace);
  229661. }
  229662. bool isVectorDevice() const { return false; }
  229663. void setOrigin (int x, int y)
  229664. {
  229665. CGContextTranslateCTM (context, x, -y);
  229666. if (lastClipRectIsValid)
  229667. lastClipRect.translate (-x, -y);
  229668. }
  229669. void addTransform (const AffineTransform& transform)
  229670. {
  229671. applyTransform (AffineTransform::scale (1.0f, -1.0f)
  229672. .translated (0, flipHeight)
  229673. .followedBy (transform)
  229674. .translated (0, -flipHeight)
  229675. .scaled (1.0f, -1.0f));
  229676. lastClipRectIsValid = false;
  229677. }
  229678. float getScaleFactor()
  229679. {
  229680. CGAffineTransform t = CGContextGetCTM (context);
  229681. return (float) juce_hypot (t.a + t.c, t.b + t.d);
  229682. }
  229683. bool clipToRectangle (const Rectangle<int>& r)
  229684. {
  229685. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  229686. if (lastClipRectIsValid)
  229687. {
  229688. // This is actually incorrect, because the actual clip region may be complex, and
  229689. // clipping its bounds to a rect may not be right... But, removing this shortcut
  229690. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  229691. // when calculating the resultant clip bounds, and makes the same mistake!
  229692. lastClipRect = lastClipRect.getIntersection (r);
  229693. return ! lastClipRect.isEmpty();
  229694. }
  229695. return ! isClipEmpty();
  229696. }
  229697. bool clipToRectangleList (const RectangleList& clipRegion)
  229698. {
  229699. if (clipRegion.isEmpty())
  229700. {
  229701. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  229702. lastClipRectIsValid = true;
  229703. lastClipRect = Rectangle<int>();
  229704. return false;
  229705. }
  229706. else
  229707. {
  229708. const int numRects = clipRegion.getNumRectangles();
  229709. HeapBlock <CGRect> rects (numRects);
  229710. for (int i = 0; i < numRects; ++i)
  229711. {
  229712. const Rectangle<int>& r = clipRegion.getRectangle(i);
  229713. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  229714. }
  229715. CGContextClipToRects (context, rects, numRects);
  229716. lastClipRectIsValid = false;
  229717. return ! isClipEmpty();
  229718. }
  229719. }
  229720. void excludeClipRectangle (const Rectangle<int>& r)
  229721. {
  229722. RectangleList remaining (getClipBounds());
  229723. remaining.subtract (r);
  229724. clipToRectangleList (remaining);
  229725. lastClipRectIsValid = false;
  229726. }
  229727. void clipToPath (const Path& path, const AffineTransform& transform)
  229728. {
  229729. createPath (path, transform);
  229730. CGContextClip (context);
  229731. lastClipRectIsValid = false;
  229732. }
  229733. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  229734. {
  229735. if (! transform.isSingularity())
  229736. {
  229737. Image singleChannelImage (sourceImage);
  229738. if (sourceImage.getFormat() != Image::SingleChannel)
  229739. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  229740. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace, true);
  229741. flip();
  229742. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  229743. applyTransform (t);
  229744. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  229745. CGContextClipToMask (context, r, image);
  229746. applyTransform (t.inverted());
  229747. flip();
  229748. CGImageRelease (image);
  229749. lastClipRectIsValid = false;
  229750. }
  229751. }
  229752. bool clipRegionIntersects (const Rectangle<int>& r)
  229753. {
  229754. return getClipBounds().intersects (r);
  229755. }
  229756. const Rectangle<int> getClipBounds() const
  229757. {
  229758. if (! lastClipRectIsValid)
  229759. {
  229760. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229761. lastClipRectIsValid = true;
  229762. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  229763. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  229764. roundToInt (bounds.size.width),
  229765. roundToInt (bounds.size.height));
  229766. }
  229767. return lastClipRect;
  229768. }
  229769. bool isClipEmpty() const
  229770. {
  229771. return getClipBounds().isEmpty();
  229772. }
  229773. void saveState()
  229774. {
  229775. CGContextSaveGState (context);
  229776. stateStack.add (new SavedState (*state));
  229777. }
  229778. void restoreState()
  229779. {
  229780. CGContextRestoreGState (context);
  229781. SavedState* const top = stateStack.getLast();
  229782. if (top != 0)
  229783. {
  229784. state = top;
  229785. stateStack.removeLast (1, false);
  229786. lastClipRectIsValid = false;
  229787. }
  229788. else
  229789. {
  229790. jassertfalse; // trying to pop with an empty stack!
  229791. }
  229792. }
  229793. void beginTransparencyLayer (float opacity)
  229794. {
  229795. saveState();
  229796. CGContextSetAlpha (context, opacity);
  229797. CGContextBeginTransparencyLayer (context, 0);
  229798. }
  229799. void endTransparencyLayer()
  229800. {
  229801. CGContextEndTransparencyLayer (context);
  229802. restoreState();
  229803. }
  229804. void setFill (const FillType& fillType)
  229805. {
  229806. state->fillType = fillType;
  229807. if (fillType.isColour())
  229808. {
  229809. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  229810. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  229811. CGContextSetAlpha (context, 1.0f);
  229812. }
  229813. }
  229814. void setOpacity (float newOpacity)
  229815. {
  229816. state->fillType.setOpacity (newOpacity);
  229817. setFill (state->fillType);
  229818. }
  229819. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  229820. {
  229821. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  229822. ? kCGInterpolationLow
  229823. : kCGInterpolationHigh);
  229824. }
  229825. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  229826. {
  229827. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  229828. }
  229829. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  229830. {
  229831. if (replaceExistingContents)
  229832. {
  229833. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229834. CGContextClearRect (context, cgRect);
  229835. #else
  229836. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229837. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  229838. CGContextClearRect (context, cgRect);
  229839. else
  229840. #endif
  229841. CGContextSetBlendMode (context, kCGBlendModeCopy);
  229842. #endif
  229843. fillCGRect (cgRect, false);
  229844. CGContextSetBlendMode (context, kCGBlendModeNormal);
  229845. }
  229846. else
  229847. {
  229848. if (state->fillType.isColour())
  229849. {
  229850. CGContextFillRect (context, cgRect);
  229851. }
  229852. else if (state->fillType.isGradient())
  229853. {
  229854. CGContextSaveGState (context);
  229855. CGContextClipToRect (context, cgRect);
  229856. drawGradient();
  229857. CGContextRestoreGState (context);
  229858. }
  229859. else
  229860. {
  229861. CGContextSaveGState (context);
  229862. CGContextClipToRect (context, cgRect);
  229863. drawImage (state->fillType.image, state->fillType.transform, true);
  229864. CGContextRestoreGState (context);
  229865. }
  229866. }
  229867. }
  229868. void fillPath (const Path& path, const AffineTransform& transform)
  229869. {
  229870. CGContextSaveGState (context);
  229871. if (state->fillType.isColour())
  229872. {
  229873. flip();
  229874. applyTransform (transform);
  229875. createPath (path);
  229876. if (path.isUsingNonZeroWinding())
  229877. CGContextFillPath (context);
  229878. else
  229879. CGContextEOFillPath (context);
  229880. }
  229881. else
  229882. {
  229883. createPath (path, transform);
  229884. if (path.isUsingNonZeroWinding())
  229885. CGContextClip (context);
  229886. else
  229887. CGContextEOClip (context);
  229888. if (state->fillType.isGradient())
  229889. drawGradient();
  229890. else
  229891. drawImage (state->fillType.image, state->fillType.transform, true);
  229892. }
  229893. CGContextRestoreGState (context);
  229894. }
  229895. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  229896. {
  229897. const int iw = sourceImage.getWidth();
  229898. const int ih = sourceImage.getHeight();
  229899. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace, false);
  229900. CGContextSaveGState (context);
  229901. CGContextSetAlpha (context, state->fillType.getOpacity());
  229902. flip();
  229903. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  229904. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  229905. if (fillEntireClipAsTiles)
  229906. {
  229907. #if JUCE_IOS
  229908. CGContextDrawTiledImage (context, imageRect, image);
  229909. #else
  229910. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  229911. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  229912. // if it's doing a transformation - it's quicker to just draw lots of images manually
  229913. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  229914. CGContextDrawTiledImage (context, imageRect, image);
  229915. else
  229916. #endif
  229917. {
  229918. // Fallback to manually doing a tiled fill on 10.4
  229919. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  229920. int x = 0, y = 0;
  229921. while (x > clip.origin.x) x -= iw;
  229922. while (y > clip.origin.y) y -= ih;
  229923. const int right = (int) (clip.origin.x + clip.size.width);
  229924. const int bottom = (int) (clip.origin.y + clip.size.height);
  229925. while (y < bottom)
  229926. {
  229927. for (int x2 = x; x2 < right; x2 += iw)
  229928. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  229929. y += ih;
  229930. }
  229931. }
  229932. #endif
  229933. }
  229934. else
  229935. {
  229936. CGContextDrawImage (context, imageRect, image);
  229937. }
  229938. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  229939. CGContextRestoreGState (context);
  229940. }
  229941. void drawLine (const Line<float>& line)
  229942. {
  229943. if (state->fillType.isColour())
  229944. {
  229945. CGContextSetLineCap (context, kCGLineCapSquare);
  229946. CGContextSetLineWidth (context, 1.0f);
  229947. CGContextSetRGBStrokeColor (context,
  229948. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  229949. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  229950. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  229951. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  229952. CGContextStrokeLineSegments (context, cgLine, 1);
  229953. }
  229954. else
  229955. {
  229956. Path p;
  229957. p.addLineSegment (line, 1.0f);
  229958. fillPath (p, AffineTransform::identity);
  229959. }
  229960. }
  229961. void drawVerticalLine (const int x, float top, float bottom)
  229962. {
  229963. if (state->fillType.isColour())
  229964. {
  229965. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229966. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  229967. #else
  229968. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229969. // the x co-ord slightly to trick it..
  229970. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  229971. #endif
  229972. }
  229973. else
  229974. {
  229975. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  229976. }
  229977. }
  229978. void drawHorizontalLine (const int y, float left, float right)
  229979. {
  229980. if (state->fillType.isColour())
  229981. {
  229982. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  229983. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  229984. #else
  229985. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  229986. // the x co-ord slightly to trick it..
  229987. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  229988. #endif
  229989. }
  229990. else
  229991. {
  229992. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  229993. }
  229994. }
  229995. void setFont (const Font& newFont)
  229996. {
  229997. if (state->font != newFont)
  229998. {
  229999. state->fontRef = 0;
  230000. state->font = newFont;
  230001. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230002. if (mf != 0)
  230003. {
  230004. state->fontRef = mf->fontRef;
  230005. CGContextSetFont (context, state->fontRef);
  230006. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230007. state->fontTransform = mf->renderingTransform;
  230008. state->fontTransform.a *= state->font.getHorizontalScale();
  230009. CGContextSetTextMatrix (context, state->fontTransform);
  230010. }
  230011. }
  230012. }
  230013. const Font getFont()
  230014. {
  230015. return state->font;
  230016. }
  230017. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230018. {
  230019. if (state->fontRef != 0 && state->fillType.isColour())
  230020. {
  230021. if (transform.isOnlyTranslation())
  230022. {
  230023. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230024. CGGlyph g = glyphNumber;
  230025. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230026. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230027. }
  230028. else
  230029. {
  230030. CGContextSaveGState (context);
  230031. flip();
  230032. applyTransform (transform);
  230033. CGAffineTransform t = state->fontTransform;
  230034. t.d = -t.d;
  230035. CGContextSetTextMatrix (context, t);
  230036. CGGlyph g = glyphNumber;
  230037. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230038. CGContextRestoreGState (context);
  230039. }
  230040. }
  230041. else
  230042. {
  230043. Path p;
  230044. Font& f = state->font;
  230045. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230046. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230047. .followedBy (transform));
  230048. }
  230049. }
  230050. private:
  230051. CGContextRef context;
  230052. const CGFloat flipHeight;
  230053. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230054. CGFunctionCallbacks gradientCallbacks;
  230055. mutable Rectangle<int> lastClipRect;
  230056. mutable bool lastClipRectIsValid;
  230057. struct SavedState
  230058. {
  230059. SavedState()
  230060. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230061. {
  230062. }
  230063. SavedState (const SavedState& other)
  230064. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230065. fontTransform (other.fontTransform)
  230066. {
  230067. }
  230068. FillType fillType;
  230069. Font font;
  230070. CGFontRef fontRef;
  230071. CGAffineTransform fontTransform;
  230072. };
  230073. ScopedPointer <SavedState> state;
  230074. OwnedArray <SavedState> stateStack;
  230075. HeapBlock <PixelARGB> gradientLookupTable;
  230076. int numGradientLookupEntries;
  230077. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230078. {
  230079. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230080. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230081. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230082. colour.unpremultiply();
  230083. outData[0] = colour.getRed() / 255.0f;
  230084. outData[1] = colour.getGreen() / 255.0f;
  230085. outData[2] = colour.getBlue() / 255.0f;
  230086. outData[3] = colour.getAlpha() / 255.0f;
  230087. }
  230088. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230089. {
  230090. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable) - 1;
  230091. CGShadingRef result = 0;
  230092. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230093. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230094. if (gradient.isRadial)
  230095. {
  230096. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230097. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230098. function, true, true);
  230099. }
  230100. else
  230101. {
  230102. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230103. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230104. function, true, true);
  230105. }
  230106. CGFunctionRelease (function);
  230107. return result;
  230108. }
  230109. void drawGradient()
  230110. {
  230111. flip();
  230112. applyTransform (state->fillType.transform);
  230113. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230114. // you draw a gradient with high quality interp enabled).
  230115. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230116. CGContextSetAlpha (context, state->fillType.getOpacity());
  230117. CGContextDrawShading (context, shading);
  230118. CGShadingRelease (shading);
  230119. }
  230120. void createPath (const Path& path) const
  230121. {
  230122. CGContextBeginPath (context);
  230123. Path::Iterator i (path);
  230124. while (i.next())
  230125. {
  230126. switch (i.elementType)
  230127. {
  230128. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230129. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230130. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230131. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230132. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230133. default: jassertfalse; break;
  230134. }
  230135. }
  230136. }
  230137. void createPath (const Path& path, const AffineTransform& transform) const
  230138. {
  230139. CGContextBeginPath (context);
  230140. Path::Iterator i (path);
  230141. while (i.next())
  230142. {
  230143. switch (i.elementType)
  230144. {
  230145. case Path::Iterator::startNewSubPath:
  230146. transform.transformPoint (i.x1, i.y1);
  230147. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230148. break;
  230149. case Path::Iterator::lineTo:
  230150. transform.transformPoint (i.x1, i.y1);
  230151. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230152. break;
  230153. case Path::Iterator::quadraticTo:
  230154. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230155. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230156. break;
  230157. case Path::Iterator::cubicTo:
  230158. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230159. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230160. break;
  230161. case Path::Iterator::closePath:
  230162. CGContextClosePath (context); break;
  230163. default:
  230164. jassertfalse;
  230165. break;
  230166. }
  230167. }
  230168. }
  230169. void flip() const
  230170. {
  230171. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230172. }
  230173. void applyTransform (const AffineTransform& transform) const
  230174. {
  230175. CGAffineTransform t;
  230176. t.a = transform.mat00;
  230177. t.b = transform.mat10;
  230178. t.c = transform.mat01;
  230179. t.d = transform.mat11;
  230180. t.tx = transform.mat02;
  230181. t.ty = transform.mat12;
  230182. CGContextConcatCTM (context, t);
  230183. }
  230184. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreGraphicsContext);
  230185. };
  230186. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230187. {
  230188. return new CoreGraphicsContext (context, height);
  230189. }
  230190. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230191. const Image juce_loadWithCoreImage (InputStream& input)
  230192. {
  230193. MemoryBlock data;
  230194. input.readIntoMemoryBlock (data, -1);
  230195. #if JUCE_IOS
  230196. JUCE_AUTORELEASEPOOL
  230197. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230198. length: data.getSize()
  230199. freeWhenDone: NO]];
  230200. if (image != nil)
  230201. {
  230202. CGImageRef loadedImage = image.CGImage;
  230203. #else
  230204. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230205. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230206. CGDataProviderRelease (provider);
  230207. if (imageSource != 0)
  230208. {
  230209. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230210. CFRelease (imageSource);
  230211. #endif
  230212. if (loadedImage != 0)
  230213. {
  230214. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  230215. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  230216. && alphaInfo != kCGImageAlphaNoneSkipLast
  230217. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  230218. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  230219. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230220. hasAlphaChan, Image::NativeImage);
  230221. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230222. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230223. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230224. CGContextFlush (cgImage->context);
  230225. #if ! JUCE_IOS
  230226. CFRelease (loadedImage);
  230227. #endif
  230228. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  230229. // to find out whether the file they just loaded the image from had an alpha channel or not.
  230230. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  230231. return image;
  230232. }
  230233. }
  230234. return Image::null;
  230235. }
  230236. #endif
  230237. #endif
  230238. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230239. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230240. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230241. // compiled on its own).
  230242. #if JUCE_INCLUDED_FILE
  230243. class NSViewComponentPeer;
  230244. END_JUCE_NAMESPACE
  230245. @interface NSEvent (JuceDeviceDelta)
  230246. - (float) deviceDeltaX;
  230247. - (float) deviceDeltaY;
  230248. @end
  230249. #define JuceNSView MakeObjCClassName(JuceNSView)
  230250. @interface JuceNSView : NSView<NSTextInput>
  230251. {
  230252. @public
  230253. NSViewComponentPeer* owner;
  230254. NSNotificationCenter* notificationCenter;
  230255. String* stringBeingComposed;
  230256. bool textWasInserted;
  230257. }
  230258. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230259. - (void) dealloc;
  230260. - (BOOL) isOpaque;
  230261. - (void) drawRect: (NSRect) r;
  230262. - (void) mouseDown: (NSEvent*) ev;
  230263. - (void) asyncMouseDown: (NSEvent*) ev;
  230264. - (void) mouseUp: (NSEvent*) ev;
  230265. - (void) asyncMouseUp: (NSEvent*) ev;
  230266. - (void) mouseDragged: (NSEvent*) ev;
  230267. - (void) mouseMoved: (NSEvent*) ev;
  230268. - (void) mouseEntered: (NSEvent*) ev;
  230269. - (void) mouseExited: (NSEvent*) ev;
  230270. - (void) rightMouseDown: (NSEvent*) ev;
  230271. - (void) rightMouseDragged: (NSEvent*) ev;
  230272. - (void) rightMouseUp: (NSEvent*) ev;
  230273. - (void) otherMouseDown: (NSEvent*) ev;
  230274. - (void) otherMouseDragged: (NSEvent*) ev;
  230275. - (void) otherMouseUp: (NSEvent*) ev;
  230276. - (void) scrollWheel: (NSEvent*) ev;
  230277. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230278. - (void) frameChanged: (NSNotification*) n;
  230279. - (void) viewDidMoveToWindow;
  230280. - (void) keyDown: (NSEvent*) ev;
  230281. - (void) keyUp: (NSEvent*) ev;
  230282. // NSTextInput Methods
  230283. - (void) insertText: (id) aString;
  230284. - (void) doCommandBySelector: (SEL) aSelector;
  230285. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  230286. - (void) unmarkText;
  230287. - (BOOL) hasMarkedText;
  230288. - (long) conversationIdentifier;
  230289. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  230290. - (NSRange) markedRange;
  230291. - (NSRange) selectedRange;
  230292. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  230293. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  230294. - (NSArray*) validAttributesForMarkedText;
  230295. - (void) flagsChanged: (NSEvent*) ev;
  230296. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230297. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  230298. #endif
  230299. - (BOOL) becomeFirstResponder;
  230300. - (BOOL) resignFirstResponder;
  230301. - (BOOL) acceptsFirstResponder;
  230302. - (void) asyncRepaint: (id) rect;
  230303. - (NSArray*) getSupportedDragTypes;
  230304. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  230305. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  230306. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  230307. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  230308. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  230309. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  230310. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  230311. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  230312. @end
  230313. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  230314. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  230315. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  230316. #else
  230317. @interface JuceNSWindow : NSWindow
  230318. #endif
  230319. {
  230320. @private
  230321. NSViewComponentPeer* owner;
  230322. bool isZooming;
  230323. }
  230324. - (void) setOwner: (NSViewComponentPeer*) owner;
  230325. - (BOOL) canBecomeKeyWindow;
  230326. - (void) becomeKeyWindow;
  230327. - (BOOL) windowShouldClose: (id) window;
  230328. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  230329. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  230330. - (void) zoom: (id) sender;
  230331. @end
  230332. BEGIN_JUCE_NAMESPACE
  230333. class NSViewComponentPeer : public ComponentPeer
  230334. {
  230335. public:
  230336. NSViewComponentPeer (Component* const component,
  230337. const int windowStyleFlags,
  230338. NSView* viewToAttachTo);
  230339. ~NSViewComponentPeer();
  230340. void* getNativeHandle() const;
  230341. void setVisible (bool shouldBeVisible);
  230342. void setTitle (const String& title);
  230343. void setPosition (int x, int y);
  230344. void setSize (int w, int h);
  230345. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  230346. const Rectangle<int> getBounds (const bool global) const;
  230347. const Rectangle<int> getBounds() const;
  230348. const Point<int> getScreenPosition() const;
  230349. const Point<int> localToGlobal (const Point<int>& relativePosition);
  230350. const Point<int> globalToLocal (const Point<int>& screenPosition);
  230351. void setAlpha (float newAlpha);
  230352. void setMinimised (bool shouldBeMinimised);
  230353. bool isMinimised() const;
  230354. void setFullScreen (bool shouldBeFullScreen);
  230355. bool isFullScreen() const;
  230356. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  230357. const BorderSize<int> getFrameSize() const;
  230358. bool setAlwaysOnTop (bool alwaysOnTop);
  230359. void toFront (bool makeActiveWindow);
  230360. void toBehind (ComponentPeer* other);
  230361. void setIcon (const Image& newIcon);
  230362. const StringArray getAvailableRenderingEngines();
  230363. int getCurrentRenderingEngine() throw();
  230364. void setCurrentRenderingEngine (int index);
  230365. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  230366. for example having more than one juce plugin loaded into a host, then when a
  230367. method is called, the actual code that runs might actually be in a different module
  230368. than the one you expect... So any calls to library functions or statics that are
  230369. made inside obj-c methods will probably end up getting executed in a different DLL's
  230370. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  230371. To work around this insanity, I'm only allowing obj-c methods to make calls to
  230372. virtual methods of an object that's known to live inside the right module's space.
  230373. */
  230374. virtual void redirectMouseDown (NSEvent* ev);
  230375. virtual void redirectMouseUp (NSEvent* ev);
  230376. virtual void redirectMouseDrag (NSEvent* ev);
  230377. virtual void redirectMouseMove (NSEvent* ev);
  230378. virtual void redirectMouseEnter (NSEvent* ev);
  230379. virtual void redirectMouseExit (NSEvent* ev);
  230380. virtual void redirectMouseWheel (NSEvent* ev);
  230381. void sendMouseEvent (NSEvent* ev);
  230382. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  230383. virtual bool redirectKeyDown (NSEvent* ev);
  230384. virtual bool redirectKeyUp (NSEvent* ev);
  230385. virtual void redirectModKeyChange (NSEvent* ev);
  230386. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230387. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  230388. #endif
  230389. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  230390. virtual bool isOpaque();
  230391. virtual void drawRect (NSRect r);
  230392. virtual bool canBecomeKeyWindow();
  230393. virtual bool windowShouldClose();
  230394. virtual void redirectMovedOrResized();
  230395. virtual void viewMovedToWindow();
  230396. virtual NSRect constrainRect (NSRect r);
  230397. static void showArrowCursorIfNeeded();
  230398. static void updateModifiers (NSEvent* e);
  230399. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  230400. static int getKeyCodeFromEvent (NSEvent* ev)
  230401. {
  230402. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  230403. int keyCode = unmodified[0];
  230404. if (keyCode == 0x19) // (backwards-tab)
  230405. keyCode = '\t';
  230406. else if (keyCode == 0x03) // (enter)
  230407. keyCode = '\r';
  230408. else
  230409. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  230410. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  230411. {
  230412. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  230413. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  230414. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  230415. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  230416. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  230417. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  230418. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  230419. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  230420. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  230421. if (keyCode == numPadConversions [i])
  230422. keyCode = numPadConversions [i + 1];
  230423. }
  230424. return keyCode;
  230425. }
  230426. static int64 getMouseTime (NSEvent* e)
  230427. {
  230428. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  230429. + (int64) ([e timestamp] * 1000.0);
  230430. }
  230431. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  230432. {
  230433. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  230434. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  230435. }
  230436. static int getModifierForButtonNumber (const NSInteger num)
  230437. {
  230438. return num == 0 ? ModifierKeys::leftButtonModifier
  230439. : (num == 1 ? ModifierKeys::rightButtonModifier
  230440. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  230441. }
  230442. virtual void viewFocusGain();
  230443. virtual void viewFocusLoss();
  230444. bool isFocused() const;
  230445. void grabFocus();
  230446. void textInputRequired (const Point<int>& position);
  230447. void repaint (const Rectangle<int>& area);
  230448. void performAnyPendingRepaintsNow();
  230449. NSWindow* window;
  230450. JuceNSView* view;
  230451. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  230452. static ModifierKeys currentModifiers;
  230453. static ComponentPeer* currentlyFocusedPeer;
  230454. static Array<int> keysCurrentlyDown;
  230455. private:
  230456. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer);
  230457. };
  230458. END_JUCE_NAMESPACE
  230459. @implementation JuceNSView
  230460. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  230461. withFrame: (NSRect) frame
  230462. {
  230463. [super initWithFrame: frame];
  230464. owner = owner_;
  230465. stringBeingComposed = 0;
  230466. textWasInserted = false;
  230467. notificationCenter = [NSNotificationCenter defaultCenter];
  230468. [notificationCenter addObserver: self
  230469. selector: @selector (frameChanged:)
  230470. name: NSViewFrameDidChangeNotification
  230471. object: self];
  230472. if (! owner_->isSharedWindow)
  230473. {
  230474. [notificationCenter addObserver: self
  230475. selector: @selector (frameChanged:)
  230476. name: NSWindowDidMoveNotification
  230477. object: owner_->window];
  230478. }
  230479. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  230480. return self;
  230481. }
  230482. - (void) dealloc
  230483. {
  230484. [notificationCenter removeObserver: self];
  230485. delete stringBeingComposed;
  230486. [super dealloc];
  230487. }
  230488. - (void) drawRect: (NSRect) r
  230489. {
  230490. if (owner != 0)
  230491. owner->drawRect (r);
  230492. }
  230493. - (BOOL) isOpaque
  230494. {
  230495. return owner == 0 || owner->isOpaque();
  230496. }
  230497. - (void) mouseDown: (NSEvent*) ev
  230498. {
  230499. if (JUCEApplication::isStandaloneApp())
  230500. [self asyncMouseDown: ev];
  230501. else
  230502. // In some host situations, the host will stop modal loops from working
  230503. // correctly if they're called from a mouse event, so we'll trigger
  230504. // the event asynchronously..
  230505. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  230506. withObject: ev
  230507. waitUntilDone: NO];
  230508. }
  230509. - (void) asyncMouseDown: (NSEvent*) ev
  230510. {
  230511. if (owner != 0)
  230512. owner->redirectMouseDown (ev);
  230513. }
  230514. - (void) mouseUp: (NSEvent*) ev
  230515. {
  230516. if (! JUCEApplication::isStandaloneApp())
  230517. [self asyncMouseUp: ev];
  230518. else
  230519. // In some host situations, the host will stop modal loops from working
  230520. // correctly if they're called from a mouse event, so we'll trigger
  230521. // the event asynchronously..
  230522. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  230523. withObject: ev
  230524. waitUntilDone: NO];
  230525. }
  230526. - (void) asyncMouseUp: (NSEvent*) ev
  230527. {
  230528. if (owner != 0)
  230529. owner->redirectMouseUp (ev);
  230530. }
  230531. - (void) mouseDragged: (NSEvent*) ev
  230532. {
  230533. if (owner != 0)
  230534. owner->redirectMouseDrag (ev);
  230535. }
  230536. - (void) mouseMoved: (NSEvent*) ev
  230537. {
  230538. if (owner != 0)
  230539. owner->redirectMouseMove (ev);
  230540. }
  230541. - (void) mouseEntered: (NSEvent*) ev
  230542. {
  230543. if (owner != 0)
  230544. owner->redirectMouseEnter (ev);
  230545. }
  230546. - (void) mouseExited: (NSEvent*) ev
  230547. {
  230548. if (owner != 0)
  230549. owner->redirectMouseExit (ev);
  230550. }
  230551. - (void) rightMouseDown: (NSEvent*) ev
  230552. {
  230553. [self mouseDown: ev];
  230554. }
  230555. - (void) rightMouseDragged: (NSEvent*) ev
  230556. {
  230557. [self mouseDragged: ev];
  230558. }
  230559. - (void) rightMouseUp: (NSEvent*) ev
  230560. {
  230561. [self mouseUp: ev];
  230562. }
  230563. - (void) otherMouseDown: (NSEvent*) ev
  230564. {
  230565. [self mouseDown: ev];
  230566. }
  230567. - (void) otherMouseDragged: (NSEvent*) ev
  230568. {
  230569. [self mouseDragged: ev];
  230570. }
  230571. - (void) otherMouseUp: (NSEvent*) ev
  230572. {
  230573. [self mouseUp: ev];
  230574. }
  230575. - (void) scrollWheel: (NSEvent*) ev
  230576. {
  230577. if (owner != 0)
  230578. owner->redirectMouseWheel (ev);
  230579. }
  230580. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  230581. {
  230582. (void) ev;
  230583. return YES;
  230584. }
  230585. - (void) frameChanged: (NSNotification*) n
  230586. {
  230587. (void) n;
  230588. if (owner != 0)
  230589. owner->redirectMovedOrResized();
  230590. }
  230591. - (void) viewDidMoveToWindow
  230592. {
  230593. if (owner != 0)
  230594. owner->viewMovedToWindow();
  230595. }
  230596. - (void) asyncRepaint: (id) rect
  230597. {
  230598. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  230599. [self setNeedsDisplayInRect: *r];
  230600. }
  230601. - (void) keyDown: (NSEvent*) ev
  230602. {
  230603. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230604. textWasInserted = false;
  230605. if (target != 0)
  230606. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  230607. else
  230608. deleteAndZero (stringBeingComposed);
  230609. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  230610. [super keyDown: ev];
  230611. }
  230612. - (void) keyUp: (NSEvent*) ev
  230613. {
  230614. if (owner == 0 || ! owner->redirectKeyUp (ev))
  230615. [super keyUp: ev];
  230616. }
  230617. - (void) insertText: (id) aString
  230618. {
  230619. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  230620. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  230621. if ([newText length] > 0)
  230622. {
  230623. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230624. if (target != 0)
  230625. {
  230626. target->insertTextAtCaret (nsStringToJuce (newText));
  230627. textWasInserted = true;
  230628. }
  230629. }
  230630. deleteAndZero (stringBeingComposed);
  230631. }
  230632. - (void) doCommandBySelector: (SEL) aSelector
  230633. {
  230634. (void) aSelector;
  230635. }
  230636. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  230637. {
  230638. (void) selectionRange;
  230639. if (stringBeingComposed == 0)
  230640. stringBeingComposed = new String();
  230641. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  230642. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230643. if (target != 0)
  230644. {
  230645. const Range<int> currentHighlight (target->getHighlightedRegion());
  230646. target->insertTextAtCaret (*stringBeingComposed);
  230647. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  230648. textWasInserted = true;
  230649. }
  230650. }
  230651. - (void) unmarkText
  230652. {
  230653. if (stringBeingComposed != 0)
  230654. {
  230655. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230656. if (target != 0)
  230657. {
  230658. target->insertTextAtCaret (*stringBeingComposed);
  230659. textWasInserted = true;
  230660. }
  230661. }
  230662. deleteAndZero (stringBeingComposed);
  230663. }
  230664. - (BOOL) hasMarkedText
  230665. {
  230666. return stringBeingComposed != 0;
  230667. }
  230668. - (long) conversationIdentifier
  230669. {
  230670. return (long) (pointer_sized_int) self;
  230671. }
  230672. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  230673. {
  230674. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230675. if (target != 0)
  230676. {
  230677. const Range<int> r ((int) theRange.location,
  230678. (int) (theRange.location + theRange.length));
  230679. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  230680. }
  230681. return nil;
  230682. }
  230683. - (NSRange) markedRange
  230684. {
  230685. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  230686. : NSMakeRange (NSNotFound, 0);
  230687. }
  230688. - (NSRange) selectedRange
  230689. {
  230690. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  230691. if (target != 0)
  230692. {
  230693. const Range<int> highlight (target->getHighlightedRegion());
  230694. if (! highlight.isEmpty())
  230695. return NSMakeRange (highlight.getStart(), highlight.getLength());
  230696. }
  230697. return NSMakeRange (NSNotFound, 0);
  230698. }
  230699. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  230700. {
  230701. (void) theRange;
  230702. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  230703. if (comp == 0)
  230704. return NSMakeRect (0, 0, 0, 0);
  230705. const Rectangle<int> bounds (comp->getScreenBounds());
  230706. return NSMakeRect (bounds.getX(),
  230707. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  230708. bounds.getWidth(),
  230709. bounds.getHeight());
  230710. }
  230711. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  230712. {
  230713. (void) thePoint;
  230714. return NSNotFound;
  230715. }
  230716. - (NSArray*) validAttributesForMarkedText
  230717. {
  230718. return [NSArray array];
  230719. }
  230720. - (void) flagsChanged: (NSEvent*) ev
  230721. {
  230722. if (owner != 0)
  230723. owner->redirectModKeyChange (ev);
  230724. }
  230725. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230726. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  230727. {
  230728. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  230729. return true;
  230730. return [super performKeyEquivalent: ev];
  230731. }
  230732. #endif
  230733. - (BOOL) becomeFirstResponder
  230734. {
  230735. if (owner != 0)
  230736. owner->viewFocusGain();
  230737. return true;
  230738. }
  230739. - (BOOL) resignFirstResponder
  230740. {
  230741. if (owner != 0)
  230742. owner->viewFocusLoss();
  230743. return true;
  230744. }
  230745. - (BOOL) acceptsFirstResponder
  230746. {
  230747. return owner != 0 && owner->canBecomeKeyWindow();
  230748. }
  230749. - (NSArray*) getSupportedDragTypes
  230750. {
  230751. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  230752. }
  230753. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  230754. {
  230755. return owner != 0 && owner->sendDragCallback (type, sender);
  230756. }
  230757. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  230758. {
  230759. if ([self sendDragCallback: 0 sender: sender])
  230760. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230761. else
  230762. return NSDragOperationNone;
  230763. }
  230764. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  230765. {
  230766. if ([self sendDragCallback: 0 sender: sender])
  230767. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  230768. else
  230769. return NSDragOperationNone;
  230770. }
  230771. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  230772. {
  230773. [self sendDragCallback: 1 sender: sender];
  230774. }
  230775. - (void) draggingExited: (id <NSDraggingInfo>) sender
  230776. {
  230777. [self sendDragCallback: 1 sender: sender];
  230778. }
  230779. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  230780. {
  230781. (void) sender;
  230782. return YES;
  230783. }
  230784. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  230785. {
  230786. return [self sendDragCallback: 2 sender: sender];
  230787. }
  230788. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  230789. {
  230790. (void) sender;
  230791. }
  230792. @end
  230793. @implementation JuceNSWindow
  230794. - (void) setOwner: (NSViewComponentPeer*) owner_
  230795. {
  230796. owner = owner_;
  230797. isZooming = false;
  230798. }
  230799. - (BOOL) canBecomeKeyWindow
  230800. {
  230801. return owner != 0 && owner->canBecomeKeyWindow();
  230802. }
  230803. - (void) becomeKeyWindow
  230804. {
  230805. [super becomeKeyWindow];
  230806. if (owner != 0)
  230807. owner->grabFocus();
  230808. }
  230809. - (BOOL) windowShouldClose: (id) window
  230810. {
  230811. (void) window;
  230812. return owner == 0 || owner->windowShouldClose();
  230813. }
  230814. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  230815. {
  230816. (void) screen;
  230817. if (owner != 0)
  230818. frameRect = owner->constrainRect (frameRect);
  230819. return frameRect;
  230820. }
  230821. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  230822. {
  230823. (void) window;
  230824. if (isZooming)
  230825. return proposedFrameSize;
  230826. NSRect frameRect = [self frame];
  230827. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  230828. frameRect.size = proposedFrameSize;
  230829. if (owner != 0)
  230830. frameRect = owner->constrainRect (frameRect);
  230831. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230832. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230833. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230834. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230835. return frameRect.size;
  230836. }
  230837. - (void) zoom: (id) sender
  230838. {
  230839. isZooming = true;
  230840. [super zoom: sender];
  230841. isZooming = false;
  230842. }
  230843. - (void) windowWillMove: (NSNotification*) notification
  230844. {
  230845. (void) notification;
  230846. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  230847. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  230848. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  230849. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  230850. }
  230851. @end
  230852. BEGIN_JUCE_NAMESPACE
  230853. ModifierKeys NSViewComponentPeer::currentModifiers;
  230854. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  230855. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  230856. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  230857. {
  230858. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  230859. return true;
  230860. if (keyCode >= 'A' && keyCode <= 'Z'
  230861. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  230862. return true;
  230863. if (keyCode >= 'a' && keyCode <= 'z'
  230864. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  230865. return true;
  230866. return false;
  230867. }
  230868. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  230869. {
  230870. int m = 0;
  230871. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  230872. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  230873. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  230874. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  230875. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  230876. }
  230877. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  230878. {
  230879. updateModifiers (ev);
  230880. int keyCode = getKeyCodeFromEvent (ev);
  230881. if (keyCode != 0)
  230882. {
  230883. if (isKeyDown)
  230884. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  230885. else
  230886. keysCurrentlyDown.removeValue (keyCode);
  230887. }
  230888. }
  230889. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  230890. {
  230891. return NSViewComponentPeer::currentModifiers;
  230892. }
  230893. void ModifierKeys::updateCurrentModifiers() throw()
  230894. {
  230895. currentModifiers = NSViewComponentPeer::currentModifiers;
  230896. }
  230897. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  230898. const int windowStyleFlags,
  230899. NSView* viewToAttachTo)
  230900. : ComponentPeer (component_, windowStyleFlags),
  230901. window (0),
  230902. view (0),
  230903. isSharedWindow (viewToAttachTo != 0),
  230904. fullScreen (false),
  230905. insideDrawRect (false),
  230906. #if USE_COREGRAPHICS_RENDERING
  230907. usingCoreGraphics (true),
  230908. #else
  230909. usingCoreGraphics (false),
  230910. #endif
  230911. recursiveToFrontCall (false)
  230912. {
  230913. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  230914. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  230915. [view setPostsFrameChangedNotifications: YES];
  230916. if (isSharedWindow)
  230917. {
  230918. window = [viewToAttachTo window];
  230919. [viewToAttachTo addSubview: view];
  230920. }
  230921. else
  230922. {
  230923. r.origin.x = (float) component->getX();
  230924. r.origin.y = (float) component->getY();
  230925. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  230926. unsigned int style = 0;
  230927. if ((windowStyleFlags & windowHasTitleBar) == 0)
  230928. style = NSBorderlessWindowMask;
  230929. else
  230930. style = NSTitledWindowMask;
  230931. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  230932. style |= NSMiniaturizableWindowMask;
  230933. if ((windowStyleFlags & windowHasCloseButton) != 0)
  230934. style |= NSClosableWindowMask;
  230935. if ((windowStyleFlags & windowIsResizable) != 0)
  230936. style |= NSResizableWindowMask;
  230937. window = [[JuceNSWindow alloc] initWithContentRect: r
  230938. styleMask: style
  230939. backing: NSBackingStoreBuffered
  230940. defer: YES];
  230941. [((JuceNSWindow*) window) setOwner: this];
  230942. [window orderOut: nil];
  230943. [window setDelegate: (JuceNSWindow*) window];
  230944. [window setOpaque: component->isOpaque()];
  230945. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  230946. if (component->isAlwaysOnTop())
  230947. [window setLevel: NSFloatingWindowLevel];
  230948. [window setContentView: view];
  230949. [window setAutodisplay: YES];
  230950. [window setAcceptsMouseMovedEvents: YES];
  230951. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  230952. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  230953. [window setReleasedWhenClosed: YES];
  230954. [window retain];
  230955. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  230956. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  230957. }
  230958. const float alpha = component->getAlpha();
  230959. if (alpha < 1.0f)
  230960. setAlpha (alpha);
  230961. setTitle (component->getName());
  230962. }
  230963. NSViewComponentPeer::~NSViewComponentPeer()
  230964. {
  230965. view->owner = 0;
  230966. [view removeFromSuperview];
  230967. [view release];
  230968. if (! isSharedWindow)
  230969. {
  230970. [((JuceNSWindow*) window) setOwner: 0];
  230971. [window close];
  230972. [window release];
  230973. }
  230974. }
  230975. void* NSViewComponentPeer::getNativeHandle() const
  230976. {
  230977. return view;
  230978. }
  230979. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  230980. {
  230981. if (isSharedWindow)
  230982. {
  230983. [view setHidden: ! shouldBeVisible];
  230984. }
  230985. else
  230986. {
  230987. if (shouldBeVisible)
  230988. {
  230989. [window orderFront: nil];
  230990. handleBroughtToFront();
  230991. }
  230992. else
  230993. {
  230994. [window orderOut: nil];
  230995. }
  230996. }
  230997. }
  230998. void NSViewComponentPeer::setTitle (const String& title)
  230999. {
  231000. const ScopedAutoReleasePool pool;
  231001. if (! isSharedWindow)
  231002. [window setTitle: juceStringToNS (title)];
  231003. }
  231004. void NSViewComponentPeer::setPosition (int x, int y)
  231005. {
  231006. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231007. }
  231008. void NSViewComponentPeer::setSize (int w, int h)
  231009. {
  231010. setBounds (component->getX(), component->getY(), w, h, false);
  231011. }
  231012. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231013. {
  231014. fullScreen = isNowFullScreen;
  231015. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231016. if (isSharedWindow)
  231017. {
  231018. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231019. if ([view frame].size.width != r.size.width
  231020. || [view frame].size.height != r.size.height)
  231021. [view setNeedsDisplay: true];
  231022. [view setFrame: r];
  231023. }
  231024. else
  231025. {
  231026. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231027. [window setFrame: [window frameRectForContentRect: r]
  231028. display: true];
  231029. }
  231030. }
  231031. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231032. {
  231033. NSRect r = [view frame];
  231034. if (global && [view window] != 0)
  231035. {
  231036. r = [view convertRect: r toView: nil];
  231037. NSRect wr = [[view window] frame];
  231038. r.origin.x += wr.origin.x;
  231039. r.origin.y += wr.origin.y;
  231040. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231041. }
  231042. else
  231043. {
  231044. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231045. }
  231046. return Rectangle<int> (convertToRectInt (r));
  231047. }
  231048. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231049. {
  231050. return getBounds (! isSharedWindow);
  231051. }
  231052. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231053. {
  231054. return getBounds (true).getPosition();
  231055. }
  231056. const Point<int> NSViewComponentPeer::localToGlobal (const Point<int>& relativePosition)
  231057. {
  231058. return relativePosition + getScreenPosition();
  231059. }
  231060. const Point<int> NSViewComponentPeer::globalToLocal (const Point<int>& screenPosition)
  231061. {
  231062. return screenPosition - getScreenPosition();
  231063. }
  231064. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231065. {
  231066. if (constrainer != 0)
  231067. {
  231068. NSRect current = [window frame];
  231069. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231070. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231071. Rectangle<int> pos (convertToRectInt (r));
  231072. Rectangle<int> original (convertToRectInt (current));
  231073. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  231074. if ([window inLiveResize])
  231075. #else
  231076. if ([window respondsToSelector: @selector (inLiveResize)]
  231077. && [window performSelector: @selector (inLiveResize)])
  231078. #endif
  231079. {
  231080. constrainer->checkBounds (pos, original,
  231081. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231082. false, false, true, true);
  231083. }
  231084. else
  231085. {
  231086. constrainer->checkBounds (pos, original,
  231087. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231088. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231089. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231090. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231091. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231092. }
  231093. r.origin.x = pos.getX();
  231094. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231095. r.size.width = pos.getWidth();
  231096. r.size.height = pos.getHeight();
  231097. }
  231098. return r;
  231099. }
  231100. void NSViewComponentPeer::setAlpha (float newAlpha)
  231101. {
  231102. if (! isSharedWindow)
  231103. [window setAlphaValue: (CGFloat) newAlpha];
  231104. else
  231105. [view setAlphaValue: (CGFloat) newAlpha];
  231106. }
  231107. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231108. {
  231109. if (! isSharedWindow)
  231110. {
  231111. if (shouldBeMinimised)
  231112. [window miniaturize: nil];
  231113. else
  231114. [window deminiaturize: nil];
  231115. }
  231116. }
  231117. bool NSViewComponentPeer::isMinimised() const
  231118. {
  231119. return window != 0 && [window isMiniaturized];
  231120. }
  231121. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231122. {
  231123. if (! isSharedWindow)
  231124. {
  231125. Rectangle<int> r (lastNonFullscreenBounds);
  231126. setMinimised (false);
  231127. if (fullScreen != shouldBeFullScreen)
  231128. {
  231129. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231130. {
  231131. fullScreen = true;
  231132. [window performZoom: nil];
  231133. }
  231134. else
  231135. {
  231136. if (shouldBeFullScreen)
  231137. r = Desktop::getInstance().getMainMonitorArea();
  231138. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231139. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231140. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231141. }
  231142. }
  231143. }
  231144. }
  231145. bool NSViewComponentPeer::isFullScreen() const
  231146. {
  231147. return fullScreen;
  231148. }
  231149. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231150. {
  231151. if (! (isPositiveAndBelow (position.getX(), component->getWidth())
  231152. && isPositiveAndBelow (position.getY(), component->getHeight())))
  231153. return false;
  231154. NSPoint p;
  231155. p.x = (float) position.getX();
  231156. p.y = (float) position.getY();
  231157. NSView* v = [view hitTest: p];
  231158. if (trueIfInAChildWindow)
  231159. return v != nil;
  231160. return v == view;
  231161. }
  231162. const BorderSize<int> NSViewComponentPeer::getFrameSize() const
  231163. {
  231164. BorderSize<int> b;
  231165. if (! isSharedWindow)
  231166. {
  231167. NSRect v = [view convertRect: [view frame] toView: nil];
  231168. NSRect w = [window frame];
  231169. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231170. b.setBottom ((int) v.origin.y);
  231171. b.setLeft ((int) v.origin.x);
  231172. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231173. }
  231174. return b;
  231175. }
  231176. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231177. {
  231178. if (! isSharedWindow)
  231179. {
  231180. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231181. : NSNormalWindowLevel];
  231182. }
  231183. return true;
  231184. }
  231185. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231186. {
  231187. if (isSharedWindow)
  231188. {
  231189. [[view superview] addSubview: view
  231190. positioned: NSWindowAbove
  231191. relativeTo: nil];
  231192. }
  231193. if (window != 0 && component->isVisible())
  231194. {
  231195. if (makeActiveWindow)
  231196. [window makeKeyAndOrderFront: nil];
  231197. else
  231198. [window orderFront: nil];
  231199. if (! recursiveToFrontCall)
  231200. {
  231201. recursiveToFrontCall = true;
  231202. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231203. handleBroughtToFront();
  231204. recursiveToFrontCall = false;
  231205. }
  231206. }
  231207. }
  231208. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231209. {
  231210. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231211. jassert (otherPeer != 0); // wrong type of window?
  231212. if (otherPeer != 0)
  231213. {
  231214. if (isSharedWindow)
  231215. {
  231216. [[view superview] addSubview: view
  231217. positioned: NSWindowBelow
  231218. relativeTo: otherPeer->view];
  231219. }
  231220. else
  231221. {
  231222. [window orderWindow: NSWindowBelow
  231223. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231224. : nil ];
  231225. }
  231226. }
  231227. }
  231228. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231229. {
  231230. // to do..
  231231. }
  231232. void NSViewComponentPeer::viewFocusGain()
  231233. {
  231234. if (currentlyFocusedPeer != this)
  231235. {
  231236. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231237. currentlyFocusedPeer->handleFocusLoss();
  231238. currentlyFocusedPeer = this;
  231239. handleFocusGain();
  231240. }
  231241. }
  231242. void NSViewComponentPeer::viewFocusLoss()
  231243. {
  231244. if (currentlyFocusedPeer == this)
  231245. {
  231246. currentlyFocusedPeer = 0;
  231247. handleFocusLoss();
  231248. }
  231249. }
  231250. void juce_HandleProcessFocusChange()
  231251. {
  231252. NSViewComponentPeer::keysCurrentlyDown.clear();
  231253. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231254. {
  231255. if (Process::isForegroundProcess())
  231256. {
  231257. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231258. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  231259. }
  231260. else
  231261. {
  231262. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231263. // turn kiosk mode off if we lose focus..
  231264. Desktop::getInstance().setKioskModeComponent (0);
  231265. }
  231266. }
  231267. }
  231268. bool NSViewComponentPeer::isFocused() const
  231269. {
  231270. return isSharedWindow ? this == currentlyFocusedPeer
  231271. : (window != 0 && [window isKeyWindow]);
  231272. }
  231273. void NSViewComponentPeer::grabFocus()
  231274. {
  231275. if (window != 0)
  231276. {
  231277. [window makeKeyWindow];
  231278. [window makeFirstResponder: view];
  231279. viewFocusGain();
  231280. }
  231281. }
  231282. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231283. {
  231284. }
  231285. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231286. {
  231287. String unicode (nsStringToJuce ([ev characters]));
  231288. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231289. int keyCode = getKeyCodeFromEvent (ev);
  231290. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231291. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231292. if (unicode.isNotEmpty() || keyCode != 0)
  231293. {
  231294. if (isKeyDown)
  231295. {
  231296. bool used = false;
  231297. while (unicode.length() > 0)
  231298. {
  231299. juce_wchar textCharacter = unicode[0];
  231300. unicode = unicode.substring (1);
  231301. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231302. textCharacter = 0;
  231303. used = handleKeyUpOrDown (true) || used;
  231304. used = handleKeyPress (keyCode, textCharacter) || used;
  231305. }
  231306. return used;
  231307. }
  231308. else
  231309. {
  231310. if (handleKeyUpOrDown (false))
  231311. return true;
  231312. }
  231313. }
  231314. return false;
  231315. }
  231316. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  231317. {
  231318. updateKeysDown (ev, true);
  231319. bool used = handleKeyEvent (ev, true);
  231320. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231321. {
  231322. // for command keys, the key-up event is thrown away, so simulate one..
  231323. updateKeysDown (ev, false);
  231324. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  231325. }
  231326. // (If we're running modally, don't allow unused keystrokes to be passed
  231327. // along to other blocked views..)
  231328. if (Component::getCurrentlyModalComponent() != 0)
  231329. used = true;
  231330. return used;
  231331. }
  231332. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  231333. {
  231334. updateKeysDown (ev, false);
  231335. return handleKeyEvent (ev, false)
  231336. || Component::getCurrentlyModalComponent() != 0;
  231337. }
  231338. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  231339. {
  231340. keysCurrentlyDown.clear();
  231341. handleKeyUpOrDown (true);
  231342. updateModifiers (ev);
  231343. handleModifierKeysChange();
  231344. }
  231345. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231346. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  231347. {
  231348. if ([ev type] == NSKeyDown)
  231349. return redirectKeyDown (ev);
  231350. else if ([ev type] == NSKeyUp)
  231351. return redirectKeyUp (ev);
  231352. return false;
  231353. }
  231354. #endif
  231355. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  231356. {
  231357. updateModifiers (ev);
  231358. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  231359. }
  231360. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  231361. {
  231362. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231363. sendMouseEvent (ev);
  231364. }
  231365. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  231366. {
  231367. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231368. sendMouseEvent (ev);
  231369. showArrowCursorIfNeeded();
  231370. }
  231371. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  231372. {
  231373. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  231374. sendMouseEvent (ev);
  231375. }
  231376. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  231377. {
  231378. currentModifiers = currentModifiers.withoutMouseButtons();
  231379. sendMouseEvent (ev);
  231380. showArrowCursorIfNeeded();
  231381. }
  231382. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  231383. {
  231384. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231385. currentModifiers = currentModifiers.withoutMouseButtons();
  231386. sendMouseEvent (ev);
  231387. }
  231388. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  231389. {
  231390. currentModifiers = currentModifiers.withoutMouseButtons();
  231391. sendMouseEvent (ev);
  231392. }
  231393. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  231394. {
  231395. updateModifiers (ev);
  231396. float x = 0, y = 0;
  231397. @try
  231398. {
  231399. x = [ev deviceDeltaX] * 0.5f;
  231400. y = [ev deviceDeltaY] * 0.5f;
  231401. }
  231402. @catch (...)
  231403. {}
  231404. if (x == 0 && y == 0)
  231405. {
  231406. x = [ev deltaX] * 10.0f;
  231407. y = [ev deltaY] * 10.0f;
  231408. }
  231409. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  231410. }
  231411. void NSViewComponentPeer::showArrowCursorIfNeeded()
  231412. {
  231413. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  231414. if (mouse.getComponentUnderMouse() == 0
  231415. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  231416. {
  231417. [[NSCursor arrowCursor] set];
  231418. }
  231419. }
  231420. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  231421. {
  231422. NSString* bestType
  231423. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  231424. if (bestType == nil)
  231425. return false;
  231426. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  231427. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  231428. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  231429. if (list == nil)
  231430. return false;
  231431. StringArray files;
  231432. if ([list isKindOfClass: [NSArray class]])
  231433. {
  231434. NSArray* items = (NSArray*) list;
  231435. for (unsigned int i = 0; i < [items count]; ++i)
  231436. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  231437. }
  231438. if (files.size() == 0)
  231439. return false;
  231440. if (type == 0)
  231441. handleFileDragMove (files, pos);
  231442. else if (type == 1)
  231443. handleFileDragExit (files);
  231444. else if (type == 2)
  231445. handleFileDragDrop (files, pos);
  231446. return true;
  231447. }
  231448. bool NSViewComponentPeer::isOpaque()
  231449. {
  231450. return component == 0 || component->isOpaque();
  231451. }
  231452. void NSViewComponentPeer::drawRect (NSRect r)
  231453. {
  231454. if (r.size.width < 1.0f || r.size.height < 1.0f)
  231455. return;
  231456. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  231457. if (! component->isOpaque())
  231458. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  231459. #if USE_COREGRAPHICS_RENDERING
  231460. if (usingCoreGraphics)
  231461. {
  231462. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  231463. insideDrawRect = true;
  231464. handlePaint (context);
  231465. insideDrawRect = false;
  231466. }
  231467. else
  231468. #endif
  231469. {
  231470. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  231471. (int) (r.size.width + 0.5f),
  231472. (int) (r.size.height + 0.5f),
  231473. ! getComponent()->isOpaque());
  231474. const int xOffset = -roundToInt (r.origin.x);
  231475. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  231476. const NSRect* rects = 0;
  231477. NSInteger numRects = 0;
  231478. [view getRectsBeingDrawn: &rects count: &numRects];
  231479. const Rectangle<int> clipBounds (temp.getBounds());
  231480. RectangleList clip;
  231481. for (int i = 0; i < numRects; ++i)
  231482. {
  231483. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  231484. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  231485. roundToInt (rects[i].size.width),
  231486. roundToInt (rects[i].size.height))));
  231487. }
  231488. if (! clip.isEmpty())
  231489. {
  231490. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  231491. insideDrawRect = true;
  231492. handlePaint (context);
  231493. insideDrawRect = false;
  231494. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  231495. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace, false);
  231496. CGColorSpaceRelease (colourSpace);
  231497. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  231498. CGImageRelease (image);
  231499. }
  231500. }
  231501. }
  231502. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  231503. {
  231504. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  231505. #if USE_COREGRAPHICS_RENDERING
  231506. s.add ("CoreGraphics Renderer");
  231507. #endif
  231508. return s;
  231509. }
  231510. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  231511. {
  231512. return usingCoreGraphics ? 1 : 0;
  231513. }
  231514. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  231515. {
  231516. #if USE_COREGRAPHICS_RENDERING
  231517. if (usingCoreGraphics != (index > 0))
  231518. {
  231519. usingCoreGraphics = index > 0;
  231520. [view setNeedsDisplay: true];
  231521. }
  231522. #endif
  231523. }
  231524. bool NSViewComponentPeer::canBecomeKeyWindow()
  231525. {
  231526. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  231527. }
  231528. bool NSViewComponentPeer::windowShouldClose()
  231529. {
  231530. if (! isValidPeer (this))
  231531. return YES;
  231532. handleUserClosingWindow();
  231533. return NO;
  231534. }
  231535. void NSViewComponentPeer::redirectMovedOrResized()
  231536. {
  231537. handleMovedOrResized();
  231538. }
  231539. void NSViewComponentPeer::viewMovedToWindow()
  231540. {
  231541. if (isSharedWindow)
  231542. window = [view window];
  231543. }
  231544. void Desktop::createMouseInputSources()
  231545. {
  231546. mouseSources.add (new MouseInputSource (0, true));
  231547. }
  231548. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  231549. {
  231550. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  231551. if (enableOrDisable)
  231552. {
  231553. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  231554. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  231555. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231556. }
  231557. else
  231558. {
  231559. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  231560. }
  231561. #else
  231562. if (enableOrDisable)
  231563. {
  231564. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  231565. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  231566. }
  231567. else
  231568. {
  231569. SetSystemUIMode (kUIModeNormal, 0);
  231570. }
  231571. #endif
  231572. }
  231573. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  231574. {
  231575. if (insideDrawRect)
  231576. {
  231577. class AsyncRepaintMessage : public CallbackMessage
  231578. {
  231579. public:
  231580. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  231581. : peer (peer_), rect (rect_)
  231582. {
  231583. }
  231584. void messageCallback()
  231585. {
  231586. if (ComponentPeer::isValidPeer (peer))
  231587. peer->repaint (rect);
  231588. }
  231589. private:
  231590. NSViewComponentPeer* const peer;
  231591. const Rectangle<int> rect;
  231592. };
  231593. (new AsyncRepaintMessage (this, area))->post();
  231594. }
  231595. else
  231596. {
  231597. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  231598. (float) area.getWidth(), (float) area.getHeight())];
  231599. }
  231600. }
  231601. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  231602. {
  231603. [view displayIfNeeded];
  231604. }
  231605. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  231606. {
  231607. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  231608. }
  231609. const Image juce_createIconForFile (const File& file)
  231610. {
  231611. const ScopedAutoReleasePool pool;
  231612. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  231613. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  231614. [NSGraphicsContext saveGraphicsState];
  231615. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  231616. [image drawAtPoint: NSMakePoint (0, 0)
  231617. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  231618. operation: NSCompositeSourceOver fraction: 1.0f];
  231619. [[NSGraphicsContext currentContext] flushGraphics];
  231620. [NSGraphicsContext restoreGraphicsState];
  231621. return Image (result);
  231622. }
  231623. const int KeyPress::spaceKey = ' ';
  231624. const int KeyPress::returnKey = 0x0d;
  231625. const int KeyPress::escapeKey = 0x1b;
  231626. const int KeyPress::backspaceKey = 0x7f;
  231627. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  231628. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  231629. const int KeyPress::upKey = NSUpArrowFunctionKey;
  231630. const int KeyPress::downKey = NSDownArrowFunctionKey;
  231631. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  231632. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  231633. const int KeyPress::endKey = NSEndFunctionKey;
  231634. const int KeyPress::homeKey = NSHomeFunctionKey;
  231635. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  231636. const int KeyPress::insertKey = -1;
  231637. const int KeyPress::tabKey = 9;
  231638. const int KeyPress::F1Key = NSF1FunctionKey;
  231639. const int KeyPress::F2Key = NSF2FunctionKey;
  231640. const int KeyPress::F3Key = NSF3FunctionKey;
  231641. const int KeyPress::F4Key = NSF4FunctionKey;
  231642. const int KeyPress::F5Key = NSF5FunctionKey;
  231643. const int KeyPress::F6Key = NSF6FunctionKey;
  231644. const int KeyPress::F7Key = NSF7FunctionKey;
  231645. const int KeyPress::F8Key = NSF8FunctionKey;
  231646. const int KeyPress::F9Key = NSF9FunctionKey;
  231647. const int KeyPress::F10Key = NSF10FunctionKey;
  231648. const int KeyPress::F11Key = NSF1FunctionKey;
  231649. const int KeyPress::F12Key = NSF12FunctionKey;
  231650. const int KeyPress::F13Key = NSF13FunctionKey;
  231651. const int KeyPress::F14Key = NSF14FunctionKey;
  231652. const int KeyPress::F15Key = NSF15FunctionKey;
  231653. const int KeyPress::F16Key = NSF16FunctionKey;
  231654. const int KeyPress::numberPad0 = 0x30020;
  231655. const int KeyPress::numberPad1 = 0x30021;
  231656. const int KeyPress::numberPad2 = 0x30022;
  231657. const int KeyPress::numberPad3 = 0x30023;
  231658. const int KeyPress::numberPad4 = 0x30024;
  231659. const int KeyPress::numberPad5 = 0x30025;
  231660. const int KeyPress::numberPad6 = 0x30026;
  231661. const int KeyPress::numberPad7 = 0x30027;
  231662. const int KeyPress::numberPad8 = 0x30028;
  231663. const int KeyPress::numberPad9 = 0x30029;
  231664. const int KeyPress::numberPadAdd = 0x3002a;
  231665. const int KeyPress::numberPadSubtract = 0x3002b;
  231666. const int KeyPress::numberPadMultiply = 0x3002c;
  231667. const int KeyPress::numberPadDivide = 0x3002d;
  231668. const int KeyPress::numberPadSeparator = 0x3002e;
  231669. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  231670. const int KeyPress::numberPadEquals = 0x30030;
  231671. const int KeyPress::numberPadDelete = 0x30031;
  231672. const int KeyPress::playKey = 0x30000;
  231673. const int KeyPress::stopKey = 0x30001;
  231674. const int KeyPress::fastForwardKey = 0x30002;
  231675. const int KeyPress::rewindKey = 0x30003;
  231676. #endif
  231677. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231678. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  231679. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231680. // compiled on its own).
  231681. #if JUCE_INCLUDED_FILE
  231682. #if JUCE_MAC
  231683. namespace MouseCursorHelpers
  231684. {
  231685. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  231686. {
  231687. NSImage* im = CoreGraphicsImage::createNSImage (image);
  231688. NSCursor* c = [[NSCursor alloc] initWithImage: im
  231689. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  231690. [im release];
  231691. return c;
  231692. }
  231693. static void* fromWebKitFile (const char* filename, float hx, float hy)
  231694. {
  231695. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  231696. BufferedInputStream buf (fileStream, 4096);
  231697. PNGImageFormat pngFormat;
  231698. Image im (pngFormat.decodeImage (buf));
  231699. if (im.isValid())
  231700. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  231701. jassertfalse;
  231702. return 0;
  231703. }
  231704. }
  231705. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  231706. {
  231707. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  231708. }
  231709. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  231710. {
  231711. const ScopedAutoReleasePool pool;
  231712. NSCursor* c = 0;
  231713. switch (type)
  231714. {
  231715. case NormalCursor: c = [NSCursor arrowCursor]; break;
  231716. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  231717. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  231718. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  231719. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  231720. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  231721. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  231722. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  231723. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  231724. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  231725. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  231726. case UpDownResizeCursor:
  231727. case TopEdgeResizeCursor:
  231728. case BottomEdgeResizeCursor:
  231729. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  231730. case TopLeftCornerResizeCursor:
  231731. case BottomRightCornerResizeCursor:
  231732. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  231733. case TopRightCornerResizeCursor:
  231734. case BottomLeftCornerResizeCursor:
  231735. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  231736. case UpDownLeftRightResizeCursor:
  231737. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  231738. default:
  231739. jassertfalse;
  231740. break;
  231741. }
  231742. [c retain];
  231743. return c;
  231744. }
  231745. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  231746. {
  231747. [((NSCursor*) cursorHandle) release];
  231748. }
  231749. void MouseCursor::showInAllWindows() const
  231750. {
  231751. showInWindow (0);
  231752. }
  231753. void MouseCursor::showInWindow (ComponentPeer*) const
  231754. {
  231755. NSCursor* c = (NSCursor*) getHandle();
  231756. if (c == 0)
  231757. c = [NSCursor arrowCursor];
  231758. [c set];
  231759. }
  231760. #else
  231761. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  231762. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  231763. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  231764. void MouseCursor::showInAllWindows() const {}
  231765. void MouseCursor::showInWindow (ComponentPeer*) const {}
  231766. #endif
  231767. #endif
  231768. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  231769. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  231770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231771. // compiled on its own).
  231772. #if JUCE_INCLUDED_FILE
  231773. class NSViewComponentInternal : public ComponentMovementWatcher
  231774. {
  231775. public:
  231776. NSViewComponentInternal (NSView* const view_, Component& owner_)
  231777. : ComponentMovementWatcher (&owner_),
  231778. owner (owner_),
  231779. currentPeer (0),
  231780. view (view_)
  231781. {
  231782. [view_ retain];
  231783. if (owner.isShowing())
  231784. componentPeerChanged();
  231785. }
  231786. ~NSViewComponentInternal()
  231787. {
  231788. [view removeFromSuperview];
  231789. [view release];
  231790. }
  231791. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  231792. {
  231793. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  231794. // The ComponentMovementWatcher version of this method avoids calling
  231795. // us when the top-level comp is resized, but for an NSView we need to know this
  231796. // because with inverted co-ords, we need to update the position even if the
  231797. // top-left pos hasn't changed
  231798. if (comp.isOnDesktop() && wasResized)
  231799. componentMovedOrResized (wasMoved, wasResized);
  231800. }
  231801. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  231802. {
  231803. Component* const topComp = owner.getTopLevelComponent();
  231804. if (topComp->getPeer() != 0)
  231805. {
  231806. const Point<int> pos (topComp->getLocalPoint (&owner, Point<int>()));
  231807. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner.getWidth(), (float) owner.getHeight());
  231808. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231809. [view setFrame: r];
  231810. }
  231811. }
  231812. void componentPeerChanged()
  231813. {
  231814. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner.getPeer());
  231815. if (currentPeer != peer)
  231816. {
  231817. if ([view superview] != nil)
  231818. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  231819. // override the call and use it as a sign that they're being deleted, which breaks everything..
  231820. currentPeer = peer;
  231821. if (peer != 0)
  231822. {
  231823. [peer->view addSubview: view];
  231824. componentMovedOrResized (false, false);
  231825. }
  231826. }
  231827. [view setHidden: ! owner.isShowing()];
  231828. }
  231829. void componentVisibilityChanged()
  231830. {
  231831. componentPeerChanged();
  231832. }
  231833. const Rectangle<int> getViewBounds() const
  231834. {
  231835. NSRect r = [view frame];
  231836. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  231837. }
  231838. private:
  231839. Component& owner;
  231840. NSViewComponentPeer* currentPeer;
  231841. public:
  231842. NSView* const view;
  231843. private:
  231844. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentInternal);
  231845. };
  231846. NSViewComponent::NSViewComponent()
  231847. {
  231848. }
  231849. NSViewComponent::~NSViewComponent()
  231850. {
  231851. }
  231852. void NSViewComponent::setView (void* view)
  231853. {
  231854. if (view != getView())
  231855. {
  231856. if (view != 0)
  231857. info = new NSViewComponentInternal ((NSView*) view, *this);
  231858. else
  231859. info = 0;
  231860. }
  231861. }
  231862. void* NSViewComponent::getView() const
  231863. {
  231864. return info == 0 ? 0 : info->view;
  231865. }
  231866. void NSViewComponent::resizeToFitView()
  231867. {
  231868. if (info != 0)
  231869. setBounds (info->getViewBounds());
  231870. }
  231871. void NSViewComponent::paint (Graphics&)
  231872. {
  231873. }
  231874. #endif
  231875. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  231876. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  231877. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231878. // compiled on its own).
  231879. #if JUCE_INCLUDED_FILE
  231880. AppleRemoteDevice::AppleRemoteDevice()
  231881. : device (0),
  231882. queue (0),
  231883. remoteId (0)
  231884. {
  231885. }
  231886. AppleRemoteDevice::~AppleRemoteDevice()
  231887. {
  231888. stop();
  231889. }
  231890. namespace
  231891. {
  231892. io_object_t getAppleRemoteDevice()
  231893. {
  231894. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  231895. io_iterator_t iter = 0;
  231896. io_object_t iod = 0;
  231897. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  231898. && iter != 0)
  231899. {
  231900. iod = IOIteratorNext (iter);
  231901. }
  231902. IOObjectRelease (iter);
  231903. return iod;
  231904. }
  231905. bool createAppleRemoteInterface (io_object_t iod, void** device)
  231906. {
  231907. jassert (*device == 0);
  231908. io_name_t classname;
  231909. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  231910. {
  231911. IOCFPlugInInterface** cfPlugInInterface = 0;
  231912. SInt32 score = 0;
  231913. if (IOCreatePlugInInterfaceForService (iod,
  231914. kIOHIDDeviceUserClientTypeID,
  231915. kIOCFPlugInInterfaceID,
  231916. &cfPlugInInterface,
  231917. &score) == kIOReturnSuccess)
  231918. {
  231919. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  231920. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  231921. device);
  231922. (void) hr;
  231923. (*cfPlugInInterface)->Release (cfPlugInInterface);
  231924. }
  231925. }
  231926. return *device != 0;
  231927. }
  231928. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  231929. {
  231930. if (result == kIOReturnSuccess)
  231931. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  231932. }
  231933. }
  231934. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  231935. {
  231936. if (queue != 0)
  231937. return true;
  231938. stop();
  231939. bool result = false;
  231940. io_object_t iod = getAppleRemoteDevice();
  231941. if (iod != 0)
  231942. {
  231943. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  231944. result = true;
  231945. else
  231946. stop();
  231947. IOObjectRelease (iod);
  231948. }
  231949. return result;
  231950. }
  231951. void AppleRemoteDevice::stop()
  231952. {
  231953. if (queue != 0)
  231954. {
  231955. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  231956. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  231957. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  231958. queue = 0;
  231959. }
  231960. if (device != 0)
  231961. {
  231962. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  231963. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  231964. device = 0;
  231965. }
  231966. }
  231967. bool AppleRemoteDevice::isActive() const
  231968. {
  231969. return queue != 0;
  231970. }
  231971. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  231972. {
  231973. Array <int> cookies;
  231974. CFArrayRef elements;
  231975. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  231976. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  231977. return false;
  231978. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  231979. {
  231980. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  231981. // get the cookie
  231982. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  231983. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  231984. continue;
  231985. long number;
  231986. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  231987. continue;
  231988. cookies.add ((int) number);
  231989. }
  231990. CFRelease (elements);
  231991. if ((*(IOHIDDeviceInterface**) device)
  231992. ->open ((IOHIDDeviceInterface**) device,
  231993. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  231994. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  231995. {
  231996. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  231997. if (queue != 0)
  231998. {
  231999. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232000. for (int i = 0; i < cookies.size(); ++i)
  232001. {
  232002. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232003. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232004. }
  232005. CFRunLoopSourceRef eventSource;
  232006. if ((*(IOHIDQueueInterface**) queue)
  232007. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232008. {
  232009. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232010. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232011. {
  232012. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232013. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232014. return true;
  232015. }
  232016. }
  232017. }
  232018. }
  232019. return false;
  232020. }
  232021. void AppleRemoteDevice::handleCallbackInternal()
  232022. {
  232023. int totalValues = 0;
  232024. AbsoluteTime nullTime = { 0, 0 };
  232025. char cookies [12];
  232026. int numCookies = 0;
  232027. while (numCookies < numElementsInArray (cookies))
  232028. {
  232029. IOHIDEventStruct e;
  232030. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232031. break;
  232032. if ((int) e.elementCookie == 19)
  232033. {
  232034. remoteId = e.value;
  232035. buttonPressed (switched, false);
  232036. }
  232037. else
  232038. {
  232039. totalValues += e.value;
  232040. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232041. }
  232042. }
  232043. cookies [numCookies++] = 0;
  232044. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232045. static const char buttonPatterns[] =
  232046. {
  232047. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232048. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232049. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232050. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232051. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232052. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232053. 0x1f, 0x12, 0x04, 0x02, 0,
  232054. 0x1f, 0x12, 0x03, 0x02, 0,
  232055. 0x1f, 0x12, 0x1f, 0x12, 0,
  232056. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232057. 19, 0
  232058. };
  232059. int buttonNum = (int) menuButton;
  232060. int i = 0;
  232061. while (i < numElementsInArray (buttonPatterns))
  232062. {
  232063. if (strcmp (cookies, buttonPatterns + i) == 0)
  232064. {
  232065. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232066. break;
  232067. }
  232068. i += (int) strlen (buttonPatterns + i) + 1;
  232069. ++buttonNum;
  232070. }
  232071. }
  232072. #endif
  232073. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232074. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232075. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232076. // compiled on its own).
  232077. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232078. #if JUCE_MAC
  232079. END_JUCE_NAMESPACE
  232080. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232081. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232082. {
  232083. CriticalSection* contextLock;
  232084. bool needsUpdate;
  232085. }
  232086. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232087. - (bool) makeActive;
  232088. - (void) makeInactive;
  232089. - (void) reshape;
  232090. @end
  232091. @implementation ThreadSafeNSOpenGLView
  232092. - (id) initWithFrame: (NSRect) frameRect
  232093. pixelFormat: (NSOpenGLPixelFormat*) format
  232094. {
  232095. contextLock = new CriticalSection();
  232096. self = [super initWithFrame: frameRect pixelFormat: format];
  232097. if (self != nil)
  232098. [[NSNotificationCenter defaultCenter] addObserver: self
  232099. selector: @selector (_surfaceNeedsUpdate:)
  232100. name: NSViewGlobalFrameDidChangeNotification
  232101. object: self];
  232102. return self;
  232103. }
  232104. - (void) dealloc
  232105. {
  232106. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232107. delete contextLock;
  232108. [super dealloc];
  232109. }
  232110. - (bool) makeActive
  232111. {
  232112. const ScopedLock sl (*contextLock);
  232113. if ([self openGLContext] == 0)
  232114. return false;
  232115. [[self openGLContext] makeCurrentContext];
  232116. if (needsUpdate)
  232117. {
  232118. [super update];
  232119. needsUpdate = false;
  232120. }
  232121. return true;
  232122. }
  232123. - (void) makeInactive
  232124. {
  232125. const ScopedLock sl (*contextLock);
  232126. [NSOpenGLContext clearCurrentContext];
  232127. }
  232128. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232129. {
  232130. (void) notification;
  232131. const ScopedLock sl (*contextLock);
  232132. needsUpdate = true;
  232133. }
  232134. - (void) update
  232135. {
  232136. const ScopedLock sl (*contextLock);
  232137. needsUpdate = true;
  232138. }
  232139. - (void) reshape
  232140. {
  232141. const ScopedLock sl (*contextLock);
  232142. needsUpdate = true;
  232143. }
  232144. @end
  232145. BEGIN_JUCE_NAMESPACE
  232146. class WindowedGLContext : public OpenGLContext
  232147. {
  232148. public:
  232149. WindowedGLContext (Component& component,
  232150. const OpenGLPixelFormat& pixelFormat_,
  232151. NSOpenGLContext* sharedContext)
  232152. : renderContext (0),
  232153. pixelFormat (pixelFormat_)
  232154. {
  232155. NSOpenGLPixelFormatAttribute attribs [64];
  232156. int n = 0;
  232157. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232158. attribs[n++] = NSOpenGLPFAAccelerated;
  232159. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232160. attribs[n++] = NSOpenGLPFAColorSize;
  232161. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232162. pixelFormat.greenBits,
  232163. pixelFormat.blueBits);
  232164. attribs[n++] = NSOpenGLPFAAlphaSize;
  232165. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232166. attribs[n++] = NSOpenGLPFADepthSize;
  232167. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232168. attribs[n++] = NSOpenGLPFAStencilSize;
  232169. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232170. attribs[n++] = NSOpenGLPFAAccumSize;
  232171. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232172. pixelFormat.accumulationBufferGreenBits,
  232173. pixelFormat.accumulationBufferBlueBits,
  232174. pixelFormat.accumulationBufferAlphaBits);
  232175. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232176. attribs[n++] = NSOpenGLPFASampleBuffers;
  232177. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232178. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232179. attribs[n++] = NSOpenGLPFANoRecovery;
  232180. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232181. NSOpenGLPixelFormat* format
  232182. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232183. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232184. pixelFormat: format];
  232185. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232186. shareContext: sharedContext] autorelease];
  232187. const GLint swapInterval = 1;
  232188. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232189. [view setOpenGLContext: renderContext];
  232190. [format release];
  232191. viewHolder = new NSViewComponentInternal (view, component);
  232192. }
  232193. ~WindowedGLContext()
  232194. {
  232195. deleteContext();
  232196. viewHolder = 0;
  232197. }
  232198. void deleteContext()
  232199. {
  232200. makeInactive();
  232201. [renderContext clearDrawable];
  232202. [renderContext setView: nil];
  232203. [view setOpenGLContext: nil];
  232204. renderContext = nil;
  232205. }
  232206. bool makeActive() const throw()
  232207. {
  232208. jassert (renderContext != 0);
  232209. if ([renderContext view] != view)
  232210. [renderContext setView: view];
  232211. [view makeActive];
  232212. return isActive();
  232213. }
  232214. bool makeInactive() const throw()
  232215. {
  232216. [view makeInactive];
  232217. return true;
  232218. }
  232219. bool isActive() const throw()
  232220. {
  232221. return [NSOpenGLContext currentContext] == renderContext;
  232222. }
  232223. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232224. void* getRawContext() const throw() { return renderContext; }
  232225. void updateWindowPosition (int /*x*/, int /*y*/, int /*w*/, int /*h*/, int /*outerWindowHeight*/)
  232226. {
  232227. }
  232228. void swapBuffers()
  232229. {
  232230. [renderContext flushBuffer];
  232231. }
  232232. bool setSwapInterval (const int numFramesPerSwap)
  232233. {
  232234. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232235. forParameter: NSOpenGLCPSwapInterval];
  232236. return true;
  232237. }
  232238. int getSwapInterval() const
  232239. {
  232240. GLint numFrames = 0;
  232241. [renderContext getValues: &numFrames
  232242. forParameter: NSOpenGLCPSwapInterval];
  232243. return numFrames;
  232244. }
  232245. void repaint()
  232246. {
  232247. // we need to invalidate the juce view that holds this gl view, to make it
  232248. // cause a repaint callback
  232249. NSView* v = (NSView*) viewHolder->view;
  232250. NSRect r = [v frame];
  232251. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232252. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232253. // repaint message, thus never causing our paint() callback, and never repainting
  232254. // the comp. So invalidating just a little bit around the edge helps..
  232255. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232256. }
  232257. void* getNativeWindowHandle() const { return viewHolder->view; }
  232258. NSOpenGLContext* renderContext;
  232259. ThreadSafeNSOpenGLView* view;
  232260. private:
  232261. OpenGLPixelFormat pixelFormat;
  232262. ScopedPointer <NSViewComponentInternal> viewHolder;
  232263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowedGLContext);
  232264. };
  232265. OpenGLContext* OpenGLComponent::createContext()
  232266. {
  232267. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (*this, preferredPixelFormat,
  232268. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232269. return (c->renderContext != 0) ? c.release() : 0;
  232270. }
  232271. void* OpenGLComponent::getNativeWindowHandle() const
  232272. {
  232273. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232274. : 0;
  232275. }
  232276. void juce_glViewport (const int w, const int h)
  232277. {
  232278. glViewport (0, 0, w, h);
  232279. }
  232280. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232281. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232282. {
  232283. /* GLint attribs [64];
  232284. int n = 0;
  232285. attribs[n++] = AGL_RGBA;
  232286. attribs[n++] = AGL_DOUBLEBUFFER;
  232287. attribs[n++] = AGL_ACCELERATED;
  232288. attribs[n++] = AGL_NO_RECOVERY;
  232289. attribs[n++] = AGL_NONE;
  232290. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232291. while (p != 0)
  232292. {
  232293. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232294. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232295. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232296. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232297. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232298. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232299. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232300. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232301. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232302. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232303. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232304. results.add (pf);
  232305. p = aglNextPixelFormat (p);
  232306. }*/
  232307. //jassertfalse // can't see how you do this in cocoa!
  232308. }
  232309. #else
  232310. END_JUCE_NAMESPACE
  232311. @interface JuceGLView : UIView
  232312. {
  232313. }
  232314. + (Class) layerClass;
  232315. @end
  232316. @implementation JuceGLView
  232317. + (Class) layerClass
  232318. {
  232319. return [CAEAGLLayer class];
  232320. }
  232321. @end
  232322. BEGIN_JUCE_NAMESPACE
  232323. class GLESContext : public OpenGLContext
  232324. {
  232325. public:
  232326. GLESContext (UIViewComponentPeer* peer,
  232327. Component* const component_,
  232328. const OpenGLPixelFormat& pixelFormat_,
  232329. const GLESContext* const sharedContext,
  232330. NSUInteger apiType)
  232331. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  232332. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  232333. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  232334. {
  232335. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  232336. view.opaque = YES;
  232337. view.hidden = NO;
  232338. view.backgroundColor = [UIColor blackColor];
  232339. view.userInteractionEnabled = NO;
  232340. glLayer = (CAEAGLLayer*) [view layer];
  232341. [peer->view addSubview: view];
  232342. if (sharedContext != 0)
  232343. context = [[EAGLContext alloc] initWithAPI: apiType
  232344. sharegroup: [sharedContext->context sharegroup]];
  232345. else
  232346. context = [[EAGLContext alloc] initWithAPI: apiType];
  232347. createGLBuffers();
  232348. }
  232349. ~GLESContext()
  232350. {
  232351. deleteContext();
  232352. [view removeFromSuperview];
  232353. [view release];
  232354. freeGLBuffers();
  232355. }
  232356. void deleteContext()
  232357. {
  232358. makeInactive();
  232359. [context release];
  232360. context = nil;
  232361. }
  232362. bool makeActive() const throw()
  232363. {
  232364. jassert (context != 0);
  232365. [EAGLContext setCurrentContext: context];
  232366. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232367. return true;
  232368. }
  232369. void swapBuffers()
  232370. {
  232371. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232372. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  232373. }
  232374. bool makeInactive() const throw()
  232375. {
  232376. return [EAGLContext setCurrentContext: nil];
  232377. }
  232378. bool isActive() const throw()
  232379. {
  232380. return [EAGLContext currentContext] == context;
  232381. }
  232382. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232383. void* getRawContext() const throw() { return glLayer; }
  232384. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232385. {
  232386. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  232387. if (lastWidth != w || lastHeight != h)
  232388. {
  232389. lastWidth = w;
  232390. lastHeight = h;
  232391. freeGLBuffers();
  232392. createGLBuffers();
  232393. }
  232394. }
  232395. bool setSwapInterval (const int numFramesPerSwap)
  232396. {
  232397. numFrames = numFramesPerSwap;
  232398. return true;
  232399. }
  232400. int getSwapInterval() const
  232401. {
  232402. return numFrames;
  232403. }
  232404. void repaint()
  232405. {
  232406. }
  232407. void createGLBuffers()
  232408. {
  232409. makeActive();
  232410. glGenFramebuffersOES (1, &frameBufferHandle);
  232411. glGenRenderbuffersOES (1, &colorBufferHandle);
  232412. glGenRenderbuffersOES (1, &depthBufferHandle);
  232413. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232414. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  232415. GLint width, height;
  232416. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  232417. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  232418. if (useDepthBuffer)
  232419. {
  232420. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  232421. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  232422. }
  232423. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  232424. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  232425. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  232426. if (useDepthBuffer)
  232427. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  232428. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  232429. }
  232430. void freeGLBuffers()
  232431. {
  232432. if (frameBufferHandle != 0)
  232433. {
  232434. glDeleteFramebuffersOES (1, &frameBufferHandle);
  232435. frameBufferHandle = 0;
  232436. }
  232437. if (colorBufferHandle != 0)
  232438. {
  232439. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  232440. colorBufferHandle = 0;
  232441. }
  232442. if (depthBufferHandle != 0)
  232443. {
  232444. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  232445. depthBufferHandle = 0;
  232446. }
  232447. }
  232448. private:
  232449. WeakReference<Component> component;
  232450. OpenGLPixelFormat pixelFormat;
  232451. JuceGLView* view;
  232452. CAEAGLLayer* glLayer;
  232453. EAGLContext* context;
  232454. bool useDepthBuffer;
  232455. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  232456. int numFrames;
  232457. int lastWidth, lastHeight;
  232458. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GLESContext);
  232459. };
  232460. OpenGLContext* OpenGLComponent::createContext()
  232461. {
  232462. ScopedAutoReleasePool pool;
  232463. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  232464. if (peer != 0)
  232465. return new GLESContext (peer, this, preferredPixelFormat,
  232466. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  232467. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  232468. return 0;
  232469. }
  232470. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232471. OwnedArray <OpenGLPixelFormat>& /*results*/)
  232472. {
  232473. }
  232474. void juce_glViewport (const int w, const int h)
  232475. {
  232476. glViewport (0, 0, w, h);
  232477. }
  232478. #endif
  232479. #endif
  232480. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  232481. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  232482. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232483. // compiled on its own).
  232484. #if JUCE_INCLUDED_FILE
  232485. class JuceMainMenuHandler;
  232486. END_JUCE_NAMESPACE
  232487. using namespace JUCE_NAMESPACE;
  232488. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  232489. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232490. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  232491. #else
  232492. @interface JuceMenuCallback : NSObject
  232493. #endif
  232494. {
  232495. JuceMainMenuHandler* owner;
  232496. }
  232497. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  232498. - (void) dealloc;
  232499. - (void) menuItemInvoked: (id) menu;
  232500. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232501. @end
  232502. BEGIN_JUCE_NAMESPACE
  232503. class JuceMainMenuHandler : private MenuBarModel::Listener,
  232504. private DeletedAtShutdown
  232505. {
  232506. public:
  232507. JuceMainMenuHandler()
  232508. : currentModel (0),
  232509. lastUpdateTime (0)
  232510. {
  232511. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  232512. }
  232513. ~JuceMainMenuHandler()
  232514. {
  232515. setMenu (0);
  232516. jassert (instance == this);
  232517. instance = 0;
  232518. [callback release];
  232519. }
  232520. void setMenu (MenuBarModel* const newMenuBarModel)
  232521. {
  232522. if (currentModel != newMenuBarModel)
  232523. {
  232524. if (currentModel != 0)
  232525. currentModel->removeListener (this);
  232526. currentModel = newMenuBarModel;
  232527. if (currentModel != 0)
  232528. currentModel->addListener (this);
  232529. menuBarItemsChanged (0);
  232530. }
  232531. }
  232532. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  232533. const String& name, const int menuId, const int tag)
  232534. {
  232535. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  232536. action: nil
  232537. keyEquivalent: @""];
  232538. [item setTag: tag];
  232539. NSMenu* sub = createMenu (child, name, menuId, tag);
  232540. [parent setSubmenu: sub forItem: item];
  232541. [sub setAutoenablesItems: false];
  232542. [sub release];
  232543. }
  232544. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  232545. const String& name, const int menuId, const int tag)
  232546. {
  232547. [parentItem setTag: tag];
  232548. NSMenu* menu = [parentItem submenu];
  232549. [menu setTitle: juceStringToNS (name)];
  232550. while ([menu numberOfItems] > 0)
  232551. [menu removeItemAtIndex: 0];
  232552. PopupMenu::MenuItemIterator iter (menuToCopy);
  232553. while (iter.next())
  232554. addMenuItem (iter, menu, menuId, tag);
  232555. [menu setAutoenablesItems: false];
  232556. [menu update];
  232557. }
  232558. void menuBarItemsChanged (MenuBarModel*)
  232559. {
  232560. lastUpdateTime = Time::getMillisecondCounter();
  232561. StringArray menuNames;
  232562. if (currentModel != 0)
  232563. menuNames = currentModel->getMenuBarNames();
  232564. NSMenu* menuBar = [NSApp mainMenu];
  232565. while ([menuBar numberOfItems] > 1 + menuNames.size())
  232566. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  232567. int menuId = 1;
  232568. for (int i = 0; i < menuNames.size(); ++i)
  232569. {
  232570. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  232571. if (i >= [menuBar numberOfItems] - 1)
  232572. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  232573. else
  232574. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  232575. }
  232576. }
  232577. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  232578. {
  232579. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  232580. if (item != 0)
  232581. flashMenuBar ([item menu]);
  232582. }
  232583. void updateMenus (NSMenu* menu)
  232584. {
  232585. if (PopupMenu::dismissAllActiveMenus())
  232586. {
  232587. // If we were running a juce menu, then we should let that modal loop finish before allowing
  232588. // the OS menus to start their own modal loop - so cancel the menu that was being opened..
  232589. if ([menu respondsToSelector: @selector (cancelTracking)])
  232590. [menu performSelector: @selector (cancelTracking)];
  232591. }
  232592. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  232593. menuBarItemsChanged (0);
  232594. }
  232595. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  232596. {
  232597. if (currentModel != 0)
  232598. {
  232599. if (commandManager != 0)
  232600. {
  232601. ApplicationCommandTarget::InvocationInfo info (commandId);
  232602. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  232603. commandManager->invoke (info, true);
  232604. }
  232605. currentModel->menuItemSelected (commandId, topLevelIndex);
  232606. }
  232607. }
  232608. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  232609. const int topLevelMenuId, const int topLevelIndex)
  232610. {
  232611. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  232612. if (text == 0)
  232613. text = @"";
  232614. if (iter.isSeparator)
  232615. {
  232616. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  232617. }
  232618. else if (iter.isSectionHeader)
  232619. {
  232620. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232621. action: nil
  232622. keyEquivalent: @""];
  232623. [item setEnabled: false];
  232624. }
  232625. else if (iter.subMenu != 0)
  232626. {
  232627. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232628. action: nil
  232629. keyEquivalent: @""];
  232630. [item setTag: iter.itemId];
  232631. [item setEnabled: iter.isEnabled];
  232632. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  232633. [sub setDelegate: nil];
  232634. [menuToAddTo setSubmenu: sub forItem: item];
  232635. [sub release];
  232636. }
  232637. else
  232638. {
  232639. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  232640. action: @selector (menuItemInvoked:)
  232641. keyEquivalent: @""];
  232642. [item setTag: iter.itemId];
  232643. [item setEnabled: iter.isEnabled];
  232644. [item setState: iter.isTicked ? NSOnState : NSOffState];
  232645. [item setTarget: (id) callback];
  232646. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  232647. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  232648. [item setRepresentedObject: info];
  232649. if (iter.commandManager != 0)
  232650. {
  232651. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  232652. ->getKeyPressesAssignedToCommand (iter.itemId));
  232653. if (keyPresses.size() > 0)
  232654. {
  232655. const KeyPress& kp = keyPresses.getReference(0);
  232656. if (kp.getKeyCode() != KeyPress::backspaceKey
  232657. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  232658. // every time you press the key while editing text)
  232659. {
  232660. juce_wchar key = kp.getTextCharacter();
  232661. if (kp.getKeyCode() == KeyPress::backspaceKey)
  232662. key = NSBackspaceCharacter;
  232663. else if (kp.getKeyCode() == KeyPress::deleteKey)
  232664. key = NSDeleteCharacter;
  232665. else if (key == 0)
  232666. key = (juce_wchar) kp.getKeyCode();
  232667. unsigned int mods = 0;
  232668. if (kp.getModifiers().isShiftDown())
  232669. mods |= NSShiftKeyMask;
  232670. if (kp.getModifiers().isCtrlDown())
  232671. mods |= NSControlKeyMask;
  232672. if (kp.getModifiers().isAltDown())
  232673. mods |= NSAlternateKeyMask;
  232674. if (kp.getModifiers().isCommandDown())
  232675. mods |= NSCommandKeyMask;
  232676. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  232677. [item setKeyEquivalentModifierMask: mods];
  232678. }
  232679. }
  232680. }
  232681. }
  232682. }
  232683. static JuceMainMenuHandler* instance;
  232684. MenuBarModel* currentModel;
  232685. uint32 lastUpdateTime;
  232686. JuceMenuCallback* callback;
  232687. private:
  232688. NSMenu* createMenu (const PopupMenu menu,
  232689. const String& menuName,
  232690. const int topLevelMenuId,
  232691. const int topLevelIndex)
  232692. {
  232693. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  232694. [m setAutoenablesItems: false];
  232695. [m setDelegate: callback];
  232696. PopupMenu::MenuItemIterator iter (menu);
  232697. while (iter.next())
  232698. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  232699. [m update];
  232700. return m;
  232701. }
  232702. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  232703. {
  232704. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  232705. {
  232706. NSMenuItem* m = [menu itemAtIndex: i];
  232707. if ([m tag] == info.commandID)
  232708. return m;
  232709. if ([m submenu] != 0)
  232710. {
  232711. NSMenuItem* found = findMenuItem ([m submenu], info);
  232712. if (found != 0)
  232713. return found;
  232714. }
  232715. }
  232716. return 0;
  232717. }
  232718. static void flashMenuBar (NSMenu* menu)
  232719. {
  232720. if ([[menu title] isEqualToString: @"Apple"])
  232721. return;
  232722. [menu retain];
  232723. const unichar f35Key = NSF35FunctionKey;
  232724. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  232725. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  232726. action: nil
  232727. keyEquivalent: f35String];
  232728. [item setTarget: nil];
  232729. [menu insertItem: item atIndex: [menu numberOfItems]];
  232730. [item release];
  232731. if ([menu indexOfItem: item] >= 0)
  232732. {
  232733. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  232734. location: NSZeroPoint
  232735. modifierFlags: NSCommandKeyMask
  232736. timestamp: 0
  232737. windowNumber: 0
  232738. context: [NSGraphicsContext currentContext]
  232739. characters: f35String
  232740. charactersIgnoringModifiers: f35String
  232741. isARepeat: NO
  232742. keyCode: 0];
  232743. [menu performKeyEquivalent: f35Event];
  232744. if ([menu indexOfItem: item] >= 0)
  232745. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  232746. }
  232747. [menu release];
  232748. }
  232749. };
  232750. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  232751. END_JUCE_NAMESPACE
  232752. @implementation JuceMenuCallback
  232753. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  232754. {
  232755. [super init];
  232756. owner = owner_;
  232757. return self;
  232758. }
  232759. - (void) dealloc
  232760. {
  232761. [super dealloc];
  232762. }
  232763. - (void) menuItemInvoked: (id) menu
  232764. {
  232765. NSMenuItem* item = (NSMenuItem*) menu;
  232766. if ([[item representedObject] isKindOfClass: [NSArray class]])
  232767. {
  232768. // 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
  232769. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  232770. // into the focused component and let it trigger the menu item indirectly.
  232771. NSEvent* e = [NSApp currentEvent];
  232772. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  232773. {
  232774. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  232775. {
  232776. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  232777. if (peer != 0)
  232778. {
  232779. if ([e type] == NSKeyDown)
  232780. peer->redirectKeyDown (e);
  232781. else
  232782. peer->redirectKeyUp (e);
  232783. return;
  232784. }
  232785. }
  232786. }
  232787. NSArray* info = (NSArray*) [item representedObject];
  232788. owner->invoke ((int) [item tag],
  232789. (ApplicationCommandManager*) (pointer_sized_int)
  232790. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  232791. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  232792. }
  232793. }
  232794. - (void) menuNeedsUpdate: (NSMenu*) menu;
  232795. {
  232796. if (JuceMainMenuHandler::instance != 0)
  232797. JuceMainMenuHandler::instance->updateMenus (menu);
  232798. }
  232799. @end
  232800. BEGIN_JUCE_NAMESPACE
  232801. namespace MainMenuHelpers
  232802. {
  232803. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  232804. {
  232805. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  232806. {
  232807. PopupMenu::MenuItemIterator iter (*extraItems);
  232808. while (iter.next())
  232809. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  232810. [menu addItem: [NSMenuItem separatorItem]];
  232811. }
  232812. NSMenuItem* item;
  232813. // Services...
  232814. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  232815. action: nil keyEquivalent: @""];
  232816. [menu addItem: item];
  232817. [item release];
  232818. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  232819. [menu setSubmenu: servicesMenu forItem: item];
  232820. [NSApp setServicesMenu: servicesMenu];
  232821. [servicesMenu release];
  232822. [menu addItem: [NSMenuItem separatorItem]];
  232823. // Hide + Show stuff...
  232824. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  232825. action: @selector (hide:) keyEquivalent: @"h"];
  232826. [item setTarget: NSApp];
  232827. [menu addItem: item];
  232828. [item release];
  232829. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  232830. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  232831. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  232832. [item setTarget: NSApp];
  232833. [menu addItem: item];
  232834. [item release];
  232835. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  232836. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  232837. [item setTarget: NSApp];
  232838. [menu addItem: item];
  232839. [item release];
  232840. [menu addItem: [NSMenuItem separatorItem]];
  232841. // Quit item....
  232842. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  232843. action: @selector (terminate:) keyEquivalent: @"q"];
  232844. [item setTarget: NSApp];
  232845. [menu addItem: item];
  232846. [item release];
  232847. return menu;
  232848. }
  232849. // Since our app has no NIB, this initialises a standard app menu...
  232850. void rebuildMainMenu (const PopupMenu* extraItems)
  232851. {
  232852. // this can't be used in a plugin!
  232853. jassert (JUCEApplication::isStandaloneApp());
  232854. if (JUCEApplication::getInstance() != 0)
  232855. {
  232856. const ScopedAutoReleasePool pool;
  232857. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  232858. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  232859. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  232860. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  232861. [mainMenu setSubmenu: appMenu forItem: item];
  232862. [NSApp setMainMenu: mainMenu];
  232863. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  232864. [appMenu release];
  232865. [mainMenu release];
  232866. }
  232867. }
  232868. }
  232869. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  232870. const PopupMenu* extraAppleMenuItems)
  232871. {
  232872. if (getMacMainMenu() != newMenuBarModel)
  232873. {
  232874. const ScopedAutoReleasePool pool;
  232875. if (newMenuBarModel == 0)
  232876. {
  232877. delete JuceMainMenuHandler::instance;
  232878. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  232879. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  232880. extraAppleMenuItems = 0;
  232881. }
  232882. else
  232883. {
  232884. if (JuceMainMenuHandler::instance == 0)
  232885. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  232886. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  232887. }
  232888. }
  232889. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  232890. if (newMenuBarModel != 0)
  232891. newMenuBarModel->menuItemsChanged();
  232892. }
  232893. MenuBarModel* MenuBarModel::getMacMainMenu()
  232894. {
  232895. return JuceMainMenuHandler::instance != 0
  232896. ? JuceMainMenuHandler::instance->currentModel : 0;
  232897. }
  232898. void juce_initialiseMacMainMenu()
  232899. {
  232900. if (JuceMainMenuHandler::instance == 0)
  232901. MainMenuHelpers::rebuildMainMenu (0);
  232902. }
  232903. #endif
  232904. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  232905. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  232906. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232907. // compiled on its own).
  232908. #if JUCE_INCLUDED_FILE
  232909. #if JUCE_MAC
  232910. END_JUCE_NAMESPACE
  232911. using namespace JUCE_NAMESPACE;
  232912. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  232913. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  232914. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  232915. #else
  232916. @interface JuceFileChooserDelegate : NSObject
  232917. #endif
  232918. {
  232919. StringArray* filters;
  232920. }
  232921. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  232922. - (void) dealloc;
  232923. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  232924. @end
  232925. @implementation JuceFileChooserDelegate
  232926. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  232927. {
  232928. [super init];
  232929. filters = filters_;
  232930. return self;
  232931. }
  232932. - (void) dealloc
  232933. {
  232934. delete filters;
  232935. [super dealloc];
  232936. }
  232937. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  232938. {
  232939. (void) sender;
  232940. const File f (nsStringToJuce (filename));
  232941. for (int i = filters->size(); --i >= 0;)
  232942. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  232943. return true;
  232944. return f.isDirectory();
  232945. }
  232946. @end
  232947. BEGIN_JUCE_NAMESPACE
  232948. void FileChooser::showPlatformDialog (Array<File>& results,
  232949. const String& title,
  232950. const File& currentFileOrDirectory,
  232951. const String& filter,
  232952. bool selectsDirectory,
  232953. bool selectsFiles,
  232954. bool isSaveDialogue,
  232955. bool /*warnAboutOverwritingExistingFiles*/,
  232956. bool selectMultipleFiles,
  232957. FilePreviewComponent* /*extraInfoComponent*/)
  232958. {
  232959. const ScopedAutoReleasePool pool;
  232960. StringArray* filters = new StringArray();
  232961. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  232962. filters->trim();
  232963. filters->removeEmptyStrings();
  232964. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  232965. [delegate autorelease];
  232966. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  232967. : [NSOpenPanel openPanel];
  232968. [panel setTitle: juceStringToNS (title)];
  232969. if (! isSaveDialogue)
  232970. {
  232971. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  232972. [openPanel setCanChooseDirectories: selectsDirectory];
  232973. [openPanel setCanChooseFiles: selectsFiles];
  232974. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  232975. }
  232976. [panel setDelegate: delegate];
  232977. if (isSaveDialogue || selectsDirectory)
  232978. [panel setCanCreateDirectories: YES];
  232979. String directory, filename;
  232980. if (currentFileOrDirectory.isDirectory())
  232981. {
  232982. directory = currentFileOrDirectory.getFullPathName();
  232983. }
  232984. else
  232985. {
  232986. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  232987. filename = currentFileOrDirectory.getFileName();
  232988. }
  232989. if ([panel runModalForDirectory: juceStringToNS (directory)
  232990. file: juceStringToNS (filename)]
  232991. == NSOKButton)
  232992. {
  232993. if (isSaveDialogue)
  232994. {
  232995. results.add (File (nsStringToJuce ([panel filename])));
  232996. }
  232997. else
  232998. {
  232999. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233000. NSArray* urls = [openPanel filenames];
  233001. for (unsigned int i = 0; i < [urls count]; ++i)
  233002. {
  233003. NSString* f = [urls objectAtIndex: i];
  233004. results.add (File (nsStringToJuce (f)));
  233005. }
  233006. }
  233007. }
  233008. [panel setDelegate: nil];
  233009. }
  233010. #else
  233011. void FileChooser::showPlatformDialog (Array<File>& results,
  233012. const String& title,
  233013. const File& currentFileOrDirectory,
  233014. const String& filter,
  233015. bool selectsDirectory,
  233016. bool selectsFiles,
  233017. bool isSaveDialogue,
  233018. bool warnAboutOverwritingExistingFiles,
  233019. bool selectMultipleFiles,
  233020. FilePreviewComponent* extraInfoComponent)
  233021. {
  233022. const ScopedAutoReleasePool pool;
  233023. jassertfalse; //xxx to do
  233024. }
  233025. #endif
  233026. #endif
  233027. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233028. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233029. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233030. // compiled on its own).
  233031. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233032. END_JUCE_NAMESPACE
  233033. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233034. @interface NonInterceptingQTMovieView : QTMovieView
  233035. {
  233036. }
  233037. - (id) initWithFrame: (NSRect) frame;
  233038. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233039. - (NSView*) hitTest: (NSPoint) p;
  233040. @end
  233041. @implementation NonInterceptingQTMovieView
  233042. - (id) initWithFrame: (NSRect) frame
  233043. {
  233044. self = [super initWithFrame: frame];
  233045. [self setNextResponder: [self superview]];
  233046. return self;
  233047. }
  233048. - (void) dealloc
  233049. {
  233050. [super dealloc];
  233051. }
  233052. - (NSView*) hitTest: (NSPoint) point
  233053. {
  233054. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233055. }
  233056. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233057. {
  233058. return YES;
  233059. }
  233060. @end
  233061. BEGIN_JUCE_NAMESPACE
  233062. #define theMovie (static_cast <QTMovie*> (movie))
  233063. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233064. : movie (0)
  233065. {
  233066. setOpaque (true);
  233067. setVisible (true);
  233068. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233069. setView (view);
  233070. [view release];
  233071. }
  233072. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233073. {
  233074. closeMovie();
  233075. setView (0);
  233076. }
  233077. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233078. {
  233079. return true;
  233080. }
  233081. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233082. {
  233083. // unfortunately, QTMovie objects can only be created on the main thread..
  233084. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233085. QTMovie* movie = 0;
  233086. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233087. if (fin != 0)
  233088. {
  233089. movieFile = fin->getFile();
  233090. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233091. error: nil];
  233092. }
  233093. else
  233094. {
  233095. MemoryBlock temp;
  233096. movieStream->readIntoMemoryBlock (temp);
  233097. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233098. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233099. {
  233100. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233101. length: temp.getSize()]
  233102. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233103. MIMEType: @""]
  233104. error: nil];
  233105. if (movie != 0)
  233106. break;
  233107. }
  233108. }
  233109. return movie;
  233110. }
  233111. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233112. const bool isControllerVisible_)
  233113. {
  233114. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233115. }
  233116. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233117. const bool controllerVisible_)
  233118. {
  233119. closeMovie();
  233120. if (getPeer() == 0)
  233121. {
  233122. // To open a movie, this component must be visible inside a functioning window, so that
  233123. // the QT control can be assigned to the window.
  233124. jassertfalse;
  233125. return false;
  233126. }
  233127. movie = openMovieFromStream (movieStream, movieFile);
  233128. [theMovie retain];
  233129. QTMovieView* view = (QTMovieView*) getView();
  233130. [view setMovie: theMovie];
  233131. [view setControllerVisible: controllerVisible_];
  233132. setLooping (looping);
  233133. return movie != nil;
  233134. }
  233135. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233136. const bool isControllerVisible_)
  233137. {
  233138. // unfortunately, QTMovie objects can only be created on the main thread..
  233139. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233140. closeMovie();
  233141. if (getPeer() == 0)
  233142. {
  233143. // To open a movie, this component must be visible inside a functioning window, so that
  233144. // the QT control can be assigned to the window.
  233145. jassertfalse;
  233146. return false;
  233147. }
  233148. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233149. NSError* err;
  233150. if ([QTMovie canInitWithURL: url])
  233151. movie = [QTMovie movieWithURL: url error: &err];
  233152. [theMovie retain];
  233153. QTMovieView* view = (QTMovieView*) getView();
  233154. [view setMovie: theMovie];
  233155. [view setControllerVisible: controllerVisible];
  233156. setLooping (looping);
  233157. return movie != nil;
  233158. }
  233159. void QuickTimeMovieComponent::closeMovie()
  233160. {
  233161. stop();
  233162. QTMovieView* view = (QTMovieView*) getView();
  233163. [view setMovie: nil];
  233164. [theMovie release];
  233165. movie = 0;
  233166. movieFile = File::nonexistent;
  233167. }
  233168. bool QuickTimeMovieComponent::isMovieOpen() const
  233169. {
  233170. return movie != nil;
  233171. }
  233172. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233173. {
  233174. return movieFile;
  233175. }
  233176. void QuickTimeMovieComponent::play()
  233177. {
  233178. [theMovie play];
  233179. }
  233180. void QuickTimeMovieComponent::stop()
  233181. {
  233182. [theMovie stop];
  233183. }
  233184. bool QuickTimeMovieComponent::isPlaying() const
  233185. {
  233186. return movie != 0 && [theMovie rate] != 0;
  233187. }
  233188. void QuickTimeMovieComponent::setPosition (const double seconds)
  233189. {
  233190. if (movie != 0)
  233191. {
  233192. QTTime t;
  233193. t.timeValue = (uint64) (100000.0 * seconds);
  233194. t.timeScale = 100000;
  233195. t.flags = 0;
  233196. [theMovie setCurrentTime: t];
  233197. }
  233198. }
  233199. double QuickTimeMovieComponent::getPosition() const
  233200. {
  233201. if (movie == 0)
  233202. return 0.0;
  233203. QTTime t = [theMovie currentTime];
  233204. return t.timeValue / (double) t.timeScale;
  233205. }
  233206. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233207. {
  233208. [theMovie setRate: newSpeed];
  233209. }
  233210. double QuickTimeMovieComponent::getMovieDuration() const
  233211. {
  233212. if (movie == 0)
  233213. return 0.0;
  233214. QTTime t = [theMovie duration];
  233215. return t.timeValue / (double) t.timeScale;
  233216. }
  233217. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233218. {
  233219. looping = shouldLoop;
  233220. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233221. forKey: QTMovieLoopsAttribute];
  233222. }
  233223. bool QuickTimeMovieComponent::isLooping() const
  233224. {
  233225. return looping;
  233226. }
  233227. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233228. {
  233229. [theMovie setVolume: newVolume];
  233230. }
  233231. float QuickTimeMovieComponent::getMovieVolume() const
  233232. {
  233233. return movie != 0 ? [theMovie volume] : 0.0f;
  233234. }
  233235. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233236. {
  233237. width = 0;
  233238. height = 0;
  233239. if (movie != 0)
  233240. {
  233241. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233242. width = (int) s.width;
  233243. height = (int) s.height;
  233244. }
  233245. }
  233246. void QuickTimeMovieComponent::paint (Graphics& g)
  233247. {
  233248. if (movie == 0)
  233249. g.fillAll (Colours::black);
  233250. }
  233251. bool QuickTimeMovieComponent::isControllerVisible() const
  233252. {
  233253. return controllerVisible;
  233254. }
  233255. void QuickTimeMovieComponent::goToStart()
  233256. {
  233257. setPosition (0.0);
  233258. }
  233259. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233260. const RectanglePlacement& placement)
  233261. {
  233262. int normalWidth, normalHeight;
  233263. getMovieNormalSize (normalWidth, normalHeight);
  233264. const Rectangle<int> normalSize (0, 0, normalWidth, normalHeight);
  233265. if (! (spaceToFitWithin.isEmpty() || normalSize.isEmpty()))
  233266. setBounds (placement.appliedTo (normalSize, spaceToFitWithin));
  233267. else
  233268. setBounds (spaceToFitWithin);
  233269. }
  233270. #if ! (JUCE_MAC && JUCE_64BIT)
  233271. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233272. {
  233273. if (movieStream == 0)
  233274. return false;
  233275. File file;
  233276. QTMovie* movie = openMovieFromStream (movieStream, file);
  233277. if (movie != nil)
  233278. result = [movie quickTimeMovie];
  233279. return movie != nil;
  233280. }
  233281. #endif
  233282. #endif
  233283. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233284. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233285. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233286. // compiled on its own).
  233287. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233288. const int kilobytesPerSecond1x = 176;
  233289. END_JUCE_NAMESPACE
  233290. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233291. @interface OpenDiskDevice : NSObject
  233292. {
  233293. @public
  233294. DRDevice* device;
  233295. NSMutableArray* tracks;
  233296. bool underrunProtection;
  233297. }
  233298. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233299. - (void) dealloc;
  233300. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233301. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233302. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233303. @end
  233304. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233305. @interface AudioTrackProducer : NSObject
  233306. {
  233307. JUCE_NAMESPACE::AudioSource* source;
  233308. int readPosition, lengthInFrames;
  233309. }
  233310. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233311. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233312. - (void) dealloc;
  233313. - (void) setupTrackProperties: (DRTrack*) track;
  233314. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233315. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233316. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233317. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233318. toMedia:(NSDictionary*)mediaInfo;
  233319. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233320. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233321. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233322. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233323. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233324. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233325. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233326. ioFlags:(uint32_t*)flags;
  233327. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  233328. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233329. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233330. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  233331. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  233332. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  233333. ioFlags:(uint32_t*)flags;
  233334. @end
  233335. @implementation OpenDiskDevice
  233336. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  233337. {
  233338. [super init];
  233339. device = device_;
  233340. tracks = [[NSMutableArray alloc] init];
  233341. underrunProtection = true;
  233342. return self;
  233343. }
  233344. - (void) dealloc
  233345. {
  233346. [tracks release];
  233347. [super dealloc];
  233348. }
  233349. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  233350. {
  233351. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  233352. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  233353. [p setupTrackProperties: t];
  233354. [tracks addObject: t];
  233355. [t release];
  233356. [p release];
  233357. }
  233358. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233359. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  233360. {
  233361. DRBurn* burn = [DRBurn burnForDevice: device];
  233362. if (! [device acquireExclusiveAccess])
  233363. {
  233364. *error = "Couldn't open or write to the CD device";
  233365. return;
  233366. }
  233367. [device acquireMediaReservation];
  233368. NSMutableDictionary* d = [[burn properties] mutableCopy];
  233369. [d autorelease];
  233370. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  233371. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  233372. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  233373. if (burnSpeed > 0)
  233374. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  233375. if (! underrunProtection)
  233376. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  233377. [burn setProperties: d];
  233378. [burn writeLayout: tracks];
  233379. for (;;)
  233380. {
  233381. JUCE_NAMESPACE::Thread::sleep (300);
  233382. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  233383. if (listener != 0 && listener->audioCDBurnProgress (progress))
  233384. {
  233385. [burn abort];
  233386. *error = "User cancelled the write operation";
  233387. break;
  233388. }
  233389. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  233390. {
  233391. *error = "Write operation failed";
  233392. break;
  233393. }
  233394. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  233395. {
  233396. break;
  233397. }
  233398. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  233399. objectForKey: DRErrorStatusErrorStringKey];
  233400. if ([err length] > 0)
  233401. {
  233402. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  233403. break;
  233404. }
  233405. }
  233406. [device releaseMediaReservation];
  233407. [device releaseExclusiveAccess];
  233408. }
  233409. @end
  233410. @implementation AudioTrackProducer
  233411. - (AudioTrackProducer*) init: (int) lengthInFrames_
  233412. {
  233413. lengthInFrames = lengthInFrames_;
  233414. readPosition = 0;
  233415. return self;
  233416. }
  233417. - (void) setupTrackProperties: (DRTrack*) track
  233418. {
  233419. NSMutableDictionary* p = [[track properties] mutableCopy];
  233420. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  233421. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  233422. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  233423. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  233424. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  233425. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  233426. [track setProperties: p];
  233427. [p release];
  233428. }
  233429. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  233430. {
  233431. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  233432. if (s != nil)
  233433. s->source = source_;
  233434. return s;
  233435. }
  233436. - (void) dealloc
  233437. {
  233438. if (source != 0)
  233439. {
  233440. source->releaseResources();
  233441. delete source;
  233442. }
  233443. [super dealloc];
  233444. }
  233445. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  233446. {
  233447. (void) track;
  233448. }
  233449. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  233450. {
  233451. (void) track;
  233452. return true;
  233453. }
  233454. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  233455. {
  233456. (void) track;
  233457. return lengthInFrames;
  233458. }
  233459. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  233460. toMedia: (NSDictionary*) mediaInfo
  233461. {
  233462. (void) track; (void) burn; (void) mediaInfo;
  233463. if (source != 0)
  233464. source->prepareToPlay (44100 / 75, 44100);
  233465. readPosition = 0;
  233466. return true;
  233467. }
  233468. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  233469. {
  233470. (void) track;
  233471. if (source != 0)
  233472. source->prepareToPlay (44100 / 75, 44100);
  233473. return true;
  233474. }
  233475. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  233476. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233477. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233478. {
  233479. (void) track; (void) address; (void) blockSize; (void) flags;
  233480. if (source != 0)
  233481. {
  233482. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  233483. if (numSamples > 0)
  233484. {
  233485. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  233486. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  233487. info.buffer = &tempBuffer;
  233488. info.startSample = 0;
  233489. info.numSamples = numSamples;
  233490. source->getNextAudioBlock (info);
  233491. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  233492. JUCE_NAMESPACE::AudioData::LittleEndian,
  233493. JUCE_NAMESPACE::AudioData::Interleaved,
  233494. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  233495. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  233496. JUCE_NAMESPACE::AudioData::NativeEndian,
  233497. JUCE_NAMESPACE::AudioData::NonInterleaved,
  233498. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  233499. CDSampleFormat left (buffer, 2);
  233500. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  233501. CDSampleFormat right (buffer + 2, 2);
  233502. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  233503. readPosition += numSamples;
  233504. }
  233505. return numSamples * 4;
  233506. }
  233507. return 0;
  233508. }
  233509. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  233510. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  233511. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  233512. ioFlags: (uint32_t*) flags
  233513. {
  233514. (void) track; (void) address; (void) blockSize; (void) flags;
  233515. zeromem (buffer, bufferLength);
  233516. return bufferLength;
  233517. }
  233518. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  233519. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  233520. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  233521. {
  233522. (void) track; (void) buffer; (void) bufferLength; (void) address; (void) blockSize; (void) flags;
  233523. return true;
  233524. }
  233525. @end
  233526. BEGIN_JUCE_NAMESPACE
  233527. class AudioCDBurner::Pimpl : public Timer
  233528. {
  233529. public:
  233530. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  233531. : device (0), owner (owner_)
  233532. {
  233533. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  233534. if (dev != 0)
  233535. {
  233536. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  233537. lastState = getDiskState();
  233538. startTimer (1000);
  233539. }
  233540. }
  233541. ~Pimpl()
  233542. {
  233543. stopTimer();
  233544. [device release];
  233545. }
  233546. void timerCallback()
  233547. {
  233548. const DiskState state = getDiskState();
  233549. if (state != lastState)
  233550. {
  233551. lastState = state;
  233552. owner.sendChangeMessage();
  233553. }
  233554. }
  233555. DiskState getDiskState() const
  233556. {
  233557. if ([device->device isValid])
  233558. {
  233559. NSDictionary* status = [device->device status];
  233560. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  233561. if ([state isEqualTo: DRDeviceMediaStateNone])
  233562. {
  233563. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  233564. return trayOpen;
  233565. return noDisc;
  233566. }
  233567. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  233568. {
  233569. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  233570. return writableDiskPresent;
  233571. else
  233572. return readOnlyDiskPresent;
  233573. }
  233574. }
  233575. return unknown;
  233576. }
  233577. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  233578. const Array<int> getAvailableWriteSpeeds() const
  233579. {
  233580. Array<int> results;
  233581. if ([device->device isValid])
  233582. {
  233583. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  233584. for (unsigned int i = 0; i < [speeds count]; ++i)
  233585. {
  233586. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  233587. results.add (kbPerSec / kilobytesPerSecond1x);
  233588. }
  233589. }
  233590. return results;
  233591. }
  233592. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  233593. {
  233594. if ([device->device isValid])
  233595. {
  233596. device->underrunProtection = shouldBeEnabled;
  233597. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  233598. }
  233599. return false;
  233600. }
  233601. int getNumAvailableAudioBlocks() const
  233602. {
  233603. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  233604. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  233605. }
  233606. OpenDiskDevice* device;
  233607. private:
  233608. DiskState lastState;
  233609. AudioCDBurner& owner;
  233610. };
  233611. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  233612. {
  233613. pimpl = new Pimpl (*this, deviceIndex);
  233614. }
  233615. AudioCDBurner::~AudioCDBurner()
  233616. {
  233617. }
  233618. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  233619. {
  233620. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  233621. if (b->pimpl->device == 0)
  233622. b = 0;
  233623. return b.release();
  233624. }
  233625. namespace
  233626. {
  233627. NSArray* findDiskBurnerDevices()
  233628. {
  233629. NSMutableArray* results = [NSMutableArray array];
  233630. NSArray* devs = [DRDevice devices];
  233631. for (int i = 0; i < [devs count]; ++i)
  233632. {
  233633. NSDictionary* dic = [[devs objectAtIndex: i] info];
  233634. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  233635. if (name != nil)
  233636. [results addObject: name];
  233637. }
  233638. return results;
  233639. }
  233640. }
  233641. const StringArray AudioCDBurner::findAvailableDevices()
  233642. {
  233643. NSArray* names = findDiskBurnerDevices();
  233644. StringArray s;
  233645. for (unsigned int i = 0; i < [names count]; ++i)
  233646. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  233647. return s;
  233648. }
  233649. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  233650. {
  233651. return pimpl->getDiskState();
  233652. }
  233653. bool AudioCDBurner::isDiskPresent() const
  233654. {
  233655. return getDiskState() == writableDiskPresent;
  233656. }
  233657. bool AudioCDBurner::openTray()
  233658. {
  233659. return pimpl->openTray();
  233660. }
  233661. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  233662. {
  233663. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  233664. DiskState oldState = getDiskState();
  233665. DiskState newState = oldState;
  233666. while (newState == oldState && Time::currentTimeMillis() < timeout)
  233667. {
  233668. newState = getDiskState();
  233669. Thread::sleep (100);
  233670. }
  233671. return newState;
  233672. }
  233673. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  233674. {
  233675. return pimpl->getAvailableWriteSpeeds();
  233676. }
  233677. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  233678. {
  233679. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  233680. }
  233681. int AudioCDBurner::getNumAvailableAudioBlocks() const
  233682. {
  233683. return pimpl->getNumAvailableAudioBlocks();
  233684. }
  233685. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  233686. {
  233687. if ([pimpl->device->device isValid])
  233688. {
  233689. [pimpl->device addSourceTrack: source numSamples: numSamps];
  233690. return true;
  233691. }
  233692. return false;
  233693. }
  233694. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  233695. bool ejectDiscAfterwards,
  233696. bool performFakeBurnForTesting,
  233697. int writeSpeed)
  233698. {
  233699. String error ("Couldn't open or write to the CD device");
  233700. if ([pimpl->device->device isValid])
  233701. {
  233702. error = String::empty;
  233703. [pimpl->device burn: listener
  233704. errorString: &error
  233705. ejectAfterwards: ejectDiscAfterwards
  233706. isFake: performFakeBurnForTesting
  233707. speed: writeSpeed];
  233708. }
  233709. return error;
  233710. }
  233711. #endif
  233712. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233713. void AudioCDReader::ejectDisk()
  233714. {
  233715. const ScopedAutoReleasePool p;
  233716. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  233717. }
  233718. #endif
  233719. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  233720. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  233721. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233722. // compiled on its own).
  233723. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  233724. namespace CDReaderHelpers
  233725. {
  233726. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  233727. {
  233728. forEachXmlChildElementWithTagName (xml, child, "key")
  233729. if (child->getAllSubText().trim() == key)
  233730. return child->getNextElement();
  233731. return 0;
  233732. }
  233733. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  233734. {
  233735. const XmlElement* const block = getElementForKey (xml, key);
  233736. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  233737. }
  233738. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  233739. // Returns NULL on success, otherwise a const char* representing an error.
  233740. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  233741. {
  233742. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  233743. if (xml == 0)
  233744. return "Couldn't parse XML in file";
  233745. const XmlElement* const dict = xml->getChildByName ("dict");
  233746. if (dict == 0)
  233747. return "Couldn't get top level dictionary";
  233748. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  233749. if (sessions == 0)
  233750. return "Couldn't find sessions key";
  233751. const XmlElement* const session = sessions->getFirstChildElement();
  233752. if (session == 0)
  233753. return "Couldn't find first session";
  233754. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  233755. if (leadOut < 0)
  233756. return "Couldn't find Leadout Block";
  233757. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  233758. if (trackArray == 0)
  233759. return "Couldn't find Track Array";
  233760. forEachXmlChildElement (*trackArray, track)
  233761. {
  233762. const int trackValue = getIntValueForKey (*track, "Start Block");
  233763. if (trackValue < 0)
  233764. return "Couldn't find Start Block in the track";
  233765. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  233766. }
  233767. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  233768. return 0;
  233769. }
  233770. static void findDevices (Array<File>& cds)
  233771. {
  233772. File volumes ("/Volumes");
  233773. volumes.findChildFiles (cds, File::findDirectories, false);
  233774. for (int i = cds.size(); --i >= 0;)
  233775. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  233776. cds.remove (i);
  233777. }
  233778. struct TrackSorter
  233779. {
  233780. static int getCDTrackNumber (const File& file)
  233781. {
  233782. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  233783. }
  233784. static int compareElements (const File& first, const File& second)
  233785. {
  233786. const int firstTrack = getCDTrackNumber (first);
  233787. const int secondTrack = getCDTrackNumber (second);
  233788. jassert (firstTrack > 0 && secondTrack > 0);
  233789. return firstTrack - secondTrack;
  233790. }
  233791. };
  233792. }
  233793. const StringArray AudioCDReader::getAvailableCDNames()
  233794. {
  233795. Array<File> cds;
  233796. CDReaderHelpers::findDevices (cds);
  233797. StringArray names;
  233798. for (int i = 0; i < cds.size(); ++i)
  233799. names.add (cds.getReference(i).getFileName());
  233800. return names;
  233801. }
  233802. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  233803. {
  233804. Array<File> cds;
  233805. CDReaderHelpers::findDevices (cds);
  233806. if (cds[index].exists())
  233807. return new AudioCDReader (cds[index]);
  233808. return 0;
  233809. }
  233810. AudioCDReader::AudioCDReader (const File& volume)
  233811. : AudioFormatReader (0, "CD Audio"),
  233812. volumeDir (volume),
  233813. currentReaderTrack (-1),
  233814. reader (0)
  233815. {
  233816. sampleRate = 44100.0;
  233817. bitsPerSample = 16;
  233818. numChannels = 2;
  233819. usesFloatingPointData = false;
  233820. refreshTrackLengths();
  233821. }
  233822. AudioCDReader::~AudioCDReader()
  233823. {
  233824. }
  233825. void AudioCDReader::refreshTrackLengths()
  233826. {
  233827. tracks.clear();
  233828. trackStartSamples.clear();
  233829. lengthInSamples = 0;
  233830. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  233831. CDReaderHelpers::TrackSorter sorter;
  233832. tracks.sort (sorter);
  233833. const File toc (volumeDir.getChildFile (".TOC.plist"));
  233834. if (toc.exists())
  233835. {
  233836. XmlDocument doc (toc);
  233837. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  233838. (void) error; // could be logged..
  233839. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  233840. }
  233841. }
  233842. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  233843. int64 startSampleInFile, int numSamples)
  233844. {
  233845. while (numSamples > 0)
  233846. {
  233847. int track = -1;
  233848. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  233849. {
  233850. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  233851. {
  233852. track = i;
  233853. break;
  233854. }
  233855. }
  233856. if (track < 0)
  233857. return false;
  233858. if (track != currentReaderTrack)
  233859. {
  233860. reader = 0;
  233861. FileInputStream* const in = tracks [track].createInputStream();
  233862. if (in != 0)
  233863. {
  233864. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  233865. AiffAudioFormat format;
  233866. reader = format.createReaderFor (bin, true);
  233867. if (reader == 0)
  233868. currentReaderTrack = -1;
  233869. else
  233870. currentReaderTrack = track;
  233871. }
  233872. }
  233873. if (reader == 0)
  233874. return false;
  233875. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  233876. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  233877. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  233878. numSamples -= numAvailable;
  233879. startSampleInFile += numAvailable;
  233880. }
  233881. return true;
  233882. }
  233883. bool AudioCDReader::isCDStillPresent() const
  233884. {
  233885. return volumeDir.exists();
  233886. }
  233887. bool AudioCDReader::isTrackAudio (int trackNum) const
  233888. {
  233889. return tracks [trackNum].hasFileExtension (".aiff");
  233890. }
  233891. void AudioCDReader::enableIndexScanning (bool)
  233892. {
  233893. // any way to do this on a Mac??
  233894. }
  233895. int AudioCDReader::getLastIndex() const
  233896. {
  233897. return 0;
  233898. }
  233899. const Array <int> AudioCDReader::findIndexesInTrack (const int /*trackNumber*/)
  233900. {
  233901. return Array <int>();
  233902. }
  233903. #endif
  233904. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  233905. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  233906. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233907. // compiled on its own).
  233908. #if JUCE_INCLUDED_FILE
  233909. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  233910. for example having more than one juce plugin loaded into a host, then when a
  233911. method is called, the actual code that runs might actually be in a different module
  233912. than the one you expect... So any calls to library functions or statics that are
  233913. made inside obj-c methods will probably end up getting executed in a different DLL's
  233914. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  233915. To work around this insanity, I'm only allowing obj-c methods to make calls to
  233916. virtual methods of an object that's known to live inside the right module's space.
  233917. */
  233918. class AppDelegateRedirector
  233919. {
  233920. public:
  233921. AppDelegateRedirector()
  233922. {
  233923. }
  233924. virtual ~AppDelegateRedirector()
  233925. {
  233926. }
  233927. virtual NSApplicationTerminateReply shouldTerminate()
  233928. {
  233929. if (JUCEApplication::getInstance() != 0)
  233930. {
  233931. JUCEApplication::getInstance()->systemRequestedQuit();
  233932. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  233933. return NSTerminateCancel;
  233934. }
  233935. return NSTerminateNow;
  233936. }
  233937. virtual void willTerminate()
  233938. {
  233939. JUCEApplication::appWillTerminateByForce();
  233940. }
  233941. virtual BOOL openFile (NSString* filename)
  233942. {
  233943. if (JUCEApplication::getInstance() != 0)
  233944. {
  233945. JUCEApplication::getInstance()->anotherInstanceStarted (quotedIfContainsSpaces (filename));
  233946. return YES;
  233947. }
  233948. return NO;
  233949. }
  233950. virtual void openFiles (NSArray* filenames)
  233951. {
  233952. StringArray files;
  233953. for (unsigned int i = 0; i < [filenames count]; ++i)
  233954. files.add (quotedIfContainsSpaces ((NSString*) [filenames objectAtIndex: i]));
  233955. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  233956. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  233957. }
  233958. virtual void focusChanged()
  233959. {
  233960. juce_HandleProcessFocusChange();
  233961. }
  233962. struct CallbackMessagePayload
  233963. {
  233964. MessageCallbackFunction* function;
  233965. void* parameter;
  233966. void* volatile result;
  233967. bool volatile hasBeenExecuted;
  233968. };
  233969. virtual void performCallback (CallbackMessagePayload* pl)
  233970. {
  233971. pl->result = (*pl->function) (pl->parameter);
  233972. pl->hasBeenExecuted = true;
  233973. }
  233974. virtual void deleteSelf()
  233975. {
  233976. delete this;
  233977. }
  233978. void postMessage (Message* const m)
  233979. {
  233980. messageQueue.post (m);
  233981. }
  233982. private:
  233983. CFRunLoopRef runLoop;
  233984. CFRunLoopSourceRef runLoopSource;
  233985. MessageQueue messageQueue;
  233986. static const String quotedIfContainsSpaces (NSString* file)
  233987. {
  233988. String s (nsStringToJuce (file));
  233989. if (s.containsChar (' '))
  233990. s = s.quoted ('"');
  233991. return s;
  233992. }
  233993. };
  233994. END_JUCE_NAMESPACE
  233995. using namespace JUCE_NAMESPACE;
  233996. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  233997. @interface JuceAppDelegate : NSObject
  233998. {
  233999. @private
  234000. id oldDelegate;
  234001. @public
  234002. AppDelegateRedirector* redirector;
  234003. }
  234004. - (JuceAppDelegate*) init;
  234005. - (void) dealloc;
  234006. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234007. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234008. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234009. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234010. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234011. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234012. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234013. - (void) performCallback: (id) info;
  234014. - (void) dummyMethod;
  234015. @end
  234016. @implementation JuceAppDelegate
  234017. - (JuceAppDelegate*) init
  234018. {
  234019. [super init];
  234020. redirector = new AppDelegateRedirector();
  234021. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234022. if (JUCEApplication::isStandaloneApp())
  234023. {
  234024. oldDelegate = [NSApp delegate];
  234025. [NSApp setDelegate: self];
  234026. }
  234027. else
  234028. {
  234029. oldDelegate = 0;
  234030. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234031. name: NSApplicationDidResignActiveNotification object: NSApp];
  234032. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234033. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234034. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234035. name: NSApplicationWillUnhideNotification object: NSApp];
  234036. }
  234037. return self;
  234038. }
  234039. - (void) dealloc
  234040. {
  234041. if (oldDelegate != 0)
  234042. [NSApp setDelegate: oldDelegate];
  234043. redirector->deleteSelf();
  234044. [super dealloc];
  234045. }
  234046. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234047. {
  234048. (void) app;
  234049. return redirector->shouldTerminate();
  234050. }
  234051. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234052. {
  234053. (void) aNotification;
  234054. redirector->willTerminate();
  234055. }
  234056. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234057. {
  234058. (void) app;
  234059. return redirector->openFile (filename);
  234060. }
  234061. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234062. {
  234063. (void) sender;
  234064. return redirector->openFiles (filenames);
  234065. }
  234066. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234067. {
  234068. (void) notification;
  234069. redirector->focusChanged();
  234070. }
  234071. - (void) applicationDidResignActive: (NSNotification*) notification
  234072. {
  234073. (void) notification;
  234074. redirector->focusChanged();
  234075. }
  234076. - (void) applicationWillUnhide: (NSNotification*) notification
  234077. {
  234078. (void) notification;
  234079. redirector->focusChanged();
  234080. }
  234081. - (void) performCallback: (id) info
  234082. {
  234083. if ([info isKindOfClass: [NSData class]])
  234084. {
  234085. AppDelegateRedirector::CallbackMessagePayload* pl
  234086. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234087. if (pl != 0)
  234088. redirector->performCallback (pl);
  234089. }
  234090. else
  234091. {
  234092. jassertfalse; // should never get here!
  234093. }
  234094. }
  234095. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234096. @end
  234097. BEGIN_JUCE_NAMESPACE
  234098. static JuceAppDelegate* juceAppDelegate = 0;
  234099. void MessageManager::runDispatchLoop()
  234100. {
  234101. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234102. {
  234103. const ScopedAutoReleasePool pool;
  234104. // must only be called by the message thread!
  234105. jassert (isThisTheMessageThread());
  234106. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234107. @try
  234108. {
  234109. [NSApp run];
  234110. }
  234111. @catch (NSException* e)
  234112. {
  234113. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234114. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234115. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234116. }
  234117. @finally
  234118. {
  234119. }
  234120. #else
  234121. [NSApp run];
  234122. #endif
  234123. }
  234124. }
  234125. void MessageManager::stopDispatchLoop()
  234126. {
  234127. quitMessagePosted = true;
  234128. [NSApp stop: nil];
  234129. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234130. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234131. }
  234132. namespace
  234133. {
  234134. bool isEventBlockedByModalComps (NSEvent* e)
  234135. {
  234136. if (Component::getNumCurrentlyModalComponents() == 0)
  234137. return false;
  234138. NSWindow* const w = [e window];
  234139. if (w == 0 || [w worksWhenModal])
  234140. return false;
  234141. bool isKey = false, isInputAttempt = false;
  234142. switch ([e type])
  234143. {
  234144. case NSKeyDown:
  234145. case NSKeyUp:
  234146. isKey = isInputAttempt = true;
  234147. break;
  234148. case NSLeftMouseDown:
  234149. case NSRightMouseDown:
  234150. case NSOtherMouseDown:
  234151. isInputAttempt = true;
  234152. break;
  234153. case NSLeftMouseDragged:
  234154. case NSRightMouseDragged:
  234155. case NSLeftMouseUp:
  234156. case NSRightMouseUp:
  234157. case NSOtherMouseUp:
  234158. case NSOtherMouseDragged:
  234159. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234160. return false;
  234161. break;
  234162. case NSMouseMoved:
  234163. case NSMouseEntered:
  234164. case NSMouseExited:
  234165. case NSCursorUpdate:
  234166. case NSScrollWheel:
  234167. case NSTabletPoint:
  234168. case NSTabletProximity:
  234169. break;
  234170. default:
  234171. return false;
  234172. }
  234173. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234174. {
  234175. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234176. NSView* const compView = (NSView*) peer->getNativeHandle();
  234177. if ([compView window] == w)
  234178. {
  234179. if (isKey)
  234180. {
  234181. if (compView == [w firstResponder])
  234182. return false;
  234183. }
  234184. else
  234185. {
  234186. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234187. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234188. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234189. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234190. return false;
  234191. }
  234192. }
  234193. }
  234194. if (isInputAttempt)
  234195. {
  234196. if (! [NSApp isActive])
  234197. [NSApp activateIgnoringOtherApps: YES];
  234198. Component* const modal = Component::getCurrentlyModalComponent (0);
  234199. if (modal != 0)
  234200. modal->inputAttemptWhenModal();
  234201. }
  234202. return true;
  234203. }
  234204. }
  234205. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234206. {
  234207. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234208. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234209. while (! quitMessagePosted)
  234210. {
  234211. const ScopedAutoReleasePool pool;
  234212. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234213. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234214. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234215. inMode: NSDefaultRunLoopMode
  234216. dequeue: YES];
  234217. if (e != 0 && ! isEventBlockedByModalComps (e))
  234218. [NSApp sendEvent: e];
  234219. if (Time::getMillisecondCounter() >= endTime)
  234220. break;
  234221. }
  234222. return ! quitMessagePosted;
  234223. }
  234224. void MessageManager::doPlatformSpecificInitialisation()
  234225. {
  234226. if (juceAppDelegate == 0)
  234227. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234228. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234229. // correctly (needed prior to 10.5)
  234230. if (! [NSThread isMultiThreaded])
  234231. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234232. toTarget: juceAppDelegate
  234233. withObject: nil];
  234234. }
  234235. void MessageManager::doPlatformSpecificShutdown()
  234236. {
  234237. if (juceAppDelegate != 0)
  234238. {
  234239. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234240. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234241. [juceAppDelegate release];
  234242. juceAppDelegate = 0;
  234243. }
  234244. }
  234245. bool juce_postMessageToSystemQueue (Message* message)
  234246. {
  234247. juceAppDelegate->redirector->postMessage (message);
  234248. return true;
  234249. }
  234250. void MessageManager::broadcastMessage (const String&)
  234251. {
  234252. }
  234253. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234254. {
  234255. if (isThisTheMessageThread())
  234256. {
  234257. return (*callback) (data);
  234258. }
  234259. else
  234260. {
  234261. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234262. // deadlock because the message manager is blocked from running, so can never
  234263. // call your function..
  234264. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234265. const ScopedAutoReleasePool pool;
  234266. AppDelegateRedirector::CallbackMessagePayload cmp;
  234267. cmp.function = callback;
  234268. cmp.parameter = data;
  234269. cmp.result = 0;
  234270. cmp.hasBeenExecuted = false;
  234271. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234272. withObject: [NSData dataWithBytesNoCopy: &cmp
  234273. length: sizeof (cmp)
  234274. freeWhenDone: NO]
  234275. waitUntilDone: YES];
  234276. return cmp.result;
  234277. }
  234278. }
  234279. #endif
  234280. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234281. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234282. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234283. // compiled on its own).
  234284. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234285. #if JUCE_MAC
  234286. END_JUCE_NAMESPACE
  234287. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234288. @interface DownloadClickDetector : NSObject
  234289. {
  234290. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234291. }
  234292. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234293. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234294. request: (NSURLRequest*) request
  234295. frame: (WebFrame*) frame
  234296. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234297. @end
  234298. @implementation DownloadClickDetector
  234299. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  234300. {
  234301. [super init];
  234302. ownerComponent = ownerComponent_;
  234303. return self;
  234304. }
  234305. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234306. request: (NSURLRequest*) request
  234307. frame: (WebFrame*) frame
  234308. decisionListener: (id <WebPolicyDecisionListener>) listener
  234309. {
  234310. (void) sender;
  234311. (void) request;
  234312. (void) frame;
  234313. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  234314. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  234315. [listener use];
  234316. else
  234317. [listener ignore];
  234318. }
  234319. @end
  234320. BEGIN_JUCE_NAMESPACE
  234321. class WebBrowserComponentInternal : public NSViewComponent
  234322. {
  234323. public:
  234324. WebBrowserComponentInternal (WebBrowserComponent* owner)
  234325. {
  234326. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  234327. frameName: @""
  234328. groupName: @""];
  234329. setView (webView);
  234330. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  234331. [webView setPolicyDelegate: clickListener];
  234332. }
  234333. ~WebBrowserComponentInternal()
  234334. {
  234335. [webView setPolicyDelegate: nil];
  234336. [clickListener release];
  234337. setView (0);
  234338. }
  234339. void goToURL (const String& url,
  234340. const StringArray* headers,
  234341. const MemoryBlock* postData)
  234342. {
  234343. NSMutableURLRequest* r
  234344. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  234345. cachePolicy: NSURLRequestUseProtocolCachePolicy
  234346. timeoutInterval: 30.0];
  234347. if (postData != 0 && postData->getSize() > 0)
  234348. {
  234349. [r setHTTPMethod: @"POST"];
  234350. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  234351. length: postData->getSize()]];
  234352. }
  234353. if (headers != 0)
  234354. {
  234355. for (int i = 0; i < headers->size(); ++i)
  234356. {
  234357. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  234358. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  234359. [r setValue: juceStringToNS (headerValue)
  234360. forHTTPHeaderField: juceStringToNS (headerName)];
  234361. }
  234362. }
  234363. stop();
  234364. [[webView mainFrame] loadRequest: r];
  234365. }
  234366. void goBack()
  234367. {
  234368. [webView goBack];
  234369. }
  234370. void goForward()
  234371. {
  234372. [webView goForward];
  234373. }
  234374. void stop()
  234375. {
  234376. [webView stopLoading: nil];
  234377. }
  234378. void refresh()
  234379. {
  234380. [webView reload: nil];
  234381. }
  234382. void mouseMove (const MouseEvent&)
  234383. {
  234384. // WebKit doesn't capture mouse-moves itself, so it seems the only way to make
  234385. // them work is to push them via this non-public method..
  234386. if ([webView respondsToSelector: @selector (_updateMouseoverWithFakeEvent)])
  234387. [webView performSelector: @selector (_updateMouseoverWithFakeEvent)];
  234388. }
  234389. private:
  234390. WebView* webView;
  234391. DownloadClickDetector* clickListener;
  234392. };
  234393. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234394. : browser (0),
  234395. blankPageShown (false),
  234396. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  234397. {
  234398. setOpaque (true);
  234399. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  234400. }
  234401. WebBrowserComponent::~WebBrowserComponent()
  234402. {
  234403. deleteAndZero (browser);
  234404. }
  234405. void WebBrowserComponent::goToURL (const String& url,
  234406. const StringArray* headers,
  234407. const MemoryBlock* postData)
  234408. {
  234409. lastURL = url;
  234410. lastHeaders.clear();
  234411. if (headers != 0)
  234412. lastHeaders = *headers;
  234413. lastPostData.setSize (0);
  234414. if (postData != 0)
  234415. lastPostData = *postData;
  234416. blankPageShown = false;
  234417. browser->goToURL (url, headers, postData);
  234418. }
  234419. void WebBrowserComponent::stop()
  234420. {
  234421. browser->stop();
  234422. }
  234423. void WebBrowserComponent::goBack()
  234424. {
  234425. lastURL = String::empty;
  234426. blankPageShown = false;
  234427. browser->goBack();
  234428. }
  234429. void WebBrowserComponent::goForward()
  234430. {
  234431. lastURL = String::empty;
  234432. browser->goForward();
  234433. }
  234434. void WebBrowserComponent::refresh()
  234435. {
  234436. browser->refresh();
  234437. }
  234438. void WebBrowserComponent::paint (Graphics&)
  234439. {
  234440. }
  234441. void WebBrowserComponent::checkWindowAssociation()
  234442. {
  234443. if (isShowing())
  234444. {
  234445. if (blankPageShown)
  234446. goBack();
  234447. }
  234448. else
  234449. {
  234450. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  234451. {
  234452. // when the component becomes invisible, some stuff like flash
  234453. // carries on playing audio, so we need to force it onto a blank
  234454. // page to avoid this, (and send it back when it's made visible again).
  234455. blankPageShown = true;
  234456. browser->goToURL ("about:blank", 0, 0);
  234457. }
  234458. }
  234459. }
  234460. void WebBrowserComponent::reloadLastURL()
  234461. {
  234462. if (lastURL.isNotEmpty())
  234463. {
  234464. goToURL (lastURL, &lastHeaders, &lastPostData);
  234465. lastURL = String::empty;
  234466. }
  234467. }
  234468. void WebBrowserComponent::parentHierarchyChanged()
  234469. {
  234470. checkWindowAssociation();
  234471. }
  234472. void WebBrowserComponent::resized()
  234473. {
  234474. browser->setSize (getWidth(), getHeight());
  234475. }
  234476. void WebBrowserComponent::visibilityChanged()
  234477. {
  234478. checkWindowAssociation();
  234479. }
  234480. bool WebBrowserComponent::pageAboutToLoad (const String&)
  234481. {
  234482. return true;
  234483. }
  234484. #else
  234485. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  234486. {
  234487. }
  234488. WebBrowserComponent::~WebBrowserComponent()
  234489. {
  234490. }
  234491. void WebBrowserComponent::goToURL (const String& url,
  234492. const StringArray* headers,
  234493. const MemoryBlock* postData)
  234494. {
  234495. }
  234496. void WebBrowserComponent::stop()
  234497. {
  234498. }
  234499. void WebBrowserComponent::goBack()
  234500. {
  234501. }
  234502. void WebBrowserComponent::goForward()
  234503. {
  234504. }
  234505. void WebBrowserComponent::refresh()
  234506. {
  234507. }
  234508. void WebBrowserComponent::paint (Graphics& g)
  234509. {
  234510. }
  234511. void WebBrowserComponent::checkWindowAssociation()
  234512. {
  234513. }
  234514. void WebBrowserComponent::reloadLastURL()
  234515. {
  234516. }
  234517. void WebBrowserComponent::parentHierarchyChanged()
  234518. {
  234519. }
  234520. void WebBrowserComponent::resized()
  234521. {
  234522. }
  234523. void WebBrowserComponent::visibilityChanged()
  234524. {
  234525. }
  234526. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  234527. {
  234528. return true;
  234529. }
  234530. #endif
  234531. #endif
  234532. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234533. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  234534. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234535. // compiled on its own).
  234536. #if JUCE_INCLUDED_FILE
  234537. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234538. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  234539. #endif
  234540. #undef log
  234541. #if JUCE_COREAUDIO_LOGGING_ENABLED
  234542. #define log(a) Logger::writeToLog (a)
  234543. #else
  234544. #define log(a)
  234545. #endif
  234546. #undef OK
  234547. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  234548. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  234549. {
  234550. if (err == noErr)
  234551. return true;
  234552. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  234553. jassertfalse;
  234554. return false;
  234555. }
  234556. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  234557. #else
  234558. #define OK(a) (a == noErr)
  234559. #endif
  234560. class CoreAudioInternal : public Timer
  234561. {
  234562. public:
  234563. CoreAudioInternal (AudioDeviceID id)
  234564. : inputLatency (0),
  234565. outputLatency (0),
  234566. callback (0),
  234567. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  234568. audioProcID (0),
  234569. #endif
  234570. isSlaveDevice (false),
  234571. deviceID (id),
  234572. started (false),
  234573. sampleRate (0),
  234574. bufferSize (512),
  234575. numInputChans (0),
  234576. numOutputChans (0),
  234577. callbacksAllowed (true),
  234578. numInputChannelInfos (0),
  234579. numOutputChannelInfos (0)
  234580. {
  234581. jassert (deviceID != 0);
  234582. updateDetailsFromDevice();
  234583. AudioObjectPropertyAddress pa;
  234584. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234585. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234586. pa.mElement = kAudioObjectPropertyElementWildcard;
  234587. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  234588. }
  234589. ~CoreAudioInternal()
  234590. {
  234591. AudioObjectPropertyAddress pa;
  234592. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  234593. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234594. pa.mElement = kAudioObjectPropertyElementWildcard;
  234595. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  234596. stop (false);
  234597. }
  234598. void allocateTempBuffers()
  234599. {
  234600. const int tempBufSize = bufferSize + 4;
  234601. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  234602. tempInputBuffers.calloc (numInputChans + 2);
  234603. tempOutputBuffers.calloc (numOutputChans + 2);
  234604. int i, count = 0;
  234605. for (i = 0; i < numInputChans; ++i)
  234606. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234607. for (i = 0; i < numOutputChans; ++i)
  234608. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  234609. }
  234610. // returns the number of actual available channels
  234611. void fillInChannelInfo (const bool input)
  234612. {
  234613. int chanNum = 0;
  234614. UInt32 size;
  234615. AudioObjectPropertyAddress pa;
  234616. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  234617. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234618. pa.mElement = kAudioObjectPropertyElementMaster;
  234619. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234620. {
  234621. HeapBlock <AudioBufferList> bufList;
  234622. bufList.calloc (size, 1);
  234623. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  234624. {
  234625. const int numStreams = bufList->mNumberBuffers;
  234626. for (int i = 0; i < numStreams; ++i)
  234627. {
  234628. const AudioBuffer& b = bufList->mBuffers[i];
  234629. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  234630. {
  234631. String name;
  234632. {
  234633. char channelName [256];
  234634. zerostruct (channelName);
  234635. UInt32 nameSize = sizeof (channelName);
  234636. UInt32 channelNum = chanNum + 1;
  234637. pa.mSelector = kAudioDevicePropertyChannelName;
  234638. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  234639. name = String::fromUTF8 (channelName, nameSize);
  234640. }
  234641. if (input)
  234642. {
  234643. if (activeInputChans[chanNum])
  234644. {
  234645. inputChannelInfo [numInputChannelInfos].streamNum = i;
  234646. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  234647. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234648. ++numInputChannelInfos;
  234649. }
  234650. if (name.isEmpty())
  234651. name << "Input " << (chanNum + 1);
  234652. inChanNames.add (name);
  234653. }
  234654. else
  234655. {
  234656. if (activeOutputChans[chanNum])
  234657. {
  234658. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  234659. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  234660. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  234661. ++numOutputChannelInfos;
  234662. }
  234663. if (name.isEmpty())
  234664. name << "Output " << (chanNum + 1);
  234665. outChanNames.add (name);
  234666. }
  234667. ++chanNum;
  234668. }
  234669. }
  234670. }
  234671. }
  234672. }
  234673. void updateDetailsFromDevice()
  234674. {
  234675. stopTimer();
  234676. if (deviceID == 0)
  234677. return;
  234678. const ScopedLock sl (callbackLock);
  234679. Float64 sr;
  234680. UInt32 size = sizeof (Float64);
  234681. AudioObjectPropertyAddress pa;
  234682. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234683. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234684. pa.mElement = kAudioObjectPropertyElementMaster;
  234685. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  234686. sampleRate = sr;
  234687. UInt32 framesPerBuf;
  234688. size = sizeof (framesPerBuf);
  234689. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234690. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  234691. {
  234692. bufferSize = framesPerBuf;
  234693. allocateTempBuffers();
  234694. }
  234695. bufferSizes.clear();
  234696. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  234697. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234698. {
  234699. HeapBlock <AudioValueRange> ranges;
  234700. ranges.calloc (size, 1);
  234701. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234702. {
  234703. bufferSizes.add ((int) ranges[0].mMinimum);
  234704. for (int i = 32; i < 2048; i += 32)
  234705. {
  234706. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234707. {
  234708. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  234709. {
  234710. bufferSizes.addIfNotAlreadyThere (i);
  234711. break;
  234712. }
  234713. }
  234714. }
  234715. if (bufferSize > 0)
  234716. bufferSizes.addIfNotAlreadyThere (bufferSize);
  234717. }
  234718. }
  234719. if (bufferSizes.size() == 0 && bufferSize > 0)
  234720. bufferSizes.add (bufferSize);
  234721. sampleRates.clear();
  234722. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  234723. String rates;
  234724. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  234725. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  234726. {
  234727. HeapBlock <AudioValueRange> ranges;
  234728. ranges.calloc (size, 1);
  234729. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  234730. {
  234731. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  234732. {
  234733. bool ok = false;
  234734. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  234735. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  234736. ok = true;
  234737. if (ok)
  234738. {
  234739. sampleRates.add (possibleRates[i]);
  234740. rates << possibleRates[i] << ' ';
  234741. }
  234742. }
  234743. }
  234744. }
  234745. if (sampleRates.size() == 0 && sampleRate > 0)
  234746. {
  234747. sampleRates.add (sampleRate);
  234748. rates << sampleRate;
  234749. }
  234750. log ("sr: " + rates);
  234751. inputLatency = 0;
  234752. outputLatency = 0;
  234753. UInt32 lat;
  234754. size = sizeof (lat);
  234755. pa.mSelector = kAudioDevicePropertyLatency;
  234756. pa.mScope = kAudioDevicePropertyScopeInput;
  234757. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234758. inputLatency = (int) lat;
  234759. pa.mScope = kAudioDevicePropertyScopeOutput;
  234760. size = sizeof (lat);
  234761. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  234762. outputLatency = (int) lat;
  234763. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  234764. inChanNames.clear();
  234765. outChanNames.clear();
  234766. inputChannelInfo.calloc (numInputChans + 2);
  234767. numInputChannelInfos = 0;
  234768. outputChannelInfo.calloc (numOutputChans + 2);
  234769. numOutputChannelInfos = 0;
  234770. fillInChannelInfo (true);
  234771. fillInChannelInfo (false);
  234772. }
  234773. const StringArray getSources (bool input)
  234774. {
  234775. StringArray s;
  234776. HeapBlock <OSType> types;
  234777. const int num = getAllDataSourcesForDevice (deviceID, types);
  234778. for (int i = 0; i < num; ++i)
  234779. {
  234780. AudioValueTranslation avt;
  234781. char buffer[256];
  234782. avt.mInputData = &(types[i]);
  234783. avt.mInputDataSize = sizeof (UInt32);
  234784. avt.mOutputData = buffer;
  234785. avt.mOutputDataSize = 256;
  234786. UInt32 transSize = sizeof (avt);
  234787. AudioObjectPropertyAddress pa;
  234788. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  234789. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234790. pa.mElement = kAudioObjectPropertyElementMaster;
  234791. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  234792. {
  234793. DBG (buffer);
  234794. s.add (buffer);
  234795. }
  234796. }
  234797. return s;
  234798. }
  234799. int getCurrentSourceIndex (bool input) const
  234800. {
  234801. OSType currentSourceID = 0;
  234802. UInt32 size = sizeof (currentSourceID);
  234803. int result = -1;
  234804. AudioObjectPropertyAddress pa;
  234805. pa.mSelector = kAudioDevicePropertyDataSource;
  234806. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234807. pa.mElement = kAudioObjectPropertyElementMaster;
  234808. if (deviceID != 0)
  234809. {
  234810. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  234811. {
  234812. HeapBlock <OSType> types;
  234813. const int num = getAllDataSourcesForDevice (deviceID, types);
  234814. for (int i = 0; i < num; ++i)
  234815. {
  234816. if (types[num] == currentSourceID)
  234817. {
  234818. result = i;
  234819. break;
  234820. }
  234821. }
  234822. }
  234823. }
  234824. return result;
  234825. }
  234826. void setCurrentSourceIndex (int index, bool input)
  234827. {
  234828. if (deviceID != 0)
  234829. {
  234830. HeapBlock <OSType> types;
  234831. const int num = getAllDataSourcesForDevice (deviceID, types);
  234832. if (isPositiveAndBelow (index, num))
  234833. {
  234834. AudioObjectPropertyAddress pa;
  234835. pa.mSelector = kAudioDevicePropertyDataSource;
  234836. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  234837. pa.mElement = kAudioObjectPropertyElementMaster;
  234838. OSType typeId = types[index];
  234839. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  234840. }
  234841. }
  234842. }
  234843. const String reopen (const BigInteger& inputChannels,
  234844. const BigInteger& outputChannels,
  234845. double newSampleRate,
  234846. int bufferSizeSamples)
  234847. {
  234848. String error;
  234849. log ("CoreAudio reopen");
  234850. callbacksAllowed = false;
  234851. stopTimer();
  234852. stop (false);
  234853. activeInputChans = inputChannels;
  234854. activeInputChans.setRange (inChanNames.size(),
  234855. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  234856. false);
  234857. activeOutputChans = outputChannels;
  234858. activeOutputChans.setRange (outChanNames.size(),
  234859. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  234860. false);
  234861. numInputChans = activeInputChans.countNumberOfSetBits();
  234862. numOutputChans = activeOutputChans.countNumberOfSetBits();
  234863. // set sample rate
  234864. AudioObjectPropertyAddress pa;
  234865. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  234866. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234867. pa.mElement = kAudioObjectPropertyElementMaster;
  234868. Float64 sr = newSampleRate;
  234869. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  234870. {
  234871. error = "Couldn't change sample rate";
  234872. }
  234873. else
  234874. {
  234875. // change buffer size
  234876. UInt32 framesPerBuf = bufferSizeSamples;
  234877. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  234878. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  234879. {
  234880. error = "Couldn't change buffer size";
  234881. }
  234882. else
  234883. {
  234884. // Annoyingly, after changing the rate and buffer size, some devices fail to
  234885. // correctly report their new settings until some random time in the future, so
  234886. // after calling updateDetailsFromDevice, we need to manually bodge these values
  234887. // to make sure we're using the correct numbers..
  234888. updateDetailsFromDevice();
  234889. sampleRate = newSampleRate;
  234890. bufferSize = bufferSizeSamples;
  234891. if (sampleRates.size() == 0)
  234892. error = "Device has no available sample-rates";
  234893. else if (bufferSizes.size() == 0)
  234894. error = "Device has no available buffer-sizes";
  234895. else if (inputDevice != 0)
  234896. error = inputDevice->reopen (inputChannels,
  234897. outputChannels,
  234898. newSampleRate,
  234899. bufferSizeSamples);
  234900. }
  234901. }
  234902. callbacksAllowed = true;
  234903. return error;
  234904. }
  234905. bool start (AudioIODeviceCallback* cb)
  234906. {
  234907. if (! started)
  234908. {
  234909. callback = 0;
  234910. if (deviceID != 0)
  234911. {
  234912. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234913. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  234914. #else
  234915. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  234916. #endif
  234917. {
  234918. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  234919. {
  234920. started = true;
  234921. }
  234922. else
  234923. {
  234924. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234925. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234926. #else
  234927. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234928. audioProcID = 0;
  234929. #endif
  234930. }
  234931. }
  234932. }
  234933. }
  234934. if (started)
  234935. {
  234936. const ScopedLock sl (callbackLock);
  234937. callback = cb;
  234938. }
  234939. if (inputDevice != 0)
  234940. return started && inputDevice->start (cb);
  234941. else
  234942. return started;
  234943. }
  234944. void stop (bool leaveInterruptRunning)
  234945. {
  234946. {
  234947. const ScopedLock sl (callbackLock);
  234948. callback = 0;
  234949. }
  234950. if (started
  234951. && (deviceID != 0)
  234952. && ! leaveInterruptRunning)
  234953. {
  234954. OK (AudioDeviceStop (deviceID, audioIOProc));
  234955. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  234956. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  234957. #else
  234958. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  234959. audioProcID = 0;
  234960. #endif
  234961. started = false;
  234962. { const ScopedLock sl (callbackLock); }
  234963. // wait until it's definately stopped calling back..
  234964. for (int i = 40; --i >= 0;)
  234965. {
  234966. Thread::sleep (50);
  234967. UInt32 running = 0;
  234968. UInt32 size = sizeof (running);
  234969. AudioObjectPropertyAddress pa;
  234970. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  234971. pa.mScope = kAudioObjectPropertyScopeWildcard;
  234972. pa.mElement = kAudioObjectPropertyElementMaster;
  234973. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  234974. if (running == 0)
  234975. break;
  234976. }
  234977. const ScopedLock sl (callbackLock);
  234978. }
  234979. if (inputDevice != 0)
  234980. inputDevice->stop (leaveInterruptRunning);
  234981. }
  234982. double getSampleRate() const
  234983. {
  234984. return sampleRate;
  234985. }
  234986. int getBufferSize() const
  234987. {
  234988. return bufferSize;
  234989. }
  234990. void audioCallback (const AudioBufferList* inInputData,
  234991. AudioBufferList* outOutputData)
  234992. {
  234993. int i;
  234994. const ScopedLock sl (callbackLock);
  234995. if (callback != 0)
  234996. {
  234997. if (inputDevice == 0)
  234998. {
  234999. for (i = numInputChans; --i >= 0;)
  235000. {
  235001. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235002. float* dest = tempInputBuffers [i];
  235003. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235004. + info.dataOffsetSamples;
  235005. const int stride = info.dataStrideSamples;
  235006. if (stride != 0) // if this is zero, info is invalid
  235007. {
  235008. for (int j = bufferSize; --j >= 0;)
  235009. {
  235010. *dest++ = *src;
  235011. src += stride;
  235012. }
  235013. }
  235014. }
  235015. }
  235016. if (! isSlaveDevice)
  235017. {
  235018. if (inputDevice == 0)
  235019. {
  235020. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235021. numInputChans,
  235022. tempOutputBuffers,
  235023. numOutputChans,
  235024. bufferSize);
  235025. }
  235026. else
  235027. {
  235028. jassert (inputDevice->bufferSize == bufferSize);
  235029. // Sometimes the two linked devices seem to get their callbacks in
  235030. // parallel, so we need to lock both devices to stop the input data being
  235031. // changed while inside our callback..
  235032. const ScopedLock sl2 (inputDevice->callbackLock);
  235033. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235034. inputDevice->numInputChans,
  235035. tempOutputBuffers,
  235036. numOutputChans,
  235037. bufferSize);
  235038. }
  235039. for (i = numOutputChans; --i >= 0;)
  235040. {
  235041. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235042. const float* src = tempOutputBuffers [i];
  235043. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235044. + info.dataOffsetSamples;
  235045. const int stride = info.dataStrideSamples;
  235046. if (stride != 0) // if this is zero, info is invalid
  235047. {
  235048. for (int j = bufferSize; --j >= 0;)
  235049. {
  235050. *dest = *src++;
  235051. dest += stride;
  235052. }
  235053. }
  235054. }
  235055. }
  235056. }
  235057. else
  235058. {
  235059. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235060. {
  235061. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235062. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235063. + info.dataOffsetSamples;
  235064. const int stride = info.dataStrideSamples;
  235065. if (stride != 0) // if this is zero, info is invalid
  235066. {
  235067. for (int j = bufferSize; --j >= 0;)
  235068. {
  235069. *dest = 0.0f;
  235070. dest += stride;
  235071. }
  235072. }
  235073. }
  235074. }
  235075. }
  235076. // called by callbacks
  235077. void deviceDetailsChanged()
  235078. {
  235079. if (callbacksAllowed)
  235080. startTimer (100);
  235081. }
  235082. void timerCallback()
  235083. {
  235084. stopTimer();
  235085. log ("CoreAudio device changed callback");
  235086. const double oldSampleRate = sampleRate;
  235087. const int oldBufferSize = bufferSize;
  235088. updateDetailsFromDevice();
  235089. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235090. {
  235091. callbacksAllowed = false;
  235092. stop (false);
  235093. updateDetailsFromDevice();
  235094. callbacksAllowed = true;
  235095. }
  235096. }
  235097. CoreAudioInternal* getRelatedDevice() const
  235098. {
  235099. UInt32 size = 0;
  235100. ScopedPointer <CoreAudioInternal> result;
  235101. AudioObjectPropertyAddress pa;
  235102. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235103. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235104. pa.mElement = kAudioObjectPropertyElementMaster;
  235105. if (deviceID != 0
  235106. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235107. && size > 0)
  235108. {
  235109. HeapBlock <AudioDeviceID> devs;
  235110. devs.calloc (size, 1);
  235111. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235112. {
  235113. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235114. {
  235115. if (devs[i] != deviceID && devs[i] != 0)
  235116. {
  235117. result = new CoreAudioInternal (devs[i]);
  235118. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235119. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235120. if (thisIsInput != otherIsInput
  235121. || (inChanNames.size() + outChanNames.size() == 0)
  235122. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235123. break;
  235124. result = 0;
  235125. }
  235126. }
  235127. }
  235128. }
  235129. return result.release();
  235130. }
  235131. int inputLatency, outputLatency;
  235132. BigInteger activeInputChans, activeOutputChans;
  235133. StringArray inChanNames, outChanNames;
  235134. Array <double> sampleRates;
  235135. Array <int> bufferSizes;
  235136. AudioIODeviceCallback* callback;
  235137. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235138. AudioDeviceIOProcID audioProcID;
  235139. #endif
  235140. ScopedPointer<CoreAudioInternal> inputDevice;
  235141. bool isSlaveDevice;
  235142. private:
  235143. CriticalSection callbackLock;
  235144. AudioDeviceID deviceID;
  235145. bool started;
  235146. double sampleRate;
  235147. int bufferSize;
  235148. HeapBlock <float> audioBuffer;
  235149. int numInputChans, numOutputChans;
  235150. bool callbacksAllowed;
  235151. struct CallbackDetailsForChannel
  235152. {
  235153. int streamNum;
  235154. int dataOffsetSamples;
  235155. int dataStrideSamples;
  235156. };
  235157. int numInputChannelInfos, numOutputChannelInfos;
  235158. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235159. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235160. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235161. const AudioTimeStamp* /*inNow*/,
  235162. const AudioBufferList* inInputData,
  235163. const AudioTimeStamp* /*inInputTime*/,
  235164. AudioBufferList* outOutputData,
  235165. const AudioTimeStamp* /*inOutputTime*/,
  235166. void* device)
  235167. {
  235168. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235169. return noErr;
  235170. }
  235171. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235172. {
  235173. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235174. switch (pa->mSelector)
  235175. {
  235176. case kAudioDevicePropertyBufferSize:
  235177. case kAudioDevicePropertyBufferFrameSize:
  235178. case kAudioDevicePropertyNominalSampleRate:
  235179. case kAudioDevicePropertyStreamFormat:
  235180. case kAudioDevicePropertyDeviceIsAlive:
  235181. intern->deviceDetailsChanged();
  235182. break;
  235183. case kAudioDevicePropertyBufferSizeRange:
  235184. case kAudioDevicePropertyVolumeScalar:
  235185. case kAudioDevicePropertyMute:
  235186. case kAudioDevicePropertyPlayThru:
  235187. case kAudioDevicePropertyDataSource:
  235188. case kAudioDevicePropertyDeviceIsRunning:
  235189. break;
  235190. }
  235191. return noErr;
  235192. }
  235193. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235194. {
  235195. AudioObjectPropertyAddress pa;
  235196. pa.mSelector = kAudioDevicePropertyDataSources;
  235197. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235198. pa.mElement = kAudioObjectPropertyElementMaster;
  235199. UInt32 size = 0;
  235200. if (deviceID != 0
  235201. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235202. {
  235203. types.calloc (size, 1);
  235204. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235205. return size / (int) sizeof (OSType);
  235206. }
  235207. return 0;
  235208. }
  235209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioInternal);
  235210. };
  235211. class CoreAudioIODevice : public AudioIODevice
  235212. {
  235213. public:
  235214. CoreAudioIODevice (const String& deviceName,
  235215. AudioDeviceID inputDeviceId,
  235216. const int inputIndex_,
  235217. AudioDeviceID outputDeviceId,
  235218. const int outputIndex_)
  235219. : AudioIODevice (deviceName, "CoreAudio"),
  235220. inputIndex (inputIndex_),
  235221. outputIndex (outputIndex_),
  235222. isOpen_ (false),
  235223. isStarted (false)
  235224. {
  235225. CoreAudioInternal* device = 0;
  235226. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235227. {
  235228. jassert (inputDeviceId != 0);
  235229. device = new CoreAudioInternal (inputDeviceId);
  235230. }
  235231. else
  235232. {
  235233. device = new CoreAudioInternal (outputDeviceId);
  235234. if (inputDeviceId != 0)
  235235. {
  235236. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235237. device->inputDevice = secondDevice;
  235238. secondDevice->isSlaveDevice = true;
  235239. }
  235240. }
  235241. internal = device;
  235242. AudioObjectPropertyAddress pa;
  235243. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235244. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235245. pa.mElement = kAudioObjectPropertyElementWildcard;
  235246. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235247. }
  235248. ~CoreAudioIODevice()
  235249. {
  235250. AudioObjectPropertyAddress pa;
  235251. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235252. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235253. pa.mElement = kAudioObjectPropertyElementWildcard;
  235254. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235255. }
  235256. const StringArray getOutputChannelNames()
  235257. {
  235258. return internal->outChanNames;
  235259. }
  235260. const StringArray getInputChannelNames()
  235261. {
  235262. if (internal->inputDevice != 0)
  235263. return internal->inputDevice->inChanNames;
  235264. else
  235265. return internal->inChanNames;
  235266. }
  235267. int getNumSampleRates()
  235268. {
  235269. return internal->sampleRates.size();
  235270. }
  235271. double getSampleRate (int index)
  235272. {
  235273. return internal->sampleRates [index];
  235274. }
  235275. int getNumBufferSizesAvailable()
  235276. {
  235277. return internal->bufferSizes.size();
  235278. }
  235279. int getBufferSizeSamples (int index)
  235280. {
  235281. return internal->bufferSizes [index];
  235282. }
  235283. int getDefaultBufferSize()
  235284. {
  235285. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235286. if (getBufferSizeSamples(i) >= 512)
  235287. return getBufferSizeSamples(i);
  235288. return 512;
  235289. }
  235290. const String open (const BigInteger& inputChannels,
  235291. const BigInteger& outputChannels,
  235292. double sampleRate,
  235293. int bufferSizeSamples)
  235294. {
  235295. isOpen_ = true;
  235296. if (bufferSizeSamples <= 0)
  235297. bufferSizeSamples = getDefaultBufferSize();
  235298. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235299. isOpen_ = lastError.isEmpty();
  235300. return lastError;
  235301. }
  235302. void close()
  235303. {
  235304. isOpen_ = false;
  235305. internal->stop (false);
  235306. }
  235307. bool isOpen()
  235308. {
  235309. return isOpen_;
  235310. }
  235311. int getCurrentBufferSizeSamples()
  235312. {
  235313. return internal != 0 ? internal->getBufferSize() : 512;
  235314. }
  235315. double getCurrentSampleRate()
  235316. {
  235317. return internal != 0 ? internal->getSampleRate() : 0;
  235318. }
  235319. int getCurrentBitDepth()
  235320. {
  235321. return 32; // no way to find out, so just assume it's high..
  235322. }
  235323. const BigInteger getActiveOutputChannels() const
  235324. {
  235325. return internal != 0 ? internal->activeOutputChans : BigInteger();
  235326. }
  235327. const BigInteger getActiveInputChannels() const
  235328. {
  235329. BigInteger chans;
  235330. if (internal != 0)
  235331. {
  235332. chans = internal->activeInputChans;
  235333. if (internal->inputDevice != 0)
  235334. chans |= internal->inputDevice->activeInputChans;
  235335. }
  235336. return chans;
  235337. }
  235338. int getOutputLatencyInSamples()
  235339. {
  235340. if (internal == 0)
  235341. return 0;
  235342. // this seems like a good guess at getting the latency right - comparing
  235343. // this with a round-trip measurement, it gets it to within a few millisecs
  235344. // for the built-in mac soundcard
  235345. return internal->outputLatency + internal->getBufferSize() * 2;
  235346. }
  235347. int getInputLatencyInSamples()
  235348. {
  235349. if (internal == 0)
  235350. return 0;
  235351. return internal->inputLatency + internal->getBufferSize() * 2;
  235352. }
  235353. void start (AudioIODeviceCallback* callback)
  235354. {
  235355. if (internal != 0 && ! isStarted)
  235356. {
  235357. if (callback != 0)
  235358. callback->audioDeviceAboutToStart (this);
  235359. isStarted = true;
  235360. internal->start (callback);
  235361. }
  235362. }
  235363. void stop()
  235364. {
  235365. if (isStarted && internal != 0)
  235366. {
  235367. AudioIODeviceCallback* const lastCallback = internal->callback;
  235368. isStarted = false;
  235369. internal->stop (true);
  235370. if (lastCallback != 0)
  235371. lastCallback->audioDeviceStopped();
  235372. }
  235373. }
  235374. bool isPlaying()
  235375. {
  235376. if (internal->callback == 0)
  235377. isStarted = false;
  235378. return isStarted;
  235379. }
  235380. const String getLastError()
  235381. {
  235382. return lastError;
  235383. }
  235384. int inputIndex, outputIndex;
  235385. private:
  235386. ScopedPointer<CoreAudioInternal> internal;
  235387. bool isOpen_, isStarted;
  235388. String lastError;
  235389. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235390. {
  235391. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235392. switch (pa->mSelector)
  235393. {
  235394. case kAudioHardwarePropertyDevices:
  235395. intern->deviceDetailsChanged();
  235396. break;
  235397. case kAudioHardwarePropertyDefaultOutputDevice:
  235398. case kAudioHardwarePropertyDefaultInputDevice:
  235399. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  235400. break;
  235401. }
  235402. return noErr;
  235403. }
  235404. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODevice);
  235405. };
  235406. class CoreAudioIODeviceType : public AudioIODeviceType
  235407. {
  235408. public:
  235409. CoreAudioIODeviceType()
  235410. : AudioIODeviceType ("CoreAudio"),
  235411. hasScanned (false)
  235412. {
  235413. }
  235414. ~CoreAudioIODeviceType()
  235415. {
  235416. }
  235417. void scanForDevices()
  235418. {
  235419. hasScanned = true;
  235420. inputDeviceNames.clear();
  235421. outputDeviceNames.clear();
  235422. inputIds.clear();
  235423. outputIds.clear();
  235424. UInt32 size;
  235425. AudioObjectPropertyAddress pa;
  235426. pa.mSelector = kAudioHardwarePropertyDevices;
  235427. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235428. pa.mElement = kAudioObjectPropertyElementMaster;
  235429. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  235430. {
  235431. HeapBlock <AudioDeviceID> devs;
  235432. devs.calloc (size, 1);
  235433. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  235434. {
  235435. const int num = size / (int) sizeof (AudioDeviceID);
  235436. for (int i = 0; i < num; ++i)
  235437. {
  235438. char name [1024];
  235439. size = sizeof (name);
  235440. pa.mSelector = kAudioDevicePropertyDeviceName;
  235441. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  235442. {
  235443. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  235444. const int numIns = getNumChannels (devs[i], true);
  235445. const int numOuts = getNumChannels (devs[i], false);
  235446. if (numIns > 0)
  235447. {
  235448. inputDeviceNames.add (nameString);
  235449. inputIds.add (devs[i]);
  235450. }
  235451. if (numOuts > 0)
  235452. {
  235453. outputDeviceNames.add (nameString);
  235454. outputIds.add (devs[i]);
  235455. }
  235456. }
  235457. }
  235458. }
  235459. }
  235460. inputDeviceNames.appendNumbersToDuplicates (false, true);
  235461. outputDeviceNames.appendNumbersToDuplicates (false, true);
  235462. }
  235463. const StringArray getDeviceNames (bool wantInputNames) const
  235464. {
  235465. jassert (hasScanned); // need to call scanForDevices() before doing this
  235466. if (wantInputNames)
  235467. return inputDeviceNames;
  235468. else
  235469. return outputDeviceNames;
  235470. }
  235471. int getDefaultDeviceIndex (bool forInput) const
  235472. {
  235473. jassert (hasScanned); // need to call scanForDevices() before doing this
  235474. AudioDeviceID deviceID;
  235475. UInt32 size = sizeof (deviceID);
  235476. // if they're asking for any input channels at all, use the default input, so we
  235477. // get the built-in mic rather than the built-in output with no inputs..
  235478. AudioObjectPropertyAddress pa;
  235479. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  235480. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235481. pa.mElement = kAudioObjectPropertyElementMaster;
  235482. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  235483. {
  235484. if (forInput)
  235485. {
  235486. for (int i = inputIds.size(); --i >= 0;)
  235487. if (inputIds[i] == deviceID)
  235488. return i;
  235489. }
  235490. else
  235491. {
  235492. for (int i = outputIds.size(); --i >= 0;)
  235493. if (outputIds[i] == deviceID)
  235494. return i;
  235495. }
  235496. }
  235497. return 0;
  235498. }
  235499. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  235500. {
  235501. jassert (hasScanned); // need to call scanForDevices() before doing this
  235502. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  235503. if (d == 0)
  235504. return -1;
  235505. return asInput ? d->inputIndex
  235506. : d->outputIndex;
  235507. }
  235508. bool hasSeparateInputsAndOutputs() const { return true; }
  235509. AudioIODevice* createDevice (const String& outputDeviceName,
  235510. const String& inputDeviceName)
  235511. {
  235512. jassert (hasScanned); // need to call scanForDevices() before doing this
  235513. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  235514. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  235515. String deviceName (outputDeviceName);
  235516. if (deviceName.isEmpty())
  235517. deviceName = inputDeviceName;
  235518. if (index >= 0)
  235519. return new CoreAudioIODevice (deviceName,
  235520. inputIds [inputIndex],
  235521. inputIndex,
  235522. outputIds [outputIndex],
  235523. outputIndex);
  235524. return 0;
  235525. }
  235526. private:
  235527. StringArray inputDeviceNames, outputDeviceNames;
  235528. Array <AudioDeviceID> inputIds, outputIds;
  235529. bool hasScanned;
  235530. static int getNumChannels (AudioDeviceID deviceID, bool input)
  235531. {
  235532. int total = 0;
  235533. UInt32 size;
  235534. AudioObjectPropertyAddress pa;
  235535. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235536. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235537. pa.mElement = kAudioObjectPropertyElementMaster;
  235538. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235539. {
  235540. HeapBlock <AudioBufferList> bufList;
  235541. bufList.calloc (size, 1);
  235542. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235543. {
  235544. const int numStreams = bufList->mNumberBuffers;
  235545. for (int i = 0; i < numStreams; ++i)
  235546. {
  235547. const AudioBuffer& b = bufList->mBuffers[i];
  235548. total += b.mNumberChannels;
  235549. }
  235550. }
  235551. }
  235552. return total;
  235553. }
  235554. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CoreAudioIODeviceType);
  235555. };
  235556. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  235557. {
  235558. return new CoreAudioIODeviceType();
  235559. }
  235560. #undef log
  235561. #endif
  235562. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  235563. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  235564. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235565. // compiled on its own).
  235566. #if JUCE_INCLUDED_FILE
  235567. #if JUCE_MAC
  235568. namespace CoreMidiHelpers
  235569. {
  235570. bool logError (const OSStatus err, const int lineNum)
  235571. {
  235572. if (err == noErr)
  235573. return true;
  235574. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235575. jassertfalse;
  235576. return false;
  235577. }
  235578. #undef CHECK_ERROR
  235579. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  235580. const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  235581. {
  235582. String result;
  235583. CFStringRef str = 0;
  235584. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  235585. if (str != 0)
  235586. {
  235587. result = PlatformUtilities::cfStringToJuceString (str);
  235588. CFRelease (str);
  235589. str = 0;
  235590. }
  235591. MIDIEntityRef entity = 0;
  235592. MIDIEndpointGetEntity (endpoint, &entity);
  235593. if (entity == 0)
  235594. return result; // probably virtual
  235595. if (result.isEmpty())
  235596. {
  235597. // endpoint name has zero length - try the entity
  235598. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  235599. if (str != 0)
  235600. {
  235601. result += PlatformUtilities::cfStringToJuceString (str);
  235602. CFRelease (str);
  235603. str = 0;
  235604. }
  235605. }
  235606. // now consider the device's name
  235607. MIDIDeviceRef device = 0;
  235608. MIDIEntityGetDevice (entity, &device);
  235609. if (device == 0)
  235610. return result;
  235611. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  235612. if (str != 0)
  235613. {
  235614. const String s (PlatformUtilities::cfStringToJuceString (str));
  235615. CFRelease (str);
  235616. // if an external device has only one entity, throw away
  235617. // the endpoint name and just use the device name
  235618. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  235619. {
  235620. result = s;
  235621. }
  235622. else if (! result.startsWithIgnoreCase (s))
  235623. {
  235624. // prepend the device name to the entity name
  235625. result = (s + " " + result).trimEnd();
  235626. }
  235627. }
  235628. return result;
  235629. }
  235630. const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  235631. {
  235632. String result;
  235633. // Does the endpoint have connections?
  235634. CFDataRef connections = 0;
  235635. int numConnections = 0;
  235636. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  235637. if (connections != 0)
  235638. {
  235639. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  235640. if (numConnections > 0)
  235641. {
  235642. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  235643. for (int i = 0; i < numConnections; ++i, ++pid)
  235644. {
  235645. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  235646. MIDIObjectRef connObject;
  235647. MIDIObjectType connObjectType;
  235648. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  235649. if (err == noErr)
  235650. {
  235651. String s;
  235652. if (connObjectType == kMIDIObjectType_ExternalSource
  235653. || connObjectType == kMIDIObjectType_ExternalDestination)
  235654. {
  235655. // Connected to an external device's endpoint (10.3 and later).
  235656. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  235657. }
  235658. else
  235659. {
  235660. // Connected to an external device (10.2) (or something else, catch-all)
  235661. CFStringRef str = 0;
  235662. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  235663. if (str != 0)
  235664. {
  235665. s = PlatformUtilities::cfStringToJuceString (str);
  235666. CFRelease (str);
  235667. }
  235668. }
  235669. if (s.isNotEmpty())
  235670. {
  235671. if (result.isNotEmpty())
  235672. result += ", ";
  235673. result += s;
  235674. }
  235675. }
  235676. }
  235677. }
  235678. CFRelease (connections);
  235679. }
  235680. if (result.isNotEmpty())
  235681. return result;
  235682. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  235683. return getEndpointName (endpoint, false);
  235684. }
  235685. MIDIClientRef getGlobalMidiClient()
  235686. {
  235687. static MIDIClientRef globalMidiClient = 0;
  235688. if (globalMidiClient == 0)
  235689. {
  235690. String name ("JUCE");
  235691. if (JUCEApplication::getInstance() != 0)
  235692. name = JUCEApplication::getInstance()->getApplicationName();
  235693. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  235694. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  235695. CFRelease (appName);
  235696. }
  235697. return globalMidiClient;
  235698. }
  235699. class MidiPortAndEndpoint
  235700. {
  235701. public:
  235702. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  235703. : port (port_), endPoint (endPoint_)
  235704. {
  235705. }
  235706. ~MidiPortAndEndpoint()
  235707. {
  235708. if (port != 0)
  235709. MIDIPortDispose (port);
  235710. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  235711. MIDIEndpointDispose (endPoint);
  235712. }
  235713. void send (const MIDIPacketList* const packets)
  235714. {
  235715. if (port != 0)
  235716. MIDISend (port, endPoint, packets);
  235717. else
  235718. MIDIReceived (endPoint, packets);
  235719. }
  235720. MIDIPortRef port;
  235721. MIDIEndpointRef endPoint;
  235722. };
  235723. class MidiPortAndCallback;
  235724. CriticalSection callbackLock;
  235725. Array<MidiPortAndCallback*> activeCallbacks;
  235726. class MidiPortAndCallback
  235727. {
  235728. public:
  235729. MidiPortAndCallback (MidiInputCallback& callback_)
  235730. : input (0), active (false), callback (callback_), concatenator (2048)
  235731. {
  235732. }
  235733. ~MidiPortAndCallback()
  235734. {
  235735. active = false;
  235736. {
  235737. const ScopedLock sl (callbackLock);
  235738. activeCallbacks.removeValue (this);
  235739. }
  235740. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  235741. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  235742. }
  235743. void handlePackets (const MIDIPacketList* const pktlist)
  235744. {
  235745. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  235746. const ScopedLock sl (callbackLock);
  235747. if (activeCallbacks.contains (this) && active)
  235748. {
  235749. const MIDIPacket* packet = &pktlist->packet[0];
  235750. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  235751. {
  235752. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  235753. input, callback);
  235754. packet = MIDIPacketNext (packet);
  235755. }
  235756. }
  235757. }
  235758. MidiInput* input;
  235759. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  235760. volatile bool active;
  235761. private:
  235762. MidiInputCallback& callback;
  235763. MidiDataConcatenator concatenator;
  235764. };
  235765. void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  235766. {
  235767. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  235768. }
  235769. }
  235770. const StringArray MidiOutput::getDevices()
  235771. {
  235772. StringArray s;
  235773. const ItemCount num = MIDIGetNumberOfDestinations();
  235774. for (ItemCount i = 0; i < num; ++i)
  235775. {
  235776. MIDIEndpointRef dest = MIDIGetDestination (i);
  235777. if (dest != 0)
  235778. {
  235779. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  235780. if (name.isEmpty())
  235781. name = "<error>";
  235782. s.add (name);
  235783. }
  235784. else
  235785. {
  235786. s.add ("<error>");
  235787. }
  235788. }
  235789. return s;
  235790. }
  235791. int MidiOutput::getDefaultDeviceIndex()
  235792. {
  235793. return 0;
  235794. }
  235795. MidiOutput* MidiOutput::openDevice (int index)
  235796. {
  235797. MidiOutput* mo = 0;
  235798. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfDestinations()))
  235799. {
  235800. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  235801. CFStringRef pname;
  235802. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  235803. {
  235804. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235805. MIDIPortRef port;
  235806. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  235807. {
  235808. mo = new MidiOutput();
  235809. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  235810. }
  235811. CFRelease (pname);
  235812. }
  235813. }
  235814. return mo;
  235815. }
  235816. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  235817. {
  235818. MidiOutput* mo = 0;
  235819. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  235820. MIDIEndpointRef endPoint;
  235821. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  235822. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  235823. {
  235824. mo = new MidiOutput();
  235825. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  235826. }
  235827. CFRelease (name);
  235828. return mo;
  235829. }
  235830. MidiOutput::~MidiOutput()
  235831. {
  235832. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235833. }
  235834. void MidiOutput::reset()
  235835. {
  235836. }
  235837. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  235838. {
  235839. return false;
  235840. }
  235841. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  235842. {
  235843. }
  235844. void MidiOutput::sendMessageNow (const MidiMessage& message)
  235845. {
  235846. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  235847. if (message.isSysEx())
  235848. {
  235849. const int maxPacketSize = 256;
  235850. int pos = 0, bytesLeft = message.getRawDataSize();
  235851. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  235852. HeapBlock <MIDIPacketList> packets;
  235853. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  235854. packets->numPackets = numPackets;
  235855. MIDIPacket* p = packets->packet;
  235856. for (int i = 0; i < numPackets; ++i)
  235857. {
  235858. p->timeStamp = AudioGetCurrentHostTime();
  235859. p->length = jmin (maxPacketSize, bytesLeft);
  235860. memcpy (p->data, message.getRawData() + pos, p->length);
  235861. pos += p->length;
  235862. bytesLeft -= p->length;
  235863. p = MIDIPacketNext (p);
  235864. }
  235865. mpe->send (packets);
  235866. }
  235867. else
  235868. {
  235869. MIDIPacketList packets;
  235870. packets.numPackets = 1;
  235871. packets.packet[0].timeStamp = AudioGetCurrentHostTime();
  235872. packets.packet[0].length = message.getRawDataSize();
  235873. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  235874. mpe->send (&packets);
  235875. }
  235876. }
  235877. const StringArray MidiInput::getDevices()
  235878. {
  235879. StringArray s;
  235880. const ItemCount num = MIDIGetNumberOfSources();
  235881. for (ItemCount i = 0; i < num; ++i)
  235882. {
  235883. MIDIEndpointRef source = MIDIGetSource (i);
  235884. if (source != 0)
  235885. {
  235886. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  235887. if (name.isEmpty())
  235888. name = "<error>";
  235889. s.add (name);
  235890. }
  235891. else
  235892. {
  235893. s.add ("<error>");
  235894. }
  235895. }
  235896. return s;
  235897. }
  235898. int MidiInput::getDefaultDeviceIndex()
  235899. {
  235900. return 0;
  235901. }
  235902. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  235903. {
  235904. jassert (callback != 0);
  235905. using namespace CoreMidiHelpers;
  235906. MidiInput* newInput = 0;
  235907. if (isPositiveAndBelow (index, (int) MIDIGetNumberOfSources()))
  235908. {
  235909. MIDIEndpointRef endPoint = MIDIGetSource (index);
  235910. if (endPoint != 0)
  235911. {
  235912. CFStringRef name;
  235913. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  235914. {
  235915. MIDIClientRef client = getGlobalMidiClient();
  235916. if (client != 0)
  235917. {
  235918. MIDIPortRef port;
  235919. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235920. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  235921. {
  235922. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  235923. {
  235924. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  235925. newInput = new MidiInput (getDevices() [index]);
  235926. mpc->input = newInput;
  235927. newInput->internal = mpc;
  235928. const ScopedLock sl (callbackLock);
  235929. activeCallbacks.add (mpc.release());
  235930. }
  235931. else
  235932. {
  235933. CHECK_ERROR (MIDIPortDispose (port));
  235934. }
  235935. }
  235936. }
  235937. }
  235938. CFRelease (name);
  235939. }
  235940. }
  235941. return newInput;
  235942. }
  235943. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  235944. {
  235945. jassert (callback != 0);
  235946. using namespace CoreMidiHelpers;
  235947. MidiInput* mi = 0;
  235948. MIDIClientRef client = getGlobalMidiClient();
  235949. if (client != 0)
  235950. {
  235951. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  235952. mpc->active = false;
  235953. MIDIEndpointRef endPoint;
  235954. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  235955. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  235956. {
  235957. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  235958. mi = new MidiInput (deviceName);
  235959. mpc->input = mi;
  235960. mi->internal = mpc;
  235961. const ScopedLock sl (callbackLock);
  235962. activeCallbacks.add (mpc.release());
  235963. }
  235964. CFRelease (name);
  235965. }
  235966. return mi;
  235967. }
  235968. MidiInput::MidiInput (const String& name_)
  235969. : name (name_)
  235970. {
  235971. }
  235972. MidiInput::~MidiInput()
  235973. {
  235974. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  235975. }
  235976. void MidiInput::start()
  235977. {
  235978. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235979. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  235980. }
  235981. void MidiInput::stop()
  235982. {
  235983. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  235984. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  235985. }
  235986. #undef CHECK_ERROR
  235987. #else // Stubs for iOS...
  235988. MidiOutput::~MidiOutput() {}
  235989. void MidiOutput::reset() {}
  235990. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  235991. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  235992. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  235993. const StringArray MidiOutput::getDevices() { return StringArray(); }
  235994. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  235995. const StringArray MidiInput::getDevices() { return StringArray(); }
  235996. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  235997. #endif
  235998. #endif
  235999. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236000. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236001. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236002. // compiled on its own).
  236003. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236004. #if ! JUCE_QUICKTIME
  236005. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236006. #endif
  236007. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236008. class QTCameraDeviceInteral;
  236009. END_JUCE_NAMESPACE
  236010. @interface QTCaptureCallbackDelegate : NSObject
  236011. {
  236012. @public
  236013. CameraDevice* owner;
  236014. QTCameraDeviceInteral* internal;
  236015. int64 firstPresentationTime;
  236016. int64 averageTimeOffset;
  236017. }
  236018. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236019. - (void) dealloc;
  236020. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236021. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236022. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236023. fromConnection: (QTCaptureConnection*) connection;
  236024. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236025. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236026. fromConnection: (QTCaptureConnection*) connection;
  236027. @end
  236028. BEGIN_JUCE_NAMESPACE
  236029. class QTCameraDeviceInteral
  236030. {
  236031. public:
  236032. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236033. {
  236034. const ScopedAutoReleasePool pool;
  236035. session = [[QTCaptureSession alloc] init];
  236036. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236037. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236038. input = 0;
  236039. audioInput = 0;
  236040. audioDevice = 0;
  236041. fileOutput = 0;
  236042. imageOutput = 0;
  236043. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236044. internalDev: this];
  236045. NSError* err = 0;
  236046. [device retain];
  236047. [device open: &err];
  236048. if (err == 0)
  236049. {
  236050. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236051. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236052. [session addInput: input error: &err];
  236053. if (err == 0)
  236054. {
  236055. resetFile();
  236056. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236057. [imageOutput setDelegate: callbackDelegate];
  236058. if (err == 0)
  236059. {
  236060. [session startRunning];
  236061. return;
  236062. }
  236063. }
  236064. }
  236065. openingError = nsStringToJuce ([err description]);
  236066. DBG (openingError);
  236067. }
  236068. ~QTCameraDeviceInteral()
  236069. {
  236070. [session stopRunning];
  236071. [session removeOutput: imageOutput];
  236072. [session release];
  236073. [input release];
  236074. [device release];
  236075. [audioDevice release];
  236076. [audioInput release];
  236077. [fileOutput release];
  236078. [imageOutput release];
  236079. [callbackDelegate release];
  236080. }
  236081. void resetFile()
  236082. {
  236083. [fileOutput recordToOutputFileURL: nil];
  236084. [session removeOutput: fileOutput];
  236085. [fileOutput release];
  236086. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236087. [session removeInput: audioInput];
  236088. [audioInput release];
  236089. audioInput = 0;
  236090. [audioDevice release];
  236091. audioDevice = 0;
  236092. [fileOutput setDelegate: callbackDelegate];
  236093. }
  236094. void addDefaultAudioInput()
  236095. {
  236096. NSError* err = nil;
  236097. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236098. if ([audioDevice open: &err])
  236099. [audioDevice retain];
  236100. else
  236101. audioDevice = nil;
  236102. if (audioDevice != 0)
  236103. {
  236104. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236105. [session addInput: audioInput error: &err];
  236106. }
  236107. }
  236108. void addListener (CameraDevice::Listener* listenerToAdd)
  236109. {
  236110. const ScopedLock sl (listenerLock);
  236111. if (listeners.size() == 0)
  236112. [session addOutput: imageOutput error: nil];
  236113. listeners.addIfNotAlreadyThere (listenerToAdd);
  236114. }
  236115. void removeListener (CameraDevice::Listener* listenerToRemove)
  236116. {
  236117. const ScopedLock sl (listenerLock);
  236118. listeners.removeValue (listenerToRemove);
  236119. if (listeners.size() == 0)
  236120. [session removeOutput: imageOutput];
  236121. }
  236122. void callListeners (CIImage* frame, int w, int h)
  236123. {
  236124. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236125. Image image (cgImage);
  236126. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236127. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236128. CGContextFlush (cgImage->context);
  236129. const ScopedLock sl (listenerLock);
  236130. for (int i = listeners.size(); --i >= 0;)
  236131. {
  236132. CameraDevice::Listener* const l = listeners[i];
  236133. if (l != 0)
  236134. l->imageReceived (image);
  236135. }
  236136. }
  236137. QTCaptureDevice* device;
  236138. QTCaptureDeviceInput* input;
  236139. QTCaptureDevice* audioDevice;
  236140. QTCaptureDeviceInput* audioInput;
  236141. QTCaptureSession* session;
  236142. QTCaptureMovieFileOutput* fileOutput;
  236143. QTCaptureDecompressedVideoOutput* imageOutput;
  236144. QTCaptureCallbackDelegate* callbackDelegate;
  236145. String openingError;
  236146. Array<CameraDevice::Listener*> listeners;
  236147. CriticalSection listenerLock;
  236148. };
  236149. END_JUCE_NAMESPACE
  236150. @implementation QTCaptureCallbackDelegate
  236151. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236152. internalDev: (QTCameraDeviceInteral*) d
  236153. {
  236154. [super init];
  236155. owner = owner_;
  236156. internal = d;
  236157. firstPresentationTime = 0;
  236158. averageTimeOffset = 0;
  236159. return self;
  236160. }
  236161. - (void) dealloc
  236162. {
  236163. [super dealloc];
  236164. }
  236165. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236166. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236167. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236168. fromConnection: (QTCaptureConnection*) connection
  236169. {
  236170. if (internal->listeners.size() > 0)
  236171. {
  236172. const ScopedAutoReleasePool pool;
  236173. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236174. CVPixelBufferGetWidth (videoFrame),
  236175. CVPixelBufferGetHeight (videoFrame));
  236176. }
  236177. }
  236178. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236179. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236180. fromConnection: (QTCaptureConnection*) connection
  236181. {
  236182. const Time now (Time::getCurrentTime());
  236183. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236184. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236185. #else
  236186. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236187. #endif
  236188. int64 presentationTime = (hosttime != nil)
  236189. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236190. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236191. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236192. if (firstPresentationTime == 0)
  236193. {
  236194. firstPresentationTime = presentationTime;
  236195. averageTimeOffset = timeDiff;
  236196. }
  236197. else
  236198. {
  236199. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236200. }
  236201. }
  236202. @end
  236203. BEGIN_JUCE_NAMESPACE
  236204. class QTCaptureViewerComp : public NSViewComponent
  236205. {
  236206. public:
  236207. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236208. {
  236209. const ScopedAutoReleasePool pool;
  236210. captureView = [[QTCaptureView alloc] init];
  236211. [captureView setCaptureSession: internal->session];
  236212. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236213. setView (captureView);
  236214. }
  236215. ~QTCaptureViewerComp()
  236216. {
  236217. setView (0);
  236218. [captureView setCaptureSession: nil];
  236219. [captureView release];
  236220. }
  236221. QTCaptureView* captureView;
  236222. };
  236223. CameraDevice::CameraDevice (const String& name_, int index)
  236224. : name (name_)
  236225. {
  236226. isRecording = false;
  236227. internal = new QTCameraDeviceInteral (this, index);
  236228. }
  236229. CameraDevice::~CameraDevice()
  236230. {
  236231. stopRecording();
  236232. delete static_cast <QTCameraDeviceInteral*> (internal);
  236233. internal = 0;
  236234. }
  236235. Component* CameraDevice::createViewerComponent()
  236236. {
  236237. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236238. }
  236239. const String CameraDevice::getFileExtension()
  236240. {
  236241. return ".mov";
  236242. }
  236243. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236244. {
  236245. stopRecording();
  236246. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236247. d->callbackDelegate->firstPresentationTime = 0;
  236248. file.deleteFile();
  236249. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236250. // out wrong, so we'll put some audio in there too..,
  236251. d->addDefaultAudioInput();
  236252. [d->session addOutput: d->fileOutput error: nil];
  236253. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236254. for (;;)
  236255. {
  236256. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236257. if (connection == 0)
  236258. break;
  236259. QTCompressionOptions* options = 0;
  236260. NSString* mediaType = [connection mediaType];
  236261. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236262. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236263. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236264. : @"QTCompressionOptions240SizeH264Video"];
  236265. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236266. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236267. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236268. }
  236269. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236270. isRecording = true;
  236271. }
  236272. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236273. {
  236274. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236275. if (d->callbackDelegate->firstPresentationTime != 0)
  236276. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236277. return Time();
  236278. }
  236279. void CameraDevice::stopRecording()
  236280. {
  236281. if (isRecording)
  236282. {
  236283. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236284. isRecording = false;
  236285. }
  236286. }
  236287. void CameraDevice::addListener (Listener* listenerToAdd)
  236288. {
  236289. if (listenerToAdd != 0)
  236290. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236291. }
  236292. void CameraDevice::removeListener (Listener* listenerToRemove)
  236293. {
  236294. if (listenerToRemove != 0)
  236295. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236296. }
  236297. const StringArray CameraDevice::getAvailableDevices()
  236298. {
  236299. const ScopedAutoReleasePool pool;
  236300. StringArray results;
  236301. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236302. for (int i = 0; i < (int) [devs count]; ++i)
  236303. {
  236304. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  236305. results.add (nsStringToJuce ([dev localizedDisplayName]));
  236306. }
  236307. return results;
  236308. }
  236309. CameraDevice* CameraDevice::openDevice (int index,
  236310. int minWidth, int minHeight,
  236311. int maxWidth, int maxHeight)
  236312. {
  236313. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  236314. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  236315. return d.release();
  236316. return 0;
  236317. }
  236318. #endif
  236319. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  236320. #endif
  236321. #endif
  236322. END_JUCE_NAMESPACE
  236323. #endif
  236324. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  236325. #elif JUCE_ANDROID
  236326. /*** Start of inlined file: juce_android_NativeCode.cpp ***/
  236327. /*
  236328. This file wraps together all the android-specific code, so that
  236329. we can include all the native headers just once, and compile all our
  236330. platform-specific stuff in one big lump, keeping it out of the way of
  236331. the rest of the codebase.
  236332. */
  236333. #if JUCE_ANDROID
  236334. #undef JUCE_BUILD_NATIVE
  236335. #define JUCE_BUILD_NATIVE 1
  236336. BEGIN_JUCE_NAMESPACE
  236337. #define JUCE_JNI_CALLBACK(className, methodName, returnType, params) \
  236338. extern "C" __attribute__ ((visibility("default"))) returnType Java_com_juce_ ## className ## _ ## methodName params
  236339. #define JUCE_JNI_CLASSES(JAVACLASS) \
  236340. JAVACLASS (activityClass, "com/juce/JuceAppActivity") \
  236341. JAVACLASS (componentPeerViewClass, "com/juce/ComponentPeerView") \
  236342. JAVACLASS (fileClass, "java/io/File") \
  236343. JAVACLASS (contextClass, "android/content/Context") \
  236344. JAVACLASS (canvasClass, "android/graphics/Canvas") \
  236345. JAVACLASS (paintClass, "android/graphics/Paint") \
  236346. #define JUCE_JNI_METHODS(METHOD, STATICMETHOD) \
  236347. \
  236348. STATICMETHOD (activityClass, printToConsole, "printToConsole", "(Ljava/lang/String;)V") \
  236349. METHOD (activityClass, createNewView, "createNewView", "()Lcom/juce/ComponentPeerView;") \
  236350. METHOD (activityClass, deleteView, "deleteView", "(Lcom/juce/ComponentPeerView;)V") \
  236351. \
  236352. METHOD (fileClass, fileExists, "exists", "()Z") \
  236353. \
  236354. METHOD (componentPeerViewClass, layout, "layout", "(IIII)V") \
  236355. \
  236356. METHOD (canvasClass, drawRect, "drawRect", "(FFFFLandroid/graphics/Paint;)V") \
  236357. \
  236358. METHOD (paintClass, paintClassConstructor, "<init>", "()V") \
  236359. METHOD (paintClass, setColor, "setColor", "(I)V") \
  236360. class GlobalRef
  236361. {
  236362. public:
  236363. GlobalRef()
  236364. : env (0), obj (0)
  236365. {
  236366. }
  236367. GlobalRef (JNIEnv* const env_, jobject obj_)
  236368. : env (env_),
  236369. obj (retain (env_, obj_))
  236370. {
  236371. }
  236372. GlobalRef (const GlobalRef& other)
  236373. : env (other.env),
  236374. obj (retain (other.env, other.obj))
  236375. {
  236376. }
  236377. ~GlobalRef()
  236378. {
  236379. release();
  236380. }
  236381. GlobalRef& operator= (const GlobalRef& other)
  236382. {
  236383. release();
  236384. env = other.env;
  236385. obj = retain (env, other.obj);
  236386. return *this;
  236387. }
  236388. GlobalRef& operator= (jobject newObj)
  236389. {
  236390. jassert (env != 0 || newObj == 0);
  236391. if (newObj != obj && env != 0)
  236392. {
  236393. release();
  236394. obj = retain (env, newObj);
  236395. }
  236396. }
  236397. inline operator jobject() const throw() { return obj; }
  236398. inline jobject get() const throw() { return obj; }
  236399. inline JNIEnv* getEnv() const throw() { return env; }
  236400. #define DECLARE_CALL_TYPE_METHOD(returnType, typeName) \
  236401. returnType call##typeName##Method (jmethodID methodID, ... ) \
  236402. { \
  236403. returnType result; \
  236404. va_list args; \
  236405. va_start (args, methodID); \
  236406. result = env->Call##typeName##MethodV (obj, methodID, args); \
  236407. va_end (args); \
  236408. return result; \
  236409. }
  236410. DECLARE_CALL_TYPE_METHOD (jobject, Object)
  236411. DECLARE_CALL_TYPE_METHOD (jboolean, Boolean)
  236412. DECLARE_CALL_TYPE_METHOD (jbyte, Byte)
  236413. DECLARE_CALL_TYPE_METHOD (jchar, Char)
  236414. DECLARE_CALL_TYPE_METHOD (jshort, Short)
  236415. DECLARE_CALL_TYPE_METHOD (jint, Int)
  236416. DECLARE_CALL_TYPE_METHOD (jlong, Long)
  236417. DECLARE_CALL_TYPE_METHOD (jfloat, Float)
  236418. DECLARE_CALL_TYPE_METHOD (jdouble, Double)
  236419. #undef DECLARE_CALL_TYPE_METHOD
  236420. void callVoidMethod (jmethodID methodID, ... )
  236421. {
  236422. va_list args;
  236423. va_start (args, methodID);
  236424. env->CallVoidMethodV (obj, methodID, args);
  236425. va_end (args);
  236426. }
  236427. private:
  236428. JNIEnv* env;
  236429. jobject obj;
  236430. void release()
  236431. {
  236432. if (env != 0)
  236433. env->DeleteGlobalRef (obj);
  236434. }
  236435. static jobject retain (JNIEnv* const env, jobject obj_)
  236436. {
  236437. return env == 0 ? 0 : env->NewGlobalRef (obj_);
  236438. }
  236439. };
  236440. class AndroidJavaCallbacks
  236441. {
  236442. public:
  236443. AndroidJavaCallbacks() : env (0)
  236444. {
  236445. }
  236446. void initialise (JNIEnv* env_, jobject activity_)
  236447. {
  236448. env = env_;
  236449. activity = GlobalRef (env, activity_);
  236450. #define CREATE_JNI_CLASS(className, path) \
  236451. className = (jclass) env->NewGlobalRef (env->FindClass (path)); \
  236452. jassert (className != 0);
  236453. JUCE_JNI_CLASSES (CREATE_JNI_CLASS);
  236454. #undef CREATE_JNI_CLASS
  236455. #define CREATE_JNI_METHOD(ownerClass, methodID, stringName, params) \
  236456. methodID = env->GetMethodID (ownerClass, stringName, params); \
  236457. jassert (methodID != 0);
  236458. #define CREATE_JNI_STATICMETHOD(ownerClass, methodID, stringName, params) \
  236459. methodID = env->GetStaticMethodID (ownerClass, stringName, params); \
  236460. jassert (methodID != 0);
  236461. JUCE_JNI_METHODS (CREATE_JNI_METHOD, CREATE_JNI_STATICMETHOD);
  236462. #undef CREATE_JNI_METHOD
  236463. }
  236464. void shutdown()
  236465. {
  236466. if (env != 0)
  236467. {
  236468. #define RELEASE_JNI_CLASS(className, path) env->DeleteGlobalRef (className);
  236469. JUCE_JNI_CLASSES (RELEASE_JNI_CLASS);
  236470. #undef RELEASE_JNI_CLASS
  236471. activity = 0;
  236472. env = 0;
  236473. }
  236474. }
  236475. const String juceString (jstring s) const
  236476. {
  236477. jboolean isCopy;
  236478. const char* const utf8 = env->GetStringUTFChars (s, &isCopy);
  236479. CharPointer_UTF8 utf8CP (utf8);
  236480. const String result (utf8CP);
  236481. env->ReleaseStringUTFChars (s, utf8);
  236482. return result;
  236483. }
  236484. jstring javaString (const String& s) const
  236485. {
  236486. return env->NewStringUTF (s.toUTF8());
  236487. }
  236488. JNIEnv* env;
  236489. GlobalRef activity;
  236490. #define DECLARE_JNI_CLASS(className, path) jclass className;
  236491. JUCE_JNI_CLASSES (DECLARE_JNI_CLASS);
  236492. #undef DECLARE_JNI_CLASS
  236493. #define DECLARE_JNI_METHOD(ownerClass, methodID, stringName, params) jmethodID methodID;
  236494. JUCE_JNI_METHODS (DECLARE_JNI_METHOD, DECLARE_JNI_METHOD);
  236495. #undef DECLARE_JNI_METHOD
  236496. };
  236497. static AndroidJavaCallbacks android;
  236498. #define JUCE_INCLUDED_FILE 1
  236499. // Now include the actual code files..
  236500. /*** Start of inlined file: juce_android_Misc.cpp ***/
  236501. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236502. // compiled on its own).
  236503. #if JUCE_INCLUDED_FILE
  236504. END_JUCE_NAMESPACE
  236505. extern JUCE_NAMESPACE::JUCEApplication* juce_CreateApplication(); // (from START_JUCE_APPLICATION)
  236506. BEGIN_JUCE_NAMESPACE
  236507. JUCE_JNI_CALLBACK (JuceAppActivity, launchApp, void, (JNIEnv* env, jobject activity))
  236508. {
  236509. android.initialise (env, activity);
  236510. JUCEApplication::createInstance = &juce_CreateApplication;
  236511. initialiseJuce_GUI();
  236512. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  236513. exit (0);
  236514. }
  236515. JUCE_JNI_CALLBACK (JuceAppActivity, quitApp, void, (JNIEnv* env, jobject activity))
  236516. {
  236517. JUCEApplication::appWillTerminateByForce();
  236518. android.shutdown();
  236519. }
  236520. void PlatformUtilities::beep()
  236521. {
  236522. // TODO
  236523. }
  236524. void Logger::outputDebugString (const String& text)
  236525. {
  236526. android.env->CallStaticVoidMethod (android.activityClass, android.printToConsole,
  236527. android.javaString (text));
  236528. }
  236529. void SystemClipboard::copyTextToClipboard (const String& text)
  236530. {
  236531. // TODO
  236532. }
  236533. const String SystemClipboard::getTextFromClipboard()
  236534. {
  236535. String result;
  236536. // TODO
  236537. return result;
  236538. }
  236539. #endif
  236540. /*** End of inlined file: juce_android_Misc.cpp ***/
  236541. /*** Start of inlined file: juce_android_SystemStats.cpp ***/
  236542. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  236543. // compiled on its own).
  236544. #if JUCE_INCLUDED_FILE
  236545. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  236546. {
  236547. return Android;
  236548. }
  236549. const String SystemStats::getOperatingSystemName()
  236550. {
  236551. return "Android";
  236552. }
  236553. bool SystemStats::isOperatingSystem64Bit()
  236554. {
  236555. #if JUCE_64BIT
  236556. return true;
  236557. #else
  236558. return false;
  236559. #endif
  236560. }
  236561. namespace AndroidStatsHelpers
  236562. {
  236563. // TODO
  236564. const String getCpuInfo (const char* const key)
  236565. {
  236566. StringArray lines;
  236567. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  236568. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  236569. if (lines[i].startsWithIgnoreCase (key))
  236570. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  236571. return String::empty;
  236572. }
  236573. }
  236574. const String SystemStats::getCpuVendor()
  236575. {
  236576. return AndroidStatsHelpers::getCpuInfo ("vendor_id");
  236577. }
  236578. int SystemStats::getCpuSpeedInMegaherz()
  236579. {
  236580. return roundToInt (AndroidStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  236581. }
  236582. int SystemStats::getMemorySizeInMegabytes()
  236583. {
  236584. // TODO
  236585. struct sysinfo sysi;
  236586. if (sysinfo (&sysi) == 0)
  236587. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  236588. return 0;
  236589. }
  236590. int SystemStats::getPageSize()
  236591. {
  236592. // TODO
  236593. return sysconf (_SC_PAGESIZE);
  236594. }
  236595. const String SystemStats::getLogonName()
  236596. {
  236597. // TODO
  236598. const char* user = getenv ("USER");
  236599. if (user == 0)
  236600. {
  236601. struct passwd* const pw = getpwuid (getuid());
  236602. if (pw != 0)
  236603. user = pw->pw_name;
  236604. }
  236605. return String::fromUTF8 (user);
  236606. }
  236607. const String SystemStats::getFullUserName()
  236608. {
  236609. return getLogonName();
  236610. }
  236611. void SystemStats::initialiseStats()
  236612. {
  236613. // TODO
  236614. const String flags (AndroidStatsHelpers::getCpuInfo ("flags"));
  236615. cpuFlags.hasMMX = flags.contains ("mmx");
  236616. cpuFlags.hasSSE = flags.contains ("sse");
  236617. cpuFlags.hasSSE2 = flags.contains ("sse2");
  236618. cpuFlags.has3DNow = flags.contains ("3dnow");
  236619. // TODO
  236620. cpuFlags.numCpus = AndroidStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  236621. }
  236622. void PlatformUtilities::fpuReset() {}
  236623. uint32 juce_millisecondsSinceStartup() throw()
  236624. {
  236625. // TODO
  236626. timespec t;
  236627. clock_gettime (CLOCK_MONOTONIC, &t);
  236628. return t.tv_sec * 1000 + t.tv_nsec / 1000000;
  236629. }
  236630. int64 Time::getHighResolutionTicks() throw()
  236631. {
  236632. // TODO
  236633. timespec t;
  236634. clock_gettime (CLOCK_MONOTONIC, &t);
  236635. return (t.tv_sec * (int64) 1000000) + (t.tv_nsec / (int64) 1000);
  236636. }
  236637. int64 Time::getHighResolutionTicksPerSecond() throw()
  236638. {
  236639. // TODO
  236640. return 1000000; // (microseconds)
  236641. }
  236642. double Time::getMillisecondCounterHiRes() throw()
  236643. {
  236644. return getHighResolutionTicks() * 0.001;
  236645. }
  236646. bool Time::setSystemTimeToThisTime() const
  236647. {
  236648. jassertfalse;
  236649. return false;
  236650. }
  236651. #endif
  236652. /*** End of inlined file: juce_android_SystemStats.cpp ***/
  236653. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  236654. /*
  236655. This file contains posix routines that are common to both the Linux and Mac builds.
  236656. It gets included directly in the cpp files for these platforms.
  236657. */
  236658. CriticalSection::CriticalSection() throw()
  236659. {
  236660. pthread_mutexattr_t atts;
  236661. pthread_mutexattr_init (&atts);
  236662. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  236663. #if ! JUCE_ANDROID
  236664. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236665. #endif
  236666. pthread_mutex_init (&internal, &atts);
  236667. }
  236668. CriticalSection::~CriticalSection() throw()
  236669. {
  236670. pthread_mutex_destroy (&internal);
  236671. }
  236672. void CriticalSection::enter() const throw()
  236673. {
  236674. pthread_mutex_lock (&internal);
  236675. }
  236676. bool CriticalSection::tryEnter() const throw()
  236677. {
  236678. return pthread_mutex_trylock (&internal) == 0;
  236679. }
  236680. void CriticalSection::exit() const throw()
  236681. {
  236682. pthread_mutex_unlock (&internal);
  236683. }
  236684. class WaitableEventImpl
  236685. {
  236686. public:
  236687. WaitableEventImpl (const bool manualReset_)
  236688. : triggered (false),
  236689. manualReset (manualReset_)
  236690. {
  236691. pthread_cond_init (&condition, 0);
  236692. pthread_mutexattr_t atts;
  236693. pthread_mutexattr_init (&atts);
  236694. #if ! JUCE_ANDROID
  236695. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  236696. #endif
  236697. pthread_mutex_init (&mutex, &atts);
  236698. }
  236699. ~WaitableEventImpl()
  236700. {
  236701. pthread_cond_destroy (&condition);
  236702. pthread_mutex_destroy (&mutex);
  236703. }
  236704. bool wait (const int timeOutMillisecs) throw()
  236705. {
  236706. pthread_mutex_lock (&mutex);
  236707. if (! triggered)
  236708. {
  236709. if (timeOutMillisecs < 0)
  236710. {
  236711. do
  236712. {
  236713. pthread_cond_wait (&condition, &mutex);
  236714. }
  236715. while (! triggered);
  236716. }
  236717. else
  236718. {
  236719. struct timeval now;
  236720. gettimeofday (&now, 0);
  236721. struct timespec time;
  236722. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  236723. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  236724. if (time.tv_nsec >= 1000000000)
  236725. {
  236726. time.tv_nsec -= 1000000000;
  236727. time.tv_sec++;
  236728. }
  236729. do
  236730. {
  236731. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  236732. {
  236733. pthread_mutex_unlock (&mutex);
  236734. return false;
  236735. }
  236736. }
  236737. while (! triggered);
  236738. }
  236739. }
  236740. if (! manualReset)
  236741. triggered = false;
  236742. pthread_mutex_unlock (&mutex);
  236743. return true;
  236744. }
  236745. void signal() throw()
  236746. {
  236747. pthread_mutex_lock (&mutex);
  236748. triggered = true;
  236749. pthread_cond_broadcast (&condition);
  236750. pthread_mutex_unlock (&mutex);
  236751. }
  236752. void reset() throw()
  236753. {
  236754. pthread_mutex_lock (&mutex);
  236755. triggered = false;
  236756. pthread_mutex_unlock (&mutex);
  236757. }
  236758. private:
  236759. pthread_cond_t condition;
  236760. pthread_mutex_t mutex;
  236761. bool triggered;
  236762. const bool manualReset;
  236763. JUCE_DECLARE_NON_COPYABLE (WaitableEventImpl);
  236764. };
  236765. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  236766. : internal (new WaitableEventImpl (manualReset))
  236767. {
  236768. }
  236769. WaitableEvent::~WaitableEvent() throw()
  236770. {
  236771. delete static_cast <WaitableEventImpl*> (internal);
  236772. }
  236773. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  236774. {
  236775. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  236776. }
  236777. void WaitableEvent::signal() const throw()
  236778. {
  236779. static_cast <WaitableEventImpl*> (internal)->signal();
  236780. }
  236781. void WaitableEvent::reset() const throw()
  236782. {
  236783. static_cast <WaitableEventImpl*> (internal)->reset();
  236784. }
  236785. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  236786. {
  236787. struct timespec time;
  236788. time.tv_sec = millisecs / 1000;
  236789. time.tv_nsec = (millisecs % 1000) * 1000000;
  236790. nanosleep (&time, 0);
  236791. }
  236792. const juce_wchar File::separator = '/';
  236793. const String File::separatorString ("/");
  236794. const File File::getCurrentWorkingDirectory()
  236795. {
  236796. HeapBlock<char> heapBuffer;
  236797. char localBuffer [1024];
  236798. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  236799. int bufferSize = 4096;
  236800. while (cwd == 0 && errno == ERANGE)
  236801. {
  236802. heapBuffer.malloc (bufferSize);
  236803. cwd = getcwd (heapBuffer, bufferSize - 1);
  236804. bufferSize += 1024;
  236805. }
  236806. return File (String::fromUTF8 (cwd));
  236807. }
  236808. bool File::setAsCurrentWorkingDirectory() const
  236809. {
  236810. return chdir (getFullPathName().toUTF8()) == 0;
  236811. }
  236812. namespace
  236813. {
  236814. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236815. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  236816. #else
  236817. typedef struct stat juce_statStruct;
  236818. #endif
  236819. bool juce_stat (const String& fileName, juce_statStruct& info)
  236820. {
  236821. return fileName.isNotEmpty()
  236822. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236823. && (stat64 (fileName.toUTF8(), &info) == 0);
  236824. #else
  236825. && (stat (fileName.toUTF8(), &info) == 0);
  236826. #endif
  236827. }
  236828. // if this file doesn't exist, find a parent of it that does..
  236829. bool juce_doStatFS (File f, struct statfs& result)
  236830. {
  236831. for (int i = 5; --i >= 0;)
  236832. {
  236833. if (f.exists())
  236834. break;
  236835. f = f.getParentDirectory();
  236836. }
  236837. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  236838. }
  236839. void updateStatInfoForFile (const String& path, bool* const isDir, int64* const fileSize,
  236840. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  236841. {
  236842. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  236843. {
  236844. juce_statStruct info;
  236845. const bool statOk = juce_stat (path, info);
  236846. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  236847. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  236848. if (modTime != 0) *modTime = Time (statOk ? (int64) info.st_mtime * 1000 : 0);
  236849. if (creationTime != 0) *creationTime = Time (statOk ? (int64) info.st_ctime * 1000 : 0);
  236850. }
  236851. if (isReadOnly != 0)
  236852. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  236853. }
  236854. }
  236855. bool File::isDirectory() const
  236856. {
  236857. juce_statStruct info;
  236858. return fullPath.isEmpty()
  236859. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  236860. }
  236861. bool File::exists() const
  236862. {
  236863. juce_statStruct info;
  236864. return fullPath.isNotEmpty()
  236865. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  236866. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  236867. #else
  236868. && (lstat (fullPath.toUTF8(), &info) == 0);
  236869. #endif
  236870. }
  236871. bool File::existsAsFile() const
  236872. {
  236873. return exists() && ! isDirectory();
  236874. }
  236875. int64 File::getSize() const
  236876. {
  236877. juce_statStruct info;
  236878. return juce_stat (fullPath, info) ? info.st_size : 0;
  236879. }
  236880. bool File::hasWriteAccess() const
  236881. {
  236882. if (exists())
  236883. return access (fullPath.toUTF8(), W_OK) == 0;
  236884. if ((! isDirectory()) && fullPath.containsChar (separator))
  236885. return getParentDirectory().hasWriteAccess();
  236886. return false;
  236887. }
  236888. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  236889. {
  236890. juce_statStruct info;
  236891. if (! juce_stat (fullPath, info))
  236892. return false;
  236893. info.st_mode &= 0777; // Just permissions
  236894. if (shouldBeReadOnly)
  236895. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  236896. else
  236897. // Give everybody write permission?
  236898. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  236899. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  236900. }
  236901. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  236902. {
  236903. modificationTime = 0;
  236904. accessTime = 0;
  236905. creationTime = 0;
  236906. juce_statStruct info;
  236907. if (juce_stat (fullPath, info))
  236908. {
  236909. modificationTime = (int64) info.st_mtime * 1000;
  236910. accessTime = (int64) info.st_atime * 1000;
  236911. creationTime = (int64) info.st_ctime * 1000;
  236912. }
  236913. }
  236914. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  236915. {
  236916. juce_statStruct info;
  236917. if ((modificationTime != 0 || accessTime != 0) && juce_stat (fullPath, info))
  236918. {
  236919. struct utimbuf times;
  236920. times.actime = accessTime != 0 ? (time_t) (accessTime / 1000) : info.st_atime;
  236921. times.modtime = modificationTime != 0 ? (time_t) (modificationTime / 1000) : info.st_mtime;
  236922. return utime (fullPath.toUTF8(), &times) == 0;
  236923. }
  236924. return false;
  236925. }
  236926. bool File::deleteFile() const
  236927. {
  236928. if (! exists())
  236929. return true;
  236930. if (isDirectory())
  236931. return rmdir (fullPath.toUTF8()) == 0;
  236932. return remove (fullPath.toUTF8()) == 0;
  236933. }
  236934. bool File::moveInternal (const File& dest) const
  236935. {
  236936. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  236937. return true;
  236938. if (hasWriteAccess() && copyInternal (dest))
  236939. {
  236940. if (deleteFile())
  236941. return true;
  236942. dest.deleteFile();
  236943. }
  236944. return false;
  236945. }
  236946. void File::createDirectoryInternal (const String& fileName) const
  236947. {
  236948. mkdir (fileName.toUTF8(), 0777);
  236949. }
  236950. int64 juce_fileSetPosition (void* handle, int64 pos)
  236951. {
  236952. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  236953. return pos;
  236954. return -1;
  236955. }
  236956. void FileInputStream::openHandle()
  236957. {
  236958. totalSize = file.getSize();
  236959. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  236960. if (f != -1)
  236961. fileHandle = (void*) f;
  236962. }
  236963. void FileInputStream::closeHandle()
  236964. {
  236965. if (fileHandle != 0)
  236966. {
  236967. close ((int) (pointer_sized_int) fileHandle);
  236968. fileHandle = 0;
  236969. }
  236970. }
  236971. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  236972. {
  236973. if (fileHandle != 0)
  236974. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  236975. return 0;
  236976. }
  236977. void FileOutputStream::openHandle()
  236978. {
  236979. if (file.exists())
  236980. {
  236981. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  236982. if (f != -1)
  236983. {
  236984. currentPosition = lseek (f, 0, SEEK_END);
  236985. if (currentPosition >= 0)
  236986. fileHandle = (void*) f;
  236987. else
  236988. close (f);
  236989. }
  236990. }
  236991. else
  236992. {
  236993. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  236994. if (f != -1)
  236995. fileHandle = (void*) f;
  236996. }
  236997. }
  236998. void FileOutputStream::closeHandle()
  236999. {
  237000. if (fileHandle != 0)
  237001. {
  237002. close ((int) (pointer_sized_int) fileHandle);
  237003. fileHandle = 0;
  237004. }
  237005. }
  237006. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  237007. {
  237008. if (fileHandle != 0)
  237009. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  237010. return 0;
  237011. }
  237012. void FileOutputStream::flushInternal()
  237013. {
  237014. if (fileHandle != 0)
  237015. fsync ((int) (pointer_sized_int) fileHandle);
  237016. }
  237017. const File juce_getExecutableFile()
  237018. {
  237019. #if JUCE_ANDROID
  237020. // TODO
  237021. return File::nonexistent;
  237022. #else
  237023. Dl_info exeInfo;
  237024. dladdr ((void*) juce_getExecutableFile, &exeInfo); // (can't be a const void* on android)
  237025. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  237026. #endif
  237027. }
  237028. int64 File::getBytesFreeOnVolume() const
  237029. {
  237030. struct statfs buf;
  237031. if (juce_doStatFS (*this, buf))
  237032. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  237033. return 0;
  237034. }
  237035. int64 File::getVolumeTotalSize() const
  237036. {
  237037. struct statfs buf;
  237038. if (juce_doStatFS (*this, buf))
  237039. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  237040. return 0;
  237041. }
  237042. const String File::getVolumeLabel() const
  237043. {
  237044. #if JUCE_MAC
  237045. struct VolAttrBuf
  237046. {
  237047. u_int32_t length;
  237048. attrreference_t mountPointRef;
  237049. char mountPointSpace [MAXPATHLEN];
  237050. } attrBuf;
  237051. struct attrlist attrList;
  237052. zerostruct (attrList);
  237053. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  237054. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  237055. File f (*this);
  237056. for (;;)
  237057. {
  237058. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  237059. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  237060. (int) attrBuf.mountPointRef.attr_length);
  237061. const File parent (f.getParentDirectory());
  237062. if (f == parent)
  237063. break;
  237064. f = parent;
  237065. }
  237066. #endif
  237067. return String::empty;
  237068. }
  237069. int File::getVolumeSerialNumber() const
  237070. {
  237071. int result = 0;
  237072. /* int fd = open (getFullPathName().toUTF8(), O_RDONLY | O_NONBLOCK);
  237073. char info [512];
  237074. #ifndef HDIO_GET_IDENTITY
  237075. #define HDIO_GET_IDENTITY 0x030d
  237076. #endif
  237077. if (ioctl (fd, HDIO_GET_IDENTITY, info) == 0)
  237078. {
  237079. DBG (String (info + 20, 20));
  237080. result = String (info + 20, 20).trim().getIntValue();
  237081. }
  237082. close (fd);*/
  237083. return result;
  237084. }
  237085. void juce_runSystemCommand (const String& command)
  237086. {
  237087. int result = system (command.toUTF8());
  237088. (void) result;
  237089. }
  237090. const String juce_getOutputFromCommand (const String& command)
  237091. {
  237092. // slight bodge here, as we just pipe the output into a temp file and read it...
  237093. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  237094. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  237095. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  237096. String result (tempFile.loadFileAsString());
  237097. tempFile.deleteFile();
  237098. return result;
  237099. }
  237100. class InterProcessLock::Pimpl
  237101. {
  237102. public:
  237103. Pimpl (const String& name, const int timeOutMillisecs)
  237104. : handle (0), refCount (1)
  237105. {
  237106. #if JUCE_MAC
  237107. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  237108. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  237109. #else
  237110. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  237111. #endif
  237112. temp.create();
  237113. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  237114. if (handle != 0)
  237115. {
  237116. struct flock fl;
  237117. zerostruct (fl);
  237118. fl.l_whence = SEEK_SET;
  237119. fl.l_type = F_WRLCK;
  237120. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  237121. for (;;)
  237122. {
  237123. const int result = fcntl (handle, F_SETLK, &fl);
  237124. if (result >= 0)
  237125. return;
  237126. if (errno != EINTR)
  237127. {
  237128. if (timeOutMillisecs == 0
  237129. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  237130. break;
  237131. Thread::sleep (10);
  237132. }
  237133. }
  237134. }
  237135. closeFile();
  237136. }
  237137. ~Pimpl()
  237138. {
  237139. closeFile();
  237140. }
  237141. void closeFile()
  237142. {
  237143. if (handle != 0)
  237144. {
  237145. struct flock fl;
  237146. zerostruct (fl);
  237147. fl.l_whence = SEEK_SET;
  237148. fl.l_type = F_UNLCK;
  237149. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  237150. {}
  237151. close (handle);
  237152. handle = 0;
  237153. }
  237154. }
  237155. int handle, refCount;
  237156. };
  237157. InterProcessLock::InterProcessLock (const String& name_)
  237158. : name (name_)
  237159. {
  237160. }
  237161. InterProcessLock::~InterProcessLock()
  237162. {
  237163. }
  237164. bool InterProcessLock::enter (const int timeOutMillisecs)
  237165. {
  237166. const ScopedLock sl (lock);
  237167. if (pimpl == 0)
  237168. {
  237169. pimpl = new Pimpl (name, timeOutMillisecs);
  237170. if (pimpl->handle == 0)
  237171. pimpl = 0;
  237172. }
  237173. else
  237174. {
  237175. pimpl->refCount++;
  237176. }
  237177. return pimpl != 0;
  237178. }
  237179. void InterProcessLock::exit()
  237180. {
  237181. const ScopedLock sl (lock);
  237182. // Trying to release the lock too many times!
  237183. jassert (pimpl != 0);
  237184. if (pimpl != 0 && --(pimpl->refCount) == 0)
  237185. pimpl = 0;
  237186. }
  237187. void JUCE_API juce_threadEntryPoint (void*);
  237188. void* threadEntryProc (void* userData)
  237189. {
  237190. JUCE_AUTORELEASEPOOL
  237191. juce_threadEntryPoint (userData);
  237192. return 0;
  237193. }
  237194. void Thread::launchThread()
  237195. {
  237196. threadHandle_ = 0;
  237197. pthread_t handle = 0;
  237198. if (pthread_create (&handle, 0, threadEntryProc, this) == 0)
  237199. {
  237200. pthread_detach (handle);
  237201. threadHandle_ = (void*) handle;
  237202. threadId_ = (ThreadID) threadHandle_;
  237203. }
  237204. }
  237205. void Thread::closeThreadHandle()
  237206. {
  237207. threadId_ = 0;
  237208. threadHandle_ = 0;
  237209. }
  237210. void Thread::killThread()
  237211. {
  237212. if (threadHandle_ != 0)
  237213. {
  237214. #if JUCE_ANDROID
  237215. jassertfalse; // pthread_cancel not available!
  237216. #else
  237217. pthread_cancel ((pthread_t) threadHandle_);
  237218. #endif
  237219. }
  237220. }
  237221. void Thread::setCurrentThreadName (const String& /*name*/)
  237222. {
  237223. }
  237224. bool Thread::setThreadPriority (void* handle, int priority)
  237225. {
  237226. struct sched_param param;
  237227. int policy;
  237228. priority = jlimit (0, 10, priority);
  237229. if (handle == 0)
  237230. handle = (void*) pthread_self();
  237231. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  237232. return false;
  237233. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  237234. const int minPriority = sched_get_priority_min (policy);
  237235. const int maxPriority = sched_get_priority_max (policy);
  237236. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  237237. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  237238. }
  237239. Thread::ThreadID Thread::getCurrentThreadId()
  237240. {
  237241. return (ThreadID) pthread_self();
  237242. }
  237243. void Thread::yield()
  237244. {
  237245. sched_yield();
  237246. }
  237247. /* Remove this macro if you're having problems compiling the cpu affinity
  237248. calls (the API for these has changed about quite a bit in various Linux
  237249. versions, and a lot of distros seem to ship with obsolete versions)
  237250. */
  237251. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  237252. #define SUPPORT_AFFINITIES 1
  237253. #endif
  237254. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  237255. {
  237256. #if SUPPORT_AFFINITIES
  237257. cpu_set_t affinity;
  237258. CPU_ZERO (&affinity);
  237259. for (int i = 0; i < 32; ++i)
  237260. if ((affinityMask & (1 << i)) != 0)
  237261. CPU_SET (i, &affinity);
  237262. /*
  237263. N.B. If this line causes a compile error, then you've probably not got the latest
  237264. version of glibc installed.
  237265. If you don't want to update your copy of glibc and don't care about cpu affinities,
  237266. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  237267. */
  237268. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  237269. sched_yield();
  237270. #else
  237271. /* affinities aren't supported because either the appropriate header files weren't found,
  237272. or the SUPPORT_AFFINITIES macro was turned off
  237273. */
  237274. jassertfalse;
  237275. (void) affinityMask;
  237276. #endif
  237277. }
  237278. /*** End of inlined file: juce_posix_SharedCode.h ***/
  237279. /*** Start of inlined file: juce_android_Files.cpp ***/
  237280. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237281. // compiled on its own).
  237282. #if JUCE_INCLUDED_FILE
  237283. bool File::copyInternal (const File& dest) const
  237284. {
  237285. // TODO
  237286. FileInputStream in (*this);
  237287. if (dest.deleteFile())
  237288. {
  237289. {
  237290. FileOutputStream out (dest);
  237291. if (out.failedToOpen())
  237292. return false;
  237293. if (out.writeFromInputStream (in, -1) == getSize())
  237294. return true;
  237295. }
  237296. dest.deleteFile();
  237297. }
  237298. return false;
  237299. }
  237300. void File::findFileSystemRoots (Array<File>& destArray)
  237301. {
  237302. // TODO
  237303. destArray.add (File ("/"));
  237304. }
  237305. bool File::isOnCDRomDrive() const
  237306. {
  237307. return false;
  237308. }
  237309. bool File::isOnHardDisk() const
  237310. {
  237311. return true;
  237312. }
  237313. bool File::isOnRemovableDrive() const
  237314. {
  237315. return false;
  237316. }
  237317. bool File::isHidden() const
  237318. {
  237319. // TODO
  237320. return getFileName().startsWithChar ('.');
  237321. }
  237322. namespace
  237323. {
  237324. const File juce_readlink (const String& file, const File& defaultFile)
  237325. {
  237326. const int size = 8192;
  237327. HeapBlock<char> buffer;
  237328. buffer.malloc (size + 4);
  237329. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  237330. if (numBytes > 0 && numBytes <= size)
  237331. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  237332. return defaultFile;
  237333. }
  237334. }
  237335. const File File::getLinkedTarget() const
  237336. {
  237337. // TODO
  237338. return juce_readlink (getFullPathName().toUTF8(), *this);
  237339. }
  237340. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  237341. const File File::getSpecialLocation (const SpecialLocationType type)
  237342. {
  237343. // TODO
  237344. switch (type)
  237345. {
  237346. case userHomeDirectory:
  237347. {
  237348. const char* homeDir = getenv ("HOME");
  237349. if (homeDir == 0)
  237350. {
  237351. struct passwd* const pw = getpwuid (getuid());
  237352. if (pw != 0)
  237353. homeDir = pw->pw_dir;
  237354. }
  237355. return File (String::fromUTF8 (homeDir));
  237356. }
  237357. case userDocumentsDirectory:
  237358. case userMusicDirectory:
  237359. case userMoviesDirectory:
  237360. case userApplicationDataDirectory:
  237361. return File ("~");
  237362. case userDesktopDirectory:
  237363. return File ("~/Desktop");
  237364. case commonApplicationDataDirectory:
  237365. return File ("/var");
  237366. case globalApplicationsDirectory:
  237367. return File ("/usr");
  237368. case tempDirectory:
  237369. {
  237370. File tmp ("/var/tmp");
  237371. if (! tmp.isDirectory())
  237372. {
  237373. tmp = "/tmp";
  237374. if (! tmp.isDirectory())
  237375. tmp = File::getCurrentWorkingDirectory();
  237376. }
  237377. return tmp;
  237378. }
  237379. case invokedExecutableFile:
  237380. if (juce_Argv0 != 0)
  237381. return File (String::fromUTF8 (juce_Argv0));
  237382. // deliberate fall-through...
  237383. case currentExecutableFile:
  237384. case currentApplicationFile:
  237385. return juce_getExecutableFile();
  237386. case hostApplicationPath:
  237387. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  237388. default:
  237389. jassertfalse; // unknown type?
  237390. break;
  237391. }
  237392. return File::nonexistent;
  237393. }
  237394. const String File::getVersion() const
  237395. {
  237396. return String::empty;
  237397. }
  237398. bool File::moveToTrash() const
  237399. {
  237400. if (! exists())
  237401. return true;
  237402. // TODO
  237403. return false;
  237404. }
  237405. class DirectoryIterator::NativeIterator::Pimpl
  237406. {
  237407. public:
  237408. Pimpl (const File& directory, const String& wildCard_)
  237409. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  237410. wildCard (wildCard_),
  237411. dir (opendir (directory.getFullPathName().toUTF8()))
  237412. {
  237413. wildcardUTF8 = wildCard.toUTF8();
  237414. }
  237415. ~Pimpl()
  237416. {
  237417. if (dir != 0)
  237418. closedir (dir);
  237419. }
  237420. bool next (String& filenameFound,
  237421. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237422. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237423. {
  237424. if (dir != 0)
  237425. {
  237426. for (;;)
  237427. {
  237428. struct dirent* const de = readdir (dir);
  237429. if (de == 0)
  237430. break;
  237431. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  237432. {
  237433. filenameFound = String::fromUTF8 (de->d_name);
  237434. updateStatInfoForFile (parentDir + filenameFound, isDir, fileSize, modTime, creationTime, isReadOnly);
  237435. if (isHidden != 0)
  237436. *isHidden = filenameFound.startsWithChar ('.');
  237437. return true;
  237438. }
  237439. }
  237440. }
  237441. return false;
  237442. }
  237443. private:
  237444. String parentDir, wildCard;
  237445. const char* wildcardUTF8;
  237446. DIR* dir;
  237447. JUCE_DECLARE_NON_COPYABLE (Pimpl);
  237448. };
  237449. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  237450. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  237451. {
  237452. }
  237453. DirectoryIterator::NativeIterator::~NativeIterator()
  237454. {
  237455. }
  237456. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  237457. bool* const isDir, bool* const isHidden, int64* const fileSize,
  237458. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  237459. {
  237460. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  237461. }
  237462. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  237463. {
  237464. }
  237465. void File::revealToUser() const
  237466. {
  237467. }
  237468. #endif
  237469. /*** End of inlined file: juce_android_Files.cpp ***/
  237470. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  237471. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237472. // compiled on its own).
  237473. #if JUCE_INCLUDED_FILE
  237474. struct NamedPipeInternal
  237475. {
  237476. String pipeInName, pipeOutName;
  237477. int pipeIn, pipeOut;
  237478. bool volatile createdPipe, blocked, stopReadOperation;
  237479. static void signalHandler (int) {}
  237480. };
  237481. void NamedPipe::cancelPendingReads()
  237482. {
  237483. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  237484. {
  237485. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237486. intern->stopReadOperation = true;
  237487. char buffer [1] = { 0 };
  237488. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  237489. (void) bytesWritten;
  237490. int timeout = 2000;
  237491. while (intern->blocked && --timeout >= 0)
  237492. Thread::sleep (2);
  237493. intern->stopReadOperation = false;
  237494. }
  237495. }
  237496. void NamedPipe::close()
  237497. {
  237498. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237499. if (intern != 0)
  237500. {
  237501. internal = 0;
  237502. if (intern->pipeIn != -1)
  237503. ::close (intern->pipeIn);
  237504. if (intern->pipeOut != -1)
  237505. ::close (intern->pipeOut);
  237506. if (intern->createdPipe)
  237507. {
  237508. unlink (intern->pipeInName.toUTF8());
  237509. unlink (intern->pipeOutName.toUTF8());
  237510. }
  237511. delete intern;
  237512. }
  237513. }
  237514. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  237515. {
  237516. close();
  237517. NamedPipeInternal* const intern = new NamedPipeInternal();
  237518. internal = intern;
  237519. intern->createdPipe = createPipe;
  237520. intern->blocked = false;
  237521. intern->stopReadOperation = false;
  237522. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  237523. siginterrupt (SIGPIPE, 1);
  237524. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  237525. intern->pipeInName = pipePath + "_in";
  237526. intern->pipeOutName = pipePath + "_out";
  237527. intern->pipeIn = -1;
  237528. intern->pipeOut = -1;
  237529. if (createPipe)
  237530. {
  237531. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  237532. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  237533. {
  237534. delete intern;
  237535. internal = 0;
  237536. return false;
  237537. }
  237538. }
  237539. return true;
  237540. }
  237541. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  237542. {
  237543. int bytesRead = -1;
  237544. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237545. if (intern != 0)
  237546. {
  237547. intern->blocked = true;
  237548. if (intern->pipeIn == -1)
  237549. {
  237550. if (intern->createdPipe)
  237551. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  237552. else
  237553. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  237554. if (intern->pipeIn == -1)
  237555. {
  237556. intern->blocked = false;
  237557. return -1;
  237558. }
  237559. }
  237560. bytesRead = 0;
  237561. char* p = static_cast<char*> (destBuffer);
  237562. while (bytesRead < maxBytesToRead)
  237563. {
  237564. const int bytesThisTime = maxBytesToRead - bytesRead;
  237565. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  237566. if (numRead <= 0 || intern->stopReadOperation)
  237567. {
  237568. bytesRead = -1;
  237569. break;
  237570. }
  237571. bytesRead += numRead;
  237572. p += bytesRead;
  237573. }
  237574. intern->blocked = false;
  237575. }
  237576. return bytesRead;
  237577. }
  237578. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  237579. {
  237580. int bytesWritten = -1;
  237581. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  237582. if (intern != 0)
  237583. {
  237584. if (intern->pipeOut == -1)
  237585. {
  237586. if (intern->createdPipe)
  237587. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  237588. else
  237589. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  237590. if (intern->pipeOut == -1)
  237591. {
  237592. return -1;
  237593. }
  237594. }
  237595. const char* p = static_cast<const char*> (sourceBuffer);
  237596. bytesWritten = 0;
  237597. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  237598. while (bytesWritten < numBytesToWrite
  237599. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  237600. {
  237601. const int bytesThisTime = numBytesToWrite - bytesWritten;
  237602. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  237603. if (numWritten <= 0)
  237604. {
  237605. bytesWritten = -1;
  237606. break;
  237607. }
  237608. bytesWritten += numWritten;
  237609. p += bytesWritten;
  237610. }
  237611. }
  237612. return bytesWritten;
  237613. }
  237614. #endif
  237615. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  237616. /*** Start of inlined file: juce_android_Threads.cpp ***/
  237617. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237618. // compiled on its own).
  237619. #if JUCE_INCLUDED_FILE
  237620. /*
  237621. Note that a lot of methods that you'd expect to find in this file actually
  237622. live in juce_posix_SharedCode.h!
  237623. */
  237624. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  237625. void Process::setPriority (ProcessPriority prior)
  237626. {
  237627. // TODO
  237628. struct sched_param param;
  237629. int policy, maxp, minp;
  237630. const int p = (int) prior;
  237631. if (p <= 1)
  237632. policy = SCHED_OTHER;
  237633. else
  237634. policy = SCHED_RR;
  237635. minp = sched_get_priority_min (policy);
  237636. maxp = sched_get_priority_max (policy);
  237637. if (p < 2)
  237638. param.sched_priority = 0;
  237639. else if (p == 2 )
  237640. // Set to middle of lower realtime priority range
  237641. param.sched_priority = minp + (maxp - minp) / 4;
  237642. else
  237643. // Set to middle of higher realtime priority range
  237644. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  237645. pthread_setschedparam (pthread_self(), policy, &param);
  237646. }
  237647. void Process::terminate()
  237648. {
  237649. // TODO
  237650. exit (0);
  237651. }
  237652. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  237653. {
  237654. return false;
  237655. }
  237656. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  237657. {
  237658. return juce_isRunningUnderDebugger();
  237659. }
  237660. void Process::raisePrivilege() {}
  237661. void Process::lowerPrivilege() {}
  237662. #endif
  237663. /*** End of inlined file: juce_android_Threads.cpp ***/
  237664. /*** Start of inlined file: juce_android_Network.cpp ***/
  237665. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237666. // compiled on its own).
  237667. #if JUCE_INCLUDED_FILE
  237668. void MACAddress::findAllAddresses (Array<MACAddress>& result)
  237669. {
  237670. // TODO
  237671. }
  237672. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  237673. const String& emailSubject,
  237674. const String& bodyText,
  237675. const StringArray& filesToAttach)
  237676. {
  237677. // TODO
  237678. return false;
  237679. }
  237680. class WebInputStream : public InputStream
  237681. {
  237682. public:
  237683. WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
  237684. URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237685. const String& headers_, int timeOutMs_, StringPairArray* responseHeaders)
  237686. {
  237687. // TODO
  237688. openedOk = false;
  237689. }
  237690. ~WebInputStream()
  237691. {
  237692. }
  237693. bool isExhausted()
  237694. {
  237695. return true; // TODO
  237696. }
  237697. int64 getPosition()
  237698. {
  237699. return 0; // TODO
  237700. }
  237701. int64 getTotalLength()
  237702. {
  237703. return -1; // TODO
  237704. }
  237705. int read (void* buffer, int bytesToRead)
  237706. {
  237707. // TODO
  237708. return 0;
  237709. }
  237710. bool setPosition (int64 wantedPos)
  237711. {
  237712. // TODO
  237713. return false;
  237714. }
  237715. bool openedOk;
  237716. private:
  237717. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WebInputStream);
  237718. };
  237719. InputStream* URL::createNativeStream (const String& address, bool isPost, const MemoryBlock& postData,
  237720. OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
  237721. const String& headers, const int timeOutMs, StringPairArray* responseHeaders)
  237722. {
  237723. ScopedPointer <WebInputStream> wi (new WebInputStream (address, isPost, postData,
  237724. progressCallback, progressCallbackContext,
  237725. headers, timeOutMs, responseHeaders));
  237726. return wi->openedOk ? wi.release() : 0;
  237727. }
  237728. #endif
  237729. /*** End of inlined file: juce_android_Network.cpp ***/
  237730. /*** Start of inlined file: juce_android_Messaging.cpp ***/
  237731. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237732. // compiled on its own).
  237733. #if JUCE_INCLUDED_FILE
  237734. void MessageManager::doPlatformSpecificInitialisation()
  237735. {
  237736. }
  237737. void MessageManager::doPlatformSpecificShutdown()
  237738. {
  237739. }
  237740. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  237741. {
  237742. // TODO
  237743. /*
  237744. The idea here is that this will check the system message queue, pull off a
  237745. message if there is one, deliver it, and return true if a message was delivered.
  237746. If the queue's empty, return false.
  237747. If the message is one of our special ones (i.e. a Message object being delivered,
  237748. this must call MessageManager::getInstance()->deliverMessage() to deliver it
  237749. */
  237750. return true;
  237751. }
  237752. bool juce_postMessageToSystemQueue (Message* message)
  237753. {
  237754. // TODO
  237755. return true;
  237756. }
  237757. class AsyncFunctionCaller : public AsyncUpdater
  237758. {
  237759. public:
  237760. static void* call (MessageCallbackFunction* func_, void* parameter_)
  237761. {
  237762. if (MessageManager::getInstance()->isThisTheMessageThread())
  237763. return func_ (parameter_);
  237764. AsyncFunctionCaller caller (func_, parameter_);
  237765. caller.triggerAsyncUpdate();
  237766. caller.finished.wait();
  237767. return caller.result;
  237768. }
  237769. void handleAsyncUpdate()
  237770. {
  237771. result = (*func) (parameter);
  237772. finished.signal();
  237773. }
  237774. private:
  237775. WaitableEvent finished;
  237776. MessageCallbackFunction* func;
  237777. void* parameter;
  237778. void* volatile result;
  237779. AsyncFunctionCaller (MessageCallbackFunction* func_, void* parameter_)
  237780. : result (0), func (func_), parameter (parameter_)
  237781. {}
  237782. JUCE_DECLARE_NON_COPYABLE (AsyncFunctionCaller);
  237783. };
  237784. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  237785. {
  237786. return AsyncFunctionCaller::call (func, parameter);
  237787. }
  237788. void MessageManager::broadcastMessage (const String&)
  237789. {
  237790. }
  237791. #endif
  237792. /*** End of inlined file: juce_android_Messaging.cpp ***/
  237793. /*** Start of inlined file: juce_android_Fonts.cpp ***/
  237794. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237795. // compiled on its own).
  237796. #if JUCE_INCLUDED_FILE
  237797. const StringArray Font::findAllTypefaceNames()
  237798. {
  237799. StringArray results;
  237800. // TODO
  237801. return results;
  237802. }
  237803. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed, String& defaultFallback)
  237804. {
  237805. // TODO
  237806. defaultSans = "Verdana";
  237807. defaultSerif = "Times";
  237808. defaultFixed = "Lucida Console";
  237809. defaultFallback = "Tahoma";
  237810. }
  237811. class AndroidTypeface : public Typeface
  237812. {
  237813. public:
  237814. AndroidTypeface (const Font& font)
  237815. : Typeface (font.getTypefaceName())
  237816. {
  237817. // TODO
  237818. }
  237819. float getAscent() const
  237820. {
  237821. return 0; // TODO
  237822. }
  237823. float getDescent() const
  237824. {
  237825. return 0; // TODO
  237826. }
  237827. float getStringWidth (const String& text)
  237828. {
  237829. // TODO
  237830. return 0;
  237831. }
  237832. void getGlyphPositions (const String& text, Array<int>& glyphs, Array<float>& xOffsets)
  237833. {
  237834. // TODO
  237835. }
  237836. bool getOutlineForGlyph (int glyphNumber, Path& destPath)
  237837. {
  237838. // TODO
  237839. return false;
  237840. }
  237841. private:
  237842. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidTypeface);
  237843. };
  237844. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  237845. {
  237846. return new AndroidTypeface (font);
  237847. }
  237848. #endif
  237849. /*** End of inlined file: juce_android_Fonts.cpp ***/
  237850. /*** Start of inlined file: juce_android_GraphicsContext.cpp ***/
  237851. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  237852. // compiled on its own).
  237853. #if JUCE_INCLUDED_FILE
  237854. // TODO
  237855. class AndroidLowLevelGraphicsContext : public LowLevelGraphicsContext
  237856. {
  237857. public:
  237858. AndroidLowLevelGraphicsContext (const GlobalRef& canvas_)
  237859. : canvas (canvas_)
  237860. {
  237861. }
  237862. ~AndroidLowLevelGraphicsContext()
  237863. {
  237864. }
  237865. bool isVectorDevice() const { return false; }
  237866. void setOrigin (int x, int y)
  237867. {
  237868. }
  237869. void addTransform (const AffineTransform& transform)
  237870. {
  237871. }
  237872. float getScaleFactor()
  237873. {
  237874. return 1.0f;
  237875. }
  237876. bool clipToRectangle (const Rectangle<int>& r)
  237877. {
  237878. return true;
  237879. }
  237880. bool clipToRectangleList (const RectangleList& clipRegion)
  237881. {
  237882. return true;
  237883. }
  237884. void excludeClipRectangle (const Rectangle<int>& r)
  237885. {
  237886. }
  237887. void clipToPath (const Path& path, const AffineTransform& transform)
  237888. {
  237889. }
  237890. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  237891. {
  237892. }
  237893. bool clipRegionIntersects (const Rectangle<int>& r)
  237894. {
  237895. return true;
  237896. }
  237897. const Rectangle<int> getClipBounds() const
  237898. {
  237899. return Rectangle<int> (0, 0, 1000, 1000);
  237900. }
  237901. bool isClipEmpty() const
  237902. {
  237903. return false;
  237904. }
  237905. void saveState()
  237906. {
  237907. }
  237908. void restoreState()
  237909. {
  237910. }
  237911. void beginTransparencyLayer (float opacity)
  237912. {
  237913. }
  237914. void endTransparencyLayer()
  237915. {
  237916. }
  237917. void setFill (const FillType& fillType)
  237918. {
  237919. currentPaint = android.env->NewObject (android.paintClass, android.paintClassConstructor);
  237920. currentPaint.callVoidMethod (android.setColor, fillType.colour.getARGB());
  237921. }
  237922. void setOpacity (float newOpacity)
  237923. {
  237924. }
  237925. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  237926. {
  237927. }
  237928. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  237929. {
  237930. canvas.callVoidMethod (android.drawRect,
  237931. (float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom(),
  237932. currentPaint.get());
  237933. }
  237934. void fillPath (const Path& path, const AffineTransform& transform)
  237935. {
  237936. }
  237937. void drawImage (const Image& sourceImage, const AffineTransform& transform, bool fillEntireClipAsTiles)
  237938. {
  237939. }
  237940. void drawLine (const Line <float>& line)
  237941. {
  237942. }
  237943. void drawVerticalLine (int x, float top, float bottom)
  237944. {
  237945. }
  237946. void drawHorizontalLine (int y, float left, float right)
  237947. {
  237948. }
  237949. void setFont (const Font& newFont)
  237950. {
  237951. }
  237952. const Font getFont()
  237953. {
  237954. return Font();
  237955. }
  237956. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  237957. {
  237958. }
  237959. private:
  237960. GlobalRef canvas, currentPaint;
  237961. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidLowLevelGraphicsContext);
  237962. };
  237963. #endif
  237964. /*** End of inlined file: juce_android_GraphicsContext.cpp ***/
  237965. /*** Start of inlined file: juce_android_Windowing.cpp ***/
  237966. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  237967. // compiled on its own).
  237968. #if JUCE_INCLUDED_FILE
  237969. class AndroidComponentPeer : public ComponentPeer
  237970. {
  237971. public:
  237972. AndroidComponentPeer (Component* const component, const int windowStyleFlags)
  237973. : ComponentPeer (component, windowStyleFlags)
  237974. {
  237975. view = GlobalRef (android.env, android.activity.callObjectMethod (android.createNewView));
  237976. }
  237977. ~AndroidComponentPeer()
  237978. {
  237979. android.activity.callVoidMethod (android.deleteView, view.get());
  237980. view = 0;
  237981. }
  237982. void* getNativeHandle() const
  237983. {
  237984. return 0; // TODO
  237985. }
  237986. void setVisible (bool shouldBeVisible)
  237987. {
  237988. }
  237989. void setTitle (const String& title)
  237990. {
  237991. }
  237992. void setPosition (int x, int y)
  237993. {
  237994. // TODO
  237995. }
  237996. void setSize (int w, int h)
  237997. {
  237998. }
  237999. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  238000. {
  238001. DBG ("Window size: " << x << " " << y << " " << w << " " << h);
  238002. view.callVoidMethod (android.layout, x, y, x + w, y + h);
  238003. }
  238004. const Rectangle<int> getBounds() const
  238005. {
  238006. // TODO
  238007. return Rectangle<int>();
  238008. }
  238009. const Point<int> getScreenPosition() const
  238010. {
  238011. // TODO
  238012. return Point<int>();
  238013. }
  238014. const Point<int> localToGlobal (const Point<int>& relativePosition)
  238015. {
  238016. // TODO
  238017. return relativePosition + getScreenPosition();
  238018. }
  238019. const Point<int> globalToLocal (const Point<int>& screenPosition)
  238020. {
  238021. // TODO
  238022. return screenPosition - getScreenPosition();
  238023. }
  238024. void setMinimised (bool shouldBeMinimised)
  238025. {
  238026. // TODO
  238027. }
  238028. bool isMinimised() const
  238029. {
  238030. }
  238031. void setFullScreen (bool shouldBeFullScreen)
  238032. {
  238033. // TODO
  238034. }
  238035. bool isFullScreen() const
  238036. {
  238037. // TODO
  238038. return false;
  238039. }
  238040. void setIcon (const Image& newIcon)
  238041. {
  238042. // TODO
  238043. }
  238044. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  238045. {
  238046. // TODO
  238047. return isPositiveAndBelow (position.getX(), component->getWidth())
  238048. && isPositiveAndBelow (position.getY(), component->getHeight());
  238049. }
  238050. const BorderSize<int> getFrameSize() const
  238051. {
  238052. // TODO
  238053. return BorderSize<int>();
  238054. }
  238055. bool setAlwaysOnTop (bool alwaysOnTop)
  238056. {
  238057. // TODO
  238058. return false;
  238059. }
  238060. void toFront (bool makeActive)
  238061. {
  238062. // TODO
  238063. }
  238064. void toBehind (ComponentPeer* other)
  238065. {
  238066. // TODO
  238067. }
  238068. bool isFocused() const
  238069. {
  238070. // TODO
  238071. return false;
  238072. }
  238073. void grabFocus()
  238074. {
  238075. // TODO
  238076. }
  238077. void textInputRequired (const Point<int>& position)
  238078. {
  238079. // TODO
  238080. }
  238081. void handlePaintCallback (JNIEnv* env, jobject canvas)
  238082. {
  238083. AndroidLowLevelGraphicsContext g (GlobalRef (env, canvas));
  238084. handlePaint (g);
  238085. }
  238086. void repaint (const Rectangle<int>& area)
  238087. {
  238088. // TODO
  238089. }
  238090. void performAnyPendingRepaintsNow()
  238091. {
  238092. // TODO
  238093. }
  238094. void setAlpha (float newAlpha)
  238095. {
  238096. // TODO
  238097. }
  238098. static AndroidComponentPeer* findPeerForJavaView (jobject viewToFind)
  238099. {
  238100. for (int i = getNumPeers(); --i >= 0;)
  238101. {
  238102. AndroidComponentPeer* const ap = static_cast <AndroidComponentPeer*> (getPeer(i));
  238103. jassert (dynamic_cast <AndroidComponentPeer*> (getPeer(i)) != 0);
  238104. if (ap->view == viewToFind)
  238105. return ap;
  238106. }
  238107. return 0;
  238108. }
  238109. private:
  238110. GlobalRef view;
  238111. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidComponentPeer);
  238112. };
  238113. #define JUCE_VIEW_CALLBACK(returnType, javaMethodName, params, juceMethodInvocation) \
  238114. JUCE_JNI_CALLBACK (ComponentPeerView, javaMethodName, returnType, params) \
  238115. { \
  238116. AndroidComponentPeer* const peer = AndroidComponentPeer::findPeerForJavaView (view); \
  238117. if (peer != 0) \
  238118. peer->juceMethodInvocation; \
  238119. }
  238120. JUCE_VIEW_CALLBACK (void, handlePaint, (JNIEnv* env, jobject view, jobject canvas),
  238121. handlePaintCallback (env, canvas))
  238122. ComponentPeer* Component::createNewPeer (int styleFlags, void*)
  238123. {
  238124. return new AndroidComponentPeer (this, styleFlags);
  238125. }
  238126. bool Desktop::canUseSemiTransparentWindows() throw()
  238127. {
  238128. return true; // TODO
  238129. }
  238130. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  238131. {
  238132. // TODO
  238133. return upright;
  238134. }
  238135. void Desktop::createMouseInputSources()
  238136. {
  238137. // This creates a mouse input source for each possible finger
  238138. for (int i = 0; i < 10; ++i)
  238139. mouseSources.add (new MouseInputSource (i, false));
  238140. }
  238141. const Point<int> MouseInputSource::getCurrentMousePosition()
  238142. {
  238143. // TODO
  238144. return Point<int>();
  238145. }
  238146. void Desktop::setMousePosition (const Point<int>& newPosition)
  238147. {
  238148. // not needed
  238149. }
  238150. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  238151. {
  238152. // TODO
  238153. return false;
  238154. }
  238155. void ModifierKeys::updateCurrentModifiers() throw()
  238156. {
  238157. // not needed
  238158. }
  238159. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  238160. {
  238161. // TODO
  238162. return ModifierKeys();
  238163. }
  238164. bool Process::isForegroundProcess()
  238165. {
  238166. return true; // TODO
  238167. }
  238168. bool AlertWindow::showNativeDialogBox (const String& title,
  238169. const String& bodyText,
  238170. bool isOkCancel)
  238171. {
  238172. // TODO
  238173. }
  238174. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  238175. {
  238176. return createSoftwareImage (format, width, height, clearImage);
  238177. }
  238178. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  238179. {
  238180. // TODO
  238181. }
  238182. bool Desktop::isScreenSaverEnabled()
  238183. {
  238184. return true;
  238185. }
  238186. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  238187. {
  238188. }
  238189. static int screenWidth = 0, screenHeight = 0;
  238190. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  238191. {
  238192. monitorCoords.add (Rectangle<int> (0, 0, screenWidth, screenHeight));
  238193. }
  238194. JUCE_JNI_CALLBACK (JuceAppActivity, setScreenSize, void, (JNIEnv* env, jobject activity, int w, int h))
  238195. {
  238196. screenWidth = w;
  238197. screenHeight = h;
  238198. }
  238199. const Image juce_createIconForFile (const File& file)
  238200. {
  238201. Image image;
  238202. // TODO
  238203. return image;
  238204. }
  238205. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  238206. {
  238207. return 0;
  238208. }
  238209. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  238210. {
  238211. }
  238212. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  238213. {
  238214. return 0;
  238215. }
  238216. void MouseCursor::showInWindow (ComponentPeer*) const {}
  238217. void MouseCursor::showInAllWindows() const {}
  238218. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  238219. {
  238220. return false;
  238221. }
  238222. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  238223. {
  238224. return false;
  238225. }
  238226. const int extendedKeyModifier = 0x10000;
  238227. const int KeyPress::spaceKey = ' ';
  238228. const int KeyPress::returnKey = 0x0d;
  238229. const int KeyPress::escapeKey = 0x1b;
  238230. const int KeyPress::backspaceKey = 0x7f;
  238231. const int KeyPress::leftKey = extendedKeyModifier + 1;
  238232. const int KeyPress::rightKey = extendedKeyModifier + 2;
  238233. const int KeyPress::upKey = extendedKeyModifier + 3;
  238234. const int KeyPress::downKey = extendedKeyModifier + 4;
  238235. const int KeyPress::pageUpKey = extendedKeyModifier + 5;
  238236. const int KeyPress::pageDownKey = extendedKeyModifier + 6;
  238237. const int KeyPress::endKey = extendedKeyModifier + 7;
  238238. const int KeyPress::homeKey = extendedKeyModifier + 8;
  238239. const int KeyPress::deleteKey = extendedKeyModifier + 9;
  238240. const int KeyPress::insertKey = -1;
  238241. const int KeyPress::tabKey = 9;
  238242. const int KeyPress::F1Key = extendedKeyModifier + 10;
  238243. const int KeyPress::F2Key = extendedKeyModifier + 11;
  238244. const int KeyPress::F3Key = extendedKeyModifier + 12;
  238245. const int KeyPress::F4Key = extendedKeyModifier + 13;
  238246. const int KeyPress::F5Key = extendedKeyModifier + 14;
  238247. const int KeyPress::F6Key = extendedKeyModifier + 16;
  238248. const int KeyPress::F7Key = extendedKeyModifier + 17;
  238249. const int KeyPress::F8Key = extendedKeyModifier + 18;
  238250. const int KeyPress::F9Key = extendedKeyModifier + 19;
  238251. const int KeyPress::F10Key = extendedKeyModifier + 20;
  238252. const int KeyPress::F11Key = extendedKeyModifier + 21;
  238253. const int KeyPress::F12Key = extendedKeyModifier + 22;
  238254. const int KeyPress::F13Key = extendedKeyModifier + 23;
  238255. const int KeyPress::F14Key = extendedKeyModifier + 24;
  238256. const int KeyPress::F15Key = extendedKeyModifier + 25;
  238257. const int KeyPress::F16Key = extendedKeyModifier + 26;
  238258. const int KeyPress::numberPad0 = extendedKeyModifier + 27;
  238259. const int KeyPress::numberPad1 = extendedKeyModifier + 28;
  238260. const int KeyPress::numberPad2 = extendedKeyModifier + 29;
  238261. const int KeyPress::numberPad3 = extendedKeyModifier + 30;
  238262. const int KeyPress::numberPad4 = extendedKeyModifier + 31;
  238263. const int KeyPress::numberPad5 = extendedKeyModifier + 32;
  238264. const int KeyPress::numberPad6 = extendedKeyModifier + 33;
  238265. const int KeyPress::numberPad7 = extendedKeyModifier + 34;
  238266. const int KeyPress::numberPad8 = extendedKeyModifier + 35;
  238267. const int KeyPress::numberPad9 = extendedKeyModifier + 36;
  238268. const int KeyPress::numberPadAdd = extendedKeyModifier + 37;
  238269. const int KeyPress::numberPadSubtract = extendedKeyModifier + 38;
  238270. const int KeyPress::numberPadMultiply = extendedKeyModifier + 39;
  238271. const int KeyPress::numberPadDivide = extendedKeyModifier + 40;
  238272. const int KeyPress::numberPadSeparator = extendedKeyModifier + 41;
  238273. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 42;
  238274. const int KeyPress::numberPadEquals = extendedKeyModifier + 43;
  238275. const int KeyPress::numberPadDelete = extendedKeyModifier + 44;
  238276. const int KeyPress::playKey = extendedKeyModifier + 45;
  238277. const int KeyPress::stopKey = extendedKeyModifier + 46;
  238278. const int KeyPress::fastForwardKey = extendedKeyModifier + 47;
  238279. const int KeyPress::rewindKey = extendedKeyModifier + 48;
  238280. #endif
  238281. /*** End of inlined file: juce_android_Windowing.cpp ***/
  238282. /*** Start of inlined file: juce_android_FileChooser.cpp ***/
  238283. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238284. // compiled on its own).
  238285. #if JUCE_INCLUDED_FILE
  238286. void FileChooser::showPlatformDialog (Array<File>& results,
  238287. const String& title,
  238288. const File& currentFileOrDirectory,
  238289. const String& filter,
  238290. bool selectsDirectory,
  238291. bool selectsFiles,
  238292. bool isSaveDialogue,
  238293. bool warnAboutOverwritingExistingFiles,
  238294. bool selectMultipleFiles,
  238295. FilePreviewComponent* extraInfoComponent)
  238296. {
  238297. // TODO
  238298. }
  238299. #endif
  238300. /*** End of inlined file: juce_android_FileChooser.cpp ***/
  238301. /*** Start of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238302. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238303. // compiled on its own).
  238304. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  238305. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  238306. : browser (0),
  238307. blankPageShown (false),
  238308. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  238309. {
  238310. setOpaque (true);
  238311. }
  238312. WebBrowserComponent::~WebBrowserComponent()
  238313. {
  238314. }
  238315. void WebBrowserComponent::goToURL (const String& url,
  238316. const StringArray* headers,
  238317. const MemoryBlock* postData)
  238318. {
  238319. lastURL = url;
  238320. lastHeaders.clear();
  238321. if (headers != 0)
  238322. lastHeaders = *headers;
  238323. lastPostData.setSize (0);
  238324. if (postData != 0)
  238325. lastPostData = *postData;
  238326. blankPageShown = false;
  238327. }
  238328. void WebBrowserComponent::stop()
  238329. {
  238330. }
  238331. void WebBrowserComponent::goBack()
  238332. {
  238333. lastURL = String::empty;
  238334. blankPageShown = false;
  238335. }
  238336. void WebBrowserComponent::goForward()
  238337. {
  238338. lastURL = String::empty;
  238339. }
  238340. void WebBrowserComponent::refresh()
  238341. {
  238342. }
  238343. void WebBrowserComponent::paint (Graphics& g)
  238344. {
  238345. g.fillAll (Colours::white);
  238346. }
  238347. void WebBrowserComponent::checkWindowAssociation()
  238348. {
  238349. }
  238350. void WebBrowserComponent::reloadLastURL()
  238351. {
  238352. if (lastURL.isNotEmpty())
  238353. {
  238354. goToURL (lastURL, &lastHeaders, &lastPostData);
  238355. lastURL = String::empty;
  238356. }
  238357. }
  238358. void WebBrowserComponent::parentHierarchyChanged()
  238359. {
  238360. checkWindowAssociation();
  238361. }
  238362. void WebBrowserComponent::resized()
  238363. {
  238364. }
  238365. void WebBrowserComponent::visibilityChanged()
  238366. {
  238367. checkWindowAssociation();
  238368. }
  238369. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  238370. {
  238371. return true;
  238372. }
  238373. #endif
  238374. /*** End of inlined file: juce_android_WebBrowserComponent.cpp ***/
  238375. /*** Start of inlined file: juce_android_OpenGLComponent.cpp ***/
  238376. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238377. // compiled on its own).
  238378. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  238379. // TODO
  238380. OpenGLContext* OpenGLComponent::createContext()
  238381. {
  238382. return 0;
  238383. }
  238384. void* OpenGLComponent::getNativeWindowHandle() const
  238385. {
  238386. return 0;
  238387. }
  238388. void juce_glViewport (const int w, const int h)
  238389. {
  238390. // glViewport (0, 0, w, h);
  238391. }
  238392. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  238393. OwnedArray <OpenGLPixelFormat>& results)
  238394. {
  238395. }
  238396. #endif
  238397. /*** End of inlined file: juce_android_OpenGLComponent.cpp ***/
  238398. /*** Start of inlined file: juce_android_Midi.cpp ***/
  238399. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238400. // compiled on its own).
  238401. #if JUCE_INCLUDED_FILE
  238402. const StringArray MidiOutput::getDevices()
  238403. {
  238404. StringArray devices;
  238405. return devices;
  238406. }
  238407. int MidiOutput::getDefaultDeviceIndex()
  238408. {
  238409. return 0;
  238410. }
  238411. MidiOutput* MidiOutput::openDevice (int index)
  238412. {
  238413. return 0;
  238414. }
  238415. MidiOutput::~MidiOutput()
  238416. {
  238417. }
  238418. void MidiOutput::reset()
  238419. {
  238420. }
  238421. bool MidiOutput::getVolume (float&, float&)
  238422. {
  238423. return false;
  238424. }
  238425. void MidiOutput::setVolume (float, float)
  238426. {
  238427. }
  238428. void MidiOutput::sendMessageNow (const MidiMessage&)
  238429. {
  238430. }
  238431. MidiInput::MidiInput (const String& name_)
  238432. : name (name_),
  238433. internal (0)
  238434. {
  238435. }
  238436. MidiInput::~MidiInput()
  238437. {
  238438. }
  238439. void MidiInput::start()
  238440. {
  238441. }
  238442. void MidiInput::stop()
  238443. {
  238444. }
  238445. int MidiInput::getDefaultDeviceIndex()
  238446. {
  238447. return 0;
  238448. }
  238449. const StringArray MidiInput::getDevices()
  238450. {
  238451. StringArray devs;
  238452. return devs;
  238453. }
  238454. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  238455. {
  238456. return 0;
  238457. }
  238458. #endif
  238459. /*** End of inlined file: juce_android_Midi.cpp ***/
  238460. /*** Start of inlined file: juce_android_Audio.cpp ***/
  238461. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238462. // compiled on its own).
  238463. #if JUCE_INCLUDED_FILE
  238464. class AndroidAudioIODevice : public AudioIODevice
  238465. {
  238466. public:
  238467. AndroidAudioIODevice (const String& deviceName)
  238468. : AudioIODevice (deviceName, "Audio"),
  238469. callback (0),
  238470. sampleRate (0),
  238471. numInputChannels (0),
  238472. numOutputChannels (0),
  238473. actualBufferSize (0),
  238474. isRunning (false)
  238475. {
  238476. numInputChannels = 2;
  238477. numOutputChannels = 2;
  238478. // TODO
  238479. }
  238480. ~AndroidAudioIODevice()
  238481. {
  238482. close();
  238483. }
  238484. const StringArray getOutputChannelNames()
  238485. {
  238486. StringArray s;
  238487. s.add ("Left"); // TODO
  238488. s.add ("Right");
  238489. return s;
  238490. }
  238491. const StringArray getInputChannelNames()
  238492. {
  238493. StringArray s;
  238494. s.add ("Left");
  238495. s.add ("Right");
  238496. return s;
  238497. }
  238498. int getNumSampleRates() { return 1;}
  238499. double getSampleRate (int index) { return sampleRate; }
  238500. int getNumBufferSizesAvailable() { return 1; }
  238501. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  238502. int getDefaultBufferSize() { return 1024; }
  238503. const String open (const BigInteger& inputChannels,
  238504. const BigInteger& outputChannels,
  238505. double sampleRate,
  238506. int bufferSize)
  238507. {
  238508. close();
  238509. lastError = String::empty;
  238510. int preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  238511. activeOutputChans = outputChannels;
  238512. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  238513. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  238514. activeInputChans = inputChannels;
  238515. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  238516. numInputChannels = activeInputChans.countNumberOfSetBits();
  238517. // TODO
  238518. actualBufferSize = 0; // whatever is possible based on preferredBufferSize
  238519. isRunning = true;
  238520. return lastError;
  238521. }
  238522. void close()
  238523. {
  238524. if (isRunning)
  238525. {
  238526. isRunning = false;
  238527. // TODO
  238528. }
  238529. }
  238530. int getOutputLatencyInSamples()
  238531. {
  238532. return 0; // TODO
  238533. }
  238534. int getInputLatencyInSamples()
  238535. {
  238536. return 0; // TODO
  238537. }
  238538. bool isOpen() { return isRunning; }
  238539. int getCurrentBufferSizeSamples() { return actualBufferSize; }
  238540. int getCurrentBitDepth() { return 16; }
  238541. double getCurrentSampleRate() { return sampleRate; }
  238542. const BigInteger getActiveOutputChannels() const { return activeOutputChans; }
  238543. const BigInteger getActiveInputChannels() const { return activeInputChans; }
  238544. const String getLastError() { return lastError; }
  238545. bool isPlaying() { return isRunning && callback != 0; }
  238546. // TODO
  238547. void start (AudioIODeviceCallback* newCallback)
  238548. {
  238549. if (isRunning && callback != newCallback)
  238550. {
  238551. if (newCallback != 0)
  238552. newCallback->audioDeviceAboutToStart (this);
  238553. const ScopedLock sl (callbackLock);
  238554. callback = newCallback;
  238555. }
  238556. }
  238557. void stop()
  238558. {
  238559. if (isRunning)
  238560. {
  238561. AudioIODeviceCallback* lastCallback;
  238562. {
  238563. const ScopedLock sl (callbackLock);
  238564. lastCallback = callback;
  238565. callback = 0;
  238566. }
  238567. if (lastCallback != 0)
  238568. lastCallback->audioDeviceStopped();
  238569. }
  238570. }
  238571. private:
  238572. CriticalSection callbackLock;
  238573. AudioIODeviceCallback* callback;
  238574. double sampleRate;
  238575. int numInputChannels, numOutputChannels;
  238576. int actualBufferSize;
  238577. bool isRunning;
  238578. String lastError;
  238579. BigInteger activeOutputChans, activeInputChans;
  238580. JUCE_DECLARE_NON_COPYABLE (AndroidAudioIODevice);
  238581. };
  238582. // TODO
  238583. class AndroidAudioIODeviceType : public AudioIODeviceType
  238584. {
  238585. public:
  238586. AndroidAudioIODeviceType()
  238587. : AudioIODeviceType ("Android Audio")
  238588. {
  238589. }
  238590. void scanForDevices()
  238591. {
  238592. }
  238593. const StringArray getDeviceNames (bool wantInputNames) const
  238594. {
  238595. StringArray s;
  238596. s.add ("Android Audio");
  238597. return s;
  238598. }
  238599. int getDefaultDeviceIndex (bool forInput) const
  238600. {
  238601. return 0;
  238602. }
  238603. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  238604. {
  238605. return device != 0 ? 0 : -1;
  238606. }
  238607. bool hasSeparateInputsAndOutputs() const { return false; }
  238608. AudioIODevice* createDevice (const String& outputDeviceName,
  238609. const String& inputDeviceName)
  238610. {
  238611. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  238612. return new AndroidAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  238613. : inputDeviceName);
  238614. return 0;
  238615. }
  238616. private:
  238617. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidAudioIODeviceType);
  238618. };
  238619. AudioIODeviceType* juce_createAudioIODeviceType_Android()
  238620. {
  238621. return new AndroidAudioIODeviceType();
  238622. }
  238623. #endif
  238624. /*** End of inlined file: juce_android_Audio.cpp ***/
  238625. /*** Start of inlined file: juce_android_CameraDevice.cpp ***/
  238626. // (This file gets included by juce_android_NativeCode.cpp, rather than being
  238627. // compiled on its own).
  238628. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  238629. // TODO
  238630. class AndroidCameraInternal
  238631. {
  238632. public:
  238633. AndroidCameraInternal()
  238634. {
  238635. }
  238636. ~AndroidCameraInternal()
  238637. {
  238638. }
  238639. private:
  238640. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AndroidCameraInternal);
  238641. };
  238642. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  238643. : name (name_)
  238644. {
  238645. internal = new AndroidCameraInternal();
  238646. // TODO
  238647. }
  238648. CameraDevice::~CameraDevice()
  238649. {
  238650. stopRecording();
  238651. delete static_cast <AndroidCameraInternal*> (internal);
  238652. internal = 0;
  238653. }
  238654. Component* CameraDevice::createViewerComponent()
  238655. {
  238656. // TODO
  238657. return 0;
  238658. }
  238659. const String CameraDevice::getFileExtension()
  238660. {
  238661. return ".m4a"; // TODO correct?
  238662. }
  238663. void CameraDevice::startRecordingToFile (const File& file, int quality)
  238664. {
  238665. // TODO
  238666. }
  238667. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  238668. {
  238669. // TODO
  238670. return Time();
  238671. }
  238672. void CameraDevice::stopRecording()
  238673. {
  238674. // TODO
  238675. }
  238676. void CameraDevice::addListener (Listener* listenerToAdd)
  238677. {
  238678. // TODO
  238679. }
  238680. void CameraDevice::removeListener (Listener* listenerToRemove)
  238681. {
  238682. // TODO
  238683. }
  238684. const StringArray CameraDevice::getAvailableDevices()
  238685. {
  238686. StringArray devs;
  238687. // TODO
  238688. return devs;
  238689. }
  238690. CameraDevice* CameraDevice::openDevice (int index,
  238691. int minWidth, int minHeight,
  238692. int maxWidth, int maxHeight)
  238693. {
  238694. // TODO
  238695. return 0;
  238696. }
  238697. #endif
  238698. /*** End of inlined file: juce_android_CameraDevice.cpp ***/
  238699. END_JUCE_NAMESPACE
  238700. #endif
  238701. /*** End of inlined file: juce_android_NativeCode.cpp ***/
  238702. #endif
  238703. #endif